Skip to content
Open
24 changes: 22 additions & 2 deletions docs/architecture/code-index-architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
43 changes: 23 additions & 20 deletions server/code/workers/backport_gaps.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,33 +129,36 @@ 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

started = time.monotonic()
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)


Expand Down
24 changes: 13 additions & 11 deletions server/code/workers/graph_stats.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
7 changes: 5 additions & 2 deletions server/identity/app/me_service_accounts.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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")
Expand All @@ -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:
Expand Down
128 changes: 66 additions & 62 deletions server/identity/app/namespace_membership.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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]]:
Expand Down
Loading
Loading