Skip to content

perf(query): add opt-in SQLite snapshots for CLI queries - #5383

Open
Max17190 wants to merge 10 commits into
Graphify-Labs:v8from
Max17190:perf/query-snapshot
Open

Max17190 wants to merge 10 commits into
Graphify-Labs:v8from
Max17190:perf/query-snapshot

Conversation

@Max17190

@Max17190 Max17190 commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Why

A fresh graphify query process loads the full graph from graph.json. Keyword queries also rebuild the search index. A Guava query that returned two nodes took 3.37 s and peaked at 388 MiB.

Summary

Add graphify query --snapshot. The first invocation builds a local SQLite cache for that generation of graph.json. Later invocations read candidate nodes and the edges they traverse, then use the existing scorer and renderer.

The baseline includes the betweenness and path-rebasing changes from #5303 and #5322. #5382 reduces work during clustering. This change targets the cost of querying an existing graph.

Related to #1297. #3271 persists trigram postings. The snapshot also serves node and adjacency reads from disk.

Type of change

  • New feature

Verification & Invariants

The snapshot preserves stdout, stderr, and exit status. It supports undirected simple graphs with normalized labels. The JSON path handles unsupported graph types, nonnormalized labels, arguments SQLite cannot encode, and cache read or build failures. Context-filtered queries retain learning annotations on both the JSON and snapshot paths.

The cache is specific to the graph generation and the interpreter's Unicode data version. Invalid metadata and corrupt payloads fall back to JSON. The next successful build replaces the invalid cache. One process builds at a time and concurrent queries return their JSON answer without waiting. The README documents invalidation and disk usage.

Benchmarks

Workload Pairs Upstream p50 Snapshot p50 Speedup Peak RSS, MiB
Graphify, incremental resolution 5 1,058 ms 285 ms 3.7× 188 → 98
Django, QuerySet 5 1,583 ms 250 ms 6.3× 312 → 108
Guava, broad question 5 3,278 ms 663 ms 4.9× 366 → 309
Guava, context filter 5 3,368 ms 168 ms 20.0× 388 → 63
Guava, seed and 22 edges 5 1,286 ms 125 ms 10.3× 363 → 56
251K-node composite, mixed question 3 9,140 ms 317 ms 28.9× 908 → 78

Fresh CLI processes on an Apple M5 with CPython 3.13. Each pair ran against v8 at b582ad40 and this PR at 29635a75. The snapshot runs reused an existing cache. All 28 pairs matched stdout, stderr, and exit status. The composite combines Graphify, Django, and two namespaced copies of Guava. Peak RSS is the median per-process high-water mark.

Guava's first request took 7.16 s including cache construction. Its 149 MB graph produced a 260 MB cache. The composite took 21.49 s on the first request and produced a 736 MB cache. The flag is opt-in.

Changes after rebasing onto v8

v8 now caches per-node query fields, degrees, and traversal indexes for the whole graph. For a snapshot, those caches fill lazily as the query reaches each node, so snapshot scoring and traversal run the same v8 code without loading every row. Against Graphify's own graph (26,369 nodes), 32 queries covering BFS, DFS, context filters, depth, budget, seeds, short terms, and dotted names matched stdout and exit status with and without --snapshot. None fell back to JSON. Warm snapshot queries ran 3.9× to 7.0× faster, best of five. The first query, which builds the cache, took 1.9 s against 0.95 s.

  • graphify.build and graphify.affected no longer import the snapshot module.
  • The answer prints before the snapshot is written. A failed build no longer changes the output or exit status, and an interrupted build has already printed the answer.
  • Dotted queries such as Type.Member check a table of source files instead of reading every node row. The cache format moves to version 3, so existing caches rebuild.
  • The next build removes partial files left by a killed builder.
  • New parity tests cover the qualified-name tier, source path queries, file path seeds, and hub cutoffs, with and without --context.

Known limitation: a --seed given as a label or path goes through the shared seed resolver, which reads every row. Seeds given as node IDs are unaffected.

Test Plan

Passed 357 focused tests. Regression coverage includes deeply nested cache corruption, concurrent cold queries, and context-filtered learning annotations. The annotation test verifies that a warm snapshot and the JSON path render identical output. The concurrent test keeps one builder open while a separate CLI process returns its JSON answer. In a separate run against Graphify's own graph, four cold CLI processes returned identical output and built one snapshot. The snapshot tests passed on CPython 3.11 through 3.14. A separate CLI run warmed the cache on Python 3.13 and verified on Python 3.14 that both the first and subsequent snapshot queries matched the JSON path for a case mapping added in Unicode 16.

python -m pytest -q tests/test_query_snapshot_cli.py tests/test_query_cli.py tests/test_query_mcp_direction.py tests/test_serve.py tests/test_build.py::test_build_annotations_all_resolve
python -m pytest -q tests/test_query_deterministic_order.py tests/test_query_fallback_edges.py tests/test_query_induced_edges.py tests/test_query_names_its_graph.py tests/test_query_seed_order.py tests/test_query_seeds.py tests/test_query_source_first.py tests/test_mcp_graph_view_cache.py
ruff check .
pyright --pythonpath <interpreter> --outputjson
python -m tools.skillgen --check
python -m graphify update .

