diff --git a/docs/architecture/llm-architecture.md b/docs/architecture/llm-architecture.md index 8734b3e0c81..aea8448c068 100644 --- a/docs/architecture/llm-architecture.md +++ b/docs/architecture/llm-architecture.md @@ -176,8 +176,13 @@ With `LOOM_ADAPTIVE_THRESHOLDS` on (the default), `calibrate_embedder` in corpora (paraphrase pairs, question-to-fact pairs, distractor pairs) and reads their cosine distributions (`derive_thresholds`). Memory paraphrases use document/document vectors; question/fact and distractor pairs use query/document vectors. `code.calibrate` -explicitly uses query/document vectors for its authored query/code positives in both -positive distributions, including the persisted conflict and duplicate gates: +explicitly uses query/document vectors for its query/code positives in both positive +distributions, including the persisted conflict and duplicate gates. Its probes come from +the namespace's documented functions (the doc comment's first paragraph as the query, the +function without it as the positive, a function in another language or another +directory two levels deep as the distractor, or another file when every function shares +one language and directory), or from a fixed corpus for a namespace that yields fewer +than 20 such probes: | Threshold | Derived as | | ------------- | ------------------------------------------ | @@ -189,6 +194,15 @@ positive distributions, including the persisted conflict and duplicate gates: | conflict | paraphrase p50 | | duplicate | paraphrase p75 | +`code.calibrate` caps abstain at the 10th percentile of the query-to-function cosines +it measured on its probe pairs (up to `LOOM_CODE_CALIBRATE_PROBES`, 200 by default, or +the fixed corpus) and keeps the noise floor 0.05 under it; the trigger gates are then +clamped to that floor. When the distractors' 90th percentile reaches the pairs' 75th, +no cosine separates a right function from an unrelated one, so the cap is skipped and +the calibration has no confidence scale. The 10th-percentile cap describes the probe +pairs, not the namespace: it places no bound on how often search abstains for a function the +sample did not draw, or for a query whose correct hit never enters the candidate set. + Each search resolves thresholds in three tiers: 1. a per-namespace calibration (`loom.namespace_calibration_result`, written by @@ -213,9 +227,9 @@ Each search resolves thresholds in three tiers: - With adaptivity off and a real embedder other than `text-embedding-3-small` (the model the scalar gates were tuned for), boot logs a warning. You own re-benching. - The `recalibration` worker (weekly, `LOOM_RECALIBRATION_ENABLED`, on the leader) - re-runs the probe, publishes the result as the cluster calibration, - warns on a drift of 0.05 or more, and re-probes namespace corpora with at least 5 - similar and 3 distractor pairs. + re-runs the probe, publishes the result as the cluster calibration and warns on a + drift of 0.05 or more. Per-namespace calibrations come only from `code.calibrate`, + which the `code_calibration` worker also runs (`LOOM_CODE_CALIBRATION_ENABLED`). **Why.** Deriving thresholds from the model's own distribution makes an embedder swap a configuration change. The cost: thresholds are statistical. A namespace corpus whose diff --git a/docs/benchmarks/running.md b/docs/benchmarks/running.md index 2830ca5c393..88b86832332 100644 --- a/docs/benchmarks/running.md +++ b/docs/benchmarks/running.md @@ -515,7 +515,7 @@ skips paths with a `datasets` segment. | `bench/fixtures/code_intel_mined_issue_ka.jsonl` | 14 rows | `code_intel_qa.py` | The keyword-agnostic slice (`code_intel_ka_slice.py`) | | `bench/fixtures/code_intel_history.jsonl` | 105 rows | `code_intel_qa.py` | "What fixed issue N" questions mined from merged PRs | | `bench/fixtures/code_intel_oss.jsonl` | 304 rows | `code_intel_qa.py` | An MIT-licensed third-party code-search corpus at a pinned revision; model-authored gold | -| `bench/fixtures/code_calibration_probes.jsonl` | 20 query / positive pairs | code calibration (`server/code/app/admin.py`) | Over the ClickHouse repository | +| `bench/fixtures/code_calibration_probes.jsonl` | 20 query / positive pairs | code calibration fallback (`server/code/app/admin.py`) | Over the ClickHouse repository | | `bench/fixtures/code_plane_ablation/` | 2 tasks, arm A and arm C transcripts | `code_plane_ablation.py selftest`, `acceptance/plugin.py` | Synthetic transcripts that prove the scorer | | `bench/acceptance/fixtures/shunt_decisions.json` | 12 cases | `acceptance/plugin.py` | Read / Grep decisions the plugin's code shunt must make | | `bench/code_ask_cache_threshold/pairs.json` | 42 paraphrase, 43 different, 22 different-identifier pairs | `code_ask_cache_threshold/measure.py` | Written from a live `code.ask` cache's questions ([results](./results.md#codeask-answer-cache-threshold)) | diff --git a/docs/operations/code-index-operations.md b/docs/operations/code-index-operations.md index fb5f49aa400..629ef3f9ad1 100644 --- a/docs/operations/code-index-operations.md +++ b/docs/operations/code-index-operations.md @@ -397,15 +397,29 @@ docker exec loom-workers loom code backfill-prs --namespace code-myrepo --org ac Then: - `POST /v1/code.calibrate` (`ADMIN`) derives the code index's abstention thresholds, and - the confident-hit cosine at which `retrieval_confidence` reads 1.0, from - `bench/fixtures/code_calibration_probes.jsonl` (shipped in the image). Run it for - every code namespace, and again after a change of embedding model. A namespace - without its own calibration (`calibration.get` reads `source: cluster`) reads code - on the embedder's boot calibration, which is derived from prose. On an embedding - model that scores a right code hit lower than a right prose answer, answerable - searches then read `medium` or `high`, and with `LOOM_PROMPT_PACK_MIN_CONF` unset the - coding-agent plugins send one search pointer there, the first pick, only for a bug - report whose answer the pick model words `high` or `medium` + the confident-hit cosine at which `retrieval_confidence` reads 1.0, from the + namespace's own code. It samples up to `LOOM_CODE_CALIBRATE_PROBES` (200) documented + functions across the namespace's languages and directories. Each probe embeds the first + paragraph of the function's doc comment as the query against the function without that + comment, and against a function in another language or another directory two levels + deep (another file when every function shares one language and directory). A + namespace that yields fewer than 20 probes with both a usable query and a distractor + is calibrated on `bench/fixtures/code_calibration_probes.jsonl` (shipped in the image) + instead; `probe_source` in the reply says which. The abstain threshold is capped at the + probes' 10th-percentile query-to-function cosine: functions of one repository share + its vocabulary, so an unrelated one, read as indexed with its doc comment, scores + close to the right one read without it, and the distractor percentile alone would + abstain on many right answers. The cap is skipped when the distractors' 90th + percentile reaches the probes' 75th. The 10th-percentile cap is over the probe pairs + and does not bound abstention for unsampled functions or a query whose correct hit + never enters the candidate set. Run it for every code namespace, and again + after a change of embedding model. A namespace without its own calibration + (`calibration.get` reads `source: cluster`) reads code on the embedder's boot + calibration, which is derived from prose. On an embedding model that scores a right + code hit lower than a right prose answer, answerable searches then read `medium` or + `high`, and with `LOOM_PROMPT_PACK_MIN_CONF` unset the coding-agent plugins send one + search pointer there, the first pick, only for a bug report whose answer the pick + model words `high` or `medium` ([the pick](../features/integrations/claude-code.md#model-picked-pointers-for-a-bug-report)). - `loom code describe --top-pct 20` (optional, LLM cost) writes one-line descriptions for the most central chunks. `--limit N` starts at most N description calls. `--max-usd D` diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index f527e35256a..2ab58a99e74 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -711,6 +711,7 @@ The code index's network git (clone, fetch, ls-remote, submodule update) through | `LOOM_CODE_SEARCH_RRF_LEXICAL_WEIGHT_RESPONSIBILITY` | `float` | `1.0` | | Lexical list's RRF weight for a responsibility question (vector = 1.0). 1.0 = equal weights. | | `LOOM_CODE_SEARCH_ABSTAIN_CARD_BELOW` | `float` | `0.0` | | A prose question whose nearest file card's cosine is below this abstains `off_domain`; independent of the card leg. 0 = off. | | `LOOM_CODE_SEARCH_ABSTAIN_CONFIDENCE_BELOW` | `float` | `0.35` | | The abstain score below which a code.search result is flagged `low_calibrated_confidence` (still returned). The score is not `retrieval_confidence`: it blends the top cosine, its margin over the second hit, route agreement and the pool size. The deployment sets 0.30. | +| `LOOM_CODE_CALIBRATE_PROBES` | `int` | `200` | | Probes `code.calibrate` samples from a namespace's documented functions, three embeddings each (four uncached) and no LLM call; under 20 usable probes it uses the fixed corpus. | | `LOOM_CODE_SEARCH_MEDIUM_RISK_FROM` | `float` | `0.35` | | The `retrieval_confidence` from which a code.search result reads `retrieval_risk` "medium"; below it the result reads "high". In the measurement behind the default about half of the prompts sent to another repository's index scored under it. | | `LOOM_CODE_SEARCH_LOW_RISK_FROM` | `float` | `0.7` | | The `retrieval_confidence` from which a code.search result reads `retrieval_risk` "low": the best cosine is close to that of a confident hit. A prompt about other code usually scores lower, but about one in five sent to another repository's index still read low. With `LOOM_PROMPT_PACK_MIN_CONF` unset the coding-agent plugins send their prompt pointers from it and, for a bug report, below it the first pick of an answer the pick model words `high` or `medium`. | | `LOOM_CODE_SEARCH_HYDE_KINDS` | `str` | `'responsibility'` | | The question kinds the hypothetical answer votes on. | diff --git a/docs/reference/operations.md b/docs/reference/operations.md index cca532898b4..1f267ef5f72 100644 --- a/docs/reference/operations.md +++ b/docs/reference/operations.md @@ -192,7 +192,7 @@ Fields for every `code` op: [operations/code.md](operations/code.md). | [`code.backport_gaps`](operations/code.md#codebackport_gaps) | The set-wide backport report: which merged fixes labelled for backport does a release branch still owe? | viewer | read | no | | | [`code.bisect_candidates`](operations/code.md#codebisect_candidates) | Rank PRs that may have introduced a bug; Loom does not test or reproduce it. | viewer | read | no | | | [`code.blame_range`](operations/code.md#codeblame_range) | Which merged PRs last touched these lines, between release A and B? | viewer | read | no | | -| [`code.calibrate`](operations/code.md#codecalibrate) | Derive this namespace's calibration from the authored probe corpus and persist it: the code-specific abstention thresholds and the confident-hit cosine at the top of the `retrieval_confidence` scale. | admin | write | no | yes | +| [`code.calibrate`](operations/code.md#codecalibrate) | Derive this namespace's calibration and persist it: the code-specific abstention thresholds and the confident-hit cosine at the top of the `retrieval_confidence` scale. | admin | write | no | yes | | [`code.callees`](operations/code.md#codecallees) | What does this symbol call — forward call edges (depth<=3), tier-marked like code.callers. | viewer | read | no | | | [`code.callers`](operations/code.md#codecallers) | Find callers before editing shared code. | viewer | read | yes | | | [`code.context_pack`](operations/code.md#codecontext_pack) | Briefing at the START of a task, instead of exploring file by file. | viewer | read | yes | | diff --git a/docs/reference/operations/calibration.md b/docs/reference/operations/calibration.md index 28fbc9737c4..bdfd9aa2737 100644 --- a/docs/reference/operations/calibration.md +++ b/docs/reference/operations/calibration.md @@ -23,11 +23,11 @@ Resolve the active calibration for (org, namespace): per-namespace, then cluster | --- | --- | --- | | `source` | `str` | "namespace" / "cluster" / "scalar" | | `embedder_model` | `str` | The embedder the thresholds were derived for; with `scalar`, the configured model. | -| `noise_floor` | `float` | Cosine below which a search hit is dropped as noise (distractor P90 + 0.02 when probed). | +| `noise_floor` | `float` | Cosine below which a search hit is dropped as noise (distractor P90 + 0.02 when probed; for a code namespace, 0.05 under an abstain threshold capped at question-to-fact P10). | | `rerank_skip_above` | `float` | Top-hit cosine at or above which the LLM rerank is skipped (question-to-fact P75, never below `hyde_fallback_threshold`). | | `hyde_fallback_threshold` | `float` | The question-to-fact P25 gate, never below `query_rewrite_threshold`; `loom_search` reads it as its precision floor. | | `query_rewrite_threshold` | `float` | The question-to-fact P10 gate, held at least 0.01 above `noise_floor`. | -| `abstain_threshold` | `float` | Top-hit cosine below which a search abstains (`noise_floor` + 0.05 when probed). | +| `abstain_threshold` | `float` | Top-hit cosine below which a search abstains (`noise_floor` + 0.05 when probed; for a code namespace, at most question-to-fact P10 unless distractor P90 reaches its P75). | | `conflict_threshold` | `float` | Cosine at or above which a write against an active peer is flagged `conflicted` (paraphrase P50 when probed). | | `duplicate_threshold` | `float` | Cosine at or above which a write with a canonical-form mismatch is marked `duplicate` (paraphrase P75 when probed). | | `similar_p10` | `float` | Probe percentiles; default 0.0 when source is 'scalar' (no probe ran). | @@ -35,7 +35,7 @@ Resolve the active calibration for (org, namespace): per-namespace, then cluster | `similar_p50` | `float` | Median cosine of the paraphrase pairs. | | `similar_p75` | `float` | 75th percentile cosine of the paraphrase pairs. | | `distractor_p50` | `float` | Median cosine of the unrelated (distractor) pairs. | -| `distractor_p90` | `float` | 90th percentile cosine of the distractor pairs, the anchor of `noise_floor`. | +| `distractor_p90` | `float` | 90th percentile cosine of the distractor pairs, the anchor of `noise_floor` unless a code namespace's abstain cap moved it. | | `similar_pairs_n` | `int` | Paraphrase pairs the probe embedded; 0 when `source` is `scalar`. | | `distractor_pairs_n` | `int` | Distractor pairs the probe embedded; 0 when `source` is `scalar`. | diff --git a/docs/reference/operations/code.md b/docs/reference/operations/code.md index f5cf4b3c191..6b60d14c86c 100644 --- a/docs/reference/operations/code.md +++ b/docs/reference/operations/code.md @@ -240,7 +240,7 @@ Which merged PRs last touched these lines, between release A and B? ## `code.calibrate` -Derive this namespace's calibration from the authored probe corpus and persist it: the code-specific abstention thresholds and the confident-hit cosine at the top of the `retrieval_confidence` scale. +Derive this namespace's calibration and persist it: the code-specific abstention thresholds and the confident-hit cosine at the top of the `retrieval_confidence` scale. `POST /v1/code.calibrate` · MCP `loom_code_calibrate` · role `admin` · write · audited · not listed under the MCP `all` toolset @@ -254,12 +254,14 @@ Derive this namespace's calibration from the authored probe corpus and persist i | Output field | Type | Meaning | | --- | --- | --- | -| `noise_floor` | `float` | Cosine below which a hit is noise: the distractors' 90th percentile plus 0.02. | -| `abstain_threshold` | `float` | Cosine below which the search abstains: `noise_floor` plus 0.05. | -| `rerank_skip_above` | `float` | Cosine of a confident hit, the probes' 75th-percentile question-to-answer cosine: where `code.search`'s `retrieval_confidence` reads 1.0. | +| `noise_floor` | `float` | Cosine below which a hit is noise: the distractors' 90th percentile plus 0.02, or 0.05 under the abstain threshold when that is capped. | +| `abstain_threshold` | `float` | Cosine below which the search abstains: `noise_floor` plus 0.05, or the probes' 10th-percentile question-to-answer cosine when that is lower, unless the distractors' 90th percentile reaches the probes' 75th. | +| `rerank_skip_above` | `float` | Cosine of a confident hit, the probes' 75th-percentile question-to-answer cosine and at least 0.01 over `noise_floor`: where `code.search`'s `retrieval_confidence` reads 1.0. | | `embedder_model` | `str` | The embedding model the probes ran against; the calibration applies to it. | -| `positives` | `int` | Query/positive pairs read from the probe corpus. | -| `distractors` | `int` | Query/distractor pairs read from the probe corpus. | +| `positives` | `int` | Query/positive pairs the thresholds were derived from. | +| `distractors` | `int` | Query/distractor pairs the thresholds were derived from. | +| `probe_source` | `Literal['namespace', 'fixture'] \| None` | Where the probes came from: `namespace` (its own documented functions) or `fixture` (the fixed corpus). | +| `strata` | `int \| None` | Language-and-directory strata the namespace probes were drawn from; 0 for the fixture. | ## `code.callees` diff --git a/loom.example.yaml b/loom.example.yaml index d41fe99dfb5..ab20348ad7e 100644 --- a/loom.example.yaml +++ b/loom.example.yaml @@ -2233,6 +2233,11 @@ settings: # route agreement and the pool size. The deployment sets 0.30. [restart] # code_search_abstain_confidence_below: 0.35 + # Probes `code.calibrate` samples from a namespace's documented functions, three + # embeddings each (four uncached) and no LLM call; under 20 usable probes it uses the + # fixed corpus. [restart] + # code_calibrate_probes: 200 + # The `retrieval_confidence` from which a code.search result reads `retrieval_risk` # "medium"; below it the result reads "high". In the measurement behind the default # about half of the prompts sent to another repository's index scored under it. diff --git a/schemas/loom-settings.schema.json b/schemas/loom-settings.schema.json index 0edf4525e06..e4bdce49f48 100644 --- a/schemas/loom-settings.schema.json +++ b/schemas/loom-settings.schema.json @@ -846,6 +846,13 @@ "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_calibrate_probes": { + "default": 200, + "maximum": 1000, + "minimum": 20, + "type": "integer", + "description": "Probes `code.calibrate` samples from a namespace's documented functions, three embeddings each (four uncached) and no LLM call; under 20 usable probes it uses the fixed corpus." + }, "code_calibration_enabled": { "default": false, "type": "boolean", diff --git a/sdk/go/wire/models.gen.go b/sdk/go/wire/models.gen.go index 79cb98a45a3..115e664976e 100644 --- a/sdk/go/wire/models.gen.go +++ b/sdk/go/wire/models.gen.go @@ -892,6 +892,8 @@ type CodeCalibrateOutput struct { EmbedderModel string `json:"embedder_model"` Positives int64 `json:"positives"` Distractors int64 `json:"distractors"` + ProbeSource Optional[string] `json:"probe_source,omitempty"` + Strata Optional[int64] `json:"strata,omitempty"` } // CodeCalleesInput is the request to code.callees. diff --git a/sdk/python/loom/ops.py b/sdk/python/loom/ops.py index 4032263eea7..7751d5be6c7 100644 --- a/sdk/python/loom/ops.py +++ b/sdk/python/loom/ops.py @@ -6511,6 +6511,8 @@ class CodeCalibrateOutput(TypedDict, total=False): embedder_model: Required[str] positives: Required[int] distractors: Required[int] + probe_source: NotRequired[Optional[Literal["namespace", "fixture"]]] + strata: NotRequired[Optional[int]] class CodeCallersInput(TypedDict, total=False): diff --git a/sdk/rust/src/wire_models.rs b/sdk/rust/src/wire_models.rs index 6099304a9a5..6510a5ff1e1 100644 --- a/sdk/rust/src/wire_models.rs +++ b/sdk/rust/src/wire_models.rs @@ -7718,6 +7718,15 @@ impl CodeBlameRangeInput { } } +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[non_exhaustive] +pub enum CodeCalibrateOutputProbeSource { + #[serde(rename = "namespace")] + Namespace, + #[serde(rename = "fixture")] + Fixture, +} + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct CodeCalibrateOutput { @@ -7727,6 +7736,10 @@ pub struct CodeCalibrateOutput { pub embedder_model: String, pub positives: Integer, pub distractors: Integer, + #[serde(default = "default_code_calibrate_output_probe_source")] + pub probe_source: Option, + #[serde(default = "default_code_calibrate_output_strata")] + pub strata: Option, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] @@ -67521,6 +67534,12 @@ fn default_code_blame_range_output_tracker_unavailable() -> bool { fn default_code_blame_range_output_trace_run_id() -> String { serde_json::from_str("\"\"").expect("schema default") } +fn default_code_calibrate_output_probe_source() -> Option { + serde_json::from_str("null").expect("schema default") +} +fn default_code_calibrate_output_strata() -> Option { + serde_json::from_str("null").expect("schema default") +} fn default_code_callers_output_lessons() -> Vec> { serde_json::from_str("[]").expect("schema default") } diff --git a/sdk/rust/tests/registry_contracts.rs b/sdk/rust/tests/registry_contracts.rs index 263bf0c8192..ddc32090285 100644 --- a/sdk/rust/tests/registry_contracts.rs +++ b/sdk/rust/tests/registry_contracts.rs @@ -12373,6 +12373,16 @@ fn code_calibrate() { let value: clickhouse_loom::CodeCalibrateOutput = serde_json::from_str("{\"noise_floor\":1.0,\"abstain_threshold\":1.0,\"rerank_skip_above\":1.0,\"embedder_model\":\"sample\",\"positives\":1,\"distractors\":1}").unwrap(); let encoded = serde_json::to_value(value).unwrap(); assert!(encoded.is_object()); + assert_eq!( + encoded["probe_source"], + serde_json::from_str::("null").unwrap(), + "code.calibrate:probe_source" + ); + assert_eq!( + encoded["strata"], + serde_json::from_str::("null").unwrap(), + "code.calibrate:strata" + ); } #[test] fn code_coverage_watch() { diff --git a/sdk/typescript/src/generated/ops.ts b/sdk/typescript/src/generated/ops.ts index 69b75a1248b..70849a2f9e1 100644 --- a/sdk/typescript/src/generated/ops.ts +++ b/sdk/typescript/src/generated/ops.ts @@ -433,6 +433,8 @@ export interface CodeCalibrateOutput { embedder_model: string; positives: number; distractors: number; + probe_source?: "namespace" | "fixture" | null; + strata?: number | null; } export interface CodeCallersInput { diff --git a/server/code/api/models_ingest.py b/server/code/api/models_ingest.py index d19a94418a5..f403d3a8ce8 100644 --- a/server/code/api/models_ingest.py +++ b/server/code/api/models_ingest.py @@ -6,6 +6,7 @@ from __future__ import annotations import uuid +from typing import Literal from pydantic import BaseModel, Field, field_validator @@ -147,16 +148,24 @@ class CodeCalibrateInput(_CodeIdentity): class CodeCalibrateOutput(BaseModel): - # Cosine below which a hit is noise: the distractors' 90th percentile plus 0.02. + # Cosine below which a hit is noise: the distractors' 90th percentile plus 0.02, or + # 0.05 under the abstain threshold when that is capped. noise_floor: float - # Cosine below which the search abstains: `noise_floor` plus 0.05. + # Cosine below which the search abstains: `noise_floor` plus 0.05, or the probes' + # 10th-percentile question-to-answer cosine when that is lower, unless the + # distractors' 90th percentile reaches the probes' 75th. abstain_threshold: float - # Cosine of a confident hit, the probes' 75th-percentile question-to-answer cosine: - # where `code.search`'s `retrieval_confidence` reads 1.0. + # Cosine of a confident hit, the probes' 75th-percentile question-to-answer cosine and + # at least 0.01 over `noise_floor`: where `code.search`'s `retrieval_confidence` reads 1.0. rerank_skip_above: float # The embedding model the probes ran against; the calibration applies to it. embedder_model: str - # Query/positive pairs read from the probe corpus. + # Query/positive pairs the thresholds were derived from. positives: int - # Query/distractor pairs read from the probe corpus. + # Query/distractor pairs the thresholds were derived from. distractors: int + # Where the probes came from: `namespace` (its own documented functions) or `fixture` + # (the fixed corpus). + probe_source: Literal["namespace", "fixture"] | None = None + # Language-and-directory strata the namespace probes were drawn from; 0 for the fixture. + strata: int | None = None diff --git a/server/code/app/admin.py b/server/code/app/admin.py index c539367abcf..3b248a6721c 100644 --- a/server/code/app/admin.py +++ b/server/code/app/admin.py @@ -4,6 +4,8 @@ import json import logging +from functools import partial +from typing import Literal from server.code.api.models_ingest import ( CodeCalibrateInput, @@ -12,14 +14,19 @@ CodeReindexOutput, ) from server.code.app.common import require_code_intel, resolve_code_identity +from server.code.domain.calibration_probes import Probes, Unit, sample_probes from server.code.domain.index.repos import repo_for_namespace from server.code.store.index import CodeRepo -from server.core.errors import NotFoundError, ValidationError +from server.core.errors import NotFoundError, ValidationError, caller_text from server.core.paths import REPO_ROOT +from server.settings import settings logger = logging.getLogger(__name__) _PROBES_PATH = REPO_ROOT / "bench" / "fixtures" / "code_calibration_probes.jsonl" +# not a setting: below this many probes the distractors' 90th percentile rests on one +# or two pairs, and the fixed corpus is the better estimate +MIN_NAMESPACE_PROBES = 20 async def handle_code_reindex(input: CodeReindexInput) -> CodeReindexOutput: @@ -48,13 +55,68 @@ async def handle_code_reindex(input: CodeReindexInput) -> CodeReindexOutput: return CodeReindexOutput(previous_head=previous, new_head=input.git_head) +def _fixture_probes() -> Probes: + """The fixed query/positive/distractor corpus, for a namespace too small to sample.""" + if not _PROBES_PATH.exists(): + raise ValidationError(f"probe corpus missing: {_PROBES_PATH}") + probes = Probes() + for line in _PROBES_PATH.read_text().splitlines(): + line = line.strip() + if not line or line.startswith("//"): + continue + probe = json.loads(line) + q = str(probe["query"]) + probes.positives.append((q, str(probe["positive"]))) + if probe.get("distractor"): + probes.distractors.append((q, str(probe["distractor"]))) + return probes + + +async def _namespace_probes(org: str, ns: str) -> Probes: + """Probes sampled from the namespace's documented functions under the served + embedding model, each text clipped as ingest clipped it before embedding. Raises + `ValidationError` when the embedder cannot be built: the fixed corpus would need it + too.""" + from server.code.app.index.embed_text import clip_for_embedding + from server.embedding.embedder import get_embedder + + try: + embedder = get_embedder() + model = str(embedder.model_name) + except Exception as e: # any build failure means no probe can run + logger.warning("code.calibrate: embedder unavailable: %s", e) + raise ValidationError(f"embedder unavailable: {caller_text(e)}") from e + size = settings.code_calibrate_probes + repo = CodeRepo() + # Most doc comments pass the query filter; five candidates per probe keep a + # namespace with a few documented strata from running dry. + documented = await repo.calibration_units(org, ns, model, limit=size * 5) + if len(documented) < MIN_NAMESPACE_PROBES: + return Probes() # the fixed corpus is certain: the pool is not read + pool = await repo.calibration_pool(org, ns, model, limit=size * 5) + probes = sample_probes( + ns, + [Unit(r["path"], r["context_text"], r["doc"], r["name"]) for r in documented], + [Unit(r["path"], r["context_text"]) for r in pool], + size=size, + ) + clip = partial(clip_for_embedding, count_tokens=getattr(embedder, "_count_tokens", None)) + probes.positives = [(q, clip(text)) for q, text in probes.positives] + probes.distractors = [(q, clip(text)) for q, text in probes.distractors] + return probes + + async def handle_code_calibrate(input: CodeCalibrateInput) -> CodeCalibrateOutput: - """Derive this namespace's calibration from the authored probe corpus and - persist it: the code-specific abstention thresholds and the confident-hit - cosine at the top of the `retrieval_confidence` scale. The probes are - query/positive/hard-distractor triples over the indexed repo. Cosine - distributions for code differ from prose — the namespace must not inherit - prose-derived gates.""" + """Derive this namespace's calibration and persist it: the code-specific + abstention thresholds and the confident-hit cosine at the top of the + `retrieval_confidence` scale. The probes are the namespace's own documented + functions (the doc comment's first paragraph as the query, the unit without it as + the positive, a unit in another language or another directory two levels deep as the + distractor, or in another file when every unit shares one language and directory); a + namespace that yields fewer than `MIN_NAMESPACE_PROBES` probes with a distractor is + calibrated on the fixed corpus. Cosine distributions for code differ from prose, and + from one repository to the next: the namespace must not inherit another corpus's + gates.""" require_code_intel() org, ns = resolve_code_identity(input.org, input.namespace) return await calibrate_namespace(org, ns) @@ -63,26 +125,20 @@ async def handle_code_calibrate(input: CodeCalibrateInput) -> CodeCalibrateOutpu 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.""" + customer). The probes are the namespace's own documented functions, or the fixed + corpus when they yield fewer than `MIN_NAMESPACE_PROBES` probes with a distractor. + Raises `ValidationError` when the probes are too few or the embedder cannot be + probed; the stored row stays.""" from server.memory.app.embedder_calibration import ( calibrate_embedder, persist_namespace_calibration, ) - if not _PROBES_PATH.exists(): - raise ValidationError(f"probe corpus missing: {_PROBES_PATH}") - positives: list[tuple[str, str]] = [] - distractors: list[tuple[str, str]] = [] - for line in _PROBES_PATH.read_text().splitlines(): - line = line.strip() - if not line or line.startswith("//"): - continue - probe = json.loads(line) - q = str(probe["query"]) - positives.append((q, str(probe["positive"]))) - if probe.get("distractor"): - distractors.append((q, str(probe["distractor"]))) + probes = await _namespace_probes(org, ns) + source: Literal["namespace", "fixture"] = "namespace" + if len(probes.distractors) < MIN_NAMESPACE_PROBES: # each comes with a positive + probes, source = _fixture_probes(), "fixture" + positives, distractors = probes.positives, probes.distractors if len(positives) < 5 or len(distractors) < 3: raise ValidationError( f"probe corpus too small: {len(positives)} positives, " @@ -97,6 +153,7 @@ async def calibrate_namespace(org: str, ns: str) -> CodeCalibrateOutput: distractor_pairs=distractors, question_fact_pairs=positives, paraphrase_pair_purpose="query_document", + cap_at_answers=True, ) if calibration is None: raise ValidationError( @@ -111,4 +168,6 @@ async def calibrate_namespace(org: str, ns: str) -> CodeCalibrateOutput: embedder_model=calibration.embedder_model, positives=len(positives), distractors=len(distractors), + probe_source=source, + strata=probes.strata, ) diff --git a/server/code/app/index/embed_text.py b/server/code/app/index/embed_text.py index ca42ab9c426..ddc35e19546 100644 --- a/server/code/app/index/embed_text.py +++ b/server/code/app/index/embed_text.py @@ -10,11 +10,11 @@ from __future__ import annotations from collections.abc import Callable -from typing import Any + +from server.embedding.documents import TRUNCATION_MARK as _MARK EMBED_MAX_CHARS = 20_000 EMBED_MAX_TOKENS = 8_000 # provider limit 8,191; leave headroom for the marker -_MARK = "\n…[truncated for embedding]" def clip_for_embedding( @@ -46,44 +46,3 @@ def clip_for_embedding( keep = max(256, int(len(text) * max_tokens / n * 0.9)) text = text[:keep] + _MARK return text - - -# httpx's HTTPStatusError carries only "Client error '400 Bad Request' for -# url ..." — the provider's "maximum context length" body never reaches the -# message. An embeddings endpoint's 400 is, in practice, a length rejection -# (the model name and key are fixed per process), so treat it as one: a -# genuinely different 400 shrinks a few times and then raises unchanged. -_TOO_LONG_MARKERS = ( - "context length", - "maximum context", - "too large", - "tokens", - "400 bad request", -) - - -def looks_too_long(exc: BaseException) -> bool: - msg = str(exc).lower() - return any(m in msg for m in _TOO_LONG_MARKERS) - - -async def embed_shrinking(embedder: Any, text: str, *, attempts: int = 5) -> list[float]: - """One stored vector for `text` (`embed_many`: the raw text, as ingest - stores it; `embed` is the query path and normalises), halving the input on - a provider "too long" rejection. Provider-driven on purpose: the local token counter degrades to - len//4 without tiktoken and undercounts hex-heavy SQL threefold, so only - the provider knows the true length. Non-length errors propagate at once.""" - last: BaseException | None = None - for _ in range(attempts): - try: - vecs: list[list[float]] = await embedder.embed_many([text]) - if len(vecs) != 1: - raise RuntimeError(f"embed_many returned {len(vecs)} vectors for 1 input") - return vecs[0] - except Exception as e: - if not looks_too_long(e) or len(text) <= 256: - raise - last = e - text = text[: max(256, len(text) // 2)] + _MARK - assert last is not None - raise last diff --git a/server/code/app/index/ingest.py b/server/code/app/index/ingest.py index ed234cab50c..b78cd46ff05 100644 --- a/server/code/app/index/ingest.py +++ b/server/code/app/index/ingest.py @@ -97,7 +97,7 @@ async def _embed_texts(texts: list[str], embedder: Any) -> EmbedResult: for i, v in enumerate(vecs): result.vectors[start + i] = v continue - from server.code.app.index.embed_text import embed_shrinking + from server.embedding.documents import embed_shrinking for i, text in enumerate(batch): try: diff --git a/server/code/domain/calibration_probes.py b/server/code/domain/calibration_probes.py new file mode 100644 index 00000000000..a53851fa0bb --- /dev/null +++ b/server/code/domain/calibration_probes.py @@ -0,0 +1,202 @@ +"""Calibration probes sampled from a code namespace's own units. + +A documented function is a query and its answer that the repository already wrote: +the first paragraph of its doc comment says what the unit does, the way a question +about it would. `code.calibrate` embeds each such query against its unit (with the +doc comment taken out, so the answer does not contain the question) and against a +unit from another part of the namespace as it is indexed, doc comment included, since +a wrong hit in a search carries its doc comment too. The thresholds then follow the +repository's own language and vocabulary instead of a fixed corpus. +""" + +from __future__ import annotations + +import hashlib +import random +import re +from bisect import bisect_left, bisect_right +from dataclasses import dataclass, field +from pathlib import PurePosixPath + +# not a setting: a paragraph shorter than this names the unit, it does not describe it +_MIN_QUERY_WORDS = 4 +# not a setting: a search query is about a sentence; a longer paragraph is cut there +_MAX_QUERY_WORDS = 32 +# not a setting: a stratum is a directory two levels deep, the grain a repository's +# components usually sit at +_STRATUM_DEPTH = 2 + +_LEADER = re.compile(r"^\s*(?:/{2,3}!?|/\*+!?|\*+/?|#+|[rRuUbBfF]{0,2}(?:\"{3}|'{3})|--)\s?") +_TAG = re.compile(r"^[@\\](brief|summary)\s+") +_SECTION = re.compile( + r"^(?:[@\\:]\w+|(?:Args|Arguments|Returns?|Raises|Yields|Parameters|Example)s?:)" +) +# `end`/`endif` close a block in lower case; a description can start with "End". +_NOT_PROSE = re.compile(r"://|^namespace(?:\s+\w+)?\s*$|(?-i:^(?:end|endif)\b)", re.IGNORECASE) +_WORD = re.compile(r"[A-Za-z]{2}") +_NOT_DESCRIPTION = ("todo", "fixme", "xxx", "hack", "copyright", "spdx", "noqa", "type:", "pylint") + + +@dataclass(frozen=True) +class Unit: + """A function chunk: its path, the text it was embedded from, its doc comment and + its name.""" + + path: str + context_text: str + doc_comment: str = "" + name: str = "" + + +@dataclass +class Probes: + positives: list[tuple[str, str]] = field(default_factory=list) + distractors: list[tuple[str, str]] = field(default_factory=list) + # Strata the positives were drawn from: language and directory. + strata: int = 0 + + +def probe_query(doc_comment: str, name: str = "") -> str: + """The first paragraph of a doc comment as a search query, or '' when it does not + describe the unit (too short, a tag, a link, a note to maintainers). A leading `name` + is dropped: Go opens a doc comment with it, and a question seldom names the unit.""" + words: list[str] = [] + for raw in doc_comment.strip().splitlines(): + # the closer is the two characters `*/`, so a line ending in `src/*` keeps its glob + line = _TAG.sub("", _LEADER.sub("", raw).strip().removesuffix("*/").strip()) + if not line: + if words: + break + continue + if _SECTION.match(line): + break + if _NOT_PROSE.search(line): + if words: + break + continue + words.extend(line.split()) + query = " ".join(words).strip("\"' ") + first, _, rest = query.partition(" ") + if name and first.rstrip(",.:;") == name: + query = rest + if len(query.split()) < _MIN_QUERY_WORDS or query.lower().startswith(_NOT_DESCRIPTION): + return "" + if sum(ch.isalpha() or ch.isspace() for ch in query) < 0.8 * len(query): + return "" + return " ".join(query.split()[:_MAX_QUERY_WORDS]) + + +# A comment's opening token ahead of its text on the same line (or alone on the line +# before), as `_LEADER` reads them; a docstring's quote may sit right after the `:` of +# its `def`. +_OPENER = re.compile( + r"(?:(?:/\*+!?|[rRuUbBfF]{0,2}(?:\"{3}|'{3}))[ \t]*\n[ \t]*" + r"|(?:/{2,3}!?|/\*+!?|\*+|#+|--|[rRuUbBfF]{0,2}(?:\"{3}|'{3}|\"|'))[ \t]*)$" +) +_QUOTE = re.compile(r"\"{3}|'{3}|\"|'") +# A block comment or docstring closed on a line of its own, when no opener names it. +_CLOSING_LINE = re.compile(r"[ \t]*\n[ \t]*(?:\*+/|\"{3}|'{3})[ \t]*(?=\n|$)") + + +def _closer(opener: str) -> re.Pattern[str]: + quote = _QUOTE.search(opener) + token = re.escape(quote.group()) if quote else (r"\*+/" if "*" in opener else "") + return re.compile(rf"[ \t]*(?:\n[ \t]*)?(?:{token})") if token else _CLOSING_LINE + + +def _doc_span(body: str, start: int, doc: list[str], limit: int) -> tuple[int, int]: + """The doc text found at `start`, its opener ahead of it and its closer after it.""" + end = start + len(doc[0]) + if len(doc) > 1 and (last := body.find(doc[-1], end, limit)) >= 0: + end = last + len(doc[-1]) + opener = _OPENER.search(body, 0, start) + closing = (_closer(opener.group()) if opener else _CLOSING_LINE).match(body, end) + return (opener.start() if opener else start), (closing.end() if closing else end) + + +def _cut(body: str, start: int, end: int) -> str: + """`body` without [start, end): a line the doc owned goes with it; a line that also + holds code keeps the code (`def f(): \"\"\"doc\"\"\"; return 1` becomes `def f(): return 1`).""" + left, right = body[:start], body[end:].lstrip(" \t;") + line_start = left.rfind("\n") + 1 + code_left = bool(left[line_start:].strip()) + code_right = bool(right.partition("\n")[0].strip()) + if code_left: + return left.rstrip(" \t") + (" " if code_right else "") + right + if code_right: + return left + right + return left[:line_start] + right.partition("\n")[2] + + +def without_doc(context_text: str, doc_comment: str) -> str: + """`context_text` with every copy of the doc comment removed from its body (a unit's + chunk can carry it both ahead of the declaration and inside it), so a probe's + positive does not contain its own query. Only the doc text goes, with its comment + opener and closer: a one-line function keeps its declaration and body.""" + doc = [line.strip() for line in doc_comment.strip().splitlines() if _WORD.search(line)] + if not doc: + return context_text + head, sep, body = context_text.partition("\n---\n") + if not sep: + head, body = "", context_text + # a copy's lines may carry a comment leader the parsed doc comment lacks + reach = len(doc_comment) + 16 * len(doc) + 64 + while (found := body.find(doc[0])) >= 0: + start, end = _doc_span(body, found, doc, found + reach) + body = _cut(body, start, end) + kept = body.removesuffix("\n") + return f"{head}{sep}{kept}" if sep else kept + + +def stratum(path: str) -> tuple[str, str]: + """(extension, directory two levels deep): the language and the component.""" + p = PurePosixPath(path) + return p.suffix, "/".join(p.parts[:-1][:_STRATUM_DEPTH]) + + +def _seed(namespace: str) -> int: + # One namespace draws the same probes on every replica and every rerun of the same + # index, so two calibrations differ only when the code or the embedder did. + return int.from_bytes(hashlib.sha256(namespace.encode()).digest()[:8], "big") + + +def sample_probes(namespace: str, units: list[Unit], pool: list[Unit], *, size: int) -> Probes: + """At most `size` query/positive pairs from the documented `units`, drawn + round-robin across strata so no one directory or language dominates, and for each + query one distractor from `pool` in another stratum (another file when the + namespace has one stratum).""" + rng = random.Random(_seed(namespace)) + by_stratum: dict[tuple[str, str], list[tuple[Unit, str]]] = {} + for unit in units: + if query := probe_query(unit.doc_comment, unit.name): + by_stratum.setdefault(stratum(unit.path), []).append((unit, query)) + keys = sorted(by_stratum) + rng.shuffle(keys) + for key in keys: + rng.shuffle(by_stratum[key]) + picked: list[tuple[Unit, str]] = [] + while len(picked) < size and any(by_stratum[k] for k in keys): + for key in keys: + if by_stratum[key] and len(picked) < size: + picked.append(by_stratum[key].pop()) + probes = Probes(strata=len({stratum(unit.path) for unit, _ in picked})) + # The pool sorted by stratum, then file, is parsed once: the units outside a probe's + # stratum (or, with one stratum, its file) are the pool less one run, drawn from in + # place instead of copied per stratum. + pool_strata = [stratum(o.path) for o in pool] + order = sorted(range(len(pool)), key=lambda i: (pool_strata[i], pool[i].path)) + sorted_strata = [pool_strata[i] for i in order] + sorted_paths = [pool[i].path for i in order] + for unit, query in picked: + probes.positives.append((query, without_doc(unit.context_text, unit.doc_comment))) + key = stratum(unit.path) + lo, hi = bisect_left(sorted_strata, key), bisect_right(sorted_strata, key) + if hi - lo == len(order): + # one stratum, so the paths are sorted across the whole pool + lo, hi = bisect_left(sorted_paths, unit.path), bisect_right(sorted_paths, unit.path) + if rest := len(order) - (hi - lo): + i = rng.randrange(rest) + probes.distractors.append( + (query, pool[order[i if i < lo else i + hi - lo]].context_text) + ) + return probes diff --git a/server/code/store/index/search.py b/server/code/store/index/search.py index b6efccba0c7..e4afcd76b11 100644 --- a/server/code/store/index/search.py +++ b/server/code/store/index/search.py @@ -12,11 +12,13 @@ from server.code.domain.idents import whole_literal_pattern from server.code.domain.index.grep_plan import GREP_FINAL_SETTINGS, any_literal_guard +from server.code.domain.index.test_gate import TEST_PATH_PATTERN from server.code.domain.search_scope import SearchScope from server.code.store.index.base import CodeRepoBase from server.code.store.index.sql import _gather_batched, _scope_sql, skip_tests_sql from server.code.store.index.symbol_rank import SYMBOL_NOISE_PATH_RE from server.core.datetimes import naive_utc_now as _now +from server.core.repo_base import query_all_sliced def _nearest_first(rows: list[dict[str, Any]], *keys: str) -> list[dict[str, Any]]: @@ -31,6 +33,18 @@ def order(r: dict[str, Any]) -> tuple[Any, ...]: return sorted(rows, key=order) +def _function_chunks(model: str) -> str: + """FROM and WHERE of the live, embedded function chunks `code.calibrate` reads.""" + from server.core.vectors.code_tables import code_vector_table + + return f""" + 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 AND kind = 'function' AND context_text != '' + """ + + class SearchMixin(CodeRepoBase): """code.search legs, corpus statistics and outcome signals.""" @@ -335,6 +349,67 @@ async def vector_search_cards( ) return _nearest_first(rows, "path") + async def calibration_units( + self, org: str, ns: str, model: str, *, limit: int + ) -> list[dict[str, Any]]: + """`code.calibrate`'s documented units: the first live chunk of up to `limit` source + functions that have a doc comment, each with that comment and the function's name, + in a hash order of their ids, so a rerun on an unchanged index reads the same + rows. The chunks are read in slices of ids that each fit one HTTP form field.""" + # Test files are dropped before the limit, so they cannot use up the budget. + docs = await self._ch.query_all( + """ + SELECT symbol_id, name, doc_comment AS doc + FROM loom.code_symbols FINAL + WHERE org = {org:String} AND namespace = {ns:String} + AND kind = 'function' AND doc_comment != '' AND tombstoned_at IS NULL + AND tier = 'treesitter' AND NOT match(path, {test_path_pattern:String}) + ORDER BY cityHash64(symbol_id) + LIMIT {limit:UInt32} + """, + {"org": org, "ns": ns, "limit": limit, "test_path_pattern": TEST_PATH_PATTERN}, + ) + doc_of = {str(r["symbol_id"]): (str(r["doc"]), str(r["name"])) for r in docs} + # At the 1,000-probe ceiling the ids fill ~180 KB, over the server's 128 KiB form + # field: read them a slice at a time and merge on the one draw order. + rows = await query_all_sliced( + self._ch, + f""" + SELECT path, context_text, symbol_ids[1] AS symbol_id, cityHash64(chunk_id) AS draw + {_function_chunks(model)} + AND symbol_ids[1] IN {{ids:Array(String)}} + ORDER BY symbol_id, start_line + LIMIT 1 BY symbol_id + """, + {"org": org, "ns": ns, "model": model, "ids": list(doc_of)}, + "ids", + ) + rows.sort(key=lambda r: (int(r["draw"]), str(r["symbol_id"]))) + return [ + { + "path": r["path"], + "context_text": r["context_text"], + "doc": doc_of[str(r["symbol_id"])][0], + "name": doc_of[str(r["symbol_id"])][1], + } + for r in rows + ] + + async def calibration_pool( + self, org: str, ns: str, model: str, *, limit: int + ) -> list[dict[str, Any]]: + """`code.calibrate`'s distractor pool: up to `limit` live function chunks, + documented or not, in a hash order of their ids.""" + rows = await self._ch.query_all( + f""" + SELECT path, context_text {_function_chunks(model)} + ORDER BY cityHash64(chunk_id) + LIMIT {{limit:UInt32}} + """, + {"org": org, "ns": ns, "model": model, "limit": limit}, + ) + return [{"path": r["path"], "context_text": r["context_text"]} for r in rows] + async def vector_search_chunks( self, org: str, diff --git a/server/code/workers/calibration.py b/server/code/workers/calibration.py index 543c7b9a0df..e1985361b68 100644 --- a/server/code/workers/calibration.py +++ b/server/code/workers/calibration.py @@ -37,8 +37,9 @@ 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. +# One calibration is up to ~4,000 embedding calls, 16 in flight: 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 @@ -131,7 +132,7 @@ async def _run(result: CodeCalibrationResult) -> None: 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) + out = 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() @@ -139,4 +140,11 @@ async def _run(result: CodeCalibrationResult) -> None: else: _failed.pop((org, ns), None) result.calibrated = f"{org}/{ns}" + logger.info( + "code_calibration: %s/%s calibrated from %s probes (%s strata)", + org, + ns, + out.probe_source, + out.strata, + ) return # one namespace a pass, calibrated or failed diff --git a/server/code/workers/embed_recovery.py b/server/code/workers/embed_recovery.py index 0865f6090c2..cdebc69293e 100644 --- a/server/code/workers/embed_recovery.py +++ b/server/code/workers/embed_recovery.py @@ -341,7 +341,7 @@ async def _vectors_for( raise except Exception as e: # noqa: BLE001 — fall back per-text logger.warning("code_embed_recovery: batch failed (%s), per-text", e) - from server.code.app.index.embed_text import embed_shrinking + from server.embedding.documents import embed_shrinking vectors: dict[int, list[float]] = {} for i in todo: diff --git a/server/embedding/documents.py b/server/embedding/documents.py index 6177a09a043..0a49f3d8fdd 100644 --- a/server/embedding/documents.py +++ b/server/embedding/documents.py @@ -2,13 +2,17 @@ from __future__ import annotations -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Any +from server.clients._retry import is_retryable from server.embedding._provider import MalformedEmbedding, vector if TYPE_CHECKING: from server.embedding.embedder import Embedder +# Appended to a text cut short for embedding; the stored text keeps its whole content. +TRUNCATION_MARK = "\n…[truncated for embedding]" + async def document_vectors(embedder: Embedder, texts: list[str]) -> list[list[float]]: """Embed raw document text with one validated vector per input.""" @@ -23,3 +27,48 @@ async def document_vectors(embedder: Embedder, texts: list[str]) -> list[list[fl async def document_vector(embedder: Embedder, text: str) -> list[float]: """A single stored document uses the same provider purpose as a batch.""" return (await document_vectors(embedder, [text]))[0] + + +# httpx's HTTPStatusError carries only "Client error '400 Bad Request' for +# url ..." — the provider's "maximum context length" body never reaches the +# message. An embeddings endpoint's 400 is, in practice, a length rejection +# (the model name and key are fixed per process), so treat it as one: a +# genuinely different 400 shrinks a few times and then raises unchanged. +_TOO_LONG_MARKERS = ( + "context length", + "maximum context", + "too large", + "tokens", + "400 bad request", +) + + +def looks_too_long(exc: BaseException) -> bool: + # A rate limit or an overload is retried, never shrunk: OpenAI's tokens-per-minute + # 429 names `type=tokens`, and a shorter text would succeed on the next call. + if is_retryable(exc): + return False + msg = str(exc).lower() + return any(m in msg for m in _TOO_LONG_MARKERS) + + +async def embed_shrinking(embedder: Any, text: str, *, attempts: int = 5) -> list[float]: + """One stored vector for `text` (`embed_many`: the raw text, as ingest + stores it; `embed` is the query path and normalises), halving the input on + a provider "too long" rejection. Provider-driven on purpose: the local token counter degrades to + len//4 without tiktoken and undercounts hex-heavy SQL threefold, so only + the provider knows the true length. Non-length errors propagate at once.""" + last: BaseException | None = None + for _ in range(attempts): + try: + vecs: list[list[float]] = await embedder.embed_many([text]) + if len(vecs) != 1: + raise RuntimeError(f"embed_many returned {len(vecs)} vectors for 1 input") + return vecs[0] + except Exception as e: + if not looks_too_long(e) or len(text) <= 256: + raise + last = e + text = text[: max(256, len(text) // 2)] + TRUNCATION_MARK + assert last is not None + raise last diff --git a/server/memory/api/models_calibration.py b/server/memory/api/models_calibration.py index 52f0bb58256..c76062d0dfd 100644 --- a/server/memory/api/models_calibration.py +++ b/server/memory/api/models_calibration.py @@ -19,7 +19,8 @@ class CalibrationGetOutput(BaseModel): # The embedder the thresholds were derived for; with `scalar`, the configured model. embedder_model: str = "" - # Cosine below which a search hit is dropped as noise (distractor P90 + 0.02 when probed). + # Cosine below which a search hit is dropped as noise (distractor P90 + 0.02 when probed; + # for a code namespace, 0.05 under an abstain threshold capped at question-to-fact P10). noise_floor: float # Top-hit cosine at or above which the LLM rerank is skipped (question-to-fact P75, # never below `hyde_fallback_threshold`). @@ -29,7 +30,8 @@ class CalibrationGetOutput(BaseModel): hyde_fallback_threshold: float # The question-to-fact P10 gate, held at least 0.01 above `noise_floor`. query_rewrite_threshold: float - # Top-hit cosine below which a search abstains (`noise_floor` + 0.05 when probed). + # Top-hit cosine below which a search abstains (`noise_floor` + 0.05 when probed; for a + # code namespace, at most question-to-fact P10 unless distractor P90 reaches its P75). abstain_threshold: float # Cosine at or above which a write against an active peer is flagged `conflicted` # (paraphrase P50 when probed). @@ -48,7 +50,8 @@ class CalibrationGetOutput(BaseModel): similar_p75: float = Field(default=0.0) # Median cosine of the unrelated (distractor) pairs. distractor_p50: float = Field(default=0.0) - # 90th percentile cosine of the distractor pairs, the anchor of `noise_floor`. + # 90th percentile cosine of the distractor pairs, the anchor of `noise_floor` unless a + # code namespace's abstain cap moved it. distractor_p90: float = Field(default=0.0) # Paraphrase pairs the probe embedded; 0 when `source` is `scalar`. diff --git a/server/memory/app/embedder_calibration.py b/server/memory/app/embedder_calibration.py index 7cf6ee86b26..1b48b9c1005 100644 --- a/server/memory/app/embedder_calibration.py +++ b/server/memory/app/embedder_calibration.py @@ -238,13 +238,17 @@ def derive_thresholds( distractor_cosines: list[float], *, embedder_model: str, + cap_at_answers: bool = False, ) -> CalibrationResult: """Pure derivation: probe cosine distributions → CalibrationResult. Filter gates (noise_floor, abstain) anchor to the distractor distribution; read-time trigger gates (rerank_skip, hyde, query_rewrite) to question→fact; write-time gates (conflict, - duplicate) to paraphrase. + duplicate) to paraphrase. `cap_at_answers` keeps abstain at most the + question→fact 10th percentile, with the floor 0.05 under it, before the + trigger gates are clamped to that floor, unless the distractors' 90th + percentile reaches the question→fact 75th. """ sim_p10 = _percentile(similar_cosines, 10) sim_p25 = _percentile(similar_cosines, 25) @@ -261,6 +265,11 @@ def derive_thresholds( # legitimate hits under the floor. noise_floor = dist_p90 + 0.02 abstain_threshold = noise_floor + 0.05 + # Units of one code repository share its vocabulary, so an unrelated unit scores + # close to the right one, and the distractors alone would abstain on many answers. + # Distractors over most answers mean no cosine separates them: no cap, no scale. + if cap_at_answers and qf_p10 < abstain_threshold and dist_p90 < qf_p75: + abstain_threshold, noise_floor = qf_p10, qf_p10 - 0.05 # Trigger gates can't fire below the floor (sub-floor hits already # dropped), so clamp each to floor + margin; the max() chain keeps @@ -300,25 +309,37 @@ def derive_thresholds( ) +def _root(error: BaseException) -> BaseException: + """The first failure inside nested task groups.""" + while isinstance(error, BaseExceptionGroup): + error = error.exceptions[0] + return error + + +# not a setting: code.calibrate sends up to 1,000 pairs a phase through the model client +# every search embeds its query on; 16 calls in flight a calibration leave it the rest of +# its connections. +_PROBE_PAIRS_IN_FLIGHT = 8 + + async def calibrate_embedder( paraphrase_pairs: list[tuple[str, str]] | None = None, distractor_pairs: list[tuple[str, str]] | None = None, question_fact_pairs: list[tuple[str, str]] | None = None, *, paraphrase_pair_purpose: Literal["document_document", "query_document"] = "document_document", + cap_at_answers: bool = False, ) -> CalibrationResult | None: """Probe the configured embedder and compute percentile-based thresholds. Returns None on probe failure (gates fall through to scalar settings). Each corpus arg: None → module-level default corpus; a custom list → - per-namespace operator-shipped corpus. The operator corpus carries - only similar/distractor pairs, so per-NS probes keep the module - question→fact corpus — the question-vs-fact register gap is a - property of the embedder, not the domain vocabulary. Ordinary memory - paraphrases use document/document vectors. Code calibration explicitly - supplies query/document positives for both positive distributions. + `code.calibrate`'s probes (the namespace's own or the fixed corpus), which + supplies all three and passes its query/document positives as both positive + distributions. Ordinary memory paraphrases use document/document vectors. """ + from server.embedding.documents import embed_shrinking from server.embedding.embedder import get_embedder para = paraphrase_pairs if paraphrase_pairs is not None else PARAPHRASE_PAIRS @@ -349,34 +370,49 @@ async def calibrate_embedder( ) return None + in_flight = asyncio.Semaphore(_PROBE_PAIRS_IN_FLIGHT) + async def _embed_pair(a: str, b: str, *, query: bool) -> float: # The recalibration worker's fixed pairs are the deployment's; code.calibrate - # probes a namespace's corpus under its request's org, which wins. - with customer.system(): - if query: - va, documents = await asyncio.gather(embedder.embed(a), embedder.embed_many([b])) - vb = documents[0] - else: - va, vb = await embedder.embed_many([a, b]) - return _cosine(va, vb) + # probes a namespace's corpus under its request's org, which wins. A document + # the provider refuses as too long is halved, as ingest halves one before storing. + # The pair owns both calls: one that fails cancels and joins the other before + # the pair, and so the semaphore slot, is released. + async with in_flight: + with customer.system(): + async with asyncio.TaskGroup() as calls: + va = calls.create_task( + embedder.embed(a) if query else embed_shrinking(embedder, a) + ) + vb = calls.create_task(embed_shrinking(embedder, b)) + return _cosine(va.result(), vb.result()) + + # Code calibration passes its positives as both positive corpora: each pair is + # embedded once. + measured: dict[tuple[str, str, bool], float] = {} + + async def _cosines(pairs: list[tuple[str, str]], *, query: bool) -> list[float]: + todo = dict.fromkeys((a, b, query) for a, b in pairs if (a, b, query) not in measured) + # A failed pair cancels the rest of the phase instead of leaving it running. + async with asyncio.TaskGroup() as group: + tasks = {key: group.create_task(_embed_pair(*key[:2], query=query)) for key in todo} + measured.update({key: task.result() for key, task in tasks.items()}) + return [measured[(a, b, query)] for a, b in pairs] try: - similar_cosines = await asyncio.gather( - *(_embed_pair(a, b, query=paraphrase_pair_purpose == "query_document") for a, b in para) - ) - question_fact_cosines = await asyncio.gather( - *(_embed_pair(a, b, query=True) for a, b in qf) - ) - distractor_cosines = await asyncio.gather(*(_embed_pair(a, b, query=True) for a, b in dist)) + similar_cosines = await _cosines(para, query=paraphrase_pair_purpose == "query_document") + question_fact_cosines = await _cosines(qf, query=True) + distractor_cosines = await _cosines(dist, query=True) except Exception as e: # noqa: BLE001 — a failed probe: the scalar gates serve - log.warning("calibration: probe failed (%s); falling back to scalar settings", e) + log.warning("calibration: probe failed (%s); falling back to scalar settings", _root(e)) return None result = derive_thresholds( - list(similar_cosines), - list(question_fact_cosines), - list(distractor_cosines), + similar_cosines, + question_fact_cosines, + distractor_cosines, embedder_model=embedder.model_name, + cap_at_answers=cap_at_answers, ) log.info( "calibration: embedder=%s similar_p50=%.3f question_fact_p25=%.3f " diff --git a/server/settings/catalog.py b/server/settings/catalog.py index 66c186a8611..54eeb5a69f6 100644 --- a/server/settings/catalog.py +++ b/server/settings/catalog.py @@ -1843,6 +1843,9 @@ def _check_git_proxy(self) -> CodeSettings: # `retrieval_confidence`: it blends the top cosine, its margin over the second # hit, route agreement and the pool size. The deployment sets 0.30. code_search_abstain_confidence_below: float = 0.35 + # Probes `code.calibrate` samples from a namespace's documented functions, three embeddings + # each (four uncached) and no LLM call; under 20 usable probes it uses the fixed corpus. + code_calibrate_probes: int = Field(default=200, ge=20, le=1000) # The `retrieval_confidence` from which a code.search result reads # `retrieval_risk` "medium"; below it the result reads "high". In the measurement # behind the default about half of the prompts sent to another repository's index @@ -6477,7 +6480,9 @@ class TrackerSettings(BaseModel): # (≤400 lines, 5 s cap, cached 10 min) beside one rev-list and two # ledger reads, gathered; optional bounded tracker reads "code.blame_range": 6000, - # Probes the live embedder over the whole corpus: slow by design. + # Three ClickHouse reads (~3 s over 330k functions), then up to four embeddings a + # probe, 16 in flight: sized for the default `code_calibrate_probes` (200); a + # deployment that raises it raises this with `latency_budget_overrides`. "code.calibrate": 30000, "code.callees": 400, "code.callers": 400, diff --git a/tests/integration/test_code_calibration_units_live_ch.py b/tests/integration/test_code_calibration_units_live_ch.py new file mode 100644 index 00000000000..232976d9b49 --- /dev/null +++ b/tests/integration/test_code_calibration_units_live_ch.py @@ -0,0 +1,153 @@ +"""`code.calibrate` reads its documented units and its pool from real ClickHouse rows.""" + +from __future__ import annotations + +import datetime as dt +import uuid +from typing import Any + +import pytest + +from server.code.store.index import CodeRepo +from server.core.ch import get_client +from server.settings import settings +from tests.integration._resources import unique_org + +_SYMBOL_COLUMNS = [ + "org", + "namespace", + "tier", + "qualified_name", + "symbol_id", + "name", + "kind", + "path", + "doc_comment", + "tombstoned_at", +] +_CHUNK_COLUMNS = [ + "org", + "namespace", + "embedding_model", + "path", + "chunk_id", + "kind", + "start_line", + "end_line", + "content", + "context_text", + "symbol_ids", + "embedding", + "embedding_dim", + "tombstoned_at", +] + + +def _symbol( + org: str, ns: str, symbol_id: str, doc: str, *, tier: str = "treesitter", path: str = "a/x.py" +) -> list[Any]: + return [org, ns, tier, f"mod.{symbol_id}", symbol_id, symbol_id, "function", path, doc, None] + + +def _chunk( + org: str, + ns: str, + path: str, + start: int, + text: str, + symbol_ids: list[str], + *, + tombstoned_at: dt.datetime | None = None, + kind: str = "function", + embedded: bool = True, +) -> list[Any]: + dim = settings.embedding_dim + return [ + org, + ns, + "m", + path, + uuid.uuid4(), + kind, + start, + start + 9, + text, + text, + symbol_ids, + [0.5] * dim, + dim if embedded else 0, + tombstoned_at, + ] + + +@pytest.mark.asyncio +async def test_calibration_units_read_documented_functions_from_real_rows( + ch_client: Any, +) -> None: + org, ns = unique_org("calib-units"), "units" + ch_client.insert( + "loom.code_symbols", + [ + _symbol(org, ns, "sum_rows", "Sum each row."), + _symbol(org, ns, "merge_parts", "Merge two parts."), + _symbol(org, ns, "bare", ""), + # another tier's row under the same id must not change the drawn doc + _symbol(org, ns, "bare", "A doc only the SCIP tier carries.", tier="scip"), + # documented, but with no embedded function chunk + _symbol(org, ns, "outline", "Draw the outline of each class."), + _symbol(org, ns, "stub", "Return the value of the stub."), + # a test function is never a probe, so it must not use up the read's limit + _symbol(org, ns, "check_sums", "Check that each row sums.", path="tests/test_sum.py"), + _symbol( + org, ns, "check_merge", "Check that two parts merge.", path="pkg/test_merge.py" + ), + ], + column_names=_SYMBOL_COLUMNS, + ) + ch_client.insert( + "loom.code_chunks", + [ + _chunk(org, ns, "a/sum.py", 1, "sum head", ["sum_rows"]), + # an oversized function is stored as several chunks of one symbol: only the first + # piece answers the doc comment + _chunk(org, ns, "a/sum.py", 40, "sum tail", ["sum_rows"]), + _chunk(org, ns, "a/sum.py", 80, "sum last", ["sum_rows"]), + _chunk(org, ns, "a/merge.py", 1, "merge", ["merge_parts"]), + _chunk(org, ns, "a/bare.py", 1, "bare", ["bare"]), + # a nested function's chunk belongs to its own symbol, not to the documented outer one + _chunk(org, ns, "a/nested.py", 1, "nested", ["bare", "merge_parts"]), + _chunk(org, ns, "a/klass.py", 1, "klass", ["outline"], kind="class_skeleton"), + _chunk(org, ns, "a/stub.py", 1, "stub", ["stub"], embedded=False), + _chunk(org, ns, "tests/test_sum.py", 1, "check", ["check_sums"]), + _chunk(org, ns, "pkg/test_merge.py", 1, "check merge", ["check_merge"]), + _chunk( + org, + ns, + "a/gone.py", + 1, + "gone", + ["merge_parts"], + tombstoned_at=dt.datetime(2026, 1, 1), + ), + ], + column_names=_CHUNK_COLUMNS, + ) + + await get_client().connect() + units = await CodeRepo().calibration_units(org, ns, "m", limit=10) + pool = await CodeRepo().calibration_pool(org, ns, "m", limit=10) + + assert sorted((u["path"], u["context_text"], u["doc"], u["name"]) for u in units) == [ + ("a/merge.py", "merge", "Merge two parts.", "merge_parts"), + ("a/sum.py", "sum head", "Sum each row.", "sum_rows"), + ] + assert sorted(p["path"] for p in pool) == [ + "a/bare.py", + "a/merge.py", + "a/nested.py", + "a/sum.py", + "a/sum.py", + "a/sum.py", + "pkg/test_merge.py", + "tests/test_sum.py", + ] diff --git a/tests/unit/snapshots/settings_defaults.json b/tests/unit/snapshots/settings_defaults.json index 8806a7cec98..ed6a5ca548e 100644 --- a/tests/unit/snapshots/settings_defaults.json +++ b/tests/unit/snapshots/settings_defaults.json @@ -138,6 +138,7 @@ "code_bootstrap_mirror_refresh_s": 5.0, "code_bootstrap_mirror_retry_s": 60.0, "code_bot_authors": "", + "code_calibrate_probes": 200, "code_calibration_enabled": false, "code_calibration_interval_seconds": 3600, "code_callers_candidate_min_confidence": 0.2, diff --git a/tests/unit/test_code_calibration_parameter_bounds.py b/tests/unit/test_code_calibration_parameter_bounds.py new file mode 100644 index 00000000000..2cb8580c502 --- /dev/null +++ b/tests/unit/test_code_calibration_parameter_bounds.py @@ -0,0 +1,111 @@ +"""`code.calibrate` at its supported maximum: every read fits one HTTP form field. + +`code_calibrate_probes` is bounded at 1,000, and `_namespace_probes` asks the store +for five documented functions per probe. At the ceiling that is 5,000 symbol ids. +Bound as one `{ids:Array(String)}` parameter they would be 5,000 x 36 bytes ≈ +180,000 bytes in a single form field, over ClickHouse's default +`http_max_field_value_size` of 128 KiB, which the server refuses with "Field value +too long". + +The fake below refuses a bound parameter the way the server does, and answers the +documented-symbol, unit and pool reads from one fixture. +""" + +from __future__ import annotations + +from types import SimpleNamespace +from typing import Any + +import pytest +from annotated_types import Le +from clickhouse_connect.driver.binding import format_bind_value + +from server.code.store.index import CodeRepo +from server.settings.catalog import CodeSettings + +_HTTP_FIELD_BYTES = 128 * 1024 +# The setting's ceiling, and the five documented functions `_namespace_probes` reads a probe. +_MAX_PROBES = next( + bound.le + for bound in CodeSettings.model_fields["code_calibrate_probes"].metadata + if isinstance(bound, Le) +) +_DOCUMENTED = _MAX_PROBES * 5 + + +class _BoundedCH: + """ClickHouse's HTTP field limit, and the three reads `code.calibrate` makes.""" + + def __init__(self, documented: int) -> None: + self.symbols = [ + (f"{i:032x}", f"Return the total weight of bucket {i} now.") for i in range(documented) + ] + # A draw order the server's `cityHash64(chunk_id)` would give: fixed, and not + # the id order, so a merge that keeps chunk order instead of the hash fails. + self.draw = {s: (i * 7919) % documented for i, (s, _) in enumerate(self.symbols)} + self.paths = {s: f"src/d{i % 4}/m{i}.py" for i, (s, _) in enumerate(self.symbols)} + self.docs = dict(self.symbols) + + async def query_all(self, sql: str, params: dict[str, Any]) -> list[dict[str, Any]]: + for name, value in params.items(): + size = len(format_bind_value(value).encode()) + assert size <= _HTTP_FIELD_BYTES, ( + f"param {name} is {size} bytes, over ClickHouse's " + f"{_HTTP_FIELD_BYTES}-byte http_max_field_value_size" + ) + if "FROM loom.code_symbols" in sql: + rows = self.symbols[: params["limit"]] + return [{"symbol_id": s, "name": "weight", "doc": d} for s, d in rows] + if "symbol_ids[1] IN" in sql: + rows = [ + { + "path": self.paths[s], + "context_text": f"{self.paths[s]} · src/d · symbol {s}", + "symbol_id": s, + "draw": self.draw[s], + } + for s in params["ids"] + ] + return rows # in id order: the merge sorts on the draw + assert "context_text" in sql # the pool read + return [ + {"path": self.paths[s], "context_text": f"{self.paths[s]} · src/d · symbol {s}"} + for s, _ in self.symbols[: params["limit"]] + ] + + +@pytest.mark.asyncio +async def test_calibration_units_at_the_supported_maximum_fit_one_form_field() -> None: + ch = _BoundedCH(_DOCUMENTED) + repo = CodeRepo(ch) # type: ignore[arg-type] + units = await repo.calibration_units("org", "ns", "m", limit=_DOCUMENTED) + pool = await repo.calibration_pool("org", "ns", "m", limit=_DOCUMENTED) + + # Every documented symbol was read, in the draw order the merge must preserve. + text_of = {s: f"{ch.paths[s]} · src/d · symbol {s}" for s, _ in ch.symbols} + symbol_of = {text: s for s, text in text_of.items()} + assert len(units) == _DOCUMENTED + assert len(pool) == _DOCUMENTED + assert [ch.draw[symbol_of[u["context_text"]]] for u in units] == sorted(ch.draw.values()) + assert [u["doc"] for u in units] == [ch.docs[symbol_of[u["context_text"]]] for u in units] + + +@pytest.mark.asyncio +async def test_namespace_probes_at_the_supported_maximum_are_read_and_sampled( + monkeypatch: pytest.MonkeyPatch, +) -> None: + from server.code.app import admin + from server.core import ch as ch_module + from server.embedding import embedder as embedder_module + from server.settings import settings + + ch = _BoundedCH(_DOCUMENTED) + monkeypatch.setattr(ch_module, "get_client", lambda: ch) + monkeypatch.setattr( + embedder_module, "get_embedder", lambda: SimpleNamespace(model_name="probe-test-embedder") + ) + monkeypatch.setattr(settings, "code_calibrate_probes", _MAX_PROBES) + + probes = await admin._namespace_probes("org", "ns") + + assert (len(probes.positives), len(probes.distractors)) == (_MAX_PROBES, _MAX_PROBES) diff --git a/tests/unit/test_code_calibration_probes.py b/tests/unit/test_code_calibration_probes.py new file mode 100644 index 00000000000..e0ba8458bb7 --- /dev/null +++ b/tests/unit/test_code_calibration_probes.py @@ -0,0 +1,576 @@ +"""code.calibrate's probes come from the namespace's own documented units.""" + +from __future__ import annotations + +import json +import math +from types import SimpleNamespace +from unittest.mock import AsyncMock + +import pytest + +from server.code.app.index.ingest_parse import parse_for_ingest +from server.code.domain.calibration_probes import ( + Unit, + probe_query, + sample_probes, + stratum, + without_doc, +) +from server.code.domain.extract.chunker import chunk_file +from server.code.domain.index.test_gate import TEST_PATH_PATTERN + + +def test_probe_query_reads_the_first_paragraph_of_a_python_docstring() -> None: + doc = "Apply repetition penalties to the logits.\n\n Args:\n logits: scores" + assert probe_query(doc) == "Apply repetition penalties to the logits." + + +def test_probe_query_strips_cpp_comment_leaders_and_brief_tags() -> None: + doc = "/**\n * @brief Batch version of swap_blocks: copies N independent\n * triples in one call.\n *\n * Thin wrapper.\n */" + assert ( + probe_query(doc) + == "Batch version of swap_blocks: copies N independent triples in one call." + ) + assert probe_query( + "// Floats ordered as unsigned integers, so a larger float\n// gives a larger key." + ) == ("Floats ordered as unsigned integers, so a larger float gives a larger key.") + + +def test_probe_query_refuses_what_does_not_describe_the_unit() -> None: + assert probe_query("Returns the size.") == "" # too short to read as a question + assert probe_query("TODO: split this function into two parts") == "" + assert ( + probe_query("// namespace kernels\n// taken from\n// https://github.com/x/y/blob/z") == "" + ) + assert probe_query("@param a the first operand of it") == "" + # a namespace-closing comment above the function's own is not part of the query + assert probe_query("// namespace\n// Conv stage of the linear attention path.") == ( + "Conv stage of the linear attention path." + ) + assert probe_query("// end namespace kernels\n// Conv stage of the linear attention path.") == ( + "Conv stage of the linear attention path." + ) + assert probe_query("End the span and record its duration.") == ( + "End the span and record its duration." + ) + assert probe_query('r"""Applies a 1D convolution over the input signal.') == ( + "Applies a 1D convolution over the input signal." + ) + + +def test_probe_query_drops_the_name_a_go_doc_comment_opens_with() -> None: + doc = "// ParseConfig reads the file at path into a Config." + assert probe_query(doc, "ParseConfig") == "reads the file at path into a Config." + # a name later in the sentence is part of the description + assert probe_query("// Load the file and return a Config.", "Config") == ( + "Load the file and return a Config." + ) + + +def test_probe_query_keeps_a_glob_that_ends_a_line() -> None: + # The block-comment closer is the two characters `*/`, not a set of characters: + # a description that ends in `testdata/*` keeps its glob. + doc = "/**\n * Load every fixture listed in testdata/*\n */" + assert probe_query(doc) == "Load every fixture listed in testdata/*" + # The closer still comes off, with or without a space before it. + assert probe_query("/* Load every fixture listed in testdata/* */") == ( + "Load every fixture listed in testdata/*" + ) + assert probe_query("/* Load every fixture listed in testdata */") == ( + "Load every fixture listed in testdata" + ) + + +def test_probe_query_cuts_a_long_paragraph_to_a_sentence_of_words() -> None: + assert len(probe_query(" ".join(["word"] * 80)).split()) == 32 + + +def test_without_doc_removes_the_query_from_its_positive() -> None: + doc = "Compute the RMS norm of each row in place." + text = ( + "csrc/norm.py · csrc\nnorm::rms(x)\n---\n" + 'def rms(x):\n """Compute the RMS norm of each row in place."""\n return x / x.norm()\n' + ) + stripped = without_doc(text, doc) + assert "Compute the RMS norm" not in stripped + assert stripped.startswith("csrc/norm.py · csrc\nnorm::rms(x)\n---\ndef rms(x):") + assert "return x / x.norm()" in stripped + + +def test_without_doc_removes_a_multi_line_cpp_comment() -> None: + doc = "// Load elements and compute\n// the sum of squares." + text = "a.cpp · a.cpp\nf()\n---\n// Load elements and compute\n// the sum of squares.\nvoid f() {}\n" + assert without_doc(text, doc) == "a.cpp · a.cpp\nf()\n---\nvoid f() {}" + + +def test_without_doc_removes_every_copy_of_a_multi_paragraph_docstring() -> None: + # The chunk carries the docstring ahead of the declaration and inside it. + doc = "Get the port from the environment.\n\n Returns:\n The port, or None." + text = ( + "tools/envs.py · tools\nenvs::port()\n---\n" + "Get the port from the environment.\n\n Returns:\n The port, or None.\n" + 'def port():\n """Get the port from the environment.\n\n Returns:\n' + ' The port, or None.\n """\n return 1\n' + ) + stripped = without_doc(text, doc) + assert "Get the port" not in stripped + assert "The port, or None" not in stripped + assert stripped.endswith("def port():\n return 1") + + +def test_without_doc_ignores_comment_lines_without_words() -> None: + doc = "#\n# Determine the number of compile jobs.\n#" + text = "setup.py · setup.py\njobs()\n---\n#\n# Determine the number of compile jobs.\n#\n def jobs(self):\n # keep\n" + stripped = without_doc(text, doc) + assert "Determine" not in stripped + assert "# keep" in stripped + + +def _chunked(path: str, source: str, name: str = "total") -> tuple[str, str]: + """The text a function's chunk is embedded from, and its parsed doc comment.""" + parsed, error = parse_for_ingest(path, source.encode()) + assert parsed is not None and not error + symbol = next(s for s in parsed.symbols if s.name == name and s.kind == "function") + chunk = next(c for c in chunk_file(parsed) if symbol.id in c.symbol_ids) + return f"{path} · x\n{name}()\n---\n{chunk.content}", symbol.doc_comment + + +_SUM = "Return the sum of both page counts." +_Q3 = "'" * 3 + + +@pytest.mark.parametrize( + ("path", "source", "kept"), + [ + # the doc shares its source line with the declaration and the body + ("a.py", f'def total(): """{_SUM}"""; return 123 + 456\n', "def total(): return 123 + 456"), + ( + "a.py", + f'def total():\n """{_SUM}"""; return 123 + 456\n', + "def total():\n return 123 + 456", + ), + ( + "a.py", + 'def total():\n """Return the sum of\n both page counts."""; return 1\n', + "def total():\n return 1", + ), + ( + "a.py", + f"def total():\n {_Q3}{_SUM}{_Q3} ; x = 1\n return x\n", + "def total():\n x = 1\n return x", + ), + ( + "a.cpp", + f"/* {_SUM} */ int total() {{ return 123 + 456; }}\n", + "int total() { return 123 + 456; }", + ), + ( + "a.cpp", + f"/// {_SUM}\nint total() {{ return 123 + 456; }}\n", + "int total() { return 123 + 456; }", + ), + ( + "a.cpp", + f"// {_SUM}\nint total() {{ return 123 + 456; }}\n", + "int total() { return 123 + 456; }", + ), + ( + "a.cpp", + f"/**\n * {_SUM}\n */\nint total() {{ return 123 + 456; }}\n", + "int total() { return 123 + 456; }", + ), + ( + "a.ts", + f"/** {_SUM} */ function total() {{ return 123 + 456; }}\n", + "function total() { return 123 + 456; }", + ), + ( + "a.ts", + f"/** {_SUM} */\nfunction total() {{ return 123 + 456; }}\n", + "function total() { return 123 + 456; }", + ), + ( + "a.go", + "// total returns the sum of both page counts.\nfunc total() int { return 123 + 456 }\n", + "func total() int { return 123 + 456 }", + ), + ( + "a.rs", + f"/// {_SUM}\nfn total() -> u32 {{ 123 + 456 }}\n", + "fn total() -> u32 { 123 + 456 }", + ), + ], + ids=[ + "py-one-line", + "py-docstring-line", + "py-two-line-docstring", + "py-single-quotes", + "cpp-block-one-line", + "cpp-triple-slash", + "cpp-double-slash", + "cpp-javadoc-block", + "ts-jsdoc-one-line", + "ts-jsdoc-above", + "go", + "rust", + ], +) +def test_without_doc_keeps_the_code_a_one_line_function_shares_with_its_doc( + path: str, source: str, kept: str +) -> None: + # A chunk's text goes through the parser and the chunker, which prepend the doc to + # the body: only the doc text, never a source line that holds more, comes out. + text, doc = _chunked(path, source) + assert without_doc(text, doc) == f"{path} · x\ntotal()\n---\n{kept}" + + +def test_without_doc_keeps_a_multi_line_docstring_apart_from_the_code_around_it() -> None: + source = ( + "def total(a, b):\n" + ' """Return the sum of both page counts.\n\n' + " Args:\n a: pages of the first.\n b: pages of the second.\n" + ' """\n' + " return a + b\n" + ) + text, doc = _chunked("a.py", source) + assert without_doc(text, doc) == "a.py · x\ntotal()\n---\ndef total(a, b):\n return a + b" + + +def _unit(path: str, n: int) -> Unit: + return Unit( + path=path, + context_text=f'{path} · x\nf{n}()\n---\ndef f{n}():\n """Describe unit number {n} of {path} well."""\n', + doc_comment=f"Describe unit number {n} of {path} well.", + ) + + +def test_sample_probes_spreads_across_strata() -> None: + units = [_unit(f"src/big/m{i}.py", i) for i in range(50)] + units += [_unit("src/small/one.py", 99), _unit("csrc/kern/k.cpp", 98)] + probes = sample_probes("ns", units, units, size=6) + paths = {p for q, p in probes.positives} + assert len(probes.positives) == 6 + assert probes.strata == 3 + assert any("src/small/one.py" in p for p in paths) + assert any("csrc/kern/k.cpp" in p for p in paths) + assert all(q not in p for q, p in probes.positives) + + +def test_sample_probes_draws_each_distractor_from_another_stratum() -> None: + units = [_unit("src/a/x.py", 1), _unit("src/a/y.py", 2)] + pool = [*units, _unit("lib/b/z.py", 3)] + probes = sample_probes("ns", units, pool, size=2) + assert len(probes.distractors) == 2 + assert all(d.startswith("lib/b/z.py") for _, d in probes.distractors) + + +def test_sample_probes_draws_from_another_file_when_the_namespace_has_one_stratum() -> None: + units = [_unit("src/a/x.py", 1), _unit("src/a/y.py", 2)] + probes = sample_probes("ns", units, units, size=2) + assert len(probes.distractors) == 2 + for (_, positive), (_, distractor) in zip(probes.positives, probes.distractors, strict=True): + assert positive.split(" ")[0] != distractor.split(" ")[0] + + +def test_sample_probes_parses_each_unit_path_once_not_once_per_probe(monkeypatch) -> None: + """Grouping the pool again for every probe would parse size x pool paths: + seconds of blocked event loop at the 1,000-probe bound.""" + from server.code.domain import calibration_probes + + calls = 0 + real = calibration_probes.stratum + + def counting(path: str) -> tuple[str, str]: + nonlocal calls + calls += 1 + return real(path) + + monkeypatch.setattr(calibration_probes, "stratum", counting) + units = [_unit(f"src/d{i % 40}/m{i}.py", i) for i in range(40)] + pool = [_unit(f"src/p{i % 25}/n{i}.py", 1000 + i) for i in range(200)] + probes = sample_probes("ns", units, pool, size=40) + assert len(probes.distractors) == len(probes.positives) > 0 + assert calls <= 3 * (len(units) + len(pool) + 40) + + +def test_sample_probes_is_stable_per_namespace() -> None: + units = [_unit(f"src/d{i % 7}/m{i}.py", i) for i in range(200)] + assert sample_probes("ns", units, units, size=20) == sample_probes("ns", units, units, size=20) + + +def test_stratum_is_language_and_component() -> None: + assert stratum("csrc/moe/kernels/topk.cpp") == (".cpp", "csrc/moe") + assert stratum("setup.py") == (".py", "") + + +def _vec(cosine: float) -> list[float]: + # a unit vector at `cosine` to the query vector [1, 0, 0] + return [cosine, math.sqrt(1.0 - cosine * cosine), 0.0] + + +class _Embedder: + """Queries embed to [1, 0, 0]; a namespace unit (`src/`) sits at `answer` to them, + anything else at `other`.""" + + model_name = "probe-test-embedder" + answer, other = 0.7, 0.2 + + async def embed(self, text: str) -> list[float]: + return [1.0, 0.0, 0.0] + + async def embed_many(self, texts: list[str]) -> list[list[float]]: + return [_vec(self.answer if t.startswith("src/") else self.other) for t in texts] + + +def _documented(n: int) -> list[dict[str, str]]: + return [ + { + "path": f"src/d{i % 4}/m{i}.py", + "context_text": ( + f"src/d{i % 4}/m{i}.py · src/d{i % 4}\nm{i}::weight()\n---\n" + f'def weight():\n """Return the total weight of bucket {i} now."""\n' + ), + "doc": f"Return the total weight of bucket {i} now.", + "name": "weight", + } + for i in range(n) + ] + + +def _pool(n: int) -> list[dict[str, str]]: + return [ + {"path": f"lib/p{i}.cpp", "context_text": f"lib/p{i}.cpp · lib\ng{i}()"} for i in range(n) + ] + + +def _calibrate_with(monkeypatch, documented, pool, *, size=24): + from server.code.app import admin + from server.settings import settings + + reads: list[tuple[str, str, str, str, int]] = [] + + class Repo: + async def calibration_units(self, org, ns, model, *, limit: int): + reads.append(("units", org, ns, model, limit)) + return documented + + async def calibration_pool(self, org, ns, model, *, limit: int): + reads.append(("pool", org, ns, model, limit)) + return pool + + insert = AsyncMock() + monkeypatch.setattr("server.core.ch.get_client", lambda: SimpleNamespace(insert=insert)) + monkeypatch.setattr("server.embedding.embedder.get_embedder", _Embedder) + monkeypatch.setattr(admin, "CodeRepo", Repo) + monkeypatch.setattr(admin, "require_code_intel", lambda: None) + monkeypatch.setattr(admin, "resolve_code_identity", lambda *args: ("org", "team")) + monkeypatch.setattr(settings, "code_calibrate_probes", size) + return admin, reads, insert + + +async def test_code_calibrate_samples_the_namespace(monkeypatch, tmp_path) -> None: + from server.code.api.models_ingest import CodeCalibrateInput + + admin, reads, insert = _calibrate_with(monkeypatch, _documented(40), _pool(40)) + # the fixed corpus is not read when the namespace has enough probes + monkeypatch.setattr(admin, "_PROBES_PATH", tmp_path / "absent.jsonl") + result = await admin.handle_code_calibrate(CodeCalibrateInput()) + assert reads == [ + ("units", "org", "team", "probe-test-embedder", 120), + ("pool", "org", "team", "probe-test-embedder", 120), + ] + assert (result.probe_source, result.positives, result.distractors) == ("namespace", 24, 24) + assert result.strata == 4 + # distractors at 0.2: noise floor 0.22, abstain 0.27; positives at 0.7 + assert result.noise_floor == pytest.approx(0.22) + assert result.abstain_threshold == pytest.approx(0.27) + assert result.rerank_skip_above == pytest.approx(0.7) + row = insert.call_args.args[1][0] + assert (row["org"], row["namespace"], row["distractor_pairs_n"]) == ("org", "team", 24) + + +async def test_code_calibrate_caps_abstain_at_the_probes_p10( + monkeypatch, +) -> None: + """Units of one repository share its vocabulary, so an unrelated unit can score + close to the right one. The abstain threshold then stays at the answers' 10th + percentile instead of rising above most of them.""" + from server.code.api.models_ingest import CodeCalibrateInput + + admin, _, _ = _calibrate_with(monkeypatch, _documented(40), _pool(40)) + monkeypatch.setattr(_Embedder, "answer", 0.55) + monkeypatch.setattr(_Embedder, "other", 0.52) + result = await admin.handle_code_calibrate(CodeCalibrateInput()) + # distractor p90 0.52 alone would put abstain at 0.59, above every answer + assert result.abstain_threshold == pytest.approx(0.55) + assert result.noise_floor == pytest.approx(0.50) + assert result.noise_floor <= result.abstain_threshold <= result.rerank_skip_above + + +def _refuses_over_300_tokens(text: str) -> None: + from server.embedding._provider import check_size + + check_size(text, 300, "probe-test-embedder") # a provider that states its limit + + +def _refuses_over_1500_chars(text: str) -> None: + # an OpenAI-compatible server that states none and answers 413 + if len(text) > 1500: + raise RuntimeError("Client error '413 Payload Too Large' for url 'http://embed/v1'") + + +@pytest.mark.parametrize("refuse", [_refuses_over_300_tokens, _refuses_over_1500_chars]) +async def test_code_calibrate_shrinks_each_probe_text_the_provider_refuses_as_too_long( + monkeypatch, refuse +) -> None: + """A refused chunk would fail the phase on every rerun of the same draw; the probe + halves it as ingest did before storing its vector.""" + from server.code.api.models_ingest import CodeCalibrateInput + + class _Limited(_Embedder): + async def embed_many(self, texts: list[str]) -> list[list[float]]: + for text in texts: + refuse(text) + return await super().embed_many(texts) + + body = " total += 1\n" * 400 # a 6,000-character chunk, the default chunk size + documented = [dict(r, context_text=r["context_text"] + body) for r in _documented(40)] + pool = [dict(r, context_text=r["context_text"] + body) for r in _pool(40)] + admin, _, _ = _calibrate_with(monkeypatch, documented, pool) + monkeypatch.setattr("server.embedding.embedder.get_embedder", _Limited) + result = await admin.handle_code_calibrate(CodeCalibrateInput()) + assert (result.probe_source, result.positives, result.distractors) == ("namespace", 24, 24) + assert result.abstain_threshold == pytest.approx(0.27) + + +async def test_code_calibrate_clips_each_probe_text_as_ingest_did(monkeypatch) -> None: + """Ingest embeds a chunk over `EMBED_MAX_CHARS` by its head; the probe measures that + head, not a halving of the whole stored text.""" + from server.code.api.models_ingest import CodeCalibrateInput + from server.code.app.index.embed_text import EMBED_MAX_CHARS + + sent: list[int] = [] + + class _Recording(_Embedder): + async def embed_many(self, texts: list[str]) -> list[list[float]]: + sent.extend(len(t) for t in texts) + return await super().embed_many(texts) + + body = " total += 1\n" * 2000 # 30,000 characters, a raised `code_chunk_max_chars` + documented = [dict(r, context_text=r["context_text"] + body) for r in _documented(40)] + pool = [dict(r, context_text=r["context_text"] + body) for r in _pool(40)] + admin, _, _ = _calibrate_with(monkeypatch, documented, pool) + monkeypatch.setattr("server.embedding.embedder.get_embedder", _Recording) + result = await admin.handle_code_calibrate(CodeCalibrateInput()) + assert result.probe_source == "namespace" + assert sent and max(sent) == EMBED_MAX_CHARS + + +async def test_code_calibrate_names_an_unbuilt_embedder_by_its_kind(monkeypatch) -> None: + from server.code.app import admin + from server.core.errors import ValidationError + from server.embedding import embedder + + def _unbuilt() -> None: + raise RuntimeError("connect to the embedding host refused") + + monkeypatch.setattr(embedder, "get_embedder", _unbuilt) + with pytest.raises(ValidationError) as raised: + await admin._namespace_probes("org", "team") + assert raised.value.message == "embedder unavailable: RuntimeError" + + +def _fixture_corpus(tmp_path): + corpus = tmp_path / "probes.jsonl" + corpus.write_text( + "\n".join( + json.dumps({"query": f"q{i}", "positive": f"src/c{i}", "distractor": f"x{i}"}) + for i in range(6) + ) + ) + return corpus + + +async def test_code_calibrate_falls_back_to_the_fixture_for_a_small_namespace( + monkeypatch, tmp_path +) -> None: + from server.code.api.models_ingest import CodeCalibrateInput + + admin, reads, _ = _calibrate_with(monkeypatch, _documented(5), _pool(40)) + monkeypatch.setattr(admin, "_PROBES_PATH", _fixture_corpus(tmp_path)) + result = await admin.handle_code_calibrate(CodeCalibrateInput()) + assert (result.probe_source, result.positives, result.distractors) == ("fixture", 6, 6) + assert result.strata == 0 + # under 20 documented units the fallback is certain: the pool is not read + assert [read[0] for read in reads] == ["units"] + + +@pytest.mark.parametrize( + "documented", + [ + # one file: no distractor can come from another file + [dict(r, path="src/d0/m.py") for r in _documented(40)], + # doc comments that do not describe their unit + [dict(r, doc=f"TODO: weigh bucket {i} again") for i, r in enumerate(_documented(40))], + ], + ids=["one-file", "no-usable-doc-comment"], +) +async def test_code_calibrate_falls_back_to_the_fixture_after_sampling( + monkeypatch, tmp_path, documented +) -> None: + """Enough documented units to read the pool, too few usable probes to keep.""" + from server.code.api.models_ingest import CodeCalibrateInput + + admin, reads, _ = _calibrate_with(monkeypatch, documented, documented) + monkeypatch.setattr(admin, "_PROBES_PATH", _fixture_corpus(tmp_path)) + result = await admin.handle_code_calibrate(CodeCalibrateInput()) + assert (result.probe_source, result.positives, result.distractors) == ("fixture", 6, 6) + assert [read[0] for read in reads] == ["units", "pool"] + + +async def test_calibration_units_pair_each_documented_chunk_with_its_doc_comment() -> None: + from server.code.store.index import CodeRepo + from tests.unit.ch_fake import RecordingCH + + text = "a/x.py · a\nf()\n---\ndef f():\n pass\n" + ch = RecordingCH() + ch.on("FROM loom.code_symbols", [{"symbol_id": "s1", "name": "f", "doc": "Sum each row."}]) + ch.on( + "symbol_ids[1] IN", + [{"path": "a/x.py", "context_text": text, "symbol_id": "s1", "draw": 3}], + ) + ch.on("SELECT path, context_text", [{"path": "b/y.py", "context_text": "b"}]) + units = await CodeRepo(ch).calibration_units("org", "ns", "m", limit=10) + pool = await CodeRepo(ch).calibration_pool("org", "ns", "m", limit=7) + assert units == [{"path": "a/x.py", "context_text": text, "doc": "Sum each row.", "name": "f"}] + assert pool == [{"path": "b/y.py", "context_text": "b"}] + docs, chunks, others = ch.calls + assert docs.params == { + "org": "org", + "ns": "ns", + "limit": 10, + "test_path_pattern": TEST_PATH_PATTERN, + } + assert (chunks.params["ids"], chunks.params["model"]) == (["s1"], "m") + assert (others.params["model"], others.params["limit"]) == ("m", 7) + + +def test_code_calibrate_probes_is_bounded() -> None: + from pydantic import ValidationError + + from server.settings.catalog import CodeSettings + + for bad in (-1, 0, 19, 1001): + with pytest.raises(ValidationError): + CodeSettings(code_calibrate_probes=bad) + assert CodeSettings(code_calibrate_probes=20).code_calibrate_probes == 20 + assert CodeSettings(code_calibrate_probes=1000).code_calibrate_probes == 1000 + + +def test_the_probe_fields_are_optional_in_the_reply() -> None: + # A replica on the build before this one answers without them. + from server.code.api.models_ingest import CodeCalibrateOutput + + required = CodeCalibrateOutput.model_json_schema()["required"] + assert "probe_source" not in required and "strata" not in required diff --git a/tests/unit/test_code_calibration_worker.py b/tests/unit/test_code_calibration_worker.py index 4bcd1ee56a9..058ac825c45 100644 --- a/tests/unit/test_code_calibration_worker.py +++ b/tests/unit/test_code_calibration_worker.py @@ -12,6 +12,7 @@ import pytest +from server.code.api.models_ingest import CodeCalibrateOutput from server.code.app import admin from server.code.app.index import erasing from server.code.domain.index import repos as repos_mod @@ -24,6 +25,16 @@ ORG = "acme" SERVED = "m-new" +REPLY = CodeCalibrateOutput( + noise_floor=0.2, + abstain_threshold=0.25, + rerank_skip_above=0.7, + embedder_model=SERVED, + positives=24, + distractors=24, + probe_source="namespace", + strata=4, +) class _Cfg: @@ -111,12 +122,13 @@ def __init__(self) -> None: def world(monkeypatch: pytest.MonkeyPatch) -> Iterator[_World]: out = _World() - async def calibrate(org: str, ns: str) -> None: + async def calibrate(org: str, ns: str) -> CodeCalibrateOutput: out.calibrated.append(ns) if ns in out.cancelled: raise asyncio.CancelledError if out.fail or ns in out.failing: raise RuntimeError("probe failed") + return REPLY async def no_erasure(org: str, ns: str) -> bool: return False @@ -367,9 +379,10 @@ async def test_a_bare_label_row_the_worker_refreshed_reads_as_missing_after_a_wi rows = {"a": SERVED} _namespaces(monkeypatch, {"a": (0, 5)}, rows) - async def calibrate(org: str, ns: str) -> None: + async def calibrate(org: str, ns: str) -> CodeCalibrateOutput: world.calibrated.append(ns) rows[ns] = _stored(SERVED) # what persist_namespace_calibration writes + return REPLY monkeypatch.setattr(admin, "calibrate_namespace", calibrate) assert await ec.get_namespace_calibration(ORG, "a") is not None diff --git a/tests/unit/test_code_ingest_errors.py b/tests/unit/test_code_ingest_errors.py index 47eff52b5ec..95ed473e8c1 100644 --- a/tests/unit/test_code_ingest_errors.py +++ b/tests/unit/test_code_ingest_errors.py @@ -251,7 +251,7 @@ def test_clip_for_embedding_uses_the_token_counter() -> None: @pytest.mark.asyncio async def test_embed_shrinking_halves_on_provider_length_rejection() -> None: - from server.code.app.index.embed_text import embed_shrinking + from server.embedding.documents import embed_shrinking calls: list[int] = [] @@ -270,9 +270,34 @@ async def embed_many(self, texts: list[str]) -> list[list[float]]: assert calls[0] == 20_000 and calls[-1] <= 3_000 and len(calls) <= 5 +@pytest.mark.asyncio +async def test_embed_shrinking_raises_a_rate_limit_that_names_tokens_without_shrinking() -> None: + import httpx + + from server.embedding.documents import embed_shrinking + + calls: list[int] = [] + request = httpx.Request("POST", "https://api.openai.com/v1/embeddings") + response = httpx.Response(429, request=request) + + class _E: + async def embed_many(self, texts: list[str]) -> list[list[float]]: + calls.append(len(texts[0])) + # the first line raise_for_status_with_detail gives OpenAI's TPM limit + raise httpx.HTTPStatusError( + "429 Too Many Requests from openai: type=tokens code=rate_limit_exceeded", + request=request, + response=response, + ) + + with pytest.raises(httpx.HTTPStatusError): + await embed_shrinking(_E(), "z" * 20_000) + assert calls == [20_000] + + @pytest.mark.asyncio async def test_embed_shrinking_propagates_other_errors() -> None: - from server.code.app.index.embed_text import embed_shrinking + from server.embedding.documents import embed_shrinking class _E: async def embed_many(self, texts: list[str]) -> list[list[float]]: diff --git a/tests/unit/test_embedder_calibration.py b/tests/unit/test_embedder_calibration.py index daf51737cb2..9e382001f35 100644 --- a/tests/unit/test_embedder_calibration.py +++ b/tests/unit/test_embedder_calibration.py @@ -11,6 +11,7 @@ from __future__ import annotations +import asyncio import json import math import random @@ -218,6 +219,13 @@ async def embed_many(self, texts): monkeypatch.setattr("server.core.ch.get_client", lambda: SimpleNamespace(insert=insert)) monkeypatch.setattr("server.embedding.embedder.get_embedder", Asymmetric) monkeypatch.setattr(admin, "_PROBES_PATH", corpus) + + class NoDocumentedUnits: + async def calibration_units(self, *args, **kwargs): + return [] + + # a namespace with no documented functions is calibrated on the fixed corpus + monkeypatch.setattr(admin, "CodeRepo", NoDocumentedUnits) monkeypatch.setattr(admin, "require_code_intel", lambda: None) monkeypatch.setattr(admin, "resolve_code_identity", lambda *args: ("org", "team")) result = await admin.handle_code_calibrate(CodeCalibrateInput()) @@ -282,6 +290,119 @@ async def test_per_ns_probe_defaults_to_module_question_fact_corpus(monkeypatch) assert r.question_fact_pairs_n == len(ec.QUESTION_FACT_PAIRS) +class _Counting(_HashEmbedder): + """Counts every embedding and the most in flight; `fail` raises on that text.""" + + def __init__(self, fail: str = "") -> None: + self.fail, self.calls, self.now, self.peak = fail, 0, 0, 0 + + async def embed(self, text: str) -> list[float]: + self.calls += 1 + self.now += 1 + self.peak = max(self.peak, self.now) + try: + await asyncio.sleep(0) + if text == self.fail: + raise RuntimeError("provider refused") + return await super().embed(text) + finally: + self.now -= 1 + + +async def test_probe_embeds_each_pair_once_with_its_calls_bounded(monkeypatch) -> None: + # Each pair sends two calls; 200 pairs gathered at once would hold 400 open. + embedder = _Counting() + monkeypatch.setattr("server.embedding.embedder.get_embedder", lambda: embedder) + positives = [(f"q{i}", f"d{i}") for i in range(200)] + r = await ec.calibrate_embedder( + paraphrase_pairs=positives, + distractor_pairs=[(f"q{i}", f"x{i}") for i in range(200)], + question_fact_pairs=positives, + paraphrase_pair_purpose="query_document", + ) + assert r is not None + assert embedder.peak == 16 + # two calls a pair; the positives, passed as both positive corpora, are embedded once + assert embedder.calls == 800 + + +async def test_a_failed_pair_stops_the_rest_of_its_phase(monkeypatch) -> None: + embedder = _Counting(fail="q0") + monkeypatch.setattr("server.embedding.embedder.get_embedder", lambda: embedder) + pairs = [(f"q{i}", f"d{i}") for i in range(200)] + assert await ec.calibrate_embedder(pairs, pairs, pairs) is None + for _ in range(1000): # a pair still running would start its call here + await asyncio.sleep(0) + # the 8 pairs in flight when the first one failed, and the one pair that took the + # slot it freed once its partner call was joined + assert embedder.calls <= 18 + + +class _PairStub: + """`fail` raises once the other text's call is in flight; every other call waits + until it is cancelled. `done` lists the calls that reached their cleanup.""" + + model_name = "pair-stub" + + def __init__(self, fail: str, other: str) -> None: + self.fail, self.other = fail, other + self.started = {fail: asyncio.Event(), other: asyncio.Event()} + self.done: list[str] = [] + + async def _call(self, text: str) -> list[float]: + self.started[text].set() + try: + if text == self.fail: + await self.started[self.other].wait() + raise RuntimeError("provider refused") + await asyncio.Event().wait() + return [1.0, 0.0] + finally: + self.done.append(text) + + async def embed(self, text: str) -> list[float]: + return await self._call(text) + + async def embed_many(self, texts: list[str]) -> list[list[float]]: + return [await self._call(texts[0])] + + +@pytest.mark.parametrize("fail", ["q0", "d0"], ids=["query-fails", "document-fails"]) +async def test_a_failed_call_cancels_and_joins_its_partner_before_calibration_returns( + monkeypatch, fail: str +) -> None: + # One call of a pair raises while the other is still on the provider: calibration + # must not return, and release its connections, before that call is cancelled. + embedder = _PairStub(fail, "d0" if fail == "q0" else "q0") + monkeypatch.setattr("server.embedding.embedder.get_embedder", lambda: embedder) + pairs = [("q0", "d0")] + result = await ec.calibrate_embedder( + pairs, pairs, pairs, paraphrase_pair_purpose="query_document" + ) + assert result is None + assert sorted(embedder.done) == ["d0", "q0"] + + +def test_the_answer_cap_moves_the_trigger_gates_with_the_floor() -> None: + answers = [0.40 + 0.02 * i for i in range(17)] # p10 0.432, p75 0.64 + r = ec.derive_thresholds(answers, answers, [0.62] * 20, embedder_model="m", cap_at_answers=True) + assert r.abstain_threshold == pytest.approx(r.question_fact_p10) + assert r.noise_floor == pytest.approx(r.question_fact_p10 - 0.05) + assert r.query_rewrite_threshold == pytest.approx(r.question_fact_p10) + assert r.rerank_skip_above == pytest.approx(r.question_fact_p75) + # the memory derivation keeps the distractors' floor, and its gates clamp to it + uncapped = ec.derive_thresholds(answers, answers, [0.62] * 20, embedder_model="m") + assert uncapped.abstain_threshold == pytest.approx(0.69) + assert uncapped.rerank_skip_above == pytest.approx(0.65) + + +def test_the_answer_cap_leaves_distractors_over_most_answers_without_a_scale() -> None: + answers = [0.40 + 0.01 * i for i in range(17)] # p75 0.52, under the distractors + r = ec.derive_thresholds(answers, answers, [0.60] * 20, embedder_model="m", cap_at_answers=True) + assert r.abstain_threshold == pytest.approx(0.67) + assert r.rerank_skip_above < r.abstain_threshold + + async def test_probe_failure_returns_none(monkeypatch) -> None: def _broken() -> None: raise RuntimeError("no embedder configured") diff --git a/tests/unit/test_workers_poll_the_work.py b/tests/unit/test_workers_poll_the_work.py index 6b86f70f166..16ac7146eec 100644 --- a/tests/unit/test_workers_poll_the_work.py +++ b/tests/unit/test_workers_poll_the_work.py @@ -409,11 +409,11 @@ async def embed_many(self, texts): async def _shrink(embedder, text): raise RuntimeError("provider down") - from server.code.app.index import embed_text + from server.embedding import documents from server.embedding import embedder as emb_mod monkeypatch.setattr(emb_mod, "get_embedder", lambda: _Down()) - monkeypatch.setattr(embed_text, "embed_shrinking", _shrink) + monkeypatch.setattr(documents, "embed_shrinking", _shrink) monkeypatch.setattr(settings, "code_embed_max_attempts", 2) stub = _chunk_stub("n1", 1, 5) stub["embed_attempts"] = 1