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.

clew/query/symbols.py:2229

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
lines 2242–2242◇ if not table_exists(conn, "call_edges")lines 2243–2243return 0, 0lines 2244–2244candidates = len({sig for _, sig, _, _, _ in function_candidates(conn, fn)})lines 2245–2245◇ if candidates < 2lines 2246–2246return candidates, 0lines 2247–2247endpoint, focal = ("c", "x") if want_callers else ("x", "c")lines 2248–2254shared = 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]lines 2255–2255return candidates, int(shared or 0)

Flows

_build_thread

Thread clew.query.symbols._build_thread(sqlite3.Connection conn, tuple row)

Assemble a Thread dataclass from a threads row (+ member count).

clew/query/symbols.py:956

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
lines 964–964tid, name, kind, entry_rowid, source, conf = row[:6]lines 965–965spawn_path_rowid = row[6] if len(row) > 6 else Nonelines 966–966spawn_line = row[7] if len(row) > 7 else Nonelines 969–969spawn_function = (row[8] if len(row) > 8 else None) or ""lines 970–970entry = name_of(conn, entry_rowid) if entry_rowid is not None else Nonelines 971–978member_count = ( conn.execute( "SELECT COUNT(*) FROM thread_membership WHERE thread_id=?", (tid,), ).fetchone()[0] if table_exists(conn, "thread_membership") else 0 )lines 979–979spawn_file, external_root = _spawn_attribution(conn, spawn_path_rowid)lines 980–995return 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, )

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.

clew/query/symbols.py:1644

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
lines 1656–1664return [ ( -_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) ]

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.

clew/query/symbols.py:295

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
lines 317–317return max(variants, key=lambda v: _variant_rank(*v))

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.

clew/query/symbols.py:1674

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
lines 1689–1702return [ ( -_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) ]

Flows

_doc_brief

str clew.query.symbols._doc_brief(str doc)

Shorten a file's documentation to a brief, at a word boundary.

clew/query/symbols.py:1369

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
lines 1374–1374◇ if len(doc) <= FILE_BRIEF_CHARSlines 1375–1375return doclines 1376–1376head = doc[:FILE_BRIEF_CHARS]lines 1377–1377cut = head.rsplit(" ", 1)[0] if " " in head else headlines 1378–1378return f"{cut} …"

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.

clew/query/symbols.py:1533

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
lines 1544–1544return "COALESCE(m.initializer,'')" if has_columns(conn, "memberdef", "initializer") else "''"

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.

clew/query/symbols.py:1592

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
lines 1616–1616generated = self_declared_paths(conn)lines 1617–1634return [ ( -( _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)] ]

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.

clew/query/symbols.py:599

Show on the map →

Called by _direct_call_edges

