Repository navigation
Calibrate a code namespace after its first embed and after an embedder change #2022
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
zlareb1
merged 7 commits into
ClickHouse:main
from
KaloyanNaumov:pr/code-calibrate-on-embed
Dec 3, 2026
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
5e77183
Calibrate a code namespace after its first embed and after an embedde…
KaloyanNaumov 15df0d6
Calibrate only a namespace that has finished embedding under the serv…
KaloyanNaumov 516288f
Key a namespace calibration row by its embedding space
KaloyanNaumov 0232f3b
test: pin the calibration cooldown to code_calibration_interval_seconds
KaloyanNaumov 5cf6df8
Keep the thresholds of a namespace row written before the fingerprint
KaloyanNaumov 90c77cf
Merge remote-tracking branch 'origin/main' into wip/code-calibrate-on…
KaloyanNaumov cc5e3e4
Refresh a bare-label calibration row from the worker
KaloyanNaumov File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.