reachability.py¶
clew/reachability.py
Symbol-liveness BFS over call_edges from entry-point seeds.
_bfs_live_set
set[int] clew.reachability._bfs_live_set(sqlite3.Connection conn, set[int] seeds)
BFS over call_edges (non-fuzzy) from seeds.
Source · 23 lines
def _bfs_live_set(conn: sqlite3.Connection, seeds: set[int]) -> set[int]:
"""BFS over call_edges (non-fuzzy) from seeds. Return set of live rowids."""
live: set[int] = set()
frontier = list(seeds)
while frontier:
batch = frontier
frontier = []
for src in batch:
live.add(src)
placeholders = ",".join(["?"] * len(batch))
callees = conn.execute(
f"""
SELECT DISTINCT callee_rowid FROM call_edges
WHERE caller_rowid IN ({placeholders}) AND confidence != 'fuzzy'
""",
list(batch),
).fetchall()
for (dst,) in callees:
if dst not in live:
frontier.append(dst)
return live
Activity · 13 steps
Requirements
_gather_reachability_seeds
tuple[set[int], set[int]] clew.reachability._gather_reachability_seeds(sqlite3.Connection conn, list[str] entry_patterns)
Return (pattern_seeds, zero_incoming_seeds).
Source · 29 lines
def _gather_reachability_seeds(
conn: sqlite3.Connection,
entry_patterns: list[str],
) -> tuple[set[int], set[int]]:
"""Return (pattern_seeds, zero_incoming_seeds)."""
seed_clauses = " OR ".join(["name LIKE ?"] * len(entry_patterns))
pattern_seeds = {
r[0]
for r in conn.execute(
f"SELECT rowid FROM memberdef WHERE kind = 'function' AND ({seed_clauses})",
entry_patterns,
).fetchall()
}
zero_incoming_seeds = {
r[0]
for r in conn.execute(
"""
SELECT m.rowid FROM memberdef m
WHERE m.kind = 'function'
AND NOT EXISTS (
SELECT 1 FROM call_edges ce
WHERE ce.callee_rowid = m.rowid AND ce.confidence != 'fuzzy'
)
""",
).fetchall()
}
return pattern_seeds, zero_incoming_seeds
Activity · 4 steps
Requirements
_write_symbol_liveness
tuple[int, int] clew.reachability._write_symbol_liveness(sqlite3.Connection conn, set[int] live)
Populate symbol_liveness from live .
Source · 17 lines
def _write_symbol_liveness(
conn: sqlite3.Connection,
live: set[int],
) -> tuple[int, int]:
"""Populate symbol_liveness from `live`. Return (live_count, total)."""
candidates = conn.execute(
"SELECT rowid FROM memberdef WHERE kind = 'function'",
).fetchall()
rows = [(rid, "live" if rid in live else "orphan") for (rid,) in candidates]
conn.executemany(
"INSERT INTO symbol_liveness (memberdef_rowid, status) VALUES (?, ?)",
rows,
)
live_count = sum(1 for _, status in rows if status == "live")
return live_count, len(rows)
Activity · 5 steps
Requirements
mark_reachability
None clew.reachability.mark_reachability(Path db_path, list[str]|None entry_patterns=None, set[int]|None extra_seeds=None)
Compute symbol liveness via BFS over call_edges from entry seeds.
Called by _build_stages, run_real_stages, schema_db
Tested by
Calls _bfs_live_set, _gather_reachability_seeds, _write_symbol_liveness
Source · 82 lines
def mark_reachability(
db_path: Path,
entry_patterns: list[str] | None = None,
extra_seeds: set[int] | None = None,
) -> None:
"""Compute symbol liveness via BFS over call_edges from entry seeds.
Skips fuzzy-confidence edges (they add false-positive liveness).
Bails out early when call_edges has no non-fuzzy rows.
A THIRD seed source joins the two the module docstring describes:
`extra_seeds`, rowids identified structurally rather than by name. It exists
because neither existing source can see a Python `if __name__ ==
"__main__":` entry. Measured on the Python real codebase: doxygen attributes the
guard's `_main()` call to `_main` ITSELF, so the function has a non-fuzzy
incoming edge (excluding it from the zero-incoming source), its only caller
is itself, and nothing reaches it — a real entry point reported dead. The
parameter defaults to None, so a C/C++ build's seed set is unchanged.
@brief Walk call_edges BFS and tag symbols live/orphan.
@version 6
"""
if entry_patterns is None:
entry_patterns = DEFAULT_ENTRY_PATTERNS
conn = sqlite3.connect(str(db_path))
edge_count = conn.execute(
"SELECT COUNT(*) FROM call_edges WHERE confidence != 'fuzzy'",
).fetchone()[0]
if edge_count == 0:
logger.warning(
"call_edges has no non-fuzzy rows — skipping reachability pass",
)
conn.close()
return
conn.execute("DROP TABLE IF EXISTS symbol_liveness")
conn.execute(
f"""
CREATE TABLE symbol_liveness (
memberdef_rowid INTEGER PRIMARY KEY,
status TEXT {check("symbol_liveness", "status")} NOT NULL
)
""",
)
pattern_seeds, zero_incoming_seeds = _gather_reachability_seeds(
conn,
entry_patterns,
)
structural_seeds = extra_seeds or set()
seeds = pattern_seeds | zero_incoming_seeds | structural_seeds
logger.info(
"Reachability seeds: pattern=%d zero_incoming=%d structural=%d union=%d",
len(pattern_seeds),
len(zero_incoming_seeds),
len(structural_seeds),
len(seeds),
)
live = _bfs_live_set(conn, seeds)
live_count, total = _write_symbol_liveness(conn, live)
conn.commit()
conn.close()
orphan_count = total - live_count
logger.info(
"Reachability: live=%d orphan=%d total=%d (seeds=%d, edges=%d)",
live_count,
orphan_count,
total,
len(seeds),
edge_count,
)
if total > 0 and orphan_count / total > 0.8:
logger.warning(
"More than 80%% of functions/variables are orphan (%d/%d). "
"Entry-point seeds may be wrong for this repo — consider "
"passing --entry-patterns with repo-specific patterns.",
orphan_count,
total,
)1 more lines, not shown