Skip to content
Merged
32 changes: 32 additions & 0 deletions docs/architecture/code-index-architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions docs/reference/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |
Expand Down Expand Up @@ -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. |
Expand Down
15 changes: 9 additions & 6 deletions loom.example.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions schemas/loom-settings.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down
9 changes: 7 additions & 2 deletions server/code/app/search/calibrate.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
4 changes: 2 additions & 2 deletions server/code/app/search/definitions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down
41 changes: 28 additions & 13 deletions server/code/app/search/fusion.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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):
Expand Down Expand Up @@ -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)
Expand Down
9 changes: 7 additions & 2 deletions server/code/app/search/gather.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand All @@ -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(
Expand Down
19 changes: 14 additions & 5 deletions server/code/app/search/lexical.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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).
Expand All @@ -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(
Expand Down
7 changes: 5 additions & 2 deletions server/code/app/search/pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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,
Expand Down
Loading
Loading