Skip to content

fix(context): used_by from call edges, not header/impl pairing - #1789

Closed
sloemo01 wants to merge 1 commit into
repowise-dev:mainfrom
sloemo01:fix/cpp-used-by-call-edges
Closed

sloemo01 wants to merge 1 commit into
repowise-dev:mainfrom
sloemo01:fix/cpp-used-by-call-edges

Conversation

@sloemo01

Copy link
Copy Markdown
Contributor

What

Fixes #1655. get_context's used_by for a symbol was populated from the C++ header/impl pairing, not from resolved call/reference edges — it named the paired header (which never references the symbol) and omitted the file that actually calls it.

Root cause

The used_by query matched GraphEdge.target_node_id == sym.file_path (the bare path). Symbol nodes are keyed <path>::<name>, and call/reference edges point at that symbol node — so the query never matched a single call edge. It only ever caught file→file edges, which for a C++ symbol is the synthetic header/source imports pair (minted with imported_names = []).

Fix

targets.py now matches either kind of evidence:

  1. symbol→symbol calls / references edges targeting the symbol node (<path>::<name>) — the real cross-file C++ callers.
  2. file→file imports edges whose imported_names actually names the symbol — gated on the name so the empty-imports header pair is not served as a fabricated user.

Distinct sources afterwards, so a file that both imports and calls a symbol is one user. The Python file-import path (imported_names-based) is preserved — existing ranking tests pass unchanged.

Tests

  • test_used_by_ranking.py — 6 passed (4 existing + 2 new):
    • test_call_edge_to_symbol_node_is_a_user — a cross-file C++ call edge now surfaces the caller in used_by.
    • test_empty_header_pair_edge_is_not_a_user — the synthetic header pair (empty imported_names) is excluded.
  • Targeted context/used_by suites: 42 passed, no regression.

This is confined to the graph-surface consumers (context / get_context / get_symbol); dead-code was already correct per the issue.

`used_by` for a symbol was queried with `GraphEdge.target_node_id ==
sym.file_path` (the bare path). Symbol nodes are keyed `<path>::<name>`
and call/reference edges point *at* that symbol node, so the query never
matched them — it only ever caught file→file edges. For a C++ symbol that
is the synthetic header/source `imports` pair (`imported_names = []`),
so `used_by` named the paired header (which never references the symbol)
and omitted the file that actually calls it.

Now match either kind of evidence:
- symbol→symbol `calls`/`references` edges targeting the symbol node, or
- file→file `imports` edges whose `imported_names` actually names the
  symbol (gated, so an empty-imports header pair is not a fabricated user).

Distinct sources afterwards, so a file that both imports and calls is one
user. Python file-import used_by is preserved.

Fixes repowise-dev#1655
@repowise-bot

repowise-bot Bot commented Aug 21, 2026

Copy link
Copy Markdown
Contributor

✅ Health of changed files: 2.2 → 2.9 (+0.7)
⚠️ Change risk: moderate, riskier than 36% of this repo's commits.

📋 At a glance
1 file changed health · 2 hotspots touched · 2 new findings introduced · 1 file with recent fix history.

Files & modules (2)
  • packages (1 file)
    • .../tool_context/targets.py
  • tests (1 file)
    • .../mcp/test_used_by_ranking.py

✅ Health gate: passed

📌 Before you merge

  • Run .../mcp/test_context_file_preview.py, .../mcp/test_context_symbol_targets.py: they import the changed files
🔎 More signals (2)

🗺️ Change map