Ruff and the generated skill check passed. Pyright produced the same diagnostics as before the follow-up.

After the rebase, 627 focused tests passed across the snapshot, query, serve, affected, and build suites, and ruff passed.

Before this follow-up, all four Python versions passed on the same Git tree across two CI runs. The second Python 3.12 job hit a timing-sensitive watch test. I reproduced its stale-graph failure on unmodified v8 by delaying a Git subprocess after it closed its output pipes. The test replaces the process-wide time.sleep. Isolating that patch to the watcher made all six watch cases pass with the delay in place. Earlier matrix · Python 3.12 pass on the same tree.

CI matrix for the current commit.

Graphify-specific checklist

  • Read the contribution guide and reviewed serialization and cache handling.
  • Verified query parity and cache invalidation through the CLI.
  • Documented cache costs and supported graph types.
  • Checked generated skill artifacts.
  • Disclosed AI assistance in the original implementation commits.

@Max17190
Max17190 requested a review from safishamsi as a code owner November 21, 2026 20:51
@github-actions

Copy link
Copy Markdown

Thanks for the pull request, @Max17190. 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.11 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 Nov 21, 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 review View in Graphify

Nothing blocking · 5 possible issues to check · Merge confidence 5/5

5 possible issues to check · High impact

graphify query --snapshot can build and reuse a SQLite projection of the graph for query search and traversal.

5 possible issues we couldn't confirm
  • Snapshot write after the answer can crash the query and skip its exit code · graphify/cli.py:2338
  • resolve_seed and resolve_reference_forms now require a QueryGraph but still use networkx-style graph calls · graphify/affected.py:207
  • edge_datas returns one merged entry instead of one per parallel edge when given a query snapshot, because it only recognises networkx graphs · graphify/build.py:1234
  • +2 more in Graphify

They don't change the score.

What this review covered
  • We didn't review 1 file that isn't source code, such as docs, config, images, or generated or third-party code.
  • Some lookups asked for files or lines that do not exist; the review was told and carried on.
  • 6 of 6 changed files inspected. This is scope, not a correctness guarantee.
Code graph · 2985 functions depend on this change
  • 8 functions became more coupled. Largest: main() (131 callers), _query_graph_text() (57 callers), dispatch_command() (8 callers).
  • 629 of 629 test files are affected by this change.
  • Gate, test list and every flagged function: in the Graphify check.

Reviewed 56699ad · 14 earlier findings not re-checked

@Max17190 Max17190 changed the title perf(query): reuse SQLite snapshots across CLI invocations perf(query): add opt-in SQLite snapshots for CLI queries Nov 21, 2026
Comment thread graphify/query_snapshot.py Resolved
Max17190 and others added 10 commits November 25, 2026 11:10
Fresh CLI queries rebuild the search index and hydrate the full graph.
An opt-in snapshot preserves query behavior while reading candidates
and neighborhoods on demand.

Refs Graphify-Labs#1297

Co-Authored-By: OpenAI Codex <[email protected]>
Keep serving JSON results when the optional cache directory cannot be
resolved or an unrelated graph row cannot be indexed. Verify recovery
by corrupting exactly the active generation in the CLI test.

Refs Graphify-Labs#1297

Co-Authored-By: OpenAI Codex <[email protected]>
Use the JSON query path for inputs the snapshot cannot represent. Reject unreadable snapshot metadata and key the projection by Unicode data version so an interpreter upgrade cannot reuse stale search text.

Refs Graphify-Labs#1297
Fall back to the JSON query when a cached payload exceeds the decoder recursion limit. Let one process publish a snapshot while other cold queries keep their JSON result.

Refs Graphify-Labs#1297
Carry the learning overlay into filtered JSON graphs and filtered snapshots. Verify that both paths render the same annotations, including on a warm cache hit.

Refs Graphify-Labs#1297
graphify.build and graphify.affected imported the snapshot module only
for a type annotation, so every build or affected run loaded it and
SQLite even though snapshots are opt-in. Describe what edge_datas reads
with a small protocol in build.py, which keeps its annotations resolvable
at runtime, and import the alias in affected.py for type checking only.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`graphify query --snapshot` built the cache before printing, so an
error outside the handled set, or an interrupt during a slow first
build, lost an answer that was already computed. Print and flush the
answer first, and never let the optional build change the exit status.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A `Type.Member` or `file.ext` query first checks whether the text names
a source file, which decoded every node row of a warm snapshot. Store
the distinct source files in the snapshot and check those instead.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…hots

Compare warm snapshot answers with the JSON path for the qualified-name
tier, source path queries, explicit file seeds, and walks that stop at a
high-degree hub, with and without context filters.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A builder killed before its cleanup ran left its partial database in the
cache directory for good. Builders hold the build lock, so the next one
can safely remove any build file it finds there.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Max17190
Max17190 force-pushed the perf/query-snapshot branch from 38e6946 to 56699ad Compare November 25, 2026 19:38

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.

1 participant