Skip to content

perf(serve): persist the trigram index and add an exact-id fast path - #3271

Open
mallyskies wants to merge 4 commits into
Graphify-Labs:v8from
masquepublishing:perf/trigram-cache-and-exact-id
Open

mallyskies wants to merge 4 commits into
Graphify-Labs:v8from
masquepublishing:perf/trigram-cache-and-exact-id

Conversation

@mallyskies

@mallyskies mallyskies commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

A cold CLI call spends most of its time rebuilding the trigram index. _get_trigram_index memoizes on G.graph, which is right for a long-lived server but does nothing for a CLI where every invocation is a fresh process. The index is small and pickles in a fraction of a second, so it can be persisted to disk instead.

Two changes.

An on-disk trigram cache, keyed on the graph file's path, mtime and size. Writes go to a temporary file that is renamed into place, so a partially-written file is never read back. Nothing in the cache path raises. If the file is missing, stale or unreadable, the index is rebuilt exactly as it is today.

The cache lives under XDG_CACHE_HOME or LOCALAPPDATA rather than beside graph.json because a large cache file written into the corpus could mistakenly end up part of the corpus itself. GRAPHIFY_TRIGRAM_CACHE_DIR overrides the location and GRAPHIFY_TRIGRAM_CACHE_DISABLE=1 turns the cache off.

The cache filename carries a digest of that key, so a rebuilt graph.json writes a new name rather than replacing the existing file. That matters on Windows, where replacing a destination another process holds open fails with PermissionError WinError 5 while POSIX allows it. Measured on Windows 11 with a reader holding the file open for three seconds, all four concurrent writers failed, and because the cache path swallows exceptions the failure is silent. Giving each generation its own name removes the contention instead of retrying around it. _prune_trigram_cache deletes superseded generations on write.

An exact-id fast path. _find_node_tiers now returns immediately when the query is already a node id. Callers that hold one were paying a full index build to rediscover a node the graph looks up in constant time. The clearest case is the second call after a find_node_ambiguity error, which hands the caller an id and invites them to call again with it. A single-entry tier also reports no ambiguity, which is correct, since an id names exactly one node.

NOTE: These numbers come from a corpus roughly 12x your largest published benchmark, ERPNext at 22,620 nodes and 48,710 edges. On our 285k-node, 445k-edge graph that was about 6.7s of a 10.3s call. The saving is proportional rather than absolute, so another graph will benefit more or less than ours. Fortunately, the mechanism costs virtually nothing when the cache misses.

🤖 Generated with Claude Code

…de ids

A cold CLI call spent ~6.7s of ~10.3s rebuilding the trigram index.
`_get_trigram_index` already memoizes, but on `G.graph` — right for a
long-lived server, useless to a CLI where every invocation is a fresh
process. The index is small and pickles in ~0.05s, so persist it.

- `_find_node_tiers` returns immediately when the query is already a node
  id. Callers holding one — notably the second call after a
  `find_node_ambiguity` error, which hands the caller an id — were paying
  a full index build to rediscover a node the graph looks up in constant
  time. A single-entry tier also reports no ambiguity, which is correct:
  an id names exactly one node.

- `_get_trigram_index` reads and writes a pickle keyed on the graph file's
  path, mtime and size. Written via temp-file-plus-rename so a torn write
  is never read back; every failure path falls through to a rebuild rather
  than raising, so a corrupt or unwritable cache costs speed, never
  correctness. It lives under the user cache dir (LOCALAPPDATA on Windows,
  XDG_CACHE_HOME or ~/.cache elsewhere), not beside graph.json — an 80 MB
  derived binary inside the corpus lands inside whatever VCS tracks the
  graph, and is not something you want synced between machines.
  GRAPHIFY_TRIGRAM_CACHE_DISABLE=1 opts out;
  GRAPHIFY_TRIGRAM_CACHE_DIR relocates it.

The cache key needs the graph's path. `serve._load_graph` stashes it, but
the CLI builds its own graph in `cli.py` and never calls that function, so
the two load sites `explain` and `path` use stash it too.

