Skip to content
Closed
2 changes: 1 addition & 1 deletion docs/reference/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -654,7 +654,7 @@ The code index's network git (clone, fetch, ls-remote, submodule update) through
| --- | --- | --- | --- | --- |
| `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_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_QUERY_MAX_TOKENS` | `int` | `48` | | Long-question trim: past this many lexemes the question is treated as an issue body (template headings stripped, at most 32 tokens gate: its identifiers and its words, those it repeats first; 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. |
| `LOOM_CODE_VECTOR_TABLES` | `str` | `''` | | JSON {label: {"table": "loom.x", "dim": 256}}: where a label's chunk rows live (the coded vector column is fixed-width). Absent label = loom.code_chunks. Inserts and the vector leg route by it. |
Expand Down
5 changes: 3 additions & 2 deletions loom.example.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -1971,8 +1971,9 @@ settings:
# code_fusion_signals: 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 first 512 cleaned words
# embed). Under the cap nothing changes. 0 = off. [restart]
# (template headings stripped, at most 32 tokens gate: its identifiers and its words,
# those it repeats first; the first 512 cleaned words embed). Under the cap nothing
# changes. 0 = off. [restart]
# code_search_query_max_tokens: 48

# Per-file saturation: the 2nd, 3rd... unit from one path is multiplied by
Expand Down
2 changes: 1 addition & 1 deletion schemas/loom-settings.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -2227,7 +2227,7 @@
"code_search_query_max_tokens": {
"default": 48,
"type": "integer",
"description": "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."
"description": "Long-question trim: past this many lexemes the question is treated as an issue body (template headings stripped, at most 32 tokens gate: its identifiers and its words, those it repeats first; the first 512 cleaned words embed). Under the cap nothing changes. 0 = off."
},
"code_search_rerank_default": {
"default": "",
Expand Down
5 changes: 3 additions & 2 deletions server/code/api/models_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,9 @@
class CodeSearchInput(_CodeIdentity, _ResultLessons):
# The question, identifier or phrase to search for; a symbol-shaped query tries the
# symbol table first (`route` says which path answered). A long one (a pasted issue
# body) is clipped to QUERY_MAX_CHARS, never refused: the search keeps its rarest
# terms (code_search_query_max_tokens) whatever its length.
# body) is clipped to QUERY_MAX_CHARS, never refused: the search keeps its identifiers
# and its words, those it repeats first (code_search_query_max_tokens), whatever its
# length.
query: str = Field(
min_length=1,
description="Issue, task, behavior question or identifier to locate in indexed code.",
Expand Down
5 changes: 2 additions & 3 deletions server/code/app/search/cards.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,9 +149,8 @@ async def _concept_leg_rows(
work["concept_terms"] = len(terms)
concept_stats["terms"] = terms
if terms:
plan2 = query_trim.plan(
" ".join(terms), None, settings.code_search_query_max_tokens, {}
)
# chosen terms, all kept: not a question to pick words from
plan2 = query_trim.plan("", terms, settings.code_search_query_max_tokens, {})
c_tokens, c_idfs = await _lexical_terms(
repo,
org,
Expand Down
4 changes: 2 additions & 2 deletions server/code/app/search/gather.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,8 @@ async def _gather_legs(
work, scope, constrained, shape, model = st.work, st.scope, st.constrained, st.shape, st.model
# extra_terms extend the LEXICAL leg only (code.ask query expansion: proposed
# identifiers bridge natural-language -> codebase vocabulary; the vector leg keeps
# embedding the user's actual question). A long question is asked with its rarest
# words and its cleaned first page
# embedding the user's actual question). A long question is asked with its
# identifiers, the words it repeats and its cleaned first page
trim = query_trim.plan(query, extra_terms, settings.code_search_query_max_tokens, work)
tokens = st.tokens = trim.tokens
# one query embedding per embedder per call: _QueryVecMemo
Expand Down
7 changes: 5 additions & 2 deletions server/code/app/search/lexical.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,8 @@ async def _lexical_terms(
"""The lexical leg's (tokens, idfs): one corpus-stats read.

Under an active trim plan the stats read probes EVERY token of the cleaned question
and the leg keeps the rarest `trim.cap` of them (identifiers always)."""
and the leg keeps at most `trim.cap`: its identifiers and its words, those it repeats
first."""
from server.code.app.index import corpus_stats

trimming = trim is not None and trim.active
Expand All @@ -91,7 +92,9 @@ async def _lexical_terms(
df, n_chunks, _avgdl = await corpus_stats.stats(repo, org, ns, base, work)
lex_tokens = tokens
if trimming and trim is not None:
lex_tokens = query_trim.select_rarest(base, df, trim.cap, trim.keep)
lex_tokens = query_trim.select_terms(
base, df, n_chunks, trim.cap, keep=trim.keep, said=trim.said, own=trim.own
)
work["query_trimmed_tokens_used"] = len(lex_tokens)
idfs = [bm25.idf(df.get(t, 0), max(n_chunks, 1)) for t in lex_tokens]
return lex_tokens, idfs
164 changes: 117 additions & 47 deletions server/code/domain/index/query_trim.py
Original file line number Diff line number Diff line change
@@ -1,28 +1,32 @@
"""A long question is asked with its rarest words and its first page.
"""A long question is asked with its identifiers, the words it repeats and its first page.

An issue-shaped question arrives as the issue body: the template's headings ("Company or
project name", "Describe what's wrong", "_No response_") come first, the subject comes
after them, and the reproducer's URL hashes come last. The lexical leg's token list is
the FIRST 32 lexemes in first-seen order (code_search/), so on such a question the
headings and the prose stopwords take the slots, the subject words past position 32
never reach the gate, and the `multiSearchAny` gate admits about half of the corpus
(44–56 % of 267k chunks on the four longest questions of one consumer's week; the rarest
32 of the same words admit 7–33 %).
An issue-shaped question arrives as the issue body: a greeting or a template, the
subject, a reproducer, its output and the links, in no fixed order. The lexical leg
sums idf times presence over at most `LEXICAL_TOKEN_CAP` lexemes, so every lexeme the
subject's code does not hold only adds other chunks to the pool. What marks a subject
lexeme is not where it stands or how rare it is: a word that is rare in code is rare
because it is not code vocabulary, and an opening can be a greeting. A question names
its subject as code, or returns to it.

This module is the plan for such a question, pure and unit-testable:

* `strip_boilerplate` removes the template headings by a fixed list — they
arrive flattened into one line, so the match is a case-insensitive phrase,
not a line — and counts what it removed.
* `select_rarest` keeps the K rarest tokens by document frequency from the
corpus statistics the leg already reads, never dropping a token that is
the whole form of an identifier (camel / snake / `a::b`), and ranking
last the tokens that cannot help: hash-like hex fragments, bare numbers,
and words the corpus does not contain (df 0 admits no row and scores
nothing).
* `strip_non_terms` removes what names no subject before the tokenizer splits it:
URLs and hashes.
* `select_terms` keeps the whole forms of the identifiers (camel / snake / `a::b`)
and, for `WORD_SHARE` of the list, the words: those the question says more than
once first, then the others, each in reading order. An English function word and
a word that more than `COMMON_SHARE` of the chunks hold are not words to keep. A
bare number, and a lexeme the corpus does not contain (df 0 admits no row and
scores nothing), fill a slot only when nothing better is left.
* the vector leg embeds the first `EMBED_MAX_WORDS` words of the cleaned
text instead of the raw body.

Known limits: a subject the question states once, as a plain word, after its word
share is already taken is not asked for; the function words are English.

Nothing here runs for a question whose tokenizer output fits the cap: the
plan's `lexical_query`, `embed_text` and `tokens` are then the raw inputs,
so every statement and the embedding cache key are byte-identical to the
Expand All @@ -32,6 +36,7 @@
from __future__ import annotations

import re
from collections import Counter
from dataclasses import dataclass, field

from server.code.domain.extract.tokenize import code_tokens, compound_identifiers
Expand All @@ -53,12 +58,25 @@
"_No response_",
)

# The lexical leg's list is bounded at 32 lexemes; the trim replaces WHICH 32
# (rarest instead of first), never widens.
# The lexical leg's list is bounded at 32 lexemes; the trim chooses WHICH, never widens.
LEXICAL_TOKEN_CAP = 32
# Words take at most this share of the list and identifiers the rest, so that neither
# kind crowds the other out.
WORD_SHARE = 0.5
# A word that more of the chunks hold than this ranks nothing and opens the gate to
# most of the namespace.
COMMON_SHARE = 1 / 8
# The vector leg embeds at most this many whitespace words of the cleaned text (~2,000
# characters of prose: the request cap for `query`).
EMBED_MAX_WORDS = 512
# English function words: a question repeats them more than its subject, and they name
# none. A closed class, so a fixed list.
_FUNCTION_WORDS = frozenset(
"a an the is are was were be been being am has have had do does did can cannot could "
"should would will may might must shall of to in on at for with by from as into about "
"and or but if then than so because that this these those it its you your we our they "
"their them he she his her my me which who what when where why how not no there here".split()
)

_BOILERPLATE_RE = re.compile(
"|".join(
Expand All @@ -72,9 +90,11 @@
_QUALIFIED_RE = re.compile(
r"(?<![A-Za-z0-9_])[0-9]*+([A-Za-z_][A-Za-z0-9_]*+(?:::[A-Za-z_][A-Za-z0-9_]*+)+)"
)
# Tokens that cannot name a subject: a bare number, or a hex fragment of a
# commit / fiddle hash (letters a–f with at least one digit, 4+ chars).
_NOISE_RE = re.compile(r"^(?:[0-9]+|(?=.*[0-9])[0-9a-f]{4,})$")
# A commit or fiddle hash: seven or more hex characters, the shortest form git prints.
_HEX_RE = re.compile(r"[0-9a-f]{7,}")
# An address, not a subject: its host, route words, hash and line anchor.
_URL_RE = re.compile(r"https?://\S+")
_WORD_RE = re.compile(r"[A-Za-z0-9_]+")


@dataclass(frozen=True)
Expand All @@ -88,6 +108,8 @@ class TrimPlan:
tokens_in: int = 0
all_tokens: list[str] = field(default_factory=list)
keep: frozenset[str] = frozenset()
said: dict[str, int] = field(default_factory=dict)
own: frozenset[str] = frozenset()
cap: int = LEXICAL_TOKEN_CAP
boilerplate_dropped: int = 0

Expand All @@ -104,40 +126,81 @@ def strip_boilerplate(text: str) -> tuple[str, int]:
def identifier_forms(text: str) -> frozenset[str]:
"""Lowercased whole forms of the identifiers in `text` that a trim must
keep: camel / snake compounds (tokenize.compound_identifiers) and every
side of a `a::b` qualified name. A hash fragment splits at its
letter-digit edges like an identifier but is noise, not one."""
keep = {t for t in compound_identifiers(text) if not is_noise_token(t)}
side of a `a::b` qualified name. A hash splits at its letter-digit edges
like an identifier but is not one."""
keep = {t for t in compound_identifiers(text) if not is_hash(t)}
for m in _QUALIFIED_RE.finditer(text):
for part in m.group(1).split("::"):
if len(part) >= 2:
keep.add(part.lower())
return frozenset(keep)


def is_noise_token(tok: str) -> bool:
"""A bare number or a hash-like hex fragment: rarest by df, yet no subject."""
return bool(_NOISE_RE.match(tok))
def is_hash(word: str) -> bool:
"""A lowercased word of seven or more hex characters, letters among two or more
digits: a commit or fiddle hash. A short code (`f401`, `e164`) and a word spelled
in a to f around one digit (`face2face`) are names; a number stays a number."""
return bool(_HEX_RE.fullmatch(word)) and 2 <= sum(c.isdigit() for c in word) < len(word)


def strip_non_terms(text: str) -> str:
"""The text without what names no subject: URLs and hashes. A hash goes whole,
before the tokenizer splits it at its letter-digit edges into letter-only pieces
that read as rare words."""
return _WORD_RE.sub(
lambda m: " " if is_hash(m.group(0).lower()) else m.group(0),
_URL_RE.sub(" ", text),
)
Comment thread
zlareb1 marked this conversation as resolved.
Resolved


def term_counts(text: str) -> dict[str, int]:
"""How many words of `text` hold each lexeme, whole or as a subtoken."""
counts: Counter[str] = Counter()
for m in _WORD_RE.finditer(text):
counts.update(code_tokens(m.group(0)))
return dict(counts)


def select_rarest(
tokens: list[str], df: dict[str, int], k: int, keep: frozenset[str] = frozenset()
def select_terms(
tokens: list[str],
df: dict[str, int],
n_chunks: int,
k: int,
*,
keep: frozenset[str],
said: dict[str, int],
own: frozenset[str] = frozenset(),
) -> list[str]:
"""The `k` tokens the lexical gate keeps, in their first-seen order:
identifier forms first (always), then prose tokens the corpus knows by
ascending df (ties by position), then noise and unknown tokens (df 0),
which fill remaining slots only when nothing better is left."""
"""At most `k` tokens for the lexical gate, in their first-seen order: the caller's
own terms (`own`), the identifier forms (`keep`) and, for `WORD_SHARE` of `k`, the
words: those `said` more than once first, then the others, each in reading order;
never a function word or one more than `COMMON_SHARE` of `n_chunks` chunks hold.
Past `k` the caller's terms go first, then the words, then the identifiers, the
rarest by document frequency first. A bare number and an unknown token (df 0) rank
after everything the corpus knows."""
k = max(int(k), 1)
kept = [t for t in tokens if t in keep][:k]
room = k - len(kept)
rest = [t for t in tokens if t not in keep]
good = [t for t in rest if df.get(t, 0) > 0 and not is_noise_token(t)]
good.sort(key=lambda t: (df[t], tokens.index(t)))
chosen = set(kept) | set(good[:room])
if len(chosen) < k:
for t in rest:
if len(chosen) >= k:
break
chosen.add(t)
position = {t: i for i, t in enumerate(tokens)}

def unknown(t: str) -> bool:
return df.get(t, 0) <= 0 or t.isdigit()

words = [
t
for t in tokens
if t not in keep
and t not in own
and t not in _FUNCTION_WORDS
and df.get(t, 0) <= n_chunks * COMMON_SHARE
]
words.sort(key=lambda t: (unknown(t), said.get(t, 0) < 2, position[t]))
kept_words = set(words[: max(int(k * WORD_SHARE), 1)])

def rank(t: str) -> tuple[bool, int, bool, int, int]:
tier = 0 if t in own else 1 if t in kept_words else 2
return (unknown(t), tier, t not in keep, df.get(t, 0), position[t])

eligible = [t for t in tokens if t in own or t in kept_words or t in keep]
chosen = set(sorted(eligible, key=rank)[:k])
return [t for t in tokens if t in chosen]


Expand All @@ -154,17 +217,22 @@ def plan(
code_search_query_max_tokens) <= 0 turns the trim off;
otherwise a question whose tokenizer output exceeds it is stripped of
boilerplate, its vector text is the cleaned first page, and its lexical
gate will take the rarest `min(max_tokens, LEXICAL_TOKEN_CAP)` tokens
once the corpus statistics arrive (select_rarest). `work` receives the
disclosure counters only when the trim is active."""
gate will take at most `min(max_tokens, LEXICAL_TOKEN_CAP)` tokens once the
corpus statistics arrive (select_terms): its identifiers and its words, those
it repeats first. `extra_terms` are a caller's own choice of terms: they are
always kept. `work` receives the disclosure counters only when the trim is active."""
lexical_query = query if not extra_terms else query + " " + " ".join(extra_terms)
raw_tokens = code_tokens(lexical_query)
cap = int(max_tokens)
if cap <= 0 or len(raw_tokens) <= cap:
return TrimPlan(lexical_query, query, raw_tokens[:LEXICAL_TOKEN_CAP])
cleaned_q, dropped = strip_boilerplate(query)
cleaned_lex = cleaned_q if not extra_terms else cleaned_q + " " + " ".join(extra_terms)
extra = " ".join(extra_terms or ())
text = cleaned_q if not extra else cleaned_q + " " + extra
cleaned_lex = strip_non_terms(text)
all_tokens = code_tokens(cleaned_lex)
if not all_tokens: # only addresses and hashes: they are all the question says
cleaned_lex, all_tokens = text, code_tokens(text)
work["query_trimmed_tokens_in"] = len(raw_tokens)
work["query_trimmed_boilerplate_lines_dropped"] = dropped
return TrimPlan(
Expand All @@ -175,6 +243,8 @@ def plan(
tokens_in=len(raw_tokens),
all_tokens=all_tokens,
keep=identifier_forms(cleaned_lex),
said=term_counts(cleaned_lex),
own=frozenset(code_tokens(extra)),
cap=min(cap, LEXICAL_TOKEN_CAP),
boilerplate_dropped=dropped,
)
5 changes: 3 additions & 2 deletions server/settings/catalog.py
Original file line number Diff line number Diff line change
Expand Up @@ -1638,8 +1638,9 @@ def _check_git_proxy(self) -> CodeSettings:
# boost. Kill switch.
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
# first 512 cleaned words embed). Under the cap nothing changes. 0 = off.
# issue body (template headings stripped, at most 32 tokens gate: its
# identifiers and its words, those it repeats first; the first 512 cleaned
# words embed). Under the cap nothing changes. 0 = off.
code_search_query_max_tokens: int = 48
# 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.
Expand Down
Loading
Loading