diff --git a/docs/architecture/code-index-architecture.md b/docs/architecture/code-index-architecture.md index b6c0f6e9ec..a92799eae1 100644 --- a/docs/architecture/code-index-architecture.md +++ b/docs/architecture/code-index-architecture.md @@ -87,7 +87,8 @@ it on the host that served the call; every other host's sweep removes its own co a parse of the configuration, and a `realpath` and a `stat` of each entry's clone directory. A lookup of one entry (its classification, its trunk, whether it is a repository) derives them all. These calls and passes make one for every entry, memory, -search hit or directory row, and run that loop inside `repos.derived_once()`: +search hit, directory row, grant, changed file, fix, namespace a token names or code name +a document mentions, and run that loop inside `repos.derived_once()`: - `code.repos`, whose gate reads each entry's classification; - `code_link_reads.stale_links` and `repo_scope.repo_names`, which ask each entry for its @@ -112,7 +113,26 @@ search hit or directory row, and run that loop inside `repos.derived_once()`: configuration errors of its own derivation; - the failing-tier read on the registry's refresh timer (`tier_health.refresh_failing`) and the health problem's read of it (`tier_health.problem_rows`), which ask each - failing tier's entry whether it is restricted. + failing tier's entry whether it is restricted; +- a token mint (`service_accounts.create`, `personal_tokens.create`, `admin/token.mint`), + which asks each namespace the token names whether it is restricted and whether it is a + repository; `service_accounts.create` and `personal_tokens.create` also ask each + restricted one for the tracker bound to it; +- `namespace.list_mine`, which reads the configured kinds and asks each grant a token + inherits from its creator whether its entry is restricted; +- `memory.for_file`, which asks each extra namespace and the request's `repo:` tag for + their trunk, each link for the trunk its memory names, and the gate for each of them; +- the link recheck that `code.refresh` asks for (`code_link_recheck.recheck_repository`), + which asks for the repository's entry at each git read and file read, and each link it + moves for the trunk its memory names; +- the risk refit of the graph statistics pass (`graph_stats._refit_jit_risk`), which asks + each entry for the tracker bound to it and that tracker whether it is restricted; +- the backport-gap pass (`code/workers/backport_gaps.py`), which asks each trunk for the + tracker bound to it and each fix for its trunk's release branches; +- a document's decision extraction (`decision_extract.extract_document`), which asks the + document's namespace and the repository for their trunk and their gate, and looks up + each code name the document mentions. A write it leaves running when it ends derives + the entries itself. Within the block the task derives the entries once. A registry snapshot that replaces the one the block read is read at the next call, so a branch added from the page or a diff --git a/server/code/workers/backport_gaps.py b/server/code/workers/backport_gaps.py index d9887d3532..ea333f92e3 100644 --- a/server/code/workers/backport_gaps.py +++ b/server/code/workers/backport_gaps.py @@ -129,6 +129,7 @@ async def _run( ) -> None: from server.code.app.backport import run_backport_gap from server.code.app.index.bootstrap import awaits_first_index + from server.code.domain.index.repos import derived_once from server.code.store.backport_gaps import CodeBackportGapsRepo from server.code.store.index import CodeRepo @@ -136,26 +137,28 @@ async def _run( repo = repo or CodeBackportGapsRepo() code_repo = code_repo or CodeRepo() run = runner or run_backport_gap - for cfg, sibs in trunks(): - try: - if await awaits_first_index(cfg, code_repo): - continue - await refresh_namespace( - cfg, - sibs, - repo, - code_repo, - result=result, - now=now or _now(), - runner=run, - source_factory=source_factory, - started=started, - ) - result.namespaces += 1 - except Exception as e: - result.errors.append(f"{cfg.namespace}: {type(e).__name__}: {e}") - note_failure(e, f"code_backport_gaps:{cfg.namespace}") - logger.exception("code_backport_gaps: namespace %s failed", cfg.namespace) + # each trunk is asked for its tracker, each fix for its release branches + with derived_once(): + for cfg, sibs in trunks(): + try: + if await awaits_first_index(cfg, code_repo): + continue + await refresh_namespace( + cfg, + sibs, + repo, + code_repo, + result=result, + now=now or _now(), + runner=run, + source_factory=source_factory, + started=started, + ) + result.namespaces += 1 + except Exception as e: + result.errors.append(f"{cfg.namespace}: {type(e).__name__}: {e}") + note_failure(e, f"code_backport_gaps:{cfg.namespace}") + logger.exception("code_backport_gaps: namespace %s failed", cfg.namespace) result.wall_ms = int((time.monotonic() - started) * 1000) diff --git a/server/code/workers/graph_stats.py b/server/code/workers/graph_stats.py index b389fca739..b6322534f9 100644 --- a/server/code/workers/graph_stats.py +++ b/server/code/workers/graph_stats.py @@ -404,20 +404,22 @@ async def _refit_jit_risk(repos: list[Any], result: CodeGraphStatsResult) -> Non namespace, refitted when its stored fit is a week old — one QA statement and a ~0.3 s fit per namespace, never fatal to the pass.""" from server.code.app.index import risk_fit + from server.code.domain.index.repos import derived_once from server.code.store.index import CodeRepo repo = CodeRepo() - for cfg in repos: - out = await risk_fit.refit_namespace(repo, cfg.org, cfg.namespace) - if out.status == "written": - result.jit_risk_fits += 1 - result.jit_risk_fit_n = out.n - result.jit_risk_holdout_auc = out.holdout_auc - logger.info("code_graph_stats: risk fit %s — %s", cfg.label, out.detail) - elif out.status == "failed": - result.errors.append(f"{cfg.label}: jit_risk: {out.detail}") - else: - result.jit_risk_skipped += 1 + with derived_once(): # each entry is asked for the tracker bound to it + for cfg in repos: + out = await risk_fit.refit_namespace(repo, cfg.org, cfg.namespace) + if out.status == "written": + result.jit_risk_fits += 1 + result.jit_risk_fit_n = out.n + result.jit_risk_holdout_auc = out.holdout_auc + logger.info("code_graph_stats: risk fit %s — %s", cfg.label, out.detail) + elif out.status == "failed": + result.errors.append(f"{cfg.label}: jit_risk: {out.detail}") + else: + result.jit_risk_skipped += 1 async def _run(result: CodeGraphStatsResult) -> None: diff --git a/server/identity/app/me_service_accounts.py b/server/identity/app/me_service_accounts.py index 43bb29811a..0ce8cddaed 100644 --- a/server/identity/app/me_service_accounts.py +++ b/server/identity/app/me_service_accounts.py @@ -22,6 +22,7 @@ from server.auth.public_url import public_base_url from server.auth.self_signup import AGENT_NAME_PREFIX from server.auth.service_accounts import hand_down_lineage, revoked_row +from server.code.domain.index.repos import derived_once from server.core.datetimes import naive_utc_now_seconds from server.core.errors import BackendUnavailableError from server.core.grant_sql import LIVE_GRANT @@ -290,7 +291,8 @@ async def me_service_accounts_create( request: Request, payload: dict[str, object] ) -> dict[str, object]: """Mint a general service-account token under the caller's live grants.""" - return await _create_token(request, payload) + with derived_once(): # each namespace the token names is asked for its entry + return await _create_token(request, payload) @router.post("/v1/me/personal_tokens.create") @@ -312,7 +314,8 @@ async def me_personal_tokens_create( or request.headers.get("X-Loom-On-Behalf-Of") is not None ): raise _personal_session_required() - return await _create_token(request, payload, personal_parent=parent) + with derived_once(): # each namespace the token names is asked for its entry + return await _create_token(request, payload, personal_parent=parent) def _personal_session_required() -> HTTPException: diff --git a/server/identity/app/namespace_membership.py b/server/identity/app/namespace_membership.py index 3b1ff5467f..03150b6ab7 100644 --- a/server/identity/app/namespace_membership.py +++ b/server/identity/app/namespace_membership.py @@ -521,6 +521,7 @@ async def handle_namespace_list_mine( load, so the personal namespace lazily-creates on first visit. """ from server.auth.aliases import subject_aliases + from server.code.domain.index.repos import derived_once from server.identity.app.namespace_kinds import configured_kinds ch = get_client() @@ -539,77 +540,80 @@ async def handle_namespace_list_mine( # the server serves. subjects = await subject_aliases(input.org, caller, ch=ch) grant_rows = _one_per_namespace(await _membership_rows(ch, input.org, subjects)) - configured = configured_kinds(input.org) - seen = {r["namespace"] for r in grant_rows} - # Only resolve admins for rows with a pending_role. - needs_admins = {r["namespace"] for r in grant_rows if r.get("pending_role")} - admins_by_ns: dict[str, list[str]] = {} - for ns in needs_admins: - admins_by_ns[ns] = await _list_namespace_admins(ch, input.org, ns) - - out_rows: list[_MineEntry] = [ - _MineEntry( - namespace=r["namespace"], - role=r["role"], - status=(r.get("status") or "active"), - pending_role=r.get("pending_role") or None, - pending_since=r.get("pending_since"), - pending_admins=admins_by_ns.get(r["namespace"], []), - visibility=r.get("visibility") or "private", - kind=_kind(configured, r["namespace"], r.get("kind")), - title=r.get("title") or "", - description=r.get("description") or "", - joined_at=r["joined_at"], - is_new=bool(r.get("is_new")), - ) - for r in grant_rows - ] - - from server.auth.authz import live_claims - from server.auth.context import current_auth - - auth = current_auth() - if auth is not None: - jwt_only = await live_claims( - auth, input.org, [ns for ns in auth.namespaces if ns not in seen] - ) - # Claim-only namespaces have no grant row to JOIN through, so look up - # kind/visibility directly — otherwise a code namespace named in a - # token's claim would masquerade as a memory namespace and the header - # picker would happily default to it. - meta = await _namespace_meta(ch, input.org, jwt_only) if jwt_only else {} - for ns in jwt_only: - m = meta.get(ns) or {} - out_rows.append( - _MineEntry( - namespace=ns, - role="jwt", - visibility=m.get("visibility") or "private", # type: ignore[arg-type] - kind=_kind(configured, ns, m.get("kind")), - title=m.get("title") or "", - description=m.get("description") or "", - ) - ) - - # What a client token reads through its creator. - seen_all = seen | {r.namespace for r in out_rows} - for r in await _inherited_rows(ch, input.org, caller, seen_all): - out_rows.append( + # the configured kinds, and each grant a token inherits when `_inherited_rows` asks + # whether its entry is restricted + with derived_once(): + configured = configured_kinds(input.org) + seen = {r["namespace"] for r in grant_rows} + # Only resolve admins for rows with a pending_role. + needs_admins = {r["namespace"] for r in grant_rows if r.get("pending_role")} + admins_by_ns: dict[str, list[str]] = {} + for ns in needs_admins: + admins_by_ns[ns] = await _list_namespace_admins(ch, input.org, ns) + + out_rows: list[_MineEntry] = [ _MineEntry( namespace=r["namespace"], role=r["role"], - status="active", + status=(r.get("status") or "active"), + pending_role=r.get("pending_role") or None, + pending_since=r.get("pending_since"), + pending_admins=admins_by_ns.get(r["namespace"], []), visibility=r.get("visibility") or "private", kind=_kind(configured, r["namespace"], r.get("kind")), title=r.get("title") or "", description=r.get("description") or "", - joined_at=r.get("joined_at"), - is_new=False, - inherited=True, + joined_at=r["joined_at"], + is_new=bool(r.get("is_new")), + ) + for r in grant_rows + ] + + from server.auth.authz import live_claims + from server.auth.context import current_auth + + auth = current_auth() + if auth is not None: + jwt_only = await live_claims( + auth, input.org, [ns for ns in auth.namespaces if ns not in seen] + ) + # Claim-only namespaces have no grant row to JOIN through, so look up + # kind/visibility directly — otherwise a code namespace named in a + # token's claim would masquerade as a memory namespace and the header + # picker would happily default to it. + meta = await _namespace_meta(ch, input.org, jwt_only) if jwt_only else {} + for ns in jwt_only: + m = meta.get(ns) or {} + out_rows.append( + _MineEntry( + namespace=ns, + role="jwt", + visibility=m.get("visibility") or "private", # type: ignore[arg-type] + kind=_kind(configured, ns, m.get("kind")), + title=m.get("title") or "", + description=m.get("description") or "", + ) + ) + + # What a client token reads through its creator. + seen_all = seen | {r.namespace for r in out_rows} + for r in await _inherited_rows(ch, input.org, caller, seen_all): + out_rows.append( + _MineEntry( + namespace=r["namespace"], + role=r["role"], + status="active", + visibility=r.get("visibility") or "private", + kind=_kind(configured, r["namespace"], r.get("kind")), + title=r.get("title") or "", + description=r.get("description") or "", + joined_at=r.get("joined_at"), + is_new=False, + inherited=True, + ) ) - ) - return NamespaceListMineOutput(rows=out_rows) + return NamespaceListMineOutput(rows=out_rows) async def _namespace_meta(ch: Any, org: str, namespaces: list[str]) -> dict[str, dict[str, str]]: diff --git a/server/insights/app/admin_routes.py b/server/insights/app/admin_routes.py index fb03529509..5e97507194 100644 --- a/server/insights/app/admin_routes.py +++ b/server/insights/app/admin_routes.py @@ -865,6 +865,7 @@ async def admin_token_mint( from server.auth.delegation import DEFAULT_TTL_DAYS, NEVER, Delegated, delegable_role, delegate from server.auth.grant_claims import service_account_change from server.auth.jwt import new_jti + from server.code.domain.index.repos import derived_once from server.core.datetimes import naive_utc_now_seconds from server.identity.app import me_service_accounts as tokens from server.identity.app import token_grants @@ -901,67 +902,74 @@ async def admin_token_mint( asked = asked_saves_to(input.saves_to, everything="*" in requested) jti = new_jti() - async with service_account_change(input.org, name): - await tokens.refuse_taken_name(input.org, name, creator) - if info is not None: - delegated = await delegate( - info, - org=input.org, - requested=requested, - scoped=bool(input.ns_roles), - ttl_seconds=input.ttl_seconds, - is_service_account=True, + # each namespace is asked whether it is restricted and whether it is a repository, + # and the one named before `*` for its kind + with derived_once(): + async with service_account_change(input.org, name): + await tokens.refuse_taken_name(input.org, name, creator) + if info is not None: + delegated = await delegate( + info, + org=input.org, + requested=requested, + scoped=bool(input.ns_roles), + ttl_seconds=input.ttl_seconds, + is_service_account=True, + ) + # Capped at the caller's own grant there; read before anything is saved. + roles_on = await token_grants.restricted_roles( + input.org, creator, delegated, requested + ) + else: + # Auth off: nothing to delegate from. + ttl = DEFAULT_TTL_DAYS * 86400 if input.ttl_seconds is None else input.ttl_seconds + delegated = Delegated( + org=input.org, + namespaces=list(input.namespaces), + roles=[] if input.ns_roles else list(input.roles), + ns_roles=dict(input.ns_roles) if input.ns_roles else None, + write_namespaces=None, + read_scope="", + read_user_id="", + ttl_seconds=None if ttl == NEVER else ttl, + parents=[], + parent_subjects=[], + parent_iats=[], + creator="", + is_service_account=True, + ) + # Every namespace of the token; the grant below keeps only the restricted ones. + flat_role = (delegated.roles or ["viewer"])[0] + roles_on = delegated.ns_roles or dict.fromkeys(delegated.namespaces, flat_role) + delegated = await saves_to_target( + input.org, delegated, asked, before_star=star_home(input.namespaces) ) - # Capped at the caller's own grant there; read before anything is saved. - roles_on = await token_grants.restricted_roles(input.org, creator, delegated, requested) - else: - # Auth off: nothing to delegate from. - ttl = DEFAULT_TTL_DAYS * 86400 if input.ttl_seconds is None else input.ttl_seconds - delegated = Delegated( - org=input.org, - namespaces=list(input.namespaces), - roles=[] if input.ns_roles else list(input.roles), - ns_roles=dict(input.ns_roles) if input.ns_roles else None, - write_namespaces=None, - read_scope="", - read_user_id="", - ttl_seconds=None if ttl == NEVER else ttl, - parents=[], - parent_subjects=[], - parent_iats=[], - creator="", - is_service_account=True, + # Before the token is saved: a refusal (an unread code registry) strands nothing. + is_code = await token_grants.code_namespace_predicate(input.org, list(roles_on)) + sa_subject = tokens.new_token_subject(input.org, name, creator) + minted = delegated.mint(sa_subject, jti=jti, consumer=input.consumer or None) + await tokens.save_token( + name, sa_subject, delegated, created_by=creator, now=naive_utc_now_seconds() ) - # Every namespace of the token; the grant below keeps only the restricted ones. - flat_role = (delegated.roles or ["viewer"])[0] - roles_on = delegated.ns_roles or dict.fromkeys(delegated.namespaces, flat_role) - delegated = await saves_to_target( - input.org, delegated, asked, before_star=star_home(input.namespaces) + # A restricted namespace is read only by a subject with a direct grant there. + granted = await token_grants.grant_restricted_to_token( + input.org, sa_subject, creator, roles_on, is_code_namespace=is_code ) - # Before the token is saved: a refusal (an unread code registry) strands nothing. - is_code = await token_grants.code_namespace_predicate(input.org, list(roles_on)) - sa_subject = tokens.new_token_subject(input.org, name, creator) - minted = delegated.mint(sa_subject, jti=jti, consumer=input.consumer or None) - await tokens.save_token( - name, sa_subject, delegated, created_by=creator, now=naive_utc_now_seconds() + await note_restricted_grants( + info, op="admin.token.mint", org=input.org, namespaces=granted, granted_to=sa_subject ) - # A restricted namespace is read only by a subject with a direct grant there. - granted = await token_grants.grant_restricted_to_token( - input.org, sa_subject, creator, roles_on, is_code_namespace=is_code - ) - await note_restricted_grants( - info, op="admin.token.mint", org=input.org, namespaces=granted, granted_to=sa_subject - ) - if info is not None: - await _audit_mint(info, input, delegated, sa_subject, jti) + if info is not None: + await _audit_mint(info, input, delegated, sa_subject, jti) + # The token's recorded target: a list token's saves_to, else its writable memory + # home before `*` (`caller_home.minted_home`), else "" (it only reads, or follows + # its owner's pick). + home = minted_home(delegated.as_auth(sa_subject)) + if home and not ( + is_memory_home(await kind_map(input.org), home) and delegated.writes(home) + ): + home = "" # Retired: the token's subject is its own, and it is always a service account. ignored = sorted({"subject", "is_service_account"} & set(body)) - # The token's recorded target: a list token's saves_to, else its writable memory home - # before `*` (`caller_home.minted_home`), else "" (it only reads, or follows its - # owner's pick). - home = minted_home(delegated.as_auth(sa_subject)) - if home and not (is_memory_home(await kind_map(input.org), home) and delegated.writes(home)): - home = "" saves_to = delegated.saves_to or home return TokenMintOutput.model_validate( { diff --git a/server/memory/app/code_link_recheck.py b/server/memory/app/code_link_recheck.py index 9f03c13e62..b9b99f7f92 100644 --- a/server/memory/app/code_link_recheck.py +++ b/server/memory/app/code_link_recheck.py @@ -25,7 +25,7 @@ unnumbered, ) from server.code.domain.declaration import fingerprint_version -from server.code.domain.index.repos import repo_for_namespace +from server.code.domain.index.repos import derived_once, repo_for_namespace from server.code.domain.successor import ( Side, Successor, @@ -122,7 +122,9 @@ async def recheck_repository(org: str, cns: str) -> link_pass.PassResult | None: result = link_pass.PassResult() async with link_pass.repository_locks.lease(_lock_name(org, cns)): budget = link_pass.Budget(judgements=0, revises=False) - await _recheck_repository(org, cns, budget, result) + # each git read and file read asks for the entry, each moved link for its trunk + with derived_once(): + await _recheck_repository(org, cns, budget, result) return result diff --git a/server/memory/app/decision_extract.py b/server/memory/app/decision_extract.py index 076454d685..c58eecab7e 100644 --- a/server/memory/app/decision_extract.py +++ b/server/memory/app/decision_extract.py @@ -68,6 +68,7 @@ from server.auth.authz import row_in_scope from server.code.app.prose_candidates import CodeDiscovery, discover_candidates from server.code.domain.extract.lang_markdown import is_markdown_path +from server.code.domain.index.repos import derived_once from server.core.background import TaskSet from server.core.errors import LoomServerError from server.identity.domain.read_scope import WHOLE_NAMESPACE @@ -467,65 +468,69 @@ async def extract_document( if error := no_model_error(): report.error = error return report - t = await _target(org, namespace, repo, into, dry_run) - if isinstance(t, str): - report.error = t - return report - doc = await ordinary_get(KnowledgeGetInput(org=org, namespace=namespace, source_uri=source_uri)) - if not doc.found: - report.error = f"no live document {source_uri!r} in {org}/{namespace}" - return report - chunks = await document_chunks(org, namespace, source_uri) - if not chunks: - report.error = ( - f"{source_uri!r} has no chunks for the current embedding model; run " - f"`loom rechunk --org {org} --namespace {namespace} --source-uri {source_uri} " - "--apply` first" + # the document's namespace, the repository and each code name ask for their entry + with derived_once(): + t = await _target(org, namespace, repo, into, dry_run) + if isinstance(t, str): + report.error = t + return report + doc = await ordinary_get( + KnowledgeGetInput(org=org, namespace=namespace, source_uri=source_uri) ) - return report - from server.settings import settings - - report.image_only = dx.image_only_sections(doc.content or "") - chars = window_chars or settings.memory_decision_extract_window_chars - wins = _windows(chunks, set(report.image_only), chars) - report.windows = len(wins) - # One scan of the extractor's rows on this document and their records, for the prompts - # and the retire step; rows this run writes are skipped by the retire step. - try: - own, report.error = await _read_own(org, t, source_uri) - except _REPORTED_ERRORS as e: - # Before any model call: a run that cannot see its own rows reads nothing. - report.error = f"could not read the extractor's rows: {_refusal(e)}" - if report.error: - return report - known = _known_decisions(own) - statements = {row.memory_key: dx.stored_statement(record) for row, record in own} - state, answered = await _candidates( - org, - t, - source_uri, - wins, - max_per_section, - report, - known, - statements, - doc.title or "", - read_deadline, - ) - if wins and not answered and not report.error: - report.error = ( - "no window was read: every model call failed, was answered by the fake model, " - "came back unreadable, or answered nothing and failed when read again" + if not doc.found: + report.error = f"no live document {source_uri!r} in {org}/{namespace}" + return report + chunks = await document_chunks(org, namespace, source_uri) + if not chunks: + report.error = ( + f"{source_uri!r} has no chunks for the current embedding model; run " + f"`loom rechunk --org {org} --namespace {namespace} --source-uri {source_uri} " + "--apply` first" + ) + return report + from server.settings import settings + + report.image_only = dx.image_only_sections(doc.content or "") + chars = window_chars or settings.memory_decision_extract_window_chars + wins = _windows(chunks, set(report.image_only), chars) + report.windows = len(wins) + # One scan of the extractor's rows on this document and their records, for the prompts + # and the retire step; rows this run writes are skipped by the retire step. + try: + own, report.error = await _read_own(org, t, source_uri) + except _REPORTED_ERRORS as e: + # Before any model call: a run that cannot see its own rows reads nothing. + report.error = f"could not read the extractor's rows: {_refusal(e)}" + if report.error: + return report + known = _known_decisions(own) + statements = {row.memory_key: dx.stored_statement(record) for row, record in own} + state, answered = await _candidates( + org, + t, + source_uri, + wins, + max_per_section, + report, + known, + statements, + doc.title or "", + read_deadline, ) - if report.error: - # Held, out of time or nothing read: such a run must not write or retire anything. + if wins and not answered and not report.error: + report.error = ( + "no window was read: every model call failed, was answered by the fake model, " + "came back unreadable, or answered nothing and failed when read again" + ) + if report.error: + # Held, out of time or nothing read: such a run must not write or retire anything. + return report + # An empty TaskSet is falsy: the caller's is told apart from none by `is None`. + units = TaskSet() if writes is None else writes + written = await _write_kept(org, t, source_uri, state, dry_run, report, may_write, units) + if written is not None: + await _retire(report, own, state, written, t.row_tag, may_write, units) return report - # An empty TaskSet is falsy: the caller's is told apart from none by `is None`. - units = TaskSet() if writes is None else writes - written = await _write_kept(org, t, source_uri, state, dry_run, report, may_write, units) - if written is not None: - await _retire(report, own, state, written, t.row_tag, may_write, units) - return report async def _write_kept( diff --git a/server/memory/app/for_file.py b/server/memory/app/for_file.py index e8793c2f1a..ac6e24101b 100644 --- a/server/memory/app/for_file.py +++ b/server/memory/app/for_file.py @@ -12,6 +12,7 @@ from server.code.app.common import repo_relative from server.code.domain.anchor import local_name, names_symbol +from server.code.domain.index.repos import derived_once from server.core.ch import get_client, statement_timeout from server.core.datetimes import naive_utc_now from server.core.hashing import as_valid_unicode @@ -1072,12 +1073,14 @@ def _as_printed(row: dict[str, Any]) -> dict[str, Any]: async def handle_memory_for_file(input: MemoryForFileInput) -> MemoryForFileOutput: path = repo_relative(input.path) - # The rows the caller wrote in their other namespaces are read beside the request's - # own and take the places `top_k` leaves after them: a wider read never costs a row - # the narrower one served. - (rows, _skipped), others = await asyncio.gather( - _merged_rows(input, path), _own_rows(input, path) - ) + # each extra namespace, each link and each trunk is asked for its entry and its gate + with derived_once(): + # The rows the caller wrote in their other namespaces are read beside the request's + # own and take the places `top_k` leaves after them: a wider read never costs a row + # the narrower one served. + (rows, _skipped), others = await asyncio.gather( + _merged_rows(input, path), _own_rows(input, path) + ) if others is not None: note_budget_shape("own_namespaces") rows = rows + others[: max(int(input.top_k) - len(rows), 0)] diff --git a/tests/unit/test_namespace_loops_derive_once.py b/tests/unit/test_namespace_loops_derive_once.py new file mode 100644 index 0000000000..1aec6c2473 --- /dev/null +++ b/tests/unit/test_namespace_loops_derive_once.py @@ -0,0 +1,676 @@ +"""A call or a pass that asks about one namespace at a time derives the configured +repositories once. + +Deriving the configured entries parses the operator's configuration and takes a +`realpath` and a `stat` of every entry's clone directory. A lookup of one namespace (its +entry, its trunk, whether it is restricted, the tracker bound to it) derives them all, +so a call that asks it of each namespace a token names, each grant a token inherits, +each file a push changed, each repository of a pass or each code name of a document +costs those items times the entries on the event loop. + +The entries, the directory and the caller are those of +`test_repo_listings_derive_once.py`: the real configuration parse and the real gate over +two orgs, repositories of several branches, a branch added from the Repositories page, +and entries the caller may only ask to join or may not see. Each answer is asserted +beside its derivation count. +""" + +from __future__ import annotations + +import contextlib +import json +import time +from collections.abc import AsyncIterator, Iterator +from datetime import datetime +from types import SimpleNamespace +from typing import Any +from unittest.mock import AsyncMock + +import pytest + +from server.auth import authz, service_accounts +from server.auth.jwt import AuthInfo +from server.code.app import backport, memory_links +from server.code.app import symbol as code_symbol +from server.code.app.index import risk_fit +from server.code.domain.declaration import fingerprint_version +from server.code.domain.index import repos +from server.code.workers import backport_gaps, graph_stats +from server.core import grant_cache +from server.identity.api.models import NamespaceListMineInput +from server.identity.app import me_service_accounts as tokens +from server.identity.app import namespace_kinds, namespace_membership +from server.identity.store import grants as grants_store +from server.insights.app import admin_routes +from server.insights.app.admin_models import TokenMintInput +from server.memory.api.models_for_file import MemoryForFileInput +from server.memory.app import ( + code_link_pass, + code_link_policy, + code_link_reads, + code_link_recheck, + code_link_rehash, + code_links, + decision_extract, + for_file, +) +from server.memory.store.code_links import LinkRow, link_row +from server.operations.base import Role, grant_rank +from server.settings import settings +from server.tracker.app import binding +from tests.unit import test_code_backport_gaps as gap_fixtures +from tests.unit import test_decision_extract as extract_fixtures +from tests.unit import test_memory_for_file as file_fixtures +from tests.unit import test_repo_listings_derive_once as listings +from tests.unit.ch_fake import RecordingCH +from tests.unit.principals import acting_as, principal + +pytestmark = pytest.mark.asyncio + +derivations = listings.derivations +_memory, _tag = listings._memory, listings._tag + +OWNER = "alice" +# what a token is minted for: a memory namespace, two repositories and a restricted one +NAMED = ["notes", "code-widgets", "code-gears-25-8", "code-safe"] +# a token for every namespace of its creator, which saves to the one named before `*` +HOME_THEN_ALL = ["notes", "*"] + + +class _TokenStore: + """The token list and the directory a mint reads: no token, no saved pick, and the + owner's grant on each namespace of `NAMED`.""" + + async def insert(self, table: str, rows: list[dict[str, Any]], **_: Any) -> None: + return None + + async def query_all(self, sql: str, **_: Any) -> list[dict[str, Any]]: + return [] + + async def query_one(self, sql: str, **kw: Any) -> dict[str, Any] | None: + if "max(version)" in sql: # a new token's version, past its name's rows + return {"v": time.time_ns()} + if "FROM loom.namespace_grants FINAL" in sql and kw["params"]["ns"] in NAMED: + return {"role": "writer"} + return None + + +@pytest.fixture(autouse=True) +def kinds_unread() -> Iterator[None]: + """No namespace kind is read yet, and the kinds a mint or a file lookup reads are + dropped after it: they are kept per org for 30 s.""" + namespace_kinds.reset_cache() + yield + namespace_kinds.reset_cache() + + +@pytest.fixture +def owner(monkeypatch: pytest.MonkeyPatch) -> list[list[dict[str, Any]]]: + """`OWNER` signed in to the dashboard as an admin of org `o`, a writer of every + namespace of `NAMED`; the grant rows a mint writes.""" + granted: list[list[dict[str, Any]]] = [] + + async def grant_role_for(org: str, ns: str, subject: str) -> Role | None: + return Role.WRITER if (org, subject) == ("o", OWNER) and ns in NAMED else None + + async def grant_rows(org: str, subject: str) -> grant_cache.GrantMap: + held = NAMED if (org, subject) == ("o", OWNER) else [] + return grant_cache.GrantMap(ranks=dict.fromkeys(held, grant_rank("writer"))) + + async def account_active(org: str, creator: str) -> bool: + return True + + async def insert_rows(rows: list[dict[str, Any]], **_: Any) -> None: + granted.append(rows) + + caller = AuthInfo( + subject=OWNER, + org="o", + namespaces=("*",), + roles=(Role.ORG_ADMIN,), + is_service_account=False, + token_id="login-1", + session_id="s1", + first_party=True, + issued_at=int(time.time()), + ) + monkeypatch.setattr(authz, "grant_role_for", grant_role_for) + monkeypatch.setattr(grant_cache, "_read", grant_rows) + monkeypatch.setattr("server.auth.delegation.creator_account_active", account_active) + for module in ("server.core.ch", "server.observability.audit"): + monkeypatch.setattr(f"{module}.get_client", lambda: _TokenStore()) + monkeypatch.setattr(grants_store, "insert_rows", insert_rows) + monkeypatch.setattr(binding, "refresh_overrides", AsyncMock()) # no maintainer's link + monkeypatch.setattr(type(settings), "auth_actually_required", lambda self: True) + monkeypatch.setattr(settings, "public_base_url", "https://loom.example") + monkeypatch.setattr("server.auth.bearer.verify_bearer", AsyncMock(return_value=caller)) + return granted + + +def _request(body: dict[str, Any]) -> Any: + async def read() -> dict[str, Any]: + return body + + return SimpleNamespace( + headers={"Authorization": "Bearer t"}, state=SimpleNamespace(), json=read + ) + + +async def _own_token(create: Any = tokens.me_service_accounts_create) -> dict[str, Any]: + body = {"name": "ci", "namespaces": NAMED, "role": "viewer"} + result: dict[str, Any] = await create(_request(body), body) + return result + + +async def test_a_token_reads_the_namespaces_it_names_and_is_granted_the_restricted_one( + derivations: list[int], owner: list[list[dict[str, Any]]] +) -> None: + out = await _own_token() + assert out["namespaces"] == NAMED + assert out["ns_roles"] == dict.fromkeys(NAMED, "viewer") + assert out["restricted_namespaces"] == ["code-safe"] + assert [(r["namespace"], r["role"]) for rows in owner for r in rows] == [ + ("code-safe", "viewer") + ] + + +@pytest.mark.parametrize( + "create", [tokens.me_service_accounts_create, tokens.me_personal_tokens_create] +) +async def test_a_token_mint_derives_the_configured_entries_once( + create: Any, derivations: list[int], owner: list[list[dict[str, Any]]] +) -> None: + """Each namespace the token names is asked whether it is restricted, for its role + and whether it is a repository, and each restricted one for the tracker bound to it.""" + await _own_token(create) + assert derivations == [1], f"one mint derived the operator's entries {derivations[0]} times" + + +async def _admin_token(namespaces: list[str] = NAMED, role: str = "viewer") -> Any: + body = {"name": "ci", "org": "o", "namespaces": namespaces, "roles": [role]} + return await admin_routes.admin_token_mint(_request(body), TokenMintInput(**body)) + + +async def test_an_admins_token_reads_the_namespaces_it_names( + derivations: list[int], owner: list[list[dict[str, Any]]] +) -> None: + out = await _admin_token() + assert out.namespaces == NAMED and out.roles == ["viewer"] + assert [(r["namespace"], r["role"]) for rows in owner for r in rows] == [ + ("code-safe", "viewer") + ] + + +async def test_an_admins_token_for_every_namespace_saves_to_the_one_named_before_the_star( + derivations: list[int], owner: list[list[dict[str, Any]]] +) -> None: + out = await _admin_token(HOME_THEN_ALL, "writer") + assert out.namespaces == HOME_THEN_ALL and out.saves_to == "notes" + assert [r for rows in owner for r in rows] == [] # no restricted namespace is named + + +@pytest.mark.parametrize(("namespaces", "role"), [(NAMED, "viewer"), (HOME_THEN_ALL, "writer")]) +async def test_an_admins_token_mint_derives_the_configured_entries_once( + namespaces: list[str], role: str, derivations: list[int], owner: list[list[dict[str, Any]]] +) -> None: + """Each namespace the token names is asked whether it is restricted and whether it + is a repository, and the one named before `*` for its kind.""" + await _admin_token(namespaces, role) + assert derivations == [1], f"one mint derived the operator's entries {derivations[0]} times" + + +# the namespaces the creator of a token holds a grant on +HELD = ( + "notes", + "code-widgets", + "code-widgets-26-1", + "code-gears-25-8", + "code-safe", # restricted by its entry + "code-vault", # restricted by its entry and closed +) + + +async def _listed(monkeypatch: pytest.MonkeyPatch) -> list[tuple[str, str, bool]]: + """(namespace, kind, inherited) of what a token that reads as its creator lists.""" + + def grants(sql: str, params: dict[str, Any]) -> list[dict[str, Any]]: + if OWNER not in params.get("subs", []): + return [] + return [ + { + "namespace": ns, + "role": "viewer", + "status": "active", + "joined_at": datetime(2026, 1, 1), + "visibility": "private", + "kind": "", + "title": "", + "description": "", + "is_new": 0, + } + for ns in HELD + ] + + async def creator(org: str, subject: str, ch: Any = None) -> str: + return OWNER + + ch = RecordingCH(strict=False).on("lower(g.subject) IN", grants) + ch.install(monkeypatch, "server.identity.app.namespace_membership") + monkeypatch.setattr(service_accounts, "inheriting_creator", creator) + token = principal(Role.VIEWER, org="o", namespaces=("scratch",), subject="sa:ci") + with acting_as(token): + out = await namespace_membership.handle_namespace_list_mine(NamespaceListMineInput(org="o")) + return [(r.namespace, r.kind, r.inherited) for r in out.rows] + + +async def test_a_token_lists_its_creators_namespaces_but_no_restricted_one( + derivations: list[int], monkeypatch: pytest.MonkeyPatch +) -> None: + assert await _listed(monkeypatch) == [ + ("scratch", "memory", False), + ("notes", "memory", True), + ("code-widgets", "code", True), + ("code-widgets-26-1", "code", True), + ("code-gears-25-8", "code", True), + ] + + +async def test_a_tokens_namespace_list_derives_the_configured_entries_once( + derivations: list[int], monkeypatch: pytest.MonkeyPatch +) -> None: + """Each grant the token inherits is asked whether its entry is restricted.""" + await _listed(monkeypatch) + assert derivations == [1], f"one listing derived the operator's entries {derivations[0]} times" + + +WHO = {"agent": "a", "user_id": "-", "session_id": "-"} +CODE_SYMBOL = code_symbol.handle_code_symbol # the handler, before a test's world replaces it + + +def _file_link(head: dict[str, Any], cns: str, path: str, **fields: Any) -> LinkRow: + """A link made from `head` as it is now, to the file `path` of `cns`.""" + return link_row( + namespace=head["namespace"], + memory_key=head["memory_key"], + memory_id=head["mid"], + code_namespace=cns, + inputs_hash=code_link_reads.memory_inputs(head, cns), + path=path, + complete=1, + **WHO, + **fields, + ) + + +async def _file_lookup( + monkeypatch: pytest.MonkeyPatch, +) -> tuple[list[tuple[list[str], list[str]]], list[tuple[str, str, str]]]: + """(trunks, memory namespaces) of each read of the links to a file, and (namespace, + key, code state) of each hit, for a pre-edit lookup from a checkout of `acme/widgets` + that also names a branch of it and a repository the caller may not read. Two of the + caller's memories are linked to the file and name it nowhere else: one in the trunk + of `acme/widgets`, one in the trunk of that repository.""" + asked: list[tuple[list[str], list[str]]] = [] + heads = [ + _memory("retries", "The reader retries twice.", "acme/widgets"), + _memory("gears", "The reader feeds the gears.", "acme/gears"), + ] + links = [ + _file_link(h, cns, "src/io/reader.py", state="fresh") + for h, cns in zip(heads, ("code-widgets", "code-gears"), strict=True) + ] + + async def for_paths(org: str, trunks: list[str], paths: list[str], **kw: Any) -> list[LinkRow]: + asked.append((trunks, kw["namespaces"])) + return links + + async def heads_by_identity(org: str, idents: list[Any]) -> list[dict[str, Any]]: + return heads + + def linked(sql: str, params: dict[str, Any]) -> list[dict[str, Any]]: + """The rows of one namespace among the linked memories the statement names.""" + return [ + file_fixtures._row( + h["memory_key"], json.dumps(h["value"]), tags=h["tags"], matched_files=[] + ) + for h in heads + if h["mid"] in params["linked"] and h["namespace"] == params.get("ns") + ] + + ch = listings._directory().on("memory_id IN {linked:Array(UUID)}", linked) + ch.install(monkeypatch, "server.memory.app.for_file") + monkeypatch.setattr(code_link_reads.store, "for_paths", for_paths) + monkeypatch.setattr(code_link_reads.store, "heads_by_identity", heads_by_identity) + monkeypatch.setattr(settings, "memory_search_default_namespace_scope", "all_mine") + me = principal( + Role.VIEWER, + org="o", + namespaces=("personal", "notes"), + subject=listings.ME, + service_account=False, + ) + with acting_as(me): + out = await for_file.handle_memory_for_file( + MemoryForFileInput( + org="o", + namespace="personal", + path="src/io/reader.py", + tags=[_tag("acme/widgets")], + extra_namespaces=["code-widgets-26-1", "code-gears"], + ) + ) + return asked, [(h.namespace, h.memory_key, h.code_state) for h in out.hits] + + +async def test_a_file_lookup_serves_the_links_in_the_trunks_the_caller_may_read( + derivations: list[int], monkeypatch: pytest.MonkeyPatch +) -> None: + """The links of the request's namespaces and of the caller's other namespaces are + read in the trunk of each extra namespace, for the memories of those the caller may + read. A link in a trunk the caller may not read is dropped: the memory it alone + reaches is not a hit.""" + asked, hits = await _file_lookup(monkeypatch) + trunks = ["code-widgets", "code-gears"] + assert asked == [(trunks, ["personal", "code-widgets-26-1"]), (trunks, ["notes"])] + assert hits == [("personal", "retries", "fresh")] + + +async def test_a_file_lookup_derives_the_configured_entries_once( + derivations: list[int], monkeypatch: pytest.MonkeyPatch +) -> None: + """Each extra namespace is asked for its gate and its trunk, each link for the + trunk its memory names, and each trunk for its gate.""" + await _file_lookup(monkeypatch) + assert derivations == [1], f"one lookup derived the operator's entries {derivations[0]} times" + + +async def _mined(monkeypatch: pytest.MonkeyPatch) -> tuple[str, list[str]]: + """(why it did not run, the namespace of each decision recorded) for one document + of a branch's code namespace, mined for its repository as the operator. The model, + the document and the memory writes are the test's; the code names are looked up + by `code.symbol` itself, in an index that holds none.""" + world = extract_fixtures._World(monkeypatch, [extract_fixtures._candidate()]) + monkeypatch.setattr(code_symbol, "handle_code_symbol", CODE_SYMBOL) + report = await decision_extract.extract_document( + "o", "code-widgets-26-1", "doc.md", dry_run=False, repo="acme/widgets" + ) + return report.error, [r.namespace for r in world.recorded] + + +async def test_a_documents_decisions_are_recorded_in_its_repositorys_trunk( + derivations: list[int], monkeypatch: pytest.MonkeyPatch +) -> None: + assert await _mined(monkeypatch) == ("", ["code-widgets"]) + + +async def test_a_documents_extraction_derives_the_configured_entries_once( + derivations: list[int], monkeypatch: pytest.MonkeyPatch +) -> None: + """The document's namespace and the repository are each asked for their trunk and + their gate, and each code name it mentions is looked up in the trunk.""" + await _mined(monkeypatch) + assert derivations == [1], ( + f"one extraction derived the operator's entries {derivations[0]} times" + ) + + +# the tracker namespace bound to the entries of two repositories +BOUND = json.dumps({"code-widgets*": "tracker-widgets", "code-gears*": "tracker-gears"}) + + +class _State: + """Code index state with no stored fit, and a head for every namespace.""" + + async def get_state(self, org: str, ns: str, key: str) -> str: + return "h" if key == "git_head" else "" + + async def set_state(self, *_: Any, **__: Any) -> None: + return None + + +async def _refitted( + monkeypatch: pytest.MonkeyPatch, derivations: list[int] +) -> tuple[list[tuple[str, str]], int]: + """The (org, tracker namespace) whose outcomes the risk refit read, one per bound + entry, and the entries it skipped, in one pass over every entry. `derivations` + counts from the refit's start.""" + read: list[tuple[str, str]] = [] + + async def outcomes(org: str, tracker_ns: str, months: int) -> list[dict[str, Any]]: + read.append((org, tracker_ns)) + return [] + + monkeypatch.setattr(settings, "tracker_code_namespace_bindings_json", BOUND) + monkeypatch.setattr(binding, "refresh_overrides", AsyncMock()) # no maintainer's link + monkeypatch.setattr("server.code.store.index.CodeRepo", _State) + monkeypatch.setattr(risk_fit, "_tracker_outcomes", outcomes) + entries = repos.configured_repos() + derivations[0] = 0 + result = graph_stats.CodeGraphStatsResult() + await graph_stats._refit_jit_risk(entries, result) + return read, result.jit_risk_skipped + + +async def test_a_risk_refit_reads_the_tracker_bound_to_each_entry( + derivations: list[int], monkeypatch: pytest.MonkeyPatch +) -> None: + """An entry no tracker is bound to is skipped, and so is one whose tracker has too + few outcomes to fit.""" + read, skipped = await _refitted(monkeypatch, derivations) + assert read == [*[("o", "tracker-widgets")] * 3, *[("o", "tracker-gears")] * 2] + assert skipped == len(listings.ENTRIES) + 1 # and the branch added from the page + + +async def test_a_risk_refit_derives_the_configured_entries_once( + derivations: list[int], monkeypatch: pytest.MonkeyPatch +) -> None: + """Each entry is asked for the tracker bound to it, and that tracker whether it is + restricted.""" + await _refitted(monkeypatch, derivations) + assert derivations == [1], f"one refit derived the operator's entries {derivations[0]} times" + + +class _Fixes: + """A code index with two labelled fixes in each trunk's window, and its head.""" + + async def get_state(self, org: str, ns: str, key: str) -> str: + return "a" * 40 if key == "git_head" else "" + + async def labelled_fixes_in_window(self, org: str, ns: str, **_: Any) -> list[dict[str, Any]]: + return [ + { + "pr_number": n, + "title": f"Fix {n}", + "merged_at": gap_fixtures.NOW, + "labels": ["pr-must-backport"], + "merge_commit_sha": b"\xaa" * 20, + } + for n in (101, 102) + ] + + +async def _gap_pass(monkeypatch: pytest.MonkeyPatch) -> list[tuple[str, int, str, str]]: + """(trunk, fix, branch namespace, branch) of each row one nightly pass writes. The + fix's read is the test's: it asks the configuration for the trunk's release + branches and their refs, as the composed read does, and finds a gap in each.""" + + async def read_fix(req: Any) -> Any: + mirror, refs = backport.branch_refs(req.org, req.namespace) + branches = backport.resolve_branches(req.org, req.namespace, []) + assert await binding.authorized_tracker_namespace(req.org, req.namespace) + return SimpleNamespace( + branches=[ + {"namespace": ns, "branch": refs[ns], "verdict": "gap", "epistemic": "exact"} + for ns, _ in branches + ], + fix={}, + causes=[], + tracker_unavailable=False, + ) + + monkeypatch.setattr(settings, "tracker_code_namespace_bindings_json", BOUND) + monkeypatch.setattr(binding, "refresh_overrides", AsyncMock()) # no maintainer's link + monkeypatch.setattr(settings, "code_backport_gaps_pace_s", 0.0) + written = gap_fixtures._GapsRepo() + result = backport_gaps.BackportGapsResult() + await backport_gaps._run( + result, + now=gap_fixtures.NOW, + repo=written, + code_repo=_Fixes(), + source_factory=lambda org, ns: gap_fixtures._WantedSource([]), + runner=read_fix, + ) + assert not result.errors, result.errors + return [ + (r["code_namespace"], r["pr_number"], r["branch_namespace"], r["branch"]) + for rows in written.inserted + for r in rows + ] + + +async def test_a_backport_gap_pass_writes_a_row_for_each_release_branch_of_each_trunk( + derivations: list[int], monkeypatch: pytest.MonkeyPatch +) -> None: + """The trunks with a standard release branch, in each org; the page's branch is a + release of `acme/widgets` too.""" + widgets = [ + ("code-widgets-26-2", "26.2"), + ("code-widgets-26-1", "26.1"), + ("code-widgets-25-3", "25.3"), + ] + assert await _gap_pass(monkeypatch) == [ + *[("code-widgets", pr, ns, b) for pr in (101, 102) for ns, b in widgets], + *[("code-gears", pr, "code-gears-25-8", "25.8") for pr in (101, 102)], + ] + + +async def test_a_backport_gap_pass_derives_the_configured_entries_once( + derivations: list[int], monkeypatch: pytest.MonkeyPatch +) -> None: + """Each trunk is asked for the tracker bound to it, and each fix for its trunk's + release branches, their refs and that tracker again.""" + await _gap_pass(monkeypatch) + assert derivations == [1], f"one pass derived the operator's entries {derivations[0]} times" + + +# the files one push to `acme/widgets` changed, each with a memory linked to it +PUSHED = ["src/io/reader.py", "src/io/writer.py", "src/plan.py"] + + +async def _rechecked(monkeypatch: pytest.MonkeyPatch) -> list[tuple[str, str, str]]: + """(path, definition, the commit it was checked at) of each link the recheck of + `code-widgets` leaves after its index moved from `h1` to `h2`, as `code.refresh` + asks for it: each memory names `retry_limit` and is linked to a file that defines + it since the push. The mirror, the link store and the index's heads are the test's.""" + heads = [ + _memory(f"m{i}", "`retry_limit` caps the retries.", "acme/widgets") + | {"org": "o", "status": "active", "tombstoned_at": None} + for i in range(len(PUSHED)) + ] + links = [ + _file_link( + h, + "code-widgets", + path, + org="o", + state="fresh", + checked_commit="h1", + fingerprint_version=fingerprint_version(), + ) + for h, path in zip(heads, PUSHED, strict=True) + ] + written: list[LinkRow] = [] + state = {"git_head": "h2"} + + async def git_ok(*_: Any, **__: Any) -> bool: + return True + + async def diff(git_dir: str, base: str, head: str) -> dict[str, str]: + return {p: p for p in PUSHED} + + async def rev_list(git_dir: str, *args: str) -> str: + return "" + + async def blob(git_dir: str, commit: str, path: str, **_: Any) -> bytes: + return b"retry_limit = 2\n\n\ndef read():\n return retry_limit\n" + + async def cursor(name: str) -> str: + return "" + + async def pending(*_: Any, **__: Any) -> tuple[list[Any], None]: + return [], None + + async def for_paths(org: str, cns: list[str], paths: list[str]) -> list[LinkRow]: + return [a for a in links if a["path"] in paths] + + async def memory_heads(org: str, ids: list[str]) -> list[dict[str, Any]]: + return [h for h in heads if h["mid"] in ids] + + async def none(*_: Any, **__: Any) -> list[Any]: + return [] + + async def no_policy(org: str, namespaces: list[str]) -> dict[str, str]: + return {} + + async def insert(rows: list[LinkRow]) -> None: + written.extend(rows) + + @contextlib.asynccontextmanager + async def lease(name: str, **_: Any) -> AsyncIterator[None]: + yield + + class Index: + async def get_state(self, org: str, ns: str, key: str) -> str: + return state.get(key, "h1") + + async def set_state(self, org: str, ns: str, key: str, value: str) -> None: + state[key] = value + + store, git = code_links.store, memory_links.gitrepo + monkeypatch.setattr(settings, "memory_code_links_enabled", True) + monkeypatch.setattr(memory_links, "CodeRepo", Index) + monkeypatch.setattr(memory_links, "link_cursor", cursor) + monkeypatch.setattr(memory_links, "set_link_cursor", AsyncMock()) + monkeypatch.setattr(memory_links, "candidates", none) # the index names no definition + for name, read in (("is_ancestor", git_ok), ("has_commit", git_ok), ("file_at", blob)): + monkeypatch.setattr(git, name, read) + monkeypatch.setattr(git, "diff_paths_renamed", diff) + monkeypatch.setattr(git, "run", rev_list) + monkeypatch.setattr(code_link_pass.repository_locks, "lease", lease) + monkeypatch.setattr(store, "code_namespaces", AsyncMock(return_value=[("o", "code-widgets")])) + monkeypatch.setattr(store, "pending", pending) + monkeypatch.setattr(store, "for_paths", for_paths) + monkeypatch.setattr(store, "memory_heads", memory_heads) + for name in ("lost", "for_memories"): + monkeypatch.setattr(store, name, none) + monkeypatch.setattr(store, "code_change_policies", no_policy) + monkeypatch.setattr(store, "insert", insert) + monkeypatch.setattr(code_link_rehash, "refingerprint", AsyncMock()) + monkeypatch.setattr(code_link_policy, "apply_policies", AsyncMock()) + result = await code_link_recheck.recheck_repository("o", "code-widgets") + assert result is not None and not result.errors, result + return [ + (a["path"], a["qualified_name"], a["checked_commit"]) + for a in written + if a["tombstoned_at"] is None + ] + + +async def test_a_refresh_links_each_memory_to_the_definition_its_file_now_holds( + derivations: list[int], monkeypatch: pytest.MonkeyPatch +) -> None: + assert await _rechecked(monkeypatch) == [ + ("src/io/reader.py", "src.io.reader::retry_limit", "h2"), + ("src/io/writer.py", "src.io.writer::retry_limit", "h2"), + ("src/plan.py", "src.plan::retry_limit", "h2"), + ] + + +async def test_a_refreshs_link_recheck_derives_the_configured_entries_once( + derivations: list[int], monkeypatch: pytest.MonkeyPatch +) -> None: + """Each git read and each file read asks for the repository's entry, and each + link it moves for the trunk its memory names.""" + await _rechecked(monkeypatch) + assert derivations == [1], f"one recheck derived the operator's entries {derivations[0]} times"