Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(health): add intra-procedural CFG core for flagged functions (#612)

Raghav Chamadiya112c0976e56c
diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/__init__.py b/packages/core/src/repowise/core/analysis/health/dataflow/__init__.py
new file mode 100644
index 000000000..7f7bfaf0e
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/dataflow/__init__.py
@@ -0,0 +1,46 @@
+"""Intra-procedural dataflow layer for the health pass.
+
+This subpackage builds a per-function control-flow graph (CFG) as the
+foundation for dataflow-aware refactoring signals (Extract Method) and the
+later def/use + reaching-definitions passes. It is deliberately standalone:
+nothing here is wired into the health engine yet, so the layer can be built
+and measured in isolation before it joins a hot path.
+
+**Performance contract (load-bearing).** A CFG is built ONLY for a function a
+structural biomarker already flagged (``large_method`` / ``brain_method`` /
+``complex_method``). The pass takes a pre-filtered flagged-function set, never
+the full function corpus -- see :func:`gating.is_flagged_function` and
+:func:`gating.build_cfgs_for_file`. Building for every function could add a
+double-digit percentage to the parse/walk layer, so we never do. A size guard
+caps pathological functions (emit nothing past the cap), and any per-function
+failure degrades to silence (no CFG, no raise).
+
+Phase scope: Python only. The CFG builder is structural and largely
+language-agnostic; the jump-node classification it relies on is Python-specific
+for now and generalises behind a dialect in a later phase.
+"""
+
+from __future__ import annotations
+
+from .cfg import CFG, BasicBlock, Statement, build_cfg
+from .gating import (
+ CFGPassStats,
+ FileCFGResult,
+ FunctionCFG,
+ build_cfgs_for_file,
+ is_flagged,
+ is_flagged_function,
+)
+
+__all__ = [
+ "CFG",
+ "BasicBlock",
+ "CFGPassStats",
+ "FileCFGResult",
+ "FunctionCFG",
+ "Statement",
+ "build_cfg",
+ "build_cfgs_for_file",
+ "is_flagged",
+ "is_flagged_function",
+]
diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/cfg.py b/packages/core/src/repowise/core/analysis/health/dataflow/cfg.py
new file mode 100644
index 000000000..283202c4a
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/dataflow/cfg.py
@@ -0,0 +1,430 @@
+"""Control-flow graph construction for a single function (Python).
+
+Three stages, all in one structural pass:
+
+1. **Statement sequencer** -- a function body's named children become an
+ ordered statement list. Tree-sitter exposes these; nothing materialises
+ them today.
+2. **Basic-block splitter** -- the statement list is partitioned at branch /
+ loop / exception boundaries (classified by the existing ``branch_kinds`` /
+ ``loop_kinds`` / ``try_kinds`` / ``catch_kinds`` on ``LanguageNodeMap``).
+3. **CFG builder** -- straight-line ``BasicBlock`` objects joined by
+ successor / predecessor edges, with loop back-edges, branch join points,
+ and synthetic entry / exit blocks.
+
+The construction is *structured*: Python control flow nests cleanly (no
+``goto``), so the graph is built recursively from the AST rather than from a
+flat instruction stream with a leader scan. Each compound statement closes the
+current straight-line block, builds its sub-structure, and the builder threads
+a single fall-through block through to whatever follows.
+
+**Determinism.** Blocks are emitted in a fixed pre-order (test block, then
+then-branch, then alternatives, then the join; loop header, then body, then the
+exit). Edge lists are appended in that order and de-duplicated. The same source
+therefore yields byte-identical block ids and edges across runs -- a
+prerequisite for stable trends and cache hits downstream.
+
+**Language scope.** The block-structure logic is language-agnostic over
+``LanguageNodeMap``; only the jump classification (``return`` / ``raise`` /
+``break`` / ``continue``) is Python-specific in this phase. A later phase lifts
+that into a per-language dialect alongside the other ``DefUseDialect`` work.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import TYPE_CHECKING
+
+from ..complexity.languages import LanguageNodeMap
+
+if TYPE_CHECKING:
+ from tree_sitter import Node
+
+# Python jump node types. The layer is Python-only for now; a later pass generalises
+# these behind a dialect (mirroring ``perf/dialects/`` and the ``DefUseDialect``
+# pattern). Each set degrades to "no special handling" for a language that does
+# not map it -- the statement is then recorded as a plain straight-line node.
+_RETURN_KINDS: frozenset[str] = frozenset({"return_statement"})
+_RAISE_KINDS: frozenset[str] = frozenset({"raise_statement"})
+_BREAK_KINDS: frozenset[str] = frozenset({"break_statement"})
+_CONTINUE_KINDS: frozenset[str] = frozenset({"continue_statement"})
+
+# Upper bound on basic blocks per function. A structured CFG has roughly one
+# block per branch/loop arm, so a few hundred is already an extreme function;
+# the cap is a backstop against pathological generated code, not a real limit.
+# Tripping it returns no CFG for that function (degrade-to-silence).
+_DEFAULT_MAX_BLOCKS = 5000
+
+
+class CFGGuardTrippedError(Exception):
+ """Raised internally when a function exceeds the basic-block cap.
+
+ Caught at the harness boundary (:mod:`gating`) so the function is skipped
+ with no CFG and no finding, never propagated to the caller.
+ """
+
+
+@dataclass(frozen=True)
+class Statement:
+ """One statement (or a compound statement's head) within a basic block.
+
+ ``kind`` is the tree-sitter node type. For a compound construct that opens
+ a block (``if`` / ``while`` / ``for``), only its *head* -- the condition or
+ loop clause -- is recorded here; the body lives in successor blocks.
+ """
+
+ kind: str
+ start_line: int # 1-indexed
+ end_line: int # 1-indexed
+
+
+@dataclass
+class BasicBlock:
+ """A maximal straight-line run of statements with a single entry/exit.
+
+ ``kind`` labels the block's role so consumers (and tests) can reason about
+ shape without re-deriving it:
+
+ - ``entry`` / ``exit`` -- the synthetic function boundaries (no statements).
+ - ``normal`` -- a straight-line run.
+ - ``branch`` -- ends in a condition test with two successors.
+ - ``loop_header`` -- a loop's test; one edge into the body, one past it,
+ and a back-edge predecessor from the body tail.
+ - ``loop_exit`` -- the join immediately after a loop.
+ - ``join`` -- a merge point after an ``if`` / ``try``.
+ - ``handler`` -- an ``except`` clause entry.
+ - ``unreachable`` -- a block with no predecessor, created for statements
+ that follow a terminator within the same sequence (dead code).
+ """
+
+ id: int
+ kind: str = "normal"
+ statements: list[Statement] = field(default_factory=list)
+ successors: list[int] = field(default_factory=list)
+ predecessors: list[int] = field(default_factory=list)
+
+ @property
+ def start_line(self) -> int:
+ return min((s.start_line for s in self.statements), default=0)
+
+ @property
+ def end_line(self) -> int:
+ return max((s.end_line for s in self.statements), default=0)
+
+ @property
+ def is_empty(self) -> bool:
+ return not self.statements
+
+
+@dataclass
+class CFG:
+ """A single function's control-flow graph.
+
+ ``blocks`` is ordered by id (emission order). ``entry_id`` / ``exit_id``
+ are the synthetic boundary blocks; every path from entry that does not
+ diverge into an infinite loop reaches exit.
+ """
+
+ blocks: list[BasicBlock]
+ entry_id: int
+ exit_id: int
+ function_name: str = ""
+ function_start_line: int = 0
+
+ def __post_init__(self) -> None:
+ self._by_id: dict[int, BasicBlock] = {b.id: b for b in self.blocks}
+
+ @property
+ def entry(self) -> BasicBlock:
+ return self._by_id[self.entry_id]
+
+ @property
+ def exit(self) -> BasicBlock:
+ return self._by_id[self.exit_id]
+
+ def block(self, block_id: int) -> BasicBlock:
+ return self._by_id[block_id]
+
+ def successors(self, block: BasicBlock) -> list[BasicBlock]:
+ return [self._by_id[s] for s in block.successors]
+
+ def predecessors(self, block: BasicBlock) -> list[BasicBlock]:
+ return [self._by_id[p] for p in block.predecessors]
+
+ def reachable_ids(self) -> set[int]:
+ """Block ids reachable from entry (forward BFS)."""
+ seen: set[int] = set()
+ stack = [self.entry_id]
+ while stack:
+ bid = stack.pop()
+ if bid in seen:
+ continue
+ seen.add(bid)
+ stack.extend(self._by_id[bid].successors)
+ return seen
+
+ def back_edges(self) -> list[tuple[int, int]]:
+ """Edges ``(src, dst)`` where ``dst`` is a loop header re-entered from
+ within its own body -- the loop back-edges, in id order."""
+ out: list[tuple[int, int]] = []
+ for b in self.blocks:
+ if b.kind != "loop_header":
+ continue
+ out.extend((p, b.id) for p in sorted(b.predecessors) if p > b.id)
+ return out
+
+
+@dataclass
+class _LoopCtx:
+ """Jump targets for ``break`` / ``continue`` within the enclosing loop."""
+
+ continue_target: BasicBlock # loop header (the back-edge destination)
+ break_target: BasicBlock # the block past the loop
+
+
+class _CFGBuilder:
+ """Recursive structured-CFG builder over one function's AST.
+
+ The public entry is :func:`build_cfg`; this class holds the per-build
+ mutable state (the block list, the id counter, and the loop-target stack).
+ """
+
+ def __init__(self, lmap: LanguageNodeMap, *, max_blocks: int) -> None:
+ self.lmap = lmap
+ self.max_blocks = max_blocks
+ self.blocks: list[BasicBlock] = []
+ self._next_id = 0
+ self._loops: list[_LoopCtx] = []
+ self.exit_block: BasicBlock | None = None
+
+ # -- low-level graph ops --------------------------------------------------
+
+ def _new(self, kind: str = "normal") -> BasicBlock:
+ if self._next_id >= self.max_blocks:
+ raise CFGGuardTrippedError(self._next_id)
+ block = BasicBlock(id=self._next_id, kind=kind)
+ self._next_id += 1
+ self.blocks.append(block)
+ return block
+
+ @staticmethod
+ def _edge(src: BasicBlock | None, dst: BasicBlock | None) -> None:
+ if src is None or dst is None:
+ return
+ if dst.id not in src.successors:
+ src.successors.append(dst.id)
+ if src.id not in dst.predecessors:
+ dst.predecessors.append(src.id)
+
+ def _record_stmt(self, block: BasicBlock, node: Node) -> None:
+ block.statements.append(
+ Statement(node.type, node.start_point[0] + 1, node.end_point[0] + 1)
+ )
+
+ def _record_head(self, block: BasicBlock, node: Node) -> None:
+ """Record a compound statement's head (its condition / loop clause)."""
+ cond = node.child_by_field_name("condition")
+ line = node.start_point[0] + 1
+ end = (cond.end_point[0] + 1) if cond is not None else line
+ block.statements.append(Statement(node.type, line, end))
+
+ # -- block / clause access ------------------------------------------------
+
+ @staticmethod
+ def _block_of(node: Node | None) -> Node | None:
+ """The ``block`` body of a clause (``consequence`` / ``body`` field, or
+ the first child of type ``block`` for clauses with no body field)."""
+ if node is None:
+ return None
+ body = node.child_by_field_name("consequence") or node.child_by_field_name("body")
+ if body is not None:
+ return body
+ for child in node.children:
+ if child.type == "block":
+ return child
+ return None
+
+ @staticmethod
+ def _body_stmts(block: Node | None) -> list[Node]:
+ if block is None:
+ return []
+ return [c for c in block.named_children]
+
+ # -- the recursive walk ---------------------------------------------------
+
+ def build(self, fn_node: Node) -> CFG:
+ entry = self._new("entry")
+ self.exit_block = self._new("exit")
+ body = fn_node.child_by_field_name("body") or fn_node
+ first = self._new()
+ self._edge(entry, first)
+ out = self._process_seq(self._body_stmts(body), first)
+ if out is not None:
+ self._edge(out, self.exit_block)
+ return CFG(blocks=self.blocks, entry_id=entry.id, exit_id=self.exit_block.id)
+
+ def _process_seq(self, stmts: list[Node], cur: BasicBlock | None) -> BasicBlock | None:
+ """Thread *stmts* onto *cur*, returning the fall-through block.
+
+ Returns ``None`` when control cannot fall through (the sequence ended
+ in a terminator on every path). Compound statements close *cur* and the
+ builder continues from the construct's join block.
+ """
+ assert self.exit_block is not None
+ for st in stmts:
+ if cur is None:
+ # Statements after a terminator: dead code with no predecessor.
+ # Captured in an ``unreachable`` block so the statement is not
+ # silently dropped, but it is reachable from nothing.
+ cur = self._new("unreachable")
+ t = st.type
+ if t == "if_statement":
+ cur = self._build_if(st, cur)
+ elif t in self.lmap.loop_kinds:
+ cur = self._build_loop(st, cur)
+ elif t in self.lmap.try_kinds:
+ cur = self._build_try(st, cur)
+ elif t in _RETURN_KINDS or t in _RAISE_KINDS:
+ self._record_stmt(cur, st)
+ self._edge(cur, self.exit_block)
+ cur = None
+ elif t in _BREAK_KINDS:
+ self._record_stmt(cur, st)
+ if self._loops:
+ self._edge(cur, self._loops[-1].break_target)
+ cur = None
+ elif t in _CONTINUE_KINDS:
+ self._record_stmt(cur, st)
+ if self._loops:
+ self._edge(cur, self._loops[-1].continue_target)
+ cur = None
+ else:
+ self._record_stmt(cur, st)
+ return cur
+
+ def _build_if(self, if_node: Node, cur: BasicBlock) -> BasicBlock:
+ cur.kind = "branch"
+ self._record_head(cur, if_node)
+ join = self._new("join")
+
+ # then-branch
+ then_entry = self._new()
+ self._edge(cur, then_entry)
+ then_out = self._process_seq(
+ self._body_stmts(if_node.child_by_field_name("consequence")), then_entry
+ )
+ if then_out is not None:
+ self._edge(then_out, join)
+
+ # elif / else chain. Each ``elif`` hangs off the previous test's false
+ # edge as a nested branch; ``else`` consumes the final false edge.
+ alts = [c for c in if_node.children if c.type in ("elif_clause", "else_clause")]
+ false_src: BasicBlock | None = cur
+ for alt in alts:
+ if alt.type == "elif_clause":
+ elif_test = self._new("branch")
+ self._record_head(elif_test, alt)
+ self._edge(false_src, elif_test)
+ elif_entry = self._new()
+ self._edge(elif_test, elif_entry)
+ elif_out = self._process_seq(
+ self._body_stmts(alt.child_by_field_name("consequence")), elif_entry
+ )
+ if elif_out is not None:
+ self._edge(elif_out, join)
+ false_src = elif_test
+ else: # else_clause
+ else_entry = self._new()
+ self._edge(false_src, else_entry)
+ else_out = self._process_seq(self._body_stmts(self._block_of(alt)), else_entry)
+ if else_out is not None:
+ self._edge(else_out, join)
+ false_src = None
+
+ # No ``else``: the last test's false edge falls straight through.
+ if false_src is not None:
+ self._edge(false_src, join)
+ return join
+
+ def _build_loop(self, loop_node: Node, cur: BasicBlock) -> BasicBlock:
+ header = self._new("loop_header")
+ self._record_head(header, loop_node)
+ self._edge(cur, header)
+ after = self._new("loop_exit")
+
+ body_entry = self._new()
+ self._edge(header, body_entry) # enter the loop body
+ self._edge(header, after) # skip / exhaust the loop
+
+ self._loops.append(_LoopCtx(continue_target=header, break_target=after))
+ body_out = self._process_seq(
+ self._body_stmts(loop_node.child_by_field_name("body")), body_entry
+ )
+ self._loops.pop()
+
+ if body_out is not None:
+ self._edge(body_out, header) # back-edge
+ return after
+
+ def _build_try(self, try_node: Node, cur: BasicBlock) -> BasicBlock:
+ join = self._new("join")
+
+ # ``finally`` is the convergence point everything funnels through; with
+ # no ``finally`` the join itself is that point.
+ finally_clause = next((c for c in try_node.children if c.type == "finally_clause"), None)
+ normal_join: BasicBlock = join
+ if finally_clause is not None:
+ fin_entry = self._new()
+ fin_out = self._process_seq(self._body_stmts(self._block_of(finally_clause)), fin_entry)
+ if fin_out is not None:
+ self._edge(fin_out, join)
+ normal_join = fin_entry
+
+ # try body (the protected region)
+ body_entry = self._new()
+ self._edge(cur, body_entry)
+ body_out = self._process_seq(
+ self._body_stmts(try_node.child_by_field_name("body")), body_entry
+ )
+
+ # ``else`` runs only when the body completed without an exception.
+ else_clause = next((c for c in try_node.children if c.type == "else_clause"), None)
+ if else_clause is not None and body_out is not None:
+ else_entry = self._new()
+ self._edge(body_out, else_entry)
+ else_out = self._process_seq(self._body_stmts(self._block_of(else_clause)), else_entry)
+ if else_out is not None:
+ self._edge(else_out, normal_join)
+ elif body_out is not None:
+ self._edge(body_out, normal_join)
+
+ # except handlers are reachable from the protected region (an exception
+ # may escape any statement in the body -> approximate with an edge from
+ # the body entry to each handler).
+ for handler in (c for c in try_node.children if c.type in self.lmap.catch_kinds):
+ handler_entry = self._new("handler")
+ self._edge(body_entry, handler_entry)
+ handler_out = self._process_seq(
+ self._body_stmts(self._block_of(handler)), handler_entry
+ )
+ if handler_out is not None:
+ self._edge(handler_out, normal_join)
+
+ return join
+
+
+def build_cfg(
+ fn_node: Node,
+ lmap: LanguageNodeMap,
+ *,
+ max_blocks: int = _DEFAULT_MAX_BLOCKS,
+) -> CFG:
+ """Build the control-flow graph for one function AST node.
+
+ *fn_node* is a function/method definition node (the kind
+ ``_collect_function_nodes`` yields); *lmap* is its language's
+ ``LanguageNodeMap``. Raises :class:`CFGGuardTrippedError` if the function
+ exceeds *max_blocks* -- callers building over a corpus should catch it and
+ skip the function (the :mod:`gating` harness does).
+ """
+ return _CFGBuilder(lmap, max_blocks=max_blocks).build(fn_node)
diff --git a/packages/core/src/repowise/core/analysis/health/dataflow/gating.py b/packages/core/src/repowise/core/analysis/health/dataflow/gating.py
new file mode 100644
index 000000000..d55027699
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/health/dataflow/gating.py
@@ -0,0 +1,174 @@
+"""Flagged-only gating + the file-level CFG harness.
+
+The performance contract of the whole dataflow layer lives here. A CFG is
+built **only** for a function that a structural biomarker already flagged --
+``large_method`` (``nloc >= 60`` with some branching), ``complex_method``
+(``ccn >= 9``), or ``brain_method`` (``nloc >= 70`` and ``ccn >= 9``, plus a
+centrality gate the engine applies separately). The thresholds are imported
+from the biomarker detectors so the gate never drifts from them.
+
+:func:`build_cfgs_for_file` is the harness: it parses a file once, computes the
+two cheap metrics the gate needs (``ccn`` and ``nloc``) per function reusing
+the complexity walker's passes, and builds a CFG for the flagged subset only.
+The :class:`CFGPassStats` it returns records ``functions_seen`` vs
+``functions_built`` so a budget test can assert the pass never runs for an
+un-flagged function. Any parse failure or per-function error degrades to
+silence -- an empty result, never a raise.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+
+import structlog
+
+from ..biomarkers.complex_method import ComplexMethodDetector
+from ..biomarkers.large_method import LargeMethodDetector
+from ..complexity.ast_utils import _collect_function_nodes, _find_function_entry_name
+from ..complexity.cyclomatic import _walk_function_body
+from ..complexity.languages import get_language_map
+from ..complexity.nloc import _count_nloc
+from .cfg import CFG, CFGGuardTrippedError, build_cfg
+
+log = structlog.get_logger(__name__)
+
+# Pulled from the biomarker detectors so the gate stays in lockstep with the
+# flags it mirrors. ``complex_method`` (ccn >= 9) already subsumes the
+# ``brain_method`` ccn condition, so the predicate needs only these two shapes.
+_COMPLEX_CCN = ComplexMethodDetector._CCN_THRESHOLD # 9
+_LARGE_NLOC = LargeMethodDetector._NLOC_THRESHOLD # 60
+_LARGE_CCN_FLOOR = LargeMethodDetector._CCN_FLOOR # 2
+
+
+def is_flagged(*, ccn: int, nloc: int) -> bool:
+ """True if a function with these metrics is flagged by a structural smell.
+
+ The union of the size/complexity biomarker triggers:
+
+ - ``complex_method`` -- ``ccn >= 9`` (also covers ``brain_method``'s ccn).
+ - ``large_method`` -- ``nloc >= 60`` with at least one branch (``ccn >= 2``).
+ """
+ if ccn >= _COMPLEX_CCN:
+ return True
+ return nloc >= _LARGE_NLOC and ccn >= _LARGE_CCN_FLOOR
+
+
+def is_flagged_function(fc) -> bool:
+ """:func:`is_flagged` over a walker ``FunctionComplexity`` record.
+
+ ``fc`` is a ``complexity.models.FunctionComplexity``; it is untyped here to
+ keep this leaf module free of a walker-models import.
+ """
+ return is_flagged(ccn=fc.ccn, nloc=fc.nloc)
+
+
+@dataclass
+class CFGPassStats:
+ """Counters proving the flagged-only gate held for one file.
+
+ ``functions_seen`` is every function the parse discovered;
+ ``functions_built`` is the flagged subset a CFG was actually built for.
+ ``guard_tripped`` counts functions skipped by the size cap. The budget test
+ asserts ``functions_built`` equals the flagged count, never the total.
+ """
+
+ functions_seen: int = 0
+ functions_built: int = 0
+ guard_tripped: int = 0
+
+
+@dataclass
+class FunctionCFG:
+ """A flagged function paired with its control-flow graph."""
+
+ name: str
+ start_line: int # 1-indexed
+ end_line: int # 1-indexed
+ ccn: int
+ nloc: int
+ cfg: CFG
+
+
+@dataclass
+class FileCFGResult:
+ """The CFGs built for one file's flagged functions, plus the pass stats."""
+
+ functions: list[FunctionCFG] = field(default_factory=list)
+ stats: CFGPassStats = field(default_factory=CFGPassStats)
+
+
+def build_cfgs_for_file(
+ abs_path: str,
+ language: str,
+ source: bytes,
+ *,
+ flagged_only: bool = True,
+) -> FileCFGResult:
+ """Parse *source* once and build a CFG for each flagged function.
+
+ Returns an empty result (never raises) when the language is unsupported,
+ the tree-sitter pack is missing, or parsing fails. ``flagged_only=False``
+ is a test/measurement escape hatch that builds for every function; the
+ default and the only production-intended mode is ``True``.
+ """
+ result = FileCFGResult()
+ lmap = get_language_map(language)
+ if lmap is None:
+ return result
+
+ try:
+ from tree_sitter import Parser
+
+ from repowise.core.ingestion.parser import _get_language
+ except Exception as exc:
+ log.debug("dataflow_cfg_import_failed", error=str(exc))
+ return result
+
+ grammar = _get_language(language)
+ if grammar is None:
+ return result
+
+ try:
+ parser = Parser(grammar)
+ tree = parser.parse(source)
+ except Exception as exc:
+ log.debug("dataflow_cfg_parse_failed", path=abs_path, error=str(exc))
+ return result
+
+ for fn_node in _collect_function_nodes(tree.root_node, lmap):
+ result.stats.functions_seen += 1
+ body = fn_node.child_by_field_name("body") or fn_node
+ try:
+ ccn, _max_nest, _cog, _bumps, _conds = _walk_function_body(body, lmap)
+ nloc = _count_nloc(body, source)
+ except Exception as exc:
+ log.debug("dataflow_cfg_metrics_failed", path=abs_path, error=str(exc))
+ continue
+
+ if flagged_only and not is_flagged(ccn=ccn, nloc=nloc):
+ continue
+
+ try:
+ cfg = build_cfg(fn_node, lmap)
+ except CFGGuardTrippedError:
+ result.stats.guard_tripped += 1
+ continue
+ except Exception as exc:
+ log.debug("dataflow_cfg_build_failed", path=abs_path, error=str(exc))
+ continue
+
+ cfg.function_name = _find_function_entry_name(fn_node, lmap)
+ cfg.function_start_line = fn_node.start_point[0] + 1
+ result.stats.functions_built += 1
+ result.functions.append(
+ FunctionCFG(
+ name=cfg.function_name,
+ start_line=cfg.function_start_line,
+ end_line=fn_node.end_point[0] + 1,
+ ccn=ccn,
+ nloc=nloc,
+ cfg=cfg,
+ )
+ )
+
+ return result
diff --git a/tests/unit/health/test_dataflow_cfg.py b/tests/unit/health/test_dataflow_cfg.py
new file mode 100644
index 000000000..73f7d96ea
--- /dev/null
+++ b/tests/unit/health/test_dataflow_cfg.py
@@ -0,0 +1,401 @@
+"""Unit tests for the dataflow CFG core.
+
+Best-effort like the complexity-walker tests: tree-sitter language packs may
+not be installed in every CI lane, so each test skips when the Python pack is
+missing rather than failing.
+"""
+
+from __future__ import annotations
+
+import textwrap
+
+import pytest
+
+from repowise.core.analysis.health.complexity.ast_utils import _collect_function_nodes
+from repowise.core.analysis.health.complexity.languages import get_language_map
+from repowise.core.analysis.health.dataflow import (
+ BasicBlock,
+ build_cfg,
+ build_cfgs_for_file,
+ is_flagged,
+)
+from repowise.core.analysis.health.dataflow.cfg import CFGGuardTrippedError
+
+
+def _require_python() -> None:
+ try:
+ from repowise.core.ingestion.parser import _get_language
+ except Exception:
+ pytest.skip("tree-sitter language pack missing for python")
+ if _get_language("python") is None:
+ pytest.skip("tree-sitter language pack missing for python")
+
+
+def _first_fn(src: str):
+ """Parse *src* and return ``(function_node, lmap)`` for the first function."""
+ _require_python()
+ from tree_sitter import Parser
+
+ from repowise.core.ingestion.parser import _get_language
+
+ lmap = get_language_map("python")
+ parser = Parser(_get_language("python"))
+ tree = parser.parse(textwrap.dedent(src).encode())
+ nodes = _collect_function_nodes(tree.root_node, lmap)
+ assert nodes, "no function node parsed"
+ return nodes[0], lmap
+
+
+def _cfg(src: str):
+ fn_node, lmap = _first_fn(src)
+ return build_cfg(fn_node, lmap)
+
+
+def _by_kind(cfg, kind: str) -> list[BasicBlock]:
+ return [b for b in cfg.blocks if b.kind == kind]
+
+
+# -- straight-line --------------------------------------------------------------
+
+
+def test_straight_line_single_path():
+ cfg = _cfg(
+ """
+ def f():
+ a = 1
+ b = 2
+ c = a + b
+ print(c)
+ """
+ )
+ # entry -> body -> exit, no branches.
+ assert _by_kind(cfg, "branch") == []
+ assert _by_kind(cfg, "loop_header") == []
+ # Every block is reachable from entry, and exit is among them.
+ reachable = cfg.reachable_ids()
+ assert cfg.exit_id in reachable
+ # The single body block carries all four statements.
+ body = [b for b in cfg.blocks if b.statements]
+ assert len(body) == 1
+ assert len(body[0].statements) == 4
+ # entry has exactly one successor; exit has no successors.
+ assert len(cfg.entry.successors) == 1
+ assert cfg.exit.successors == []
+
+
+# -- if / else join -------------------------------------------------------------
+
+
+def test_if_else_join():
+ cfg = _cfg(
+ """
+ def f(x):
+ if x > 0:
+ y = 1
+ else:
+ y = 2
+ return y
+ """
+ )
+ branches = _by_kind(cfg, "branch")
+ assert len(branches) == 1
+ branch = branches[0]
+ # The branch test has two successors (then / else).
+ assert len(branch.successors) == 2
+ # Both arms converge on a single join block.
+ joins = _by_kind(cfg, "join")
+ assert len(joins) == 1
+ join = joins[0]
+ assert len(join.predecessors) == 2
+ assert set(join.predecessors) == {s for s in cfg.block(join.id).predecessors}
+ # The join flows to the return -> exit.
+ assert cfg.exit_id in cfg.reachable_ids()
+
+
+def test_if_without_else_falls_through():
+ cfg = _cfg(
+ """
+ def f(x):
+ if x:
+ y = 1
+ return y
+ """
+ )
+ branch = _by_kind(cfg, "branch")[0]
+ join = _by_kind(cfg, "join")[0]
+ # No else: the branch's false edge goes straight to the join, and the then
+ # block also reaches it -> two predecessors.
+ assert join.id in branch.successors
+ assert len(join.predecessors) == 2
+
+
+def test_elif_chain_nested_branches():
+ cfg = _cfg(
+ """
+ def f(x):
+ if x == 1:
+ y = 1
+ elif x == 2:
+ y = 2
+ elif x == 3:
+ y = 3
+ else:
+ y = 4
+ return y
+ """
+ )
+ # One head test + two elif tests = three branch blocks.
+ assert len(_by_kind(cfg, "branch")) == 3
+ # A single join collects all four arms.
+ joins = _by_kind(cfg, "join")
+ assert len(joins) == 1
+ assert len(joins[0].predecessors) == 4
+
+
+# -- while back-edge ------------------------------------------------------------
+
+
+def test_while_back_edge():
+ cfg = _cfg(
+ """
+ def f(n):
+ i = 0
+ while i < n:
+ i += 1
+ return i
+ """
+ )
+ headers = _by_kind(cfg, "loop_header")
+ assert len(headers) == 1
+ header = headers[0]
+ # Header has two successors: into the body and past the loop.
+ assert len(header.successors) == 2
+ # A back-edge: some block inside the body is a predecessor of the header
+ # with a higher id than the header (the loop tail re-enters).
+ assert any(p > header.id for p in header.predecessors)
+ assert cfg.back_edges() # non-empty
+ # The loop_exit block exists and is reachable.
+ assert _by_kind(cfg, "loop_exit")
+
+
+def test_for_loop_shape():
+ cfg = _cfg(
+ """
+ def f(items):
+ total = 0
+ for it in items:
+ total += it
+ return total
+ """
+ )
+ assert len(_by_kind(cfg, "loop_header")) == 1
+ assert cfg.back_edges()
+
+
+def test_break_and_continue_targets():
+ cfg = _cfg(
+ """
+ def f(items):
+ for it in items:
+ if it < 0:
+ continue
+ if it > 100:
+ break
+ process(it)
+ return 0
+ """
+ )
+ header = _by_kind(cfg, "loop_header")[0]
+ after = _by_kind(cfg, "loop_exit")[0]
+ # ``continue`` adds a back-edge to the header; ``break`` adds an edge to the
+ # loop-exit block from inside the body.
+ assert any(p > header.id for p in header.predecessors)
+ assert any(p > header.id for p in after.predecessors)
+
+
+# -- try / except ---------------------------------------------------------------
+
+
+def test_try_except_handler_reachable():
+ cfg = _cfg(
+ """
+ def f():
+ try:
+ risky()
+ except ValueError:
+ recover()
+ return 1
+ """
+ )
+ handlers = _by_kind(cfg, "handler")
+ assert len(handlers) == 1
+ handler = handlers[0]
+ # The handler is reachable from entry (an exception may escape the body).
+ assert handler.id in cfg.reachable_ids()
+ # Both the normal body and the handler converge before exit.
+ assert cfg.exit_id in cfg.reachable_ids()
+
+
+def test_try_except_finally_convergence():
+ cfg = _cfg(
+ """
+ def f():
+ try:
+ risky()
+ except KeyError as e:
+ handle(e)
+ except ValueError:
+ handle2()
+ else:
+ ok()
+ finally:
+ cleanup()
+ return 1
+ """
+ )
+ # Two handlers, both reachable.
+ assert len(_by_kind(cfg, "handler")) == 2
+ # The finally body runs on every path: its block has the normal body's
+ # else-out and both handlers as predecessors converging into it.
+ assert cfg.exit_id in cfg.reachable_ids()
+
+
+# -- early return ---------------------------------------------------------------
+
+
+def test_early_return_edges_to_exit():
+ cfg = _cfg(
+ """
+ def f(x):
+ if x:
+ return 1
+ y = compute()
+ return y
+ """
+ )
+ # The then-branch returns: it has an edge to exit and the join is reached
+ # only from the branch's false edge.
+ exit_preds = cfg.exit.predecessors
+ # At least two paths reach exit: the early return and the final return.
+ assert len(exit_preds) >= 2
+ # The code after the if is still reachable (false edge).
+ assert cfg.exit_id in cfg.reachable_ids()
+
+
+def test_unreachable_after_return():
+ cfg = _cfg(
+ """
+ def f():
+ return 1
+ dead = 2
+ """
+ )
+ unreachable = _by_kind(cfg, "unreachable")
+ assert len(unreachable) == 1
+ # The dead block has no predecessors and is not reachable from entry.
+ assert unreachable[0].predecessors == []
+ assert unreachable[0].id not in cfg.reachable_ids()
+
+
+# -- determinism ----------------------------------------------------------------
+
+
+def test_determinism_identical_structure():
+ src = """
+ def f(x, items):
+ total = 0
+ for it in items:
+ if it > x:
+ total += it
+ else:
+ total -= it
+ try:
+ check(total)
+ except ValueError:
+ total = 0
+ return total
+ """
+
+ def serialize(cfg):
+ return [
+ (b.id, b.kind, [(s.kind, s.start_line) for s in b.statements], list(b.successors))
+ for b in cfg.blocks
+ ]
+
+ first = serialize(_cfg(src))
+ for _ in range(3):
+ assert serialize(_cfg(src)) == first
+
+
+# -- gate (the budget contract) -------------------------------------------------
+
+
+def test_is_flagged_thresholds():
+ # complex_method: ccn >= 9 alone flags.
+ assert is_flagged(ccn=9, nloc=10)
+ assert not is_flagged(ccn=8, nloc=10)
+ # large_method: nloc >= 60 with at least one branch (ccn >= 2).
+ assert is_flagged(ccn=2, nloc=60)
+ assert not is_flagged(ccn=1, nloc=200) # flat body, no branching
+ assert not is_flagged(ccn=8, nloc=59)
+
+
+def test_flagged_only_gate_skips_small_functions():
+ # One large/complex function and one trivial function in the same file.
+ lines = ["def big(x):", " y = 0"]
+ for i in range(12):
+ lines += [f" if x == {i}:", f" y = {i}"]
+ lines += [" return y", "", "def tiny():", " return 1", ""]
+ src = "\n".join(lines)
+ result = build_cfgs_for_file("mem.py", "python", src.encode())
+ if result.stats.functions_seen == 0:
+ pytest.skip("tree-sitter language pack missing for python")
+ # Both functions were discovered, but only the flagged one got a CFG.
+ assert result.stats.functions_seen == 2
+ assert result.stats.functions_built == 1
+ assert [fc.name for fc in result.functions] == ["big"]
+ assert result.functions[0].cfg.blocks
+
+
+def test_flagged_only_false_builds_all():
+ src = textwrap.dedent(
+ """
+ def tiny():
+ return 1
+ """
+ )
+ result = build_cfgs_for_file("mem.py", "python", src.encode(), flagged_only=False)
+ if result.stats.functions_seen == 0:
+ pytest.skip("tree-sitter language pack missing for python")
+ assert result.stats.functions_built == 1
+
+
+# -- graceful degradation -------------------------------------------------------
+
+
+def test_unsupported_language_is_silent():
+ result = build_cfgs_for_file("x.unknown", "cobol", b"whatever")
+ assert result.functions == []
+ assert result.stats.functions_seen == 0
+
+
+def test_garbage_source_does_not_raise():
+ # Not valid Python; tree-sitter still produces a (broken) tree, so this must
+ # not raise -- at worst it yields no flagged functions.
+ result = build_cfgs_for_file("x.py", "python", b">>>!!! not python @@@")
+ assert isinstance(result.functions, list)
+
+
+def test_size_guard_trips_on_low_cap():
+ fn_node, lmap = _first_fn(
+ """
+ def f(x):
+ if x:
+ a = 1
+ else:
+ a = 2
+ return a
+ """
+ )
+ with pytest.raises(CFGGuardTrippedError):
+ build_cfg(fn_node, lmap, max_blocks=2)