Skip to content

perf(update): re-extract only the files whose content changed (#4800) - #4801

Closed
Deepjyoti-Sarmah wants to merge 5 commits into
Graphify-Labs:v8from
Deepjyoti-Sarmah:perf/4800-incremental-update
Closed

Deepjyoti-Sarmah wants to merge 5 commits into
Graphify-Labs:v8from
Deepjyoti-Sarmah:perf/4800-incremental-update

Conversation

@Deepjyoti-Sarmah

Copy link
Copy Markdown
Contributor

What does this PR do?

Fixes #4800. graphify update pays for the whole corpus however little changed.
0.9.96 shipped the zero-change half (#4748): an untouched tree returns at the gate in
1.96 s. Change one file and the run costs 68.15 s again, because the gate can only
answer "all unchanged" or "not all unchanged", and nothing derives which files
differ.

Seven stages run, and only the first two read source text:

scan ──> extract ──> build ──> cluster ──> analyze ──> report ──> export
disk     parse       graph     communities  findings     md/html

Everything downstream works on the graph, so a two-file edit paid for all seven
stages. This PR gives update a change set:

 _rebuild_code(watch_path, incremental=True)
   detect(watch_path)
+  changed_paths = manifest diff of the scan
+                  rows whose ast_hash moved, plus rows whose file is gone
   if changed_paths is not None:
     extract only those
     preserve every other file's nodes
     hand the unchanged corpus's AST nodes to extract() as resolution context
-  else: extract the whole corpus        <- what `update` always did
   extract -> build -> cluster -> analyze -> report -> export

On the issue's corpus (1,059 scanned files, one process per run): 68.15 s and
1,071 MB becomes 48.72 s and 537 MB. The stages after extraction still work over
every node, which is why this is 19 seconds and not 66. That is called out under
Limitations rather than buried.

The manifest already stores a content hash per file, and _rebuild_code has taken
changed_paths since the hook work. The only caller that ever passed one was git:
post-commit diffs HEAD and forwards the touched paths. update passed nothing,
which the function documents as "the full code corpus". So the missing piece was a
change set that does not depend on git. It is written with paths relative to the
scan root, so a copied checkout carries a usable baseline.

The rule the change set is built on

A false "changed" costs time. A false "unchanged" ships a graph that describes code
the reader no longer has. Every uncertain answer therefore resolves to "changed":

question answer
has this file changed? content hash, never mtime alone. A checkout or rsync --times moves mtime with identical bytes; a same-second rewrite leaves it put
no row for it? changed. Nothing describes it, so it was not in the last build
manifest missing, unreadable, or naming another tree? full path. Unknown is not "nothing changed"
file gone from disk? changed, and it must reach the deleted branch, or its nodes survive and the shrink guard refuses the write

Five commits

34333812  refactor(detect): expose the changed set for a root
5c02c991  feat(watch): derive changed_paths from the manifest in _rebuild_code (#4740)
78be63ab  feat(cli): use the incremental path for update (#4740)
2de3b0d0  fix(watch): keep cross-file resolution edges for the changed set (#4740)
0ea45d78  test(watch): make the default-path assertion robust to the no-change gate (#4740)

The split is deliberate. The refactor is behaviour-neutral and provable as such.
The capability is default-off, so the watcher and the post-checkout hook are
untouched. The CLI flag is its own commit, so reverting it returns update to
full-corpus while the capability stays.

The commit subjects say #4740, the umbrella issue this work started under. This PR
fixes #4800, its scoped successor. #4748 already landed the gate this branch sits on.

Two of the commits are correctness fixes, and the new caller is what exposed them.
Deriving a change set means only the changed files are parsed, so a call from a
changed file into an unchanged one can lose its edge (#2406/#3763). v8 answers that
by passing the unchanged corpus's AST nodes as resolution context. Commit 2de3b0d0
fixes the case where that context came back empty: the membership test anchored
stored paths via identity(), which resolves against the tree recorded in
graphify-out/.graphify_root, while the set it was compared against was built with
absolute_identity(..., project_root). On a copied checkout the marker still names
the original tree, so every stored node read as corpus-absent. Two lines, same
anchoring on both sides.

The stacked PR

fix/4800-incremental-lock-drop   records a contended incremental request instead of dropping it

_rebuild_code can lose the per-repo lock. The other two request kinds record what
they could not do, in .pending_full and .pending_changes. A manifest-derived
request names no paths, so before that PR it records nothing and returns the same
False that a queued request returns. That PR adds .pending_incremental.

It is latent today: every non-blocking caller passes explicit paths, and update
blocks on the lock. So this PR is complete on its own for the CLI path, and the stack
closes the hole for a future non-blocking incremental caller. I would rather say that
than let a reviewer find it.

Type of change

  • Bug fix (the reported symptom is cost)
  • New feature
  • Documentation
  • Tests or CI
  • Refactor (the first commit only)
  • Security fix

Verification & Invariants

A partial rebuild is sound only if its key covers every input that reaches the graph,
and the cost of being wrong is asymmetric: over-reporting costs time, under-reporting
ships a stale graph.

  • Read the CONTRIBUTING.md guide.
  • Reproduced the issue and identified the invariant.
  • Made the smallest fix necessary.
  • Added a regression test (if bug fix) or isolated boundary test.
  • Kept the PR description synchronized with the final implementation.
  • Documented any limitations / unsupported cases explicitly.

Merge Danger

Door: two-way. No schema, cache-key or file-format change. Reverting the CLI
commit alone returns update to full-corpus rebuilds.

Blast Radius: moderate, because this decides what gets re-extracted:

  • The change set is content-addressed, so a false "unchanged" needs identical bytes
    plus a matching manifest row. Everything else falls back to the full path.
  • A new file has no row and therefore always re-extracts.
  • A deleted file is carried into the change set so its nodes are evicted and the
    shrink guard can attribute the loss.
  • incremental defaults to off, so the watcher, the post-checkout hook and every
    existing caller keep the full path.
  • The first commit is a pure refactor. detect_incremental calls the factored
    helpers with the same arguments; I checked the output matches the inline version on
    a corpus with an edit, a delete and an add, for both kind="ast" and
    kind="semantic".
  • --force still means a full rebuild. An explicit changed_paths still wins over
    the derived set.
  • The gate still runs first, so a tree it can skip costs what it costs today (1.96 s
    here). The change set is only computed when the gate declines.

Limitations

  • Extraction is only part of the run. Build, cluster, analyze, report and export
    still work over every node, so 68 s becomes 49 s rather than seconds. On this
    corpus the JS/TS resolution pass re-parses the TypeScript files too, because those
    suffixes bypass the AST cache on purpose. That remaining half is the rest of [Bug]: one edited file still costs a full rebuild, so a warm graphify update goes from 2 s back to 68 s #4800.
  • An incremental rebuild is not byte-identical to a full one on a large corpus.
    On 1,059 files it keeps one sourceless any node and seven edges that a full
    rebuild drops. This is not introduced here: v8 with an explicit changed_paths
    produces the same node and edges. It is pre-existing changed_paths behaviour that
    this PR makes reachable from the CLI.
  • A source that never extracts re-queues on every run by design (Incremental manifest never retries files whose extractor failed on a missing extra #2543), so a
    corpus containing one can never reach the pure-skip case. This repository has one
    (worked/rsl-siege-manager/graph.json), which is why graphify update . here still
    re-extracts a handful of files.
  • On a copied checkout, deletions and renames are not evicted.
    graphify-out/.graphify_root still names the original tree, so stored source paths
    resolve there and the fail-closed sweep reads the removed file as alive-out-of-scan
    and preserves it. The full path behaves identically, so this predates the PR; it is
    why this branch's deletion test uses a same-directory tree.
  • No incremental rebuild for the semantic path. This covers graphify update
    (AST) only. graphify extract already had its own incremental mode.
  • The change set is not persisted, so it is recomputed per run. It costs one manifest
    read against a scan that already happened.

How was this tested?

tests/test_update_incremental.py is new and has 17 tests. Fifteen drive the real
_rebuild_code with a spy on extract(): an unchanged copied checkout, two edited
files reduced to the changed subset, an mtime bump with identical bytes, an added
file, a deleted file and the eviction that follows, the default path, --force, an
explicit changed_paths, a missing manifest, an unreadable manifest, a manifest
anchored elsewhere, incremental output equal to a full rebuild on the same tree, the
lock path, the non-blocking queue behaviour, and a cross-file call edge surviving an
incremental update both in place and on a copied checkout. Two run the real CLI as a
subprocess: update end to end, and update --force.

The assertion in test_default_is_the_full_path is the one that had to change to
coexist with the 0.9.96 gate, and a test that passes in both worlds can be vacuous,
so I checked it. The corpus now carries one change before the second run, which is
sound either way: a correct no-change gate cannot skip a tree that changed. Mutating
the derivation guard in a scratch copy to fire even when incremental is unset makes
it fail, with and without the gate:

E  AssertionError: assert [['a.py']] == [['a.py', 'b.py', 'c.py', 'uses.py']]

Gates, all with PYTHONPATH set to the repo so sys.executable -m graphify children
load this tree rather than the installed package:

.venv/bin/python -m pytest -q          -> 8889 passed, 17 skipped, 1 xfailed in 412.62s
tests/test_update_incremental.py       -> 17 passed
tests/test_extract.py::test_extract_progress_final_line_uses_consistent_denominator
                                       -> 1 passed
.venv/bin/python -m ruff check graphify/ tests/test_update_incremental.py
                                       -> All checks passed

Wall time and peak RSS for graphify update, one process per run, on 1,059 scanned
files (583 code), the same tree and the same two-file edit in both rows:

wall peak RSS
current v8 (dac06345) 68.15 s 1,071 MB
this branch 48.72 s 537 MB

The unchanged case is unchanged by this PR, because the gate answers it first:
1.96 s and 46 MB.

Not tested: Windows. The change set uses paths from detect() and the manifest's
existing anchoring rules, and nothing here adds new path construction.

Graphify-specific checklist

  • I updated generated skill artifacts (uv run python -m tools.skillgen --bless) when changing their source fragments. (N/A: no skill fragments touched.)
  • I confirmed that AST/structural extraction remains deterministic (no ambient state dependencies like ENV variables). (Extraction is untouched. The change set is a content-hash comparison against the manifest, and mtime is only used to decide whether to hash.)
  • I reviewed changes for security implications (no unsafe interpolation into shell/Python).
  • I confirmed no API keys or local-only graph data are included.
  • (If applicable) I disclosed AI authorship in my commit messages. (No trailer in the commit messages.)

@github-actions

Copy link
Copy Markdown

Thanks for the pull request, @Deepjyoti-Sarmah. 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 contributor Pull request from a returning community contributor needs:title PR title should follow the conventional-commit format labels Oct 26, 2026
@github-actions

Copy link
Copy Markdown

Thanks @Deepjyoti-Sarmah! One small thing: our changelog and release notes are built from PR titles, so we use the conventional-commits format, for example:

fix(python): resolve a bare stdlib import correctly

Prefixes we use: feat, fix, docs, chore, refactor, test, perf, build, ci. Editing the PR title clears this automatically. This is just a nudge and does not block review.

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

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

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

Not verified on this run: dispatch\_command (vacuous: never exercised), detect\_incremental (unsupported), \_rebuild\_code (unsupported).


Graphify review — findings

Makes graphify update re-extract only files whose content differs from the manifest, so a warm tree costs what changed instead of the whole corpus. _rebuild_code takes a new incremental flag that derives the change set from the manifest inside the lock. An explicit changed_paths list still wins, --force still forces a full rebuild, and a missing, unreadable or empty manifest falls back to the full path. A queued full rebuild overrides it, and an incremental request no longer writes a .pending_full marker. That makes the lock-held path the risky one, since the request has nothing queued to replay. Extracts classify_manifest_deletions from detect_incremental so the watcher shares the logic that separates genuinely deleted manifest rows (file gone from disk) from rows excluded by a changed ignore rule. Callers must pass every row they expect to see, including resolution_inputs, or those rows read as excluded on every run.

Worth a look

  • Incremental request dropped when per-repo lock is held — graphify/watch.py:1979 · Escalate · high
    • NOT verified (no proof, no reproducing execution) — needs human review
  • absolute_identity evaluated before the empty source_file guard — graphify/watch.py:2403 · Escalate · medium
    • NOT verified (no proof, no reproducing execution) — needs human review
Analysis details — impact, health, verification

Impact & health

Graphify review

Impact — 4013 functions depend on the 382 functions this change touches.

Health — this change adds coupling hotspots:

  • worse: _rebuild_code() — 222 callers, 68 callees
  • worse: load_manifest() — 17 callers, 5 callees
  • worse: classify_manifest_files() — 4 callers, 5 callees

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

Test selection

Test selection

120 of 466 test file(s) selected (26%) via static blast radius.

  • tests/test_affected_cli.py — impact
  • tests/test_agents_platform.py — impact
  • tests/test_astro_extraction.py — impact
  • tests/test_atomic_writes.py — impact
  • tests/test_backend_opt_in.py — impact
  • tests/test_binary_media_words.py — impact
  • tests/test_build.py — impact
  • tests/test_cache_stale_import_target.py — impact
  • tests/test_cargo_introspect.py — impact
  • tests/test_charmap_encoding.py — impact
  • tests/test_chunking.py — impact
  • tests/test_cjs_module_extension.py — impact
  • tests/test_claude_cli_backend.py — impact
  • tests/test_cli_export.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_detect.py — impact
  • tests/test_devin.py — impact
  • tests/test_docx_to_markdown.py — impact
  • tests/test_dotnet.py — impact
  • tests/test_ejs_extractor.py — impact
  • tests/test_elixir_import_resolution.py — impact
  • tests/test_elixir_qualified_calls.py — impact
  • tests/test_elixir_unqualified_call_scope.py — impact
  • tests/test_evidence_binding.py — impact
  • tests/test_explain_cli.py — impact
  • tests/test_explain_same_file_tie.py — impact
  • tests/test_export_direction.py — impact
  • tests/test_ext_tagged_id_clash.py — impact
  • tests/test_external_stub_endpoints.py — impact
  • tests/test_extract.py — impact
  • tests/test_extract_cli.py — impact
  • tests/test_extract_cost_ledger.py — impact
  • tests/test_file_slice.py — impact
  • tests/test_file_truncation_warning.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_nudge_wording.py — impact
  • tests/test_hook_out_of_project_paths.py — impact
  • tests/test_hook_strict.py — impact
  • tests/test_ignore_file_encoding.py — impact
  • tests/test_image_vision.py — impact
  • tests/test_import_extension_resolution.py — impact
  • tests/test_incomplete_build_guard.py — impact
  • tests/test_incremental_mtime_collision.py — impact
  • tests/test_incremental_unscanned_placeholders.py — impact
  • … and 70 more

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.

Docs that may be stale (advisory)

…and 10 more.

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: 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 detect\_incremental.

The verifier did not have enough to check detect\_incremental, 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: nondeterministic output (both versions disagreed with themselves on the witness) — not a behaviour change; a function whose output is not a function of its inputs (random / time / uuid / os.urandom, or state carried across calls) cannot be soundly distinguished by execution, so this tier abstains for the whole function

Could not verify: Could not verify \_rebuild\_code.

The verifier did not have enough to check \_rebuild\_code, 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: nondeterministic output (both versions disagreed with themselves on the witness) — not a behaviour change; a function whose output is not a function of its inputs (random / time / uuid / os.urandom, or state carried across calls) cannot be soundly distinguished by execution, so this tier abstains for the whole function

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

@Deepjyoti-Sarmah
Deepjyoti-Sarmah force-pushed the perf/4800-incremental-update branch from 0ea45d7 to 83f6fb8 Compare November 1, 2026 18:21
@safishamsi

Copy link
Copy Markdown
Member

Landed in 0.9.102 (published to PyPI), cherry-picked with your authorship preserved. Verified the incremental graph is identical to a full re-extract. Fixes #4800. Thanks @Deepjyoti-Sarmah.

@safishamsi safishamsi closed this Nov 3, 2026
safishamsi added a commit that referenced this pull request Nov 5, 2026
#4801 made _rebuild_code's no-change gate read the process-wide stat index, so
across the full suite a warm index left by an earlier test (thousands of roots
hashed in one process) could serve a stale hash and make a rebuild skip
re-extraction - failing watch/reconcile tests nondeterministically depending on
ordering. Add an autouse conftest fixture that resets the stat index to its cold
init state before each test (#3989: cross-root callers in one process must use a
fresh process; a real update/extract always does). Product behavior unchanged.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
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 needs:title PR title should follow the conventional-commit format

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: one edited file still costs a full rebuild, so a warm graphify update goes from 2 s back to 68 s

2 participants