Measured on a 209k-node, 221 MB graph: 10.2s -> 3.4s once warm, and a
two-call ambiguity resolution ~20.5s -> ~6.8s. Verified byte-identical
output with and without the cache, that touching graph.json forces a
rebuild, and that a corrupted or unwritable cache degrades rather than
raising.

@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 4 advisory finding(s) below merit a look before merge.

Formal verification. 2 change(s) tested, no difference found (not proven).


Graphify review — findings

Adds an on-disk trigram-index cache so cold CLI queries stop rebuilding the index every invocation: _get_trigram_index now loads a pickled index keyed on the graph file's path/mtime/size and stores it after a build, with the cache living under XDG_CACHE_HOME/LOCALAPPDATA (overridable via GRAPHIFY_TRIGRAM_CACHE_DIR, disableable via GRAPHIFY_TRIGRAM_CACHE_DISABLE) rather than beside graph.json where VCS would pick it up. To make the cache reachable from the CLI—which bypasses _load_graph—both graph-loading paths in dispatch_command stamp _graph_path onto the graph, and _load_graph sets it too. Also short-circuits _find_node_tiers when label is an existing node id, returning it directly so exact-id lookups (including the ambiguity two-step's second call) skip the index build entirely.

Worth a look

  • Untrusted trigram cache is deserialized with pickle — graphify/serve.py:429 · Escalate · high
    • agreed by 2 of 2 members but NOT verified (no proof, no reproducing execution) — consensus is not a verdict; needs human review
  • Non-atomic temp-file rename race with concurrent writers using shared suffix — graphify/serve.py · Escalate · medium
    • agreed by 2 of 2 members but NOT verified (no proof, no reproducing execution) — consensus is not a verdict; needs human review
  • Concurrent trigram cache writers share one temp file — graphify/serve.py:444 · Escalate · medium
    • agreed by 2 of 2 members but NOT verified (no proof, no reproducing execution) — consensus is not a verdict; needs human review
  • Cache path errors can now escape _get_trigram_index — graphify/serve.py:446 · 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 — 587 functions depend on the 182 functions this change touches.

Health — this change adds coupling hotspots:

  • new: dispatch_command() — 2 callers, 123 callees
  • new: _query_graph_text() — 20 callers, 9 callees
  • new: _score_query() — 15 callers, 5 callees
  • new: _query_terms() — 20 callers, 3 callees
  • new: run_benchmark() — 16 callers, 3 callees
  • new: _stale_graph_sources() — 7 callers, 6 callees
  • new: _load_graph() — 9 callers, 4 callees
  • new: _build_server() — 2 callers, 17 callees
  • …and 11 more — each is listed as a finding

Verification — 587 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: 533 function(s) in the blast radius were not formally verified this run

Formal verification

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: not verifiable: all 23 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)

No difference found (not proven): No behavior difference found in \_find\_node\_tiers (not a proof).

The verifier ran both versions of \_find\_node\_tiers 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.

No difference found (not proven): No behavior difference found in \_get\_trigram\_index (not a proof).

The verifier ran both versions of \_get\_trigram\_index 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 \_load\_graph.

The verifier did not have enough to check \_load\_graph, 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: not verifiable: all 23 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)

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

Comment thread graphify/serve.py
pass


def _get_trigram_index(G: nx.Graph) -> dict:

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 — _get_trigram_index()

6 callers depend on it (afferent coupling).

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

Two issues from the automated review of this PR, both real.

The temp file used a shared `<dest>.pkl.tmp`. Two processes caching
concurrently both open that one path, and when the first renames it into
place the second is still holding an open descriptor to that inode and
keeps writing, corrupting the file the first just published; its own
rename then fails because the temp path is gone. A mixed pickle stream
does not unpickle, so the cost is a rebuild rather than a wrong answer,
but the corrupt file survives until something overwrites it. Reproduced
with six concurrent writers: five failed. mkstemp in the destination
directory gives each writer its own name and keeps the rename on one
filesystem.

