Skip to content

feat(query): --learned starts from nodes that past useful answers to a similar question cited (#4477) - #4478

Open
devkancheti4-design wants to merge 2 commits into
Graphify-Labs:v8from
devkancheti4-design:query-learned
Open

devkancheti4-design wants to merge 2 commits into
Graphify-Labs:v8from
devkancheti4-design:query-learned

Conversation

@devkancheti4-design

@devkancheti4-design devkancheti4-design commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do?

Closes #4477. It adds learned to graphify query (CLI --learned, MCP query_graph learned: true): the query starts from nodes that past useful answers to a similar question cited. This closes the loop save-result and reflect already open: the memory steers where the traversal starts, instead of only labelling nodes.

_learned_seeds(G, question) reads the work-memory overlay (the .graphify_learning.json sidecar from graphify reflect --graph). A node qualifies when all of these hold:

  • its lesson is preferred or tentative, never contested, and dead-end provenance is ignored;
  • its lesson is not stale: the existing code fingerprint says the code it was learned on is unchanged;
  • one of its useful provenance questions has at least 40% of its query terms covered by the new question, sharing at least two of them (or all of a shorter question's).

Up to 3 such nodes become start nodes ahead of the keyword seeds. They're ranked by coverage, then shared terms, then lesson score, then node id, so the order is deterministic. The header names them: Learned (past useful answers): [...]. Explicit --seed values are never overridden.

A running MCP server picks up new memory too. The graph cache keyed each graph on graph.json's stat, and reflect writes only the sidecar, so a server started before a reflect kept its old memory. The cache now also stats the sidecar, and when only the sidecar changed it re-reads the overlay onto the cached graph without reloading the graph. This also keeps the existing learning= annotations current.

No embeddings: the terms are _query_terms, the same ones keyword seeding uses. _subgraph_to_text is untouched. learned defaults to false, and the CLI only reads the sidecar when it's set, so default output is unchanged.

Measured, end to end through the real pipeline

SWE-bench Lite, 12 repos, default BFS depth 2, 2,000-token budget.

  • Teaching: for each repo, the older half of the issues went through save_query_result(question=title, source_nodes=[the fixed file's node], outcome="useful"), then reflect(..., graph_path=...).
  • Asking: each taught issue by its body (the same issue in other words), and each newer issue by its title (never taught).
questions right file first: default → learned top 5: default → learned
same issue in other words (140) 26 → 98 50 → 105
new, never taught (145) 44 → 42 70 → 70

Where the 40% comes from: the same issue in other words covers a median 0.44–0.50 of the taught question's terms, and a different issue covers 0.20–0.25. I chose 0.4 on django and checked it on sympy and matplotlib, which it wasn't tuned on.

Type of change

  • Bug fix
  • New feature
  • Documentation
  • Tests or CI
  • Refactor
  • Security fix

Verification & Invariants

Invariants:

  • without learned, the output is unchanged;
  • with it, a node enters only on a fresh, positive lesson whose question the new one largely covers;
  • explicit seeds win.

The sidecar is still a derived, read-only overlay: nothing is written to graph.json, and the query never writes the sidecar.

  • Read the CONTRIBUTING.md guide.
  • Reproduced the issue and identified the invariant.
  • Made the smallest fix necessary.
  • Added isolated boundary tests and an end-to-end test.
  • Kept the PR description synchronized with the final implementation.
  • Documented any limitations / unsupported cases explicitly:
    • lexical matching only, so a rewording that shares under 40% of the taught question's terms is not recognised;
    • on new questions the right-file-first count moved 44 → 42 across 145, with the top 5 unchanged.

How was this tested?

uv run python -m pytest -q tests/test_query_learned.py      # 10 passed
uv run python -m pytest -q tests -k "query or reflect or learning or memory or lesson or mcp or serve or ingest or save_result"
                                                            # 792 passed, 9 skipped
uv run ruff check graphify/serve.py graphify/cli.py tests/test_query_learned.py   # clean

The new tests cover:

  • a question in other words finds the cited node, and an unrelated one doesn't;
  • a single shared term is not enough;
  • stale, contested, dead-end and vanished nodes never count;
  • the ranking and the cap;
  • the query starts from the learned node and names it in the header;
  • learned=False gives the default answer even with a memory;
  • explicit seeds are never overridden;
  • the real pipeline, save_query_result → reflect --graph → query;
  • a running server's cached graph sees a reflect done after it loaded (fails without the cache fix).

Graphify-specific checklist

  • No skill fragments changed.
  • AST/structural extraction untouched; deterministic ordering throughout.
  • No shell or Python interpolation; header labels are taken from the graph, as for the existing Start: line.
  • No API keys or local graph data included.
  • AI authorship disclosed in the commit message.

This continues the same SWE-bench Lite work on graphify query: #4358 (seed order), #4289 (--seed) and #4470 (--compact). I'm happy to walk through the evaluation or extend it, for example to weigh preferred lessons more, or to make this the default once the memory loop is in wider use.

🤖 Generated with Claude Code

…a similar question cited

graphify save-result --outcome useful and graphify reflect --graph already
record which nodes answered which questions (.graphify_learning.json), but the
query never used it: a question asked again in other words started from
scratch. With learned (CLI --learned, MCP query_graph learned=true), nodes whose
useful provenance questions are covered at least 40% by the new question's
query terms (sharing two or more of them) become start nodes ahead of the
keyword seeds, ranked by coverage, shared terms, then lesson score; at most 3.
Only preferred and tentative lessons count, stale ones (code changed since)
never do, explicit --seed values are never overridden, and the header names the
learned nodes. No embeddings: the terms are _query_terms.

End to end through save_query_result -> reflect -> query on SWE-bench Lite
(12 repos, older half taught by title, cited node = the fixed file):
the same issue asked in other words, right file first 26 -> 98 of 140, top 5
50 -> 105; new issues (never taught) 44 -> 42 and 70 -> 70.
Default output is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions github-actions Bot added the contributor Pull request from a returning community contributor label Oct 15, 2026
@github-actions

Copy link
Copy Markdown

Thanks for the pull request, @devkancheti4-design. A maintainer will review it soon.

Want to talk it through while it is in review? Come join us on our Discord server. For longer-form discussion there is also GitHub Discussions.

A couple of things that speed up review: make sure the test suite passes on Python 3.10 and 3.13, and that the change keeps extraction deterministic.

@graphify-labs graphify-labs Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Graphify reviewed this change.

Worth a look — the grounded gate found no coupling regressions or blocking issues, but 1 advisory finding(s) below merit a look before merge.

Not checked: tests were not run; formal verification proved 0 of 5 changed function(s) (2 sampled, not proven, 3 not verified).

Formal verification. PR-changed functions: 2/5 verified (0 proven, 2 may-equivalent, 0 distinguished) · 3 not verified (3 vacuous).

Not verified on this run: dispatch\_command (vacuous: never exercised), \_build\_server (vacuous: never exercised), \_render\_query (vacuous: never exercised).


Graphify review — findings

Adds an opt-in --learned flag to graphify query that prepends nodes cited by past useful answers to similar questions ahead of the keyword seeds, so the answer they found renders first. A past question matches when the new one covers at least 40% of its query terms (and shares at least two), counting only non-stale preferred or tentative lessons; explicit --seed values are never overridden and default output is unchanged. Exposes the same learned option on the MCP query tool and lists the matched labels in the result header, but the MCP path coerces the argument with bool() and never loads the reflect overlay that the CLI attaches to the graph.

Worth a look

  • MCP learned flag is a silent no-op: overlay never loaded — graphify/serve.py:2374 · Escalate · medium · 2 independent checks
    • agreed by 2 of 2 members but NOT verified (no proof, no reproducing execution) — consensus is not a verdict; needs human review
Analysis details — impact, health, verification

Impact & health

Graphify review

Impact — 848 functions depend on the 276 functions this change touches.

Health — this change adds coupling hotspots:

  • worse: _query_graph_text() — 52 callers, 6 callees
  • worse: _query_terms() — 19 callers, 3 callees

Verification — 848 functions in the blast radius were not formally verified this run (proofs are advisory here).

Gate & verification

graphify gate

PASS — objectively clean (no health regressions, tests not run — proofs not run this pass (advisory)). Grounded, not self-assessed.

Advisory (not blocking):

  • verification_scope: 848 function(s) in the blast radius were not formally verified this run

Test selection

Test selection

47 of 423 test file(s) selected (11%) via static blast radius.

  • tests/test_affected_cli.py — impact
  • tests/test_agents_platform.py — impact
  • tests/test_benchmark.py — impact
  • tests/test_benchmark_raw_graph.py — impact
  • tests/test_benchmark_real_query.py — impact
  • tests/test_cloud_cta.py — impact
  • tests/test_codebuddy.py — impact
  • tests/test_compact_graph_json.py — impact
  • tests/test_dedup_shrink_refuses_force_write.py — impact
  • tests/test_devin.py — impact
  • tests/test_explain_cli.py — impact
  • tests/test_explain_same_file_tie.py — impact
  • tests/test_extract_cli.py — impact
  • tests/test_file_label_disambiguation.py — impact
  • tests/test_global_add_tag_inference.py — impact
  • tests/test_god_nodes_cli.py — impact
  • tests/test_hollow_chunks_arm_shrink_guard.py — impact
  • tests/test_hook_guard_token_match.py — impact
  • tests/test_hook_out_of_project_paths.py — impact
  • tests/test_hook_strict.py — impact
  • tests/test_incomplete_build_guard.py — impact
  • tests/test_install.py — impact
  • tests/test_install_references.py — impact
  • tests/test_install_version_warning.py — impact
  • tests/test_lookup_exit_codes.py — impact
  • tests/test_mcp_graph_view_cache.py — impact
  • tests/test_merge_chunks_validation.py — impact
  • tests/test_multigraph_diagnostics.py — impact
  • tests/test_no_dedup_flag.py — impact
  • tests/test_opencode_plugin_refresh.py — impact
  • tests/test_partial_cache.py — impact
  • tests/test_path_cli.py — impact
  • tests/test_query_cli.py — impact
  • tests/test_query_induced_edges.py — impact
  • tests/test_query_learned.py — impact, changed-test
  • tests/test_query_mcp_direction.py — impact
  • tests/test_query_names_its_graph.py — impact
  • tests/test_query_seed_order.py — impact
  • tests/test_query_seeds.py — impact
  • tests/test_serve.py — impact
  • tests/test_serve_http.py — impact
  • tests/test_skill_auto_refresh.py — impact
  • tests/test_skill_version_warning.py — impact
  • tests/test_stale_prune.py — impact
  • tests/test_terraform.py — impact
  • tests/test_truncation_full_answer.py — impact
  • tests/test_unverified_semantic_shrink.py — impact

Selection is safe under the controlled-regression assumption; always-run tests + a periodic full run are the backstops. Advisory — it never changes the check verdict.

Formal verification

No difference found (not proven): No behavior difference found in \_run\_cli (not a proof).

The verifier ran both versions of \_run\_cli on many inputs and saw identical behavior every time. Strong evidence the change is safe, but evidence, not a proof.

Guarantee: Empirical: differential testing (both versions run on many generated inputs). A divergence on an untested input remains possible, so this is 'no counterexample found', not 'proven equivalent'.

Note: An input the sampler did not try could still differ.

Could not verify: Could not verify dispatch\_command.

The verifier did not have enough to check dispatch\_command, so it is saying so rather than guessing. No false assurance is the whole point.

Guarantee: No guarantee either way, this is an honest abstention, not a pass.

Note: Reason: no capturable inputs from the test suite; property tier: not verifiable: all 40 sampled inputs raised on both versions — the function never executed, so 'no divergence' would be vacuous (mostly SystemExit — names the real obstacle, not a sampling gap)

Could not verify: Could not verify \_build\_server.

The verifier did not have enough to check \_build\_server, so it is saying so rather than guessing. No false assurance is the whole point.

Guarantee: No guarantee either way, this is an honest abstention, not a pass.

Note: Reason: no capturable inputs from the test suite; property tier: not verifiable: all 40 sampled inputs raised on both versions — the function never executed, so 'no divergence' would be vacuous (mostly ValueError — names the real obstacle, not a sampling gap)

No difference found (not proven): No behavior difference found in \_query\_graph\_text (not a proof).

The verifier ran both versions of \_query\_graph\_text on many inputs and saw identical behavior every time. Strong evidence the change is safe, but evidence, not a proof.

Guarantee: Empirical: differential testing (both versions run on many generated inputs). A divergence on an untested input remains possible, so this is 'no counterexample found', not 'proven equivalent'.

Note: An input the sampler did not try could still differ.

Could not verify: Could not verify \_render\_query.

The verifier did not have enough to check \_render\_query, so it is saying so rather than guessing. No false assurance is the whole point.

Guarantee: No guarantee either way, this is an honest abstention, not a pass.

Note: Reason: no capturable inputs from the test suite; property tier: not verifiable: all 223 sampled inputs raised on both versions — the function never executed, so 'no divergence' would be vacuous (mostly TypeError — names the real obstacle, not a sampling gap)

· 2 more finding(s) on lines outside this diff (see the check run).

… startup

The MCP graph cache keys each graph on graph.json's stat, and the work-memory
overlay is read when the graph loads. `graphify reflect` writes only the
sidecar, so a server started before it never saw the new lessons, and
`query_graph` with `learned: true` (and the NODE-line annotations) kept the
memory the server started with. The cache now also stats the sidecar and,
when only the sidecar changed, re-reads the overlay onto the cached graph
without reloading it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@devkancheti4-design

Copy link
Copy Markdown
Contributor Author

Thanks for the check. I tested the MCP path directly, and the main finding doesn't hold. The server loads every graph through _load_entry → _load_graph → _read_graph, and _read_graph attaches the sidecar as _learning_overlay. I called the real query_graph handler (mcp 2.3.0) on a graph whose memory went through save_query_result → reflect --graph. With learned: true the header has the Learned (past useful answers): [...] line, and with learned: false it doesn't.

It did point me at a real gap next to it, though. The context cache keys each graph on graph.json's stat, and reflect writes only the sidecar, so a server started before a reflect kept its old memory until restart. e16b32d fixes that: the cache also stats the sidecar, and when only the sidecar changed it re-reads the overlay onto the cached graph, with no graph reload. The new test test_a_running_server_sees_a_reflect_done_after_it_loaded_the_graph fails without the fix and passes with it. This also keeps the existing learning= NODE annotations current.

bool(arguments.get("learned")) matches how undirected is read in the same server, so I left it as is.

@nothariharan

Copy link
Copy Markdown
Contributor

Thanks for the PR — reviewed and tests pass (10/10).

One minor hardening note on the MCP side: learned = bool(arguments.get("learned", False)) coerces a JSON string like "false" to True. Most clients send real booleans, but to be safe, prefer a strict check such as arguments.get("learned") is True. Same pattern exists in #4470 for compact.

Also, the bot's "MCP learned is a silent no-op" finding appears to be a false positive: the overlay is attached in _read_graph (modified in this PR) via _load_entry -> _load_graph -> _read_graph, and the sidecar mtime refresh in _GraphContextCache.load re-reads it. Worth double-checking but I don't see a gap.

Integration note: #4481 also edits the same start_nodes assembly hunk and _render_query signature; merging both needs an explicit ordering decision (suggested: learned -> lead -> keyword seeds).

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

contributor Pull request from a returning community contributor

Projects

None yet

Development

Successfully merging this pull request may close these issues.

query never uses the work memory: a question already answered, asked in other words, starts from scratch

2 participants