flowchart LR
  subgraph PR ["Changed in this PR (1 with dependents)"]
    f_packages_server_src_repowise_server_mcp_server_tool_context_targets_py[".../tool_context/targets.py 🔥"]:::changed
  end
  f_packages_server_src_repowise_server_mcp_server_tool_answer_answer_py[".../tool_answer/answer.py"]
  f_packages_server_src_repowise_server_mcp_server_tool_context_targets_py --> f_packages_server_src_repowise_server_mcp_server_tool_answer_answer_py
  f_packages_server_src_repowise_server_mcp_server_tool_context_context_py[".../tool_context/context.py"]
  f_packages_server_src_repowise_server_mcp_server_tool_context_targets_py --> f_packages_server_src_repowise_server_mcp_server_tool_context_context_py
  t_tests_unit_server_mcp_test_context_file_preview_py(["✅ .../mcp/test_context_file_preview.py"]):::guard
  t_tests_unit_server_mcp_test_context_file_preview_py -.-> f_packages_server_src_repowise_server_mcp_server_tool_context_targets_py
  classDef changed fill:#dbeafe,stroke:#1d4ed8,color:#1e3a5f
  classDef warn fill:#fef3c7,stroke:#b45309,color:#78350f
  classDef guard fill:#dcfce7,stroke:#15803d,color:#14532d
Loading

Solid arrows: code that imports the changed files (2 direct dependents, from the last indexed snapshot). Dashed: history/tests.

🔥 Hotspots touched (2)

  • .../tool_context/targets.py: 19 commits/90d, 5 dependents · primary owner: Swati Ahuja (58%)
  • .../mcp/test_used_by_ranking.py: 1 commits/90d, 2 dependents · primary owner: Swati Ahuja (100%)

📊 See the full report for this PR
Your repo map with this PR's blast radius lit up, every caller of the contracts it changes, and health before and after. No sign-in. · ⭐ Star Repowise · 📥 Install bot · Silence on a single PR with [skip repowise] in the title · Per-repo toggle on repowise.dev/settings?tab=bot · Updated 2026-08-21 07:32 UTC

@RaghavChamadiya

Copy link
Copy Markdown
Member

Thanks @sloemo01, and specifically for not stopping where the issue stopped. The report blamed the header/impl pairing, and the pairing is the symptom. GraphEdge.target_node_id == sym.file_path is a file-level query answering a symbol-level question, which is a different bug with a different fix, and you found it.

The existing comment above that query is quiet corroboration, by the way. It says distinct sources are needed because "two files joined by both an import and a call are one user", then notes the corpus holds zero duplicate rows so the guard "costs nothing and prevents nothing today". Zero duplicates because the call half never matched anything. The code was already describing the bug.

The calls / references half of this is right and I want it. What I cannot merge yet is the second branch.

The gap

The rewrite replaces the file-scoped condition with an unscoped one:

or_(
    GraphEdge.target_node_id == sym_node_id,
    GraphEdge.imported_names_json.contains(sym.name),
)

The old query was over-broad in one direction (any file importing this file, regardless of what it imported) but it was at least anchored to the symbol's own file. The new import branch drops that anchor completely. It now matches an import edge anywhere in the repository, pointing at any file, as long as the text of its imported_names_json contains the symbol's name. And because imported_names_json is Text (models.py:308), .contains() compiles to LIKE '%name%', so it is a substring match, not a name match.

Two independent widenings stacked: no file scope, and no word boundary.

What it does on this repo's own index

Distinct source files returned, running the real WHERE clause including the NON_DEPENDENCY_EDGE_TYPES exclusion, against .repowise/wiki.db:

symbol main this PR
platform/client.py::PlatformClient::get 6 620
platform/credentials.py::load 4 187
platform/store.py::load 4 177
commands/_tool_adapters.py::run 9 152
platform/store.py::update 4 83
health/config.py::HealthConfig 5 5

HealthConfig is fine because a long distinctive name has nothing to collide with. Every short name is not. PlatformClient::get has 2 real resolved callers and this returns 620 candidates, of which 618 are files that import some unrelated symbol whose name happens to contain the letters get.

That last part is what makes it worse than a cosmetic precision loss. used_by is cut at _MAX_USED_BY = 20 after ranking by the source file's PageRank. High-PageRank files import a lot, so they match a short substring often, and they sort to the top. The 2 real callers get displaced by 20 fabricated ones. The agent sees a full, confident, ranked list of 20 wrong answers, which is a worse failure than the empty one we have now.