_store_trigram_cache computed _trigram_cache_path outside its try, and
that helper calls Path.home() and expanduser(), which raise RuntimeError
when the home directory cannot be resolved. So a function documented as
never raising could propagate into any query. The path is now computed
inside the guard, verified by making the helper throw and confirming
containment.

Co-Authored-By: Claude Opus 5 <[email protected]>

@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 5 advisory finding(s) below merit a look before merge.

Formal verification. 2 change(s) tested, no difference found (not proven).


Graphify review — findings

Persists the trigram search index to an on-disk cache beside ~/.cache/graphify (keyed by graph path, mtime, and size) so CLI invocations—which spawn a fresh process each time and never hit the in-memory graph cache—skip the ~6.7s index rebuild, falling back to a rebuild on any cache miss or read/write failure; disable with GRAPHIFY_TRIGRAM_CACHE_DISABLE=1 or relocate with GRAPHIFY_TRIGRAM_CACHE_DIR. Writes are made atomic via a per-process mkstemp temp file plus rename to survive concurrent writers without corrupting a published cache. Stamps _graph_path into the graph in both _load_graph and the two CLI shortest-path/find-node paths so the cache key resolves, and short-circuits _find_node_tiers to return an exact node-id hit without building the index at all.

Worth a look

  • Trigram cache can be stored under the wrong graph generation during concurrent graph rebuild — graphify/serve.py:511 · Escalate · high
    • agreed by 2 of 2 members but NOT verified (no proof, no reproducing execution) — consensus is not a verdict; needs human review
  • Persistent trigram cache can return stale search index when graph content changes without size/mtime change — graphify/serve.py:424 · Escalate · medium
    • agreed by 2 of 2 members but NOT verified (no proof, no reproducing execution) — consensus is not a verdict; needs human review
  • Cache-key validation trusts attacker-supplied 'key' field but still trusts other pickled fields first — graphify/serve.py:447 · Escalate · medium
    • agreed by 2 of 2 members but NOT verified (no proof, no reproducing execution) — consensus is not a verdict; needs human review
  • Trigram cache uses unsafe pickle deserialization — graphify/serve.py:473 · Escalate · medium
    • agreed by 2 of 2 members but NOT verified (no proof, no reproducing execution) — consensus is not a verdict; needs human review
  • Cache path digest derived from resolved(key[0]) may differ from stored graph_path resolution — graphify/serve.py:486 · 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 — 589 functions depend on the 184 functions this change touches.

Health — this change adds coupling hotspots:

  • new: dispatch_command() — 2 callers, 123 callees
  • new: _query_graph_text() — 20 callers, 9 callees
  • new: _score_query() — 15 callers, 5 callees
  • new: _query_terms() — 20 callers, 3 callees
  • new: run_benchmark() — 16 callers, 3 callees
  • new: _stale_graph_sources() — 7 callers, 6 callees
  • new: _load_graph() — 9 callers, 4 callees
  • new: _build_server() — 2 callers, 17 callees
  • …and 11 more — each is listed as a finding

Verification — 589 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: 535 function(s) in the blast radius were not formally verified this run

Formal verification

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: not verifiable: all 23 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)

No difference found (not proven): No behavior difference found in \_find\_node\_tiers (not a proof).

The verifier ran both versions of \_find\_node\_tiers 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.

No difference found (not proven): No behavior difference found in \_get\_trigram\_index (not a proof).

The verifier ran both versions of \_get\_trigram\_index 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 \_load\_graph.

The verifier did not have enough to check \_load\_graph, 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: not verifiable: all 23 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)

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

Comment thread graphify/serve.py
pass


def _get_trigram_index(G: nx.Graph) -> dict:

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 — _get_trigram_index()

6 callers depend on it (afferent coupling).

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

@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 2 advisory finding(s) below merit a look before merge.

Formal verification. 2 change(s) tested, no difference found (not proven).


Graphify review — findings

