Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(health): store each function's execution role and body facts (#3363)
Raghav Chamadiya8fc042a6660b
diff --git a/packages/core/alembic/versions/0104_function_facts.py b/packages/core/alembic/versions/0104_function_facts.pynew file mode 100644index 000000000..cc2930aae--- /dev/null+++ b/packages/core/alembic/versions/0104_function_facts.py@@ -0,0 +1,51 @@+"""Add ``function_facts``: one row per function symbol, its execution role and body facts.++Local SQLite stores get the table from ``init_db``; this migration covers+managed Postgres. Rows appear on the next analysis.++Revision ID: 0104+Revises: 0103+Create Date: 2026-10-10+"""++from __future__ import annotations++from collections.abc import Sequence++import sqlalchemy as sa+from alembic import op++# revision identifiers+revision: str = "0104"+down_revision: str | None = "0103"+branch_labels: str | Sequence[str] | None = None+depends_on: str | Sequence[str] | None = None+++def upgrade() -> None:+ op.create_table(+ "function_facts",+ sa.Column(+ "repository_id",+ sa.String(32),+ sa.ForeignKey("repositories.id", ondelete="CASCADE"),+ primary_key=True,+ ),+ # Bytewise order, so a file's rows are one key range of the id.+ sa.Column(+ "symbol_id",+ sa.Text().with_variant(sa.Text(collation="C"), "postgresql"),+ primary_key=True,+ ),+ sa.Column("execution_role", sa.String(16), nullable=False, server_default="unknown"),+ sa.Column("awaits", sa.Boolean(), nullable=True),+ sa.Column("is_generator", sa.Boolean(), nullable=True),+ sa.Column("uses_receiver", sa.Boolean(), nullable=True),+ sa.Column("receiver_assigns_known", sa.Boolean(), nullable=True),+ sa.Column("receiver_assigns_json", sa.Text(), nullable=True),+ sa.Column("early_exits", sa.Integer(), nullable=True),+ )+++def downgrade() -> None:+ op.drop_table("function_facts")diff --git a/packages/core/src/repowise/core/analysis/health/complexity/body_facts.py b/packages/core/src/repowise/core/analysis/health/complexity/body_facts.pynew file mode 100644index 000000000..652a8058d--- /dev/null+++ b/packages/core/src/repowise/core/analysis/health/complexity/body_facts.py@@ -0,0 +1,120 @@+"""One rule for what a node says about the function holding it.++Two walks read it. The complexity walk counts a whole function's facts on its+own node visits (``cyclomatic._walk_function_body``), and the Extract Method+span walk counts a candidate span's (``dataflow.slice._span_metrics``). Both+call :func:`step` per node, so an ``await`` under an ``async`` block, a+``return`` inside a lambda or an exit macro means the same thing to each.++A lambda is a scope of its own: its awaits, yields and exits are its own, but+it shares the instance, so receiver references inside it still count.+"""++from __future__ import annotations++from collections.abc import Callable+from dataclasses import dataclass, field+from typing import TYPE_CHECKING++if TYPE_CHECKING:+ from tree_sitter import Node++IN_LAMBDA = 1+AWAIT_BLOCKED = 2+++@dataclass(frozen=True, slots=True)+class FactKinds:+ """The node kinds :func:`step` counts. An empty set counts nothing.++ ``jumps`` are what keeps a span from being lifted out (break, continue,+ yield, return, raise); ``exits`` what leaves the function (return, raise).+ ``exit_macros`` (macro kinds, macro names) count as both. ``receiver``+ are the kinds a receiver reference can be, read only with a sink.+ """++ decisions: frozenset[str] = frozenset()+ jumps: frozenset[str] = frozenset()+ exits: frozenset[str] = frozenset()+ exit_macros: tuple[frozenset[str], frozenset[str]] = (frozenset(), frozenset())+ yields: frozenset[str] = frozenset()+ awaits: frozenset[str] = frozenset()+ await_scopes: frozenset[str] = frozenset()+ lambdas: frozenset[str] = frozenset()+ receiver: frozenset[str] = frozenset()+ # Every kind above: a walk that sees every node skips the rest with one lookup.+ watched: frozenset[str] = field(init=False)++ def __post_init__(self) -> None:+ watched = (+ self.decisions+ | self.jumps+ | self.exits+ | self.exit_macros[0]+ | self.yields+ | self.awaits+ | self.await_scopes+ | self.lambdas+ | self.receiver+ )+ object.__setattr__(self, "watched", watched)+++@dataclass(slots=True)+class BodyTally:+ """What :func:`step` counted. ``on_receiver`` sees each receiver-kind node."""++ kinds: FactKinds+ on_receiver: Callable[[Node], object] | None = None+ decisions: int = 0+ jump: bool = False+ exits: int = 0+ yields: int = 0+ awaits: bool = False+++def is_exit_macro(node: Node, exit_macros: tuple[frozenset[str], frozenset[str]]) -> bool:+ """A macro whose name is in *exit_macros*, matched by its last segment:+ ``bail`` in ``anyhow::bail!``."""+ kinds, names = exit_macros+ if node.type not in kinds:+ return False+ macro = node.child_by_field_name("macro")+ name = macro.child_by_field_name("name") or macro if macro is not None else None+ return name is not None and bool(name.text) and name.text.decode("utf-8", "replace") in names+++def is_exit(node: Node, kinds: FactKinds) -> bool:+ """*node* leaves the function: an exit kind or an exit macro."""+ return node.type in kinds.exits or is_exit_macro(node, kinds.exit_macros)+++def step(tally: BodyTally, node: Node, scope: int) -> int:+ """Count *node* into *tally*; the scope its children are visited in."""+ kinds = tally.kinds+ t = node.type+ if tally.on_receiver is not None and t in kinds.receiver:+ tally.on_receiver(node)+ if t in kinds.lambdas:+ return scope | IN_LAMBDA+ if scope & IN_LAMBDA:+ return scope+ tally.decisions += t in kinds.decisions+ macro = is_exit_macro(node, kinds.exit_macros)+ tally.exits += macro or t in kinds.exits+ tally.jump = tally.jump or macro or t in kinds.jumps+ tally.yields += t in kinds.yields+ if not scope & AWAIT_BLOCKED and t in kinds.awaits:+ tally.awaits = True+ return scope | AWAIT_BLOCKED if t in kinds.await_scopes else scope+++__all__ = [+ "AWAIT_BLOCKED",+ "IN_LAMBDA",+ "BodyTally",+ "FactKinds",+ "is_exit",+ "is_exit_macro",+ "step",+]diff --git a/packages/core/src/repowise/core/analysis/health/complexity/cyclomatic.py b/packages/core/src/repowise/core/analysis/health/complexity/cyclomatic.pyindex 8720cdf53..021838b87 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/cyclomatic.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/cyclomatic.py@@ -11,6 +11,7 @@ from __future__ import annotationsfrom typing import TYPE_CHECKING+from .body_facts import BodyTally, stepfrom .languages import LanguageNodeMapfrom .models import ConditionComplexity@@ -301,6 +302,7 @@ def _walk_function_body(body_node: Node,lmap: LanguageNodeMap,deepest: list[int] | None = None,+ tally: BodyTally | None = None,) -> tuple[int, int, int, int, list[ConditionComplexity]]:"""Recursive AST walk. Returns (ccn, max_nesting, cognitive, bumps,complex_conditions).@@ -323,6 +325,10 @@ def _walk_function_body(:data:`MIN_BLOCK_LINES` lines: where a reader starts flattening it. Aone-line branch is too small to name as the place to start. Also aside-channel only.++ ``tally``, when given, is filled on the same visits by :func:`body_facts.step`.+ An expression body (``async () => await f()``) is a node the facts read+ too, so the body root is counted when it is not the function itself."""ccn = 1@@ -337,14 +343,17 @@ def _walk_function_body(deepest_depth = 0deepest_node: list[Node] = []- def _recurse(node: Node, depth: int, in_markup: bool = False) -> None:+ def _recurse(node: Node, depth: int, in_markup: bool = False, scope: int = 0) -> None:nonlocal ccn, max_nesting, cognitive, deepest_depth# Don't descend into nested function bodies — they're walked# separately at the top level. Lambdas / arrow functions DO# contribute to the enclosing function's complexity.- if node.type in lmap.function_kinds:+ node_type = node.type+ if node_type in lmap.function_kinds:return+ if tally is not None and node_type in tally.kinds.watched:+ scope = step(tally, node, scope)nesting_increment = 0ccn_increment = 0@@ -447,14 +456,22 @@ def _walk_function_body(and node.type not in _MARKUP_VALUE_KINDS)for child in node.children:- _recurse(child, new_depth, child_markup)-+ _recurse(child, new_depth, child_markup, scope)++ root_scope = 0+ if (+ tally is not None+ and body_node.type in tally.kinds.watched+ and body_node.type not in lmap.function_kinds+ and body_node.type not in lmap.lambda_kinds+ ):+ root_scope = step(tally, body_node, 0)for child in body_node.children:# Per-child peak depth: temporarily swap max_nesting out so we# can read just this child's contribution, then restore.outer_max = max_nestingmax_nesting = 0- _recurse(child, 0)+ _recurse(child, 0, scope=root_scope)child_peak = max_nestingmax_nesting = max(outer_max, child_peak)if child_peak >= 2:diff --git a/packages/core/src/repowise/core/analysis/health/complexity/models.py b/packages/core/src/repowise/core/analysis/health/complexity/models.pyindex d6b25ebfb..f2b6c0ee3 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/models.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/models.py@@ -11,6 +11,7 @@ from typing import TYPE_CHECKING, Anyif TYPE_CHECKING:from ..asserts.oracle_reach import OracleReach+ from ..dataflow.slice import FunctionFactsfrom ..perf.loop_facts import LoopFacts@@ -128,6 +129,10 @@ class FunctionComplexity:# ``max_nesting``, when the function nests at all: the concrete place to# start flattening it. ``cyclomatic._walk_function_body``.deepest_block: tuple[int, int] | None = None+ # Whole-function facts (awaits, yields, receiver, early exits), stored per+ # function symbol by the health writer. ``dataflow.slice.function_facts``;+ # None means not computed (a language with no map, or a failed read).+ facts: FunctionFacts | None = Nonedef __post_init__(self) -> None:if self.complex_conditions is None:diff --git a/packages/core/src/repowise/core/analysis/health/complexity/walker.py b/packages/core/src/repowise/core/analysis/health/complexity/walker.pyindex a746066c5..2a03e5614 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/walker.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/walker.py@@ -40,6 +40,9 @@ The whole-file passes share one descent of the tree (``file_scan``):from __future__ import annotations+from collections.abc import Callable+from typing import TYPE_CHECKING, Any+import structlogfrom ..asserts.lexicon import assert_dialect as _assert_dialect@@ -80,6 +83,12 @@ from .perf_walk import _collect_perf_hits, perf_pass_runsfrom .signature import is_constructor, is_signature_fixed, typed_param_countsfrom .test_case import is_test_case+if TYPE_CHECKING:+ from tree_sitter import Node++ from ..dataflow.slice import FunctionFacts+ from .body_facts import BodyTally+__all__ = ["ClassComplexity","CohesionGroup",@@ -166,10 +175,14 @@ def walk_file(run_perf = perf_pass_runs(language, lmap)scan = scan_file(tree.root_node, language, lmap, source, io_names=run_perf)flags = module_false_constants(tree.root_node, source, language)+ facts_of = _facts_reader(abs_path, language, lmap)for fn_node in _collect_function_nodes(tree.root_node, lmap):body = fn_node.child_by_field_name("body") or fn_nodedeepest: list[int] = []- ccn, max_nest, cognitive, bumps, conditions = _walk_function_body(body, lmap, deepest)+ start_facts, finish_facts = facts_of(fn_node)+ ccn, max_nest, cognitive, bumps, conditions = _walk_function_body(+ body, lmap, deepest, start_facts+ )(assertion_blocks,assertion_count,@@ -209,6 +222,7 @@ def walk_file(deprecated=is_deprecated(fn_node, body, name, lmap, source),gated_off=body is not fn_node and is_gated_off(body, flags),deepest_block=(deepest[0], deepest[1]) if deepest else None,+ facts=finish_facts(),)functions.append(fc)fc_by_node_id[fn_node.id] = fc@@ -232,6 +246,45 @@ def walk_file()+FactsStart = Callable[["Node"], tuple["BodyTally | None", Callable[[], "FunctionFacts | None"]]]+"""``fn_node -> (tally, finish)``; see :func:`_facts_reader`."""+++def _facts_reader(abs_path: str, language: str, lmap: Any) -> FactsStart:+ """``fn_node -> (tally, finish)``: an empty tally the CCN walk fills, and+ the call that reads :class:`FunctionFacts` off it once it is filled.++ A failure leaves the function's facts ``None`` (not computed) and is+ logged with the file, since a stored row then says nothing about it.+ Deferred import: the dataflow package imports this one.+ """+ from ..dataflow import body_tally, function_facts, get_defuse_dialect++ dialect = get_defuse_dialect(language)++ def failed(exc: Exception) -> None:+ log.warning("function_facts_failed", path=abs_path, error=str(exc))++ def start(fn_node: Node) -> tuple[BodyTally | None, Callable[[], FunctionFacts | None]]:+ try:+ receiver = dialect.receiver(fn_node, lmap) if dialect is not None else None+ tally = body_tally(fn_node, lmap, receiver)+ except Exception as exc:+ failed(exc)+ return None, lambda: None++ def finish() -> FunctionFacts | None:+ try:+ return function_facts(fn_node, lmap, receiver, tally)+ except Exception as exc:+ failed(exc)+ return None++ return tally, finish++ return start++def walk_file_complexity(abs_path: str,language: str,diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/__init__.py b/packages/core/src/repowise/core/analysis/health/dataflow/__init__.pyindex 894bebb4d..c33d8a71b 100644--- a/packages/core/src/repowise/core/analysis/health/dataflow/__init__.py+++ b/packages/core/src/repowise/core/analysis/health/dataflow/__init__.py@@ -63,7 +63,7 @@ from .gating import ()from .lookup import function_analysis_atfrom .reaching import ReachingDefinitions, compute_reaching-from .slice import Extraction, find_extractions+from .slice import Extraction, FunctionFacts, body_tally, find_extractions, function_facts__all__ = ["CFG",@@ -84,12 +84,14 @@ __all__ = ["FunctionAnalysis","FunctionCFG","FunctionDefUse",+ "FunctionFacts","Occurrence","ReachingDefinitions","Statement","StatementDefUse","analyze_file","analyze_function",+ "body_tally","build_cfg","build_cfgs_for_file","compute_def_use",@@ -97,6 +99,7 @@ __all__ = ["derive_facts","find_extractions","function_analysis_at",+ "function_facts","get_defuse_dialect","is_flagged","is_flagged_function",diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/slice.py b/packages/core/src/repowise/core/analysis/health/dataflow/slice.pyindex 5735d6e52..47d6e0912 100644--- a/packages/core/src/repowise/core/analysis/health/dataflow/slice.py+++ b/packages/core/src/repowise/core/analysis/health/dataflow/slice.py@@ -34,6 +34,7 @@ from dataclasses import dataclassfrom typing import TYPE_CHECKING, NamedTuplefrom ..complexity.ast_utils import member_object, self_member_name+from ..complexity.body_facts import BodyTally, FactKinds, is_exit, stepfrom ..complexity.nloc import _code_line_numbersfrom .dialects.base import SUPER, mentions_receiver@@ -109,6 +110,8 @@ class _Scan(NamedTuple):awaits: tuple[frozenset[str], frozenset[str]]lambdas: frozenset[str] = frozenset()receiver: Receiver | None = None+ # Built from the fields above by :func:`_scan_for`; derived when absent.+ kinds: FactKinds | None = Noneclass _Metrics(NamedTuple):@@ -253,13 +256,126 @@ def find_extractions(return _sorted(out)+@dataclass(frozen=True)+class FunctionFacts:+ """What a whole function does, counted on the complexity walk's visits.++ ``awaits``: it suspends outside any nested scope. ``is_generator``: it+ yields. ``uses_receiver`` / ``receiver_assigns`` as on :class:`Extraction`,+ for the whole body; ``receiver_assigns`` is None where an implicit receiver+ (Java, C++) can write fields by bare name, which only def/use can tell.+ ``early_exits``: returns and raises other than a final one.+ """++ awaits: bool+ is_generator: bool+ uses_receiver: bool | None+ receiver_assigns: tuple[str, ...] | None+ early_exits: int+++class _ReceiverSink:+ """``BodyTally.on_receiver``: whether the body names its receiver, and+ which of its fields it assigns."""++ __slots__ = ("assigns", "receiver", "uses")++ def __init__(self, receiver: Receiver) -> None:+ self.receiver = receiver+ self.uses = False+ self.assigns: set[str] = set()++ def __call__(self, node: Node) -> None:+ self.uses = _receiver_ref(node, self.receiver, self.assigns) or self.uses+++def body_tally(fn_node: Node, lmap: LanguageNodeMap, receiver: Receiver | None) -> BodyTally:+ """An empty tally for *fn_node*, for the complexity walk to fill. The+ receiver is watched only when the function's text names it."""+ watched = bool(+ receiver is not None and receiver.names and mentions_receiver(fn_node, receiver.names)+ )+ sink = _ReceiverSink(receiver) if watched and receiver is not None else None+ return BodyTally(_function_kinds(lmap, sink), sink)+++# Built once per language map and receiver shape: the walk asks per function.+_FUNCTION_KINDS: dict[tuple[int, frozenset[str]], FactKinds] = {}+++def _function_kinds(lmap: LanguageNodeMap, sink: _ReceiverSink | None) -> FactKinds:+ receiver = _receiver_kinds(sink.receiver) if sink else frozenset()+ key = (id(lmap), receiver)+ kinds = _FUNCTION_KINDS.get(key)+ if kinds is None:+ kinds = _FUNCTION_KINDS[key] = FactKinds(+ exits=lmap.return_kinds | lmap.raise_kinds,+ exit_macros=_exit_macros(lmap),+ yields=lmap.yield_kinds,+ awaits=lmap.await_kinds,+ await_scopes=lmap.await_scope_kinds,+ lambdas=lmap.lambda_kinds,+ receiver=receiver,+ )+ return kinds+++def _receiver_kinds(receiver: Receiver) -> frozenset[str]:+ """What :func:`_receiver_ref` can answer for: a write, or a receiver leaf."""+ return receiver.write_kinds | receiver.names | {SUPER, "identifier"}+++def function_facts(+ fn_node: Node, lmap: LanguageNodeMap, receiver: Receiver | None, tally: BodyTally+) -> FunctionFacts:+ """:class:`FunctionFacts` from a filled :func:`body_tally`."""+ body = fn_node.child_by_field_name("body") or fn_node+ sink = tally.on_receiver if isinstance(tally.on_receiver, _ReceiverSink) else None+ uses, assigns = _whole_receiver_facts(+ receiver, sink.uses if sink else False, frozenset(sink.assigns) if sink else frozenset()+ )+ return FunctionFacts(+ awaits=tally.awaits,+ is_generator=tally.yields > 0,+ uses_receiver=uses,+ receiver_assigns=assigns,+ early_exits=max(0, tally.exits - _ends_in_exit(body, lmap, tally.kinds)),+ )+++def _ends_in_exit(body: Node, lmap: LanguageNodeMap, kinds: FactKinds) -> bool:+ """Whether a block body's last statement leaves the function, so that exit+ is not an early one. The statement is the exit (Python ``return x``, TS+ ``throw e;``) or wraps it as its first named child (Rust ``return x;`` and+ ``bail!(..);`` are expression statements). An expression body has no+ statements, so its exits are early by definition and none are subtracted."""+ if body.type not in lmap.block_kinds or not body.named_children:+ return False+ tail = body.named_children[-1]+ if is_exit(tail, kinds):+ return True+ return bool(tail.named_children) and is_exit(tail.named_children[0], kinds)+++def _whole_receiver_facts(+ receiver: Receiver | None, uses: bool, assigned: frozenset[str]+) -> tuple[bool | None, tuple[str, ...] | None]:+ if receiver is None:+ return None, None+ if not receiver.names:+ return False, ()+ if receiver.implicit:+ return (True if uses else None), None+ return uses, None if _UNREAD_TARGET in assigned else tuple(sorted(assigned))++def _scan_for(lmap: LanguageNodeMap, receiver: Receiver | None, fn_node: Node) -> _Scan:"""The walk's kinds for *fn_node*. The receiver is looked for only whenits name (or ``super``) appears in the function's text at all: mostfunctions never mention it, and then no node needs the check."""if receiver is not None and not (receiver.names and mentions_receiver(fn_node, receiver.names)):receiver = None- return _Scan(+ scan = _Scan(decisions=lmap.branch_kinds| lmap.loop_kinds| lmap.case_kinds@@ -276,6 +392,7 @@ def _scan_for(lmap: LanguageNodeMap, receiver: Receiver | None, fn_node: Node) -lambdas=lmap.lambda_kinds,receiver=receiver,)+ return scan._replace(kinds=_span_kinds(scan))def _block_prefix(@@ -1091,67 +1208,54 @@ def _awaits(lmap: LanguageNodeMap) -> tuple[frozenset[str], frozenset[str]]:return lmap.await_kinds, lmap.await_scope_kinds-def _is_jump(- node: Node,- jump_kinds: frozenset[str],- exit_macros: tuple[frozenset[str], frozenset[str]],-) -> bool:- """True for a jump node, or a macro whose name is in *exit_macros*- (matched by its last segment: ``bail`` in ``anyhow::bail!``)."""- if node.type in jump_kinds:- return True- kinds, names = exit_macros- if node.type not in kinds:- return False- macro = node.child_by_field_name("macro")- name = macro.child_by_field_name("name") or macro if macro is not None else None- return name is not None and bool(name.text) and name.text.decode("utf-8", "replace") in names+def _span_kinds(scan: _Scan) -> FactKinds:+ await_kinds, await_scope_kinds = scan.awaits+ return FactKinds(+ decisions=scan.decisions,+ jumps=scan.jumps,+ exit_macros=scan.exit_macros,+ awaits=await_kinds,+ await_scopes=await_scope_kinds,+ lambdas=scan.lambdas,+ receiver=_receiver_kinds(scan.receiver) if scan.receiver is not None else frozenset(),+ )def _span_metrics(span: list[Node], scan: _Scan) -> _Metrics:"""Decision points, jump and await presence, and receiver references- within *span*: a candidate span's statements, or a function body's for- facts about the whole function. Nested scopes are not descended into,- except a lambda for the receiver alone, since it shares the instance. A- macro named in ``scan.exit_macros`` counts as a jump; an await under one- of the await scope kinds (``async`` blocks) does not suspend the- function."""- await_kinds, await_scope_kinds = scan.awaits- receiver = scan.receiver- decisions = 0- has_jump = has_await = uses = False- assigns: set[str] = set()+ within *span*: a candidate span's statements, or a function body's.+ Each node is read by :func:`body_facts.step`, the rule the complexity+ walk applies to a whole function. Nested scopes are not descended into,+ except a lambda for the receiver alone, since it shares the instance."""+ kinds = scan.kinds or _span_kinds(scan)+ watched = kinds.watched+ sink = _ReceiverSink(scan.receiver) if scan.receiver is not None else None+ tally = BodyTally(kinds, sink)for root in span:- # (node, whether its awaits count, inside a lambda: receiver only)- stack: list[tuple[Node, bool, bool]] = [(root, True, False)]+ stack: list[tuple[Node, int]] = [(root, 0)]while stack:- node, counts_await, nested = stack.pop()- if receiver is not None:- uses = _receiver_ref(node, receiver, assigns) or uses- if not nested:- t = node.type- has_jump = has_jump or _is_jump(node, scan.jumps, scan.exit_macros)- has_await = has_await or (counts_await and t in await_kinds)- decisions += t in scan.decisions- counts_await = counts_await and t not in await_scope_kinds- _push_children(node, stack, counts_await, nested, scan)- return _Metrics(decisions, has_jump, has_await, uses, frozenset(assigns))+ node, scope = stack.pop()+ if node.type in watched:+ scope = step(tally, node, scope)+ _push_children(node, stack, scope, scan)+ return _Metrics(+ tally.decisions,+ tally.jump,+ tally.awaits,+ sink.uses if sink else False,+ frozenset(sink.assigns) if sink else frozenset(),+ )def _push_children(- node: Node,- stack: list[tuple[Node, bool, bool]],- counts_await: bool,- nested: bool,- scan: _Scan,+ node: Node, stack: list[tuple[Node, int]], scope: int, scan: _Scan) -> None:"""Queue *node*'s children: nested scopes are skipped, except a lambdawhen the receiver is looked for (it shares the instance)."""for child in node.children:- if child.type not in scan.scopes:- stack.append((child, counts_await, nested))- elif scan.receiver is not None and child.type in scan.lambdas:- stack.append((child, False, True))+ t = child.type+ if t not in scan.scopes or (scan.receiver is not None and t in scan.lambdas):+ stack.append((child, scope))# Index access on a receiver field (``self.cache[k] = v``) assigns into it.diff --git a/packages/core/src/repowise/core/analysis/health/engine.py b/packages/core/src/repowise/core/analysis/health/engine.pyindex aee1b3b76..fbf6098a5 100644--- a/packages/core/src/repowise/core/analysis/health/engine.py+++ b/packages/core/src/repowise/core/analysis/health/engine.py@@ -1060,6 +1060,7 @@ class HealthAnalyzer:kpis=kpis,function_blame_rows=self._function_blame_rows(walked),execution_roles=execution_roles,+ function_facts=self._function_fact_rows(walked),repo_function_mod_p80=full_repo_fn_mod_p80,refactoring_suggestions=suggestions,performance_plan_policy=PerformancePlanPolicy(@@ -1265,6 +1266,7 @@ class HealthAnalyzer:kpis=kpis,function_blame_rows=self._function_blame_rows(walked),execution_roles=execution_roles,+ function_facts=self._function_fact_rows(walked),repo_function_mod_p80=full_repo_fn_mod_p80,refactoring_suggestions=suggestions,performance_plan_policy=PerformancePlanPolicy(@@ -1411,6 +1413,43 @@ class HealthAnalyzer:finding.details["execution_role"] = roles.role_of(owner, finding.file_path)return roles+ def _function_fact_rows(+ self, walked: list[tuple[Any, FileComplexity]]+ ) -> list[dict] | None:+ """One row per walked function the graph names, for the ``function_facts`` store.++ A function the graph holds no symbol for has no id to key on, and is left out.+ Test files are left out too: no reader needs their functions yet (perf and+ Extract Method serve production code). Drop the filter when one does.+ """+ index = self._execution_graph()+ if index is None:+ return None+ rows: list[dict] = []+ for pf, fcx in walked:+ path = pf.file_info.path+ if pf.file_info.is_test:+ continue+ for fc in fcx.functions:+ symbol = index.resolve_function(path, fc.start_line, func_end=fc.end_line)+ if symbol is None:+ continue+ facts = fc.facts+ rows.append(+ {+ "symbol_id": symbol,+ "awaits": facts.awaits if facts else None,+ "is_generator": facts.is_generator if facts else None,+ "uses_receiver": facts.uses_receiver if facts else None,+ "receiver_assigns": facts.receiver_assigns if facts else None,+ "receiver_assigns_known": (+ facts.receiver_assigns is not None if facts else None+ ),+ "early_exits": facts.early_exits if facts else None,+ }+ )+ return rows+def _function_blame_rows(self, walked: list[tuple[Any, FileComplexity]]) -> list[dict]:"""Build the per-function blame rollup from the walked files + theFULL-tier blame indexes attached to ``git_meta_map``.diff --git a/packages/core/src/repowise/core/analysis/health/models.py b/packages/core/src/repowise/core/analysis/health/models.pyindex 186df2d43..df07d4056 100644--- a/packages/core/src/repowise/core/analysis/health/models.py+++ b/packages/core/src/repowise/core/analysis/health/models.py@@ -242,3 +242,7 @@ class HealthReport:# restamp stored performance findings this run did not rescan. Typed ``Any``# for the same reason as ``refactoring_suggestions``.execution_roles: Any | None = None+ # One dict per walked function symbol, for the ``function_facts`` store+ # (``HealthAnalyzer._function_fact_rows``). None when there was no graph to+ # key rows on: the writers then leave the stored rows alone.+ function_facts: list[dict] | None = Nonediff --git a/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py b/packages/core/src/repowise/core/persistence/crud/analysis/__init__.pyindex 2834d75a7..d4ec71854 100644--- a/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py+++ b/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py@@ -13,6 +13,7 @@ from . import ( # noqa: F401coverage_map,dead_code,doc_drift,+ function_facts,health,performance,refactoring,@@ -64,6 +65,7 @@ from .doc_drift import (serialize_doc_drift_row,summarize_confidence_rows,)+from .function_facts import get_function_facts, write_function_factsfrom .health import (FILE_TREND_SNAPSHOT_WINDOW,HEALTH_SNAPSHOT_RETENTION,@@ -159,6 +161,7 @@ __all__ = ["get_doc_drift_findings","get_doc_drift_references","get_file_language_map",+ "get_function_facts","get_health_finding_by_public_id","get_health_findings","get_health_metrics",@@ -223,4 +226,5 @@ __all__ = ["upsert_health_findings","upsert_health_metrics","upsert_refactoring_suggestions",+ "write_function_facts",]diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/function_facts.py b/packages/core/src/repowise/core/persistence/crud/analysis/function_facts.pynew file mode 100644index 000000000..e024920db--- /dev/null+++ b/packages/core/src/repowise/core/persistence/crud/analysis/function_facts.py@@ -0,0 +1,129 @@+"""The per-function store: one row per function symbol, its role and body facts.++Facts are pure on a file's bytes, so a run rewrites the rows of the files it+walked and leaves the rest. A role is not: a seed or a call in another file+moves it, so every run restamps every row's role from its own role map.+"""++from __future__ import annotations++import json+from collections.abc import Iterable, Mapping+from typing import TYPE_CHECKING, Any++from sqlalchemy import and_, delete, insert, or_, select, update+from sqlalchemy.ext.asyncio import AsyncSession++from ....analysis.execution_graph import file_of_symbol+from ...models import FunctionFact++if TYPE_CHECKING:+ from ....analysis.execution_roles import ExecutionRoles++_CHUNK = 500+# Key ranges OR-ed into one DELETE: two bound values each, far under SQLite's+# variable limit, and SQLAlchemy keeps the OR flat, so no expression depth.+_RANGES_PER_DELETE = 200+++def _row(repository_id: str, row: Mapping[str, Any]) -> dict[str, Any]:+ assigns = row.get("receiver_assigns")+ return {+ "repository_id": repository_id,+ "symbol_id": row["symbol_id"],+ "awaits": row.get("awaits"),+ "is_generator": row.get("is_generator"),+ "uses_receiver": row.get("uses_receiver"),+ "receiver_assigns_known": row.get("receiver_assigns_known"),+ "receiver_assigns_json": json.dumps(list(assigns)) if assigns else None,+ "early_exits": row.get("early_exits"),+ }+++def key_range(path: str) -> tuple[str, str]:+ """A file's rows as a half-open key range: every symbol id there is ``path::...``.++ Symbol ids carry forward slashes; ``:;`` is the first string after every+ ``path::`` suffix in bytewise order, which the column's ``C`` collation+ gives PostgreSQL too.+ """+ path = path.replace("\\", "/")+ return f"{path}::", f"{path}:;"+++async def delete_file_rows(session: AsyncSession, repository_id: str, paths: Iterable[str]) -> None:+ """Delete the rows of *paths*, a chunk of key ranges per statement."""+ ranges = sorted({key_range(path) for path in paths})+ for i in range(0, len(ranges), _RANGES_PER_DELETE):+ chunk = ranges[i : i + _RANGES_PER_DELETE]+ await session.execute(+ delete(FunctionFact).where(+ FunctionFact.repository_id == repository_id,+ or_(+ *(+ and_(FunctionFact.symbol_id >= low, FunctionFact.symbol_id < high)+ for low, high in chunk+ )+ ),+ )+ )+++async def write_function_facts(+ session: AsyncSession,+ repository_id: str,+ rows: Iterable[Mapping[str, Any]],+ *,+ file_paths: Iterable[str] | None = None,+ roles: ExecutionRoles | None = None,+) -> int:+ """Replace the rows of *file_paths* (every row when ``None``) with *rows*,+ then restamp every row's role from *roles*. Returns the rows written."""+ if file_paths is None:+ await session.execute(delete(FunctionFact).where(FunctionFact.repository_id == repository_id))+ else:+ await delete_file_rows(session, repository_id, file_paths)+ # Two walked functions can resolve to one symbol; the first keeps it. Key+ # order fills the clustered pages instead of splitting them half empty.+ by_symbol = {row["symbol_id"]: _row(repository_id, row) for row in reversed(list(rows))}+ fresh = [by_symbol[symbol] for symbol in sorted(by_symbol)]+ for i in range(0, len(fresh), _CHUNK):+ await session.execute(insert(FunctionFact), fresh[i : i + _CHUNK])+ if roles is not None:+ await _restamp_roles(session, repository_id, roles)+ return len(fresh)+++async def _restamp_roles(session: AsyncSession, repository_id: str, roles: ExecutionRoles) -> None:+ stored = await session.execute(+ select(FunctionFact.symbol_id, FunctionFact.execution_role).where(+ FunctionFact.repository_id == repository_id+ )+ )+ changed = [+ {"repository_id": repository_id, "symbol_id": symbol, "execution_role": role}+ for symbol, current in stored.all()+ if (role := roles.role_of(symbol, file_of_symbol(symbol))) != current+ ]+ for i in range(0, len(changed), _CHUNK):+ await session.execute(update(FunctionFact), changed[i : i + _CHUNK])+++async def get_function_facts(+ session: AsyncSession, repository_id: str, symbol_ids: Iterable[str]+) -> dict[str, FunctionFact]:+ """The stored rows for *symbol_ids*, by symbol id."""+ ids = sorted(set(symbol_ids))+ out: dict[str, FunctionFact] = {}+ for i in range(0, len(ids), _CHUNK):+ result = await session.execute(+ select(FunctionFact).where(+ FunctionFact.repository_id == repository_id,+ FunctionFact.symbol_id.in_(ids[i : i + _CHUNK]),+ )+ )+ out.update((row.symbol_id, row) for row in result.scalars())+ return out+++__all__ = ["delete_file_rows", "get_function_facts", "key_range", "write_function_facts"]diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.pyindex cbad84066..3144ce79e 100644--- a/packages/core/src/repowise/core/persistence/models.py+++ b/packages/core/src/repowise/core/persistence/models.py@@ -2067,6 +2067,50 @@ class PerformanceSummary(Base):)+class FunctionFact(Base):+ """One function symbol: what runs it and what its body does.++ Written by the health writers: facts for the files a run walked, the+ execution role for every row each run, since a role moves with seeds and+ calls in other files. One row per function, so later per-function+ measures are new columns here rather than a second table.++ Lean on purpose: the file, name and lines are on ``graph_nodes`` under the+ same ``symbol_id`` (``path::name``), so they are joined, not copied, and a+ file's rows are a key range of ``symbol_id``. Booleans cost no body bytes+ in SQLite (0 and 1 are header-only), and on SQLite the table is clustered+ on its key, so the key is stored once.+ """++ __tablename__ = "function_facts"++ repository_id: Mapped[str] = mapped_column(+ String(32),+ ForeignKey("repositories.id", ondelete="CASCADE"),+ primary_key=True,+ )+ # Bytewise order on PostgreSQL, so a file's rows are one key range+ # (``crud.analysis.function_facts.file_rows``); SQLite compares bytes already.+ symbol_id: Mapped[str] = mapped_column(+ Text().with_variant(Text(collation="C"), "postgresql"), primary_key=True+ )+ # ``execution_roles.ExecutionRole``.+ execution_role: Mapped[str] = mapped_column(+ String(16), nullable=False, default="unknown", server_default="unknown"+ )+ # ``dataflow.slice.FunctionFacts``; NULL where the walk produced none.+ awaits: Mapped[bool | None] = mapped_column(Boolean, nullable=True)+ is_generator: Mapped[bool | None] = mapped_column(Boolean, nullable=True)+ uses_receiver: Mapped[bool | None] = mapped_column(Boolean, nullable=True)+ # Whether ``receiver_assigns_json`` is the whole set of fields assigned:+ # NULL in that column then means none, otherwise unknown.+ receiver_assigns_known: Mapped[bool | None] = mapped_column(Boolean, nullable=True)+ receiver_assigns_json: Mapped[str | None] = mapped_column(Text, nullable=True)+ early_exits: Mapped[int | None] = mapped_column(Integer, nullable=True)++ __table_args__ = ({"sqlite_with_rowid": False},)++class RefactoringOpportunity(QueueVerdict, Base):"""One file's composed refactoring work, materialized for serving.diff --git a/packages/core/src/repowise/core/pipeline/incremental.py b/packages/core/src/repowise/core/pipeline/incremental.pyindex d4287a402..7e963ebf1 100644--- a/packages/core/src/repowise/core/pipeline/incremental.py+++ b/packages/core/src/repowise/core/pipeline/incremental.py@@ -1283,6 +1283,7 @@ async def persist_partial_health(upsert_health_findings,upsert_health_metrics,upsert_refactoring_suggestions,+ write_function_facts,)from repowise.core.pipeline.persist import _analyzed_commit@@ -1293,6 +1294,9 @@ async def persist_partial_health(performance_paths = sorted(set(getattr(report, "performance_authoritative_paths", None) or ()) - set(changed_paths))+ # Nothing analysed: a deletion-only update runs no health analysis, so it+ # has no role map to restamp stored roles with. Roles, like performance+ # findings, refresh on the next run that analyses any file.if not changed_paths and not performance_paths:returnanalyzed_commit = await _analyzed_commit(session, repo_id)@@ -1351,6 +1355,17 @@ async def persist_partial_health(# opportunity folds a file's plans, and a file this run did not touch# can still lose one when a cross-file plan elsewhere resolves.await finalize_refactoring_opportunities(session, repo_id, analyzed_commit=analyzed_commit)+ # Facts for the files this run walked; roles for every stored row. No+ # rows means no graph to key them on: the stored ones stay.+ fact_rows = getattr(report, "function_facts", None)+ if fact_rows is not None:+ await write_function_facts(+ session,+ repo_id,+ fact_rows,+ file_paths={*changed_paths, *performance_paths},+ roles=getattr(report, "execution_roles", None),+ )# Per-function blame rollup for the changed files (keeps git_function_blame# current between full indexes; FULL git tier only — empty otherwise).fn_blame_rows = getattr(report, "function_blame_rows", None)diff --git a/packages/core/src/repowise/core/pipeline/persist.py b/packages/core/src/repowise/core/pipeline/persist.pyindex 12106d890..cb5bf3f1a 100644--- a/packages/core/src/repowise/core/pipeline/persist.py+++ b/packages/core/src/repowise/core/pipeline/persist.py@@ -1121,6 +1121,7 @@ async def prune_deleted_file_rows(# partial dead-code analysis has already loaded the module (13.7 ms when# it has not, measured cold after the CLI modules are up).from repowise.core.analysis.dead_code.analyzer import _is_synthetic_node+ from repowise.core.persistence.crud.analysis.function_facts import delete_file_rowsfrom repowise.core.persistence.models import (DeadCodeFinding,DocDriftFinding,@@ -1218,6 +1219,8 @@ async def prune_deleted_file_rows(await _prune_table(WikiSymbol, WikiSymbol.file_path, "wiki_symbols")await _prune_table(SecurityFinding, SecurityFinding.file_path, "security_findings")await _prune_table(DeadCodeFinding, DeadCodeFinding.file_path, "dead_code_findings")+ # Keyed on the symbol: a deleted file's rows are one key range of the id.+ await delete_file_rows(session, repo_id, dead_paths)# Keyed on the DOCUMENT. The incremental drift pass scopes its write to the# documents it read, so a deleted one is never in scope and its rows would# outlive the file without this. ``_FileLiveness`` asks disk and@@ -1911,6 +1914,7 @@ async def save_full_health_report(save_health_findings,save_health_metrics,save_refactoring_suggestions,+ write_function_facts,)hr = health_report@@ -1959,6 +1963,12 @@ async def save_full_health_report(# savepoint because it composes over the stored rows, so it has to see# the reconciliation above rather than the detector output.await finalize_refactoring_opportunities(session, repo_id, analyzed_commit=analyzed_commit)+ # No rows means no graph to key them on: the stored ones stay.+ fact_rows = getattr(hr, "function_facts", None)+ if fact_rows is not None:+ await write_function_facts(+ session, repo_id, fact_rows, roles=getattr(hr, "execution_roles", None)+ )async def refresh_governance_findings(diff --git a/tests/unit/health/test_function_facts_store.py b/tests/unit/health/test_function_facts_store.pynew file mode 100644index 000000000..77e3be294--- /dev/null+++ b/tests/unit/health/test_function_facts_store.py@@ -0,0 +1,247 @@+"""The per-function store: facts counted on the complexity walk, roles restamped every run."""++from __future__ import annotations++import json+from pathlib import Path++import networkx as nx+import pytest+from sqlalchemy import select++from repowise.core.analysis.execution_roles import ExecutionRoles+from repowise.core.analysis.health import HealthAnalyzer+from repowise.core.analysis.health.complexity.walker import walk_file+from repowise.core.analysis.health.dataflow import FunctionFacts++_PY = b'''+class Store:+ async def save(self, rows):+ if not rows:+ return 0+ await flush()+ self.count = len(rows)+ self.cache[rows[0]] = 1+ return self.count++ def each(self):+ for row in self.rows:+ yield row+++def plain(a):+ if a:+ raise ValueError(a)+ return a+'''++_TS = b"""class Counter { bump() { if (this.off) return; this.n++; return this.n; } }+async function load() { await fetch("x"); throw new Error("no"); }+function* ids() { yield 1; }+"""+++def _facts(path: str, language: str, source: bytes) -> dict[str, FunctionFacts | None]:+ return {fc.name: fc.facts for fc in walk_file(path, language, source).functions}+++def test_the_walk_reads_whole_function_facts_in_python() -> None:+ facts = _facts("store.py", "python", _PY)+ assert facts["save"] == FunctionFacts(+ awaits=True,+ is_generator=False,+ uses_receiver=True,+ receiver_assigns=("cache", "count"),+ early_exits=1,+ )+ assert facts["each"] == FunctionFacts(False, True, True, (), 0)+ assert facts["plain"] == FunctionFacts(False, False, False, (), 1)+++def test_the_walk_reads_whole_function_facts_in_typescript() -> None:+ facts = _facts("counter.ts", "typescript", _TS)+ assert facts["bump"] == FunctionFacts(False, False, True, ("n",), 1)+ assert facts["load"] == FunctionFacts(True, False, False, (), 0)+ assert facts["ids"] is not None and facts["ids"].is_generator+++class _File:+ def __init__(self, path: str, *, is_test: bool = False) -> None:+ self.file_info = type("FI", (), {"path": path, "is_test": is_test})()+++def test_fact_rows_are_keyed_on_the_graph_symbol_and_skip_tests() -> None:+ fcx = walk_file("store.py", "python", _PY)+ graph = nx.DiGraph()+ for fc in fcx.functions:+ graph.add_node(+ f"store.py::{fc.name}",+ node_type="symbol",+ kind="function",+ name=fc.name,+ file_path="store.py",+ start_line=fc.start_line,+ end_line=fc.end_line,+ )+ analyzer = HealthAnalyzer(graph)+ rows = analyzer._function_fact_rows([(_File("store.py"), fcx)])+ assert analyzer._function_fact_rows([(_File("tests/test_store.py", is_test=True), fcx)]) == []+ # No graph: no rows to key, so the writers keep what is stored.+ assert HealthAnalyzer(None)._function_fact_rows([(_File("store.py"), fcx)]) is None+ by_id = {row["symbol_id"]: row for row in rows}+ assert set(by_id) == {"store.py::save", "store.py::each", "store.py::plain"}+ assert by_id["store.py::save"]["receiver_assigns"] == ("cache", "count")+ assert by_id["store.py::save"]["receiver_assigns_known"] is True+++async def store(tmp_path: Path):+ from repowise.core.persistence import (+ create_engine,+ create_session_factory,+ get_session,+ init_db,+ upsert_repository,+ )++ engine = create_engine(f"sqlite+aiosqlite:///{(tmp_path / 'wiki.db').as_posix()}")+ try:+ await init_db(engine)+ async with get_session(create_session_factory(engine)) as session:+ repo = await upsert_repository(session, name="repo", local_path=str(tmp_path))+ await session.commit()+ yield session, repo.id+ finally:+ await engine.dispose()+++def _row(symbol: str, **facts) -> dict:+ return {"symbol_id": symbol, **facts}+++async def _stored(session, repository_id: str) -> dict[str, tuple]:+ from repowise.core.persistence.models import FunctionFact++ result = await session.execute(+ select(+ FunctionFact.symbol_id,+ FunctionFact.execution_role,+ FunctionFact.awaits,+ FunctionFact.receiver_assigns_known,+ FunctionFact.receiver_assigns_json,+ ).where(FunctionFact.repository_id == repository_id)+ )+ return {row[0]: tuple(row[1:]) for row in result.all()}+++async def test_facts_rewrite_walked_files_and_roles_restamp_every_row(store) -> None:+ from repowise.core.persistence.crud import get_function_facts, write_function_facts++ session, repo = store+ roles = ExecutionRoles({"a.py::f": "request", "b.py::g": "cli"})+ written = await write_function_facts(+ session,+ repo,+ [+ _row("a.py::f", awaits=True, receiver_assigns=("n",), receiver_assigns_known=True),+ _row("b.py::g", awaits=False, receiver_assigns=None, receiver_assigns_known=False),+ _row("a.py::h", awaits=False, receiver_assigns=(), receiver_assigns_known=True),+ # A second walked function resolving to the same symbol: the first keeps it.+ _row("b.py::g", awaits=True),+ ],+ roles=roles,+ )+ assert written == 3+ # Unknown and none both store no list; the flag tells them apart.+ assert await _stored(session, repo) == {+ "a.py::f": ("request", True, True, json.dumps(["n"])),+ "a.py::h": ("unknown", False, True, None),+ "b.py::g": ("cli", False, False, None),+ }++ # An update that walked only a.py: b.py keeps its facts, and its role moves+ # because a seed moved elsewhere.+ await write_function_facts(+ session,+ repo,+ [_row("a.py::f", awaits=False, receiver_assigns_known=False)],+ # A Windows path names the same file.+ file_paths={"a.py"},+ roles=ExecutionRoles({"a.py::f": "request", "b.py::g": "request"}),+ )+ assert await _stored(session, repo) == {+ "a.py::f": ("request", False, False, None),+ "b.py::g": ("request", False, False, None),+ }+ # A walked file whose function is gone loses its row.+ await write_function_facts(session, repo, [], file_paths={"a.py"}, roles=None)+ assert set(await get_function_facts(session, repo, ["a.py::f", "b.py::g"])) == {"b.py::g"}+++def test_facts_ignore_what_a_lambda_or_nested_function_does() -> None:+ source = b"""+class C:+ async def outer(self):+ def inner():+ yield 1+ f = lambda: self.touch()+ return [x async for x in y]+"""+ facts = _facts("nest.py", "python", source)["outer"]+ assert facts is not None+ assert (facts.is_generator, facts.early_exits) == (False, 0)+ # A lambda shares the instance, so its receiver use counts.+ assert facts.uses_receiver is True+++def test_a_windows_path_selects_the_same_rows() -> None:+ from repowise.core.persistence.crud.analysis.function_facts import key_range++ assert key_range(r"pkg\a.py") == key_range("pkg/a.py") == ("pkg/a.py::", "pkg/a.py:;")+++async def test_many_files_are_deleted_in_chunked_statements(store) -> None:+ """More files than one statement holds: every one goes, nothing else does."""+ from repowise.core.persistence.crud import write_function_facts++ session, repo = store+ paths = [f"pkg/m{i:04d}.py" for i in range(450)]+ rows = [_row(f"{path}::f") for path in paths] + [_row("keep/a.py::f"), _row("pkg/m0000.pyi::f")]+ await write_function_facts(session, repo, rows)+ statements: list[str] = []+ real = session.execute++ async def counting(statement, *args, **kwargs):+ statements.append(str(statement))+ return await real(statement, *args, **kwargs)++ session.execute = counting+ try:+ await write_function_facts(session, repo, [], file_paths=paths)+ finally:+ del session.execute+ assert sum(text.startswith("DELETE") for text in statements) == 3+ assert set(await _stored(session, repo)) == {"keep/a.py::f", "pkg/m0000.pyi::f"}+++def test_an_expression_body_is_counted() -> None:+ """``() => expr`` has no statements: the body node itself is what is read."""+ source = b"const f = async () => await g();\nconst h = () => this.x = 1;\n"+ facts = _facts("expr.ts", "typescript", source)+ assert facts["f"] is not None and facts["f"].awaits is True+ assert facts["h"] is not None and facts["h"].receiver_assigns == ("x",)+++def test_an_exit_macro_is_an_early_exit() -> None:+ source = b"""fn check(x: i32) -> Result<(), E> {+ if x < 0 { bail!("negative"); }+ if x > 9 { return Err(E); }+ Ok(())+}+fn tail() -> Result<(), E> {+ bail!("always");+}+"""+ facts = _facts("check.rs", "rust", source)+ assert facts["check"] is not None and facts["check"].early_exits == 2+ assert facts["tail"] is not None and facts["tail"].early_exits == 0diff --git a/tests/unit/persistence/test_models.py b/tests/unit/persistence/test_models.pyindex aa7078504..98a5adac8 100644--- a/tests/unit/persistence/test_models.py+++ b/tests/unit/persistence/test_models.py@@ -331,6 +331,7 @@ def test_base_includes_all_models():"refactoring_summaries","performance_opportunities","performance_summaries",+ "function_facts","coverage_files","coverage_ingests","action_states",diff --git a/tests/unit/persistence/test_prune_deleted_files.py b/tests/unit/persistence/test_prune_deleted_files.pyindex 5572a6708..63b811024 100644--- a/tests/unit/persistence/test_prune_deleted_files.py+++ b/tests/unit/persistence/test_prune_deleted_files.py@@ -244,3 +244,21 @@ async def test_prune_is_scoped_to_one_repo(async_session, repo_with_kept_file):STALE,KEPT,}+++async def test_function_facts_of_a_deleted_file_are_pruned(async_session, repo_with_kept_file):+ """Keyed on the symbol, so the rows go with the deleted file's graph nodes."""+ from repowise.core.persistence.crud import write_function_facts+ from repowise.core.persistence.models import FunctionFact++ repo = await insert_repo(async_session)+ await _seed(async_session, repo.id)+ await write_function_facts(+ async_session, repo.id, [{"symbol_id": f"{KEPT}::main"}, {"symbol_id": f"{STALE}::gone"}]+ )+ await prune_deleted_file_rows(async_session, repo.id, repo_with_kept_file, live_hint={KEPT})+ await async_session.commit()++ assert await _paths(async_session, FunctionFact, FunctionFact.symbol_id, repo.id) == {+ f"{KEPT}::main"+ }