diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index 06e23a82f4e..1ec9815a601 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -1196,6 +1196,8 @@ The memory plane outside search/ask/extraction: writes, conflicts, lifecycle, wo | --- | --- | --- | --- | --- | | `LOOM_RECALIBRATION_ENABLED` | `bool` | `True` | | Periodically re-run the embedder calibration probe so thresholds follow a silently revised embedder. Fake providers skip. | | `LOOM_RECALIBRATION_INTERVAL_SECONDS` | `int` | `604800` | | Seconds between embedder calibration probes. | +| `LOOM_CODE_CALIBRATION_ENABLED` | `bool` | `False` | | Calibrate a code namespace once it is embedded and has no calibration under the served embedder (a first embed, or an embedder change); one namespace a pass. | +| `LOOM_CODE_CALIBRATION_INTERVAL_SECONDS` | `int` | `3600` | | Seconds between code calibration passes. | | `LOOM_ENTITY_HEAL_INTERVAL_SECONDS` | `int` | `900` | | Seconds between the entity extractor's mirror divergence heal, a FINAL-to-FINAL join of loom.memory and loom.memory_embeddings (343 GB/day if run every pass). Divergence arrives a few rows a day. | | `LOOM_PROJECTION_REPAIR_ENABLED` | `bool` | `True` | | Retry best-effort projections (chunks, evidence links, graph side tables) that failed after the primary write. Bounded and idempotent; unsupported ones stay in ops.projection_failures.list. | | `LOOM_PROJECTION_REPAIR_INTERVAL_SECONDS` | `int` | `300` | | Seconds between projection repair passes. | diff --git a/docs/reference/status.md b/docs/reference/status.md index b2167b58d5b..dc62a3feb7e 100644 --- a/docs/reference/status.md +++ b/docs/reference/status.md @@ -89,13 +89,14 @@ default is `off`) are not listed here. -55 boolean settings load false. +56 boolean settings load false. | Setting | Meaning | | --- | --- | | `LOOM_ALLOW_INSECURE` | True lets a non-loopback bind start with auth off, MCP open mode, open self-signup outside trust-network, the dev signing secret or a weak root, gateway or end-user key. | | `LOOM_ASSISTANT_ENABLED` | Serve the assistant with its explicitly configured provider; false refuses chat. | | `LOOM_CH_LOG_COMMENT_STATEMENT_DIGEST` | Append `sql: ` of each statement to its `log_comment` (" "), so query_log rows group by shape. | +| `LOOM_CODE_CALIBRATION_ENABLED` | Calibrate a code namespace once it is embedded and has no calibration under the served embedder (a first embed, or an embedder change); one namespace a pass. | | `LOOM_CODE_COMPILER_SHARE_MIRROR_PACKS` | Hard-link each compiler-tier checkout's packs to its mirror's, so a tier costs its working tree, not a second copy. | | `LOOM_CODE_COVERAGE_IMPORT_ENABLED` | Import per-test line coverage from an instrumented CI run into the test map (`method='coverage'`) and the per-file executed lines (`code_coverage_files`). | | `LOOM_CODE_EMBED_RECOVERY_ENABLED` | Embedding recovery for code_chunks/code_summaries stubs (dim=0). | diff --git a/docs/reference/workers.md b/docs/reference/workers.md index 24144749710..c8e6dd1cec7 100644 --- a/docs/reference/workers.md +++ b/docs/reference/workers.md @@ -205,6 +205,7 @@ adding its row. | `adoption_telemetry` | Send live domain snapshots and completed adoption reports to the event collector. | `LOOM_ADOPTION_TELEMETRY_ENABLED` | True | fixed | 300 | | `audit_verifier` | Audit tamper-detection worker. | `LOOM_AUDIT_VERIFIER_ENABLED` | True | `LOOM_AUDIT_VERIFIER_INTERVAL_SECONDS` | 3600 | | `code_backport_gaps` | Nightly set-wide backport report: for every merged trunk PR of the last `LOOM_CODE_BACKPORT_GAPS_DAYS` that the maintainers labelled for backport (`pr-must-backport*` on loom's ledger, QA's… | `LOOM_CODE_BACKPORT_GAPS_ENABLED` + `LOOM_CODE_PR_HISTORY_ENABLED` | True | `LOOM_CODE_BACKPORT_GAPS_INTERVAL_SECONDS` | 86400.0 | +| `code_calibration` | Calibration for the code plane: a namespace gets its own thresholds once it is embedded, and again when the embedder changes. | `LOOM_CODE_CALIBRATION_ENABLED` | False | `LOOM_CODE_CALIBRATION_INTERVAL_SECONDS` | 3600 | | `code_coverage_import` | Daily measured-coverage import (`server.code.app.index.coverage_import`). | `LOOM_CODE_COVERAGE_IMPORT_ENABLED` + `LOOM_CODE_INTEL_ENABLED` | False | `LOOM_CODE_COVERAGE_IMPORT_INTERVAL_SECONDS` | 86400.0 | | `code_coverage_notify` | Coverage-watch delivery. | `LOOM_CODE_COVERAGE_NOTIFY_ENABLED` + `LOOM_CODE_INTEL_ENABLED` | True | `LOOM_CODE_COVERAGE_NOTIFY_INTERVAL_SECONDS` | 60 | | `code_crossref` | SQL <-> C++ crossref for each C++ entry whose `git_head` moved since its last run: `code_test_map` rows linking test queries to the files that register the functions and settings they use. | `LOOM_CODE_CROSSREF_ENABLED` | True | `LOOM_CODE_CROSSREF_INTERVAL_SECONDS` | 1800 | diff --git a/loom.example.yaml b/loom.example.yaml index 5452a075b11..c32849fb26f 100644 --- a/loom.example.yaml +++ b/loom.example.yaml @@ -3591,6 +3591,14 @@ settings: # Seconds between embedder calibration probes. [restart] # recalibration_interval_seconds: 604800 + # Calibrate a code namespace once it is embedded and has no calibration under the + # served embedder (a first embed, or an embedder change); one namespace a pass. + # [restart] + # code_calibration_enabled: false + + # Seconds between code calibration passes. [restart] + # code_calibration_interval_seconds: 3600 + # Seconds between the entity extractor's mirror divergence heal, a FINAL-to-FINAL join # of loom.memory and loom.memory_embeddings (343 GB/day if run every pass). Divergence # arrives a few rows a day. [restart] diff --git a/schemas/loom-settings.schema.json b/schemas/loom-settings.schema.json index f8536fdc5d3..ff5469ddbe0 100644 --- a/schemas/loom-settings.schema.json +++ b/schemas/loom-settings.schema.json @@ -846,6 +846,16 @@ "type": "string", "description": "Comma-separated GitHub logins of autonomous agents that author pull requests or issues in the indexed repositories, beyond the generic bots (dependabot, github-actions, …). They are never suggested as owners, their names are not tracker entities, and bisect ignores the lines they sign." }, + "code_calibration_enabled": { + "default": false, + "type": "boolean", + "description": "Calibrate a code namespace once it is embedded and has no calibration under the served embedder (a first embed, or an embedder change); one namespace a pass." + }, + "code_calibration_interval_seconds": { + "default": 3600, + "type": "integer", + "description": "Seconds between code calibration passes." + }, "code_callers_candidate_min_confidence": { "default": 0.2, "type": "number", diff --git a/server/code/app/admin.py b/server/code/app/admin.py index 5654aed2857..97582869533 100644 --- a/server/code/app/admin.py +++ b/server/code/app/admin.py @@ -48,14 +48,21 @@ async def handle_code_calibrate(input: CodeCalibrateInput) -> CodeCalibrateOutpu query/positive/hard-distractor triples over the indexed repo. Cosine distributions for code differ from prose — the namespace must not inherit prose-derived gates.""" + require_code_intel() + org, ns = resolve_code_identity(input.org, input.namespace) + return await calibrate_namespace(org, ns) + + +async def calibrate_namespace(org: str, ns: str) -> CodeCalibrateOutput: + """Derive and persist one code namespace's calibration, for the handler (after its + auth and identity) and the `code_calibration` worker (under the namespace's own + customer). Raises `ValidationError` when the probe corpus is too small or the + embedder cannot be probed; the stored row stays.""" from server.memory.app.embedder_calibration import ( calibrate_embedder, persist_namespace_calibration, ) - require_code_intel() - org, ns = resolve_code_identity(input.org, input.namespace) - if not _PROBES_PATH.exists(): raise ValidationError(f"probe corpus missing: {_PROBES_PATH}") positives: list[tuple[str, str]] = [] diff --git a/server/code/store/index/status.py b/server/code/store/index/status.py index a3b52c77059..0b39c71b0cd 100644 --- a/server/code/store/index/status.py +++ b/server/code/store/index/status.py @@ -14,6 +14,7 @@ from server.code.domain.extract.lang_reference import UNEMBEDDED_BY_DESIGN from server.code.domain.index.state import IndexState, StateEntry from server.code.store.index.base import CodeRepoBase +from server.core.vectors.code_tables import code_vector_table logger = logging.getLogger(__name__) @@ -477,3 +478,18 @@ async def chunk_embed_coverage(self, org: str, ns: str) -> tuple[int, int]: surfaces read the same numbers through `table_counts`.""" row = await self._chunk_embed_row(org, ns) return row["embeddable"], row["embedded"] + + async def has_embedded_chunk(self, org: str, ns: str, model: str) -> bool: + """Whether one live chunk carries a vector under `model`, read in the table that + label's rows live in (`code_vector_table`).""" + row = await self._ch.query_one( + f""" + SELECT 1 AS one FROM {code_vector_table(model)} FINAL + WHERE org = {{org:String}} AND namespace = {{ns:String}} + AND embedding_model = {{model:String}} + AND embedding_dim > 0 AND tombstoned_at IS NULL + LIMIT 1 + """, + {"org": org, "ns": ns, "model": model}, + ) + return row is not None diff --git a/server/code/workers/calibration.py b/server/code/workers/calibration.py new file mode 100644 index 00000000000..543c7b9a0df --- /dev/null +++ b/server/code/workers/calibration.py @@ -0,0 +1,142 @@ +"""Calibration for the code plane: a namespace gets its own thresholds once it is +embedded, and again when the embedder changes. + +`code.calibrate` runs only when an operator calls it, so a namespace that never +was called serves the cluster's thresholds, and a row written under another +embedder reads as missing. A row that holds the bare label, written before the +fingerprint, records no embedding space: search keeps serving it, and a pass +rewrites it under the served space's key. A pass calibrates the first configured +namespace that has no row naming the served space and has finished embedding under +it: its first index is built, no stub is left to embed, and one live chunk carries a +vector under the served label. Only one namespace is calibrated a pass, so the cost +stays bounded. +The predicate is stateless, so a restart or a second replica repeats nothing: the +namespace's row, once written, answers it. The one thing a process remembers is which +namespaces were tried, and when: a namespace that fails, or runs past the pass +deadline and is cancelled, would otherwise end every pass and hold the queue for the +rest, so it waits out a cooldown and the next candidate is tried. +""" + +from __future__ import annotations + +import logging +import time +from dataclasses import dataclass, field +from typing import Any + +from server.code.app.index import erasing +from server.core.errors import caller_text +from server.llm import customer +from server.memory.app.embedder_calibration import ( + calibration_applies, + get_namespace_calibration_stored_key, + shared_key, +) +from server.settings import settings +from server.workers.status import record_pass, set_worker_identity + +logger = logging.getLogger("loom.workers.code_calibration") + +# One calibration is a run of sequential embedding calls: the pass gets an hour rather +# than the 900 s default, so a slow provider does not cancel the same namespace every pass. +MAX_PASS_SECONDS = 3600.0 # not a setting: sized to one calibration, not to the interval + +# Namespaces (org, namespace) tried and the monotonic time of the attempt or failure; a +# restart forgets. An attempt is recorded before it runs and cleared on success, so a +# cancelled pass (the supervisor's deadline) cools down like a failed one. +_failed: dict[tuple[str, str], float] = {} +# Passes a failed namespace sits out. +_COOLDOWN_PASSES = 3 + + +def _now() -> float: + return time.monotonic() + + +def cooldown_seconds() -> float: + return float(settings.code_calibration_interval_seconds * _COOLDOWN_PASSES) + + +def forget_failures() -> None: + _failed.clear() + + +@dataclass +class CodeCalibrationResult: + checked: int = 0 + calibrated: str = "" + errors: list[str] = field(default_factory=list) + + +async def needs_calibration(repo: Any, cfg: Any, model: str) -> bool: + """Whether the namespace has no calibration naming `model`'s embedding space and has + finished embedding under it: its first index is built, no live stub is left under + `model` (as `code_embed_recovery` reads it), and one live chunk carries a vector + under it. A namespace still building or embedding, or with nothing embedded under + `model` yet, waits for a later pass. A row holding the bare label is not current: + it records no space, so the namespace is probed and the row rewritten under the + key while search keeps serving the bare one.""" + from server.code.app.index.bootstrap import BUILDING_STAGES, awaits_first_index + from server.code.domain.index.state import STAGE_KEY + + org, ns = cfg.org, cfg.namespace + if await get_namespace_calibration_stored_key(org, ns) == shared_key(model): + return False + # The first index embeds slice by slice: between two slices there is no stub yet. + if await awaits_first_index(cfg, repo): + return False + if await repo.get_state(org, ns, STAGE_KEY) in BUILDING_STAGES: + return False + if await repo.pending_embed_chunks(org, ns, model, settings.code_embed_max_attempts, 1): + return False + return bool(await repo.has_embedded_chunk(org, ns, model)) + + +async def run_pass() -> CodeCalibrationResult: + result = CodeCalibrationResult() + with record_pass("code_calibration") as rec: + await _run(result) + rec.outcome = { + "checked": result.checked, + "calibrated": result.calibrated, + "errors": len(result.errors), + } + return result + + +async def _run(result: CodeCalibrationResult) -> None: + if not calibration_applies(): + return # a fake embedder fails every probe: nothing to calibrate, nothing to log + from server.code.app.admin import calibrate_namespace + from server.code.domain.index.repos import configured_repos + from server.code.store.index import CodeRepo + from server.embedding.embedder import get_embedder + + repo = CodeRepo() + model = str(get_embedder().model_name) + # A switched-off org's namespaces wait, and so do those being erased: a row written + # after the purge would fail the erasure's residue check. + off = await customer.switched_off_orgs() + for cfg in configured_repos(): + org, ns = cfg.org, cfg.namespace + if org in off or await erasing.being_erased(org, ns): + continue + failed_at = _failed.get((org, ns)) + if failed_at is not None and _now() - failed_at < cooldown_seconds(): + continue + result.checked += 1 + try: + if not await needs_calibration(repo, cfg, model): + continue + set_worker_identity("code_calibration", org=org, namespace=ns) + _failed[(org, ns)] = _now() + with customer.for_org(org, namespace=ns): + await calibrate_namespace(org, ns) + except Exception as e: # noqa: BLE001 — the next pass reads the namespace again + logger.warning("code_calibration: %s/%s not calibrated: %s", org, ns, e) + _failed[(org, ns)] = _now() + result.errors.append(f"{org}/{ns}: {caller_text(e)}") + else: + _failed.pop((org, ns), None) + result.calibrated = f"{org}/{ns}" + return # one namespace a pass, calibrated or failed diff --git a/server/memory/app/embedder_calibration.py b/server/memory/app/embedder_calibration.py index 044a7fd40d3..32a01176125 100644 --- a/server/memory/app/embedder_calibration.py +++ b/server/memory/app/embedder_calibration.py @@ -471,9 +471,9 @@ def _served_model() -> str: def shared_key(model: str) -> str: - """The shared calibration's key: `model` and its embedding space's - fingerprint, so the same label at another width or endpoint is probed, not - adopted.""" + """The key a calibration is stored under, the shared one and a namespace's: + `model` and its embedding space's fingerprint, so the same label at another + width or endpoint is probed, not adopted.""" from server.core import embedding_space values = {**settings.model_dump(include=set(embedding_space.FIELDS)), "embedding_model": model} @@ -629,12 +629,13 @@ def clear_ns_overrides() -> None: def namespace_calibration_row(org: str, namespace: str, c: CalibrationResult) -> dict[str, Any]: """One `loom.namespace_calibration_result` row (ReplacingMergeTree(version)) for - `c`: what `get_namespace_calibration` reads back. The nanosecond version makes a - re-run replace the prior result. `persist_namespace_calibration` writes it.""" + `c`: what `get_namespace_calibration` reads back. `embedder_model` holds the + space's key (`shared_key`). The nanosecond version makes a re-run replace the + prior result. `persist_namespace_calibration` writes it.""" return { "org": org, "namespace": namespace, - "embedder_model": c.embedder_model, + "embedder_model": shared_key(c.embedder_model), "similar_p10": c.similar_p10, "similar_p25": c.similar_p25, "similar_p50": c.similar_p50, @@ -666,6 +667,45 @@ async def persist_namespace_calibration(org: str, namespace: str, c: Calibration clear_ns_overrides() +def _row_names_served_space(stored: str, served: str) -> bool: + """Whether a namespace row's `embedder_model` is the served embedding space's. + + A fingerprinted value is compared by `shared_key`. A bare label is a row the build + before the fingerprint wrote: it keeps serving when the label is the served one, so + a replica of that build and this one read the same thresholds through a rolling + upgrade. Such a row cannot tell an endpoint or width change under the same label; + the next calibration of the namespace (`code.calibrate`, or the worker when it is + enabled) writes the fingerprinted value and ends that blind spot. + """ + return stored in (shared_key(served), served) + + +async def get_namespace_calibration_stored_key(org: str, namespace: str) -> str | None: + """`embedder_model` exactly as the namespace's row stores it — a bare served label + for a row written before the fingerprint, or `shared_key` — or None without a row. + + `get_namespace_calibration` answers whether the row serves, which accepts a bare + label; the `code_calibration` worker asks this instead, so a row that does not + record its embedding space is probed and rewritten under the key. + """ + try: + from server.core.ch import get_client + + row = await get_client().query_one( + """ + SELECT embedder_model + FROM loom.namespace_calibration_result FINAL + WHERE org = {org:String} AND namespace = {ns:String} + LIMIT 1 + """, + params={"org": org, "ns": namespace}, + ) + except Exception as e: # noqa: BLE001 — no row read: the worker may calibrate + log.debug("ns calibration key lookup failed (%s); treating as missing", e) + return None + return str(row["embedder_model"]) if row is not None else None + + async def get_namespace_calibration(org: str, namespace: str) -> CalibrationResult | None: """Per-namespace calibration override from `loom.namespace_calibration_result`, else None (caller falls through @@ -715,7 +755,11 @@ async def get_namespace_calibration(org: str, namespace: str) -> CalibrationResu _ns_negative_at[key] = time.monotonic() return None - if row is None: + # A row written under another embedding space (another model, or the same label at + # another endpoint or width) describes another cosine scale: it reads as missing, so + # the cluster calibration serves until the namespace is recalibrated. + served = _served_model() + if row is None or not _row_names_served_space(str(row["embedder_model"]), served): _ns_overrides[key] = None _ns_negative_at[key] = time.monotonic() return None @@ -736,7 +780,7 @@ async def get_namespace_calibration(org: str, namespace: str) -> CalibrationResu abstain_threshold=float(row["abstain_threshold"]), conflict_threshold=float(row["conflict_threshold"]), duplicate_threshold=float(row["duplicate_threshold"]), - embedder_model=str(row["embedder_model"]), + embedder_model=served, is_fake=False, ) _ns_overrides[key] = result diff --git a/server/settings/catalog.py b/server/settings/catalog.py index f084f1a0c23..2ba5237d875 100644 --- a/server/settings/catalog.py +++ b/server/settings/catalog.py @@ -3029,6 +3029,11 @@ class MemorySettings(BaseModel): recalibration_enabled: bool = True # Seconds between embedder calibration probes. recalibration_interval_seconds: int = 7 * 24 * 3600 + # Calibrate a code namespace once it is embedded and has no calibration under the + # served embedder (a first embed, or an embedder change); one namespace a pass. + code_calibration_enabled: bool = False + # Seconds between code calibration passes. + code_calibration_interval_seconds: int = 3600 # Seconds between the entity extractor's mirror divergence heal, a # FINAL-to-FINAL join of loom.memory and loom.memory_embeddings (343 GB/day diff --git a/server/workers/registry.py b/server/workers/registry.py index 69feb29a196..61b827f82c1 100644 --- a/server/workers/registry.py +++ b/server/workers/registry.py @@ -184,6 +184,13 @@ def _spec_for(row: _Worker) -> WorkerSpec: "recalibration_enabled", "recalibration_interval_seconds", ), + _Worker( + "code_calibration", + "server.code.workers.calibration", + "code_calibration_enabled", + "code_calibration_interval_seconds", + max_pass_attr="MAX_PASS_SECONDS", + ), _Worker( "erasure_recovery", "server.erasure.workers.recovery", diff --git a/tests/unit/snapshots/settings_defaults.json b/tests/unit/snapshots/settings_defaults.json index bb4c7a1ad87..e56cc601f9c 100644 --- a/tests/unit/snapshots/settings_defaults.json +++ b/tests/unit/snapshots/settings_defaults.json @@ -138,6 +138,8 @@ "code_bootstrap_mirror_refresh_s": 5.0, "code_bootstrap_mirror_retry_s": 60.0, "code_bot_authors": "", + "code_calibration_enabled": false, + "code_calibration_interval_seconds": 3600, "code_callers_candidate_min_confidence": 0.2, "code_callers_max_distinct_seeds": 5, "code_chunk_max_chars": 6000, diff --git a/tests/unit/snapshots/worker_registry.json b/tests/unit/snapshots/worker_registry.json index 945dbb070dc..7c43d015523 100644 --- a/tests/unit/snapshots/worker_registry.json +++ b/tests/unit/snapshots/worker_registry.json @@ -58,6 +58,20 @@ "id": "server.memory.workers.recalibration:run_pass" } }, + { + "deadline_seconds()": 3600.0, + "due_scope": null, + "first_pass_due": null, + "has_first_pass_hook": false, + "idle_interval_seconds": null, + "interval_seconds": 3600, + "max_pass_seconds": 3600.0, + "name": "code_calibration", + "owned_tables": [], + "pass_callable": { + "id": "server.code.workers.calibration:run_pass" + } + }, { "deadline_seconds()": 240.0, "due_scope": null, diff --git a/tests/unit/test_code_calibration_worker.py b/tests/unit/test_code_calibration_worker.py new file mode 100644 index 00000000000..4bcd1ee56a9 --- /dev/null +++ b/tests/unit/test_code_calibration_worker.py @@ -0,0 +1,407 @@ +"""`code_calibration` calibrates a code namespace once it is embedded and has no +calibration row naming the served embedding space, one namespace a pass; and a row +written under another embedding space (another model, or the same label at another +endpoint or width) reads as missing; a row that holds a bare label, written before the +fingerprint, keeps serving search while a pass rewrites it under the served space's key.""" + +from __future__ import annotations + +import asyncio +from collections.abc import Iterator +from typing import Any + +import pytest + +from server.code.app import admin +from server.code.app.index import erasing +from server.code.domain.index import repos as repos_mod +from server.code.domain.index.state import STAGE_KEY +from server.code.store import index as cr +from server.code.workers import calibration as w +from server.llm import customer +from server.memory.app import embedder_calibration as ec +from server.workers import pass_context, registry + +ORG = "acme" +SERVED = "m-new" + + +class _Cfg: + source = "config" + + def __init__(self, ns: str) -> None: + self.org, self.namespace = ORG, ns + + +def _stored(model: str) -> str: + """The `embedder_model` a calibration row for `model` carries when written under the + current embedding settings.""" + c = ec.derive_thresholds([0.7, 0.8, 0.9], [0.4, 0.5, 0.6], [0.1, 0.2], embedder_model=model) + return str(ec.namespace_calibration_row(ORG, "ns", c)["embedder_model"]) + + +class _CH: + """`loom.namespace_calibration_result`: the `embedder_model` each namespace's row stores.""" + + def __init__(self, rows: dict[str, str]) -> None: + self.rows = rows + + async def query_one(self, sql: str, params: dict[str, Any] | None = None) -> Any: + model = self.rows.get(str((params or {})["ns"])) + if model is None: + return None + return { + "embedder_model": model, + **{ + k: 0.5 + for k in ( + "similar_p10 similar_p25 similar_p50 similar_p75 distractor_p50 " + "distractor_p90 noise_floor rerank_skip_above hyde_fallback_threshold " + "query_rewrite_threshold abstain_threshold conflict_threshold " + "duplicate_threshold" + ).split() + }, + "similar_pairs_n": 20, + "distractor_pairs_n": 20, + } + + +class _Repo: + """Namespaces by name: `stubs` still to embed and `embedded` live vectors, both under + the served model; `other_model` names those whose vectors are under another one, and + `stages` the bootstrap stage of a namespace (ready when not named).""" + + def __init__( + self, + state: dict[str, tuple[int, int]], + other_model: set[str] | None = None, + stages: dict[str, str] | None = None, + ) -> None: + self.state = state + self.other_model = other_model or set() + self.stages = stages or {} + + async def pending_embed_chunks( + self, org: str, ns: str, model: str, max_attempts: int, limit: int, **_: Any + ) -> list[dict[str, Any]]: + return [{}] * min(limit, self.state[ns][0]) + + async def has_embedded_chunk(self, org: str, ns: str, model: str) -> bool: + return self.state[ns][1] > 0 and ns not in self.other_model + + async def get_state(self, org: str, ns: str, key: str) -> str: + if key == STAGE_KEY: + return self.stages.get(ns, "ready") + return "abc123" # git_head: the first index is done + + +class _Embedder: + model_name = SERVED + + +class _World: + def __init__(self) -> None: + self.calibrated: list[str] = [] + self.fail = False + self.failing: set[str] = set() + self.cancelled: set[str] = set() + + +@pytest.fixture +def world(monkeypatch: pytest.MonkeyPatch) -> Iterator[_World]: + out = _World() + + async def calibrate(org: str, ns: str) -> None: + out.calibrated.append(ns) + if ns in out.cancelled: + raise asyncio.CancelledError + if out.fail or ns in out.failing: + raise RuntimeError("probe failed") + + async def no_erasure(org: str, ns: str) -> bool: + return False + + async def nobody_off() -> frozenset[str]: + return frozenset() + + monkeypatch.setattr(admin, "calibrate_namespace", calibrate) + monkeypatch.setattr(erasing, "being_erased", no_erasure) + monkeypatch.setattr(customer, "switched_off_orgs", nobody_off) + monkeypatch.setattr(w, "calibration_applies", lambda: True) + monkeypatch.setattr("server.embedding.embedder.get_embedder", lambda: _Embedder()) + ec.clear_ns_overrides() + w.forget_failures() + yield out + ec.clear_ns_overrides() + + +def _namespaces( + monkeypatch: pytest.MonkeyPatch, + state: dict[str, tuple[int, int]], + rows: dict[str, str], + *, + other_model: set[str] | None = None, + stages: dict[str, str] | None = None, +) -> None: + """The configured namespaces (in `state` order), their chunks, their calibration rows.""" + monkeypatch.setattr(repos_mod, "configured_repos", lambda: [_Cfg(n) for n in state]) + monkeypatch.setattr(cr, "CodeRepo", lambda: _Repo(state, other_model, stages)) + monkeypatch.setattr("server.core.ch.get_client", lambda: _CH(rows)) + + +async def _pass() -> w.CodeCalibrationResult: + pass_context.begin("code_calibration") + try: + return await w.run_pass() + finally: + pass_context.clear() + + +async def test_a_drained_namespace_without_a_row_is_calibrated( + world: _World, monkeypatch: pytest.MonkeyPatch +) -> None: + _namespaces(monkeypatch, {"a": (0, 5)}, {}) + result = await _pass() + assert world.calibrated == ["a"] and result.calibrated == f"{ORG}/a" + + +async def test_a_row_under_another_embedder_is_recalibrated( + world: _World, monkeypatch: pytest.MonkeyPatch +) -> None: + _namespaces(monkeypatch, {"a": (0, 5)}, {"a": _stored("m-old")}) + await _pass() + assert world.calibrated == ["a"] + + +async def test_a_namespace_still_embedding_or_empty_is_left_alone( + world: _World, monkeypatch: pytest.MonkeyPatch +) -> None: + _namespaces(monkeypatch, {"a": (3, 5), "b": (0, 0)}, {}) + result = await _pass() + assert world.calibrated == [] and result.calibrated == "" + + +async def test_vectors_only_under_another_embedder_are_not_calibrated( + world: _World, monkeypatch: pytest.MonkeyPatch +) -> None: + """After an embedder change nothing is embedded under the served label yet.""" + _namespaces(monkeypatch, {"a": (0, 5)}, {}, other_model={"a"}) + result = await _pass() + assert world.calibrated == [] and result.calibrated == "" + + +async def test_a_namespace_still_being_built_is_not_calibrated( + world: _World, monkeypatch: pytest.MonkeyPatch +) -> None: + """A first index built in slices has vectors and no stub between two slices.""" + _namespaces(monkeypatch, {"a": (0, 5)}, {}, stages={"a": "indexing"}) + result = await _pass() + assert world.calibrated == [] and result.calibrated == "" + + +async def test_a_row_under_the_served_embedder_is_kept( + world: _World, monkeypatch: pytest.MonkeyPatch +) -> None: + _namespaces(monkeypatch, {"a": (0, 5)}, {"a": _stored(SERVED)}) + await _pass() + assert world.calibrated == [] + + +async def test_one_namespace_is_calibrated_a_pass( + world: _World, monkeypatch: pytest.MonkeyPatch +) -> None: + _namespaces(monkeypatch, {"a": (0, 5), "b": (0, 5)}, {}) + await _pass() + assert world.calibrated == ["a"] + + +async def test_a_failed_calibration_is_recorded_and_ends_the_pass( + world: _World, monkeypatch: pytest.MonkeyPatch +) -> None: + world.fail = True + _namespaces(monkeypatch, {"a": (0, 5), "b": (0, 5)}, {}) + result = await _pass() + assert world.calibrated == ["a"] and len(result.errors) == 1 and result.calibrated == "" + + +async def test_a_namespace_that_keeps_failing_does_not_hold_the_queue( + world: _World, monkeypatch: pytest.MonkeyPatch +) -> None: + world.failing = {"a"} + _namespaces(monkeypatch, {"a": (0, 5), "b": (0, 5)}, {}) + first = await _pass() + second = await _pass() + assert world.calibrated == ["a", "b"] + assert first.calibrated == "" and second.calibrated == f"{ORG}/b" + + +async def test_a_namespace_cancelled_at_the_deadline_does_not_hold_the_queue( + world: _World, monkeypatch: pytest.MonkeyPatch +) -> None: + """The supervisor cancels a pass past its deadline; that pass counts as a failure.""" + world.cancelled = {"a"} + _namespaces(monkeypatch, {"a": (0, 5), "b": (0, 5)}, {}) + with pytest.raises(asyncio.CancelledError): + await _pass() + second = await _pass() + assert world.calibrated == ["a", "b"] and second.calibrated == f"{ORG}/b" + + +async def test_a_fake_embedder_is_not_calibrated_and_logs_nothing( + world: _World, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + monkeypatch.setattr(w, "calibration_applies", lambda: False) + _namespaces(monkeypatch, {"a": (0, 5)}, {}) + result = await _pass() + assert world.calibrated == [] and result.checked == 0 + assert not [r for r in caplog.records if r.levelname == "WARNING"] + + +async def test_a_failed_namespace_is_tried_again_after_the_cooldown( + world: _World, monkeypatch: pytest.MonkeyPatch +) -> None: + from server.settings import settings + + # A non-default interval: the cooldown is three passes of it, not three of 3600 s. + monkeypatch.setattr(settings, "code_calibration_interval_seconds", 7) + assert w.cooldown_seconds() == 21.0 + clock = [1000.0] + monkeypatch.setattr(w, "_now", lambda: clock[0]) + world.failing = {"a"} + _namespaces(monkeypatch, {"a": (0, 5)}, {}) + await _pass() + await _pass() + assert world.calibrated == ["a"] + clock[0] += 20 + await _pass() + assert world.calibrated == ["a"] + clock[0] += 2 + await _pass() + assert world.calibrated == ["a", "a"] + + +def test_the_worker_is_off_unless_enabled(monkeypatch: pytest.MonkeyPatch) -> None: + from server.settings import settings + + def running() -> list[str]: + return [s.name for s in registry.enabled_workers()] + + assert "code_calibration" not in running() + monkeypatch.setattr(settings, "code_calibration_enabled", True) + assert "code_calibration" in running() + + +def test_the_pass_deadline_fits_one_calibration_not_the_default() -> None: + assert registry.pass_deadline_seconds("code_calibration") == w.MAX_PASS_SECONDS + + +async def test_a_memory_row_under_another_embedder_reads_as_missing( + world: _World, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr( + "server.core.ch.get_client", lambda: _CH({"mem": _stored("m-old"), "now": _stored(SERVED)}) + ) + assert await ec.get_namespace_calibration(ORG, "mem") is None + current = await ec.get_namespace_calibration(ORG, "now") + assert current is not None and current.embedder_model == SERVED + + +async def test_a_code_row_under_another_embedder_reads_as_missing_for_the_gates( + world: _World, monkeypatch: pytest.MonkeyPatch +) -> None: + from server.code.app.common import resolve_code_thresholds + + monkeypatch.setattr("server.core.ch.get_client", lambda: _CH({"code-a": _stored("m-old")})) + stale = await resolve_code_thresholds(ORG, "code-a") + monkeypatch.setattr("server.core.ch.get_client", lambda: _CH({"code-a": _stored(SERVED)})) + ec.clear_ns_overrides() + assert await resolve_code_thresholds(ORG, "code-a") != stale + + +def test_a_namespace_row_names_its_embedding_space() -> None: + assert _stored(SERVED) == ec.shared_key(SERVED) != SERVED + + +@pytest.mark.parametrize( + ("field", "value"), + [ + ("embedding_base_url", "https://other-endpoint.example/v1"), + ("embedding_dim", 1024), + ], +) +async def test_a_rebuild_that_keeps_the_model_label_reads_the_row_as_missing( + world: _World, monkeypatch: pytest.MonkeyPatch, field: str, value: Any +) -> None: + """The label stays and the vectors are rebuilt at another endpoint or width: the row + written before describes the old space, so it is missing and the namespace recalibrates.""" + _namespaces(monkeypatch, {"a": (0, 5)}, {"a": _stored(SERVED)}) + assert await ec.get_namespace_calibration(ORG, "a") is not None + await _pass() + assert world.calibrated == [] + ec.clear_ns_overrides() + monkeypatch.setattr(ec.settings, field, value) + assert await ec.get_namespace_calibration(ORG, "a") is None + await _pass() + assert world.calibrated == ["a"] + + +async def test_a_bare_label_row_is_served_and_refreshed( + world: _World, monkeypatch: pytest.MonkeyPatch +) -> None: + """A row the build before the fingerprint wrote holds the bare label: search keeps + serving it, so replicas of both builds read the same thresholds, and a pass probes + the namespace and rewrites the row under the served space's key.""" + _namespaces(monkeypatch, {"a": (0, 5)}, {"a": SERVED}) + row = await ec.get_namespace_calibration(ORG, "a") + assert row is not None and row.embedder_model == SERVED + await _pass() + assert world.calibrated == ["a"] + + +async def test_a_bare_label_row_the_worker_refreshed_reads_as_missing_after_a_width_change( + world: _World, monkeypatch: pytest.MonkeyPatch +) -> None: + """The pass records the space the row was probed in: a later width change under the + same label reads as missing and the next pass calibrates again, so the row can no + longer vouch for a space it was not measured in.""" + rows = {"a": SERVED} + _namespaces(monkeypatch, {"a": (0, 5)}, rows) + + async def calibrate(org: str, ns: str) -> None: + world.calibrated.append(ns) + rows[ns] = _stored(SERVED) # what persist_namespace_calibration writes + + monkeypatch.setattr(admin, "calibrate_namespace", calibrate) + assert await ec.get_namespace_calibration(ORG, "a") is not None + await _pass() + assert world.calibrated == ["a"] and rows == {"a": _stored(SERVED)} + ec.clear_ns_overrides() + monkeypatch.setattr(ec.settings, "embedding_dim", 1024) + assert await ec.get_namespace_calibration(ORG, "a") is None + await _pass() + assert world.calibrated == ["a", "a"] + + +async def test_a_bare_label_row_under_another_label_reads_as_missing( + world: _World, monkeypatch: pytest.MonkeyPatch +) -> None: + _namespaces(monkeypatch, {"a": (0, 5)}, {"a": "m-old"}) + assert await ec.get_namespace_calibration(ORG, "a") is None + await _pass() + assert world.calibrated == ["a"] + + +async def test_a_legacy_row_keeps_its_thresholds_while_the_worker_is_off( + world: _World, monkeypatch: pytest.MonkeyPatch +) -> None: + from server.code.app.common import resolve_code_thresholds + + _namespaces(monkeypatch, {"a": (0, 5)}, {"a": SERVED}) + assert "code_calibration" not in [s.name for s in registry.enabled_workers()] + legacy = await resolve_code_thresholds(ORG, "a") + ec.clear_ns_overrides() + monkeypatch.setattr("server.core.ch.get_client", lambda: _CH({"a": _stored(SERVED)})) + assert await resolve_code_thresholds(ORG, "a") == legacy + ec.clear_ns_overrides() + monkeypatch.setattr("server.core.ch.get_client", lambda: _CH({})) + assert await resolve_code_thresholds(ORG, "a") != legacy diff --git a/tests/unit/test_shared_calibration.py b/tests/unit/test_shared_calibration.py index 5c6e00b9351..1f4f60cfe26 100644 --- a/tests/unit/test_shared_calibration.py +++ b/tests/unit/test_shared_calibration.py @@ -158,9 +158,10 @@ async def test_a_found_namespace_row_expires_so_another_replicas_write_serves( class _CH: async def query_one(self, sql: str, params: Any = None) -> Any: c = answers.pop(0) - return {k: v for k, v in asdict(c).items()} + return {**asdict(c), "embedder_model": ec.shared_key(c.embedder_model)} monkeypatch.setattr("server.core.ch.get_client", lambda: _CH()) + monkeypatch.setattr(ec, "_served_model", lambda: MODEL) # a row in another space is missing monkeypatch.setattr(ec.time, "monotonic", lambda: clock["t"]) ec.clear_ns_overrides() first = await ec.get_namespace_calibration("o", "n")