symbols.py¶
clew/query/symbols.py
Symbol-level R2 queries: resolve / callers / callees / search / threads / requirement trace, plus the shared edge/thread row→dataclass builders that `dossier` and `traversal` reuse (DRY).
_ambiguity_counts
tuple[int, int] clew.query.symbols._ambiguity_counts(sqlite3.Connection conn, str fn, *bool want_callers)
Distinct same-named signatures, and how many neighbours arrive through the name.
Source · 27 lines
def _ambiguity_counts(conn: sqlite3.Connection, fn: str, *, want_callers: bool) -> tuple[int, int]:
"""Split out from `name_ambiguity` to keep both inside the max-3-returns standard,
which the combined form breached at four — and the split is the better shape anyway,
since it separates COUNTING from deciding whether the counts are worth reporting.
Counts DISTINCT SIGNATURES, not memberdef rows: decl/def duality gives one function
several rows, so a row count would call every documented header declaration an
overload. `is_overloaded` draws the same distinction for the same reason.
@brief Count same-name candidates and the neighbours shared through the name.
@return (candidates, shared).
@version 2
"""
if not table_exists(conn, "call_edges"):
return 0, 0
candidates = len({sig for _, sig, _, _, _ in function_candidates(conn, fn)})
if candidates < 2:
return candidates, 0
endpoint, focal = ("c", "x") if want_callers else ("x", "c")
shared = conn.execute(
f"SELECT COUNT(DISTINCT {endpoint}.name) FROM call_edges e "
"JOIN memberdef c ON c.rowid = e.caller_rowid "
"JOIN memberdef x ON x.rowid = e.callee_rowid "
f"WHERE {focal}.name=? AND e.source=? AND e.confidence=?",
(fn, CALL_SOURCE_AST_MEMBER, CALL_MATCH_FUZZY),
).fetchone()[0]
return candidates, int(shared or 0)1 more lines, not shown
Activity · 8 steps
Flows
_build_thread
Thread clew.query.symbols._build_thread(sqlite3.Connection conn, tuple row)
Assemble a Thread dataclass from a threads row (+ member count).
Called by thread_roster, threads_for
Calls _spawn_attribution, name_of, table_exists
Source · 42 lines
def _build_thread(conn: sqlite3.Connection, row: tuple) -> Thread:
"""A SHORT ROW IS FOLDED, NOT REJECTED. The spawn-site columns arrive at build version 35,
so a six-element row is a pre-35 index rather than a bug — and its threads really are
unattributable, which is what an empty `spawn_file` says.
@brief Resolve a threads row's entry name, spawn site, spawner and membership count into a Thread.
@version 3
"""
tid, name, kind, entry_rowid, source, conf = row[:6]
spawn_path_rowid = row[6] if len(row) > 6 else None
spawn_line = row[7] if len(row) > 7 else None
## The ninth element arrives at build 48; an eight-element row is a pre-48 index whose
## threads really do have no recorded spawner, which is what an empty `spawn_function` says.
spawn_function = (row[8] if len(row) > 8 else None) or ""
entry = name_of(conn, entry_rowid) if entry_rowid is not None else None
member_count = (
conn.execute(
"SELECT COUNT(*) FROM thread_membership WHERE thread_id=?",
(tid,),
).fetchone()[0]
if table_exists(conn, "thread_membership")
else 0
)
spawn_file, external_root = _spawn_attribution(conn, spawn_path_rowid)
return Thread(
id=tid,
name=name,
kind=kind,
entry=entry,
source=source,
confidence=conf,
member_count=member_count,
spawn_file=spawn_file,
spawn_line=spawn_line,
spawn_function=spawn_function,
external_root=external_root,
## Elements 10 and 11 arrive at build 14; a shorter row never looked.
lifecycle=row[9] if len(row) > 9 else None,
lifecycle_line=row[10] if len(row) > 10 else None,
)
Activity · 8 steps
Flows
_class_candidates
list[_Candidate] clew.query.symbols._class_candidates(sqlite3.Connection conn, str query, list[str] tokens)
Ranked compound candidates whose name or brief carries every token.
Source · 23 lines
def _class_candidates(conn: sqlite3.Connection, query: str, tokens: list[str]) -> list[_Candidate]:
"""gh#315. A compound's NAME is scored where a function's name is scored and its
BRIEF where a function's brief is, so the single weight table in `_search_rank`
governs all three corpora and no corpus can win by being ranked on its own scale.
`provenance` stays None: every compound row is doxygen's, and `symbol_provenance`
reports only the surprising case. A compound has no tree-sitter recovery path.
@brief Match and rank indexed classes, structs, unions and interfaces.
@return Ranked candidates.
@version 1
"""
return [
(
-_search_rank(name, brief, query, tokens),
_TIER_CLASS,
name,
SymbolHit(name=name, kind=kind, file=file, brief=brief),
)
for name, kind, file, brief in class_rows(conn, tokens)
]
Activity · 1 steps
Flows
_collapse_variants
tuple[str, str | None] clew.query.symbols._collapse_variants(list[tuple[str, str|None]] variants)
Collapse one endpoint's per-layer rows into its strongest evidence.
Source · 25 lines
def _collapse_variants(variants: list[tuple[str, str | None]]) -> tuple[str, str | None]:
"""The #38 fix, in ONE place because both the per-function surface
(`_direct_call_edges`) and the traversal surface (`traversal._call_hops`) must
collapse identically — a neighbour list and a chain through that neighbour
would otherwise disagree about the same edge's provenance, and the reason
`_key_edge_rows` exists is that this exact JOIN was once written out twice and
drifted.
`call_edges` stores one row per LAYER by design
(`UNIQUE(caller_rowid, callee_rowid, source)`), so a single logical edge found
by two layers was surfaced twice. Measured on clew's own index: 520 rows for
260 distinct pairs — every neighbour list inflated exactly 2x, and every depth
cap therefore truncating half as many real edges as intended.
`source` stays a single vocabulary-registered value and must NOT become a
joined string — that would write an unregistered value into a
vocabulary-checked field.
@brief Reduce an endpoint's layer variants to one row.
@return Strongest source and its confidence.
@version 4
"""
return max(variants, key=lambda v: _variant_rank(*v))
Activity · 1 steps
Flows
_config_candidates
list[_Candidate] clew.query.symbols._config_candidates(sqlite3.Connection conn, str query, list[str] tokens)
Ranked configuration-symbol candidates whose name carries every token.
Source · 31 lines
def _config_candidates(conn: sqlite3.Connection, query: str, tokens: list[str]) -> list[_Candidate]:
"""gh#394. Scored through the SAME `_search_rank` as every other corpus so no corpus
can win by being ranked on its own scale — with an empty brief, because a gate row is a
location and not a documented entity (see `corpus.gate_symbol_rows`).
THE BRIEF IS SYNTHESISED FROM THE MEASUREMENT, not from prose the row does not have:
"gates 151 site(s) in 31 file(s)" is the useful fact about a config symbol and it comes
from the count, so it cannot drift from the rows. It is built AFTER ranking for exactly
that reason — scoring against it would let a query for "site" match every config symbol
in the repository.
@brief Match and rank the configuration symbols a repo gates on.
@return Ranked candidates.
@version 1
"""
return [
(
-_search_rank(symbol, "", query, tokens),
_TIER_CONFIG,
symbol,
SymbolHit(
name=symbol,
kind=CONFIG_SYMBOL_KIND,
file=file,
brief=f"gates {sites} site(s); origin {origin or 'unknown'}",
),
)
for symbol, sites, file, origin in gate_symbol_rows(conn, tokens)
]
Activity · 1 steps
Flows
_doc_brief
str clew.query.symbols._doc_brief(str doc)
Shorten a file's documentation to a brief, at a word boundary.
Source · 12 lines
def _doc_brief(doc: str) -> str:
"""@brief Trim file-level documentation to brief length.
@return Possibly-ellipsised brief text.
@version 1
"""
if len(doc) <= FILE_BRIEF_CHARS:
return doc
head = doc[:FILE_BRIEF_CHARS]
cut = head.rsplit(" ", 1)[0] if " " in head else head
return f"{cut} …"
Activity · 5 steps
Flows
_expansion_sql
str clew.query.symbols._expansion_sql(sqlite3.Connection conn)
SQL for a macro's expansion, degrading to '' on a schema without the column.
Source · 14 lines
def _expansion_sql(conn: sqlite3.Connection) -> str:
"""Degrades to the empty literal rather than to no macro corpus at all: a database
without the column can still match a macro BY NAME, and losing the reverse
(expansion) lookup is a smaller loss than losing the whole corpus. Interpolated
into the statement text and therefore chosen from two FIXED strings, never built
from anything a caller supplies.
@brief Pick the expansion expression this schema supports.
@return A SQL scalar expression.
@version 1
"""
return "COALESCE(m.initializer,'')" if has_columns(conn, "memberdef", "initializer") else "''"
Activity · 1 steps
Flows
_file_candidates
list[_Candidate] clew.query.symbols._file_candidates(sqlite3.Connection conn, str query, list[str] tokens)
Ranked file candidates whose path or file-level documentation carries every token.
Called by search_counted
Calls _doc_brief, _search_rank, file_doc_rows, self_declared_paths, undocumented_path_rows
Source · 45 lines
def _file_candidates(conn: sqlite3.Connection, query: str, tokens: list[str]) -> list[_Candidate]:
"""gh#10. The file's PATH is scored where a symbol's name is scored and its
documentation where a brief is, so one weight table serves both corpora and a
conceptual token in prose stays weaker evidence than the same token in an
identifier — the property `_search_rank` exists to enforce.
`provenance` is `'file_doc'` so a consumer can tell at a glance that this row
came from prose the author wrote about the FILE, not from a symbol record.
TWO READERS, ONE RANKING. `file_doc_rows` finds DOCUMENTED files; `undocumented_path_rows`
finds the ones the index knows only by name — the class C5 registers, which had no row here
at all and so could not appear in the DEFAULT corpus however the caller spelled the query.
Measured on an index rebuilt with C5 against the 1.1.0 transcripts: the agent asked for
`generate_errors` three ways and only `corpus="files"` answered, the default first and
emptiest. The two readers are disjoint by construction, so no path is doubled, and both go
through `_search_rank` — a documentation match outranks a bare path match because that table
scores prose below an identifier, not because anything here says so.
@brief Match and rank file-level documentation, and files known only by name.
@return Ranked candidates.
@version 3
"""
## The same penalty as a symbol in a self-declared generated file, so a file search is not
## crowded by generated files any more than a symbol search is by their contents.
generated = self_declared_paths(conn)
return [
(
-(
_search_rank(path, doc, query, tokens)
- (SEARCH_PENALTY_SELF_DECLARED_GENERATED if path in generated else 0)
),
_TIER_FILE,
path,
SymbolHit(
name=path,
kind="file",
file=path,
brief=_doc_brief(doc),
provenance="file_doc",
),
)
for path, doc in [*file_doc_rows(conn, tokens), *undocumented_path_rows(conn, tokens)]
]
Activity · 2 steps
Flows
_implementors_by_identity
dict[tuple[str, str], tuple[str, ...]] clew.query.symbols._implementors_by_identity(sqlite3.Connection conn, list[tuple[str, str, int, int, str, str|None]] rows)
Known implementors of each endpoint identity, from doxygen's override relation.
Source · 42 lines
def _implementors_by_identity(
conn: sqlite3.Connection,
rows: list[tuple[str, str, int, int, str, str | None]],
) -> dict[tuple[str, str], tuple[str, ...]]:
"""gh#8's answer to "what actually runs when this dispatches". A call to a virtual
base method is, in the index, one edge to the BASE — and for a C++ target that edge
is usually `fuzzy` besides, because `memberdef.name` is unqualified. The override
relation is the only thing that says which concrete bodies that call can reach, and
nothing outside `dispatch_edges.py` read it.
ONE query for the whole neighbour list, keyed on EVERY rowid the raw rows mention
rather than on the one reported rowid per identity. That is not defensive padding:
doxygen records the relation against whichever memberdef it saw the `override` on,
and `_endpoint_identities` reports the definition-preferring rowid — so keying on
the reported rowid alone drops the relation exactly when the declaration carried it,
which is the decl/def duality biting in its usual place.
Empty when the table is absent, which it is on a C-only or Python target: doxygen
creates `reimplements` itself, so absence here means the index predates that output
rather than that the code has no overrides.
@brief Map endpoint identities to the functions that reimplement them.
@return identity → implementor names, sorted.
@version 2
"""
if not rows or not table_exists(conn, "reimplements"):
return {}
identity_of = {
rowid: (name, qualified_name_of(name, definition)) for name, definition, rowid, *_ in rows
}
marks = ", ".join("?" for _ in identity_of)
found: dict[tuple[str, str], set[str]] = {}
for base_rowid, impl_name in conn.execute(
"SELECT r.reimplemented_rowid, m.name FROM reimplements r "
f"JOIN memberdef m ON m.rowid = r.memberdef_rowid "
f"WHERE r.reimplemented_rowid IN ({marks})",
list(identity_of),
):
found.setdefault(identity_of[base_rowid], set()).add(impl_name)
return {identity: tuple(sorted(names)) for identity, names in found.items()}
Activity · 8 steps
Requirements
_key_edge_rows
list[tuple] clew.query.symbols._key_edge_rows(sqlite3.Connection conn, str fn, *bool as_writer)
Raw shared-key rows for one focal function in one role.
Called by _dataflow_edges, _key_hops, key_edges
Calls _key_r1_projection, table_exists
Source · 30 lines
def _key_edge_rows(conn: sqlite3.Connection, fn: str, *, as_writer: bool) -> list[tuple]:
"""The ONE per-function shared-key JOIN. Three surfaces need the identical
JOIN + R1 column list — `key_edges` (→ KeyEdge, for dossier's split
writes/reads), `_call_edges` (→ a key-class CallEdge, for the #46 merge) and
`traversal._key_hops` (→ Hop) — and it was written out twice before, so an R1
column added to one shape was silently missing from the other.
Returned as raw tuples deliberately: each caller maps them into a DIFFERENT
dataclass, so materializing one here would force two of the three to unpack
a shape they do not want.
@brief Run the per-function shared-key JOIN once, for every consumer.
@version 2
"""
if not table_exists(conn, "shared_key_edges"):
return []
r1, tjoin = _key_r1_projection(conn)
focal, other = ("w", "r") if as_writer else ("r", "w")
sql = (
f"SELECT DISTINCT {other}.name, s.key_name, s.edge_kind, s.source, "
f"s.confidence, {r1} "
"FROM shared_key_edges s "
"JOIN memberdef w ON w.rowid = s.writer_rowid "
"JOIN memberdef r ON r.rowid = s.reader_rowid "
f"{tjoin} "
f"WHERE {focal}.name=? ORDER BY s.key_name, s.source, {other}.name"
)
return conn.execute(sql, (fn,)).fetchall()
Activity · 6 steps
Flows
_key_r1_projection
tuple[str, str] clew.query.symbols._key_r1_projection(sqlite3.Connection conn)
The R1 projection + threads JOIN a database can actually support.
Source · 25 lines
def _key_r1_projection(conn: sqlite3.Connection) -> tuple[str, str]:
"""Two independent degradations, both silent-crash sources before this
existed. A stale database predating R1 has no `dispatch_mode` at all — the
query then selects the schema's OWN default, 'unknown', so a consumer reads
"this hand-off's synchrony is unknown" instead of catching an
`OperationalError`, which is exactly what that value means. A database with
R1 columns but no `threads` table can still name the columns but has no
thread to resolve, so only the name degrades to NULL.
Fabricating nothing is the point: every degraded field lands on the value
that already means "not known here", never on a plausible-looking one.
@brief Choose the shared-key R1 select-list a given database supports.
@version 1
"""
if not has_columns(conn, "shared_key_edges", *_KEY_R1_COLUMNS):
return "'unknown', NULL, NULL, NULL", ""
if not table_exists(conn, "threads"):
return "s.dispatch_mode, s.edge_triggered, s.crosses_thread, NULL", ""
return (
"s.dispatch_mode, s.edge_triggered, s.crosses_thread, t.name",
"LEFT JOIN threads t ON t.id = s.to_thread_id",
)
Activity · 5 steps
Flows
_memberdef_candidates
list[_Candidate] clew.query.symbols._memberdef_candidates(sqlite3.Connection conn, str query, list[str] tokens, str kind, int tier, str extra_prose="''")
Ranked memberdef candidates of one kind whose name, brief, prose or FILE PATH carries every token.
Called by _memberdef_corpora
Calls _one_line, _search_rank, documented_first, self_declared_paths, strip_xml, symbol_provenance, table_exists
Source · 105 lines
def _memberdef_candidates(
conn: sqlite3.Connection,
query: str,
tokens: list[str],
kind: str,
tier: int,
extra_prose: str = "''",
) -> list[_Candidate]:
"""Parametrised by KIND when gh#372 added the variable corpus, so both corpora are
matched by one clause builder, ranked by one weight table and collapsed by one
per-name rule. Copying this body for variables would have been the DRY violation
that lets the two corpora drift — and drift here means one of them silently stops
honouring `documented_first` or the conjunction.
`extra_prose` is gh#373's addition and it is a SECOND prose column, not a
replacement: a macro's own documentation is its EXPANSION, which lives in
`memberdef.initializer` and which almost no macro duplicates in a brief (441 of
mbedtls's 2,504 macro rows have no expansion recorded at all, and most of the rest
have no brief). Matching it means `search('private_##member')` finds the macro that
produces it, which is the reverse lookup a reader of generated field names needs.
It is NOT run through `strip_xml`, deliberately and unlike a brief. A brief is
doxygen markup; an expansion is C source, and `strip_xml`'s `<[^>]+>` would eat the
middle of `((x) < 0 ? 0 : (x) > 1 ? 1 : (x))`. Two prose columns, two treatments,
because they are two different languages.
@brief Match and rank indexed names, briefs and non-XML prose for one memberdef kind.
@return Ranked candidates.
@version 2
"""
if not table_exists(conn, "memberdef"):
return []
clause = " AND ".join(
[
## THE PATH IS ALREADY JOINED AND SELECTED BELOW — it was simply never matched on.
## That omission made a symbol unreachable by the name of the file holding it.
"(LOWER(m.name) LIKE ? OR LOWER(COALESCE(m.briefdescription,'')) LIKE ? "
f"OR LOWER({extra_prose}) LIKE ? OR LOWER(COALESCE(p.name,'')) LIKE ?)"
]
* len(tokens)
)
params: list[str] = []
for token in tokens:
params += [f"%{token}%"] * 4
# `documented_first` makes doxygen's own row win the per-name collapse
# below, so a parser-recovered row can never displace a documented one and
# take its brief off this surface. See `_common.documented_first`.
rows = conn.execute(
f"SELECT m.name, m.kind, COALESCE(p.name,''), m.briefdescription, m.rowid, {extra_prose} "
"FROM memberdef m LEFT JOIN path p ON p.rowid = m.file_id "
f"WHERE m.kind=? AND {clause} "
f"ORDER BY m.name, {documented_first(conn, 'm')}m.rowid",
[kind, *params],
).fetchall()
## TWO PASSES, because the disclosure needs a fact the first pass has not finished
## collecting: which OTHER files declare each surviving name. gh#392 — the collapse
## keeps doxygen's row over a recovered one, which is right in general and was measured
## wrong once: after gh#395 recovered mbedtls's guarded `mbedtls_threading_mutex_t`, the
## kept row was the TEST FIXTURE and the dropped one was the shipping type.
##
## ONLY WHEN PROVENANCE DIFFERS, and my first cut got this wrong in the way this repo
## warns about most. Disclosing every dropped file made `mbedtls_ctr_drbg_random` report
## `also_in: library/ctr_drbg.c` — the ORDINARY decl/def duality, present on nearly every
## C function. A guard that fires on the ordinary case is worse than no guard: it buries
## the one case that matters in noise on every row.
##
## The ordering rule here is `documented_first`, so the interesting event is exactly when
## THAT rule discarded a row of different provenance — doxygen's kept, the parser's
## dropped. Decl/def pairs are both doxygen's and stay silent.
elsewhere: dict[str, list[str]] = {}
kept: dict[str, tuple] = {}
for row in rows:
name, file, rowid = row[0], row[2], row[4]
if name in kept:
differs = symbol_provenance(conn, rowid) != symbol_provenance(conn, kept[name][4])
if differs and file and file != kept[name][2] and file not in elsewhere[name]:
elsewhere[name].append(file)
continue
kept[name] = row
elsewhere[name] = []
## Read once per kind, not per row: a handful of paths, and the set is what the loop asks.
generated = self_declared_paths(conn)
candidates: list[_Candidate] = []
for name, (_n, row_kind, file, brief, rowid, extra) in kept.items():
clean = strip_xml(brief) or _one_line(extra)
penalty = SEARCH_PENALTY_SELF_DECLARED_GENERATED if file in generated else 0
candidates.append(
(
-(_search_rank(name, clean, query, tokens, file) - penalty),
tier,
name,
SymbolHit(
name=name,
kind=row_kind,
file=file,
brief=clean,
provenance=symbol_provenance(conn, rowid),
also_in=tuple(elsewhere[name]),
),
)
)
return candidates
Activity · 25 steps
Flows
_memberdef_corpora
list[_Candidate] clew.query.symbols._memberdef_corpora(sqlite3.Connection conn, str query, list[str] tokens)
Ranked candidates from EVERY searched memberdef corpus, in one list.
Source · 28 lines
def _memberdef_corpora(conn: sqlite3.Connection, query: str, tokens: list[str]) -> list[_Candidate]:
"""ONE LOOP OVER ONE TABLE, replacing the three one-line wrappers this file grew as
corpora were added a gh at a time (`_symbol_candidates`, `_variable_candidates`,
`_macro_candidates`). Their histories are kept where the decision lives — on
`SEARCHED_MEMBERDEF_KINDS` for what is read and why, and on `_memberdef_candidates`
for how a row is matched and ranked.
The wrappers were the mechanism by which the SAME defect shipped four times: adding
a corpus meant writing a new function and remembering to call it, and there was no
place a reader could look to see the whole covered set. Now there is one, and
`mcp_server.emptiness` reads it to word the reply, so what `search` covers and what
it CLAIMS to cover cannot drift apart.
Only macros take a second prose column — a macro's real documentation is its
expansion. Nothing else has one, so the extra argument is supplied for that kind
alone rather than made a column of the table for one true row.
@brief Match and rank every searched memberdef kind.
@return Ranked candidates from all memberdef corpora.
@version 1
"""
candidates: list[_Candidate] = []
for kind, tier in SEARCHED_MEMBERDEF_KINDS:
extra = _expansion_sql(conn) if kind == MACRO_KIND else "''"
candidates += _memberdef_candidates(conn, query, tokens, kind, tier, extra)
return candidates
Activity · 5 steps
Flows
_one_line
str clew.query.symbols._one_line(str|None text)
Collapse whitespace and line continuations, then trim to brief length.
Source · 19 lines
def _one_line(text: str | None) -> str:
"""gh#373. A macro expansion is C source and routinely spans several lines glued
by trailing backslashes, so pasting it into a `brief` slot verbatim would put
newlines and `\\` in a field every consumer renders as one line. The backslashes
go first, then the whitespace runs collapse — the other order leaves a stranded
`\\` mid-line for a continuation whose newline has already been eaten.
Reuses `_doc_brief`'s cap rather than declaring a second one: "how long is a brief
on this surface" should have one answer, and a macro's expansion is competing for
the same slot as a file's documentation.
@brief Flatten a multi-line expansion to a single trimmed brief.
@return One-line, length-capped text.
@version 1
"""
flat = re.sub(r"\s+", " ", (text or "").replace("\\\n", " ")).strip()
return _doc_brief(flat)
Activity · 2 steps
Flows
_one_token_count
int clew.query.symbols._one_token_count(sqlite3.Connection conn, str token)
Independent match count for one token across both search corpora.
Called by token_hit_counts
Calls _expansion_sql, class_rows, file_doc_rows, table_exists
Source · 47 lines
def _one_token_count(conn: sqlite3.Connection, token: str) -> int:
"""Counts over EVERY corpus `search` reads, because a token matching only a
file's documentation is still a token that did not empty the query, and saying
otherwise would send the caller to drop the one token that was working.
That argument is why gh#315's class corpus had to be added here in the same
change and not later: a token matching a class and nothing else would have been
counted 0 and named as the guilty token, which is gh#31's exact defect
reintroduced through the new corpus. A corpus that `search` reads and the
diagnosis does not is a diagnosis that lies about a widened tool.
gh#372's variable corpus is here for the SAME reason and was added in the SAME
change, deliberately: `mutex` matches five mbedtls globals and — on a repo whose
functions do not spell it — nothing else, so leaving variables out would have
named `mutex` as the token that emptied a query it was the only one answering.
gh#373's macro corpus, third time, same change. It also has to match the
EXPANSION, because that is what the macro corpus matches: counting it on
name-and-brief alone would under-count exactly the reverse lookups
(`private_##member`) the expansion was added for, and name the working token as
the guilty one.
gh#374 stops the fourth instance by CONSTRUCTION: the kind list is read from
`SEARCHED_MEMBERDEF_KINDS` instead of being spelled out again here. This statement
had the three kinds hardcoded, so the typedef and enumeration corpora would have
been searched and not counted — a token matching only a type name would have been
reported as matching nothing and named as the one to drop.
@brief Count one token's matches in every searched memberdef corpus, classes and file docs.
@return Combined count.
@version 5
"""
like = f"%{token}%"
symbols = 0
if table_exists(conn, "memberdef"):
kinds = [kind for kind, _tier in SEARCHED_MEMBERDEF_KINDS]
placeholders = ",".join("?" * len(kinds))
symbols = conn.execute(
"SELECT COUNT(DISTINCT m.name) FROM memberdef m "
f"WHERE m.kind IN ({placeholders}) "
"AND (LOWER(m.name) LIKE ? OR LOWER(COALESCE(m.briefdescription,'')) LIKE ? "
f"OR (m.kind=? AND LOWER({_expansion_sql(conn)}) LIKE ?))",
(*kinds, like, like, MACRO_KIND, like),
).fetchone()[0]
return symbols + len(class_rows(conn, [token])) + len(file_doc_rows(conn, [token]))
Activity · 7 steps
Flows
_override_refs
list[OverrideRef] clew.query.symbols._override_refs(sqlite3.Connection conn, str fn, *bool want_bases, str|None qualified=None)
One side of the override relation for a function, name-resolved.
Source · 58 lines
def _override_refs(
conn: sqlite3.Connection, fn: str, *, want_bases: bool, qualified: str | None = None
) -> list[OverrideRef]:
"""Both directions from one query, because they differ only in which column of
`reimplements` is the focal side — and two near-identical SQL strings in one module
is the drift condition that produced gh#26.
The focal side is filtered by the resolved IDENTITY's rowids (`identity_rowids`),
not by name, for the reason gh#26 established: a bare name can denote several
unrelated functions, and unioning their override relations onto whichever one a
dossier described would fabricate polymorphism. It is also what makes the decl/def
duality harmless here — doxygen may record the relation against the declaration and
the dossier may have chosen the definition.
AND THIS IS THE SURFACE gh#37 MADE LOAD-BEARING. A virtual base shares its bare
name with every override BY CONSTRUCTION — that is what `override` means — so
`overridden_by` on the base, the direction a consumer actually wants, is exactly
the direction a bare name cannot reach. Measured on this repo's own index: ten
`reimplements` rows name `Harvester.harvest` as the base and eleven memberdef
rows are named `harvest`, so the definition-preferring guess picks a SUBCLASS and
reports `overridden_by: []` — a confident empty answer about the one function
that has ten. `qualified` is what makes the base addressable.
@brief Read one direction of the override relation.
@return OverrideRef list.
@version 3
"""
if not table_exists(conn, "reimplements"):
return []
focal_rowids = identity_rowids(conn, fn, qualified)
if not focal_rowids:
return []
## `focal` is the side we KNOW; `other` is the side we are asking for.
focal, other = (
("memberdef_rowid", "reimplemented_rowid")
if want_bases
else ("reimplemented_rowid", "memberdef_rowid")
)
marks = ", ".join("?" for _ in focal_rowids)
return [
OverrideRef(
name=name,
rowid=rowid,
signature=f"{definition or ''}{args or ''}",
file=path,
line_start=line_start,
)
for name, rowid, definition, args, path, line_start in conn.execute(
f"SELECT DISTINCT m.name, m.rowid, COALESCE(m.definition,''), "
"COALESCE(m.argsstring,''), COALESCE(p.name,''), m.bodystart "
f"FROM reimplements r JOIN memberdef m ON m.rowid = r.{other} "
"LEFT JOIN path p ON p.rowid = m.file_id "
f"WHERE r.{focal} IN ({marks}) ORDER BY m.name, m.rowid",
focal_rowids,
)
]
Activity · 8 steps
Requirements
_req_attributes
dict[str, Any] clew.query.symbols._req_attributes(sqlite3.Connection conn, str req_id)
One requirement's 29148 attributes and its unmapped catalog keys.
Source · 20 lines
def _req_attributes(conn: sqlite3.Connection, req_id: str) -> dict[str, Any]:
"""2.0.0 (S4 served). The columns exist only on an index built since S4, so they are probed
rather than assumed. `extra` is JSON in the table and a mapping on the wire.
@brief Read the attributes.
@return Field values.
"""
if not has_columns(conn, "requirements", *_REQ_ATTRIBUTES, "extra"):
return {}
row = conn.execute(
f"SELECT {', '.join(_REQ_ATTRIBUTES)}, extra FROM requirements WHERE id=?", # noqa: S608
(req_id,),
).fetchone()
if row is None:
return {}
out: dict[str, Any] = {k: str(v or "") for k, v in zip(_REQ_ATTRIBUTES, row[:-1])}
out["extra"] = json.loads(row[-1]) if row[-1] else None
return out
Activity · 8 steps
Requirements
_req_failure_modes
list[FailureModeRef] clew.query.symbols._req_failure_modes(sqlite3.Connection conn, str req_id)
A requirement's declared failure modes, each with the tests that name it.
Source · 26 lines
def _req_failure_modes(conn: sqlite3.Connection, req_id: str) -> list[FailureModeRef]:
"""@brief Failure modes. @return Refs."""
if not table_exists(conn, "failure_modes"):
return []
linked = table_exists(conn, "test_failure_modes")
modes = conn.execute(
"SELECT mode_id, meaning FROM failure_modes WHERE req_id = ? ORDER BY mode_id", (req_id,)
).fetchall()
return [
FailureModeRef(
id=str(mode),
meaning=str(meaning),
tests=[
str(r[0])
for r in conn.execute(
"SELECT DISTINCT test_name FROM test_failure_modes WHERE mode_id = ? ORDER BY 1",
(mode,),
)
]
if linked
else [],
)
for mode, meaning in modes
]
Activity · 5 steps
Requirements
_req_links
tuple[list[str], list[str]] | None clew.query.symbols._req_links(sqlite3.Connection conn, str req_id)
Both directions of a requirement's satisfies links (GH #68).
Source · 13 lines
def _req_links(conn: sqlite3.Connection, req_id: str) -> tuple[list[str], list[str]] | None:
"""@brief Read links. @return Both directions, or None."""
if not table_exists(conn, "requirement_links"):
return None
up = conn.execute(
"SELECT satisfies FROM requirement_links WHERE req_id=? ORDER BY satisfies", (req_id,)
).fetchall()
down = conn.execute(
"SELECT req_id FROM requirement_links WHERE satisfies=? ORDER BY req_id", (req_id,)
).fetchall()
return [r[0] for r in up], [r[0] for r in down]
Activity · 5 steps
Requirements
_roster_meaning
str clew.query.symbols._roster_meaning(OriginSplit origin, bool attributable)
The sentence stating both the count and whose threads it counts.
Source · 47 lines
def _roster_meaning(origin: OriginSplit, attributable: bool) -> str:
"""The sentence is what a model QUOTES, so a correct `origin` field beside a sentence naming
only the total would preserve the wrong attribution — the lesson `lock_roster.row_meaning`
already carries.
IT SAID "Quote origin.first_party as the repository's thread count", AND THAT IS AN
OVERSTATEMENT THAT WAS QUOTED. On Mbed-TLS/mbedtls it reads 1 against a true 2:
`pthread_create` in the sample TLS server matches a default pattern, and
`_beginthread(TimerProc, 0, NULL)` in the benchmark program matches nothing, because no
Windows spawn primitive is in `DEFAULT_SPAWN_PATTERNS` at all. A graded answer wrote
"consistent with the index's count of exactly one first-party thread" — confident
incompleteness authored by this payload, not by the agent, which is instructed to trust the
index absolutely.
THE COUNT IS OF SPAWN SITES THE PATTERN SET MATCHED, which is a fact about the BUILD. Saying
so costs one clause and is simply true. And because the pattern set is DECLARABLE, the
sentence can route to the fix — `thread_patterns` — rather than hedge: a reader told "this may
be incomplete" has nowhere to go, a reader told the section name has a one-line change.
@brief Build the roster's row_meaning.
@return The sentence.
@version 4
"""
if not attributable:
return f"{origin.total} thread(s), and {_THREADS_UNATTRIBUTED_MEANING}"
roots = f" ({', '.join(origin.external_roots)})" if origin.external_roots else ""
return (
f"{origin.total} thread(s), of which {origin.first_party} are spawned by THIS "
f"repository, {origin.external} by a vendored submodule{roots}, and "
f"{origin.unresolved} from a spawn site this index could not resolve to a file. "
f"Quote origin.first_party as the repository's spawn sites THIS BUILD'S PATTERNS "
f"MATCHED — not as its thread count. THAT IS AN EXACT FIGURE, not an estimate, and "
f"stating it with its scope ('N spawn sites, across the primitives this build searches') "
f"is a COMPLETE answer rather than a hedged one. A spawn primitive outside the pattern "
f"set is "
f"invisible here rather than reported as absent, so a platform this build does not know "
f"(a Windows `_beginthread`, an RTOS wrapper, a project's own spawn helper) contributes "
f"nothing to this number: widen it by declaring a `thread_patterns` section. "
f"status.diagnostics may name a candidate, but only for a primitive this repository "
f"DECLARES — an external platform API it merely calls cannot be hinted at, so the "
f"absence of a hint is not evidence of coverage. Attribution is by SPAWN "
f"SITE, not by entry symbol: `entry` is null whenever the entry name did not resolve to "
f"an indexed function, and those rows are still attributable because the spawn call "
f"itself always has a file."
)
Activity · 4 steps
Flows
_search_rank
int clew.query.symbols._search_rank(str name, str brief, str query, list[str] tokens, str path="")
Rank one candidate against the query tokens (higher is better).
Called by _class_candidates, _config_candidates, _file_candidates, _memberdef_candidates
Calls none
Source · 26 lines
def _search_rank(name: str, brief: str, query: str, tokens: list[str], path: str = "") -> int:
"""Order by how much of the match landed in the NAME, which is what a
caller actually asked about — a token found only in prose is weaker
evidence than the same token in the identifier.
v3 scores the CONTAINING FILE, last and least. A symbol whose file is named for the query was
previously unreachable by any natural query: measured on a graded cell, `search("loader")`
returned 24 rows and none was `_candidate_paths`, defined in `_loader.py` — the symbol an
agent needed and never saw. Ranked below a brief so a path match cannot bury a named one.
@brief Score a search candidate.
@return Relevance score.
@version 3
"""
lname = name.lower()
score = 0
if lname == query:
score += SEARCH_WEIGHT_EXACT_NAME
if query and query in lname:
score += SEARCH_WEIGHT_NAME_SUBSTRING
score += SEARCH_WEIGHT_TOKEN_IN_NAME * sum(1 for t in tokens if t in lname)
score += SEARCH_WEIGHT_TOKEN_IN_BRIEF * sum(1 for t in tokens if t in brief.lower())
score += SEARCH_WEIGHT_TOKEN_IN_PATH * sum(1 for t in tokens if t in path.lower())
return score
Activity · 10 steps
Flows
_spawn_attribution
tuple[str, str] clew.query.symbols._spawn_attribution(sqlite3.Connection conn, int|None path_rowid)
The spawning file's repo-relative path and its external root.
Source · 24 lines
def _spawn_attribution(conn: sqlite3.Connection, path_rowid: int | None) -> tuple[str, str]:
"""Two values from one lookup, because they come from the same row and a caller that had to
ask twice could get an external root for a file it did not resolve.
A rowid that resolves to no `path` row returns ('', ''), which lands in the UNRESOLVED
bucket rather than the first-party one — "we do not know whose this is" is not "it is ours".
@brief Resolve a spawn site's file and owner.
@return Path and external root, each '' when unknown.
@version 1
"""
if path_rowid is None:
return "", ""
tagged = has_columns(conn, "path", EXTERNAL_ROOT_COLUMN)
column = f"p.{EXTERNAL_ROOT_COLUMN}" if tagged else "''"
row = conn.execute(
f"SELECT p.name, COALESCE({column}, '') FROM path p WHERE p.rowid=?",
(path_rowid,),
).fetchone()
if row is None:
return "", ""
return row[0] or "", row[1] or ""
Activity · 8 steps
Flows
_thread_columns
str clew.query.symbols._thread_columns(sqlite3.Connection conn)
The threads column list this index can actually supply.
Source · 19 lines
def _thread_columns(conn: sqlite3.Connection) -> str:
"""An index predating build version 35 has no spawn-site columns, and one predating build 48
has no `spawn_function`; selecting either raises `OperationalError` rather than degrading —
the contract `has_columns` exists to keep. THREE tiers now, widest first, so a current index
is never served the narrower list.
@brief Choose the threads column list for this schema.
@return SQL column list.
@version 2
"""
if has_columns(conn, "threads", "lifecycle", "lifecycle_line"):
return _THREAD_LIFECYCLE_COLUMNS
if has_columns(conn, "threads", "spawn_path_rowid", "spawn_line", "spawn_function"):
return _THREAD_SPAWNER_COLUMNS
if has_columns(conn, "threads", "spawn_path_rowid", "spawn_line"):
return _THREAD_SITE_COLUMNS
return _THREAD_COLUMNS
Activity · 7 steps
Flows
_thread_origins
list[str | None] clew.query.symbols._thread_origins(tuple[Thread,...] threads)
One origin per thread, keyed on its SPAWN SITE.
Source · 12 lines
def _thread_origins(threads: tuple[Thread, ...]) -> list[str | None]:
"""`spawn_file` EMPTY MEANS UNRESOLVED, not first party, and that distinction is the whole
point of gh#346 — the rows it separates are the ones that used to inflate the first-party
count by defaulting into it.
@brief Classify each thread by its spawn site.
@return One origin per thread.
@version 1
"""
return [(t.external_root or "") if t.spawn_file else None for t in threads]
Activity · 1 steps
Flows
_unread_kind_counts
dict[str, int] clew.query.symbols._unread_kind_counts(sqlite3.Connection conn, str table, list[str] tokens, set[str] searched)
Per-kind match counts for the kinds of one table that search does not read.
Source · 29 lines
def _unread_kind_counts(
conn: sqlite3.Connection, table: str, tokens: list[str], searched: set[str]
) -> dict[str, int]:
"""The kind list comes from the DATABASE (`SELECT DISTINCT kind`), never from a
literal here, which is what makes the caller's subtraction cover a kind nobody
wrote down. `table` is one of two fixed strings chosen by the caller and is
interpolated; every value a caller supplies is bound.
Matching mirrors `_memberdef_candidates` — the same conjunction over name and
brief — because a count that used looser matching would grade a result down on
rows `search` would not have returned even with the corpus added.
@brief Count matching distinct names per unread kind of one table.
@return {kind: distinct matching names}.
@version 1
"""
clause = " AND ".join(
["(LOWER(name) LIKE ? OR LOWER(COALESCE(briefdescription,'')) LIKE ?)"] * len(tokens)
)
params: list[str] = []
for token in tokens:
params += [f"%{token}%"] * 2
rows = conn.execute(
f"SELECT kind, COUNT(DISTINCT name) FROM {table} WHERE {clause} GROUP BY kind",
params,
).fetchall()
return {kind: n for kind, n in rows if kind not in searched}
Activity · 6 steps
Flows
_variant_rank
tuple[int, int] clew.query.symbols._variant_rank(str source, str|None confidence)
Sort key ranking one layer's evidence for the same endpoint.
Source · 22 lines
def _variant_rank(source: str, confidence: str | None) -> tuple[int, int]:
"""Ranks by resolution confidence first, then by the layer's position in the
DECLARED `CALL_SOURCE` order as a deterministic tie-break. That order is the
pipeline's own layer order, so an equal-confidence tie resolves to the
earlier, more direct extractor rather than to whatever sorted first.
An unregistered value ranks LAST rather than raising: this is a read path over
a database that may predate a vocabulary addition, and refusing to describe an
edge is worse than describing it as the weakest evidence.
@brief Rank one (source, confidence) variant of an endpoint.
@return Comparable rank tuple; higher wins.
@version 1
"""
order = (
CALL_SOURCE.values.index(source)
if source in CALL_SOURCE.values
else len(CALL_SOURCE.values)
)
return (CALL_MATCH.rank.get(confidence or "", -1), -order)
Activity · 2 steps
Flows
all_req_edges
list[ReqEdge] clew.query.symbols.all_req_edges(DbSource db)
Every requirement-traceability edge as an absolute fn → req_id pair.
Source · 19 lines
def all_req_edges(db: DbSource) -> list[ReqEdge]:
"""The bulk requirement-traceability view: every implementer edge as an
absolute fn → req_id pair, deterministically ordered. The HTML db-explorer
consumes this so the req_edges JOIN lives once in R2.
@brief List every requirement-traceability edge as fn → req_id.
@version 2
"""
with connect(db) as conn:
if not table_exists(conn, "req_edges"):
return []
rows = conn.execute(
"SELECT DISTINCT m.name, r.req_id FROM req_edges r "
"JOIN memberdef m ON m.rowid = r.memberdef_rowid "
"ORDER BY m.name, r.req_id",
).fetchall()
return [ReqEdge(fn=fn, req_id=rid) for fn, rid in rows]
Activity · 5 steps
Requirements
callees
list[CallEdge] clew.query.symbols.callees(DbSource db, str fn, str|None qualified=None)
Causal neighbours OUT of fn : its callees plus the readers of its writes.
Called by none
Tested by 19 tests
test_a_call_to_an_overridden_endpoint_is_annotated_with_its_implementors, test_a_macro_with_no_recorded_expansion_is_still_named, test_an_index_without_the_relation_degrades_to_empty, test_an_unmatched_selector_returns_nothing_rather_than_the_union, test_callees_merge_dataflow_tagged_as_key_not_call, test_callees_of_writer, test_collision_free_names_are_unaffected, test_confidence_and_strength_are_never_mixed_in_one_field, test_dataflow_polarity_is_the_writer_side_of_callers, test_decl_def_duality_keeps_its_edges, test_edge_class_is_exactly_the_registered_vocabulary, test_multi_source_edge_collapses_to_one_row_per_endpoint 7 more
test_name_accessors_degrade_gracefully_on_table_less_db, test_neighbour_wire_keys_are_pinned_literally, test_pre_r1_shared_key_schema_degrades_instead_of_raising, test_query_surface_invariants_hold_on_real_data, test_same_named_c_statics_in_different_files_still_merge, test_the_query_layer_quotes_doxygens_own_expansion_verbatim, test_wrappers_match_the_r2_library_exactly
Calls _call_edges, connect
Source · 16 lines
def callees(db: DbSource, fn: str, qualified: str | None = None) -> list[CallEdge]:
"""Everything `fn` causally reaches in one hop, in one list: direct call
edges AND the shared-key readers of the values it writes. Check `edge_class`
on every row — a `'key'` neighbour is not called by `fn`; it observes a key
`fn` wrote, possibly asynchronously and on another thread.
`qualified` (gh#37) selects among same-named functions; it narrows the `'call'`
rows and not the `'key'` rows, for the reason `_call_edges` gives.
@brief Return the causal successors of `fn` (calls + dataflow).
@version 4
"""
with connect(db) as conn:
return _call_edges(conn, fn, want_callers=False, include_dataflow=True, qualified=qualified)
Activity · 2 steps
Requirements
callers
list[CallEdge] clew.query.symbols.callers(DbSource db, str fn, str|None qualified=None)
Causal neighbours INTO fn : its callers plus the writers it reads from.
Called by none
Tested by 14 tests
test_an_unmatched_selector_returns_nothing_rather_than_the_union, test_callers_includes_fnptr_dispatch, test_confidence_and_strength_are_never_mixed_in_one_field, test_dataflow_polarity_is_the_writer_side_of_callers, test_decl_def_duality_keeps_its_edges, test_genuine_recursion_survives_the_identity_split, test_multi_source_edge_collapses_to_one_row_per_endpoint, test_name_accessors_degrade_gracefully_on_table_less_db, test_neighbour_lists_narrow_to_the_selected_identity, test_neighbour_wire_keys_are_pinned_literally, test_pre_r1_shared_key_schema_degrades_instead_of_raising, test_the_measurement_is_r2_and_the_dossier_withholds_nothing
Calls _call_edges, connect
Source · 16 lines
def callers(db: DbSource, fn: str, qualified: str | None = None) -> list[CallEdge]:
"""Everything that causally precedes `fn`, in one list: direct call edges
AND the shared-key writers whose values `fn` reads. Check `edge_class` on
every row — a `'key'` neighbour does NOT call `fn` and may run on another
thread.
`qualified` (gh#37) selects among same-named functions; it narrows the `'call'`
rows and not the `'key'` rows, for the reason `_call_edges` gives.
@brief Return the causal predecessors of `fn` (calls + dataflow).
@version 4
"""
with connect(db) as conn:
return _call_edges(conn, fn, want_callers=True, include_dataflow=True, qualified=qualified)
Activity · 2 steps
Requirements
key_edges
list[KeyEdge] clew.query.symbols.key_edges(sqlite3.Connection conn, str fn, bool as_writer)
Build KeyEdges for one function as writer (writes) or reader (reads).
Source · 28 lines
def key_edges(conn: sqlite3.Connection, fn: str, as_writer: bool) -> list[KeyEdge]:
"""Shared-key edges where `fn` is the writer (`as_writer=True`, → the
reads-from list of `writes`) or the reader. `other` is the counterpart
function. Includes the R1 dispatch/thread columns; `to_thread` is the
reader thread's NAME (LEFT JOIN threads).
@brief Build KeyEdge rows for one function in one role.
@version 3
"""
return [
KeyEdge(
key_name=k,
edge_kind=kind,
other=oname,
other_rowid=resolve_rowid(conn, oname) or -1,
source=src,
confidence=conf,
dispatch_mode=dm,
edge_triggered=to_bool(et),
crosses_thread=to_bool(ct),
to_thread=tthr,
)
for oname, k, kind, src, conf, dm, et, ct, tthr in _key_edge_rows(
conn, fn, as_writer=as_writer
)
]
Activity · 1 steps
Requirements
name_ambiguity
NameAmbiguity | None clew.query.symbols.name_ambiguity(DbSource db, str fn, *bool want_callers=True)
The name-ambiguity behind one function's neighbour list, or None when clean.
Source · 27 lines
def name_ambiguity(db: DbSource, fn: str, *, want_callers: bool = True) -> NameAmbiguity | None:
"""Quantify why a function can appear to have neighbours it does not have.
Returns None on the common path — an unambiguous name, or an ambiguous one with no
fuzzy `ast_member` neighbours — so a consumer treats a present value as a warning
rather than having to compare a number against 1 on every call.
ADDITIVE, deliberately: `callers`/`callees` keep returning `list[CallEdge]` and no
existing signature moves. The alternative was a field on `CallEdge`, which would have
changed the literal wire-key set that `test_neighbour_wire_keys_are_pinned_literally`
exists to gate — worth doing for a per-ROW fact, but this is a property of the focal
NAME, so a separate accessor states it in the right place.
BOTH SURFACES get this, because it is LOSSLESS — it adds a number and removes nothing.
Capping the rows themselves is lossy and therefore lives at the MCP boundary only,
alongside `RESPONSE_BUDGET_BYTES`, on the reasoning that a local viewer has no context
window to protect.
@brief Measure the same-name ambiguity behind a neighbour list.
@return NameAmbiguity, or None when the list is not shared with namesakes.
@version 1
"""
with connect(db) as conn:
candidates, shared = _ambiguity_counts(conn, fn, want_callers=want_callers)
return NameAmbiguity(name=fn, candidates=candidates, shared_rows=shared) if shared else None
Activity · 3 steps
Requirements
Flows
overridden_by
list[OverrideRef] clew.query.symbols.overridden_by(DbSource db, str fn, str|None qualified=None)
The derived methods that reimplement a function (what may run instead).
Source · 18 lines
def overridden_by(db: DbSource, fn: str, qualified: str | None = None) -> list[OverrideRef]:
"""The direction a consumer asking "what actually runs here" wants. See
`overrides_of` on why this takes a `DbSource`.
`qualified` IS OPTIONAL IN THE SIGNATURE AND USUALLY NECESSARY IN PRACTICE on
this direction specifically, which is worth stating rather than leaving to be
discovered: a base and its overrides share a bare name, so a bare call resolves
to whichever of them the definition-preferring order puts first, and that is a
subclass more often than not. See `_override_refs` for the measured case.
@brief What overrides this function.
@return OverrideRef list.
@version 2
"""
with connect(db) as conn:
return _override_refs(conn, fn, want_bases=False, qualified=qualified)
Activity · 2 steps
Requirements
overrides_of
list[OverrideRef] clew.query.symbols.overrides_of(DbSource db, str fn, str|None qualified=None)
The base methods a function reimplements (what it overrides).
Source · 15 lines
def overrides_of(db: DbSource, fn: str, qualified: str | None = None) -> list[OverrideRef]:
"""Takes a `DbSource` rather than a bare connection, unlike the private
`_override_refs` it delegates to, because it is EXPORTED — and every public
accessor on this surface accepts `Path | str | sqlite3.Connection`. `connect`
yields a caller-supplied connection unchanged, so `dossier` composing this inside
its own `with connect(...)` block costs nothing.
@brief What this function overrides.
@return OverrideRef list.
@version 2
"""
with connect(db) as conn:
return _override_refs(conn, fn, want_bases=True, qualified=qualified)
Activity · 2 steps
Requirements
req_trace
ReqTrace clew.query.symbols.req_trace(DbSource db, str req_id)
Version 3: also every indexed file line naming the id ( mentioned_in ), from req_mentions .
Called by _trace
Tested by 7 tests
test_all_req_edges_agrees_with_req_trace, test_an_entry_stating_none_of_them_has_empty_attributes_and_no_extra, test_an_index_from_before_the_columns_still_traces, test_req_trace_findme, test_requirement_traceability_state_is_known, test_the_29148_attributes_and_extra_are_served, test_wrappers_match_the_r2_library_exactly
Calls _req_attributes, _req_failure_modes, _req_implementers, _req_links, connect, list, table_exists, test_name_sql
Source · 61 lines
def req_trace(db: DbSource, req_id: str) -> ReqTrace:
"""Trace one requirement to its implementing functions (with liveness)
and covering test functions. Metadata fields are '' when the
requirements table has no matching row (a bare @req literal still traces).
@brief Build a ReqTrace for one requirement id.
@version 5
"""
with connect(db) as conn:
meta = None
attrs: dict[str, Any] = {}
if table_exists(conn, "requirements"):
meta = conn.execute(
"SELECT block, title, acceptance, priority FROM requirements WHERE id=?",
(req_id,),
).fetchone()
attrs = _req_attributes(conn, req_id)
## 2.1 (clew#74): each test by its own name (a Catch2 case's title) AND its function's, so
## the implementers still leave out a case whose row is named `TEST_CASE`.
linked = (
conn.execute(
f"SELECT DISTINCT {test_name_sql(conn)}, m.name FROM req_test_edges t "
"JOIN memberdef m ON m.rowid = t.test_memberdef_rowid "
"WHERE t.req_id=? ORDER BY 1",
(req_id,),
).fetchall()
if table_exists(conn, "req_test_edges")
else []
)
tests = list(dict.fromkeys(str(r[0]) for r in linked))
implementers = _req_implementers(conn, req_id, set(tests) | {str(r[1]) for r in linked})
mentions = (
[
ReqMention(file=str(r[0]), line=int(r[1]), text=str(r[2]))
for r in conn.execute(
"SELECT file, line, text FROM req_mentions WHERE req_id=? ORDER BY file, line",
(req_id,),
)
]
if table_exists(conn, "req_mentions")
else None
)
links = _req_links(conn, req_id)
modes = _req_failure_modes(conn, req_id)
block, title, acceptance, priority = meta if meta else ("", "", "", "")
return ReqTrace(
req_id=req_id,
block=block,
title=title,
acceptance=acceptance,
priority=priority,
implementers=implementers,
tests=tests,
mentioned_in=mentions,
satisfies=links[0] if links else None,
satisfied_by=links[1] if links else None,
failure_modes=modes or None,
**attrs,
)
Activity · 14 steps
Requirements
resolve_symbol
SymbolRef | None clew.query.symbols.resolve_symbol(DbSource db, str name, str|None qualified=None)
Resolve a name to a definition-preferring SymbolRef, or None.
Called by none
Tested by 10 tests
test_a_disambiguated_reply_still_reports_the_alternatives, test_a_parsed_row_is_distinguishable_from_a_doxygen_row_at_every_surface, test_a_qualified_selector_returns_the_one_identity_asked_for, test_an_ambiguous_call_without_a_selector_behaves_as_before, test_an_unmatched_selector_returns_nothing_rather_than_the_union, test_name_accessors_degrade_gracefully_on_table_less_db, test_resolve_symbol_decl_def_duality_is_not_an_overload, test_resolve_symbol_definition_preferring, test_resolve_symbol_flags_genuine_overload, test_two_identities_in_one_file_are_still_distinguishable
Calls candidate_rows, connect, function_candidates, is_overloaded, symbol_provenance
Source · 50 lines
def resolve_symbol(db: DbSource, name: str, qualified: str | None = None) -> SymbolRef | None:
"""Resolve a function name to its canonical rowid + location. None when
no function of that name is indexed. When the name maps to MORE THAN ONE
distinct signature (a genuine overload, not mere decl/def duality), the
returned SymbolRef carries the alternatives in `candidates` (capped) so a
consumer knows the primary pick was one of several and can re-query the
specific one; unambiguous names return an empty `candidates`.
`qualified` closes that loop (gh#37): pass a `candidates[i].qualified` back and
this resolves THAT identity rather than the definition-preferring first. It
remains OPTIONAL, and the bare-name path is byte-identical to what it was —
the common case is a unique name, and requiring a selector there would break
every existing caller to fix a case they do not have.
`candidates` is still reported on a DISAMBIGUATED call, deliberately, because
the name is still ambiguous — the reply says "you asked for this one, and these
others exist". Suppressing it would make a narrowed answer look unique.
@brief Resolve a function name to a SymbolRef, flagging overloads.
@version 6
"""
with connect(db) as conn:
cands = function_candidates(conn, name, qualified)
if not cands:
return None
rowid = cands[0][0]
row = conn.execute(
"SELECT m.name, m.kind, COALESCE(p.name,''), m.bodystart, m.bodyend "
"FROM memberdef m LEFT JOIN path p ON p.rowid = m.file_id "
"WHERE m.rowid=?",
(rowid,),
).fetchone()
## Ambiguity is a property of the NAME, not of this call, so it is measured
## against every same-named row rather than against the filtered subset — a
## disambiguated call to a 3-way name must not report itself as unambiguous.
all_cands = function_candidates(conn, name) if qualified is not None else cands
overloads = candidate_rows(conn, name, all_cands) if is_overloaded(all_cands) else []
provenance = symbol_provenance(conn, rowid)
return SymbolRef(
name=row[0],
rowid=rowid,
kind=row[1],
file=row[2],
line_start=row[3],
line_end=row[4],
candidates=overloads,
provenance=provenance,
)
Activity · 10 steps
Requirements
search
list[SymbolHit] clew.query.symbols.search(DbSource db, str text, int limit=DEFAULT_SEARCH_LIMIT)
Multi-token, ranked search over symbol names, briefs and file-level documentation.
Called by none
Tested by 12 tests
test_name_accessors_degrade_gracefully_on_table_less_db, test_search_empty_and_unmatched_queries_stay_empty, test_search_excludes_stl_compounds_but_lookup_class_still_reaches_them, test_search_finds_a_class_by_its_brief, test_search_finds_a_class_by_name, test_search_finds_known_symbol, test_search_for_an_absent_class_name_is_still_empty, test_search_is_capped_and_the_cap_is_caller_controlled, test_search_matches_every_token_not_the_literal_phrase, test_search_ranking_is_unchanged_on_a_db_with_no_compounds, test_search_ranks_name_matches_above_prose_matches, test_search_still_finds_a_function_unchanged
Calls search_counted
Source · 74 lines
def search(db: DbSource, text: str, limit: int = DEFAULT_SEARCH_LIMIT) -> list[SymbolHit]:
"""Every whitespace-separated token must appear in ONE searchable unit; results
are then RANKED, name matches ahead of prose matches.
This replaces a single literal `LIKE '%<whole query>%'`, which made any
multi-word query return nothing at all: `'%lock acquisition%'` is a literal
substring that no identifier contains. Verified on clew's own index —
`search("lock")` gave 9 hits while `search("lock acquisition")` gave ZERO,
and the empty envelope then told the caller "This is a definitive empty
result ... Do not retry", which is the confidently-wrong failure mode.
Search is the discovery entry point: if it answers nothing for a natural
phrase, a consumer never reaches dossier or chain_trace at all.
gh#10 adds the SECOND searchable unit: a file's module docstring or file-level
doxygen comment, returning the FILE as the hit (`kind='file'`). Without it a
query phrased as a concept missed code that is entirely about that concept —
`search("deadlock")` was zero on this repository while `query/locks.py` is a
module about lock nesting, because implementations are named for mechanics
(`lock_nestings`, `_harvest_registration`) and that is correct naming.
This is NOT a fallback to `search_prose`, which was considered and rejected:
a tool that silently changes corpus on a miss has two meanings and the caller
cannot tell which one answered. The file-level corpus is searched ALWAYS, with
the same conjunction and the same weights, and every row says which it is.
Markdown documentation remains `search_prose`'s alone.
gh#372 adds the FOURTH: a global or file-scope VARIABLE. See
`_variable_candidates` for the measurement — mbedtls's five global mutex objects
and its function-pointer lock primitive were all unfindable, and the only route to
the repo's mutex list was reading a function body. Variables sit in the LOWEST
tie-break tier, so no function's rank changes; a variable only outranks a function
by scoring strictly higher, which is what an exact name match should do.
gh#315 adds the THIRD searchable unit: a class/struct/union/interface, from
`compounddef`. Until then `search` looked only at `memberdef WHERE kind='function'`
and the file docs, so a class name was not outranked or filtered — it was ABSENT
FROM THE SEARCHED SET, and the reply was a confident empty result indistinguishable
from a measured negative. Reproduced on this repository: `search("WritePlan")`
returned the `mcp_config.py` file doc while the class sits in that same file. That
failure mode costs a graded agent marks silently, because there is nothing in the
answer to suggest a second look. See `corpus.class_rows` for why STL compounds are
excluded from this corpus while `lookup_class` still reaches them.
gh#373 adds the FIFTH: a preprocessor `#define`, matched on its name, its brief
AND its expansion. See `_macro_candidates` for the measurement — the graded
mbedtls question is about a macro, and the gating macro it turns on came back a
confident zero with three rows for it in the index.
gh#394 adds the EIGHTH: a CONFIGURATION SYMBOL the repo gates code on. Same defect
shape as the four before it, measured after gh#390 gave the mbedtls index 10,861
gating sites — `search("MBEDTLS_THREADING_PTHREAD")` returned NOTHING while `dossier`
answered for the same name, so discovery failed for the exact symbols two graded
questions are about and the agent searched for them nine times in one run. It is NOT
part of `SEARCHED_MEMBERDEF_KINDS`: gates live in their own table, not in `memberdef`,
and folding them into that tuple would claim doxygen emitted them.
gh#374 adds the SIXTH and SEVENTH: a `typedef` and an `enumeration`. The corpora
are no longer added one wrapper at a time — `SEARCHED_MEMBERDEF_KINDS` is the
covered set, `_memberdef_corpora` iterates it and `mcp_server.emptiness` words the
empty reply from it, because the recurring defect was never any single missing kind
but the absence of one place that says which kinds are read. Measured on mbedtls:
282 of 7,717 distinct `memberdef` names lived only under an unsearched kind.
WHAT IS STILL NOT READ is reported rather than assumed away: `unsearched_corpora`
counts the rows a query WOULD have matched in a corpus this function does not
cover, and an empty result that has such rows behind it is graded down instead of
being called definitive.
@brief Search functions, variables, classes, macros, types, config symbols and file docs, ranked.
@version 13
"""
return search_counted(db, text, limit)[0]
Activity · 1 steps
Requirements
search_counted
tuple[list[SymbolHit], int] clew.query.symbols.search_counted(DbSource db, str text, int limit=DEFAULT_SEARCH_LIMIT)
search , plus how many rows matched before the limit cut them.
Called by _symbol_corpus, search
Calls _class_candidates, _config_candidates, _file_candidates, _memberdef_corpora, connect
Source · 28 lines
def search_counted(
db: DbSource, text: str, limit: int = DEFAULT_SEARCH_LIMIT
) -> tuple[list[SymbolHit], int]:
"""T1 (2.0.0): every candidate is already ranked before the slice, so the total is free — a
reply cut at its limit can say "25 of 140" instead of "25". See `search` for the corpora.
@brief Ranked search with its uncut total.
@return (hits, total).
@version 1
"""
tokens = [t.lower() for t in text.split() if t]
if not tokens:
return [], 0
query = text.strip().lower()
with connect(db) as conn:
ranked = (
_memberdef_corpora(conn, query, tokens)
+ _class_candidates(conn, query, tokens)
+ _config_candidates(conn, query, tokens)
+ _file_candidates(conn, query, tokens)
)
# Negated score, then symbols ahead of files on a tie, then name: best first,
# ties alphabetical so results are stable across builds rather than dependent
# on rowid order.
ranked.sort(key=lambda r: (r[0], r[1], r[2]))
return [hit for _score, _tier, _name, hit in ranked[: max(1, limit)]], len(ranked)
Activity · 8 steps
Requirements
Flows
thread_of
list[Thread] clew.query.symbols.thread_of(DbSource db, str fn)
Threads one function belongs to.
Source · 17 lines
def thread_of(db: DbSource, fn: str) -> list[Thread]:
"""Union membership over EVERY rowid the name denotes.
Previously this resolved one canonical rowid, which broke both ways on
in practice: a QUALIFIED name straight out of `thread_roster`
(`LinkOwner::rx_loop`) matched no unqualified `memberdef.name` and
returned empty for 11 of 12 threads, while a bare ambiguous name (`run`)
silently answered for one of two real threads. Both produced a confident
empty-or-partial answer to "which thread does this run on".
@brief Return every Thread whose membership includes function `fn`.
@version 4
"""
with connect(db) as conn:
return threads_for_rowids(conn, rowids_for_name(conn, fn))
Activity · 2 steps
Requirements
thread_roster
ThreadInventory clew.query.symbols.thread_roster(DbSource db)
Every thread in the DB, with member counts and the origin split.
Called by _thread_subject, corpus_payload, threads
Tested by 8 tests
test_a_null_entry_thread_is_attributed_by_its_spawn_site, test_an_absent_thread_layer_says_so, test_an_index_with_no_spawn_sites_refuses_to_pose_as_a_measurement, test_chain_trace_crosses_thread_key_hop, test_the_thread_payload_does_not_call_a_matched_count_the_thread_count, test_the_thread_payload_leads_with_the_first_party_count, test_the_thread_split_buckets_every_row, test_thread_apis_empty_on_threadless_firmware
Calls _build_thread, _roster_meaning, _thread_columns, _thread_origins, connect, has_columns, table_exists
Source · 42 lines
def thread_roster(db: DbSource) -> ThreadInventory:
"""AN ENVELOPE SINCE gh#346, not a bare list, because this roster could not previously
express whose threads it was listing. A thread row was anchored to its ENTRY symbol, which is
legitimately NULL whenever the entry name does not resolve to a rowid — a member-function
pointer naming an unindexed class, or a bare name that is not unique — and a row with no
entry has no file, so it could not be tagged, so a submodule's threads counted as FIRST PARTY.
That inflates the one figure gh#335's invariance control rests on (admitting a submodule
must raise the total and leave every first-party figure IDENTICAL). Measured on entropic:
12 rows, 4 resolving into entropic, 6 into the vendored submodule, 2 to no file at all —
and those 2 were exactly the mis-attributed ones.
THE SPAWN SITE IS THE ANCHOR because it always exists and because it answers the question
the tag asks: where is this thread CREATED. The entry answers what it RUNS, which is
sometimes unknowable.
A PRE-35 INDEX SAYS SO IN `row_meaning` rather than reporting a zeroed split as a
measurement. An index that cannot attribute its threads and an index whose threads are all
first party would otherwise produce identical numbers.
@brief Return every thread with its entry, spawn site, member count and the origin split.
@return ThreadInventory; `threads` empty when the layer is absent.
@version 3
"""
with connect(db) as conn:
if not table_exists(conn, "threads"):
return ThreadInventory(
threads=(), rows=0, row_meaning=_THREADS_ABSENT_MEANING, origin=OriginSplit.of(())
)
attributable = has_columns(conn, "threads", "spawn_path_rowid", "spawn_line")
rows = conn.execute(
f"SELECT {_thread_columns(conn)} FROM threads t ORDER BY t.id",
).fetchall()
threads = tuple(_build_thread(conn, r) for r in rows)
origin = OriginSplit.of(_thread_origins(threads))
return ThreadInventory(
threads=threads,
rows=len(threads),
row_meaning=_roster_meaning(origin, attributable=attributable),
origin=origin,
)
Activity · 8 steps
Requirements
REQ-DDB-QUERY-001 REQ-DDB-QUERY-011
Flows
threads_for
list[Thread] clew.query.symbols.threads_for(sqlite3.Connection conn, int rowid)
Threads whose call-closure membership contains one rowid.
Source · 19 lines
def threads_for(conn: sqlite3.Connection, rowid: int) -> list[Thread]:
"""Selects through `_thread_columns` rather than its own literal list, so this and the roster
cannot drift into asking for differently-shaped rows — `_build_thread` unpacks POSITIONALLY,
so a divergence between two spellings would misread a column rather than raise.
@brief Return the Threads a memberdef rowid belongs to (by membership).
@version 3
"""
if not (table_exists(conn, "threads") and table_exists(conn, "thread_membership")):
return []
rows = conn.execute(
f"SELECT DISTINCT {_thread_columns(conn)} FROM thread_membership tm "
"JOIN threads t ON t.id = tm.thread_id "
"WHERE tm.memberdef_rowid=? ORDER BY t.id",
(rowid,),
).fetchall()
return [_build_thread(conn, r) for r in rows]
Activity · 4 steps
Requirements
threads_for_rowids
list[Thread] clew.query.symbols.threads_for_rowids(sqlite3.Connection conn, list[int] rowids)
Union thread membership over several memberdef rowids.
Source · 20 lines
def threads_for_rowids(conn: sqlite3.Connection, rowids: list[int]) -> list[Thread]:
"""`thread_membership` is keyed per rowid, so any question phrased about a
NAME must union across the rowids that name denotes — otherwise a function
whose membership was recorded against its declaration row (or against a
sibling overload) reports no thread at all.
@brief Union thread membership across rowids.
@return Deduped Threads in thread-id order.
@version 1
"""
seen: set[int] = set()
found: list[Thread] = []
for rowid in rowids:
for thread in threads_for(conn, rowid):
if thread.id not in seen:
seen.add(thread.id)
found.append(thread)
return sorted(found, key=lambda t: t.id)
Activity · 8 steps
Requirements
token_hit_counts
dict[str, int] clew.query.symbols.token_hit_counts(DbSource db, list[str] tokens)
How many symbols and files each token matches ON ITS OWN.
Source · 24 lines
def token_hit_counts(db: DbSource, tokens: list[str]) -> dict[str, int]:
"""gh#31. `search("roots target resolution")` returned a definitive-sounding
zero while `_target_from_roots` was indexed, because the conjunction is over
name+brief and that brief has `roots` and neither `target` nor `resolution`.
Ranking behaved as specified; the NOTE was the defect, telling the caller not
to retry when dropping a token was the one correct next move.
Per-token counts name the token that emptied the query, which turns a wasted
call into an answer. COST: one COUNT per token, so this is computed ONLY when
the result is already zero and only up to `MAX_DIAGNOSED_TOKENS`. Paid exactly
where the alternative is a call that returned nothing at all, and never on the
common path.
@brief Count each token's independent matches.
@return {token: count}.
@version 1
"""
counts: dict[str, int] = {}
with connect(db) as conn:
for token in tokens:
counts[token] = _one_token_count(conn, token)
return counts
Activity · 5 steps
Requirements
Flows
unresolved_inbound_for_rowids
int | None clew.query.symbols.unresolved_inbound_for_rowids(sqlite3.Connection conn, Iterable[int] ids)
How many call sites named a function this identity could be and did not resolve.
Source · 33 lines
def unresolved_inbound_for_rowids(conn: sqlite3.Connection, ids: Iterable[int]) -> int | None:
"""WHAT MAKES AN EMPTY `callers` READABLE (gh#15). Without it the list means either
"nothing calls this" or "callers exist and none survived resolution", and those are far
apart: a reporter took the first reading of the second case, followed the only caller
offered — a test helper — and shipped a wrong conclusion with the real answer one
unresolved hop away.
SUMMED OVER THE IDENTITY, not the chosen rowid, for the same reason thread membership is:
doxygen splits one function across a declaration row and a definition row, and a refusal
recorded against the sibling is a refusal against this function.
RETURNS None, NEVER 0, WHEN THE TABLE IS ABSENT. An index built before this was recorded
has no measurement, and reporting that as zero would assert a clean bill of health from a
detector that could not look — this repository's standing failure mode, and the one
`gates_unplaceable` documents on the other direction.
@return Site count, or None when unmeasured.
@version 1
"""
if not table_exists(conn, "unresolved_inbound"):
return None
rowids = list(ids)
if not rowids:
return 0
placeholders = ",".join("?" * len(rowids))
row = conn.execute(
f"SELECT COALESCE(SUM(sites), 0) FROM unresolved_inbound " # noqa: S608
f"WHERE callee_rowid IN ({placeholders})",
rowids,
).fetchone()
return int(row[0]) if row else 0
Activity · 8 steps
Requirements
unsearched_corpora
dict[str, int] clew.query.symbols.unsearched_corpora(DbSource db, list[str] tokens)
Rows a zero-result query WOULD have matched in a corpus search does not read.
Source · 39 lines
def unsearched_corpora(db: DbSource, tokens: list[str]) -> dict[str, int]:
"""THE POINT OF THIS FUNCTION IS TO MAKE A NEGATIVE HONEST, not to find rows. An
empty `search` used to assert "This IS a definitive empty result ... Do not retry
this query or fall back to guessing" whenever a single token matched nothing, and
that sentence is a claim about the REPOSITORY made from evidence about three or five
corpora. Four times now the two have differed and the sentence was simply false:
classes (gh#315), variables (gh#372), macros (gh#373), typedefs and enumerations
(gh#374). Each time the reply was maximally confident and maximally wrong, and the
graded consequence is on record — one cell answered a macro question with fifteen
consecutive searches and a fall back to `Grep`.
Adding the missing corpus fixes the instance. This fixes the CLASS, because it does
not enumerate what is missing: it derives the unread set by SUBTRACTION, from the
kinds actually present in this database minus the kinds `search` reads. A corpus
nobody has thought of yet — a kind a future doxygen emits, a layer a later pipeline
stage adds — downgrades the verdict the day it first appears, with no edit here.
That is the difference between a fix and a guard.
It is computed ONLY on a query that already returned nothing, alongside the
per-token diagnosis and under the same argument: two COUNTs on a call whose
alternative is a reply with no content at all.
@brief Count matches in corpora `search` does not read, to grade an empty result.
@return {corpus name: distinct matching names}.
@version 1
"""
if not tokens:
return {}
found: dict[str, int] = {}
with connect(db) as conn:
searched = {kind for kind, _tier in SEARCHED_MEMBERDEF_KINDS}
if table_exists(conn, "memberdef"):
found |= _unread_kind_counts(conn, "memberdef", tokens, searched)
if table_exists(conn, "compounddef"):
covered = set(CLASS_KINDS) | set(_COVERED_COMPOUND_KINDS)
found |= _unread_kind_counts(conn, "compounddef", tokens, covered)
return {kind: n for kind, n in sorted(found.items()) if n}