Persists the trigram search index to a per-user cache directory (~/.cache/graphify, LOCALAPPDATA on Windows, overridable via GRAPHIFY_TRIGRAM_CACHE_DIR) so cold CLI invocations skip the ~6.7s rebuild, keyed on the graph file's resolved path plus mtime/size and written atomically via a mkstemp-per-process temp file to survive concurrent writers; set GRAPHIFY_TRIGRAM_CACHE_DISABLE=1 to opt out, and any cache read/write failure silently falls back to a rebuild. The two graph-loading CLI commands now stash _graph_path on the graph so _get_trigram_index can resolve the cache key on paths that bypass _load_graph. Short-circuits _find_node_tiers to return the node directly when label is an exact node id, avoiding a full index build on lookups that already hold an id.

Worth a look

  • Unpickling trigram cache from user-writable cache dir enables arbitrary code execution — graphify/serve.py · Escalate · high
    • agreed by 2 of 2 members but NOT verified (no proof, no reproducing execution) — consensus is not a verdict; needs human review
  • Untrusted trigram cache is unpickled before validation — graphify/serve.py:492 · Escalate · high
    • 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 — 589 functions depend on the 184 functions this change touches.

Health — this change adds coupling hotspots:

  • new: dispatch_command() — 2 callers, 123 callees
  • new: _query_graph_text() — 20 callers, 9 callees
  • new: _score_query() — 15 callers, 5 callees
  • new: _query_terms() — 20 callers, 3 callees
  • new: run_benchmark() — 16 callers, 3 callees
  • new: _stale_graph_sources() — 7 callers, 6 callees
  • new: _load_graph() — 9 callers, 4 callees
  • new: _build_server() — 2 callers, 17 callees
  • …and 11 more — each is listed as a finding

Verification — 589 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: 535 function(s) in the blast radius were not formally verified this run

Formal verification

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: not verifiable: all 23 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)

No difference found (not proven): No behavior difference found in \_find\_node\_tiers (not a proof).

The verifier ran both versions of \_find\_node\_tiers 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.

No difference found (not proven): No behavior difference found in \_get\_trigram\_index (not a proof).

The verifier ran both versions of \_get\_trigram\_index 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 \_load\_graph.

The verifier did not have enough to check \_load\_graph, 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: not verifiable: all 23 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)

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

Comment thread graphify/serve.py
except Exception:
pass


def _get_trigram_index(G: nx.Graph) -> dict:

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 — _get_trigram_index()

6 callers depend on it (afferent coupling).

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

Two more from the automated review, both real.

The key was computed twice, once when loading the cache and again when
storing it, with a fresh stat() each time. If graph.json was rebuilt
while this process held the old content in memory, the index was written
under the NEW file's key, so the next reader matched it and loaded an
index built from content that file no longer had, with nothing to reveal
it. The key is now computed once and memoized on G.graph, which pins it
to the read the index was actually built from; a reader then sees the
mismatch and rebuilds. Verified by rewriting graph.json between the two
calls and confirming the key no longer moves.

The path is also resolved in one place instead of two. _trigram_cache_key
stored the raw path while _trigram_cache_path resolved it for the
filename digest, so a symlinked path and a real one could share a cache
file while disagreeing on the key, leaving each process to invalidate the
other's entry indefinitely. Both now derive from one resolved string.

Co-Authored-By: Claude Opus 5 <[email protected]>
@mallyskies
mallyskies force-pushed the perf/trigram-cache-and-exact-id branch from fc1a452 to 806be6c Compare September 2, 2026 17:33

@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.

Formal verification. 2 change(s) tested, no difference found (not proven).


Graphify review — findings

Persists the trigram search index to an on-disk cache (~/.cache/graphify, LOCALAPPDATA on Windows, overridable via GRAPHIFY_TRIGRAM_CACHE_DIR) so cold CLI calls stop rebuilding it from scratch each process — _get_trigram_index now reads the cache before building and writes it after, keyed on the resolved graph path plus mtime/size via _atomic_write_pickle (unique temp name for safe concurrent writers); set GRAPHIFY_TRIGRAM_CACHE_DISABLE=1 to skip. The cache key is stashed as an object attribute rather than in G.graph to keep the absolute path and username out of committed graph.json, and the CLI's path and impact command paths now set _graph_path themselves since they bypass _load_graph. Short-circuits _find_node_tiers when label is an exact node id, avoiding an index build for callers (like the ambiguity second step) that already hold one.

