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
fix(mcp): give every requested hop a share of the callee budget (#2285)
Raghav Chamadiya1154ae63d31b
diff --git a/packages/server/src/repowise/server/mcp_server/tool_symbol.py b/packages/server/src/repowise/server/mcp_server/tool_symbol.pyindex bd689592f..25fa2ab7b 100644--- a/packages/server/src/repowise/server/mcp_server/tool_symbol.py+++ b/packages/server/src/repowise/server/mcp_server/tool_symbol.py@@ -47,7 +47,7 @@ import sqlite3import timefrom datetime import UTC, datetimefrom pathlib import Path-from typing import Any+from typing import Any, NamedTuplefrom sqlalchemy import select@@ -131,32 +131,82 @@ _MAX_CALLEE_DEPTH = 3# Total chars of callee source served. Sized against the symbol cap above: a# handful of ordinary bodies, and a hub is truncated rather than serialised._CALLEE_CHAR_BUDGET = 24_000-# Per-hop fan-out cap, applied before any body is read.+# Per-hop fan-out cap, applied before any body is read. Enforced across the+# whole frontier, not per node: passing it only to the per-node edge query let a+# hop of N nodes yield up to 12xN callees, and on a 12-node frontier whose nodes+# call 14 each the walk produced **144 rows against this documented cap of 12**.+# The constant's name meant a hop; the code meant a node._MAX_CALLEES_PER_HOP = 12# Callee bodies are context for the root symbol, not the subject of the call,# so they are bounded tighter than the root's ~600._MAX_CALLEE_BODY_LINES = 150-async def _expand_callees(- session,- repo_id: str,- root_row: WikiSymbol,- repo_root: Path,- depth: int,- exclude_spec: Any,- repository: str = "default",-) -> dict[str, Any] | None:- """Breadth-first walk of the call graph from *root_row*, bodies included.+class _CalleeHop(NamedTuple):+ """One hop of the walk: its true graph distance and the rows it produced.- Symbol graph nodes are keyed by the same ``"{path}::{Name}"`` string as- ``WikiSymbol.symbol_id``, so each hop is one edge query plus one row query- regardless of fan-out. Every symbol is served at most once and at the- shallowest depth it was reached from, which keeps a diamond in the call- graph from being serialised twice.+ ``over_cap`` counts rows the per-hop fan-out cap dropped. They are reported+ as a number rather than as entries: listing them individually is the payload+ the cap exists to prevent, and saying nothing would make a silent cut out of+ a bound this module otherwise always makes recoverable. It is a floor over+ the indexed graph, not a total — the per-node edge query carries its own+ limit, so callees it never returned are not counted here either.+ """- Returns None when the root has no outbound call edges, so the caller adds- no empty block to an ordinary response.+ number: int+ rows: list[WikiSymbol]+ over_cap: int+++class _CalleeBody(NamedTuple):+ """One callee's rendered body, sliced once and costed by its own length.++ ``declared_*`` are the bounds the verified row claims; ``start``/``end`` are+ what the line cap actually served, so ``end < declared_end`` is exactly the+ truncation case.+ """++ source: str+ start: int+ end: int+ declared_start: int+ declared_end: int+ verified: bool+++def _slice_callee_body(row: WikiSymbol, text: str) -> _CalleeBody:+ """Slice *row* out of *text* under the callee line cap.++ Bounds are checked so ``verified`` is honest, but a correction is not+ written back here: healing belongs to the read that asked for the symbol,+ not to a neighbour swept up by a graph walk.+ """+ check = check_symbol_bounds(row, text)+ source, start, end, _total = _slice_text(+ text, check.start_line, check.end_line, 0, max_lines=_MAX_CALLEE_BODY_LINES+ )+ return _CalleeBody(+ source=_number_lines(source, start),+ start=start,+ end=end,+ declared_start=check.start_line,+ declared_end=check.end_line,+ verified=check.verified,+ )+++async def _unseen_callees_of(+ session,+ repo_id: str,+ frontier: list[str],+ seen: set[str],+) -> tuple[list[str], dict[str, float]]:+ """Call targets of *frontier* not already in *seen*, with their confidence.++ Mutates *seen*, which is what keeps a diamond from being walked twice.+ Edges below the confidence floor are dropped here: tier-3 resolution+ invents edges, and a guessed one drags a whole unrelated body into the+ payload."""from repowise.core.persistence.crud import get_graph_edges_for_nodefrom repowise.server.mcp_server.tool_context.enrichment import (@@ -164,32 +214,56 @@ async def _expand_callees(_MIN_CALL_CONFIDENCE,)+ next_ids: list[str] = []+ confidence_of: dict[str, float] = {}+ for node_id in frontier:+ edges = await get_graph_edges_for_node(+ session,+ repo_id,+ node_id,+ direction="callees",+ edge_types=_CALL_EDGE_TYPES,+ limit=_MAX_CALLEES_PER_HOP,+ )+ for e in edges:+ if (e.confidence or 0) < _MIN_CALL_CONFIDENCE or e.target_node_id in seen:+ continue+ seen.add(e.target_node_id)+ next_ids.append(e.target_node_id)+ confidence_of[e.target_node_id] = e.confidence or 0+ return next_ids, confidence_of+++async def _discover_callee_hops(+ session,+ repo_id: str,+ root_row: WikiSymbol,+ depth: int,+ exclude_spec: Any,+) -> list[_CalleeHop]:+ """Walk the call graph and return the rows of each hop, no bodies read.++ Discovery is separate from rendering so the renderer knows, before it+ spends the first character, how many hops actually produced rows. Reserving+ a slice of the budget for a hop that turns out to be empty costs a body+ that would otherwise have been served.++ Symbol graph nodes are keyed by the same ``"{path}::{Name}"`` string as+ ``WikiSymbol.symbol_id``, so each hop is one edge query plus one row query+ regardless of fan-out. Every symbol is reached at most once, at the+ shallowest depth that reaches it, which keeps a diamond in the call graph+ from being serialised twice. A symbol past the per-hop fan-out cap is not+ re-offered at a deeper hop: it would then be labelled with a distance that+ is not its own. It is counted in ``over_cap`` instead.+ """seen: set[str] = {root_row.symbol_id}frontier = [root_row.symbol_id]- entries: list[dict[str, Any]] = []- omitted: list[dict[str, Any]] = []- text_cache: dict[str, str | None] = {}- remaining = _CALLEE_CHAR_BUDGET+ hops: list[_CalleeHop] = []- for hop in range(1, depth):+ for hop_number in range(1, depth):if not frontier:break- next_ids: list[str] = []- for node_id in frontier:- edges = await get_graph_edges_for_node(- session,- repo_id,- node_id,- direction="callees",- edge_types=_CALL_EDGE_TYPES,- limit=_MAX_CALLEES_PER_HOP,- )- for e in edges:- if (e.confidence or 0) < _MIN_CALL_CONFIDENCE:- continue- if e.target_node_id not in seen:- seen.add(e.target_node_id)- next_ids.append(e.target_node_id)+ next_ids, confidence_of = await _unseen_callees_of(session, repo_id, frontier, seen)if not next_ids:break@@ -200,75 +274,172 @@ async def _expand_callees())rows = [r for r in res.scalars().all() if not is_excluded(r.file_path, exclude_spec)]+ # The cap the constant documents: one hop, not one frontier node. It is+ # applied *after* the row lookup and the exclusion filter, so a dangling+ # edge or an excluded path cannot spend a slot — cutting the ids first+ # let a hop whose twelve most confident targets all sat under an+ # excluded prefix come back empty while valid callees waited behind it.+ # The cut itself is ranked by edge confidence, which is the contract+ # ``get_graph_edges_for_node`` already documents for its own limit: an+ # unranked cut is deterministic and still the wrong rows.+ rows.sort(key=lambda r: (-confidence_of.get(r.symbol_id or "", 0.0), r.symbol_id or ""))+ over_cap = max(len(rows) - _MAX_CALLEES_PER_HOP, 0)+ rows = rows[:_MAX_CALLEES_PER_HOP]# Stable order so the same call returns the same payload twice.rows.sort(key=lambda r: (r.file_path or "", r.start_line or 0, r.symbol_id or ""))+ if rows:+ # The hop number is carried, not inferred from the position in this+ # list: a hop whose rows were all excluded or all dangling would+ # otherwise renumber every hop behind it, and a grandchild would be+ # served claiming to be a direct callee.+ hops.append(_CalleeHop(number=hop_number, rows=rows, over_cap=over_cap))+ frontier = next_ids++ return hops+++def _prepare_callee_entries(+ hops: list[_CalleeHop], repo_root: Path+) -> list[tuple[dict[str, Any], str, _CalleeBody | None]]:+ """One ordered record per discovered row: ``(entry, file_path, body)``.- for row in rows:+ ``body`` is None when the file could not be read. The order is fixed here,+ so the later refill pass cannot reshuffle the payload, and each body is+ sliced exactly once, so what a body costs and what is emitted for it can+ never disagree.+ """+ text_cache: dict[str, str | None] = {}+ prepared: list[tuple[dict[str, Any], str, _CalleeBody | None]] = []+ for hop in hops:+ for row in hop.rows:entry: dict[str, Any] = {"symbol_id": symbol_identity(row.symbol_id),"name": row.name,"file": row.file_path,"kind": row.kind,"signature": _clean_symbol_signature(row.signature),- "depth": hop,+ "depth": hop.number,}if row.file_path not in text_cache:text_cache[row.file_path] = _read_file_text(repo_root, row.file_path)text = text_cache[row.file_path]- if text is None:- entry["note"] = "source file could not be read"- omitted.append(entry)- continue+ body = None if text is None else _slice_callee_body(row, text)+ prepared.append((entry, row.file_path, body))+ return prepared+++async def _expand_callees(+ session,+ repo_id: str,+ root_row: WikiSymbol,+ repo_root: Path,+ depth: int,+ exclude_spec: Any,+ repository: str = "default",+) -> dict[str, Any] | None:+ """Breadth-first walk of the call graph from *root_row*, bodies included.++ Bodies are served against a per-hop share of the character budget rather+ than in loop order. Spending in loop order meant every hop-1 body was+ served before hop 2 was reached, so a handful of large direct callees+ exhausted the budget and the deeper hops the caller asked for arrived as+ references. Measured on a 20x3 hub: 10 hop-1 bodies and **zero** at hop 2;+ with a reserved share, 5 and 5.++ The reservation is taken only across hops that discovery found rows for,+ and whatever the reserve leaves unspent is refilled to the bodies it+ deferred, in hop order — so a direct callee is first in line for a share+ the deeper hops did not use. Both matter: a naive reserve cost a two-leaf+ root at depth 3 one of its two bodies in exchange for a hop 2 that was+ empty, and a reserve that only bound the shallow hops let hop 2 drain the+ budget a deferred hop-1 body was waiting on.++ Returns None when the root has no outbound call edges, so the caller adds+ no empty block to an ordinary response.+ """+ hops = await _discover_callee_hops(session, repo_id, root_row, depth, exclude_spec)+ if not hops:+ return None- # Bounds are checked so ``verified`` is honest, but a correction is- # not written back here: healing belongs to the read that asked for- # the symbol, not to a neighbour swept up by a graph walk.- check = check_symbol_bounds(row, text)- source, start, end, _total = _slice_text(- text, check.start_line, check.end_line, 0, max_lines=_MAX_CALLEE_BODY_LINES+ remaining = _CALLEE_CHAR_BUDGET+ reserve_per_hop = _CALLEE_CHAR_BUDGET // len(hops)+ prepared = _prepare_callee_entries(hops, repo_root)++ def _render(entry: dict[str, Any], file_path: str, body: _CalleeBody) -> None:+ entry.update(+ {+ "start_line": body.start,+ "end_line": body.end,+ "source": body.source,+ "verified": body.verified,+ }+ )+ if body.end < body.declared_end:+ entry["truncated"] = True+ continuation_reference = source_reference(+ repository,+ file_path,+ lines=[body.end + 1, body.declared_end],+ verification_basis="live",+ source_kind="source",)- numbered = _number_lines(source, start)- if len(numbered) > remaining:- # Out of budget: name the read that fetches it rather than- # dropping the symbol silently.- fetch_reference = source_reference(- repository,- row.file_path,- lines=[check.start_line, check.end_line],- verification_basis="live",- source_kind="source",- )- entry["fetch_with"] = fetch_reference["id"]- entry["fetch_reference"] = fetch_reference- omitted.append(entry)+ entry["continuation"] = continuation_reference["id"]+ entry["continuation_reference"] = continuation_reference++ # Pass 1: every hop spends its own share and no more — including the last,+ # which is why this is a cap and not a floor. Subtracting only the shares+ # still owed to *deeper* hops let unspent budget flow forward: a hop-1 body+ # one character over its share was deferred, the deeper hops then drained+ # everything behind it, and the direct callee — the most relevant body in+ # the response — came back as a reference. That is worse than the code this+ # replaces. Leftovers are redistributed by pass 2 instead, in hop order.+ for hop in hops:+ spendable = min(reserve_per_hop, remaining)+ for entry, file_path, body in prepared:+ if entry["depth"] != hop.number or body is None or "source" in entry:continue- remaining -= len(numbered)- entry.update(- {- "start_line": start,- "end_line": end,- "source": numbered,- "verified": check.verified,- }- )- if end < check.end_line:- entry["truncated"] = True- continuation_reference = source_reference(- repository,- row.file_path,- lines=[end + 1, check.end_line],- verification_basis="live",- source_kind="source",- )- entry["continuation"] = continuation_reference["id"]- entry["continuation_reference"] = continuation_reference- entries.append(entry)+ if len(body.source) > spendable:+ continue+ _render(entry, file_path, body)+ remaining -= len(body.source)+ spendable -= len(body.source)++ # Pass 2: a reserve nobody claimed goes back to whatever it deferred, in+ # hop order, so an empty deeper hop costs the caller nothing.+ for entry, file_path, body in prepared:+ if body is None or "source" in entry or len(body.source) > remaining:+ continue+ _render(entry, file_path, body)+ remaining -= len(body.source)- frontier = next_ids+ entries: list[dict[str, Any]] = []+ omitted: list[dict[str, Any]] = []+ for entry, file_path, body in prepared:+ if "source" in entry:+ entries.append(entry)+ elif body is None:+ entry["note"] = "source file could not be read"+ omitted.append(entry)+ else:+ # Out of budget: name the read that fetches it rather than+ # dropping the symbol silently.+ fetch_reference = source_reference(+ repository,+ file_path,+ lines=[body.declared_start, body.declared_end],+ verification_basis="live",+ source_kind="source",+ )+ entry["fetch_with"] = fetch_reference["id"]+ entry["fetch_reference"] = fetch_reference+ omitted.append(entry)- if not entries and not omitted:- return Noneblock: dict[str, Any] = {"depth": depth, "callees": entries}+ fan_out_capped = [+ {"depth": hop.number, "omitted": hop.over_cap} for hop in hops if hop.over_cap+ ]+ if fan_out_capped:+ block["fan_out_capped"] = fan_out_cappedif omitted:block["not_rendered"] = omittedblock["note"] = (diff --git a/tests/unit/server/mcp/test_symbol_callee_depth.py b/tests/unit/server/mcp/test_symbol_callee_depth.pyindex dd212965e..278aa9aca 100644--- a/tests/unit/server/mcp/test_symbol_callee_depth.py+++ b/tests/unit/server/mcp/test_symbol_callee_depth.py@@ -15,7 +15,12 @@ import pytestfrom repowise.core.persistence.models import GraphEdge, GraphNode, Repository, WikiSymbolfrom repowise.server.mcp_server import tool_symbol-from repowise.server.mcp_server.tool_symbol import _MAX_CALLEE_DEPTH, _expand_callees+from repowise.server.mcp_server.tool_symbol import (+ _CALLEE_CHAR_BUDGET,+ _MAX_CALLEE_DEPTH,+ _MAX_CALLEES_PER_HOP,+ _expand_callees,+)_FILE = "src/chain.py"_SRC = "\n".join(f"def f{i}():\n return f{i + 1}()\n" for i in range(6))@@ -305,3 +310,321 @@ async def test_a_base_class_is_not_served_as_a_callee(block = await _expand_callees(session, rid, root, chain, 2, None)assert [c["symbol_id"] for c in block["callees"]] == [f"{_FILE}::f1"]+++# --- the per-hop bounds, measured before they were written -----------------+#+# The tests below pin what a measurement pass found in the walk as it stood: a+# fan-out cap that counted per node rather than per hop, and a character budget+# spent in loop order, so hop 1 consumed everything hop 2 needed. The fixtures+# are the shapes that made each one visible.+++def _wide_body(n: int) -> str:+ return "".join(f" value_{i} = compute(argument_one, argument_two)\n" for i in range(n))+++async def _build_graph(session, rid, tmp_path, edges, body_lines):+ """Build a call graph from ``{caller: [callee, ...]}``, one file per symbol.++ One file each so the alphabetical render order is the symbol order, which+ makes "which bodies survived the budget" readable in a failure message.+ """+ names = set(edges) | {d for v in edges.values() for d in v}+ (tmp_path / "src").mkdir(exist_ok=True)+ ids = {}+ for name in sorted(names):+ lines = body_lines if isinstance(body_lines, int) else body_lines.get(name, 40)+ path = f"src/{name}.py"+ (tmp_path / "src" / f"{name}.py").write_text(+ f"def {name}():\n{_wide_body(lines)}", encoding="utf-8"+ )+ ids[name] = f"{path}::{name}"+ session.add(+ WikiSymbol(+ id=f"w-{name}",+ repository_id=rid,+ file_path=path,+ symbol_id=ids[name],+ name=name,+ qualified_name=name,+ kind="function",+ signature=f"def {name}()",+ start_line=1,+ end_line=lines + 1,+ language="python",+ complexity_estimate=1,+ )+ )+ session.add(+ GraphNode(+ id=f"wn-{name}",+ repository_id=rid,+ node_id=ids[name],+ node_type="symbol",+ name=name,+ file_path=path,+ language="python",+ )+ )+ n = 0+ for caller, callees in edges.items():+ for callee in callees:+ session.add(+ GraphEdge(+ id=f"we-{n}",+ repository_id=rid,+ source_node_id=ids[caller],+ target_node_id=ids[callee],+ edge_type="calls",+ confidence=0.9,+ )+ )+ n += 1+ await session.flush()+ return ids+++async def _walk(session, rid, tmp_path, root_id, depth):+ from sqlalchemy import select++ res = await session.execute(+ select(WikiSymbol).where(WikiSymbol.repository_id == rid, WikiSymbol.symbol_id == root_id)+ )+ return await _expand_callees(session, rid, res.scalar_one(), tmp_path, depth, None)+++def _by_hop(block, served_only=False):+ rows = list(block["callees"]) + ([] if served_only else list(block.get("not_rendered", [])))+ out: dict[int, int] = {}+ for entry in rows:+ if served_only and not entry.get("verified"):+ continue+ out[entry["depth"]] = out.get(entry["depth"], 0) + 1+ return out+++async def test_fan_out_is_capped_per_hop_not_per_frontier_node(+ session, repository, tmp_path+) -> None:+ """`_MAX_CALLEES_PER_HOP` has to mean a hop. It used to mean a node.++ The limit was passed to the per-node edge query inside the frontier loop,+ so a hop of N nodes could yield 12xN callees. Measured on exactly this+ shape before the fix: **144 rows at hop 2 against a documented cap of 12**,+ every one of them costing a row query and a not_rendered entry.+ """+ edges = {"w": [f"m{i:02d}" for i in range(12)]}+ for i in range(12):+ edges[f"m{i:02d}"] = [f"z{i:02d}{j:02d}" for j in range(14)]+ await _build_graph(session, repository.id, tmp_path, edges, 40)++ block = await _walk(session, repository.id, tmp_path, "src/w.py::w", 3)+ found = _by_hop(block)+ assert found[1] <= _MAX_CALLEES_PER_HOP+ assert found[2] <= _MAX_CALLEES_PER_HOP, f"hop 2 returned {found[2]} rows against a cap of 12"+++async def test_a_deeper_hop_keeps_a_body_when_hop_one_could_spend_it_all(+ session, repository, tmp_path+) -> None:+ """The point of asking for depth 3: hop 2 arrives as source, not as a name.++ The budget used to be consumed in loop order, so large direct callees+ exhausted all 24,000 characters and every hop-2 symbol came back as a+ `fetch_with` reference. Measured on this shape: 10 hop-1 bodies and **zero**+ at hop 2. Each hop now holds a share of the budget.+ """+ edges = {"hub": [f"c{i:02d}" for i in range(20)]}+ for i in range(20):+ edges[f"c{i:02d}"] = [f"g{i:02d}{j}" for j in range(3)]+ await _build_graph(session, repository.id, tmp_path, edges, 90)++ block = await _walk(session, repository.id, tmp_path, "src/hub.py::hub", 3)+ served = _by_hop(block, served_only=True)+ assert served.get(1), "hop 1 lost its evidence to the reservation"+ assert served.get(2), "hop 2 was requested and came back with no body at all"+ assert sum(len(c["source"]) for c in block["callees"]) <= _CALLEE_CHAR_BUDGET+++async def test_an_empty_deeper_hop_costs_the_caller_nothing(+ session, repository, tmp_path+) -> None:+ """A reserve held for a hop that does not exist is a body the caller paid for.++ Two large direct callees, both leaves, asked for at depth 3. A per-hop+ reservation taken before the walk knows which hops have rows throttles hop 1+ to half the budget and drops one of the two bodies outright: measured,+ 17,402 characters down to 8,701. The reservation is taken only across hops+ discovery actually found, and the remainder is refilled to what it deferred,+ so a depth-3 walk over leaves matches the depth-2 one exactly.+ """+ await _build_graph(session, repository.id, tmp_path, {"L": ["leaf_a", "leaf_b"]}, 200)++ deep = await _walk(session, repository.id, tmp_path, "src/L.py::L", 3)+ shallow = await _walk(session, repository.id, tmp_path, "src/L.py::L", 2)+ assert _by_hop(deep, served_only=True) == _by_hop(shallow, served_only=True) == {1: 2}+ assert "not_rendered" not in deep+++async def test_an_edge_to_an_unindexed_symbol_yields_no_entry(+ session, repository, tmp_path+) -> None:+ """A dangling edge must not become a callee with no body and no reference.++ Edges outlive symbol rows, through a deleted function or a file dropped from+ the index, and an entry with a name but nothing to fetch is worse than the+ missing hop: the agent spends a round trip proving it is empty.+ """+ ids = await _build_graph(session, repository.id, tmp_path, {"p0": ["p1"], "p1": ["p2"]}, 40)+ session.add(+ GraphEdge(+ id="we-ghost",+ repository_id=repository.id,+ source_node_id=ids["p0"],+ target_node_id="src/ghost.py::ghost",+ edge_type="calls",+ confidence=0.9,+ )+ )+ await session.flush()++ block = await _walk(session, repository.id, tmp_path, "src/p0.py::p0", 3)+ assert [c["symbol_id"] for c in block["callees"]] == [ids["p1"], ids["p2"]]+ assert "ghost" not in str(block)+++async def test_a_diamond_serves_the_shared_callee_once(session, repository, tmp_path) -> None:+ """Two callers reaching the same symbol is one body, at the shallower hop."""+ await _build_graph(+ session, repository.id, tmp_path, {"d0": ["d1", "d2"], "d1": ["d3"], "d2": ["d3"]}, 40+ )++ block = await _walk(session, repository.id, tmp_path, "src/d0.py::d0", 3)+ ids = [c["symbol_id"] for c in block["callees"]]+ assert ids == sorted(set(ids)), "the shared callee was serialised twice"+ assert _by_hop(block) == {1: 2, 2: 1}+++async def test_a_hop_with_no_indexed_rows_does_not_renumber_the_hops_behind_it(+ session, repository, tmp_path+) -> None:+ """`depth` is graph distance, not a position in the list of surviving hops.++ An excluded or unindexed middle hop produces no rows. Skipping it when the+ hops are collected, then numbering them by position, serves a grandchild+ claiming to be a direct callee — and an agent that believes the label reads+ the wrong call site.+ """+ import pathspec++ await _build_graph(+ session, repository.id, tmp_path, {"g0": ["g1"], "g1": ["g2"]}, 40+ )+ spec = pathspec.PathSpec.from_lines("gitwildmatch", ["src/g1.py"])+ from sqlalchemy import select++ res = await session.execute(+ select(WikiSymbol).where(+ WikiSymbol.repository_id == repository.id,+ WikiSymbol.symbol_id == "src/g0.py::g0",+ )+ )+ block = await _expand_callees(session, repository.id, res.scalar_one(), tmp_path, 3, spec)++ assert [c["symbol_id"] for c in block["callees"]] == ["src/g2.py::g2"]+ assert block["callees"][0]["depth"] == 2, "a grandchild was served as a direct callee"+++async def test_the_fan_out_cap_is_spent_on_rows_that_can_actually_be_served(+ session, repository, tmp_path+) -> None:+ """Excluded targets must not consume slots the hop cap could have given away.++ Two frontier nodes, eight callees each, against a cap of twelve. One node's+ callees are all excluded and all sort first. Cutting the ids before the row+ lookup spends eight of the twelve slots on rows that are then filtered out,+ and the caller loses half the evidence the hop actually had.++ Scoped to a multi-node frontier deliberately: the per-node edge query+ carries its own limit, so a single node whose top edges are all excluded is+ truncated before this function sees them, and that bound is not this+ function's to fix.+ """+ import pathspec++ edges = {+ "root": ["m_a", "m_b"],+ "m_a": [f"a_vendor_{i}" for i in range(8)],+ "m_b": [f"z_real_{i}" for i in range(8)],+ }+ await _build_graph(session, repository.id, tmp_path, edges, 40)+ spec = pathspec.PathSpec.from_lines("gitwildmatch", ["src/a_vendor_*.py"])+ from sqlalchemy import select++ res = await session.execute(+ select(WikiSymbol).where(+ WikiSymbol.repository_id == repository.id,+ WikiSymbol.symbol_id == "src/root.py::root",+ )+ )+ block = await _expand_callees(session, repository.id, res.scalar_one(), tmp_path, 3, spec)++ hop_two = [c for c in block["callees"] if c["depth"] == 2]+ hop_two += [c for c in block.get("not_rendered", []) if c["depth"] == 2]+ names = sorted(c["name"] for c in hop_two)+ assert len(hop_two) == 8, f"excluded targets ate slots the hop had to give: {names}"+ assert all(c["name"].startswith("z_real_") for c in hop_two)+++async def test_a_capped_hop_says_how_many_callees_it_dropped(+ session, repository, tmp_path+) -> None:+ """A cap this module cannot make recoverable must at least be visible.++ Listing every dropped callee is the payload the cap exists to prevent, so a+ count is what is reported. Silence would read as "this is the whole+ fan-out", which is the failure the not_rendered list already exists to+ avoid.++ The count is a floor, not a total: the per-node edge query carries its own+ limit, so callees it never handed over are not counted here either.+ """+ edges = {"w": [f"m{i:02d}" for i in range(12)]}+ for i in range(12):+ edges[f"m{i:02d}"] = [f"z{i:02d}{j:02d}" for j in range(14)]+ await _build_graph(session, repository.id, tmp_path, edges, 40)++ block = await _walk(session, repository.id, tmp_path, "src/w.py::w", 3)+ capped = {row["depth"]: row["omitted"] for row in block["fan_out_capped"]}+ assert capped[2] > 0, "hop 2 dropped callees and said nothing"+ served_at_two = [c for c in block["callees"] if c["depth"] == 2]+ dropped_at_two = [c for c in block.get("not_rendered", []) if c["depth"] == 2]+ # 12 frontier nodes calling 14 each is a true fan-out of 168, but the+ # per-node edge query hands over 12 apiece, so 144 is all the walk ever+ # sees. Everything it does see is accounted for — served, deferred, or+ # counted — and the 24 it never saw are why the count is a floor.+ assert len(served_at_two) + len(dropped_at_two) + capped[2] == 12 * 12+++async def test_budget_a_deeper_hop_leaves_unspent_returns_to_the_direct_callees(+ session, repository, tmp_path+) -> None:+ """A hop-1 body over its own share still outranks a hop-2 body for leftovers.++ If the reservation only bounds the shallow hops, an unspent share flows+ forward: a direct callee one character over its slice is deferred, the+ deeper hop drains what is left, and the single most relevant body in the+ response is the one that comes back as a reference. The hop-ordered refill+ is what prevents that, so the shape is pinned from the losing side.+ """+ edges = {"r": ["fat_one"], "fat_one": [f"small_{i}" for i in range(6)]}+ bodies = {"fat_one": 150}+ for i in range(6):+ bodies[f"small_{i}"] = 20+ await _build_graph(session, repository.id, tmp_path, edges, bodies)++ block = await _walk(session, repository.id, tmp_path, "src/r.py::r", 3)+ served = {c["name"] for c in block["callees"]}+ assert "fat_one" in served, "the direct callee lost its body to the hop behind it"+ assert any(c["depth"] == 2 for c in block["callees"]), "hop 2 got nothing"