query seeds can be hijacked by test/doc rationale nodes — make seed-path exclusion configurable with tests/ as the default
Problem
graphify query's seed selection (_score_query → _pick_seeds) matches query terms against node labels, and rationale/docstring nodes sourced from test files carry generic prose labels that substring-match common words. On multi-term natural-language queries these test nodes out-seed the production symbols the user actually asked about, so the BFS explores test neighborhoods and the 2000-token budget fills with low-signal nodes — the failure mode from #897.
Repro corpus: a Python repo with tests in both tests/ and mcp-svc/tests/.
graphify query "how does the crawl engine handle deduplication of pages?"
After stopword filtering, terms are ['crawl', 'engine', 'handle', 'deduplication', 'pages']. Seeds chosen:
crawl() mcp-svc/mcp_server.py (exact tier)
CrawlEngine agent-svc/agent/crawler.py (relevant)
CrawlEngine calls store.increment_completed() ... tests/integration/test_crawler.py
Deduplication Strategy docs/adr/0038-crawl-engine.md
Engines responded but returned no results with valid URLs. tests/service/test_searxng_client.py
Handler mcp-svc/tests/test_client.py
Pages with >70% link lines and no paragraphs fail. tests/service/test_quality.py
Three of seven seeds come from test files, via the per-term guarantee (#1445): "engine" → Engines responded..., "handle" → Handler, "pages" → Pages with >70% link lines... are the singleton winners for their terms. The per-term guarantee re-injects them even though they are pure noise for this question, and the truncation notice reports 793 nodes, so the caller still can't see DedupManager without follow-up calls.
Proposal
Add a configurable seed-path exclusion applied at seed selection only, with test directories as the default:
- Patterns are gitignore-style globs matched against root-relative
source_file(e.g.tests/integration/test_crawler.py), reusing the existing ignore-matcher indetect.pyrather than a new matching engine. - Default patterns:
tests/,**/tests/**— the second covers nested test dirs (mcp-svc/tests/,src/foo/tests/).docs/is intentionally not in the default; doc nodes are often the intended answer (ADR headings). - Scope is seed selection only: graph construction,
explain,path, and the rendered subgraph traversal are untouched. A test node excluded from seeding remains findable viaexplain "TestDedupManager"and still renders if the BFS reaches it from a real seed (which is usually useful context, e.g.TestCrawlEngineDedupexercisingDedupManager). - Explicit configuration replaces the default; an empty list disables filtering entirely (opt-out preserves current behavior).
Config surface (following existing precedent)
- CLI:
graphify query "..." --seed-ignore <pattern>(repeatable), alongside--context/--budget. - Env:
GRAPHIFY_QUERY_IGNORE_PATTERNS(comma-separated), matching theGRAPHIFY_OUT/GRAPHIFY_MAX_CONTEXTSpattern. - MCP
query_graphtool:seed_ignore_patternsargument, alongsidecontext_filter/token_budgetin_tool_query_graph(serve.py ~1494). - Precedence: CLI flag > env var > default.
Implementation sketch
The filter belongs in exactly one place because of how #1445 interacts with it:
_score_query(serve.py ~433): skip excluded nodes in thenode_iterloop (the trigram candidate iteration). This removes them from both the ranked list andbest_seed_by_termin one pass._pick_seeds(serve.py ~627): no change needed — but must not re-filter independently, because filtering only the ranked loop would let the per-term guarantee re-inject an excluded winner at serve.py ~701._query_graph_text(serve.py ~1085): new keyword argseed_ignore_patterns: list[str] | None, forwarded to_score_query; CLI parse and MCP tool forward it.
Edge cases
- Test-focused queries must still work. If filtering leaves zero seeds while the unfiltered set was non-empty, retry unfiltered once (optionally: skip the fallback when a query term contains
test). A user asking "how do tests verify dedup" should get test nodes. - Per-term guarantee semantics: a term whose only matches are excluded contributes no seed rather than an excluded one. The fallback covers the all-excluded case.
explain/path/_find_nodeare byte-identical — the filter never reaches them.source_fileis already root-relative (verified:tests/unit/...,mcp-svc/tests/...), so no path-normalization work is needed.
Acceptance criteria
- The repro query seeds on
CrawlEngine/DedupManagerinstead of test-rationale nodes, without--contextor vocabulary tricks. --seed-ignore ''(orGRAPHIFY_QUERY_IGNORE_PATTERNS=) restores today's behavior exactly.- A test-focused query ("how does test_crawler assert dedup") still returns test nodes via the fallback.
graphify query/explain/path/ MCPquery_graphagree;explainandpathoutputs are unchanged.
Related
- #897 seed scoring returns low-relevance nodes (the token-cascade symptom)
- #1445 per-term seed guarantee (the re-injection point this feature must respect)
- #1602 term-coverage scaling (already dampens exact-tier collisions; this addresses the remaining substring-tier noise)
- #1766 seed label dedup
Supporting data from a production TypeScript+Python monorepo (graphify 0.9.25, 8,437-node graph), measured during an agent-run tooling audit — including one datum that strengthens the case for path-based seed exclusion specifically.
The hijack reproduces even with zero rationale nodes in the graph. We first hit the classic form: graphify query "what calls buildWalletEvidence" returned 90 nodes for a 4-caller answer, 49% of them from one unrelated test file in a different service — seeded on the word "calls" matching test_create_order_calls_crawler_and_returns_201(). We then stripped every rationale node from the built graph (file_type == "rationale": 1,911 of 10,150 nodes, 18.8%) and rebuilt. Same question today, on a graph with 0 rationale nodes: the output is still dominated by test_*() --calls--> _db_override() edges from src/api/tests/ — because plain code labels (test function names) carry the same English words. So node-type filtering alone cannot fix this; seed-path exclusion as proposed here catches the residual class. Both are needed.
Two related observations from reading the installed package:
- The extractor's own comment says rationale nodes are excluded from callability because "their labels are docstring text, not callable", but
_pick_seedsapplies no equivalent filter — the asymmetry is what makes prose seedable at all. - A shipped
semantic_cleanupmodule already reasons about "sentence-like rationale labels" but is only imported for one narrow purpose and never runs as a cleanup pass over a built graph. The fix appears to exist and be unwired.
Also measured: --context call does not rescue a bad seed (with the English phrasing it returned more noise lines, 82 vs 68), while affected "buildWalletEvidence()" returns exactly the 4 real call sites at ~1,041 output tokens versus ~4,622 for query with the answer buried.
Corroborating this from a very different corpus, plus a measurement of the fix you suggest.
Same failure on a prose corpus, not just code. Vault of ~2,200 markdown notes; graph 9,870 nodes / 2,183 concept nodes, built with --backend claude-cli on 0.9.50.
graphify query "how much of my bankroll should I bet given an edge"
Seeds chosen:
Beta-and-Alpha, Beta and Alpha, Better-Than-Average Effect,
edge_quality(), "c2 predicate: does this 8-K report the given item (e.g. '2.02')?"
Those are matches on the word "edge" (the code symbol edge_quality()) and on "be" (Beta-, Better-). The corpus has a Kelly-Criterion concept node with degree 22 that is precisely the answer — it never appeared as a returned node, only as a community label on unrelated nodes.
So this is not specific to tests/: the same label-substring mechanism lets a code rationale node hijack a prose query, and vice versa. Path-based exclusion of tests/ would not have helped here — scripts/vault_neighbors.py is production code in this repo.
Head-to-head against plain BM25, 30 frozen paraphrase queries (never the document title), same corpus:
| hit@5 | MRR | cost | |
|---|---|---|---|
graphify query |
6/30 | 0.120 | ~1,639 tokens/response |
| stdlib BM25 (~30 lines) | 14/30 | 0.357 | ~200 tokens for 5 paths |
The fix that worked for us, measured. Rather than filtering which nodes may seed, we changed what the seeding is scored against: run BM25 over the source documents first, then seed traversal from the winning file's nodes. On a frozen 20-target set that took reach from 2/20 to 11/20.
That suggests the root cause is not really which nodes are eligible, but that labels are the wrong text to score against at all. A label is a short string — no term frequency, no length normalization — so _score_query is effectively a degenerate BM25 that inherits every vocabulary-mismatch failure without the statistics that make BM25 work. Node labels are a good index for explain/path, where the user supplies an exact name; they are a poor index for a natural-language question.
An exclusion list would help the specific tests/ case in this issue, but a query whose words happen to match any short label anywhere will keep hijacking seeds. Scoring against document text (or an indexed per-node summary) would address the class.
Happy to share the frozen query set or the harness if useful.