Worth a look

  • Untrusted trigram cache is deserialized with pickle — graphify/serve.py:494 · Escalate · high
    • 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 — 589 functions depend on the 184 functions this change touches.

Health — this change adds coupling hotspots:

  • new: dispatch_command() — 2 callers, 123 callees
  • new: _query_graph_text() — 20 callers, 9 callees
  • new: _score_query() — 15 callers, 5 callees
  • new: _query_terms() — 20 callers, 3 callees
  • new: run_benchmark() — 16 callers, 3 callees
  • new: _stale_graph_sources() — 7 callers, 6 callees
  • new: _load_graph() — 9 callers, 4 callees
  • new: _build_server() — 2 callers, 17 callees
  • …and 11 more — each is listed as a finding

Verification — 589 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: 535 function(s) in the blast radius were not formally verified this run

Formal verification

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: not verifiable: all 23 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)

No difference found (not proven): No behavior difference found in \_find\_node\_tiers (not a proof).

The verifier ran both versions of \_find\_node\_tiers 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.

No difference found (not proven): No behavior difference found in \_get\_trigram\_index (not a proof).

The verifier ran both versions of \_get\_trigram\_index 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 \_load\_graph.

The verifier did not have enough to check \_load\_graph, 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: not verifiable: all 23 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)

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

Comment thread graphify/serve.py
pass


def _get_trigram_index(G: nx.Graph) -> dict:

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 — _get_trigram_index()

6 callers depend on it (afferent coupling).

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

@mallyskies

Copy link
Copy Markdown
Contributor Author

Thanks — the three write-path findings from the earlier rounds are fixed in the two follow-up commits on this branch:

  • 1bb7a1c gives each writer its own temp file via mkstemp in the destination directory, and moves the cache-path computation inside the guard so _store_trigram_cache genuinely never raises. The shared <dest>.pkl.tmp was real: I reproduced it with six concurrent writers and five of them failed, because the first rename moves the inode out from under the others.
  • 806be6c pins the cache key to the read the index was built from. It was being computed twice with a separate stat() each time, so an index built from old content could be stored under a rebuilt file's key and read back as current.

That leaves the pickle finding, and I'd like to make the case for leaving it as it is rather than switching formats.

The trust boundary. The cache is written by graphify into a per-user cache directory, XDG_CACHE_HOME/~/.cache/graphify or LOCALAPPDATA on Windows, mode 0700. To plant a malicious cache file you need write access as that user. At that point you can also rewrite graph.json itself, the graphify package in site-packages, or the user's shell profile. The cache doesn't change any security boundaries.

I'll concede that GRAPHIFY_TRIGRAM_CACHE_DIR lets someone relocate the cache, and pointing it at a shared or world-writable path would change the picture. If you'd like, I can add a note to that variable's docstring, or refuse a directory that is group- or world-writable.

On switching formats. I'm open to considering it, but it isn't free: the index is dict[str, array.array], and json can't represent that without converting every array to a list and back on each load. That conversion is a real fraction of the rebuild this cache exists to avoid, so I'd want to measure it before trading it in. msgpack would preserve the shape better but adds a dependency for a cache that is regenerable by definition.

Worth noting the gate itself reports PASS — no health regressions — and the finding is marked "agreed by 2 of 2 members but NOT verified (no proof, no reproducing execution)". I'm just commenting to clarify the changes and answer any questions you might have.

The trigram cache keyed its filename on the graph path alone and
overwrote in place, so after a rebuild every process rewrote the same
path. On POSIX, renaming over a file another process holds open is
allowed. On Windows it fails with PermissionError WinError 5, and since
both call sites swallow exceptions the cache write silently never
succeeds.

