_common.py¶
clew/query/_common.py
Shared connection + resolution helpers for the R2 query library.
_ends_at_boundary
bool clew.query._common._ends_at_boundary(str name, str suffix)
Whether a qualified name ends with a suffix at a separator boundary (or equals it).
Source · 5 lines
def _ends_at_boundary(name: str, suffix: str) -> bool:
"""@brief Boundary-aligned suffix test. @return True when aligned."""
return name == suffix or name.endswith("." + suffix) or name.endswith("::" + suffix)
Activity · 1 steps
Flows
_one_row_per_declaration
list[tuple] clew.query._common._one_row_per_declaration(list[tuple] cands)
Collapse rows that describe ONE physical declaration into one.
Source · 37 lines
def _one_row_per_declaration(cands: list[tuple]) -> list[tuple]:
"""gh#19. doxygen emits the same member under more than one scope spelling, so
`memberdef` holds two rowids for one physical declaration and `candidates` listed it
twice — byte-identical in signature, file, line and has_body. On the one field whose
entire job is to MEASURE ambiguity, that reports an identity that does not exist, and a
consumer cannot tell it from a genuine overload.
KEYED ON (signature, file, line), NOT on the signature. `signature` here is doxygen's
`definition`, which two genuine overloads SHARE — `void C::f` for both `f(int)` and
`f(char)`, because the parameter list lives in `argsstring` and this tuple does not carry
it. Deduping on it would collapse the very rows this list exists to keep apart, and tell a
caller a name is unambiguous while it picks one of two functions for them. They differ in
LINE, and one declaration cannot be at two lines.
FAILS OPEN ON A ROW WITH NO LINE. Without a position two rows cannot be SHOWN to be one
declaration, only to be indistinguishable in this tuple, so they are both kept — the
behaviour before this existed.
BEFORE THE CAP, deliberately: deduping after `MAX_CANDIDATES` would spend cap slots on
duplicates and drop real identities off the end, which is the silent truncation
`_candidates_capped` was written to disclose.
@brief Drop exact positional duplicates from the candidate rows.
@return Deduped rows in their original order.
@version 1
"""
seen: set[tuple] = set()
kept: list[tuple] = []
for row in cands:
key = (row[1], row[2], row[3])
if row[3] is not None and key in seen:
continue
seen.add(key)
kept.append(row)
return kept
Activity · 9 steps
Requirements
Flows
_test_scope_term
str clew.query._common._test_scope_term(sqlite3.Connection conn, str column)
The ORDER BY fragment that ranks library definitions above test-code ones.
Source · 26 lines
def _test_scope_term(conn: sqlite3.Connection, column: str) -> str:
"""WHY THIS IS A TERM AND NOT A FILTER. A test-code definition is a real definition and
must stay reachable — `candidates` lists it, a qualified name selects it, and a repo whose
only definition of a name is in a test still resolves. It is only DEPRIORITISED, so nothing
becomes unanswerable.
RETURNS '' WHEN THE TABLE IS ABSENT, which is what keeps an index built before this stage
readable: the resolver falls back to its previous ordering rather than raising on a missing
table. An index where the stage RAN and matched nothing has an EMPTY table, not a missing
one, and behaves identically to a repo with no tests — the distinction `mark_test_scope`
exists to preserve.
Ordered FIRST, ahead of the in-place term, and that ordering is the whole fix. On entropic
the real `AgentEngine::run_turn` is declared in a header and defined out of line, so
`file_id == bodyfile_id` is FALSE for it and TRUE for two file-local test helpers — the
in-place term alone hands a bare name to a test.
@brief Build the test-scope ranking fragment.
@return SQL fragment ending in ', ', or ''.
@version 1
"""
if not table_exists(conn, "test_scope"):
return ""
return f"(EXISTS (SELECT 1 FROM test_scope ts WHERE ts.path_rowid = {column})) ASC, "
Activity · 3 steps
Flows
candidate_rows
list[Candidate] clew.query._common.candidate_rows(sqlite3.Connection conn, str name, list[tuple] cands)
The capped, provenance-carrying Candidate list for one ambiguous name.
Called by _dossier_conn, chain_trace, resolve_symbol, source
Tested by
Calls _one_row_per_declaration, qualified_name_of, symbol_provenance
Source · 39 lines
def candidate_rows(conn: sqlite3.Connection, name: str, cands: list[tuple]) -> list[Candidate]:
"""FOUR surfaces built this list by hand with the same comprehension —
`resolve_symbol`, `dossier`, `source` and `chain_trace` — which is exactly the
duplication that let gh#26's identity rule drift into two copies. Adding a
provenance field would have meant editing four call sites and getting it wrong
in one, so the comprehension moved here first. gh#37 then added a second field
and this is why that was a one-line change.
`name` is a REQUIRED argument rather than a defaulted one even though it is
recoverable from nothing else here, because `qualified` is the field a consumer
passes back and a silently-empty one would leave `candidates` advisory again —
exactly gh#37's defect. A default would have let a call site forget it and still
typecheck.
Deliberately does NOT check `is_overloaded`; the caller decides whether an
ambiguity exists, because `chain_trace` and `dossier` gate it differently.
@brief Build the capped overload-candidate list.
@return Candidate rows with provenance and identity.
@version 4
"""
from .models import (
Candidate,
)
return [
Candidate(
rowid=c[0],
signature=c[1],
file=c[2],
line_start=c[3],
has_body=c[4],
provenance=symbol_provenance(conn, c[0]),
qualified=qualified_name_of(name, c[1]),
)
for c in _one_row_per_declaration(cands)[:MAX_CANDIDATES]
]
Activity · 2 steps
Requirements
REQ-DDB-QUERY-003 REQ-DDB-QUERY-010
Flows
connect
Iterator[sqlite3.Connection] clew.query._common.connect(DbSource db)
Yield an open sqlite connection; close it only if we opened it.
Called by _distinct_identities, _file_licences, _flow_problems, _identity_chain, _known_requirements, _mutation_problems, _rank_enum_over_mirror, _signatures, _split_qualified, _test_flows, all_req_edges, api_pages 51 more
build_graph, call_sequence, callees, callers, chain_trace, derive_flow, directory_rollup, doc_scope, dossier, dossiers, ears_notes, entry_point_flows, function_dossier, function_dossiers, graph_stats, has_file_docs, has_prose_corpus, index_scope, indexed_extensions, kconfig_space, list_files, lock_nestings, lock_roster, locks_held_when, lookup_class, macro_definitions, name_ambiguity, node_references, overridden_by, overrides_of, recovery_hint, req_trace, requirement_evidence, resolve_subject, resolve_symbol, runs_under_lock, search_counted, search_prose_graded, sections_in, source, symbol_pages, test_pages, tests_index, thread_of, thread_roster, token_hit_counts, unresolved_kinds, unsearched_corpora, web_data, web_page, write_quick_views
Tested by
Calls none
Source · 18 lines
def connect(db: DbSource) -> Iterator[sqlite3.Connection]:
"""Normalize a `Path | str | sqlite3.Connection` into an open
connection. A caller-supplied Connection is yielded as-is (never
closed here); a path is opened read-only-ish and closed on exit.
@brief Connection normalizer for every query entry point.
@version 2
"""
if isinstance(db, sqlite3.Connection):
yield db
return
conn = sqlite3.connect(str(db))
try:
yield conn
finally:
conn.close()
Activity · 6 steps
Requirements
Flows
decided_default
tuple[str, str] | None clew.query._common.decided_default(list[tuple[str, str, int, str]] rows)
The default state one macro's config rows decide, with the site that decides it.
Source · 26 lines
def decided_default(rows: list[tuple[str, str, int, str]]) -> tuple[str, str] | None:
"""ONE RULE, TWO READERS (2.0.0, T5 served). The query layer (`kconfig._with_defaults`, what a
dossier says) and the build (`macro_refs`, which same-name definition a reference credits)
decided the same question differently: the query let the shipped header settle a
disagreement, the build required unanimity, so a dossier said MBEDTLS_PLATFORM_MEMORY is off
while both `mbedtls_calloc` definitions stayed credited. And the query kept the LAST row
whenever two declared or two shipped rows disagreed.
TIERS, MOST AUTHORITATIVE FIRST: rows from a DECLARED header (the operator named the build's
header); else rows from a SHIPPED one (`is_shipped_config`); else every row. The first
non-empty tier answers, and only when it is unanimous. Disagreement inside the deciding tier
is undecided, never the last row read.
@brief Decide a macro's default.
@return (state, site) or None.
"""
declared = [r for r in rows if r[3] == CONFIG_ORIGIN_DECLARED]
shipped = [r for r in rows if is_shipped_config(r[1])]
tier = declared or shipped or rows
states = {r[0] for r in tier}
if len(states) != 1:
return None
state, path, line, _origin = sorted(tier, key=lambda r: (r[1], r[2]))[0]
return state, f"{path}:{line}"
Activity · 8 steps
Requirements
Flows
documented_first
str clew.query._common.documented_first(sqlite3.Connection conn, str alias)
The ORDER BY fragment that makes doxygen's own row win a name collapse.
Source · 27 lines
def documented_first(conn: sqlite3.Connection, alias: str) -> str:
"""WHY A COLLAPSE MUST PREFER DOCUMENTATION. `search` collapses every
same-named row to ONE, ordered definition-row-first. A parser-recovered
row IS a definition row, so without this fragment it would outrank doxygen's
documented header declaration for the same function — and mbedtls is full of
exactly that shape: a public function documented in an indexed header and
defined inside an unsatisfied `#if`. The recovered row would win the collapse
and the brief would VANISH from a surface that used to carry it.
That is a documentation REGRESSION caused by a change whose whole purpose is to
add information, which makes it the failure mode worth naming: preferring the
documented row keeps every pre-existing row byte-identical and lets recovery add
only nodes for names doxygen did not know at all.
Returns '' on an index that predates the column, so the caller's ORDER BY is
unchanged rather than referencing a column that is not there.
@brief ORDER BY fragment preferring doxygen-sourced rows.
@return A comparison expression, or '' when provenance is not recorded.
@version 3
"""
if not records_provenance(conn):
return ""
## A parse-built JS/TS row read its JSDoc, so it counts as documented here too.
return f"({alias}.{SYMBOL_SOURCE_COLUMN} != '{SYMBOL_SOURCE_AST}') DESC, "
Activity · 3 steps
Requirements
Flows
extract_version
str clew.query._common.extract_version(str|None detail)
Extract the version value doxygen folded into detaileddescription.
Called by _enrich_one, _enum_subject, _identity, _sibling_prose, _variable_subject
Tested by
Calls none
Source · 14 lines
def extract_version(detail: str | None) -> str:
"""The words "at-version" are deliberately NOT written as a bare tag anywhere in
this block. This function's job is to parse that tag, so naming it literally put
three of them in one comment — doxygen would read each as a tag, and the guard
correctly reported a duplicate. A doc comment about a tag must not contain the
tag.
@brief Pull the <simplesect kind="version"> value, or '' when absent.
@version 2
"""
m = re.search(r'<simplesect kind="version"><para>\s*([^\s<]+)', detail or "")
return m.group(1) if m else ""
Activity · 2 steps
Requirements
function_candidates
list[tuple[int, str, str, int | None, bool]] clew.query._common.function_candidates(sqlite3.Connection conn, str name, str|None qualified=None)
Version 9: a bodiless row in its own file reports its declaration line, not bodystart = -1 .
Called by _ambiguity_counts, _direct_call_edges, _dossier_conn, _entry_rowids, _is_function, chain_trace, identity_rowids, resolve_rowid, resolve_symbol, source
Tested by
Source · 57 lines
def function_candidates(
conn: sqlite3.Connection, name: str, qualified: str | None = None
) -> list[tuple[int, str, str, int | None, bool]]:
"""Return every `kind='function'` memberdef row for a name, definition
rows first (a row that carries a body), each carrying the doxygen
`definition` signature that distinguishes overloads a bare name cannot.
This is the raw material for both `resolve_rowid` (which takes the first)
and the ambiguity signal a consumer surfaces.
THE `name` ARGUMENT STAYS BARE (gh#37). The SQL matches `memberdef.name`, and
that is the only column holding the unqualified spelling — a caller who
passed `Harvester.harvest` here would match NOTHING, which is precisely the
trap gh#37 recorded. Selection among the rows is `qualified`'s job, applied in
Python against `qualified_name_of`, so a qualified spelling never has to be
matched against `definition` with `LIKE`. That was the alternative and it is
the one gh#37 forbids: whole-signature comparison was measured to tear 122
entropic decl/def pairs in half.
Filtering AFTER the fetch rather than in SQL, deliberately. `qualified_name_of`
is a token scan over `definition`, not an expression SQLite can evaluate, and
the row set for one bare name is small (11 for the worst case on this repo's
own index, 37 on entropic) — so this costs nothing measurable and keeps ONE
identity rule in ONE place instead of a second, SQL-shaped copy of it.
@brief List same-named function rows, definition-preferring, with signatures.
@version 8
"""
if not table_exists(conn, "memberdef"):
return []
## ONE LOCATION, FROM ONE PLACE. The path is the DECLARING file (`file_id`), so the line has
## to be a line OF THAT FILE. It used to be `bodystart` — a line of the DEFINING file — which
## for a header declaration pairs `module.h` with a line of `module.c`: a colleague's valkey
## reply listed `src/module.h:9296` for a 252-line header. A definition row keeps
## `bodystart` (its declaring and defining files are the same file); a declaration row reports
## where it is declared. A `memberdef` without the `line` column — hand-built fixtures, never
## doxygen's own schema — keeps the old reading rather than raising.
## A BODILESS ROW IN ITS OWN FILE (1.3.0) reports its line too: a parse-built signature is
## written with `bodystart = -1`, which surfaced as `line_start: -1` on every TS candidate list.
has_line = any(column[1] == "line" for column in conn.execute("PRAGMA table_info(memberdef)"))
line_expr = (
"CASE WHEN m.file_id = m.bodyfile_id AND m.bodystart > 0 THEN m.bodystart ELSE m.line END"
if has_line
else "m.bodystart"
)
rows = conn.execute(
"SELECT m.rowid, COALESCE(m.definition, m.name), COALESCE(p.name,''), "
f"{line_expr}, (COALESCE(m.bodyfile_id, 0) > 0 AND COALESCE(m.bodystart, 0) > 0) AS has_body "
"FROM memberdef m LEFT JOIN path p ON p.rowid = m.file_id "
"WHERE m.name=? AND m.kind='function' "
f"ORDER BY {_test_scope_term(conn, 'm.file_id')}"
"(m.file_id = m.bodyfile_id) DESC, has_body DESC, m.rowid",
(name,),
).fetchall()
cands = [(r[0], r[1], r[2], r[3], bool(r[4])) for r in rows]
return cands if qualified is None else matching_identity(name, cands, qualified)
Activity · 7 steps
Requirements
REQ-DDB-QUERY-003 REQ-DDB-QUERY-010
Flows
has_columns
bool clew.query._common.has_columns(sqlite3.Connection conn, str table, *str cols)
True when a table exists AND carries every named column.
Called by _declaration_sites, _declaring_enum, _direct_call_edges, _documentation_mentions, _enum_row, _enumerators_of_enum, _expansion_sql, _file_members, _gate_columns, _key_r1_projection, _members, _one_file_clause 20 more
_records_external, _req_attributes, _roster_sql, _spawn_attribution, _thread_columns, _variable_rows, _was_harvested, directory_rollup, file_subject, gate_symbol_rows, gates_covering, generation_rule, line_column, list_files, macro_definitions_conn, member_doc_rows, records_provenance, test_name_sql, thread_roster, undocumented_path_rows
Calls table_exists
Source · 21 lines
def has_columns(conn: sqlite3.Connection, table: str, *cols: str) -> bool:
"""`table_exists` is not enough once a schema GROWS a column. A database
built by an older clew has the table but not the later columns, and
selecting one raises a raw `OperationalError` — verified live on a
build_version-2 target whose `shared_key_edges` has 7 columns, where FIVE
tier-1 tools died on `no such column: s.dispatch_mode` rather than degrading.
That is the same graceful-degradation contract `table_exists` already gives
a MISSING table, extended one level down to a missing column.
`pragma_table_info` is the table-valued form, so the table name is BOUND
rather than interpolated into the statement text.
@brief Guard a query against a column a stale database predates.
@version 2
"""
if not table_exists(conn, table):
return False
present = {r[0] for r in conn.execute("SELECT name FROM pragma_table_info(?)", (table,))}
return set(cols) <= present
Activity · 4 steps
Requirements
Flows
identity_rowids
list[int] clew.query._common.identity_rowids(sqlite3.Connection conn, str name, str|None qualified=None)
Every memberdef rowid belonging to the SAME function a name resolves to.
Called by _body_of, _direct_call_edges, _dossier_conn, _entry_rowids, _flow_problems, _identity_walk, _mutation_problems, _override_refs, _sibling_prose, _signatures, _split_qualified, dossier 1 more
walk
Tested by 6 tests
test_a_callee_row_publishes_the_short_form_and_the_selector_follows_it, test_a_selector_in_the_other_languages_separator_still_selects, test_decl_def_duality_keeps_its_edges, test_decl_def_duality_survives_and_the_two_rows_stay_one_function, test_genuine_recursion_survives_the_identity_split, test_the_published_identity_is_accepted_by_the_selector
Calls function_candidates, qualified_name_of, resolve_selector
Source · 46 lines
def identity_rowids(conn: sqlite3.Connection, name: str, qualified: str | None = None) -> list[int]:
"""The seam gh#26 was missing. `resolve_rowid` picks ONE canonical rowid and
`rowids_for_name` returns EVERY rowid the name denotes — including unrelated
functions that merely share it. Neither is right for attributing edges: the
first loses a function's declaration rows (doxygen emits one memberdef per
documented header declaration, and edges attach to whichever row the layer
saw), the second unions three unrelated `_classify` helpers into one node.
This returns the middle thing: the rowids of the ONE function the name
canonically resolves to, keyed by `qualified_name_of`. So a C++ function's
decl/def pair stays together while `pkg.guidance._classify` and
`pkg.scope._classify` become separate identities.
Deliberately does NOT separate genuine overloads — `Owner::run(int)` and
`Owner::run(double)` share a qualified name and remain one identity. Keying
on `argsstring` too would split them, but default arguments legitimately
differ between a declaration and its definition, which reintroduces exactly
the over-split this key was chosen to avoid. Overloads stay served by
`candidates`; see the module note in `symbols._direct_call_edges`.
`qualified` REPLACES THE GUESS RATHER THAN FILTERING AFTER IT (gh#37). Without
it the target identity is read off `cands[0]` — the definition-preferring row —
which is a reasonable default and an arbitrary one when several identities share
the bare name. Supplying it names the identity outright, so the union this
returns is the one the caller picked instead of the one the ordering happened to
put first. An unmatched selector yields `[]`, and every caller already treats an
empty rowid list as "not found".
@brief Resolve a name to the rowids of one function (decl + def), not one row.
@return Ascending rowids of the canonical identity; empty when the name is unknown.
@version 2
"""
cands = function_candidates(conn, name)
if not cands:
return []
if qualified is not None:
## A FULL NAME OR A UNIQUE SUFFIX OF ONE (1.3.7): neighbour rows publish the shortest
## unique suffix, and following one must reach the same identity the full name would.
target = resolve_selector({qualified_name_of(name, c[1]) for c in cands}, qualified)
if target is None:
return []
else:
target = qualified_name_of(name, cands[0][1])
return sorted(r for r, sig, _f, _ls, _hb in cands if qualified_name_of(name, sig) == target)
Activity · 10 steps
Requirements
REQ-DDB-QUERY-003 REQ-DDB-QUERY-010
Flows
is_overloaded
bool clew.query._common.is_overloaded(list[tuple[int, str, str, int|None, bool]] candidates)
True when a name maps to more than one DISTINCT function signature.
Source · 13 lines
def is_overloaded(candidates: list[tuple[int, str, str, int | None, bool]]) -> bool:
"""Distinguish a genuine overload from decl/def duality. A single function
contributes multiple rows (one definition + one per documented header
declaration) that all share ONE `definition` signature; those must NOT read
as ambiguous. More than one DISTINCT signature means the bare name really
does select among different functions.
@brief Report whether same-named rows are a genuine overload.
@version 1
"""
return len({sig for _, sig, _, _, _ in candidates}) > 1
Activity · 1 steps
Requirements
Flows
is_shipped_config
bool clew.query._common.is_shipped_config(str path)
Whether a config-header path is the repository's own shipped default.
Source · 14 lines
def is_shipped_config(path: str) -> bool:
"""A HEURISTIC OVER PATHS, and it is reported as `shipped` rather than applied silently, so a
reader can disagree with it. `include/mbedtls/mbedtls_config.h` is shipped;
`configs/ext/tfm_mbedcrypto_config_profile_medium.h` and
`tests/configs/user-config-malloc-0-null.h` are not.
@brief Is this the shipped config header.
@return True when shipped.
@version 1
"""
lower = path.lower()
return not any(part in lower for part in _NOT_SHIPPED_DIRS)
Activity · 2 steps
Requirements
Flows
liveness_of
str clew.query._common.liveness_of(sqlite3.Connection conn, str name)
Liveness status for one function name ('' when unknown/absent).
Source · 19 lines
def liveness_of(conn: sqlite3.Connection, name: str) -> str:
"""Return 'live'/'orphan' for a function (definition-preferring rowid),
or '' when there is no symbol_liveness row (or the table is absent).
@brief Look up one function's symbol-liveness status.
@version 1
"""
if not table_exists(conn, "symbol_liveness"):
return ""
rowid = resolve_rowid(conn, name)
if rowid is None:
return ""
row = conn.execute(
"SELECT status FROM symbol_liveness WHERE memberdef_rowid=?",
(rowid,),
).fetchone()
return row[0] if row else ""
Activity · 7 steps
Requirements
matching_identity
list[tuple[int, str, str, int | None, bool]] clew.query._common.matching_identity(str name, list[tuple[int, str, str, int|None, bool]] cands, str qualified)
Keep only the candidate rows whose IDENTITY is the named qualified one.
Called by function_candidates
Tested by
Source · 45 lines
def matching_identity(
name: str, cands: list[tuple[int, str, str, int | None, bool]], qualified: str
) -> list[tuple[int, str, str, int | None, bool]]:
"""THE DISAMBIGUATOR gh#37 IS ABOUT, and the reason it is a QUALIFIED NAME
rather than the `file` substring `Candidate` used to promise or the `rowid` it
already carried.
Against `rowid`: a rowid is a sqlite row number that a rebuild reassigns, so a
model that read `candidates`, reasoned, and re-queried after an intervening
`build_or_refresh` would silently address a DIFFERENT function. It is also the
one field on the payload that means nothing outside this database.
Against a `file` substring: it cannot separate two same-named identities in ONE
file, which is the ordinary Python shape (two classes in a module, a method and
a module-level helper) and the exact case gh#26 was filed about. It would have
resolved gh#37's motivating example and failed the general one.
For the qualified name: it is ALREADY the identity key. `qualified_name_of` is
what gh#26 chose to decide which memberdef rows are the same function, so
selecting on it means a disambiguated call gets the same identity the edge
attribution and thread membership already use — one rule, three surfaces, no
second definition of "same function" to drift. It survives a rebuild, and it is
published verbatim on every `Candidate`, so a consumer constructs it by copying
a string rather than by parsing a signature.
WHAT IT DELIBERATELY CANNOT SELECT: genuine overloads. `Owner::run(int)` and
`Owner::run(double)` share a qualified name and `identity_rowids` unions them by
design — keying on `argsstring` too would split a declaration from its
definition whenever a default argument differs. So this selects an IDENTITY, not
a signature, and a caller wanting one arm of a same-class overload still has
only `candidates` to read. That is a real boundary and it is stated on the tools.
RETURNS EMPTY ON NO MATCH, never falls back to every row. A disambiguator that
silently degrades to the bare-name union would be worse than none: the caller
would believe it had narrowed the answer. A typo must read as "no such
identity", which the accessors surface as their ordinary not-found envelope.
@brief Select the candidate rows belonging to one qualified identity.
@return The matching subset, possibly empty.
@version 1
"""
target = resolve_selector({qualified_name_of(name, c[1]) for c in cands}, qualified)
return [c for c in cands if target is not None and qualified_name_of(name, c[1]) == target]
Activity · 2 steps
Requirements
Flows
meta_section
dict[str, str] clew.query._common.meta_section(str|Path db, str prefix)
One namespaced build_meta section, read without its key prefix.
Called by _derived_pending, _meta_section, _operator_excludes, _recorded_entry_patterns, _recorded_predefined, _replay_manifest_statements, file_counts, stated_declaration
Tested by
Calls none
Source · 38 lines
def meta_section(db: str | Path, prefix: str) -> dict[str, str]:
"""ONE reader for every `build_meta` section, and it lives HERE rather than in
`mcp_server/state.py` — where it was born — because gh#7 needed a second caller.
Its own docstring already argued the point: there had been two byte-identical
copies and a third was about to be pasted in. A fourth in the query layer would
have made that four.
NOT routed through `connect`, deliberately. `connect` calls
`sqlite3.connect(str(db))`, which CREATES an empty file for a path that does not
exist; this reader is called on databases that may be absent, mid-build or
tableless, and manufacturing one would be a side effect in a status path. The
read-only URI plus a fail-soft `{}` is the contract `status` has always had, and
an absent key honestly reads as "not recorded" — the true answer on an index
built before the section existed.
The prefix is INTERPOLATED into a LIKE pattern rather than bound, because SQLite
cannot parameterize inside a literal it has to concatenate; it is a
module-controlled constant at every call site, never caller input.
@brief Read one namespaced build_meta section.
@return Mapping without the key prefix, or {}.
@version 1
"""
try:
conn = sqlite3.connect(f"file:{db}?mode=ro", uri=True)
except sqlite3.Error:
return {}
try:
rows = conn.execute(
"SELECT key, value FROM build_meta WHERE key LIKE ?", (f"{prefix}.%",)
).fetchall()
except sqlite3.Error:
return {}
finally:
conn.close()
return {key.split(".", 1)[1]: value for key, value in rows}
Activity · 9 steps
Requirements
Flows
name_of
str | None clew.query._common.name_of(sqlite3.Connection conn, int rowid)
rowid→function name (DISTINCT-by-name is implicit: rowid is unique).
Source · 9 lines
def name_of(conn: sqlite3.Connection, rowid: int) -> str | None:
"""@brief Return the function name for a memberdef rowid, or None."""
row = conn.execute(
"SELECT name FROM memberdef WHERE rowid=?",
(rowid,),
).fetchone()
return row[0] if row else None
Activity · 2 steps
Requirements
Flows
qualified_name_of
str clew.query._common.qualified_name_of(str name, str|None definition)
The QUALIFIED name a bare name + doxygen definition denotes.
Called by _direct_call_edges, _endpoint_identities, _entry_rowids, _identity_call_hops, _identity_index, _identity_walk, _implementors_by_identity, _macros_by_identity, _qualified_forms, _qualified_suffix_matches, _selector_from_signature, candidate_rows
Tested by
Calls none
Source · 37 lines
def qualified_name_of(name: str, definition: str | None) -> str:
"""The IDENTITY key for a function (gh#26). doxygen puts the qualified name
in the LAST whitespace-separated token of `definition` and the argument list
in a separate `argsstring` column, so scanning tokens from the right for one
whose tail is `name` at a `::` or `.` boundary yields
`pkg.guidance._classify` or `LinkOwner::rx_loop` without parsing C++.
Chosen over comparing the WHOLE `definition` string, which was measured to
over-split real decl/def pairs on both public C/C++ targets: a declaration
and its definition can differ by a macro attribute
(`ATTRIBUTE_TARGET_POPCNT void fuzzer::TracePC::HandleCmp` vs
`void fuzzer::TracePC::HandleCmp`) or an `inline`/`static` qualifier, which
splits ONE function into two identities. Whole-signature equality yielded
2,819 identities on entropic where the qualified name yields 2,694, and
every one of the 122 differing names was a single function torn in half.
This is the same failure the lock layer already suffered when a pointer
sigil leaked into its scope string, so the key deliberately excludes the
return type — the part that carries the sigil.
Falls back to the bare `name` rather than inventing an identity: an operator,
or a signature doxygen mis-parsed from a macro (one real entropic row reads
`if((Val|Vals[Idx])< TwoIn32) fuzzer else fuzzer::TPC HandleCmp`), degrades
to today's name-keyed behaviour instead of fabricating a distinct function.
@brief Extract a function's qualified-name identity from its signature.
@return Qualified name, else the bare name.
@version 1
"""
for token in reversed((definition or "").split()):
if token == name:
return token
tail = len(token) - len(name) - 1
if tail >= 0 and token.endswith(name) and token[tail] in ":.":
return token
return name
Activity · 7 steps
Requirements
Flows
records_provenance
bool clew.query._common.records_provenance(sqlite3.Connection conn)
Whether this index records where its memberdef rows came from.
Source · 12 lines
def records_provenance(conn: sqlite3.Connection) -> bool:
"""False for an index built before build version 19, where the column does not
exist AND every row is doxygen's by construction — so the honest answer to
"which rows are parsed?" on such a database is "none", not an error.
@brief Report whether symbol provenance is recorded.
@return True when the column is present.
@version 1
"""
return has_columns(conn, "memberdef", SYMBOL_SOURCE_COLUMN)
Activity · 1 steps
Requirements
Flows
resolve_rowid
int | None clew.query._common.resolve_rowid(sqlite3.Connection conn, str name, str|None qualified=None)
Definition-preferring function name→rowid (decl/def duality).
Called by _dataflow_edges, _expand_neighbor, _req_implementers, key_edges, liveness_of
Tested by
Source · 31 lines
def resolve_rowid(conn: sqlite3.Connection, name: str, qualified: str | None = None) -> int | None:
"""Resolve a function NAME to its canonical memberdef rowid, preferring
the row that CARRIES A BODY over a pure declaration,
then the lowest rowid. Ported from the retired walkthrough dbview helper.
The bare-name path keeps its own SQL rather than routing through
`function_candidates`, deliberately: it is the hot path (every dataflow
neighbour calls it once) and `LIMIT 1` in SQLite beats materializing every
same-named row in Python. The two orderings are the same key — body rows
first, then lowest rowid — so the disambiguated branch names the same row the
bare branch would have, for the subset it keeps.
@brief Resolve a function name to its definition-preferring rowid.
@version 8
"""
if not table_exists(conn, "memberdef"):
return None
if qualified is not None:
cands = function_candidates(conn, name, qualified)
return cands[0][0] if cands else None
row = conn.execute(
"SELECT rowid FROM memberdef WHERE name=? AND kind='function' "
f"ORDER BY {_test_scope_term(conn, 'file_id')}"
"(file_id = bodyfile_id) DESC, "
"(COALESCE(bodyfile_id, 0) > 0 AND COALESCE(bodystart, 0) > 0) DESC, "
"rowid LIMIT 1",
(name,),
).fetchone()
return row[0] if row else None
Activity · 7 steps
Requirements
REQ-DDB-QUERY-003 REQ-DDB-QUERY-010
Flows
resolve_selector
str | None clew.query._common.resolve_selector(set[str] qualifieds, str selector)
The full qualified name a selector names among a bare name's identities.
Called by _select_variable_rows, identity_rowids, matching_identity
Calls _ends_at_boundary
Source · 18 lines
def resolve_selector(qualifieds: set[str], selector: str) -> str | None:
"""EXACT FIRST, then a UNIQUE boundary-aligned suffix — the form `short_qualified` publishes.
Several matches select NOTHING, never the first: a selector that silently picked one of two
identities would be the ambiguity it exists to remove.
@brief Resolve a qualified selector.
@return Full qualified name or None.
@version 2
"""
if selector in qualifieds:
return selector
## EITHER SEPARATOR (1.3.10): `::` and `.` name the same nesting, and an agent writing one
## language's spelling for another's identity (`a::b::run` for `a.b.run`) meant that identity.
spellings = {selector, selector.replace("::", "."), selector.replace(".", "::")}
matches = {q for q in qualifieds for sp in spellings if q == sp or _ends_at_boundary(q, sp)}
return next(iter(matches)) if len(matches) == 1 else None
Activity · 5 steps
Requirements
Flows
rowids_for_name
list[int] clew.query._common.rowids_for_name(sqlite3.Connection conn, str name)
EVERY memberdef rowid a name denotes, qualified or bare.
Called by locks_held_when, sections_in, thread_of
Calls _qualified_match, table_exists
Source · 40 lines
def rowids_for_name(conn: sqlite3.Connection, name: str) -> list[int]:
"""Resolve a name to ALL the functions it denotes, not just one.
`resolve_rowid` deliberately collapses to a single canonical rowid, which
is right for "show me this function" but wrong for membership questions:
`thread_membership` is keyed per rowid, so asking one rowid answers for one
function. Two failures followed on real C++ source — `thread_roster` emits QUALIFIED
entry names (`LinkOwner::rx_loop`) that never match the unqualified
`memberdef.name` at all, so 11 of 12 threads were unresolvable; and a bare
ambiguous name (`run`, `tick_loop`) silently picked ONE of several real
functions, dropping the rest.
A qualified name is matched against the doxygen `definition` signature at
identifier boundaries; a bare name matches `memberdef.name` directly.
Deliberately NO definition-preference, unlike `resolve_rowid`. Measured on
in practice: the rows carrying thread membership are usually DECLARATION rows,
because a header-declared method has `file_id != bodyfile_id`. For
`rx_loop` the two real thread entries (LinkOwner, SensorRuntime) are both
declarations, while the sole definition row is an unrelated
anonymous-namespace helper with no membership — so preferring definitions
returned exactly the wrong rowid and answered "no threads". Filtering is
the qualified-name check's job; a union question wants every candidate.
@brief Resolve a (possibly qualified) name to every rowid it denotes.
@return Ascending list of rowids; empty when the name is unknown.
@version 4
"""
if not table_exists(conn, "memberdef"):
return []
tail = name.rsplit("::", 1)[-1]
rows = conn.execute(
"SELECT rowid, COALESCE(definition,'') FROM memberdef WHERE name=? AND kind='function'",
(tail,),
).fetchall()
if "::" in name:
rows = [r for r in rows if _qualified_match(r[1], name)]
return sorted(r[0] for r in rows)
Activity · 7 steps
Requirements
short_qualified
str clew.query._common.short_qualified(str full, set[str] others)
The shortest separator-aligned suffix of a qualified name no other identity ends with.
Source · 22 lines
def short_qualified(full: str, others: set[str]) -> str:
"""1.3.7. `qualified` was 29% of mattermost's neighbour-row bytes, because a TypeScript identity
spells its module path in full and the row's `file` spells it again. Any suffix unique among
the identities that share the bare name selects exactly one of them — `resolve_selector`
accepts it — so the row publishes the shortest. ALIGNED TO `.` OR `::`, never a string suffix:
`Monitor.run` must not stand for `HealthMonitor.run`. AT LEAST ONE QUALIFIER, because the bare
name is what the row's `name` already says.
@brief Shorten a qualified name to its shortest unique suffix.
@return The suffix.
@version 1
"""
tokens = re.split(r"(::|\.)", full)
parts, seps = tokens[0::2], tokens[1::2]
for keep in range(2, len(parts)):
start = len(parts) - keep
suffix = parts[start] + "".join(s + p for s, p in zip(seps[start:], parts[start + 1 :]))
if not any(_ends_at_boundary(other, suffix) for other in others if other != full):
return suffix
return full
Activity · 8 steps
Requirements
start_line
int clew.query._common.start_line(Any line, Any bodystart, Any file_id, Any bodyfile_id)
Where a function starts for a reader: its declaration line, when that leads its body.
Source · 16 lines
def start_line(line: Any, bodystart: Any, file_id: Any, bodyfile_id: Any) -> int:
"""2.1 (roadmap; found with W-11 in 2.0.0): doxygen's `bodystart` for a Python function with a
multi-line signature is past the `def` — `derive_flow` declares at 127, its body starts at 142 —
so a dossier pointed at the docstring and its excerpt began mid-signature. ONE FILE, DECLARATION
FIRST: the declaration line leads. A member defined out of line keeps its body's line, since its
declaration is in another file.
@brief Start line.
@return Line.
"""
same_file = not bodyfile_id or bodyfile_id == file_id
if same_file and line and bodystart and 0 < int(line) < int(bodystart):
return int(line)
return int(bodystart or 0)
Activity · 4 steps
Requirements
strip_xml
str clew.query._common.strip_xml(str|None text)
Strip doxygen's XML-ish markup from a description column.
Called by _briefs, _enrich_one, _enum_subject, _identity, _macro_def, _memberdef_candidates, _members, _sibling_prose, _variable_subject, class_rows, doc_text, lookup_class 1 more
search_prose_graded
Tested by
Calls none
Source · 17 lines
def strip_xml(text: str | None) -> str:
"""OWNER Q/A 2026-11-20 (2.0.0): served text keeps code text doxygen stored verbatim. A regex
strip of `<…>` served `(n_tokens < 2) … (llama_decode error)` as "(n_tokens" and
`std::atomic<bool>` as "std::atomic". Only doxygen's own elements are markup — the element set
`well_formed` uses, the wiki's rule since 314e4696.
ONE SPELLING (owner Q/A 2026-11-23, 2.0.1): doxygen stores a character verbatim in some
descriptions and as an entity in others, so entities are DECODED — after the elements are
removed, so an entity that spells markup (`<para>`) stays text. Every caller treats the
result as text: the wiki escapes it where it renders.
@brief Collapse doxygen description markup to plain whitespace-run text.
@return Text.
"""
return re.sub(r"\s+", " ", html.unescape(_DOX_TAG.sub(" ", text or ""))).strip()
Activity · 1 steps
Requirements
Flows
symbol_provenance
str | None clew.query._common.symbol_provenance(sqlite3.Connection conn, int rowid)
The provenance a symbol row should REPORT, or None when it says nothing.
Called by _dossier_conn, _enum_subject, _macro_def, _memberdef_candidates, _variable_subject, candidate_rows, resolve_symbol, source
Calls records_provenance
Source · 32 lines
def symbol_provenance(conn: sqlite3.Connection, rowid: int) -> str | None:
"""RETURNS None FOR A DOXYGEN ROW, deliberately, and this is the one design
decision on this surface worth arguing with.
`wire._absent` elides an empty field from every ROW, and the elision doctrine
there is "a field is present only when it says something". Every symbol in a
healthy index is doxygen's, so emitting a `'doxygen'` provenance on all of them
would add ~24 B to a measured-135 B call row — an 18% inflation of the exact
payload that module was written to shrink — to restate the norm. So the field
is present exactly when the answer is surprising.
The consequence a consumer must know, and which the tool descriptions state:
an ABSENT provenance means doxygen documented this symbol. A provenance of
'ast' means the tree-sitter parser recovered it from the source text because
doxygen never emitted it, and it therefore has NO brief, NO documented
parameters and NO `@req` tags — a preprocessor that skipped the code skipped
its doc comment too. Reading an absent brief on such a row as "undocumented
function" rather than "unparsed function" is the mistake this field prevents.
@brief The provenance worth reporting for one symbol row.
@return 'ast', or None when there is nothing to say.
@version 2
"""
if not records_provenance(conn):
return None
row = conn.execute(
f"SELECT {SYMBOL_SOURCE_COLUMN} FROM memberdef WHERE rowid=?",
(rowid,),
).fetchone()
return SYMBOL_SOURCE_AST if row is not None and row[0] == SYMBOL_SOURCE_AST else None
Activity · 4 steps
Requirements
Flows
table_exists
bool clew.query._common.table_exists(sqlite3.Connection conn, str name)
True when a table exists (partial/mini DBs lack later layers).
Called by __init__, _ambiguity_counts, _build_thread, _call_hops, _calls_something, _class_side_is_only_enum_mirrors, _declared_entry_patterns, _direct_call_edges, _distinct_identities, _documentation_mentions, _edges, _file_calls 96 more
_file_documentation, _file_licences, _file_members, _first_owners, _functions, _gate_layer_state, _gate_symbol_names, _gates, _hierarchy, _identity_call_hops, _implementer_spans, _implementors_by_identity, _include_graph, _indexed_path, _indexed_paths, _is_compound, _is_config, _is_lock, _is_requirement, _is_thread, _key_edge_rows, _key_r1_projection, _layer_present, _linked_tests, _links, _liveness, _macro_params, _memberdef_candidates, _members, _meta, _name_exists, _not_test, _one_token_count, _override_refs, _qualified_forms, _qualified_suffix_matches, _reaching_tests, _recorded_end, _referenced_by, _req_failure_modes, _req_implementers, _req_links, _reqs_and_tests, _reqs_for, _requirement_ids, _scope_provenance, _symbols, _test_definitions, _test_scope_term, _tested_calls, _thread_entries, _threads, _variable_rows, _vendor_calls_in, _with_defaults, all_req_edges, call_edge_counts, class_rows, config_defaults_conn, file_doc_rows, file_license, file_owners, function_candidates, gate_symbol_rows, gates_covering, generates_files, generation_rule, has_columns, has_file_docs, has_prose_corpus, header_classes, is_indexed_file, kconfig_space, layer_states, list_files, liveness_of, lock_roster, lookup_class, member_doc_rows, nestings_on, node_references, req_trace, resolve_rowid, rowids_for_name, runs_under_lock, same_key_sites, search_prose_graded, symbol_pages, termini_for, test_functions, thread_roster, threads_for, undocumented_path_rows, unresolved_inbound_for_rowids, unresolved_kinds, unsearched_corpora
Tested by
Calls none
Source · 11 lines
def table_exists(conn: sqlite3.Connection, name: str) -> bool:
"""@brief Return whether a user table of the given name exists."""
return (
conn.execute(
"SELECT 1 FROM sqlite_master WHERE type='table' AND name=?",
(name,),
).fetchone()
is not None
)
Activity · 1 steps
Requirements
Flows
to_bool
bool | None clew.query._common.to_bool(object value)
Coerce a 0/1/None integer column into a bool|None.
Source · 5 lines
def to_bool(value: object) -> bool | None:
"""@brief None stays None (unknown); else the value's truthiness as bool."""
return None if value is None else bool(value)