Calls qualified_name_of, table_exists

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
lines 624–624◇ if not rows or not table_exists(conn, "reimplements")lines 625–625return {}lines 626–628identity_of = { rowid: (name, qualified_name_of(name, definition)) for name, definition, rowid, *_ in rows }lines 629–629marks = ", ".join("?" for _ in identity_of)lines 630–630found: dict[tuple[str, str], set[str]] = {}lines 631–631◇ for base_rowid, impl_name in conn.execute(lines 637–637found.setdefault(identity_of[base_rowid], set()).add(impl_name)lines 638–638return {identity: tuple(sorted(names)) for identity, names in found.items()}

Requirements

REQ-DDB-QUERY-009

_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.

clew/query/symbols.py:193

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
lines 207–207◇ if not table_exists(conn, "shared_key_edges")lines 208–208return []lines 209–209r1, tjoin = _key_r1_projection(conn)lines 210–210focal, other = ("w", "r") if as_writer else ("r", "w")lines 211–219sql = ( 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" )lines 220–220return conn.execute(sql, (fn,)).fetchall()

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.

clew/query/symbols.py:161

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
lines 176–176◇ if not has_columns(conn, "shared_key_edges", *_KEY_R1_COLUMNS)lines 177–177return "'unknown', NULL, NULL, NULL", ""lines 178–178◇ if not table_exists(conn, "threads")lines 179–179return "s.dispatch_mode, s.edge_triggered, s.crosses_thread, NULL", ""lines 180–183return ( "s.dispatch_mode, s.edge_triggered, s.crosses_thread, t.name", "LEFT JOIN threads t ON t.id = s.to_thread_id", )

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.

clew/query/symbols.py:1423

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
lines 1453–1453◇ if not table_exists(conn, "memberdef")lines 1454–1454return []lines 1455–1463clause = " 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) )lines 1464–1464params: list[str] = []lines 1465–1465◇ for token in tokenslines 1466–1466params += [f"%{token}%"] * 4lines 1470–1476rows = 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()lines 1492–1492elsewhere: dict[str, list[str]] = {}lines 1493–1493kept: dict[str, tuple] = {}lines 1494–1494◇ for row in rowslines 1495–1495name, file, rowid = row[0], row[2], row[4]lines 1496–1496◇ if name in keptlines 1497–1497differs = symbol_provenance(conn, rowid) != symbol_provenance(conn, kept[name][4])lines 1498–1498◇ if differs and file and file != kept[name][2] and file not in elsewhere[name]lines 1499–1499elsewhere[name].append(file)lines 1500–1500continuelines 1501–1501kept[name] = rowlines 1502–1502elsewhere[name] = []lines 1505–1505generated = self_declared_paths(conn)lines 1506–1506candidates: list[_Candidate] = []lines 1507–1507◇ for name, (_n, row_kind, file, brief, rowid, extra) in kept.items()lines 1508–1508clean = strip_xml(brief) or _one_line(extra)lines 1509–1509penalty = SEARCH_PENALTY_SELF_DECLARED_GENERATED if file in generated else 0lines 1510–1524candidates.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]), ), ) )lines 1525–1525return candidates

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.

clew/query/symbols.py:1554

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
lines 1575–1575candidates: list[_Candidate] = []lines 1576–1576◇ for kind, tier in SEARCHED_MEMBERDEF_KINDSlines 1577–1577extra = _expansion_sql(conn) if kind == MACRO_KIND else "''"lines 1578–1578candidates += _memberdef_candidates(conn, query, tokens, kind, tier, extra)lines 1579–1579return candidates

Flows

_one_line

str clew.query.symbols._one_line(str|None text)

Collapse whitespace and line continuations, then trim to brief length.

clew/query/symbols.py:1386

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
lines 1401–1401flat = re.sub(r"\s+", " ", (text or "").replace("\\\n", " ")).strip()lines 1402–1402return _doc_brief(flat)

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.

clew/query/symbols.py:1867

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
lines 1899–1899like = f"%{token}%"lines 1900–1900symbols = 0lines 1901–1901◇ if table_exists(conn, "memberdef")lines 1902–1902kinds = [kind for kind, _tier in SEARCHED_MEMBERDEF_KINDS]lines 1903–1903placeholders = ",".join("?" * len(kinds))lines 1904–1910symbols = 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]lines 1911–1911return symbols + len(class_rows(conn, [token])) + len(file_doc_rows(conn, [token]))

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.

clew/query/symbols.py:650

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
lines 677–677◇ if not table_exists(conn, "reimplements")lines 678–678return []lines 679–679focal_rowids = identity_rowids(conn, fn, qualified)lines 680–680◇ if not focal_rowidslines 681–681return []lines 683–687focal, other = ( ("memberdef_rowid", "reimplemented_rowid") if want_bases else ("reimplemented_rowid", "memberdef_rowid") )lines 688–688marks = ", ".join("?" for _ in focal_rowids)lines 689–705return [ 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, ) ]

Requirements

REQ-DDB-QUERY-009 REQ-DDB-QUERY-010

_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.