Measured on Windows 11 with a reader holding the file open for three
seconds: all four concurrent writers failed. No corruption and no leaked
temp files, since the existing cleanup path runs, but the cache stops
working and nothing says so.

The filename now carries the generation digest the way the graph cache
already did, so two generations resolve to two names and there is no
shared path to contend over. _prune_trigram_cache drops superseded
generations, including the pre-generation single-digest name, so
existing caches migrate on the first write rather than leaking an entry.

Verified on Windows 11: four concurrent lookups correct with no stderr,
one trigram file left, old generation pruned, timings unchanged.

Co-Authored-By: Claude Opus 5 <[email protected]>

@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.

Formal verification. 2 change(s) tested, no difference found (not proven).


Graphify review — findings

Adds an on-disk trigram-index cache alongside the in-memory one so cold CLI calls stop rebuilding the index every process (~6.7s saved on the Masque graph), reading and writing it via _load_trigram_cache/_store_trigram_cache keyed on the resolved graph.json path plus its mtime/size. Writes go through _atomic_write_pickle using a per-process mkstemp temp name and _prune_trigram_cache to survive concurrent writers and Windows open-file replacement failures, and the cache lives outside the corpus (under LOCALAPPDATA/XDG_CACHE_HOME, overridable via GRAPHIFY_TRIGRAM_CACHE_DIR) so an 80 MB derived file never lands in VCS; GRAPHIFY_TRIGRAM_CACHE_DISABLE=1 turns it off. Stashes _graph_path on the graph object (not G.graph, to avoid leaking absolute paths and usernames into committed graph.json), including in the two CLI paths that bypass _load_graph, and memoizes the cache key so a graph.json rebuilt mid-process can't publish an index under the wrong generation.

Worth a look

  • Trigram cache unpickles attacker-controlled data — graphify/serve.py:522 · 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 — 591 functions depend on the 186 functions this change touches.

Health — this change adds coupling hotspots:

  • new: dispatch_command() — 2 callers, 123 callees
  • new: _query_graph_text() — 20 callers, 9 callees
  • new: _score_query() — 15 callers, 5 callees
  • new: _query_terms() — 20 callers, 3 callees
  • new: run_benchmark() — 16 callers, 3 callees
  • new: _stale_graph_sources() — 7 callers, 6 callees
  • new: _load_graph() — 9 callers, 4 callees
  • new: _build_server() — 2 callers, 17 callees
  • …and 11 more — each is listed as a finding

Verification — 591 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: 537 function(s) in the blast radius were not formally verified this run

Formal verification

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: not verifiable: all 23 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)

No difference found (not proven): No behavior difference found in \_find\_node\_tiers (not a proof).

The verifier ran both versions of \_find\_node\_tiers 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.

No difference found (not proven): No behavior difference found in \_get\_trigram\_index (not a proof).

The verifier ran both versions of \_get\_trigram\_index 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 \_load\_graph.

The verifier did not have enough to check \_load\_graph, 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: not verifiable: all 23 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)

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

Comment thread graphify/serve.py
pass


def _get_trigram_index(G: nx.Graph) -> dict:

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 — _get_trigram_index()

6 callers depend on it (afferent coupling).

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

@FelipeEspinola

Copy link
Copy Markdown

Thanks for this — the on-disk trigram cache is a nice, contained change, and I wanted to report a Windows run of it, since the PR fixes a Windows-specific contention issue.

Setup. Windows 11 Pro 25H2, i9-11900K, SATA SSD, Python 3.12.10, PYTHONHASHSEED=0, median of 5 runs. Two AST-only graphs built from graphify's own source: 5,136 nodes / 4.2 MB, and the full repo including tests, 24,924 nodes / 53,197 edges / 24.9 MB. I compared cache on against GRAPHIFY_TRIGRAM_CACHE_DISABLE=1 with the same build, so nothing else differs.

