graph.py

clew/query/graph.py

The ONE aggregate: how much of this graph should a consumer trust (gh#7).

call_edge_counts

EdgeCounts clew.query.graph.call_edge_counts(sqlite3.Connection conn)

Aggregate the call graph: rows, logical pairs, and the trust shares.

clew/query/graph.py:146

Show on the map →

Called by graph_stats

Calls _distribution, _empty_edge_counts, _scalar, table_exists

Source · 48 lines
def call_edge_counts(conn: sqlite3.Connection) -> EdgeCounts:
    """`pairs_without_nonfuzzy` is computed with `SUM(...) = 0` over a per-pair
    grouping rather than by filtering rows, and the difference is the whole point: a
    pair with one `exact` row and nine `fuzzy` ones HAS non-fuzzy evidence, and a
    row-level filter would count it on the wrong side. The question is "did ANY layer
    resolve this endpoint", which is a property of the pair.

    `confidence IS NOT NULL` is part of the non-fuzzy test because the column is
    nullable and a NULL is not evidence. Treating it as non-fuzzy would inflate the
    trustworthy share using rows that assert nothing.

    @brief Build the call-edge aggregate.
    @return EdgeCounts for this index.
    @version 3
    """
    if not table_exists(conn, "call_edges"):
        return _empty_edge_counts()
    rows = _scalar(conn, "SELECT COUNT(*) FROM call_edges")
    pairs = _scalar(
        conn,
        "SELECT COUNT(*) FROM (SELECT 1 FROM call_edges GROUP BY caller_rowid, callee_rowid)",
    )
    if not pairs:
        return _empty_edge_counts()
    unresolved = _scalar(
        conn,
        "SELECT COUNT(*) FROM (SELECT 1 FROM call_edges "
        "GROUP BY caller_rowid, callee_rowid HAVING SUM(CASE WHEN confidence IS NOT NULL "
        f"AND confidence <> '{CALL_MATCH_FUZZY}' THEN 1 ELSE 0 END) = 0)",
    )
    inflation = rows / pairs
    return EdgeCounts(
        rows=rows,
        logical_pairs=pairs,
        row_inflation=round(inflation, 4),
        pairs_without_nonfuzzy=unresolved,
        pairs_without_nonfuzzy_share=round(unresolved / pairs, 4),
        rows_by_confidence=_distribution(
            conn,
            "SELECT confidence, COUNT(*) FROM call_edges GROUP BY confidence ORDER BY 2 DESC",
        ),
        rows_by_source=_distribution(
            conn, "SELECT source, COUNT(*) FROM call_edges GROUP BY source ORDER BY 2 DESC"
        ),
        row_meaning=ROW_MEANING.format(rows=rows, pairs=pairs, inflation=inflation),
    )

Activity · 9 steps
lines 161–161◇ if not table_exists(conn, "call_edges")lines 162–162return _empty_edge_counts()lines 163–163rows = _scalar(conn, "SELECT COUNT(*) FROM call_edges")lines 164–167pairs = _scalar( conn, "SELECT COUNT(*) FROM (SELECT 1 FROM call_edges GROUP BY caller_rowid, callee_rowid)", )lines 168–168◇ if not pairslines 169–169return _empty_edge_counts()lines 170–175unresolved = _scalar( conn, "SELECT COUNT(*) FROM (SELECT 1 FROM call_edges " "GROUP BY caller_rowid, callee_rowid HAVING SUM(CASE WHEN confidence IS NOT NULL " f"AND confidence <> '{CALL_MATCH_FUZZY}' THEN 1 ELSE 0 END) = 0)", )lines 176–176inflation = rows / pairslines 177–191return EdgeCounts( rows=rows, logical_pairs=pairs, row_inflation=round(inflation, 4), pairs_without_nonfuzzy=unresolved, pairs_without_nonfuzzy_share=round(unresolved / pairs, 4), rows_by_confidence=_distribution( conn, "SELECT confidence, COUNT(*) FROM call_edges GROUP BY confidence ORDER BY 2 DESC", ), rows_by_source=_distribution( conn, "SELECT source, COUNT(*) FROM call_edges GROUP BY source ORDER BY 2 DESC" ), row_meaning=ROW_MEANING.format(rows=rows, pairs=pairs, inflation=inflation), )

Requirements

REQ-DDB-QUERY-008

file_counts

FileCounts clew.query.graph.file_counts(sqlite3.Connection conn, DbSource db)

Indexed files vs files yielding symbols vs files yielding bodies.

clew/query/graph.py:297

Show on the map →

Called by graph_stats

Calls _external_roots, _first_party, _float_figure, _int_figure, _records_external, _scalar, meta_section

Source · 70 lines
def file_counts(conn: sqlite3.Connection, db: DbSource) -> FileCounts:
    """`files_with_bodies` counts DISTINCT non-null `bodyfile_id`, and the definition
    is stated because the decl/def duality makes "a file that yielded a body"
    genuinely ambiguous — doxygen attributes a C++ method to its declaring HEADER via
    `file_id` and to the `.cpp` holding its body via `bodyfile_id`. Counting one alone
    is wrong in one direction or the other, so both are reported and neither is called
    "the" file count.

    The gh#6 figures are READ from `build_meta`, never recomputed here. `db` is taken
    separately from `conn` for that read alone: an in-memory or caller-supplied
    connection has no path, so `coverage_recorded` correctly reports False rather than
    the reader inventing a healthy-looking zero.

    THE THREE COUNTED FIGURES ARE FIRST PARTY (gh#335), which is a change to what the
    SQL asks and NOT to what the graph contains. `_first_party` is a WHERE fragment
    over `path`, so a file inside a nested git tree stays fully indexed, fully
    reachable from `chain_trace` and `callers`, and simply lands in `external_files`
    instead of `indexed_files`. On an index predating the tag the fragment is `1`,
    which counts everything — correct, because such a build EXCLUDED nested trees, so
    everything in it really is first party.

    @brief Build the file-coverage aggregate.
    @return FileCounts for this index.
    @version 2
    """
    meta = meta_section(db, "coverage") if not isinstance(db, sqlite3.Connection) else {}
    tagged = _records_external(conn)
    mine = _first_party(tagged)
    return FileCounts(
        indexed_files=_scalar(conn, f"SELECT COUNT(*) FROM path WHERE type=1 AND {mine}"),
        files_with_symbols=_scalar(
            conn,
            "SELECT COUNT(*) FROM ("
            "SELECT file_id AS f FROM memberdef WHERE file_id IS NOT NULL "
            "UNION SELECT bodyfile_id FROM memberdef WHERE bodyfile_id IS NOT NULL"
            f") WHERE f IN (SELECT rowid FROM path WHERE {mine})",
        ),
        files_with_bodies=_scalar(
            conn,
            "SELECT COUNT(DISTINCT bodyfile_id) FROM memberdef WHERE bodyfile_id IS NOT NULL "
            f"AND bodyfile_id IN (SELECT rowid FROM path WHERE {mine})",
        ),
        coverage_recorded=bool(meta),
        substantive_files=_int_figure(meta, "substantive_files"),
        barren_files=_int_figure(meta, "barren_files"),
        barren_ratio=_float_figure(meta, "barren_ratio"),
        undocumented_files=_int_figure(meta, "undocumented_files"),
        undocumented_ratio=_float_figure(meta, "undocumented_ratio"),
        external_files=(
            _scalar(
                conn,
                f"SELECT COUNT(*) FROM path WHERE type=1 AND {EXTERNAL_ROOT_COLUMN} IS NOT NULL "
                f"AND {EXTERNAL_ROOT_COLUMN} <> ''",
            )
            if tagged
            else 0
        ),
        external_roots=_external_roots(conn) if tagged else (),
        external_recorded=tagged,
        unresolved_files=(
            _scalar(
                conn,
                f"SELECT COUNT(*) FROM path WHERE type=1 AND {UNRESOLVED_PATH_COLUMN} = 1",
            )
            if tagged
            else 0
        ),
    )

Activity · 4 steps
lines 322–322meta = meta_section(db, "coverage") if not isinstance(db, sqlite3.Connection) else {}lines 323–323tagged = _records_external(conn)lines 324–324mine = _first_party(tagged)lines 325–364return FileCounts( indexed_files=_scalar(conn, f"SELECT COUNT(*) FROM path WHERE type=1 AND {mine}"), files_with_symbols=_scalar( conn, "SELECT COUNT(*) FROM (" "SELECT file_id AS f FROM memberdef WHERE file_id IS NOT NULL " "UNION SELECT bodyfile_id FROM memberdef WHERE bodyfile_id IS NOT NULL" f") WHERE f IN (SELECT rowid FROM path WHERE {mine})", ), files_with_bodies=_scalar( conn, "SELECT COUNT(DISTINCT bodyfile_id) FROM memberdef WHERE bodyfile_id IS NOT NULL " f"AND bodyfile_id IN (SELECT rowid FROM path WHERE {mine})", ), coverage_recorded=bool(meta), substantive_files=_int_figure(meta, "substantive_files"), barren_files=_int_figure(meta, "barren_files"), barren_ratio=_float_figure(meta, "barren_ratio"), undocumented_files=_int_figure(meta, "undocumented_files"), undocumented_ratio=_float_figure(meta, "undocumented_ratio"), external_files=( _scalar( conn, f"SELECT COUNT(*) FROM path WHERE type=1 AND {EXTERNAL_ROOT_COLUMN} IS NOT NULL " f"AND {EXTERNAL_ROOT_COLUMN} <> ''", ) if tagged else 0 ), external_roots=_external_roots(conn) if tagged else (), external_recorded=tagged, unresolved_files=( _scalar( conn, f"SELECT COUNT(*) FROM path WHERE type=1 AND {UNRESOLVED_PATH_COLUMN} = 1", ) if tagged else 0 ), )

Requirements

REQ-DDB-QUERY-008

graph_stats

GraphStats clew.query.graph.graph_stats(DbSource db)

Aggregate the whole graph: edges, files, layers and symbol provenance.

clew/query/graph.py:463

Source · 25 lines
def graph_stats(db: DbSource) -> GraphStats:
    """The single entry point gh#7 asks for, and the only accessor on this surface
    whose subject is the GRAPH rather than a symbol or a seed.

    NON-RAISING throughout: an index missing a later layer, a database with no
    tables, and a fully-built one all return a `GraphStats`. A trust aggregate that
    raises on a thin index is useless exactly when a consumer most needs to find out
    the index is thin — the same reasoning `coverage.measure_index_coverage` states
    for failing soft.

    @brief Build the whole-graph trust aggregate.
    @return GraphStats for this index.
    @version 1
    """
    with connect(db) as conn:
        return GraphStats(
            build_version=(
                None if isinstance(db, sqlite3.Connection) else read_build_signature(db)
            ),
            symbol_rows=_scalar(conn, "SELECT COUNT(*) FROM memberdef"),
            calls=call_edge_counts(conn),
            files=file_counts(conn, db),
            layers=layer_states(conn),
            symbol_provenance=_symbol_provenance(conn),
        )

1 more lines, not shown

Activity · 2 steps
lines 477–477with connect(db) as connlines 478–487return GraphStats( build_version=( None if isinstance(db, sqlite3.Connection) else read_build_signature(db) ), symbol_rows=_scalar(conn, "SELECT COUNT(*) FROM memberdef"), calls=call_edge_counts(conn), files=file_counts(conn, db), layers=layer_states(conn), symbol_provenance=_symbol_provenance(conn), )

Requirements

REQ-DDB-QUERY-008

layer_states

tuple[LayerStat, ...] clew.query.graph.layer_states(sqlite3.Connection conn)

Every richness layer's state, distinguishing empty from absent.

clew/query/graph.py:226

Source · 21 lines
def layer_states(conn: sqlite3.Connection) -> tuple[LayerStat, ...]:
    """`table_exists` is asked FIRST and its answer is carried, not inferred from the
    count. A `COUNT(*)` on a missing table raises, and catching that to produce 0
    would collapse `'absent'` into `'empty'` — erasing exactly the distinction this
    function exists to publish.

    @brief Report each layer as populated / empty / absent.
    @return LayerStat per declared layer.
    @version 2
    """
    stats: list[LayerStat] = []
    for layer in GRAPH_LAYERS:
        if not table_exists(conn, layer):
            stats.append(LayerStat(layer=layer, state=LAYER_STATE_ABSENT, rows=0))
            continue
        rows = _scalar(conn, f"SELECT COUNT(*) FROM {layer}")
        state = LAYER_STATE_POPULATED if rows else LAYER_STATE_EMPTY
        stats.append(LayerStat(layer=layer, state=state, rows=rows))
    return tuple(stats)

Activity · 9 steps
lines 236–236stats: list[LayerStat] = []lines 237–237◇ for layer in GRAPH_LAYERSlines 238–238◇ if not table_exists(conn, layer)lines 239–239stats.append(LayerStat(layer=layer, state=LAYER_STATE_ABSENT, rows=0))lines 240–240continuelines 241–241rows = _scalar(conn, f"SELECT COUNT(*) FROM {layer}")lines 242–242state = LAYER_STATE_POPULATED if rows else LAYER_STATE_EMPTYlines 243–243stats.append(LayerStat(layer=layer, state=state, rows=rows))lines 244–244return tuple(stats)

Requirements

REQ-DDB-QUERY-008