dossier.py¶
clew/query/dossier.py
The composite per-function dossier.
_declaration_sites
list[DeclarationSite] clew.query.dossier._declaration_sites(sqlite3.Connection conn, list[int] ids, str body_file)
Where one function identity is declared, outside the file that holds its body.
Source · 24 lines
def _declaration_sites(
conn: sqlite3.Connection, ids: list[int], body_file: str
) -> list[DeclarationSite]:
"""ONE RULE FOR BOTH SHAPES (T2; entropic F1, mbedtls F2). A C++ out-of-line member is ONE row
whose `file_id` (the class header) differs from its `bodyfile_id`; a C function with a header
prototype is TWO rows, the prototype's `file_id` being the header. Either way a declaration
site is a row's declaring file and line where that file is not the body's.
@brief List declaration sites.
@return Sites.
"""
if not ids:
return []
marks = ",".join("?" * len(ids))
## A hand-built fixture's memberdef may lack `line` (doxygen's own schema always has it).
line = "m.line" if has_columns(conn, "memberdef", "line") else "NULL"
rows = conn.execute(
f"SELECT DISTINCT p.name, {line} FROM memberdef m JOIN path p ON p.rowid = m.file_id " # noqa: S608
f"WHERE m.rowid IN ({marks}) AND p.name != ? ORDER BY 1, 2",
(*ids, body_file),
).fetchall()
return [DeclarationSite(file=str(f), line=line) for f, line in rows]
Activity · 6 steps
Requirements
_dossier_conn
Dossier | None clew.query.dossier._dossier_conn(sqlite3.Connection conn, str fn, str|None qualified, Path|str|None repo_root, int max_body_lines)
Assemble one dossier on an ALREADY-OPEN connection.
Called by function_dossier, function_dossiers
Calls _anchored_pick, _body_and_external, _call_edges, _declaration_sites, _identity, _liveness, _macro_collision, _macro_dossier, _reqs_and_tests, candidate_rows, config_defaults_conn, context_conflicts_for_rowids 20 more
context_undecidable_for_rowids, file_license, file_owners, function_candidates, gates_covering, generation_rule, identity_rowids, is_overloaded, key_edges, list, locks_held_for_rowids, macro_definitions_conn, overridden_by, overrides_of, same_key_sites, sections_for_rowids, symbol_provenance, termini_for, threads_for_rowids, unresolved_inbound_for_rowids
Source · 120 lines
def _dossier_conn(
conn: sqlite3.Connection,
fn: str,
qualified: str | None,
repo_root: Path | str | None,
max_body_lines: int,
) -> Dossier | None:
"""SPLIT OUT SO A BATCH SHARES ONE CONNECTION, and for no other reason — the body
below is `dossier`'s former body verbatim, so the single-symbol path is unchanged.
The split is what makes `dossiers` cheap: five symbols used to mean five
`connect()` calls, five sqlite opens and five sets of `table_exists` probes against
the same file. One connection answers all of them.
@brief Build one Dossier against an open connection.
@return The Dossier, or None.
@version 5
"""
macros = macro_definitions_conn(conn, fn)
cands = function_candidates(conn, fn, qualified)
if not cands:
## gh#373. A name that defines a macro and no function used to return
## None — indistinguishable from "not indexed" — while the `#define`,
## its expansion and its file:line were all sitting in `memberdef`.
## Only on a BARE name: an unmatched `qualified` is a request for a
## specific function identity, and answering it with a macro would
## substitute a different symbol for the one that was asked for.
if macros and qualified is None:
## READ ONLY ON THE MACRO PATH, one indexed lookup, and only once the subject is
## already known to be a macro — a function subject has no configured state and
## would pay for the query to learn so.
return _macro_dossier(macros, config_defaults_conn(conn, fn))
return None
rowid = _anchored_pick(conn, cands, repo_root, max_body_lines)
ident = _identity(conn, rowid)
if ident is None:
return None
reqs, tests = _reqs_and_tests(conn, ident["name"])
termini = termini_for(conn, rowid)
ids = identity_rowids(conn, fn, qualified)
body, externals = _body_and_external(conn, rowid, repo_root, max_body_lines)
## Ambiguity is a property of the NAME, so it is measured over every same-named
## row: a narrowed dossier must still disclose that alternatives exist, or a
## consumer cannot tell a disambiguated answer from a unique one.
all_cands = function_candidates(conn, fn) if qualified is not None else cands
overloads = candidate_rows(conn, fn, all_cands) if is_overloaded(all_cands) else []
## The gates covering the DEFINITION line. `ident` carries the file and line doxygen
## recorded, which is the one position every function has — a body excerpt is optional
## (`repo_root` may be None) and a declaration in a header is gated separately from its
## definition, so keying off the body would make the field vanish exactly when a caller
## asked for the cheap payload.
gates, unknown = gates_covering(conn, ident["file"], int(ident["line_start"] or 0))
return Dossier(
name=ident["name"],
rowid=rowid,
signature=ident["signature"],
file=ident["file"],
line_start=ident["line_start"],
line_end=ident["line_end"],
brief=ident["brief"],
detail=ident["detail"],
version=ident["version"],
kind=ident["kind"],
static=ident["static"],
liveness=_liveness(conn, rowid),
provenance=symbol_provenance(conn, rowid),
declared_at=_declaration_sites(conn, ids, ident["file"]),
## T4 (2.0.0; mbedtls F4): `mbedtls_strerror` lives in the generated `error.c`, and a reader
## arriving by the function's name had no route to that fact but asking for the file.
generated_by=generation_rule(conn, ident["file"]),
## 2.0.0 (S2/S3/S5 served): the file's owners and licence, as its file dossier has them.
owners=list(file_owners(conn, ident["file"]) or ()),
license=file_license(conn, ident["file"]),
same_key_sites=same_key_sites(conn, ident["file"], ident["line_start"], ident["line_end"]),
candidates=overloads,
# Membership is per-rowid, and doxygen splits one function across a
# declaration row and a definition row — so asking only the chosen
# rowid reports no thread whenever membership landed on the sibling.
# Union across the decl/def pair of THIS function; a same-named
# function in another module or on another class is excluded.
#
# gh#26: this used to compare whole `definition` signatures inline. It
# is now the SHARED `identity_rowids` helper, for two reasons. DRY —
# the call-edge surface needs the same rule, and two copies of an
# identity rule in one package is the drift condition that produced
# gh#26 in the first place. And correctness — whole-signature
# equality over-splits a single function whose declaration and
# definition differ by a macro attribute or an inline/static
# qualifier, measured at 122 such names on entropic and 13 on
# mbedtls, where the qualified-name key splits none.
threads=threads_for_rowids(conn, ids),
is_terminus=bool(termini),
termini=termini,
requirements=reqs,
covering_tests=tests,
callers=_call_edges(conn, ident["name"], want_callers=True, qualified=qualified),
callees=_call_edges(conn, ident["name"], want_callers=False, qualified=qualified),
writes=key_edges(conn, ident["name"], as_writer=True),
reads=key_edges(conn, ident["name"], as_writer=False),
# gh#8. doxygen's own `reimplements` relation was populated and read by
# nothing outside `dispatch_edges.py`, so a consumer could not ask the
# question C++ polymorphism makes unavoidable -- what runs when this
# dispatches. Both directions, because they answer different questions: what
# this replaces when called through a base pointer, and what may run instead
# of it. Resolved through the IDENTITY like the neighbour lists, so the
# decl/def duality cannot lose the relation and a bare name shared by two
# unrelated functions cannot fabricate one.
overrides=overrides_of(conn, fn, qualified),
overridden_by=overridden_by(conn, fn, qualified),
body=body,
# `sections` is what this function LOCKS; `locks_held` is what is ALREADY
# locked when it runs. Two different questions with two different join
# directions (holder_rowid vs critical_section_calls.callee_rowid), which is
# why they are two fields and not one merged "locks" list.
sections=sections_for_rowids(conn, ids),
locks_held=locks_held_for_rowids(conn, ids),
## gh#47 part 2, keyed on the SAME identity rowids as the two panels above and as
## `threads`, so "this function runs in interrupt context" and "this function blocks
## on an interrupt path" are answers about one identity rather than two.
context_conflicts=context_conflicts_for_rowids(conn, ids),41 more lines, not shown
Activity · 18 steps
Requirements
_macro_dossier
Dossier clew.query.dossier._macro_dossier(list[MacroDef] macros, list|None configs=None)
A dossier whose subject is a MACRO rather than a function.
Source · 57 lines
def _macro_dossier(macros: list[MacroDef], configs: list | None = None) -> Dossier:
"""gh#373. The name defines a macro and no function, so every function-shaped
layer is EMPTY BY CONSTRUCTION rather than unmeasured: there is no body to
excerpt, no liveness row, no thread membership, no caller and no callee, because
all of those filter `kind='function'` and a `#define` is not one. `kind` says
`'macro definition'` so a consumer can see that at a glance instead of reading an
empty `callers` list as a finding.
The FIRST site supplies the identity fields and `macros` carries all of them. The
identity has to come from somewhere — a Dossier has one `file` and one `line` —
and picking the first in file/line order is at least deterministic; the full set
is one field away and the payload does not pretend otherwise. On the motivating
case that ordering puts `library/common.h` first, which is the library-side
definition and the one a reader wants, but that is luck and is not relied on.
`signature` is spelled as the `#define` line rather than as a C declaration,
because a macro has no type and rendering one would be an invention.
`gated_by` HERE DESCRIBES THE FIRST SITE AND NOTHING ELSE, copied off that site rather
than recomputed, so it means exactly what it means on a function dossier: the gates
covering this record's own `file`:`line_start`. The per-site lists on `macros` are the
complete answer — that is where the two branches of a conditional `#define` differ, and
a dossier-level list could describe only one of them. Copying keeps the two consistent
by construction; computing it again from the same position would be a second chance to
disagree.
@brief Build the macro-subject dossier from a name's definition sites.
@version 2
"""
first = macros[0]
return Dossier(
name=first.name,
rowid=first.rowid,
signature=f"#define {first.name}{first.params}",
file=first.file,
line_start=first.line,
line_end=first.line,
## The first site that carries prose wins, exactly as `_sibling_prose` does for
## a decl/def pair: one of several `#define`s may be documented and the others
## bare, and reporting the chosen row's empty brief would call a documented
## macro undocumented.
brief=next((m.brief for m in macros if m.brief), ""),
version="",
kind=MACRO_KIND,
static=False,
liveness="",
macros=macros,
## WHERE THE SHIPPED BUILD STANDS ON IT, which `macros` structurally cannot say: that list
## is doxygen's ACTIVE definitions, and a commented-out default is not a definition.
## Measured: this reply named a TFM profile header as the macro's file and omitted the
## shipped config entirely, so it read as enabled when the default is off.
config_defaults=list(configs or ()),
gated_by=list(first.gated_by),
gates_unplaceable=first.gates_unplaceable,
)
Activity · 2 steps
Requirements
_reqs_and_tests
tuple[list[ReqRef], list[str]] clew.query.dossier._reqs_and_tests(sqlite3.Connection conn, str fn)
Requirements (with titles) + covering tests for one function.
Source · 31 lines
def _reqs_and_tests(conn: sqlite3.Connection, fn: str) -> tuple[list[ReqRef], list[str]]:
"""@brief Build the requirement refs + covering-test names for a function."""
if not table_exists(conn, "req_edges"):
return [], []
reqs = [
ReqRef(req_id=rid, title=title or "")
for rid, title in conn.execute(
"SELECT DISTINCT r.req_id, COALESCE(req.title,'') FROM req_edges r "
"LEFT JOIN requirements req ON req.id = r.req_id "
"JOIN memberdef m ON m.rowid = r.memberdef_rowid "
"WHERE m.name=? ORDER BY r.req_id",
(fn,),
)
]
tests: list[str] = []
if reqs and table_exists(conn, "req_test_edges"):
tests = [
r[0]
for r in conn.execute(
## 2.1 (clew#74): a Catch2 case by its title, not its macro's name.
f"SELECT DISTINCT {test_name_sql(conn)} FROM req_test_edges t "
"JOIN memberdef m ON m.rowid = t.test_memberdef_rowid "
"WHERE t.req_id IN (SELECT DISTINCT r2.req_id FROM req_edges r2 "
"JOIN memberdef m2 ON m2.rowid = r2.memberdef_rowid WHERE m2.name=?) "
"ORDER BY 1",
(fn,),
)
]
return reqs, tests
Activity · 7 steps
Requirements
_sibling_prose
tuple[str, str] clew.query.dossier._sibling_prose(sqlite3.Connection conn, str fn)
The prose a function's DOCUMENTED sibling row carries, if any.
Source · 35 lines
def _sibling_prose(conn: sqlite3.Connection, fn: str) -> tuple[str, str]:
"""THE ONE PLACE gh#11 COULD HAVE LOST DOCUMENTATION, and did in its first cut.
A public function documented in an indexed header and DEFINED inside an
unsatisfied `#if` gives doxygen a declaration row with a brief and no body, and
gives the parser a definition row with a body and no brief. Both are the same
function — `qualified_name_of` keys them identically, so `identity_rowids`
already unions them — but `function_candidates` orders body rows first, so the
dossier's chosen row is the parser's, and reading the brief from that row alone
reported a documented mbedtls function as having no documentation at all.
So the prose is read from the identity's rows rather than from the chosen row:
the FIRST sibling that actually carries a brief or a version wins. The chosen
row still supplies the location, which is correct — the parser is the only thing
that knows where the body is.
This is why a `Dossier` may truthfully carry `provenance: 'ast'` AND a non-empty
`brief`. It is not a contradiction: doxygen documented the declaration, the
parser recovered the definition.
@brief Read the brief/version from a function identity's documented row.
@return (brief, version), each '' when no sibling carries one.
@version 1
"""
for rowid in identity_rowids(conn, fn):
row = conn.execute(
"SELECT briefdescription, detaileddescription FROM memberdef WHERE rowid=?",
(rowid,),
).fetchone()
brief, version = (strip_xml(row[0]), extract_version(row[1])) if row else ("", "")
if brief or version:
return brief, version
return "", ""
Activity · 6 steps
Requirements
function_dossier
Dossier | None clew.query.dossier.function_dossier(DbSource db, str fn, str|None qualified=None, Path|str|None repo_root=None, int max_body_lines=DEFAULT_BODY_LINES)
Assemble the full composite dossier for one function.
Called by _gated_by
Tested by 49 tests
test_a_bare_lookup_is_unchanged_by_the_macro_kind_fix, test_a_bodiless_colliding_identity_discloses_the_macro_collision, test_a_body_read_after_the_file_moved_is_disclosed_not_returned_silently, test_a_clipped_body_says_so_and_still_reports_its_full_extent, test_a_declared_undefined_function_is_disclosed_and_still_described, test_a_defined_function_sharing_a_macro_name_is_not_flagged, test_a_documented_declaration_keeps_its_brief_when_its_body_is_recovered, test_a_dossier_on_an_overridden_function_names_its_implementors, test_a_dossier_without_a_working_tree_keeps_every_index_panel, test_a_gate_says_whether_this_build_satisfied_it, test_a_macro_only_dossier_carries_the_first_sites_gates, test_a_macro_only_name_gets_a_dossier 37 more
test_a_macro_panel_rides_a_function_dossier_of_the_same_name, test_a_non_virtual_function_gets_no_override_fields, test_a_parsed_row_carries_no_brief_and_nothing_pretends_otherwise, test_a_parsed_row_is_distinguishable_from_a_doxygen_row_at_every_surface, test_an_external_callee_is_never_promoted_to_a_call_edge, test_an_index_without_the_relation_degrades_to_empty, test_an_unmatched_selector_is_not_answered_with_a_macro, test_an_unmatched_selector_returns_nothing_rather_than_the_union, test_an_unreadable_working_tree_loses_the_body_and_not_the_dossier, test_build_index_against_a_rust_repo_is_queryable, test_call_lines_are_reported_in_source_order, test_chain_trace_crosses_thread_key_hop, test_dossier_does_not_double_report_dataflow, test_dossier_reader_and_requirements, test_dossier_unambiguous_has_no_candidates, test_dossier_unknown_function_is_none, test_dossier_writer_has_shared_key_and_r1_fields, test_dossier_writer_identity_and_liveness, test_name_accessors_degrade_gracefully_on_table_less_db, test_namesake_fanout_is_no_longer_laundered_into_exact, test_pre_r1_shared_key_schema_degrades_instead_of_raising, test_r2_dossiers_is_positional_and_matches_the_single_symbol_function, test_same_named_module_private_helpers_do_not_share_edges, test_the_body_clip_does_not_hide_calls_below_the_cut, test_the_dossier_carries_the_function_body_it_describes, test_the_dossier_describes_the_row_whose_span_is_actually_the_function, test_the_dossier_names_the_callees_the_index_cannot_resolve, test_the_dossier_returns_detail_prose_and_caps_it_loudly, test_the_exported_dossier_answers_about_a_non_function_subject, test_the_external_panel_reports_signal_and_not_every_token_that_is_unindexed, test_the_lock_panels_agree_with_the_tools_they_replace, test_the_one_shot_panels_key_on_the_resolved_identity_not_the_name, test_the_panels_survive_a_database_that_predates_the_lock_layer, test_the_two_directions_are_not_the_same_question, test_with_no_anchored_sibling_the_mismatch_is_still_disclosed, test_wrapper_content_reaches_the_r1_richness, test_wrappers_match_the_r2_library_exactly
Calls _dossier_conn, connect
Source · 55 lines
def function_dossier(
db: DbSource,
fn: str,
qualified: str | None = None,
repo_root: Path | str | None = None,
max_body_lines: int = DEFAULT_BODY_LINES,
) -> Dossier | None:
"""Build the complete `Dossier` for `fn`: identity, liveness, thread
membership, terminus status, requirements + covering tests, and the
call-graph + shared-key fan-out (both directions). None when `fn`
resolves to no indexed function. When `fn` is a genuine overload the
dossier describes the definition-preferring pick and lists the
alternatives in `candidates` so the pick is never silently arbitrary.
The neighbour lists are scoped to the resolved IDENTITY, not to the bare name
(gh#26): a bare name that denotes several unrelated functions no longer
reports the union of all their edges.
`qualified` SAYS WHICH IDENTITY (gh#37). Without it the pick is the
definition-preferring first row, which is arbitrary among namesakes; with it the
caller names the one it read out of a previous `candidates` list, and the SAME
string scopes the identity, the neighbour lists, the thread membership and both
override directions — because it is the identity key those already use, not a
second notion of sameness bolted alongside. Optional: the bare-name path is
unchanged, and the vast majority of names are unique.
Two halves it does NOT narrow, both pre-existing and both name-scoped in the
layer beneath: `writes`/`reads` (`_key_edge_rows` joins on `memberdef.name`) and
`requirements`/`covering_tests` (`_reqs_and_tests` matches `m.name=?`). Stated
here rather than left to be discovered, since an argument that appears to narrow
a whole payload and narrows most of it is how gh#37 happened in the first place.
ONE CALL, NOT SEVEN. `repo_root` turns on the two panels that read the working
tree — the bounded body excerpt and the unresolvable callee names — and the lock
panels (`sections`, `locks_held`) come from the index unconditionally. The reason
they live here rather than behind four more tools is measured: on one graded
question a model called `dossier` twice and then made fifteen further calls, seven
of them `source`, four of those only to discover which platform primitive a wrapper
forwards to. Every one of those follow-ups asked about the symbol the dossier had
just described.
ALL FOUR ARE KEYED ON THE RESOLVED IDENTITY. The lock panels take
`identity_rowids`, not `rowids_for_name` as the standalone `sections_in` /
`locks_held_when` tools do, and the body takes the chosen ROWID rather than the
name. This is not incidental: gh#26 means one bare name can denote three unrelated
functions in a single module, and a payload that widened its own scope while
reporting one identity would quote the wrong body under the right heading.
@brief Build the composite Dossier for one function.
@version 11
"""
with connect(db) as conn:
return _dossier_conn(conn, fn, qualified, repo_root, max_body_lines)
Activity · 2 steps
Requirements
function_dossiers
list[Dossier | None] clew.query.dossier.function_dossiers(DbSource db, list[str] fns, Path|str|None repo_root=None, int max_body_lines=DEFAULT_BODY_LINES)
Assemble dossiers for several functions over ONE connection.
Source · 34 lines
def function_dossiers(
db: DbSource,
fns: list[str],
repo_root: Path | str | None = None,
max_body_lines: int = DEFAULT_BODY_LINES,
) -> list[Dossier | None]:
"""FOUR TO SIX SEPARATE CALLS, MEASURED. Across three graded mbedtls runs of one
question the model called `dossier` five times each, one symbol per call, and each
call cost a whole model turn — the transcripts differ in almost every other respect
and agree on that. Per-call cost was already below the source arm's; the remaining
gap was entirely VOLUME, and a batch is the one change that removes turns rather
than bytes.
POSITIONAL, INCLUDING THE MISSES. A name that resolves to nothing yields `None` in
its own slot rather than being dropped, so `len(result) == len(fns)` always holds
and the caller can pair a miss with the name that caused it. Dropping misses would
make one unresolvable name silently re-label every dossier after it.
NO `qualified` HERE, deliberately. It selects ONE identity among namesakes, so it
has no meaning against a list — a single `qualified` cannot say which of five
symbols it disambiguates, and a parallel list of them would be a second positional
correspondence to get wrong. A caller that needs disambiguation calls `dossier` for
that one symbol; the MCP layer refuses the combination rather than ignoring it.
Duplicates are NOT removed here. The R2 contract is positional and a caller asking
twice gets two answers; de-duplication is a wire-economy concern and belongs to the
surface that has a byte budget.
@brief Build dossiers for several functions in one pass.
@return One Dossier-or-None per requested name, in request order.
@version 1
"""
with connect(db) as conn:
return [_dossier_conn(conn, fn, None, repo_root, max_body_lines) for fn in fns]1 more lines, not shown