From 5e771830e3a692a80ddd142ee003405bd72f6017 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Wed, 2 Dec 2026 11:19:14 +0000 Subject: [PATCH 1/6] Calibrate a code namespace after its first embed and after an embedder change `code.calibrate` runs only when an operator calls it, so a code namespace nobody calibrated serves the cluster thresholds. One calibrated under an old embedder kept gating with a row from another cosine scale, because `get_namespace_calibration` read `embedder_model` but never compared it with the served model. A calibration row written under another embedder now reads as missing, and a new worker, `code_calibration`, off by default, calibrates a code namespace that has no row under the served embedder and is drained under it (no stub left to embed, one embedded chunk at least). One predicate covers the first embed and an embedder change, keeps no state, and is safe to repeat on a restart or a second replica. A pass calibrates at most one namespace; a namespace that fails or runs past the pass deadline waits out a cooldown so it does not hold the queue. The handler's body after identity resolution moves into `calibrate_namespace(org, ns)`, which the handler and the worker share. The settings `code_calibration_enabled` (false) and `code_calibration_interval_seconds` (3600) sit next to `recalibration_enabled`. Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Kaloyan Naumov --- docs/reference/configuration.md | 2 + docs/reference/status.md | 3 +- docs/reference/workers.md | 1 + loom.example.yaml | 8 + schemas/loom-settings.schema.json | 10 + server/code/app/admin.py | 13 +- server/code/workers/calibration.py | 123 +++++++++ server/memory/app/embedder_calibration.py | 4 +- server/settings/catalog.py | 5 + server/workers/registry.py | 7 + tests/unit/snapshots/settings_defaults.json | 2 + tests/unit/snapshots/worker_registry.json | 14 ++ tests/unit/test_code_calibration_worker.py | 261 ++++++++++++++++++++ tests/unit/test_shared_calibration.py | 3 + 14 files changed, 451 insertions(+), 5 deletions(-) create mode 100644 server/code/workers/calibration.py create mode 100644 tests/unit/test_code_calibration_worker.py diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index 199cb5be7e9..30276872c8f 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -1193,6 +1193,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 e80a6c2f7b4..cb6eea93e59 100644 --- a/loom.example.yaml +++ b/loom.example.yaml @@ -3571,6 +3571,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 e86a55dcbb1..11b585252d5 100644 --- a/schemas/loom-settings.schema.json +++ b/schemas/loom-settings.schema.json @@ -808,6 +808,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/workers/calibration.py b/server/code/workers/calibration.py new file mode 100644 index 00000000000..626eb52baec --- /dev/null +++ b/server/code/workers/calibration.py @@ -0,0 +1,123 @@ +"""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 one calibrated under an old +embedder keeps a row `get_namespace_calibration` now reads as missing. A pass +calibrates the first configured namespace that has no calibration row under the +served embedder and is drained under it (no stub left to embed, one live chunk at +least), and only one, so the cost stays bounded per pass. 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 +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, org: str, ns: str, model: str) -> bool: + """Whether the namespace has no calibration under `model` and is drained under it: + no live stub left to embed (as `code_embed_recovery` reads it) and one embedded chunk + at least. A namespace still embedding, or empty, waits for a later pass.""" + if await get_namespace_calibration(org, ns) is not None: + return False + if await repo.pending_embed_chunks(org, ns, model, settings.code_embed_max_attempts, 1): + return False + _, embedded = await repo.chunk_embed_coverage(org, ns) + return int(embedded) > 0 + + +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, org, ns, 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..0eae9aa4c5c 100644 --- a/server/memory/app/embedder_calibration.py +++ b/server/memory/app/embedder_calibration.py @@ -715,7 +715,9 @@ 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 embedder describes another cosine scale: it reads as + # missing, so the cluster calibration serves until the namespace is recalibrated. + if row is None or str(row["embedder_model"]) != _served_model(): _ns_overrides[key] = None _ns_negative_at[key] = time.monotonic() return None diff --git a/server/settings/catalog.py b/server/settings/catalog.py index 89514370106..03debe4adca 100644 --- a/server/settings/catalog.py +++ b/server/settings/catalog.py @@ -3013,6 +3013,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 c902558a30c..951ddd8f3a9 100644 --- a/tests/unit/snapshots/settings_defaults.json +++ b/tests/unit/snapshots/settings_defaults.json @@ -132,6 +132,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..17ce32ea26d --- /dev/null +++ b/tests/unit/test_code_calibration_worker.py @@ -0,0 +1,261 @@ +"""`code_calibration` calibrates a code namespace once it is embedded and has no +calibration row under the served embedder, one namespace a pass; and a row written +under another embedder reads as missing.""" + +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.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: + def __init__(self, ns: str) -> None: + self.org, self.namespace = ORG, ns + + +class _CH: + """`loom.namespace_calibration_result`: the embedder each namespace's row names.""" + + 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, `embedded` live vectors.""" + + def __init__(self, state: dict[str, tuple[int, int]]) -> None: + self.state = state + + 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 chunk_embed_coverage(self, org: str, ns: str) -> tuple[int, int]: + return self.state[ns][1], self.state[ns][1] + + +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], +) -> 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)) + 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": "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_a_row_under_the_served_embedder_is_kept( + world: _World, monkeypatch: pytest.MonkeyPatch +) -> None: + _namespaces(monkeypatch, {"a": (0, 5)}, {"a": 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: + 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] += w.cooldown_seconds() + 1 + 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": "m-old", "now": 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": "m-old"})) + stale = await resolve_code_thresholds(ORG, "code-a") + monkeypatch.setattr("server.core.ch.get_client", lambda: _CH({"code-a": SERVED})) + ec.clear_ns_overrides() + assert await resolve_code_thresholds(ORG, "code-a") != stale diff --git a/tests/unit/test_shared_calibration.py b/tests/unit/test_shared_calibration.py index 5c6e00b9351..644e134072a 100644 --- a/tests/unit/test_shared_calibration.py +++ b/tests/unit/test_shared_calibration.py @@ -161,6 +161,9 @@ async def query_one(self, sql: str, params: Any = None) -> Any: return {k: v for k, v in asdict(c).items()} monkeypatch.setattr("server.core.ch.get_client", lambda: _CH()) + monkeypatch.setattr( + ec, "_served_model", lambda: MODEL + ) # a row under another embedder is missing monkeypatch.setattr(ec.time, "monotonic", lambda: clock["t"]) ec.clear_ns_overrides() first = await ec.get_namespace_calibration("o", "n") From 15df0d6364e5c67b6dba89b76c1b3a96e5aea271 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Wed, 2 Dec 2026 11:32:46 +0000 Subject: [PATCH 2/6] Calibrate only a namespace that has finished embedding under the served model The calibration worker called a namespace drained when no stub was left under the served model and any chunk, under any model, carried a vector. After an embedder change the old model's vectors satisfied that while nothing was embedded under the new one yet, and a first index built in slices has vectors and no stub between two slices. Either way the namespace was calibrated on a partial or mislabelled corpus, and the worker never looked at it again. The worker now skips a namespace that still awaits its first index or is in a building stage, and asks whether one live chunk carries a vector under the served model, read in the table that model's rows live in (CodeRepo.has_embedded_chunk, a LIMIT 1 read). Two tests cover vectors only under another model and a namespace in a building stage. The module docstring now describes the predicate without narrating the change. Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Kaloyan Naumov --- server/code/store/index/status.py | 16 +++++++ server/code/workers/calibration.py | 40 ++++++++++------- tests/unit/test_code_calibration_worker.py | 50 +++++++++++++++++++--- 3 files changed, 85 insertions(+), 21 deletions(-) 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 index 626eb52baec..4ea95caf55f 100644 --- a/server/code/workers/calibration.py +++ b/server/code/workers/calibration.py @@ -2,14 +2,14 @@ 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 one calibrated under an old -embedder keeps a row `get_namespace_calibration` now reads as missing. A pass -calibrates the first configured namespace that has no calibration row under the -served embedder and is drained under it (no stub left to embed, one live chunk at -least), and only one, so the cost stays bounded per pass. 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 +was called serves the cluster's thresholds, and a row written under another +embedder reads as missing. A pass calibrates the first configured namespace that +has no row under the served embedder 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. """ @@ -61,16 +61,26 @@ class CodeCalibrationResult: errors: list[str] = field(default_factory=list) -async def needs_calibration(repo: Any, org: str, ns: str, model: str) -> bool: - """Whether the namespace has no calibration under `model` and is drained under it: - no live stub left to embed (as `code_embed_recovery` reads it) and one embedded chunk - at least. A namespace still embedding, or empty, waits for a later pass.""" +async def needs_calibration(repo: Any, cfg: Any, model: str) -> bool: + """Whether the namespace has no calibration under `model` 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.""" + 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(org, ns) is not None: 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 - _, embedded = await repo.chunk_embed_coverage(org, ns) - return int(embedded) > 0 + return bool(await repo.has_embedded_chunk(org, ns, model)) async def run_pass() -> CodeCalibrationResult: @@ -107,7 +117,7 @@ async def _run(result: CodeCalibrationResult) -> None: continue result.checked += 1 try: - if not await needs_calibration(repo, org, ns, model): + if not await needs_calibration(repo, cfg, model): continue set_worker_identity("code_calibration", org=org, namespace=ns) _failed[(org, ns)] = _now() diff --git a/tests/unit/test_code_calibration_worker.py b/tests/unit/test_code_calibration_worker.py index 17ce32ea26d..abe6aacdd5a 100644 --- a/tests/unit/test_code_calibration_worker.py +++ b/tests/unit/test_code_calibration_worker.py @@ -13,6 +13,7 @@ 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 @@ -24,6 +25,8 @@ class _Cfg: + source = "config" + def __init__(self, ns: str) -> None: self.org, self.namespace = ORG, ns @@ -55,18 +58,32 @@ async def query_one(self, sql: str, params: dict[str, Any] | None = None) -> Any class _Repo: - """Namespaces by name: `stubs` still to embed, `embedded` live vectors.""" - - def __init__(self, state: dict[str, tuple[int, int]]) -> None: + """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 chunk_embed_coverage(self, org: str, ns: str) -> tuple[int, int]: - return self.state[ns][1], self.state[ns][1] + 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: @@ -113,10 +130,13 @@ 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)) + monkeypatch.setattr(cr, "CodeRepo", lambda: _Repo(state, other_model, stages)) monkeypatch.setattr("server.core.ch.get_client", lambda: _CH(rows)) @@ -152,6 +172,24 @@ async def test_a_namespace_still_embedding_or_empty_is_left_alone( 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: From 516288f07695d65b272827c6d4798cb24fa09c30 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Wed, 2 Dec 2026 12:48:00 +0000 Subject: [PATCH 3/6] Key a namespace calibration row by its embedding space A namespace calibration row carried only the model label, so a row written before a rebuild at another endpoint, provider or width, under the same label, still read as current. get_namespace_calibration accepted it and needs_calibration skipped the namespace, which kept serving thresholds from the old vector space. The row's embedder_model now holds shared_key(model), the model and its embedding space's fingerprint, the key the shared calibration is stored under, and the read compares it with the key of the served model. A row whose key differs, including one that holds a bare label, reads as missing, so the cluster calibration serves and the worker recalibrates the namespace once. No column changes, and a replica running the previous build serves the row as before. Tests cover a rebuild that retains the label at another endpoint and at another width, a row that holds a bare label, and the written key. Assisted-by: Claude Code:claude-sonnet-5-5 Signed-off-by: Kaloyan Naumov --- server/memory/app/embedder_calibration.py | 24 +++++---- tests/unit/test_code_calibration_worker.py | 61 +++++++++++++++++++--- tests/unit/test_shared_calibration.py | 6 +-- 3 files changed, 70 insertions(+), 21 deletions(-) diff --git a/server/memory/app/embedder_calibration.py b/server/memory/app/embedder_calibration.py index 0eae9aa4c5c..2834b3cb117 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, @@ -715,9 +716,12 @@ async def get_namespace_calibration(org: str, namespace: str) -> CalibrationResu _ns_negative_at[key] = time.monotonic() return None - # A row written under another embedder describes another cosine scale: it reads as - # missing, so the cluster calibration serves until the namespace is recalibrated. - if row is None or str(row["embedder_model"]) != _served_model(): + # 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. A row that + # holds a bare model label names no space, so it reads as missing too. + served = _served_model() + if row is None or str(row["embedder_model"]) != shared_key(served): _ns_overrides[key] = None _ns_negative_at[key] = time.monotonic() return None @@ -738,7 +742,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/tests/unit/test_code_calibration_worker.py b/tests/unit/test_code_calibration_worker.py index abe6aacdd5a..87c249a7560 100644 --- a/tests/unit/test_code_calibration_worker.py +++ b/tests/unit/test_code_calibration_worker.py @@ -1,6 +1,7 @@ """`code_calibration` calibrates a code namespace once it is embedded and has no calibration row under the served embedder, one namespace a pass; and a row written -under another embedder reads as missing.""" +under another embedding space (another model, or the same label at another endpoint or +width) reads as missing.""" from __future__ import annotations @@ -31,8 +32,15 @@ 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 each namespace's row names.""" + """`loom.namespace_calibration_result`: the `embedder_model` each namespace's row stores.""" def __init__(self, rows: dict[str, str]) -> None: self.rows = rows @@ -159,7 +167,7 @@ async def test_a_drained_namespace_without_a_row_is_calibrated( async def test_a_row_under_another_embedder_is_recalibrated( world: _World, monkeypatch: pytest.MonkeyPatch ) -> None: - _namespaces(monkeypatch, {"a": (0, 5)}, {"a": "m-old"}) + _namespaces(monkeypatch, {"a": (0, 5)}, {"a": _stored("m-old")}) await _pass() assert world.calibrated == ["a"] @@ -193,7 +201,7 @@ async def test_a_namespace_still_being_built_is_not_calibrated( async def test_a_row_under_the_served_embedder_is_kept( world: _World, monkeypatch: pytest.MonkeyPatch ) -> None: - _namespaces(monkeypatch, {"a": (0, 5)}, {"a": SERVED}) + _namespaces(monkeypatch, {"a": (0, 5)}, {"a": _stored(SERVED)}) await _pass() assert world.calibrated == [] @@ -281,7 +289,9 @@ def test_the_pass_deadline_fits_one_calibration_not_the_default() -> None: 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": "m-old", "now": SERVED})) + 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 @@ -292,8 +302,45 @@ async def test_a_code_row_under_another_embedder_reads_as_missing_for_the_gates( ) -> None: from server.code.app.common import resolve_code_thresholds - monkeypatch.setattr("server.core.ch.get_client", lambda: _CH({"code-a": "m-old"})) + 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": SERVED})) + 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_row_written_before_the_space_joined_the_key_reads_as_missing( + world: _World, monkeypatch: pytest.MonkeyPatch +) -> None: + """A row that holds the bare model label does not name its space: it is recalibrated once.""" + _namespaces(monkeypatch, {"a": (0, 5)}, {"a": SERVED}) + assert await ec.get_namespace_calibration(ORG, "a") is None + await _pass() + assert world.calibrated == ["a"] diff --git a/tests/unit/test_shared_calibration.py b/tests/unit/test_shared_calibration.py index 644e134072a..1f4f60cfe26 100644 --- a/tests/unit/test_shared_calibration.py +++ b/tests/unit/test_shared_calibration.py @@ -158,12 +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 under another embedder is missing + 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") From 0232f3b0c5592aa108ad314a23687d71a36accc5 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Wed, 2 Dec 2026 12:54:32 +0000 Subject: [PATCH 4/6] test: pin the calibration cooldown to code_calibration_interval_seconds The cooldown test ran at the default interval, so no test named the setting and the test inventory flagged it. Set an interval of 7 s and assert the cooldown is three passes of it: a failed namespace is still skipped 20 s later and tried again after 22 s. Assisted-by: Claude Code:claude-sonnet-5-5 Signed-off-by: Kaloyan Naumov --- tests/unit/test_code_calibration_worker.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/tests/unit/test_code_calibration_worker.py b/tests/unit/test_code_calibration_worker.py index 87c249a7560..0569946e52b 100644 --- a/tests/unit/test_code_calibration_worker.py +++ b/tests/unit/test_code_calibration_worker.py @@ -259,6 +259,11 @@ async def test_a_fake_embedder_is_not_calibrated_and_logs_nothing( 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"} @@ -266,7 +271,10 @@ async def test_a_failed_namespace_is_tried_again_after_the_cooldown( await _pass() await _pass() assert world.calibrated == ["a"] - clock[0] += w.cooldown_seconds() + 1 + clock[0] += 20 + await _pass() + assert world.calibrated == ["a"] + clock[0] += 2 await _pass() assert world.calibrated == ["a", "a"] From 5cf6df82e34e0c2312c987e564b3dca649b64a7e Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Wed, 2 Dec 2026 13:16:18 +0000 Subject: [PATCH 5/6] Keep the thresholds of a namespace row written before the fingerprint The previous build stored the bare model label in a namespace calibration row. Comparing every row by `shared_key` read those rows as missing, so a deployment that kept the same embedding space lost its thresholds on upgrade, and with the worker off nothing wrote them back. A replica of the previous build kept serving them, so replicas disagreed during the rollout. A bare label that equals the served label is now accepted as the served space. A fingerprinted value is compared by `shared_key` as before, and a bare label of another model still reads as missing. New writes store the fingerprinted key. The limit: a bare-label row written before an endpoint or width change under the same label is not detected until the namespace is calibrated once, by `code.calibrate` or by the worker when it is enabled. Assisted-by: Claude Code:claude-sonnet-5-5 Signed-off-by: Kaloyan Naumov --- server/memory/app/embedder_calibration.py | 18 ++++++++++-- tests/unit/test_code_calibration_worker.py | 34 ++++++++++++++++++++-- 2 files changed, 46 insertions(+), 6 deletions(-) diff --git a/server/memory/app/embedder_calibration.py b/server/memory/app/embedder_calibration.py index 2834b3cb117..4f7715b31d6 100644 --- a/server/memory/app/embedder_calibration.py +++ b/server/memory/app/embedder_calibration.py @@ -667,6 +667,19 @@ 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(org: str, namespace: str) -> CalibrationResult | None: """Per-namespace calibration override from `loom.namespace_calibration_result`, else None (caller falls through @@ -718,10 +731,9 @@ async def get_namespace_calibration(org: str, namespace: str) -> CalibrationResu # 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. A row that - # holds a bare model label names no space, so it reads as missing too. + # the cluster calibration serves until the namespace is recalibrated. served = _served_model() - if row is None or str(row["embedder_model"]) != shared_key(served): + 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 diff --git a/tests/unit/test_code_calibration_worker.py b/tests/unit/test_code_calibration_worker.py index 0569946e52b..5171bc8ead4 100644 --- a/tests/unit/test_code_calibration_worker.py +++ b/tests/unit/test_code_calibration_worker.py @@ -1,7 +1,8 @@ """`code_calibration` calibrates a code namespace once it is embedded and has no calibration row under the served embedder, 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.""" +width) reads as missing; a row that holds a bare label, written before the fingerprint, +keeps serving while the label is the served one.""" from __future__ import annotations @@ -344,11 +345,38 @@ async def test_a_rebuild_that_keeps_the_model_label_reads_the_row_as_missing( assert world.calibrated == ["a"] -async def test_a_row_written_before_the_space_joined_the_key_reads_as_missing( +async def test_a_bare_label_row_under_the_served_label_is_served( world: _World, monkeypatch: pytest.MonkeyPatch ) -> None: - """A row that holds the bare model label does not name its space: it is recalibrated once.""" + """A row the build before the fingerprint wrote holds the bare label: while that is the + served label it keeps serving, so replicas of both builds read the same thresholds.""" _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 == [] + + +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 From cc5e3e4d79f707c7a317c9a28d71fe351d9c8838 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Thu, 3 Dec 2026 07:23:43 +0000 Subject: [PATCH 6/6] Refresh a bare-label calibration row from the worker A namespace calibration row written before the fingerprint holds the bare embedder label, which the reader accepts: search keeps serving it during a rollout. `needs_calibration` read the row the same way, so no pass selected that namespace, and an endpoint or width change under the same label kept serving thresholds measured in the old space. The worker now asks whether the row names the served space's key, through `get_namespace_calibration_stored_key`. A bare label is probed and the row rewritten under `shared_key`. `get_namespace_calibration` and `_row_names_served_space` are unchanged, so replicas of the previous build and this one still serve the same thresholds. `test_a_bare_label_row_is_served_and_refreshed` pins the refresh, `test_a_bare_label_row_the_worker_refreshed_reads_as_missing_after_a_width_change` pins the recorded space, and `test_a_legacy_row_keeps_its_thresholds_while_the_worker_is_off` pins the read that must not change. Signed-off-by: Kaloyan Naumov --- server/code/workers/calibration.py | 31 ++++++++++------ server/memory/app/embedder_calibration.py | 26 ++++++++++++++ tests/unit/test_code_calibration_worker.py | 41 +++++++++++++++++----- 3 files changed, 79 insertions(+), 19 deletions(-) diff --git a/server/code/workers/calibration.py b/server/code/workers/calibration.py index 4ea95caf55f..543c7b9a0df 100644 --- a/server/code/workers/calibration.py +++ b/server/code/workers/calibration.py @@ -3,10 +3,13 @@ `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 pass calibrates the first configured namespace that -has no row under the served embedder 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. +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 @@ -24,7 +27,11 @@ 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 +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 @@ -62,16 +69,18 @@ class CodeCalibrationResult: async def needs_calibration(repo: Any, cfg: Any, model: str) -> bool: - """Whether the namespace has no calibration under `model` 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.""" + """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(org, ns) is not None: + 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): diff --git a/server/memory/app/embedder_calibration.py b/server/memory/app/embedder_calibration.py index 4f7715b31d6..32a01176125 100644 --- a/server/memory/app/embedder_calibration.py +++ b/server/memory/app/embedder_calibration.py @@ -680,6 +680,32 @@ def _row_names_served_space(stored: str, served: str) -> bool: 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 diff --git a/tests/unit/test_code_calibration_worker.py b/tests/unit/test_code_calibration_worker.py index 5171bc8ead4..4bcd1ee56a9 100644 --- a/tests/unit/test_code_calibration_worker.py +++ b/tests/unit/test_code_calibration_worker.py @@ -1,8 +1,8 @@ """`code_calibration` calibrates a code namespace once it is embedded and has no -calibration row under the served embedder, 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 while the label is the served one.""" +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 @@ -345,16 +345,41 @@ async def test_a_rebuild_that_keeps_the_model_label_reads_the_row_as_missing( assert world.calibrated == ["a"] -async def test_a_bare_label_row_under_the_served_label_is_served( +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: while that is the - served label it keeps serving, so replicas of both builds read the same thresholds.""" + """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 == [] + 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(