clew/query/symbols.py:2168

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
lines 2175–2175◇ if not has_columns(conn, "requirements", *_REQ_ATTRIBUTES, "extra")lines 2176–2176return {}lines 2177–2180row = conn.execute( f"SELECT {', '.join(_REQ_ATTRIBUTES)}, extra FROM requirements WHERE id=?", # noqa: S608 (req_id,), ).fetchone()lines 2181–2181◇ if row is Nonelines 2182–2182return {}lines 2183–2183out: dict[str, Any] = {k: str(v or "") for k, v in zip(_REQ_ATTRIBUTES, row[:-1])}lines 2184–2184out["extra"] = json.loads(row[-1]) if row[-1] else Nonelines 2185–2185return out

Requirements

REQ-DDB-QUERY-001

_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.

clew/query/symbols.py:2131

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
lines 2133–2133◇ if not table_exists(conn, "failure_modes")lines 2134–2134return []lines 2135–2135linked = table_exists(conn, "test_failure_modes")lines 2136–2138modes = conn.execute( "SELECT mode_id, meaning FROM failure_modes WHERE req_id = ? ORDER BY mode_id", (req_id,) ).fetchall()lines 2139–2154return [ 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 ]

Requirements

REQ-DDB-SCHEMA-006

_roster_meaning

str clew.query.symbols._roster_meaning(OriginSplit origin, bool attributable)

The sentence stating both the count and whose threads it counts.

clew/query/symbols.py:1186

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
lines 1209–1209◇ if not attributablelines 1210–1210return f"{origin.total} thread(s), and {_THREADS_UNATTRIBUTED_MEANING}"lines 1211–1211roots = f" ({', '.join(origin.external_roots)})" if origin.external_roots else ""lines 1212–1230return ( 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." )

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).

clew/query/symbols.py:1247

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
lines 1261–1261lname = name.lower()lines 1262–1262score = 0lines 1263–1263◇ if lname == querylines 1264–1264score += SEARCH_WEIGHT_EXACT_NAMElines 1265–1265◇ if query and query in lnamelines 1266–1266score += SEARCH_WEIGHT_NAME_SUBSTRINGlines 1267–1267score += SEARCH_WEIGHT_TOKEN_IN_NAME * sum(1 for t in tokens if t in lname)lines 1268–1268score += SEARCH_WEIGHT_TOKEN_IN_BRIEF * sum(1 for t in tokens if t in brief.lower())lines 1269–1269score += SEARCH_WEIGHT_TOKEN_IN_PATH * sum(1 for t in tokens if t in path.lower())lines 1270–1270return score

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.

clew/query/symbols.py:1004

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
lines 1015–1015◇ if path_rowid is Nonelines 1016–1016return "", ""lines 1017–1017tagged = has_columns(conn, "path", EXTERNAL_ROOT_COLUMN)lines 1018–1018column = f"p.{EXTERNAL_ROOT_COLUMN}" if tagged else "''"lines 1019–1022row = conn.execute( f"SELECT p.name, COALESCE({column}, '') FROM path p WHERE p.rowid=?", (path_rowid,), ).fetchone()lines 1023–1023◇ if row is Nonelines 1024–1024return "", ""lines 1025–1025return row[0] or "", row[1] or ""

Flows

_thread_columns

str clew.query.symbols._thread_columns(sqlite3.Connection conn)

The threads column list this index can actually supply.

clew/query/symbols.py:932

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
lines 942–942◇ if has_columns(conn, "threads", "lifecycle", "lifecycle_line")lines 943–943return _THREAD_LIFECYCLE_COLUMNSlines 944–944◇ if has_columns(conn, "threads", "spawn_path_rowid", "spawn_line", "spawn_function")lines 945–945return _THREAD_SPAWNER_COLUMNSlines 946–946◇ if has_columns(conn, "threads", "spawn_path_rowid", "spawn_line")lines 947–947return _THREAD_SITE_COLUMNSlines 948–948return _THREAD_COLUMNS

Flows

_thread_origins

list[str | None] clew.query.symbols._thread_origins(tuple[Thread,...] threads)

One origin per thread, keyed on its SPAWN SITE.

clew/query/symbols.py:1168

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
lines 1177–1177return [(t.external_root or "") if t.spawn_file else None for t in threads]

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.

clew/query/symbols.py:1981

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
lines 1997–1999clause = " AND ".join( ["(LOWER(name) LIKE ? OR LOWER(COALESCE(briefdescription,'')) LIKE ?)"] * len(tokens) )lines 2000–2000params: list[str] = []lines 2001–2001◇ for token in tokenslines 2002–2002params += [f"%{token}%"] * 2lines 2003–2006rows = conn.execute( f"SELECT kind, COUNT(DISTINCT name) FROM {table} WHERE {clause} GROUP BY kind", params, ).fetchall()lines 2007–2007return {kind: n for kind, n in rows if kind not in searched}

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.

clew/query/symbols.py:268

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
lines 282–286order = ( CALL_SOURCE.values.index(source) if source in CALL_SOURCE.values else len(CALL_SOURCE.values) )lines 287–287return (CALL_MATCH.rank.get(confidence or "", -1), -order)

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.

clew/query/symbols.py:892

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
lines 900–900with connect(db) as connlines 901–901◇ if not table_exists(conn, "req_edges")lines 902–902return []lines 903–907rows = 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()lines 908–908return [ReqEdge(fn=fn, req_id=rid) for fn, rid in rows]

Requirements

REQ-DDB-QUERY-004

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.

clew/query/symbols.py:839

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
lines 851–851with connect(db) as connlines 852–852return _call_edges(conn, fn, want_callers=False, include_dataflow=True, qualified=qualified)

Requirements

REQ-DDB-QUERY-001 REQ-DDB-QUERY-010

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.

clew/query/symbols.py:817

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
lines 829–829with connect(db) as connlines 830–830return _call_edges(conn, fn, want_callers=True, include_dataflow=True, qualified=qualified)

Requirements

REQ-DDB-QUERY-001 REQ-DDB-QUERY-010

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).