What I think it needs

Keep the file anchor on the import branch only, and leave the call branch unscoped since a call edge already names the symbol node exactly:

or_(
    GraphEdge.target_node_id == sym_node_id,
    and_(
        GraphEdge.target_node_id == sym.file_path,
        GraphEdge.imported_names_json.contains(sym.name),
    ),
)

Same three columns, same index, and it still excludes the header pair you were targeting, because an empty imported_names fails the contains regardless of scope. Re-running the table with that variant gives 2, 15, 5, 0 and 14 against main's 6, 4, 4, 9 and 4, so the call edges still deliver the real callers the old query was missing.

Two things I checked so you do not have to:

Only 37 of 12,941 imports edges in this index carry empty imported_names, 0.3%, so gating on the name costs essentially nothing across the corpus. It is a targeted exclusion, not a blanket one.

_tool_adapters.py::run going from 9 to 0 looks alarming and is correct. Those 9 files import that module but name other symbols in imported_names, so they are users of the file and not of run. Dropping them is the precision win the gate is for.

The substring match still lets Value match FreeValue within the one correct file. I would leave that, it is bounded to a single file now and parsing the JSON per row to fix it is not worth the cost.

Push that and I will merge. This is a good fix one condition away from done.

@RaghavChamadiya

Copy link
Copy Markdown
Member

Thanks @sloemo01, the root-cause read is right and it is the one I had reached too: target_node_id == sym.file_path is a file-level query answering a symbol-level question, so the header pairing was the symptom rather than the cause. Splitting the two node depths in the comment is the part that will stop this being re-broken.

Gating the import half on imported_names is also the correct instinct. But the way it is spelled reintroduces the same class of fabricated user in a narrower form:

GraphEdge.imported_names_json.contains(sym.name),

imported_names_json is a Text column (models.py:308), so .contains() compiles to LIKE '%name%' against the raw JSON string, not a membership test on the decoded list. A symbol whose name is a substring of another imported name matches. Concretely, used_by for a symbol called Value will pick up every edge whose imported_names holds FreeValue, and Buffer will pick up ConsoleBuffer. Both are short, common C++ names, and the result is a caller listed for a symbol it never mentions, which is the exact failure #1655 reports.

Matching the quoted JSON token closes most of it:

GraphEdge.imported_names_json.contains(f'"{sym.name}"'),

["FreeValue"] no longer matches "Value", because the quote forces the name to start at a token boundary. It is still a string match rather than a real JSON membership test, so it stays a heuristic, but it is a heuristic that cannot silently invent an edge from a substring collision. Worth a line in the comment saying that is why the quotes are there, otherwise they read as incidental.

The two tests are well built, particularly test_empty_header_pair_edge_is_not_a_user pinning the imported_names = [] case directly rather than through a fixture. If you add the quoting, a third case in the same shape (an edge importing FreeValue, asserted absent from Value's used_by) would lock it.

Everything else is ready to go. Push that and I will merge.

@sloemo01

Copy link
Copy Markdown
Contributor Author

Main already carries this fix, so I am closing rather than rebasing a four-hundred-commit-stale branch.

tool_context/targets.py on main keys used_by on the symbol's own node id (getattr(sym, "symbol_id", None) or getattr(sym, "node_id", None)), which is the change this branch made, and its comment gives the same reason: a calls edge is symbol-to-symbol and targets a path::Name, so keying on the file path could only ever answer "who imports this symbol's file".

Main's tests/unit/server/mcp/test_used_by_ranking.py asserts the same two contracts in its docstring, the source keying and the ranking of which twenty survive the cut.

Main's version also goes further than this one did: it matches both node depths, symbol-to-symbol call and reference edges plus file-to-file imports gated on imported_names actually naming the symbol, and it cites the corpus numbers behind the ranking.

The merge conflict was the useful signal, since it was the same lines changed on both sides.

@sloemo01 sloemo01 closed this Sep 18, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

2 participants