Skip to content
2 changes: 2 additions & 0 deletions docs/reference/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |
Expand Down
3 changes: 2 additions & 1 deletion docs/reference/status.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,13 +89,14 @@ default is `off`) are not listed here.
<!-- Generated by `python scripts/codegen/docs_reference.py`; edit the source, not this region. -->
<!-- prettier-ignore-start -->

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:<shape12> <first 200 chars>` of each statement to its `log_comment` ("<op> <request_id>"), 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). |
Expand Down
1 change: 1 addition & 0 deletions docs/reference/workers.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
8 changes: 8 additions & 0 deletions loom.example.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
10 changes: 10 additions & 0 deletions schemas/loom-settings.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
13 changes: 10 additions & 3 deletions server/code/app/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]] = []
Expand Down
16 changes: 16 additions & 0 deletions server/code/store/index/status.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__)

Expand Down Expand Up @@ -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
142 changes: 142 additions & 0 deletions server/code/workers/calibration.py
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
60 changes: 52 additions & 8 deletions server/memory/app/embedder_calibration.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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)
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved


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
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down
5 changes: 5 additions & 0 deletions server/settings/catalog.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Comment thread
zlareb1 marked this conversation as resolved.
Resolved

# Seconds between the entity extractor's mirror divergence heal, a
# FINAL-to-FINAL join of loom.memory and loom.memory_embeddings (343 GB/day
Expand Down
Loading
Loading