clew/query/symbols.py:859

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
lines 868–884return [ 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 ) ]

Requirements

REQ-DDB-QUERY-004

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.

clew/query/symbols.py:2195

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
lines 2217–2217with connect(db) as connlines 2218–2218candidates, shared = _ambiguity_counts(conn, fn, want_callers=want_callers)lines 2219–2219return NameAmbiguity(name=fn, candidates=candidates, shared_rows=shared) if shared else None

Requirements

REQ-DDB-QUERY-001

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).

clew/query/symbols.py:741

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
lines 755–755with connect(db) as connlines 756–756return _override_refs(conn, fn, want_bases=False, qualified=qualified)

Requirements

REQ-DDB-QUERY-001 REQ-DDB-QUERY-009 REQ-DDB-QUERY-010

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).

clew/query/symbols.py:717

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
lines 728–728with connect(db) as connlines 729–729return _override_refs(conn, fn, want_bases=True, qualified=qualified)

Requirements

REQ-DDB-QUERY-001 REQ-DDB-QUERY-009 REQ-DDB-QUERY-010

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 .

clew/query/symbols.py:2064

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
lines 2072–2072with connect(db) as connlines 2073–2073meta = Nonelines 2074–2074attrs: dict[str, Any] = {}lines 2075–2075◇ if table_exists(conn, "requirements")lines 2076–2079meta = conn.execute( "SELECT block, title, acceptance, priority FROM requirements WHERE id=?", (req_id,), ).fetchone()lines 2080–2080attrs = _req_attributes(conn, req_id)lines 2083–2092linked = ( 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 [] )lines 2093–2093tests = list(dict.fromkeys(str(r[0]) for r in linked))lines 2094–2094implementers = _req_implementers(conn, req_id, set(tests) | {str(r[1]) for r in linked})lines 2095–2105mentions = ( [ 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 )lines 2106–2106links = _req_links(conn, req_id)lines 2107–2107modes = _req_failure_modes(conn, req_id)lines 2108–2108block, title, acceptance, priority = meta if meta else ("", "", "", "")lines 2109–2122return 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, )

Requirements

REQ-DDB-QUERY-001

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.

clew/query/symbols.py:100

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
lines 121–121with connect(db) as connlines 122–122cands = function_candidates(conn, name, qualified)lines 123–123◇ if not candslines 124–124return Nonelines 125–125rowid = cands[0][0]lines 126–131row = 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()lines 135–135all_cands = function_candidates(conn, name) if qualified is not None else candslines 136–136overloads = candidate_rows(conn, name, all_cands) if is_overloaded(all_cands) else []lines 137–137provenance = symbol_provenance(conn, rowid)lines 138–147return SymbolRef( name=row[0], rowid=rowid, kind=row[1], file=row[2], line_start=row[3], line_end=row[4], candidates=overloads, provenance=provenance, )

Requirements

REQ-DDB-QUERY-003 REQ-DDB-QUERY-010

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.

clew/query/symbols.py:1795

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
lines 1805–1805tokens = [t.lower() for t in text.split() if t]lines 1806–1806◇ if not tokenslines 1807–1807return [], 0lines 1808–1808query = text.strip().lower()lines 1809–1809with connect(db) as connlines 1810–1815ranked = ( _memberdef_corpora(conn, query, tokens) + _class_candidates(conn, query, tokens) + _config_candidates(conn, query, tokens) + _file_candidates(conn, query, tokens) )lines 1819–1819ranked.sort(key=lambda r: (r[0], r[1], r[2]))lines 1820–1820return [hit for _score, _tier, _name, hit in ranked[: max(1, limit)]], len(ranked)