1. As submitted, graphify query never uses the cache. The PR stamps G.graph["_graph_path"] in _load_graph and in the path and explain CLI branches, but the query branch builds its own graph and is never stamped. As a result, _trigram_cache_key returns None and nothing is read or written. On the PR head (0.9.53 base), 24.9k-node graph:

command cache off cache warm speedup cache file
query 2091 ms 2077 ms 1.01× none written
explain 1879 ms 992 ms 1.89× 12.2 MB
path 2014 ms 1142 ms 1.76× 12.2 MB

Adding the same one-line stamp to the query branch, right after G = json_graph.node_link_graph(...), fixes it:

G.graph["_graph_path"] = str(gp)

2. Rebased on current v8 (0.9.104), with that line added:

graph command cache off cache warm speedup
24.9k nodes query 2341 ms 1420 ms 1.65×
24.9k nodes explain 1992 ms 1093 ms 1.82×
24.9k nodes path 2174 ms 1299 ms 1.67×
5.1k nodes query 1189 ms 1034 ms 1.15×

Output was byte-identical with the cache on and off in every case. The cache is about 0.5 KB per node: 12.2 MB at 24.9k nodes and 2.0 MB at 5.1k.

The rebase has three mechanical conflicts:

  • in cli.py, the path and explain loaders were rewritten on v8;
  • in serve.py, _load_graph now delegates to _read_graph, so the stamp belongs in _read_graph.

My resolved diff against v8 (6c8002e) is ~200 lines and touches the same two files. Happy to share it or open it as a follow-up if that helps.

3. Full test suite on Windows. 9,428 passed, 580 skipped, 100 failed, identical with and without the PR. The 100 failures also occur on plain v8 on this machine (hooks/shell, safe_fetch, skillgen path-injection, ...), so there are no regressions from this change. I can file the Windows failures separately.

4. Windows robustness (rebased build). All of the following passed:

  • 8 concurrent cold query processes on an empty cache: all exit 0, identical output, exactly one .pkl, no stray .pkl.tmp.
  • An old-generation cache file held open by another process (plain open(), no share-delete) while graph.json was rebuilt, with 4 concurrent writers: all exit 0, identical output, and the new generation was written. The old generation was pruned on the next write after it was released. The per-generation filename does what the PR description says.
  • A corrupted cache file (garbage bytes): silent rebuild, identical output.
  • After a node label was changed in graph.json, the new label was found exactly as on v8, with no stale index served.
  • GRAPHIFY_TRIGRAM_CACHE_DISABLE=1 writes nothing, and explain reuses the cache.

5. Smaller notes.

  • Three docstrings still describe the old location, saying the cache is "beside graph.json" or "inside the workspace": the _TRIGRAM_CACHE_VERSION comment, _load_trigram_cache and _store_trigram_cache. It now lives under LOCALAPPDATA or XDG_CACHE_HOME. The trust argument in the _load_trigram_cache docstring relies on the old location, so it might be worth restating for the per-user cache directory.

  • The discussion mentions mode 0700 for the cache directory, but _atomic_write_pickle calls dest.parent.mkdir(parents=True, exist_ok=True) without a mode. On Windows, LOCALAPPDATA ACLs are per-user anyway. On POSIX the default umask usually gives 0755: not writable by others, so the pickle concern is unchanged, but the claim doesn't match the code.

  • _graph_path itself is still stored in G.graph. As far as I can see, no path on v8 that writes graph.json loads through serve today, so nothing leaks. But for the same Node IDs for file / directory / project nodes embed the absolute scan path (leaks local username, makes committed graph.json non-portable / non-idempotent) #1789 reason that moved the key memo to an object attribute, the path could live there too.

  • There are no tests in the PR. Candidate regression tests:

    • query, explain and path each write and then reuse the cache;
    • an mtime or size change invalidates it;
    • a corrupted file falls back to a rebuild;
    • DISABLE writes nothing.

    The first one would have caught point 1.

Remaining cold time after the cache is mostly imports plus JSON → networkx (roughly 235 ms and 160 ms at 5k nodes), which is what the SQLite proposal in #1297 targets. The two look complementary.

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

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants