diff --git a/docs/architecture/code-index-architecture.md b/docs/architecture/code-index-architecture.md index 67baf34f75..a9c63d6d9f 100644 --- a/docs/architecture/code-index-architecture.md +++ b/docs/architecture/code-index-architecture.md @@ -602,6 +602,38 @@ index tokenizer. The score counts only whole app lexemes and rejects partial mat from the gate. Underscore-only lexemes use the exact score within the same tenant, model and path scope because the text index has no token for them. +For a question about the implementation, ranking multiplies the score of a test, +example or benchmark path and of a prose file by a penalty. A test word in the query +turns off the test-path penalty, the fan-in prior, the kind prior and saturation, and +leaves the prose penalty on. A doc word turns off the prose penalty only. + +The lexical leg cuts its pool on the same two penalties. Fusion gives a row of the leg +`1 / (60 + rank)`, and ranking multiplies that vote by the penalty of the row's path. A +pool of the leg's first 200 rows by rank therefore drops source rows whose vote counts +for more than the vote of the test and prose rows it keeps. The leg keeps the 200 rows +with the largest `penalty / (60 + rank)` instead: + +- **A row keeps its rank in the whole leg** and votes with it, so a row in the pool + scores what it would if the leg returned every row. A source row admitted from rank + 340 votes `1 / 400`. +- **A test or prose row leaves the pool only when 200 rows count for more.** The leg's + first-ranked test row votes `0.35 / 61`, as much as a source row at rank 114, and + stays. +- **Rows with one score rank by their penalty, the undemoted first.** The score is a + sum of idfs over the query words a chunk holds, so the rows of a one-word or + two-word query tie by the thousand, and ClickHouse returns equal rows in no fixed + order. Without the second key the order the table holds them in would decide which + of them are ranked first, and with them the pool. +- **The scan reads a bounded depth.** No row past rank `260 / f - 60` can be in the + pool, where `f` is the smallest factor a path can get: 2,912 rows for the default + penalties together, 980 for the prose penalty alone, at most 10,000. +- **Calibration does not read the cut.** The statement also returns the leg's own + first 200 rows, and leg agreement, the top similarity and abstention are computed on + those, as without the penalties. A penalty reaches them only as the order of rows + with one score. + +The vector leg and the concept leg are not cut. + After relevance ranking, per-file saturation spreads broad search results across files. It is skipped for an explicit path, a symbol route, test intent, or a code-shaped identifier named in the query that matches a qualified symbol diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index ad4b0edf21..4be55ea9f6 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -653,7 +653,7 @@ The code index's network git (clone, fetch, ls-remote, submodule update) through | Variable | Type | Default | Live | Meaning | | --- | --- | --- | --- | --- | | `LOOM_CODE_TRACE_LOG_ENABLED` | `bool` | `True` | | Fire-and-forget code_search_trace/code_search_outcome telemetry. | -| `LOOM_CODE_FUSION_SIGNALS` | `bool` | `True` | | Post-fusion rank priors in code.search (path-noise penalty, query↔path stem affinity, file coherence), applied after RRF and before the outcome boost. Kill switch. | +| `LOOM_CODE_FUSION_SIGNALS` | `bool` | `True` | | Rank priors in code.search (the test-path and prose penalties, query↔path stem affinity, file coherence), applied after RRF and before the outcome boost. The lexical leg also picks its candidates on the two path penalties, before RRF. Kill switch for both. | | `LOOM_CODE_SEARCH_QUERY_MAX_TOKENS` | `int` | `48` | | Long-question trim: past this many lexemes the question is treated as an issue body (template headings stripped, the rarest 32 tokens gate, the first 512 cleaned words embed). Under the cap nothing changes. 0 = off. | | `LOOM_CODE_SEARCH_FILE_SATURATION` | `float` | `0.5` | | Per-file saturation: the 2nd, 3rd... unit from one path is multiplied by decay^excess before the cut; a file's best unit never decays. 0 = off. Skipped under path_prefix, symbol routes and test intent. | | `LOOM_CODE_SEARCH_VECTOR_MODELS` | `str` | `''` | | CSV of vector-model specs a request may name as `vector_model` (e.g. "prefix:512:text-embedding-3-large"); only the vector leg switches. Empty = the override is refused. | @@ -686,7 +686,7 @@ The code index's network git (clone, fetch, ls-remote, submodule update) through | `LOOM_CODE_SEARCH_RERANK_TOP` | `int` | `20` | | How many fused units the default rerank reads. | | `LOOM_CODE_SEARCH_RERANK_EXCERPT_CHARS` | `int` | `300` | | Characters of each candidate shown to the default rerank (path and signature first, then the body head). | | `LOOM_CODE_SEARCH_CATALOGUE_PENALTY` | `float` | `1.0` | | Fusion multiplier for settings-catalogue units (Settings.cpp and kin) on the question kinds `code_search_catalogue_kinds` names; 1.0 = off. | -| `LOOM_CODE_SEARCH_PROSE_PENALTY` | `float` | `0.25` | | Fusion multiplier for prose files (documentation, release notes, changelogs) unless the query asks for documentation or the search is constrained to paths; 1.0 = off. | +| `LOOM_CODE_SEARCH_PROSE_PENALTY` | `float` | `0.25` | | Multiplier for prose files (documentation, release notes, changelogs) unless the query asks for documentation or the search is constrained to paths. The ranking multiplies the fused score by it, and the lexical leg picks its candidates on each row's vote times it, before RRF. A smaller value makes the lexical leg read deeper. 1.0 = off. | | `LOOM_CODE_SEARCH_KIND_PRIOR` | `'off' \| 'default' \| 'flat' \| 'structural'` | `'flat'` | | Chunk-kind ranking prior when the request names none: structural boosts the kind named by the question; flat/default apply fixed tables; off disables it. | | `LOOM_CODE_SEARCH_CATALOGUE_KINDS` | `str` | `'responsibility'` | | The question kinds `code_search_catalogue_penalty` applies to. | | `LOOM_CODE_FAN_IN_PRIOR_CAP` | `float` | `0.25` | | Cap of code.search's fan-in rank prior: score *= 1 + cap * log1p(fan_in) / log1p(max fan_in in the pool); skipped under test intent and on noise paths; inert without the stats. 0 = off. | diff --git a/loom.example.yaml b/loom.example.yaml index c7b5f1644b..6cdef8f928 100644 --- a/loom.example.yaml +++ b/loom.example.yaml @@ -1965,9 +1965,10 @@ settings: # Fire-and-forget code_search_trace/code_search_outcome telemetry. [restart] # code_trace_log_enabled: true - # Post-fusion rank priors in code.search (path-noise penalty, query↔path stem - # affinity, file coherence), applied after RRF and before the outcome boost. Kill - # switch. [restart] + # Rank priors in code.search (the test-path and prose penalties, query↔path stem + # affinity, file coherence), applied after RRF and before the outcome boost. The + # lexical leg also picks its candidates on the two path penalties, before RRF. Kill + # switch for both. [restart] # code_fusion_signals: true # Long-question trim: past this many lexemes the question is treated as an issue body @@ -2101,9 +2102,11 @@ settings: # question kinds `code_search_catalogue_kinds` names; 1.0 = off. [restart] # code_search_catalogue_penalty: 1.0 - # Fusion multiplier for prose files (documentation, release notes, changelogs) unless - # the query asks for documentation or the search is constrained to paths; 1.0 = off. - # [restart] + # Multiplier for prose files (documentation, release notes, changelogs) unless the + # query asks for documentation or the search is constrained to paths. The ranking + # multiplies the fused score by it, and the lexical leg picks its candidates on each + # row's vote times it, before RRF. A smaller value makes the lexical leg read deeper. + # 1.0 = off. [restart] # code_search_prose_penalty: 0.25 # Chunk-kind ranking prior when the request names none: structural boosts the kind diff --git a/schemas/loom-settings.schema.json b/schemas/loom-settings.schema.json index 2e1aab2503..ccfa1dcc88 100644 --- a/schemas/loom-settings.schema.json +++ b/schemas/loom-settings.schema.json @@ -1168,7 +1168,7 @@ "code_fusion_signals": { "default": true, "type": "boolean", - "description": "Post-fusion rank priors in code.search (path-noise penalty, query↔path stem affinity, file coherence), applied after RRF and before the outcome boost. Kill switch." + "description": "Rank priors in code.search (the test-path and prose penalties, query↔path stem affinity, file coherence), applied after RRF and before the outcome boost. The lexical leg also picks its candidates on the two path penalties, before RRF. Kill switch for both." }, "code_gh_items_backfill_days": { "default": 730, @@ -2227,7 +2227,7 @@ "code_search_prose_penalty": { "default": 0.25, "type": "number", - "description": "Fusion multiplier for prose files (documentation, release notes, changelogs) unless the query asks for documentation or the search is constrained to paths; 1.0 = off." + "description": "Multiplier for prose files (documentation, release notes, changelogs) unless the query asks for documentation or the search is constrained to paths. The ranking multiplies the fused score by it, and the lexical leg picks its candidates on each row's vote times it, before RRF. A smaller value makes the lexical leg read deeper. 1.0 = off." }, "code_search_query_max_tokens": { "default": 48, diff --git a/server/code/app/search/calibrate.py b/server/code/app/search/calibrate.py index 4cf2133ed5..c1f51a73dd 100644 --- a/server/code/app/search/calibrate.py +++ b/server/code/app/search/calibrate.py @@ -19,9 +19,14 @@ def _calibrate( abstain_threshold: float, ) -> bool: """Calibrate the fused list and decide abstention on it, before any - prior reorders it; returns whether the two content legs agreed.""" + prior reorders it; returns whether the two content legs agreed. + + `fused` and the lexical rows read here are the leg's own first rows + (`st.lexical_head`), not the pool it cut on the path penalties: the + penalties are priors, and no prior decides abstention. They order the + leg's rows of one score, which have no order of their own.""" result, constrained, fuzzy_hit = st.result, st.constrained, st.fuzzy_hit - lexical_rows, vector_rows = st.lexical_rows, st.vector_rows + lexical_rows, vector_rows = st.lexical_head, st.vector_rows card_gate, card_stats, concept_stats = st.card_gate, st.card_stats, st.concept_stats # similarity signal for calibration: cosine of the top vector hit when the # vector leg ran; else the lexical top presence stands in at the floor. diff --git a/server/code/app/search/definitions.py b/server/code/app/search/definitions.py index ba00b2f07c..a7aedf784e 100644 --- a/server/code/app/search/definitions.py +++ b/server/code/app/search/definitions.py @@ -8,10 +8,10 @@ import re from typing import Any -from server.code.app.search.priors import _noise_path from server.code.app.search.window import _has_test_intent from server.code.app.spans import code_span, span_attrs from server.code.domain.idents import spelled_names +from server.code.domain.index import path_class from server.code.domain.search_scope import SearchScope from server.code.domain.units import CodeUnit, unit_from_chunk from server.code.store.index import CodeRepo, is_noise_path @@ -54,7 +54,7 @@ def named_definitions( found = sorted( d for d in named - if d[0].startswith(path_prefix) and (asks_tests or not _noise_path(d[0])) + if d[0].startswith(path_prefix) and (asks_tests or not path_class.is_noise_path(d[0])) ) found = [d for d in found if not is_noise_path(d[0])] or found if found and len(found) <= _MAX_DEFINITIONS_PER_NAME: diff --git a/server/code/app/search/fusion.py b/server/code/app/search/fusion.py index a33868bc98..6bb773fe2b 100644 --- a/server/code/app/search/fusion.py +++ b/server/code/app/search/fusion.py @@ -3,22 +3,33 @@ from __future__ import annotations +from collections.abc import Iterator from typing import Any from server.code.app.search.state import _SearchState from server.code.app.spans import code_span, span_attrs +from server.code.domain.index.pool_cut import RRF_K as _RRF_K from server.settings import settings -_RRF_K = 60.0 +def _lexical_ranks(rows: list[dict[str, Any]]) -> Iterator[tuple[int, dict[str, Any]]]: + """(rank, row) for the lexical leg's rows, 1-based: the rank the leg gave the row + among everything it scored. The leg says it on the row (`lex_rank`) when it cut its + pool on the path penalties; otherwise the rank is the row's position.""" + for position, r in enumerate(rows, start=1): + yield int(r.get("lex_rank") or position), r -def _fuse(st: _SearchState) -> tuple[list[tuple[dict[str, Any], float]], str]: - """Fuse the legs' rows into one scored list; returns (fused, the fusion label).""" + +def _fuse( + st: _SearchState, lexical_rows: list[dict[str, Any]] +) -> tuple[list[tuple[dict[str, Any], float]], str]: + """Fuse `lexical_rows` (the leg's pool for the ranking, its head for calibration) + with the other legs' rows into one scored list; returns (fused, the fusion label).""" lex_weight = st.lex_weight fusion_kind = "rrf" if lex_weight == 1.0 else f"rrf(lex_w={lex_weight:g})" with code_span("search.fuse", route="rrf") as sp: fused = _rrf_fuse( - st.lexical_rows, + lexical_rows, st.vector_rows, st.history_rows, history_cap=st.history_cap, @@ -38,10 +49,11 @@ def leg_provenance( lexical_rows: list[dict[str, Any]], vector_rows: list[dict[str, Any]] ) -> dict[str, tuple[str, int, int]]: """chunk_id -> (via, lexical_rank, vector_rank) from the two leg pools as - the legs returned them (1-based, first occurrence; 0 = not in that leg). + the legs ranked them (`_lexical_ranks` for the lexical leg, the position for the + vector leg; first occurrence; 0 = not in that leg). via is "both" | "lexical" | "vector".""" lex: dict[str, int] = {} - for i, r in enumerate(lexical_rows, start=1): + for i, r in _lexical_ranks(lexical_rows): lex.setdefault(str(r["chunk_id"]), i) vec: dict[str, int] = {} for i, r in enumerate(vector_rows, start=1): @@ -92,17 +104,20 @@ def _rrf_fuse( hyde_cap: float | None = None, lexical_weight: float = 1.0, ) -> list[tuple[dict[str, Any], float]]: - """Reciprocal-rank fusion, k=60, unchanged for the two content legs. The optional - history list is fused with the same operator, except that each of its rows - contributes at most `history_cap` x the top two-leg score: a file the history names - is lifted among the content legs' candidates, never above the best of them on its - own.""" + """Reciprocal-rank fusion, k=60, unchanged for the two content legs: each row + votes with its rank in its leg (`_lexical_ranks`). The optional history list is fused + with the same operator, except that each of its rows contributes at most + `history_cap` x the top two-leg score: a file the history names is lifted among the + content legs' candidates, never above the best of them on its own.""" scores: dict[str, float] = {} rep: dict[str, dict[str, Any]] = {} # The lexical list may weigh less than the vector list (a responsibility question's # words are the corpus's common words) - for rows, weight in ((lexical_rows, float(lexical_weight)), (vector_rows, 1.0)): - for rank, r in enumerate(rows, start=1): + for ranked, weight in ( + (_lexical_ranks(lexical_rows), float(lexical_weight)), + (enumerate(vector_rows, start=1), 1.0), + ): + for rank, r in ranked: cid = str(r["chunk_id"]) rep.setdefault(cid, r) scores[cid] = scores.get(cid, 0.0) + weight / (_RRF_K + rank) diff --git a/server/code/app/search/gather.py b/server/code/app/search/gather.py index fe6fde113e..6ef97d8f54 100644 --- a/server/code/app/search/gather.py +++ b/server/code/app/search/gather.py @@ -10,6 +10,7 @@ from server.code.app.search.history import _history_leg, _history_route_units from server.code.app.search.hyde import _hyde_config from server.code.app.search.lexical import _lexical_leg +from server.code.app.search.priors import pool_penalties from server.code.app.search.state import _SearchState from server.code.app.search.symbol import _fuzzy_symbol_vote from server.code.app.search.vector import _QueryVecMemo, _vector_leg_rows @@ -109,10 +110,13 @@ async def _gather_legs( concept_stats=st.concept_stats, llm_legs=llm_legs, ) + # The path penalties of this query, decided once: the lexical leg cuts its pool on + # them and `_rank_units` multiplies by them + st.path_penalties = pool_penalties(query, prose_eligible=not constrained and shape != "symbol") # the fuzzy-symbol vote needs the query alone, so it runs beside the legs; under a # deadline a late leg is dropped and named ( - (st.lexical_rows, st.lex_tokens, st.idfs), + (st.lexical_rows, st.lexical_head, st.lex_tokens, st.idfs), (st.vector_rows, st.qvec), st.history_rows, st.history_units, @@ -135,8 +139,9 @@ async def _gather_legs( work=work, path_prefix=path_prefix, scope=scope if constrained else None, + path_penalties=st.path_penalties, ), - ([], tokens, []), + ([], [], tokens, []), ), "vector": ( _vector_leg_rows( diff --git a/server/code/app/search/lexical.py b/server/code/app/search/lexical.py index 081baa636b..93fd24508b 100644 --- a/server/code/app/search/lexical.py +++ b/server/code/app/search/lexical.py @@ -28,12 +28,16 @@ async def _lexical_leg( work: dict[str, int], path_prefix: str, scope: SearchScope | None, -) -> tuple[list[dict[str, Any]], list[str], list[float]]: - """The lexical leg: corpus stats for the idfs, then the chunk scan. + path_penalties: tuple[float, float], +) -> tuple[list[dict[str, Any]], list[dict[str, Any]], list[str], list[float]]: + """The lexical leg: corpus stats for the idfs, then the chunk scan. Returns + (pool, head, tokens, idfs): the pool is what the ranking fuses, the head is the + leg's own first rows, which calibration reads. They are one list unless the scan + cut the pool on `path_penalties`, the ranking's (test path, prose file) factors. `scope` is the constraint's predicate, None when unconstrained.""" rows: list[dict[str, Any]] = [] if not run_lexical: - return rows, tokens, [] + return rows, rows, tokens, [] # Fail soft, as the vector leg does: a corpus-stats or scan failure # (a replica refusing the read, a timeout) degrades the search to the # other leg instead of failing the whole call. The counter says so. @@ -59,6 +63,8 @@ async def _lexical_leg( path_prefix=path_prefix, pool=_POOL, scope=scope, + noise_penalty=path_penalties[0], + prose_penalty=path_penalties[1], ) # Leg wall time in ms so a bench can read the leg's cost off # the response instead of a trace (int: retrieval_work's type). @@ -67,8 +73,11 @@ async def _lexical_leg( except Exception as e: # noqa: BLE001 — vector-only degrade logger.warning("code.search lexical leg failed: %s", e) work["lexical_leg_failed"] = 1 - return [], tokens, [] - return rows, lex_tokens, idfs + return [], [], tokens, [] + if rows and "in_pool" in rows[0]: + pool = [r for r in rows if r["in_pool"]] + return pool, [r for r in rows if r["lex_rank"] <= _POOL], lex_tokens, idfs + return rows, rows, lex_tokens, idfs async def _lexical_terms( diff --git a/server/code/app/search/pipeline.py b/server/code/app/search/pipeline.py index 59d66447c3..8dec3e4f19 100644 --- a/server/code/app/search/pipeline.py +++ b/server/code/app/search/pipeline.py @@ -114,7 +114,7 @@ async def search( pr_leg_before=pr_leg_before, llm_legs=llm_legs, ) - fused, fusion_kind = _fuse(st) + fused, fusion_kind = _fuse(st, st.lexical_rows) if not fused and st.history_units: _serve_history_anchors(st, top_k=top_k, token_budget=token_budget, bodies=bodies) return result @@ -131,9 +131,12 @@ async def search( ) return result + # Calibration reads the legs' own order, before any prior: the lexical leg's first + # rows, which differ from its pool when it cut the pool on the path penalties + cut = st.lexical_head != st.lexical_rows legs_agree = _calibrate( st, - fused, + _fuse(st, st.lexical_head)[0] if cut else fused, run_vector=st.run_vector, noise_floor=noise_floor, abstain_threshold=abstain_threshold, diff --git a/server/code/app/search/priors.py b/server/code/app/search/priors.py index 21071b5718..9e4b98ddcf 100644 --- a/server/code/app/search/priors.py +++ b/server/code/app/search/priors.py @@ -13,6 +13,7 @@ from server.code.app import fan_in as code_fan_in from server.code.domain.extract.tokenize import code_tokens from server.code.domain.idents import embedded_idents +from server.code.domain.index.path_class import is_noise_path, is_prose_path from server.code.domain.units import CodeUnit from server.core.datetimes import naive_utc_now from server.settings import settings @@ -67,20 +68,11 @@ def _dir_match(path: str, recent_dirs: list[str]) -> bool: # ---- fusion rank priors: post-fusion path / definition signals that lift # recall@10 over plain RRF, all deterministic and LLM-free. Path-noise prior: -# test/example/fuzzer code is indexed on purpose (agents ask "how is X tested"), but for -# a conceptual question the implementation should outrank its tests — demote, never -# drop. -_NOISE_DIR_RE = re.compile(r"(?:^|/)(?:tests?|examples?|fuzzers|benchmarks)(?:/|$)") - - -_NOISE_FILE_RE = re.compile(r"(?:^|/)(?:test_[^/]+|[^/]+_(?:test|fuzz))\.(?:h|hpp|cpp|cc|cxx)$") - - -def _noise_path(path: str) -> bool: - """A test, example, fuzzer or benchmark path: what the noise penalty demotes.""" - return bool(_NOISE_DIR_RE.search(path) or _NOISE_FILE_RE.search(path)) - - +# test/example/fuzzer code (`path_class.is_noise_path`) is indexed on purpose (agents +# ask "how is X tested"), but for a conceptual question the implementation should +# outrank its tests: demote, never drop. The lexical leg cuts its pool on the same +# factor (`pool_penalties`): it keeps the rows whose vote times the factor is largest, +# so a test row leaves the pool only when that many rows count for more. # 0.35 with tests/ and ci/ in the corpus: a grid on the C++ conceptual fixture (penalty # {0.5, 0.35, 0.25}) read r@5 0.741/0.769/0.769, r@10 0.801/0.810/0.810 — knee at 0.35, # recovering most of the dilution the larger corpus caused (0.778 without tests/ and @@ -98,18 +90,8 @@ def _noise_path(path: str) -> bool: ) -# Prose files — documentation, release notes, changelogs — by extension or by a -# changelog-style name, never by a directory word (`src/Coordination/Changelog.cpp` -# is code). A bug report's words are the ones the release notes repeat, so prose -# outranks the source it describes: asked with public bug reports, a prose file -# ranked first on a quarter of them although every fix changed only source. -_PROSE_EXT_RE = re.compile(r"\.(?:md|mdx|markdown|rst|adoc|txt)$", re.I) -_PROSE_NAME_RE = re.compile( - r"(?:^|/)(?:CHANGELOG|CHANGES|HISTORY|NEWS|RELEASE[-_]?NOTES)(?:\.[a-z]+)?$", re.I -) -_CODE_EXT_RE = re.compile(r"\.(?:py|pyi|h|hpp|c|cc|cpp|cxx|go|rs|ts|tsx|js|jsx|java|kt|sql|sh)$") - -# Query tokens that mean the asker wants documentation; the prose penalty skips them. +# Query tokens that mean the asker wants documentation (`path_class.is_prose_path`); +# the prose penalty skips them. _DOC_INTENT_TOKENS = frozenset( { "doc", @@ -127,15 +109,6 @@ def _noise_path(path: str) -> bool: ) -def is_prose_path(path: str) -> bool: - """True for a documentation or release-notes file (`CMakeLists.txt` is build code).""" - if path.rsplit("/", 1)[-1].lower() == "cmakelists.txt": - return False - if _PROSE_EXT_RE.search(path): - return True - return bool(_PROSE_NAME_RE.search(path)) and not _CODE_EXT_RE.search(path) - - def _prose_penalty(*, eligible: bool) -> float: """The fusion-signal multiplier for a prose file on this question: `code_search_prose_penalty` unless the search is constrained to paths or is a @@ -199,26 +172,41 @@ def _prose_penalty(*, eligible: bool) -> float: ) +def pool_penalties(query: str, *, prose_eligible: bool) -> tuple[float, float]: + """The factors the ranking multiplies a test path and a prose file by on this query + (1.0 = not applied): a test word turns the first off, a doc word the second, and + both are off with the fusion signals. `prose_eligible` is False for a search + constrained to paths and for a symbol lookup. The lexical leg cuts its pool on the + pair and `_apply_fusion_signals` multiplies by it.""" + if not settings.code_fusion_signals: + return 1.0, 1.0 + q_tokens = frozenset(code_tokens(query)) + return ( + 1.0 if q_tokens & _TEST_INTENT_TOKENS else _NOISE_PENALTY, + 1.0 if q_tokens & _DOC_INTENT_TOKENS else _prose_penalty(eligible=prose_eligible), + ) + + def _apply_fusion_signals( ranked: list[CodeUnit], query: str, *, + path_penalties: tuple[float, float], prior_cap: float = 0.0, catalogue_penalty: float = 1.0, - prose_penalty: float = 1.0, ) -> list[CodeUnit]: """Path-noise penalty, stem affinity, embedded-identifier boost, file coherence — and, when `prior_cap` > 0, the fan-in prior: x(1 + cap * log1p(fan_in) / log1p(max fan_in in the pool)), read from CodeUnit.fan_in, skipped under test intent and on noise paths (the same two exemptions as the penalty), never applied to a unit - without callers. Calibration ran before this on the raw fusion, so abstention is - unaffected. Default cap 0 = the prior is not computed.""" + without callers. `path_penalties` is the query's `pool_penalties` pair, the one the + lexical leg cut its pool on. Calibration ran before this on the raw fusion, so + abstention is unaffected. Default cap 0 = the prior is not computed.""" if not ranked: return ranked q_tokens = frozenset(code_tokens(query)) + noise_penalty, prose_penalty = path_penalties test_intent = bool(q_tokens & _TEST_INTENT_TOKENS) - if q_tokens & _DOC_INTENT_TOKENS: - prose_penalty = 1.0 keywords = frozenset(t for t in q_tokens if len(t) > 2 and t not in _QUERY_STOPWORDS) embedded = embedded_idents(query) max_fan_in = max((u.fan_in for u in ranked), default=0) if prior_cap > 0 else 0 @@ -226,9 +214,9 @@ def _apply_fusion_signals( scored: list[tuple[CodeUnit, float]] = [] for u in ranked: s = u.score - noisy = _noise_path(u.path) - if not test_intent and noisy: - s *= _NOISE_PENALTY + noisy = is_noise_path(u.path) + if noisy: + s *= noise_penalty if catalogue_penalty != 1.0 and _CATALOGUE_FILE_RE.search(u.path): s *= catalogue_penalty if prose_penalty != 1.0 and is_prose_path(u.path): diff --git a/server/code/app/search/rank.py b/server/code/app/search/rank.py index 4b5c9d53b7..757d60f963 100644 --- a/server/code/app/search/rank.py +++ b/server/code/app/search/rank.py @@ -15,7 +15,6 @@ _apply_outcome_boost, _catalogue_penalty, _kind_prior_table, - _prose_penalty, _user_tiebreak, ) from server.code.app.search.rerank import _rerank_stage @@ -88,15 +87,16 @@ async def _rank_units( # ---- fusion rank priors: path-noise penalty, query<->path stem affinity, file # coherence. Applied to RRF scores BEFORE the outcome boost so both stay # multiplicative-capped priors under relevance; calibration already ran on the raw - # fusion, so abstention is unaffected. + # fusion, so abstention is unaffected. The two path penalties are the pair the + # lexical leg cut its pool on (`_gather_legs` decides it for both). fusion_signals = False if settings.code_fusion_signals: ranked = _apply_fusion_signals( ranked, query, + path_penalties=st.path_penalties, prior_cap=prior_cap, catalogue_penalty=_catalogue_penalty(work, prose=not constrained and shape != "symbol"), - prose_penalty=_prose_penalty(eligible=not constrained and shape != "symbol"), ) fusion_signals = True diff --git a/server/code/app/search/state.py b/server/code/app/search/state.py index 4b405ba142..abd2254621 100644 --- a/server/code/app/search/state.py +++ b/server/code/app/search/state.py @@ -120,8 +120,14 @@ class _SearchState: card_stats: dict[str, Any] = dc_field(default_factory=dict) concept_stats: dict[str, Any] = dc_field(default_factory=dict) lex_weight: float = 1.0 + # the factors the ranking multiplies a (test path, prose file) by on this query, + # 1.0 = not applied; the lexical leg cuts its pool on the same pair + path_penalties: tuple[float, float] = (1.0, 1.0) # what the legs returned (their empty values when a deadline dropped one) lexical_rows: list[dict[str, Any]] = dc_field(default_factory=list) + # the lexical leg's own first rows, which calibration reads: `lexical_rows` itself + # unless the leg cut its pool on `path_penalties` + lexical_head: list[dict[str, Any]] = dc_field(default_factory=list) lex_tokens: list[str] = dc_field(default_factory=list) idfs: list[float] = dc_field(default_factory=list) vector_rows: list[dict[str, Any]] = dc_field(default_factory=list) diff --git a/server/code/app/search/track.py b/server/code/app/search/track.py index 64810edccd..dd689224c3 100644 --- a/server/code/app/search/track.py +++ b/server/code/app/search/track.py @@ -113,8 +113,9 @@ def track_verdict( 'served at rank r' — a chunk of the file is in the response 'rank r in pool' — a leg returned it; fusion/priors/top_k cut it 'no lexeme match[; ...]' — no query token occurs in any chunk's lexemes - 'beyond pool: ...' — scored, but under the lexical pool floor / - past the vector pool ceiling (numbers given) + 'beyond pool: ...' — scored, but under the lexical pool floor (or + over it and cut on its path penalty) / past + the vector pool ceiling (numbers given) `best` is the chunk that came closest, with both leg ranks and raw scores.""" if not rows: return {"path": path, "verdict": "not indexed", "chunks": 0, "pool": pool} @@ -170,6 +171,12 @@ def _rank_key(r: dict[str, Any]) -> tuple[int, int, float, float]: if lexical_ran: if lex_score <= 0.0: parts.append("no lexeme match") + elif lex_pool_full and lex_score > lex_floor: + # over the floor and still out: the leg cut it on the penalty of its path + parts.append( + f"beyond pool: lexical {lex_score:.2f} over floor {lex_floor:.2f}, " + "cut on its path penalty" + ) elif lex_pool_full: parts.append(f"beyond pool: lexical {lex_score:.2f} under floor {lex_floor:.2f}") else: diff --git a/server/code/domain/index/path_class.py b/server/code/domain/index/path_class.py new file mode 100644 index 0000000000..cfbb8cadc8 --- /dev/null +++ b/server/code/domain/index/path_class.py @@ -0,0 +1,49 @@ +"""Which indexed paths are not source: test, example and benchmark trees, and prose +files. Pure. `code.search` demotes both for a question about the implementation. + +Each class is one pattern in the syntax Python's `re` and ClickHouse's `match` share +(no lookaround), so the ranking's test in Python and the lexical leg's pool cut in SQL +read the same definition (`server.code.store.index.sql.path_penalty_sql`). +""" + +from __future__ import annotations + +import re + +# Test, example, fuzzer and benchmark code is indexed on purpose (agents ask "how is X +# tested"): a directory of that name anywhere in the path, or a C++ test file by name. +NOISE_PATH_PATTERN = ( + r"(?:^|/)(?:tests?|examples?|fuzzers|benchmarks)(?:/|$)" + r"|(?:^|/)(?:test_[^/]+|[^/]+_(?:test|fuzz))\.(?:h|hpp|cpp|cc|cxx)$" +) + +# Documentation, release notes and changelogs, by extension or by a changelog-style +# name, never by a directory word (`src/Coordination/Changelog.cpp` is code). A bug +# report's words are the ones the release notes repeat, so prose outranks the source it +# describes: asked with public bug reports, a prose file ranked first on a quarter of +# them although every fix changed only source. +PROSE_PATH_PATTERN = ( + r"(?i:\.(?:md|mdx|markdown|rst|adoc|txt)$" + r"|(?:^|/)(?:CHANGELOG|CHANGES|HISTORY|NEWS|RELEASE[-_]?NOTES)(?:\.[a-z]+)?$)" +) +# What the prose pattern matches and is code: `CMakeLists.txt` is build code, and a +# changelog-style name with a code extension is a module. +PROSE_EXEMPT_PATTERN = ( + r"(?i:(?:^|/)cmakelists\.txt$)" + r"|\.(?:py|pyi|h|hpp|c|cc|cpp|cxx|go|rs|ts|tsx|js|jsx|java|kt|sql|sh)$" +) + +_NOISE_RE = re.compile(NOISE_PATH_PATTERN) +_PROSE_RE = re.compile(PROSE_PATH_PATTERN) +_PROSE_EXEMPT_RE = re.compile(PROSE_EXEMPT_PATTERN) + + +def is_noise_path(path: str) -> bool: + """True for a file under a test, example, fuzzer or benchmark directory, or a C++ + test file by name.""" + return bool(_NOISE_RE.search(path)) + + +def is_prose_path(path: str) -> bool: + """True for a documentation or release-notes file (`CMakeLists.txt` is build code).""" + return bool(_PROSE_RE.search(path)) and not _PROSE_EXEMPT_RE.search(path) diff --git a/server/code/domain/index/pool_cut.py b/server/code/domain/index/pool_cut.py new file mode 100644 index 0000000000..9992450d04 --- /dev/null +++ b/server/code/domain/index/pool_cut.py @@ -0,0 +1,37 @@ +"""The lexical leg's pool cut on the path penalties of the ranking. Pure. + +The ranking gives a row of the leg `factor / (RRF_K + rank)`: its reciprocal-rank vote +times the factor of its path (`path_class`), 1 on source. A leg that returns its first +`pool` rows by rank drops source rows whose vote counts for more than the vote of the +test and prose rows it keeps. The cut keeps the `pool` rows with the largest vote, and +each votes with the rank it has in the whole leg, so a row in the pool scores what it +would score had the leg returned every row. +""" + +from __future__ import annotations + +import math + +# Reciprocal-rank fusion's constant: a row at rank r of a leg votes 1 / (RRF_K + r). +RRF_K = 60.0 + +# ClickHouse fetches the body columns of an `ORDER BY … LIMIT n` lazily only for n at +# or under query_plan_max_limit_for_lazy_materialization (10,000 by default). +MAX_DEPTH = 10_000 + + +def cut_depth(pool: int, noise_penalty: float, prose_penalty: float) -> int: + """How many rows of the leg's own order can hold a row of the cut pool, for the two + path factors of the ranking. + + A path gets 1, one of the factors or both: `lo` and `hi` are the smallest and the + largest of those. A row at rank r votes at most hi / (RRF_K + r), and each of the + first `pool` rows votes at least lo / (RRF_K + pool). Past rank + (RRF_K + pool) * hi / lo - RRF_K a row loses to all of them, so it is not in the + pool. The depth stops at MAX_DEPTH: with no factor over 1, a factor under about + 0.026 reads that deep and no deeper.""" + factors = (1.0, noise_penalty, prose_penalty, noise_penalty * prose_penalty) + lo, hi = min(factors), max(factors) + if lo <= 0.0: + return MAX_DEPTH + return min(MAX_DEPTH, max(pool, math.ceil((RRF_K + pool) * hi / lo - RRF_K))) diff --git a/server/code/store/index/search.py b/server/code/store/index/search.py index e8516e95f1..9004beed5a 100644 --- a/server/code/store/index/search.py +++ b/server/code/store/index/search.py @@ -9,13 +9,36 @@ from datetime import datetime from typing import Any +from server.code.domain.index import pool_cut from server.code.domain.index.grep_plan import GREP_FINAL_SETTINGS from server.code.domain.search_scope import SearchScope from server.code.store.index.base import CodeRepoBase -from server.code.store.index.sql import _scope_sql, skip_tests_sql +from server.code.store.index.sql import _scope_sql, path_penalty_sql, skip_tests_sql from server.core.datetimes import naive_utc_now as _now +def _cut_on_votes(ranked_sql: str, order: str, factor: str) -> str: + """Wrap the lexical statement, limited to `{depth:UInt32}` rows in `order`, so it + ranks those rows in that order (`lex_rank`) and marks as `in_pool` the `pool` of + them with the largest vote in the ranking: `factor`, the factor of the row's path, + over RRF_K plus its rank. It returns them with the first `pool` rows by rank, in + rank order.""" + return f""" + SELECT * + FROM ( + SELECT *, row_number() OVER ( + ORDER BY {factor} / ({{rrf_k:Float64}} + lex_rank) DESC + ) <= {{pool:UInt32}} AS in_pool + FROM ( + SELECT *, row_number() OVER (ORDER BY {order}) AS lex_rank + FROM ({ranked_sql}) + ) + ) + WHERE in_pool OR lex_rank <= {{pool:UInt32}} + ORDER BY lex_rank + """ + + class SearchMixin(CodeRepoBase): """code.search legs, corpus statistics and outcome signals.""" @@ -30,6 +53,8 @@ async def lexical_search_chunks( path_prefix: str = "", pool: int = 200, scope: SearchScope | None = None, + noise_penalty: float = 1.0, + prose_penalty: float = 1.0, ) -> list[dict[str, Any]]: """Lexical leg over app-tokenized lexemes: the idf-weighted sum of `countSubstrings` over the deduplicated lexemes. tf counts space-bounded @@ -41,6 +66,22 @@ async def lexical_search_chunks( `scope` adds the pattern / path predicates to the plain WHERE after the identity keys; unset, the statement is unchanged byte for byte. + `noise_penalty` and `prose_penalty` are the factors the ranking will + multiply a test path and a prose file by. Below 1, the pool is cut on + the row's vote in the ranking, its factor / (RRF_K + its rank by + `lex_score`), not on the rank alone: tests and docs repeat the + vocabulary of the source they cover, and a row the ranking demotes + must not take a pool slot from a source row whose vote counts for + more. Every row then carries its rank in the whole leg (`lex_rank`, + what it votes with) and `in_pool`; the rows are that pool and the + leg's own first `pool` rows, which calibration reads, in rank order. + Rows with one score rank by their factor, the largest first: a short + query's rows tie by the thousand, ClickHouse returns equal rows in + no fixed order, and the rank decides the pool. The scan reads + `pool_cut.cut_depth` rows deep, past which no row can be in the + pool. At 1 the statement is unchanged byte for byte, the rows are + the pool, and a row's rank is its position. + The String query form of `hasAnyTokens` tokenizes the query with the text index's splitByNonAlpha tokenizer. Its Array form takes pre-tokenized terms, so whole underscore identifiers cannot gate @@ -64,8 +105,10 @@ async def lexical_search_chunks( "{tokens:Array(String)}, {idfs:Array(Float32)}))" ) scope_sql, scope_params = _scope_sql(scope) - rows = await self._ch.query_all( - f""" + cut = noise_penalty != 1.0 or prose_penalty != 1.0 + factor, factor_params = path_penalty_sql("path", noise_penalty, prose_penalty) + order = f"lex_score DESC, {factor} DESC" if cut else "lex_score DESC" + sql = f""" SELECT chunk_id, path, scope, kind, start_line, end_line, content, symbol_ids, context_description, {score} AS lex_score @@ -76,9 +119,16 @@ async def lexical_search_chunks( AND {score} > 0 {where_prefix} {scope_sql} - ORDER BY lex_score DESC - LIMIT {{pool:UInt32}} - """, + ORDER BY {order} + LIMIT {"{depth:UInt32}" if cut else "{pool:UInt32}"} + """ + cut_params: dict[str, Any] = {} + if cut: + sql = _cut_on_votes(sql, order, factor) + depth = pool_cut.cut_depth(pool, noise_penalty, prose_penalty) + cut_params = {**factor_params, "rrf_k": pool_cut.RRF_K, "depth": depth} + return await self._ch.query_all( + sql, { "org": org, "ns": ns, @@ -89,9 +139,9 @@ async def lexical_search_chunks( **({"gate_query": " ".join(tokens)} if gate else {}), **({"prefix": path_prefix} if path_prefix else {}), **scope_params, + **cut_params, }, ) - return rows async def definition_chunks( self, diff --git a/server/code/store/index/sql.py b/server/code/store/index/sql.py index 2f4c5f8b60..801fac8a57 100644 --- a/server/code/store/index/sql.py +++ b/server/code/store/index/sql.py @@ -1,6 +1,7 @@ """SQL fragments and read helpers the code-plane readers share: batched point reads, the search-scope and branch predicates, the test-path filter -and its Python twin, LIKE escaping, FixedString hash decoding. +and its Python twin, the path-penalty factor, LIKE escaping, FixedString hash +decoding. """ from __future__ import annotations @@ -9,6 +10,7 @@ from collections.abc import Awaitable, Callable from typing import Any +from server.code.domain.index import path_class from server.code.domain.search_scope import SearchScope from server.core.ch_params import chunks @@ -98,6 +100,25 @@ def skip_tests_sql(col: str) -> str: ) +def path_penalty_sql(col: str, noise: float, prose: float) -> tuple[str, dict[str, Any]]: + """The factor code.search's ranking multiplies a row by for its path, and its + parameters: `noise` on a test, example or benchmark path, `prose` on a documentation + file, 1 on source. The patterns are `path_class`'s, so SQL and Python agree on + which file is which.""" + return ( + f"(if(match({col}, {{noise_path:String}}), {{noise_penalty:Float64}}, 1)" + f" * if(match({col}, {{prose_path:String}})" + f" AND NOT match({col}, {{prose_exempt:String}}), {{prose_penalty:Float64}}, 1))", + { + "noise_path": path_class.NOISE_PATH_PATTERN, + "noise_penalty": noise, + "prose_path": path_class.PROSE_PATH_PATTERN, + "prose_exempt": path_class.PROSE_EXEMPT_PATTERN, + "prose_penalty": prose, + }, + ) + + def like_contains(text: str) -> str: """The LIKE pattern that matches exactly the rows whose value contains `text` — `%`, `_` and the backslash in the text escaped so diff --git a/server/settings/catalog.py b/server/settings/catalog.py index 5cd8430d7f..0e39d2076b 100644 --- a/server/settings/catalog.py +++ b/server/settings/catalog.py @@ -1633,9 +1633,10 @@ def _check_git_proxy(self) -> CodeSettings: # --- search ranking, legs and caches (code.search) ------------------------ # Fire-and-forget code_search_trace/code_search_outcome telemetry. code_trace_log_enabled: bool = True - # Post-fusion rank priors in code.search (path-noise penalty, query↔path + # Rank priors in code.search (the test-path and prose penalties, query↔path # stem affinity, file coherence), applied after RRF and before the outcome - # boost. Kill switch. + # boost. The lexical leg also picks its candidates on the two path penalties, + # before RRF. Kill switch for both. code_fusion_signals: bool = True # Long-question trim: past this many lexemes the question is treated as an # issue body (template headings stripped, the rarest 32 tokens gate, the @@ -1737,9 +1738,11 @@ def _check_git_proxy(self) -> CodeSettings: # Fusion multiplier for settings-catalogue units (Settings.cpp and kin) on the # question kinds `code_search_catalogue_kinds` names; 1.0 = off. code_search_catalogue_penalty: float = 1.0 - # Fusion multiplier for prose files (documentation, release notes, changelogs) - # unless the query asks for documentation or the search is constrained to paths; - # 1.0 = off. + # Multiplier for prose files (documentation, release notes, changelogs) unless + # the query asks for documentation or the search is constrained to paths. The + # ranking multiplies the fused score by it, and the lexical leg picks its + # candidates on each row's vote times it, before RRF. A smaller value makes + # the lexical leg read deeper. 1.0 = off. code_search_prose_penalty: float = 0.25 # Chunk-kind ranking prior when the request names none: structural boosts the # kind named by the question; flat/default apply fixed tables; off disables it. diff --git a/tests/analyzer/cases/code.py b/tests/analyzer/cases/code.py index 25c3c9fa7a..621c981efe 100644 --- a/tests/analyzer/cases/code.py +++ b/tests/analyzer/cases/code.py @@ -49,6 +49,9 @@ async def _search(ch: RecordingCH, c: dict[str, Any]) -> None: [1.0] * len(tokens), path_prefix=prefix, scope=scope, + # the pool cut on the ranking's path penalties + noise_penalty=0.35 if c["path_penalties"] else 1.0, + prose_penalty=0.25 if c["path_penalties"] else 1.0, ) await repo.vector_search_chunks(ORG, NS, MODEL, SMALL_VEC, path_prefix=prefix, scope=scope) await repo.vector_shortlist_ids( @@ -443,6 +446,7 @@ def cases() -> list[Case]: "scope": ("none", "globs", "regex"), "path_prefix": (False, True), "token_gate": ("words", "underscores"), + "path_penalties": (False, True), }, ), Case( diff --git a/tests/analyzer/shapes.txt b/tests/analyzer/shapes.txt index 856558c536..ef213f4bee 100644 --- a/tests/analyzer/shapes.txt +++ b/tests/analyzer/shapes.txt @@ -139,6 +139,7 @@ 1030febb1e77 ALTER TABLE loom.chunks UPDATE doc_superseded_at = {now:DateTime} WHERE (org = {org:String} AND user_id = {uid:String} AND doc_superseded_at IS NULL) AND ({erasure_mutation_tag:String} = {erasure_muta 1032019497c6 SELECT value, memory_type, confidence, promoted_from, promotion_event, promoted_from_candidate_id, promoted_by, rationale, promoted_at, reversible_until, tombstoned_at, version FROM loom.shared FINAL 1036d9982eb4 SELECT concat(?, c.session_id, ?, toString(c.chunk_index)) AS memory_key, ? AS memory_type, c.content AS content_excerpt, toString(ss.session_date) AS created_at, toString(ss.session_date) AS valid_at +104851cd0d21 SELECT * FROM ( SELECT *, row_number() OVER ( ORDER BY (if(match(path, {noise_path:String}), {noise_penalty:Float64}, ?) * if(match(path, {prose_path:String}) AND NOT match(path, {prose_exempt:String} 1069a110039a SELECT agent, user_id, session_id, version, summary_text, cosineDistance(summary_embedding, {q:Array(Float32)}) AS distance, -- NB: alias must NOT be `valid_at` — under the analyzer a -- SELECT alias 107be5b763da SELECT count() AS n FROM loom.memory_categories FINAL WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND tombstoned_at IS NULL 109db307d85f SELECT count() AS n FROM loom.chunks WHERE org = {org:String} AND user_id = {uid:String} AND doc_superseded_at IS NULL @@ -180,6 +181,7 @@ 1552f717160b SELECT DISTINCT org, namespace, agent, user_id, session_id, memory_key FROM loom.memory WHERE tombstoned_at IS NULL AND sensitivity = ? AND (expires_at IS NULL OR expires_at > now()) AND (match(value, 155bb556af22 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 156c81c0e9bc SELECT path, count() AS chunks, min(start_line) AS first_line, count() OVER () AS total FROM ( SELECT path, start_line, tombstoned_at FROM loom.code_chunks WHERE org = {org:String} AND namespace = {ns +15b77c91fbc6 SELECT * FROM ( SELECT *, row_number() OVER ( ORDER BY (if(match(path, {noise_path:String}), {noise_penalty:Float64}, ?) * if(match(path, {prose_path:String}) AND NOT match(path, {prose_exempt:String} 15c48e67a57a SELECT agent, user_id, session_id, memory_key, memory_type, content_excerpt, toString(created_at) AS created_at, toString(valid_at) AS valid_at, version FROM loom.memory_embeddings FINAL WHERE org = { 15ee0c6d12dd SELECT count() AS n FROM loom.procedure_runs WHERE org = {org:String} AND namespace IN {ns:Array(String)} 15fc912a653c SELECT org, namespace, source_uri, doc_id, title, tags, version, revision, access_json, superseded_at, ingested_at, content_sha256, format, parser, coverage, ingestion_id, artifact_sha256, blob_path, @@ -366,6 +368,7 @@ 2a44383c565f SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 2a4c344dc346 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 2a5db1d4ffaa SELECT name, category_id FROM loom.categories FINAL WHERE org = {org:String} AND namespace = {ns:String} AND name IN {names:Array(String)} AND tombstoned_at IS NULL +2a705cfe954b SELECT * FROM ( SELECT *, row_number() OVER ( ORDER BY (if(match(path, {noise_path:String}), {noise_penalty:Float64}, ?) * if(match(path, {prose_path:String}) AND NOT match(path, {prose_exempt:String} 2a8380b2d95e SELECT toUInt32(countDistinct(seq)) AS n FROM loom.code_scip_parts WHERE org = {org:String} AND namespace = {ns:String} AND batch_id = {bid:UUID} 2ac2ff622b95 SELECT op, returned_ids, returned_paths, abstain, route, args_json FROM loom.code_search_trace WHERE org = {org:String} AND namespace = {ns:String} AND trace_run_id = {rid:String} AND ts > now() - INT 2ac704bcfa82 SELECT namespace, max(last_write) AS last_write FROM loom.namespace_write_marks WHERE (org = {org:String} AND namespace IN {nss:Array(String)}) OR (org = ? AND namespace = ?) GROUP BY namespace @@ -406,6 +409,7 @@ 2f87519d6c67 SELECT count() AS n FROM loom.memory_records FINAL WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND tombstoned_at IS NULL 2fab97e447f4 SELECT count() AS n FROM loom.entity_vectors FINAL WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND tombstoned_at IS NULL 2fc0cc735773 SELECT toString(evidence_id) AS eid, session_id, role, actor, toString(observed_at) AS observed, content, matched FROM ( SELECT evidence_id, session_id, role, actor, observed_at, content, tombstoned_a +2fd8a58aab01 SELECT * FROM ( SELECT *, row_number() OVER ( ORDER BY (if(match(path, {noise_path:String}), {noise_penalty:Float64}, ?) * if(match(path, {prose_path:String}) AND NOT match(path, {prose_exempt:String} 2fd8ca033214 DELETE FROM loom.memory_chunks WHERE org = {org:String} AND namespace = {ns:String} AND agent = {a:String} AND user_id = {u:String} AND parent_memory_key = {k:String} AND if(session_id = {ss:String}, 30364bf4b5e4 SELECT chunk_id, path, scope, kind, start_line, end_line, content, symbol_ids, context_description, arraySum(arrayMap((tok, idf) -> idf * countSubstrings(concat(?, lexemes, ?), concat(?, tok, ?)), {to 303a1827c22d SELECT DISTINCT msg_id FROM loom.conversations WHERE org = {org:String} AND namespace = {ns:String} AND thread_id = {tid:String} AND msg_id IN {mids:Array(String)} AND is_saved AND tombstoned_at IS NU @@ -508,6 +512,7 @@ 3b05a28d96f2 SELECT count() AS cnt, sum(numeric_value) AS s, avg(numeric_value) AS a, min(occurred_at) AS first_at, max(occurred_at) AS last_at FROM loom.derived_facts WHERE org = {org:String} AND namespace = {ns: 3b1abae99635 SELECT chunk_id, path, scope, kind, start_line, end_line, content, symbol_ids, context_description, arraySum(arrayMap((tok, idf) -> idf * countSubstrings(concat(?, lexemes, ?), concat(?, tok, ?)), {to 3b1ae278b7f6 SELECT memory_type, toString(status) AS status, source_class, count() AS rows, min(updated_at) AS first_at, max(updated_at) AS last_at FROM loom.memory FINAL WHERE org = {org:String} AND namespace = { +3b33cbac1056 SELECT * FROM ( SELECT *, row_number() OVER ( ORDER BY (if(match(path, {noise_path:String}), {noise_penalty:Float64}, ?) * if(match(path, {prose_path:String}) AND NOT match(path, {prose_exempt:String} 3b4b4580cc9a SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, -- Multi-vector axis: min(value_dist, key_dist). CH?t g 3ba235828531 ALTER TABLE loom.documents UPDATE superseded_at = {now:DateTime} WHERE (org = {org:String} AND user_id != {uid:String} AND superseded_at IS NULL AND cityHash64(namespace, source_uri) IN {docs:Array(UI 3bab9ca71efb SELECT count() AS n FROM loom.memory_chunks FINAL WHERE org = {org:String} AND ((user_id = {uid:String} OR (user_id = ? AND (namespace, parent_memory_key) IN (SELECT namespace, memory_key FROM loom.me @@ -583,6 +588,7 @@ 431d46aeecdd SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, e.status AS status, e.version AS version, cosineDistance(e.embedding, {q:Array(Float32)}) AS dist 4332cad7d6f4 SELECT pr_number, merge_commit_sha, pack, pack_tokens, created_at FROM loom.code_context_packs FINAL WHERE org = {org:String} AND namespace = {ns:String} AND pr_number = {pr:UInt32} AND tombstoned_at 4359e6dcbd91 SELECT count() AS n FROM loom.session_outcomes_by_user WHERE org = {org:String} AND user_id = {uid:String} +437363e91242 SELECT * FROM ( SELECT *, row_number() OVER ( ORDER BY (if(match(path, {noise_path:String}), {noise_penalty:Float64}, ?) * if(match(path, {prose_path:String}) AND NOT match(path, {prose_exempt:String} 43d056307666 ALTER TABLE loom.shared UPDATE tombstoned_at = {now:DateTime} WHERE (org = {org:String} AND tombstoned_at IS NULL AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mut 4410feb55186 SELECT chunk_id, path, scope, kind, start_line, end_line, content, symbol_ids, context_description, cosineDistance(embedding, {q:Array(Float32)}) AS distance FROM loom.code_chunks FINAL WHERE org = {o 442e8a78a975 SELECT org, namespace, agent, user_id, session_id, scope, embedding_model, memory_key FROM loom.memory_embeddings PREWHERE embedding_dim = ? WHERE tombstoned_at IS NULL AND embed_failed_at IS NULL AND @@ -625,6 +631,7 @@ 47cc75ceb8fa SELECT count() AS n FROM ( SELECT evidence_id, tombstoned_at FROM loom.memory_evidence WHERE org = {org:String} AND namespace = {ns:String} AND agent = {agent:String} AND user_id = {uid:String} AND se 47d6216caf2e SELECT number, state, author, title, labels, opened_at, closed_at, updated_at, files, title_hits, file_hit FROM ( SELECT number, state, author, title, labels, opened_at, closed_at, updated_at, files, 47db1deeabfd SELECT DISTINCT namespace FROM ( SELECT namespace FROM loom.memory WHERE org = {org:String} AND (namespace, agent, user_id, session_id, memory_key) IN ( SELECT namespace, agent, user_id, session_id, m +47dd9527eede SELECT * FROM ( SELECT *, row_number() OVER ( ORDER BY (if(match(path, {noise_path:String}), {noise_penalty:Float64}, ?) * if(match(path, {prose_path:String}) AND NOT match(path, {prose_exempt:String} 47e13d18aa4f SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, ? - cosineDistance(e.embedding, {qv:Array(Float32)}) AS similarity, toString(coalesce(e.temporal_ 47ea41c2e2e8 SELECT agent, user_id, session_id, embedding_model, summary_text, key_facts, derived_from, valid_at, created_at, version, length(key_facts) AS kf, length(derived_from) AS df, coalesce(valid_at, create 482347c34a21 SELECT memory_key, groupUniqArray(?)(ent) AS shared FROM ( SELECT other.memory_key AS memory_key, other.entity_a AS ent FROM loom.entity_edge_memories AS other WHERE other.org = {o:String} AND other.n @@ -645,8 +652,10 @@ 4a1b7c09946c SELECT pr_number, any(title) AS title, any(body_excerpt) AS body_excerpt, any(merge_commit_sha) AS merge_commit_sha, min(merged_at) AS merged_at, any(linked_issues) AS linked_issues FROM loom.code_pr_ 4a4a4fc0989b ALTER TABLE loom.knowledge_ingest_cancels DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_s 4a536b32504b SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, ? - cosineDistance(e.embedding, {qv:Array(Float32)}) AS similarity, toString(coalesce(e.temporal_ +4a8cd6932be6 SELECT * FROM ( SELECT *, row_number() OVER ( ORDER BY (if(match(path, {noise_path:String}), {noise_penalty:Float64}, ?) * if(match(path, {prose_path:String}) AND NOT match(path, {prose_exempt:String} 4aeabb5d4edf SELECT count() AS n FROM loom.namespace_guides WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND ? 4b65a7bc66f1 SELECT count() AS n FROM loom.memory_records FINAL WHERE org = {org:String} AND tombstoned_at IS NULL AND user_id = {uid:String} +4b8f88904506 SELECT * FROM ( SELECT *, row_number() OVER ( ORDER BY (if(match(path, {noise_path:String}), {noise_penalty:Float64}, ?) * if(match(path, {prose_path:String}) AND NOT match(path, {prose_exempt:String} 4bcc327f9556 ALTER TABLE loom.knowledge_gaps DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 4bfcae48a0ba ALTER TABLE loom.query_history_sources DELETE WHERE (org = {org:String} AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 4c0a0c4d2640 SELECT namespace, parent FROM loom.collections FINAL WHERE org = {org:String} AND NOT deleted @@ -1437,6 +1446,7 @@ a30fe8e84093 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e. a339b1bc6929 ALTER TABLE loom.memory_chunks UPDATE tombstoned_at = {now:DateTime} WHERE (org = {org:String} AND tombstoned_at IS NULL AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {eras a33eb1d76cb3 SELECT count() AS n FROM loom.context_blobs FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL a350e145841a ALTER TABLE loom.memory_chunk_sources DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync +a38a8f28fbeb SELECT * FROM ( SELECT *, row_number() OVER ( ORDER BY (if(match(path, {noise_path:String}), {noise_penalty:Float64}, ?) * if(match(path, {prose_path:String}) AND NOT match(path, {prose_exempt:String} a3afc43cd42d SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e.content_excerpt AS content_excerpt, ? - cosineDistance(e.embedding, {qv:Array(Float32)}) AS similarity, toString(coalesce(e.temporal_ a3b7af18a429 SELECT ? FROM (SELECT * FROM loom.conversation_embeddings FINAL WHERE org = {org:String} AND namespace = {ns:String} AND thread_id = {tid:String} AND tombstoned_at IS NULL AND (embedding_model, msg_id a3cd47767201 SELECT count() AS n FROM loom.memory_chunks FINAL WHERE org = {org:String} AND (user_id = {uid:String} OR (user_id = ? AND (namespace, parent_memory_key) IN {keys:Array(Tuple(String, String))})) @@ -1850,6 +1860,7 @@ ce2f9959b87c SELECT count() AS n FROM loom.operator_edges FINAL WHERE org = {org ce4e744d75e7 SELECT count() AS n FROM loom.entity_edge_memories WHERE org = {org:String} AND namespace IN {ns:Array(String)} ce55cb9f5075 SELECT agent, user_id, session_id, memory_key FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL AND has(tags, {tag:String}) AND user_id = {scope_uid ce58bcb21c01 SELECT countIf(status = ? AND NOT (lowerUTF8(subject) IN (?, ?) OR startsWith(lowerUTF8(subject), ?) OR startsWith(lowerUTF8(subject), ?) OR startsWith(lowerUTF8(subject), ?))) AS people, countIf(stat +ce6b08dedf48 SELECT * FROM ( SELECT *, row_number() OVER ( ORDER BY (if(match(path, {noise_path:String}), {noise_penalty:Float64}, ?) * if(match(path, {prose_path:String}) AND NOT match(path, {prose_exempt:String} ce7728a369c3 SELECT hit.? - ? AS qidx, m.memory_id, m.memory_key, m.value, m.pinned, m.agent, m.user_id, m.session_id, m.run_id, m.valid_at, hit.? AS dist FROM loom.memory m FINAL JOIN ( SELECT agent, user_id, ses ce863a08478e SELECT count() AS n FROM loom.context_blobs FINAL WHERE org = {org:String} AND user_id = {uid:String} cea581143d39 SELECT DISTINCT org, namespace, agent, user_id, session_id, memory_key FROM loom.memory WHERE tombstoned_at IS NULL AND sensitivity = ? AND (expires_at IS NULL OR expires_at > now()) AND (match(value, @@ -1910,6 +1921,7 @@ d455eae6762a SELECT count() AS n FROM loom.procedure_runs WHERE org = {org:Strin d469073eeef7 SELECT subject, relation, object, sum(co_occur) AS co_occur, max(last_seen) AS last_seen, -- The strongest tier behind the aggregated triple. -- Not `AS provenance`: with the provenance filter in WHER d4a86d775cfd SELECT path, chunk_id, argMax(tombstoned_at IS NULL, version) AS is_live FROM loom.code_chunks WHERE org = {org:String} AND namespace = {ns:String} AND embedding_model = {model:String} AND path IN {pa d4dce40507f9 SELECT state_key, state_value, version FROM loom.code_index_state FINAL WHERE org = ? AND namespace = {ns:String} AND state_key IN {keys:Array(String)} +d4eb7b1a51b0 SELECT * FROM ( SELECT *, row_number() OVER ( ORDER BY (if(match(path, {noise_path:String}), {noise_penalty:Float64}, ?) * if(match(path, {prose_path:String}) AND NOT match(path, {prose_exempt:String} d4ef142bf4bd ALTER TABLE loom.conversation_embeddings UPDATE is_saved = false, saved_at = NULL, tombstoned_at = {when:DateTime} WHERE org = {org:String} AND namespace = {ns:String} AND agent = {agent:String} AND t d4fee96dc8f4 SELECT symbol_id, qualified_name, name, signature, path, start_line, end_line, tier, kind, toString(indexed_commit) AS extent_commit FROM loom.code_symbols FINAL WHERE org = {org:String} AND namespace d557e6a3b134 SELECT memory_key, memory_type, confidence, version, created_at, expires_at, valid_at, pinned, status, evidence_count, recall_count, last_recalled_at, tags, entities, source_trace, sensitivity, verifi diff --git a/tests/unit/test_code_fusion_signals.py b/tests/unit/test_code_fusion_signals.py index ac88f2be9c..879b13f215 100644 --- a/tests/unit/test_code_fusion_signals.py +++ b/tests/unit/test_code_fusion_signals.py @@ -2,15 +2,28 @@ from __future__ import annotations +from typing import Any + from server.code.app.search.priors import ( _COHERENCE_FRAC, _NOISE_PENALTY, _STEM_BOOST_CAP, _apply_fusion_signals, + pool_penalties, ) from server.code.domain.units import CodeUnit +def _signals( + ranked: list[CodeUnit], query: str, *, prose: bool = False, **kw: Any +) -> list[CodeUnit]: + """The ranking's call: the path factors are the query's own (`pool_penalties`), + with the prose penalty only when `prose` (a search not constrained to paths).""" + return _apply_fusion_signals( + ranked, query, path_penalties=pool_penalties(query, prose_eligible=prose), **kw + ) + + def _u(path: str, score: float, symbol: str = "") -> CodeUnit: return CodeUnit(path=path, score=score, symbol=symbol) @@ -18,7 +31,7 @@ def _u(path: str, score: float, symbol: str = "") -> CodeUnit: def test_test_dir_demoted_below_equal_impl() -> None: impl = _u("src/Storages/MergeTree/MergeTreeData.cpp", 0.030) test = _u("src/Storages/tests/gtest_merge_tree.cpp", 0.030) - out = _apply_fusion_signals([test, impl], "background merge selection") + out = _signals([test, impl], "background merge selection") assert out[0].path == impl.path assert out[-1].score < impl.score @@ -26,13 +39,13 @@ def test_test_dir_demoted_below_equal_impl() -> None: def test_functional_test_queries_dir_demoted() -> None: impl = _u("src/Interpreters/Cache/QueryResultCache.cpp", 0.030) sql = _u("tests/queries/0_stateless/02494_query_cache.sql", 0.031) - out = _apply_fusion_signals([sql, impl], "how is the result cached") + out = _signals([sql, impl], "how is the result cached") assert out[0].path == impl.path def test_noise_penalty_demotes_but_never_drops() -> None: test = _u("src/Common/tests/gtest_lru.cpp", 0.030) - out = _apply_fusion_signals([test], "lru cache eviction") + out = _signals([test], "lru cache eviction") assert len(out) == 1 assert out[0].score > 0 @@ -40,13 +53,13 @@ def test_noise_penalty_demotes_but_never_drops() -> None: def test_stem_affinity_promotes_matching_path() -> None: match = _u("src/Interpreters/Cache/QueryResultCache.cpp", 0.030) other = _u("src/Processors/Merges/MergingSortedTransform.cpp", 0.030) - out = _apply_fusion_signals([other, match], "query result cache eviction") + out = _signals([other, match], "query result cache eviction") assert out[0].path == match.path def test_stem_boost_is_capped() -> None: match = _u("src/Interpreters/Cache/QueryResultCache.cpp", 0.030) - out = _apply_fusion_signals([match], "query result cache") + out = _signals([match], "query result cache") # full overlap: x(1 + cap), plus its own coherence share of max ceiling = 0.030 * (1 + _STEM_BOOST_CAP) * (1 + _COHERENCE_FRAC) + 1e-9 assert out[0].score <= ceiling @@ -57,7 +70,7 @@ def test_coherence_concentrates_multi_chunk_file_on_best() -> None: a2 = _u("src/A.cpp", 0.019, symbol="A::g") a3 = _u("src/A.cpp", 0.018, symbol="A::h") b = _u("src/B.cpp", 0.021, symbol="B::f") - out = _apply_fusion_signals([b, a1, a2, a3], "zzz qqq") + out = _signals([b, a1, a2, a3], "zzz qqq") # A.cpp's aggregate evidence (0.057) beats B.cpp's single chunk: A's # best chunk overtakes; A's OTHER chunks do not. assert out[0].symbol == "A::f" @@ -67,7 +80,7 @@ def test_coherence_concentrates_multi_chunk_file_on_best() -> None: def test_penalised_file_cannot_buy_back_via_chunk_count() -> None: impl = _u("src/A.cpp", 0.020, symbol="A::f") tests = [_u("src/tests/gtest_a.cpp", 0.020, symbol=f"T::t{i}") for i in range(5)] - out = _apply_fusion_signals([impl, *tests], "zzz qqq") + out = _signals([impl, *tests], "zzz qqq") # coherence runs over penalised scores: 5 x (0.020*0.5) = 0.050 sum for # the test file vs 0.020 for impl — but the test chunks each sit at # 0.010 base, so impl (0.020 + its coherence share) stays on top. @@ -76,13 +89,13 @@ def test_penalised_file_cannot_buy_back_via_chunk_count() -> None: def test_empty_input_is_noop() -> None: - assert _apply_fusion_signals([], "anything") == [] + assert _signals([], "anything") == [] def test_ties_keep_fused_order() -> None: a = _u("src/X.cpp", 0.030, symbol="X::a") b = _u("src/Y.cpp", 0.030, symbol="Y::b") - out = _apply_fusion_signals([a, b], "zzz qqq") + out = _signals([a, b], "zzz qqq") # identical scores and no signal deltas beyond symmetric coherence: # RRF order survives the stable sort assert [u.symbol for u in out] == ["X::a", "Y::b"] @@ -102,9 +115,7 @@ def test_embedded_identifier_extraction_shapes() -> None: def test_embedded_symbol_boosts_owning_unit() -> None: owner = _u("src/Processors/Executors/X.cpp", 0.030, symbol="DB::PipelineExecutor::execute") other = _u("src/Interpreters/Y.cpp", 0.030, symbol="DB::Context::getSettings") - out = _apply_fusion_signals( - [other, owner], "how does PipelineExecutor schedule zzz onto worker threads" - ) + out = _signals([other, owner], "how does PipelineExecutor schedule zzz onto worker threads") assert out[0].symbol.endswith("PipelineExecutor::execute") @@ -112,8 +123,8 @@ def test_embedded_symbol_ignores_mere_mentions() -> None: # a unit whose SCOPE is unrelated is not boosted even if its body would # mention the identifier — the signal reads metadata, not content caller = _u("src/A.cpp", 0.030, symbol="DB::Unrelated::run") - out = _apply_fusion_signals([caller], "what does PipelineExecutor do") - base = _apply_fusion_signals([caller], "what does zzz qqq do") + out = _signals([caller], "what does PipelineExecutor do") + base = _signals([caller], "what does zzz qqq do") assert out[0].score == base[0].score @@ -124,9 +135,7 @@ def test_test_intent_query_is_not_penalized() -> None: penalty skipped for test-intent queries).""" harness = _u("tests/clickhouse-test", 0.030) impl = _u("src/Interpreters/InterpreterSelectQuery.cpp", 0.030) - out = _apply_fusion_signals( - [impl, harness], "how does clickhouse-test schedule tests in parallel" - ) + out = _signals([impl, harness], "how does clickhouse-test schedule tests in parallel") by_path = {u.path: u.score for u in out} # no demotion under test intent: the harness file's score is not halved assert by_path["tests/clickhouse-test"] > 0.030 * _NOISE_PENALTY * 1.5 @@ -134,35 +143,33 @@ def test_test_intent_query_is_not_penalized() -> None: def test_ci_intent_spares_ci_workflow_paths() -> None: hook = _u("ci/jobs/scripts/workflow_hooks/filter_job.py", 0.030) - out = _apply_fusion_signals([hook], "how does CI skip jobs for changed files") + out = _signals([hook], "how does CI skip jobs for changed files") assert out[0].score >= 0.030 # never demoted (ci/ isn't noise-dir anyway) def test_implementation_query_still_demotes_tests() -> None: impl = _u("src/Storages/MergeTree/MergeTreeData.cpp", 0.030) test = _u("src/Storages/tests/gtest_merge_tree.cpp", 0.030) - out = _apply_fusion_signals([test, impl], "background merge selection") + out = _signals([test, impl], "background merge selection") assert out[0].path == impl.path def test_prose_file_demoted_below_the_source_it_describes() -> None: notes = _u("docs/releases/4.2.txt", 0.031) impl = _u("django/db/models/query.py", 0.030) - out = _apply_fusion_signals([notes, impl], "QuerySet.update crashes", prose_penalty=0.25) + out = _signals([notes, impl], "QuerySet.update crashes", prose=True) assert out[0].path == impl.path def test_prose_penalty_skips_documentation_questions() -> None: notes = _u("docs/topics/cache.txt", 0.031) impl = _u("django/core/cache/backends/base.py", 0.030) - out = _apply_fusion_signals( - [notes, impl], "where is the cache documentation", prose_penalty=0.25 - ) + out = _signals([notes, impl], "where is the cache documentation", prose=True) assert out[0].path == notes.path def test_prose_paths_are_matched_by_file_not_by_directory_word() -> None: - from server.code.app.search.priors import is_prose_path + from server.code.domain.index.path_class import is_prose_path assert is_prose_path("doc/en/changelog.rst") assert is_prose_path("CHANGES") diff --git a/tests/unit/test_code_lexical_pool_cut.py b/tests/unit/test_code_lexical_pool_cut.py new file mode 100644 index 0000000000..d4e6396d15 --- /dev/null +++ b/tests/unit/test_code_lexical_pool_cut.py @@ -0,0 +1,348 @@ +"""The lexical leg cuts its pool on the vote a row has in the ranking: the factor of +its path over the reciprocal-rank constant plus its rank in the leg.""" + +from __future__ import annotations + +import asyncio +import random +from typing import Any + +import pytest + +from server.code.app.search import search +from server.code.app.search.fusion import _rrf_fuse, leg_provenance +from server.code.app.search.lexical import _lexical_leg +from server.code.app.search.priors import ( + _NOISE_PENALTY, + _apply_fusion_signals, + pool_penalties, +) +from server.code.domain.index import path_class, query_trim +from server.code.domain.index.pool_cut import MAX_DEPTH, RRF_K, cut_depth +from server.code.domain.search_scope import SearchScope +from server.code.domain.units import CodeUnit +from server.code.store.index.sql import path_penalty_sql +from server.settings import settings + +_IMPLEMENTATION = "how are parts merged" +_TESTS = "how are flaky tests retried" +_DOCS = "where is the cache documentation" + + +@pytest.fixture(autouse=True) +def _prose_penalty_on(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(settings, "code_search_prose_penalty", 0.25) + monkeypatch.setattr(settings, "code_fusion_signals", True) + + +@pytest.mark.parametrize( + "query,penalties", + [ + (_IMPLEMENTATION, (_NOISE_PENALTY, 0.25)), + (_TESTS, (1.0, 0.25)), + (_DOCS, (_NOISE_PENALTY, 1.0)), + ("docs for the test fixtures", (1.0, 1.0)), + ], +) +def test_pool_penalties_follow_the_words_of_the_query( + query: str, penalties: tuple[float, float] +) -> None: + assert pool_penalties(query, prose_eligible=True) == penalties + + +def test_a_search_the_ranking_applies_no_prose_penalty_to_cuts_on_none() -> None: + # constrained to paths, or a symbol lookup + assert pool_penalties(_IMPLEMENTATION, prose_eligible=False) == (_NOISE_PENALTY, 1.0) + + +def test_no_penalty_with_the_fusion_signals_off(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(settings, "code_fusion_signals", False) + assert pool_penalties(_IMPLEMENTATION, prose_eligible=True) == (1.0, 1.0) + + +def _u(path: str, score: float, kind: str = "function") -> CodeUnit: + return CodeUnit(path=path, score=score, kind=kind) + + +@pytest.mark.parametrize("pair", [(0.35, 0.25), (1.0, 0.25), (0.35, 1.0), (1.0, 1.0)]) +def test_the_ranking_multiplies_by_the_pair_it_is_handed(pair: tuple[float, float]) -> None: + """One chunk per file and no query word in a path: every unit gets the same + coherence share, so the score ratios are the path factors alone. The query + asks for tests and docs; only the pair decides.""" + out = _apply_fusion_signals( + [_u("pkg/aaa.py", 0.02), _u("examples/bbb.py", 0.02), _u("guide/ccc.md", 0.02)], + "docs for the test fixtures", + path_penalties=pair, + ) + score = {u.path: u.score for u in out} + assert score["examples/bbb.py"] / score["pkg/aaa.py"] == pytest.approx(pair[0], rel=1e-3) + assert score["guide/ccc.md"] / score["pkg/aaa.py"] == pytest.approx(pair[1], rel=1e-3) + + +@pytest.mark.parametrize( + "path,noise,prose", + [ + ("tests/queries/0_stateless/02494_query_cache.sql", True, False), + ("src/Common/tests/gtest_lru.cpp", True, False), + ("pkg/test/runner.py", True, False), + ("examples/demo.py", True, False), + ("src/Common/test_lru.cpp", True, False), + ("src/Common/lru_fuzz.cc", True, False), + ("src/latest/contest.py", False, False), + ("src/test_lru.py", False, False), + ("docs/releases/4.2.txt", False, True), + ("README.md", False, True), + ("docs/Guide.MD", False, True), + ("CHANGES", False, True), + ("pkg/HISTORY.rst", False, True), + ("tests/README.md", True, True), + ("CMakeLists.txt", False, False), + ("src/cmakelists.TXT", False, False), + ("src/Coordination/Changelog.cpp", False, False), + ("pkg/history.py", False, False), + ("docs/conf.py", False, False), + ], +) +def test_path_classes(path: str, noise: bool, prose: bool) -> None: + assert path_class.is_noise_path(path) is noise + assert path_class.is_prose_path(path) is prose + + +def test_the_sql_factor_binds_the_python_patterns() -> None: + sql, params = path_penalty_sql("path", 0.35, 0.25) + assert sql == ( + "(if(match(path, {noise_path:String}), {noise_penalty:Float64}, 1)" + " * if(match(path, {prose_path:String})" + " AND NOT match(path, {prose_exempt:String}), {prose_penalty:Float64}, 1))" + ) + assert params == { + "noise_path": path_class.NOISE_PATH_PATTERN, + "noise_penalty": 0.35, + "prose_path": path_class.PROSE_PATH_PATTERN, + "prose_exempt": path_class.PROSE_EXEMPT_PATTERN, + "prose_penalty": 0.25, + } + + +# ---- the depth the scan reads --------------------------------------------------- + + +@pytest.mark.parametrize( + "noise,prose,depth", + [ + (1.0, 1.0, 200), # no penalty: the pool itself + (0.35, 1.0, 683), + (1.0, 0.25, 980), + (0.35, 0.25, 2912), # a prose file under a test directory gets both + (1.0, 2.0, 460), # a factor over 1 lifts rows from past the pool + (0.35, 0.01, MAX_DEPTH), + (0.35, 0.0, MAX_DEPTH), + ], +) +def test_cut_depth(noise: float, prose: float, depth: int) -> None: + assert cut_depth(200, noise, prose) == depth + + +def _vote_pool(factors: list[float], pool: int) -> list[int]: + """The ranks (1-based) of the `pool` rows with the largest vote.""" + by_vote = sorted(range(len(factors)), key=lambda i: -factors[i] / (RRF_K + i + 1)) + return sorted(i + 1 for i in by_vote[:pool]) + + +@pytest.mark.parametrize("seed", range(20)) +def test_no_row_past_the_depth_is_in_the_pool(seed: int) -> None: + """Any mix of source, test and prose rows in any order: the rows with the largest + votes all rank within `cut_depth`, so the scan loses none of them.""" + rng = random.Random(seed) + noise, prose = rng.choice([(0.35, 0.25), (1.0, 0.25), (0.35, 1.0), (0.6, 0.9), (0.5, 1.5)]) + pool = rng.choice([5, 50, 200]) + source_share = rng.choice([0.0, 0.02, 0.15, 0.5, 1.0]) + factors = [ + 1.0 if rng.random() < source_share else rng.choice([noise, prose, noise * prose]) + for _ in range(8000) + ] + assert max(_vote_pool(factors, pool)) <= cut_depth(pool, noise, prose) + + +def test_a_first_ranked_test_row_stays_and_the_last_test_rows_leave() -> None: + """What the cut is for, and what it must not do. 1,000 rows, every fifth a source + row. Ranked alone, the pool is 160 test rows and 40 source rows. Cut on votes, the + best test rows stay (the first votes 0.35/61, more than a source row at rank 115) + and the pool reaches source rows the plain cut never saw.""" + factors = [1.0 if rank % 5 == 0 else 0.35 for rank in range(1, 1001)] + pool = _vote_pool(factors, 200) + tests = [r for r in pool if factors[r - 1] < 1.0] + source = [r for r in pool if factors[r - 1] == 1.0] + assert pool[:4] == [1, 2, 3, 4] # the leg's best rows, tests included + assert len(source) > 40 and max(source) > 200 + # test rows leave from the bottom of the leg's order, never from its top + every_test = [rank for rank in range(1, 1001) if factors[rank - 1] < 1.0] + assert 0 < len(tests) < 160 and tests == every_test[: len(tests)] + + +# ---- what the leg hands the ranking and calibration ------------------------------ + + +def test_a_row_votes_with_its_rank_in_the_whole_leg() -> None: + """A source row the cut admitted from rank 340 votes 1/(60+340), not with its place + among the rows that survived; a leg that returns no rank votes by position.""" + cut = [ + {"chunk_id": "test", "lex_rank": 1}, + {"chunk_id": "src", "lex_rank": 2}, + {"chunk_id": "deep", "lex_rank": 340}, + ] + vector = [{"chunk_id": "deep"}, {"chunk_id": "other"}] + scores = {r["chunk_id"]: s for r, s in _rrf_fuse(cut, vector)} + assert scores["deep"] == 1.0 / (RRF_K + 340) + 1.0 / (RRF_K + 1) + assert scores["src"] == 1.0 / (RRF_K + 2) + assert scores["other"] == 1.0 / (RRF_K + 2) + assert leg_provenance(cut, vector)["deep"] == ("both", 340, 1) + plain = [{"chunk_id": "a"}, {"chunk_id": "b"}] + assert leg_provenance(plain, [])["b"] == ("lexical", 2, 0) + + +_UNIT = { + "scope": "f", + "kind": "function", + "start_line": 1, + "end_line": 9, + "content": "x", + "symbol_ids": [], + "context_description": "", +} + + +def _row(cid: str, path: str, rank: int, in_pool: bool) -> dict[str, Any]: + return { + "chunk_id": cid, + "path": path, + "lex_score": 100.0 / rank, + "lex_rank": rank, + "in_pool": in_pool, + **_UNIT, + } + + +# What the cut statement returns for a pool of 200: the leg's first rows, of which the +# second (a prose file) lost its pool slot, and a source row the cut admitted from rank 340. +_CUT_ROWS = [ + _row("test", "tests/test_a.py", 1, True), + _row("notes", "docs/notes.md", 2, False), + _row("src", "src/a.py", 3, True), + _row("deep", "src/b.py", 340, True), +] + + +class _Repo: + """Answers the lexical leg with `rows` and records the penalties it was asked to + cut its pool on; the vector leg ranks the prose row the cut left out second.""" + + def __init__(self, rows: list[dict[str, Any]] | None = None) -> None: + self.rows = rows or [{"chunk_id": "a", "lex_score": 4.0, "path": "src/a.py", **_UNIT}] + self.penalties: list[tuple[float, float]] = [] + + async def code_corpus_stats(self, org: str, ns: str, tokens: list[str]) -> Any: + return {t: 1 for t in tokens}, 100, 10.0 + + async def lexical_search_chunks(self, *a: Any, **k: Any) -> list[dict[str, Any]]: + self.penalties.append((k["noise_penalty"], k["prose_penalty"])) + return self.rows + + async def vector_search_chunks(self, *a: Any, **k: Any) -> list[dict[str, Any]]: + return [ + {"chunk_id": "other", "distance": 0.2, "path": "src/c.py", **_UNIT}, + {"chunk_id": "notes", "distance": 0.3, "path": "docs/notes.md", **_UNIT}, + ] + + async def symbols_fuzzy(self, *a: Any, **k: Any) -> list[Any]: + return [] + + async def unit_signals(self, *a: Any, **k: Any) -> dict[str, Any]: + return {} + + +class _Embedder: + model_name = "fake-embed" + + async def embed(self, text: str) -> list[float]: + return [0.1, 0.2, 0.3] + + +def _leg(rows: list[dict[str, Any]]) -> tuple[list[str], list[str]]: + work = {"lexical_queries": 0} + trim = query_trim.plan(_IMPLEMENTATION, None, 48, work) + pool, head, _, _ = asyncio.run( + _lexical_leg( + _Repo(rows), # type: ignore[arg-type] + "o", + "n", + "m", + run_lexical=True, + tokens=trim.tokens, + trim=trim, + work=work, + path_prefix="", + scope=None, + path_penalties=(0.35, 0.25), + ) + ) + return [r["chunk_id"] for r in pool], [r["chunk_id"] for r in head] + + +def test_the_leg_returns_the_cut_pool_and_its_own_first_rows() -> None: + assert _leg(_CUT_ROWS) == (["test", "src", "deep"], ["test", "notes", "src"]) + + +def test_a_leg_that_cut_nothing_returns_one_list_for_both() -> None: + plain = [{"chunk_id": "a", "path": "src/a.py"}, {"chunk_id": "b", "path": "tests/b.py"}] + assert _leg(plain) == (["a", "b"], ["a", "b"]) + + +def test_calibration_reads_the_leg_s_own_order_and_the_ranking_reads_the_pool( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """The prose row is the leg's second row and the vector leg's second, so the legs + agree and it leads the fusion calibration reads (top similarity 0.7, its own), as + without the cut. It lost its pool slot, so it is ranked on its vector vote alone; + fused from the pool, the vector leg's first row would lead (0.8) and no row would + be in both legs.""" + monkeypatch.setattr(settings, "code_search_pr_leg", "off") + res = asyncio.run( + search(_Repo(_CUT_ROWS), "o", "n", query=_IMPLEMENTATION, embedder=_Embedder(), top_k=5) # type: ignore[arg-type] + ) + assert "legs_agree=True" in res.score_explanation + assert res.top_similarity == 0.7 + assert "(lexical=3, vector=2)" in res.score_explanation + found = {u.unit_id: (u.via, u.lexical_rank, u.vector_rank) for u in res.units} + assert found == { + "test": ("lexical", 1, 0), + "other": ("vector", 0, 1), + "notes": ("vector", 0, 2), + "src": ("lexical", 3, 0), + "deep": ("lexical", 340, 0), + } + + +def _asked(query: str, **kw: Any) -> tuple[float, float]: + repo = _Repo() + asyncio.run(search(repo, "o", "n", query=query, legs="lexical", **kw)) # type: ignore[arg-type] + assert len(repo.penalties) == 1 + return repo.penalties[0] + + +def test_search_hands_the_leg_the_penalties_of_the_query(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(settings, "code_search_pr_leg", "off") + assert _asked(_IMPLEMENTATION) == (_NOISE_PENALTY, 0.25) + assert _asked(_TESTS) == (1.0, 0.25) + assert _asked(_DOCS) == (_NOISE_PENALTY, 1.0) + # a search scoped to paths: the ranking applies no prose penalty + scoped = SearchScope(extensions=("py",)) + assert _asked(_IMPLEMENTATION, scope=scoped) == (_NOISE_PENALTY, 1.0) + + +def test_the_leg_cuts_on_nothing_the_ranking_does_not_apply( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setattr(settings, "code_fusion_signals", False) + monkeypatch.setattr(settings, "code_search_pr_leg", "off") + assert _asked(_IMPLEMENTATION) == (1.0, 1.0) diff --git a/tests/unit/test_code_lexical_statement.py b/tests/unit/test_code_lexical_statement.py index cf3b01aaec..ec5a7cf30c 100644 --- a/tests/unit/test_code_lexical_statement.py +++ b/tests/unit/test_code_lexical_statement.py @@ -69,6 +69,54 @@ def test_lexical_statement_byte_for_byte() -> None: } +def test_a_path_penalty_wraps_the_statement_in_the_cut_on_votes() -> None: + """The leg's own statement, read `cut_depth` rows deep, inside one that ranks those + rows, marks the pool with the largest factor / (RRF_K + rank) and returns it with + the leg's first rows. Both order rows of one score by their factor.""" + from server.code.store.index.sql import path_penalty_sql + + sql, params = _statement(noise_penalty=0.35) + factor, factor_params = path_penalty_sql("path", 0.35, 1.0) + order = f"ORDER BY lex_score DESC, {factor} DESC" + inner = _TODAY.replace("ORDER BY lex_score DESC", order).replace( + "LIMIT {pool:UInt32}", "LIMIT {depth:UInt32}" + ) + assert sql == ( + """ + SELECT * + FROM ( + SELECT *, row_number() OVER ( + ORDER BY """ + + factor + + """ / ({rrf_k:Float64} + lex_rank) DESC + ) <= {pool:UInt32} AS in_pool + FROM ( + SELECT *, row_number() OVER (""" + + order + + """) AS lex_rank + FROM (""" + + inner + + """) + ) + ) + WHERE in_pool OR lex_rank <= {pool:UInt32} + ORDER BY lex_rank + """ + ) + assert params == { + "org": "o", + "ns": "n", + "model": "m", + "tokens": ["merge", "tree"], + "gate_query": "merge tree", + "idfs": [2.5, 0.7], + "pool": 200, + "rrf_k": 60.0, + "depth": 683, + **factor_params, + } + + # ---- corpus stats ------------------------------------------------------------ @@ -142,8 +190,8 @@ def test_code_term_df_refresh_replaces_the_snapshot_hourly() -> None: def test_search_gates_on_every_query_token_and_times_the_leg() -> None: - """The service hands the leg its tokens and idfs (every token gates) and - records the leg's wall time.""" + """The service hands the leg its tokens and idfs (every token gates) and the + path penalties the pool is cut on, and records the leg's wall time.""" from server.code.app import search as cs seen: dict[str, Any] = {} @@ -185,5 +233,5 @@ async def run(**kw: Any) -> Any: res = asyncio.run(run()) tokens, idfs = seen["args"][3], seen["args"][4] assert tokens and len(idfs) == len(tokens) - assert set(seen["kw"]) == {"path_prefix", "pool", "scope"} + assert set(seen["kw"]) == {"path_prefix", "pool", "scope", "noise_penalty", "prose_penalty"} assert "lexical_leg_ms" in res.retrieval_work diff --git a/tests/unit/test_code_lexical_token_gate_sql.py b/tests/unit/test_code_lexical_token_gate_sql.py index 1975fa8d17..0b480c2ac9 100644 --- a/tests/unit/test_code_lexical_token_gate_sql.py +++ b/tests/unit/test_code_lexical_token_gate_sql.py @@ -1,4 +1,5 @@ -"""The lexical gate admits every scored identifier and rejects partial tokens.""" +"""The lexical gate admits every scored identifier and rejects partial tokens, and +the pool is cut on the vote the path penalties leave each row.""" from __future__ import annotations @@ -67,3 +68,101 @@ async def test_identifier_gate_keeps_identity_model_prefix_and_pool() -> None: "o", "n", "m", ["__init__"], [1.0], path_prefix="src/", pool=1 ) assert len(rows) == 1 and rows[0]["path"] in {"src/one.py", "src/two.py"} + + +@pytest.mark.asyncio +async def test_the_pool_is_cut_on_the_vote_each_row_has_in_the_ranking() -> None: + rows = ( + _row("tests/test_merge.py", "merge tree select"), + _row("docs/merge.txt", "merge tree select"), + _row("src/merge.py", "merge tree"), + _row("src/CMakeLists.txt", "merge tree"), + ) + tokens, idfs = ["merge", "tree", "select"], [1.0, 1.0, 1.0] + first_two = {"tests/test_merge.py", "docs/merge.txt"} + + async def leg(n: int, **penalties: float) -> list[dict]: + return await _repo(*rows).lexical_search_chunks( + "o", "n", "m", tokens, idfs, pool=n, **penalties + ) + + def pool(found: list[dict]) -> list[tuple[str, float, int]]: + return [(r["path"], r["lex_score"], r["lex_rank"]) for r in found if r["in_pool"]] + + # the test and the doc match one more term, so they are the leg's first two rows + assert {r["path"] for r in await leg(2)} == first_two + # a source row at rank 3 votes 1/63, the test row at most 0.35/61: the pool goes + # to the source rows, which keep their ranks in the whole leg + cut = await leg(2, noise_penalty=0.35, prose_penalty=0.25) + assert {p for p, _, _ in pool(cut)} == {"src/merge.py", "src/CMakeLists.txt"} + assert [(score, rank) for _, score, rank in pool(cut)] == [(2.0, 3), (2.0, 4)] + # the leg's own first two rows come back beside the pool, in rank order + assert [r["lex_rank"] for r in cut] == [1, 2, 3, 4] + assert {r["path"] for r in cut if not r["in_pool"]} == first_two + # a test row that makes the cut keeps its rank and its score + kept = pool(await leg(3, noise_penalty=0.35, prose_penalty=0.25)) + assert kept[0][:2] == ("tests/test_merge.py", 3.0) and kept[0][2] in (1, 2) + assert {p for p, _, _ in kept[1:]} == {"src/merge.py", "src/CMakeLists.txt"} + # a question that asks for tests cuts on the prose factor alone + asked = pool(await leg(2, prose_penalty=0.25)) + assert asked[0][:2] == ("tests/test_merge.py", 3.0) and asked[1][0].startswith("src/") + + +@pytest.mark.asyncio +async def test_a_first_ranked_test_row_outlasts_source_rows_that_match_less() -> None: + """The test row matches all three terms and 130 source rows match two. Its vote, + 0.35/61, is worth a source row at rank 115, so a pool of 120 keeps it at rank 1 + beside the 119 best source rows. A cut on score times factor (3 x 0.35 under 2) + would have dropped it for any pool under 131.""" + source = ( + "INSERT INTO loom.code_chunks (org, namespace, embedding_model, path, chunk_id, " + "content, lexemes, embedding) SELECT 'o', 'n', 'm', concat('src/m', toString(number), " + "'.py'), generateUUIDv4(), '', 'merge tree', arrayResize([0.1], 3072, 0.1) " + "FROM numbers(130)" + ) + repo = _repo(_row("tests/test_merge.py", "merge tree select"), source) + found = await repo.lexical_search_chunks( + "o", "n", "m", ["merge", "tree", "select"], [1.0, 1.0, 1.0], pool=120, noise_penalty=0.35 + ) + assert [(r["lex_rank"], bool(r["in_pool"])) for r in found] == [ + (rank, True) for rank in range(1, 121) + ] + assert found[0]["path"] == "tests/test_merge.py" + + +def _rows(prefix: str, n: int) -> str: + """`n` chunks under `prefix`, each holding the lexemes `merge tree`.""" + return ( + "INSERT INTO loom.code_chunks (org, namespace, embedding_model, path, chunk_id, " + f"content, lexemes, embedding) SELECT 'o', 'n', 'm', concat('{prefix}', " + "toString(number), '.py'), generateUUIDv4(), '', 'merge tree', " + f"arrayResize([0.1], 3072, 0.1) FROM numbers({n})" + ) + + +@pytest.mark.asyncio +async def test_rows_of_one_score_rank_source_first_wherever_the_table_holds_them() -> None: + """600 rows match both terms and tie: 300 source rows between 150 benchmark rows the + table holds before them and 150 test rows it holds after. ClickHouse returns equal + rows in no fixed order, and the rank decides the pool, so the rank reads the factor + next: the source rows take ranks 1 to 300, and a pool of 100 is source rows only.""" + repo = _repo(_rows("benchmarks/b", 150), _rows("src/m", 300), _rows("tests/t", 150)) + found = await repo.lexical_search_chunks( + "o", "n", "m", ["merge", "tree"], [1.0, 1.0], pool=100, noise_penalty=0.35 + ) + assert [(r["lex_rank"], bool(r["in_pool"])) for r in found] == [ + (rank, True) for rank in range(1, 101) + ] + assert all(r["path"].startswith("src/") for r in found) + + +@pytest.mark.asyncio +async def test_rows_of_one_score_fill_the_pool_with_demoted_rows_after_the_source() -> None: + """With 40 source rows in the tie, they take ranks 1 to 40 and the benchmark and + test rows the rest of a pool of 100.""" + repo = _repo(_rows("benchmarks/b", 150), _rows("src/m", 40), _rows("tests/t", 150)) + found = await repo.lexical_search_chunks( + "o", "n", "m", ["merge", "tree"], [1.0, 1.0], pool=100, noise_penalty=0.35 + ) + assert [r["lex_rank"] for r in found] == list(range(1, 101)) + assert [r["path"].startswith("src/") for r in found] == [True] * 40 + [False] * 60 diff --git a/tests/unit/test_code_search_catalogue_prior.py b/tests/unit/test_code_search_catalogue_prior.py index 8d50d82b2d..0ccceda59e 100644 --- a/tests/unit/test_code_search_catalogue_prior.py +++ b/tests/unit/test_code_search_catalogue_prior.py @@ -3,17 +3,29 @@ from __future__ import annotations +from typing import Any from unittest.mock import patch from server.code.app.search.priors import ( _CATALOGUE_FILE_RE, _apply_fusion_signals, _catalogue_penalty, + pool_penalties, ) from server.code.domain.units import CodeUnit from server.settings import settings +def _signals( + ranked: list[CodeUnit], query: str, *, prose: bool = False, **kw: Any +) -> list[CodeUnit]: + """The ranking's call: the path factors are the query's own (`pool_penalties`), + with the prose penalty only when `prose` (a search not constrained to paths).""" + return _apply_fusion_signals( + ranked, query, path_penalties=pool_penalties(query, prose_eligible=prose), **kw + ) + + def _u(path: str, score: float) -> CodeUnit: return CodeUnit(unit_id=path, path=path, kind="function", score=score, body="x") @@ -29,9 +41,9 @@ def test_catalogue_regex_names_the_catalogues_only() -> None: def test_penalty_reorders_only_when_set() -> None: ranked = [_u("src/Core/Settings.cpp", 1.0), _u("src/Common/MemoryTracker.cpp", 0.9)] with patch.object(settings, "code_fusion_signals", True): - same = _apply_fusion_signals(list(ranked), "where is the memory limit enforced") + same = _signals(list(ranked), "where is the memory limit enforced") assert [u.path for u in same][0] == "src/Core/Settings.cpp" - demoted = _apply_fusion_signals( + demoted = _signals( list(ranked), "where is the memory limit enforced", catalogue_penalty=0.35, diff --git a/tests/unit/test_code_search_provenance.py b/tests/unit/test_code_search_provenance.py index 87f14d71fd..c6db7aeb70 100644 --- a/tests/unit/test_code_search_provenance.py +++ b/tests/unit/test_code_search_provenance.py @@ -338,6 +338,23 @@ def test_track_path_lexical_only_reports_no_vector_side() -> None: assert res.tracked["best"]["distance"] is None +def test_track_verdict_names_a_row_the_leg_cut_on_its_path_penalty() -> None: + lexical = [_lex("a", 40.0) | {"lex_rank": 2}, _lex("b", 10.0) | {"lex_rank": 9}] + out = track_verdict( + "tests/test_z.py", + [_chunk("z1", 55.0, None)], + lexical, + [], + served_ids=["a"], + pool=2, + vector_ran=False, + lexical_ran=True, + ) + assert out["verdict"] == ( + "beyond pool: lexical 55.00 over floor 10.00, cut on its path penalty" + ) + + def test_track_verdict_beyond_full_pools_reports_floor_and_ceiling() -> None: lexical = [_lex("a", 40.0), _lex("b", 10.0)] vector = [_vec("c", 0.1), _vec("a", 0.2)] diff --git a/tests/unit/test_code_symbol_fan_in.py b/tests/unit/test_code_symbol_fan_in.py index 001ce3b033..160032d968 100644 --- a/tests/unit/test_code_symbol_fan_in.py +++ b/tests/unit/test_code_symbol_fan_in.py @@ -9,12 +9,22 @@ import pytest from server.code.app import fan_in as code_fan_in -from server.code.app.search.priors import _COHERENCE_FRAC, _apply_fusion_signals +from server.code.app.search.priors import _COHERENCE_FRAC, _apply_fusion_signals, pool_penalties from server.code.domain.units import CodeUnit from server.code.store.index import CODE_SYMBOL_STATS_COLS, build_row from server.code.workers.graph_stats import compute_symbol_stats +def _signals( + ranked: list[CodeUnit], query: str, *, prose: bool = False, **kw: Any +) -> list[CodeUnit]: + """The ranking's call: the path factors are the query's own (`pool_penalties`), + with the prose penalty only when `prose` (a search not constrained to paths).""" + return _apply_fusion_signals( + ranked, query, path_penalties=pool_penalties(query, prose_eligible=prose), **kw + ) + + def _agg(sid: str, qn: str, calls: int, nontest: int, files: int) -> dict[str, Any]: return { "symbol_id": sid, @@ -299,13 +309,13 @@ def test_fusion_prior_lifts_hub_under_cap_and_skips_tests_and_noise() -> None: score=0.031, fan_in=1706, ) - off = _apply_fusion_signals([leaf, hub], "zzz qqq") + off = _signals([leaf, hub], "zzz qqq") assert [u.unit_id for u in off] == ["l", "h"] # cap 0 (stats not read): order unchanged - on = _apply_fusion_signals([leaf, hub, noisy], "zzz qqq", prior_cap=0.25) + on = _signals([leaf, hub, noisy], "zzz qqq", prior_cap=0.25) assert on[0].unit_id == "h" by = {u.unit_id: u for u in on} # the whole cap, times its own coherence share of the pool max, nothing more assert by["h"].score <= 0.030 * 1.25 * (1 + _COHERENCE_FRAC) + 1e-9 assert by["t"].score < by["l"].score # noise path: penalised, never boosted - intent = _apply_fusion_signals([leaf, hub], "how are the tests wired", prior_cap=0.25) + intent = _signals([leaf, hub], "how are the tests wired", prior_cap=0.25) assert [u.unit_id for u in intent] == ["l", "h"] # test intent: prior skipped