Requirements

REQ-DDB-QUERY-001

Flows

thread_of

list[Thread] clew.query.symbols.thread_of(DbSource db, str fn)

Threads one function belongs to.

clew/query/symbols.py:1081

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
lines 1094–1094with connect(db) as connlines 1095–1095return threads_for_rowids(conn, rowids_for_name(conn, fn))

Requirements

REQ-DDB-QUERY-001

thread_roster

ThreadInventory clew.query.symbols.thread_roster(DbSource db)

Every thread in the DB, with member counts and the origin split.

clew/query/symbols.py:1121

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
lines 1144–1144with connect(db) as connlines 1145–1145◇ if not table_exists(conn, "threads")lines 1146–1148return ThreadInventory( threads=(), rows=0, row_meaning=_THREADS_ABSENT_MEANING, origin=OriginSplit.of(()) )lines 1149–1149attributable = has_columns(conn, "threads", "spawn_path_rowid", "spawn_line")lines 1150–1152rows = conn.execute( f"SELECT {_thread_columns(conn)} FROM threads t ORDER BY t.id", ).fetchall()lines 1153–1153threads = tuple(_build_thread(conn, r) for r in rows)lines 1154–1154origin = OriginSplit.of(_thread_origins(threads))lines 1155–1160return ThreadInventory( threads=threads, rows=len(threads), row_meaning=_roster_meaning(origin, attributable=attributable), origin=origin, )

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.

clew/query/symbols.py:1032

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
lines 1040–1040◇ if not (table_exists(conn, "threads") and table_exists(conn, "thread_membership"))lines 1041–1041return []lines 1042–1047rows = 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()lines 1048–1048return [_build_thread(conn, r) for r in rows]

Requirements

REQ-DDB-QUERY-004

threads_for_rowids

list[Thread] clew.query.symbols.threads_for_rowids(sqlite3.Connection conn, list[int] rowids)

Union thread membership over several memberdef rowids.

clew/query/symbols.py:1057

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
lines 1067–1067seen: set[int] = set()lines 1068–1068found: list[Thread] = []lines 1069–1069◇ for rowid in rowidslines 1070–1070◇ for thread in threads_for(conn, rowid)lines 1071–1071◇ if thread.id not in seenlines 1072–1072seen.add(thread.id)lines 1073–1073found.append(thread)lines 1074–1074return sorted(found, key=lambda t: t.id)

Requirements

REQ-DDB-QUERY-004

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.

clew/query/symbols.py:1837

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
lines 1854–1854counts: dict[str, int] = {}lines 1855–1855with connect(db) as connlines 1856–1856◇ for token in tokenslines 1857–1857counts[token] = _one_token_count(conn, token)lines 1858–1858return counts

Requirements

REQ-DDB-QUERY-007

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.

clew/query/symbols.py:363

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
lines 382–382◇ if not table_exists(conn, "unresolved_inbound")lines 383–383return Nonelines 384–384rowids = list(ids)lines 385–385◇ if not rowidslines 386–386return 0lines 387–387placeholders = ",".join("?" * len(rowids))lines 388–392row = conn.execute( f"SELECT COALESCE(SUM(sites), 0) FROM unresolved_inbound " # noqa: S608 f"WHERE callee_rowid IN ({placeholders})", rowids, ).fetchone()lines 393–393return int(row[0]) if row else 0

Requirements

REQ-DDB-QUERY-002

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.

clew/query/symbols.py:1934

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}

Activity · 11 steps
lines 1960–1960◇ if not tokenslines 1961–1961return {}lines 1962–1962found: dict[str, int] = {}lines 1963–1963with connect(db) as connlines 1964–1964searched = {kind for kind, _tier in SEARCHED_MEMBERDEF_KINDS}lines 1965–1965◇ if table_exists(conn, "memberdef")lines 1966–1966found |= _unread_kind_counts(conn, "memberdef", tokens, searched)lines 1967–1967◇ if table_exists(conn, "compounddef")lines 1968–1968covered = set(CLASS_KINDS) | set(_COVERED_COMPOUND_KINDS)lines 1969–1969found |= _unread_kind_counts(conn, "compounddef", tokens, covered)lines 1970–1970return {kind: n for kind, n in sorted(found.items()) if n}

Requirements

REQ-DDB-QUERY-007

Flows