Skip to content

feat(query): --compact writes the same answer in ~1.7x fewer tokens (#4469) - #4470

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

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

Conversation

@devkancheti4-design

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

Copy link
Copy Markdown
Contributor

What does this PR do?

Closes #4469. It adds compact to graphify query (CLI --compact, MCP query_graph compact: true): the same answer in about 1.7x fewer tokens.

The budget cut, the truncation notices and the node order are decided exactly as today. Only the NODE lines that survive the cut are rewritten:

  • each source file appears once, in the order of its first node, with its nodes beneath it in their original order;
  • the community most of a file's nodes share goes on the FILE line, and a node names its own community only when it differs;
  • empty fields (an empty community=, no location) are left out;
  • a file's own node (its label is the file name, at L1) is dropped when the FILE line already says everything it would. It stays when it carries a different community or a learning or attrs annotation.
FILE django/db/models/query.py community=Query API
  QuerySet L280
  filter() L1203
  Prefetch L2148 community=Prefetching
FILE (none)
  os

Default output is unchanged. compact defaults to false everywhere.

Measured

300 SWE-bench Lite issues x 2 queries (the issue title, and the title plus 400 characters), 12 repos, default BFS depth 2, 2,000-token budget:

graphs answers default compact saving same files, same order
AST-only (update --no-cluster) 600 1,588 tokens 912 tokens 1.74x (1.63–2.02x per repo) 600 of 600
clustered (cluster-only), 5 repos 48 1,522 tokens 1,030 tokens 1.48x 48 of 48

Tokens are characters divided by 4. "Same files, same order" compares the distinct src= paths in printed order with the FILE lines.

Type of change

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

Verification & Invariants

Invariant: compact changes how the chosen nodes are written, never which nodes are chosen or in what file order.

_subgraph_to_text (31 callers) is untouched. Compaction is a separate pure pass, _compact_answer(text, token_budget), over the answer _subgraph_to_text already rendered: same cut, same notices, same order. Only _render_query calls it, and only when compact=True. Every field it rewrites was already passed through sanitize_label. If any NODE line does not parse, the answer is returned unchanged. A complete answer that was over budget only in its default form loses the over-budget notice once its compact form fits.

  • Read the CONTRIBUTING.md guide.
  • Reproduced the issue and identified the invariant.
  • Made the smallest fix necessary.
  • Added an isolated boundary test.
  • Kept the PR description synchronized with the final implementation.
  • Documented any limitations / unsupported cases explicitly. The gain is smaller on clustered graphs (1.48x), since communities differ more within a file there. Agents that parse NODE lines keep the default.

How was this tested?

uv run python -m pytest -q tests/test_query_compact.py        # 10 passed
uv run python -m pytest -q tests/test_query_*.py tests/test_benchmark_real_query.py   # 73 passed
uv run python -m pytest -q tests                              # 7815 passed, 7 failed: test_ext_tagged_id_clash.py,
                                                              # the same 7 fail on v8 without this change here
uv run ruff check graphify/serve.py graphify/cli.py tests/test_query_compact.py   # clean

The new tests check four things:

  • compact=False returns the default answer;
  • compact gives the same files in the same order and is shorter;
  • labels and locations are kept, and empty fields are dropped;
  • the file-node and community rules hold, a truncated answer compacts exactly the nodes the default shows, under the same notice, and learning and attrs annotations survive;
  • a NODE line that does not parse leaves the whole answer unchanged.

Graphify-specific checklist

  • No skill fragments changed, so there are no generated artifacts to bless.
  • AST/structural extraction is untouched. The change is rendering only and deterministic.
  • No shell or Python interpolation; every field is already sanitized before compaction.
  • No API keys or local graph data included.
  • AI authorship disclosed in the commit message.

This comes from the same SWE-bench Lite study of graphify query as the seed-order fix (#4358) and --seed (#4289). It covers which files the query finds, in what order, and at what token cost. I have a few more measured changes to the query path from that work. I'd be glad to go through them with you, or to share the evaluation harness if it would help you judge query changes in general.

A query answer repeats each node's full file path, and on an unclustered
graph an empty community= field, on every NODE line: on SWE-bench Lite
answers those two make up about half the characters. compact (CLI --compact,
MCP query_graph compact=true) keeps the budget cut, the notices and the order
exactly as they are and rewrites only the NODE lines that survive: each source
file once, in the order of its first node, with its nodes beneath, the
community most of them share on the FILE line, and empty fields left out.
A file's own node is dropped when the FILE line already says everything it
would.

Over 600 answers (300 SWE-bench Lite issues x 2 queries, 12 repos, AST-only
graphs): 1,588 -> 912 tokens (1.74x fewer), the same files in the same order in
600 of 600. On clustered graphs (5 repos, 48 answers): 1.48x, 48 of 48.
Default output is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@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.

@github-actions github-actions Bot added the contributor Pull request from a returning community contributor label Oct 15, 2026

@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 6 changed function(s) (3 sampled, not proven, 3 not verified).

Formal verification. PR-changed functions: 3/6 verified (0 proven, 3 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 --compact flag to graphify query (and a matching compact argument on the MCP query tool) that renders the same answer in fewer tokens, with each source file written once and its nodes listed beneath. The budget cut, notices and ordering are still decided by the default path, and _compact_node_block rewrites only the surviving NODE lines, so a node with no community can inherit its file's shared community label and the grouped view may not match the default output field for field. With the flag off, output is unchanged, and a complete answer that is over budget reports the size of its compact form instead; the MCP argument is read straight from the request, so a string like "false" can turn compact mode on.

Worth a look

  • Compact view silently gives community-less nodes the file's shared community — graphify/serve.py:1360 · Escalate · medium
    • 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 — 849 functions depend on the 277 functions this change touches.

Health — this change adds coupling hotspots:

  • worse: _query_graph_text() — 49 callers, 5 callees
  • worse: _subgraph_to_text() — 31 callers, 3 callees

Verification — 849 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: 849 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_compact.py — impact, changed-test
  • tests/test_query_induced_edges.py — impact
  • 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)

No difference found (not proven): No behavior difference found in \_subgraph\_to\_text (not a proof).

The verifier ran both versions of \_subgraph\_to\_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.

· 1 grounded finding(s) anchored inline below; 1 more finding(s) on lines outside this diff (see the check run).

Comment thread graphify/serve.py Outdated


def _subgraph_to_text(G: nx.Graph, nodes: set[str], edges: list[tuple], token_budget: int = 2000, *, seeds: list[str] | None = None) -> str:
def _subgraph_to_text(G: nx.Graph, nodes: set[str], edges: list[tuple], token_budget: int = 2000, *,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Health regression — _subgraph_to_text()

31 callers depend on it (afferent coupling).

Grounded coupling-delta finding (deterministic), not an LLM guess.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Addressed in cf6f238. _subgraph_to_text is back to v8 exactly: no signature or body change, so its 31 callers are untouched. Compaction is now a separate pure pass, _compact_answer(text, token_budget), over the already rendered answer. Only _render_query calls it, and only when compact=True. If a NODE line doesn't parse, the answer comes back unchanged. The measurements are the same: 1.74x fewer tokens over 600 SWE-bench Lite answers, with the same files in the same order in 600 of 600.

… applied by _render_query

_subgraph_to_text has 31 callers, so its signature and body are back to v8
exactly. _compact_answer rewrites an already rendered answer and only
_render_query calls it, only when compact is asked for. If any NODE line does
not parse, the answer is returned unchanged. Same measurements: 1.74x fewer
tokens over 600 SWE-bench Lite answers, the same files in the same order in
600 of 600; 1.48x on clustered graphs.

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

Copy link
Copy Markdown
Contributor

Reviewed and tests pass (10/10).

Confirming the bot's "string \"false\" turns compact on" finding — real, worth fixing: compact = bool(arguments.get("compact", False)) coerces a JSON string. Suggest arguments.get("compact") is True. Same pattern in #4478 for learned.

The bot's other finding ("community-less nodes inherit the file's shared community") looks like a false positive: line 1349 sets mine = community if community != shared else "", so an empty community stays empty. Worth a second look but I don't see the inheritance path.

No other blocking issues.

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 answers repeat each node's file path; a compact form gives the same answer in ~1.7x fewer tokens

2 participants