Skip to content

fix(cache): stop a degraded semantic entry from pinning the corpus (#5083) - #5101

Closed
nothariharan wants to merge 1 commit into
Graphify-Labs:v8from
nothariharan:fix/5083-semantic-cache-partial
Closed

nothariharan wants to merge 1 commit into
Graphify-Labs:v8from
nothariharan:fix/5083-semantic-cache-partial

Conversation

@nothariharan

Copy link
Copy Markdown
Contributor

Closes #5083.

What and why

A degraded semantic extraction — a doc chunk that returns only its file-level node — is saved to the unversioned, content-hash semantic cache as an authoritative entry. Every later run then logs semantic cache: 1 hit / 0 miss, replays the degraded chunk, and the #3203 shrink guard refuses the graph write. No LLM call is made again, so the corpus stays un-updatable until someone deletes the cache entry by hand. This makes the cache self-heal instead, and stops telling the operator to fix it with --allow-partial, which would commit the degraded replay over the larger graph.

Root cause

save_semantic_cache already rejects three bad producers — corrupt JSON, a partial truncation flag, and zero-node results — but a plausible-looking 1-node entry passes all three. The check that notices the under-production runs one level up: build_merge / merge_raw_extraction compare a re-extracted source against its prior contribution in graph.json and arm the shrink guard. That verdict never reached the cache write, so the cache kept serving the chunk the guard had just rejected.

Change

  • New graphify.cache.mark_semantic_cache_partial() stamps the entry the read path would actually serve with "partial": true — the prompt-fingerprinted namespace when present, else the pre-fingerprint flat entry load_cached falls back to. The write is atomic and the payload is otherwise untouched.
  • _handle_unverified_semantic_shrink(), shared by the clustered and --no-cluster write paths, calls it after the guard measures the shrink. load_cached already treats partial as a miss, so the next run re-dispatches the file and a complete extraction overwrites the same content-hash key with a clean entry.
  • This also heals entries already poisoned by older versions: a cached replay that shrinks is marked on that run.
  • The guard's stderr now distinguishes a fresh under-production from a cached replay, names the marked entry, and no longer recommends --allow-partial for a cached replay.
  • Tests: cache-level marking (fingerprinted and legacy-flat), plus two end-to-end CLI repros. Both repros were confirmed failing on the unmodified code — the old path replayed the poisoned cache and refused again without calling the model — and pass with the fix.

Verification

Risk-tier evidence: high. All gates below were run on fc7f700f9e53aecfce44907563ac0f598aa6bef6 with PYTHONPATH pointed at this worktree (the repo's subprocess CLI tests otherwise import the local editable install).

Gate Result
cache, shrink guard, incremental and extract CLI suites (27 modules) 755 passed, 9 skipped, 1 xfailed in 203.50s
ruff check . All checks passed
python -m tools.skillgen --check 134 artifacts match committed output
FV (below) 420 checks, 0 failures

The full repository suite is left to CI. Locally I ran every suite that reaches the touched code: test_cache*, test_unverified_semantic_shrink, test_build_merge*, test_hollow_chunks_arm_shrink_guard, test_incomplete_build_guard, test_partial*, test_zero_node_no_cache, test_semantic_cache*, test_skill_semantic_all_cached, test_*shrink*, test_incremental*, test_update_incremental, test_extract*, test_cli_export.

Security review: the change only narrows what the cache serves (it cannot mark a healthy entry, since marking happens only after the existing shrink guard fires); marking is best-effort and never aborts extraction; no new input reaches a shell, a path is re-anchored against the scan root, and entries are replaced atomically.

FV

Technique: exhaustive small-domain over the entry state space, plus differential/metamorphic equivalence and adversarial shapes. Chosen because the state is finite and enumerable, and the property that matters is an equivalence (a marked entry must behave like an absent entry for the guarded read while retaining its payload), not a single example.

Invariants asserted:

  • For every semantic cache entry, marking it partial makes the non-partial read return None, while every field of the stored payload other than the partial flag stays identical.
  • The partial read still returns the retained payload, so marking is observationally equivalent to deleting the entry for the guarded read path without destroying evidence.
  • Marking an entry that is already partial, corrupt, non-object, or absent is a no-op that never raises and never rewrites the file.
  • One complete re-extraction over the same content hash writes a clean, servable, non-partial entry with the new node count.
  • The shrink handler marks the serving entry for every (prior, fresh, cached-replay, --allow-partial) combination it accepts, and only a cached replay receives the "do not pass --allow-partial" advice.

Case space: 2 layouts × 2 path forms × 4 node counts × 2 mark runs, plus 12 handler combinations across 23 prior/fresh pairs, plus corrupt/non-object/already-partial/absent/temp-file cases. Deterministic, no RNG.

FV #5083: checks=420 failures=0
PASS: marking forces a miss, preserves the payload, is idempotent, and heals on re-extraction

Script: verification/fv/graphify_5083_semantic_cache_partial_fv.py (kept in the workspace, not the PR diff).

Visual evidence

Not applicable: this is a CLI/cache correctness change with no UI surface. The observable evidence is the stderr transcript covered by the end-to-end repros.

Risk and rollback

Tier: high — it changes what is persisted in the semantic cache and what the shrink guard allows next.

Rollback is one step: revert commit fc7f700f. There is no data migration and graph.json is untouched. The change only adds an internal partial: true field to entries the #3203 guard has already judged degraded; a later run re-extracts such an entry, and older graphify versions treat the field as unknown metadata, so removing the code restores the previous replay behaviour with no cleanup.

Residual, stated honestly: a brand-new document that under-produces has no prior contribution in graph.json, so there is no baseline to flag it. This change fixes the reported wedge — an existing source whose shrink the guard already detects.

Compatibility

No public API, CLI flag, graph.json schema or manifest change. partial is an internal semantic-cache field load_cached already understands — the same flag the truncation path has written since #1950 — so entries written by older and newer versions remain mutually readable. Entries are marked only when the existing #3203 guard has already detected a shrink, so no healthy extraction is invalidated. Python versions and platforms are unchanged; the write uses the same extended-length-path and atomic-replace helpers as save_cached. Only the stderr wording changes; exit-code behaviour is unchanged.

…raphify-Labs#5083)

An under-produced semantic extraction (e.g. a doc chunk that returns only
its file-level node) is saved to the unversioned content-hash cache
without a `partial` flag. The Graphify-Labs#3203 shrink guard then refuses the graph
write on every later run while the cache keeps serving the degraded chunk,
so no LLM call is ever made again and the corpus stays un-updatable until
the entry is deleted by hand.

`save_semantic_cache` cannot read graph.json (and should not), so the
shared shrink handler marks the entry the read path would serve `partial`
once the guard has measured the shrink. `load_cached` already treats
`partial` as a miss, so the next run re-dispatches the file and a complete
extraction overwrites the same content-hash key with a clean entry. This
covers both a fresh under-production and a run that replays an
already-poisoned entry written by an older version.

The guard's stderr now separates "fresh extraction is smaller" from "a
cached smaller chunk is being replayed", names the marked cache entry, and
stops recommending --allow-partial for the cached case: following that
advice would write the degraded replay over the larger graph and drop the
prior nodes.

Tests: cache-level marking (prompt-fingerprinted and legacy flat
fallback), plus two end-to-end CLI repros that fail on the old code. The
second demonstrates the reported loop: the next run hit the poisoned
cache and refused again without ever calling the model.
@github-actions

github-actions Bot commented Nov 9, 2026

Copy link
Copy Markdown

Thanks for the pull request, @nothariharan. 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 Nov 9, 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 3 advisory finding(s) below merit a look before merge.

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

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

Not verified on this run: \_handle\_unverified\_semantic\_shrink (vacuous: never exercised), dispatch\_command (vacuous: never exercised).


Graphify review — findings

Fixes the stuck state from #5083, where a degraded semantic chunk is replayed from the unversioned cache on every run, the #3203 shrink guard keeps refusing the graph write, and no LLM call is ever made to heal it. The new mark_semantic_cache_partial stamps the entry the read path would actually serve (the prompt-fingerprint namespace, else the flat legacy layout) as partial: True, so load_cached treats it as a miss and the next run re-extracts. Its write path is best-effort and skips missing, unreadable or already-partial entries, so the temp-file write and replace sequence is the part that could leave a cache entry truncated or fail the whole marking pass. _handle_unverified_semantic_shrink now calls the marker for every shrinking source, and splits them into cache-replayed and freshly extracted using the new cached_semantic_files argument. For replayed sources it prints that the entry came from the cache and warns against --allow-partial, which would commit the degraded replay and drop the prior nodes. The "re-run to re-extract the marked sources" wording is printed from the replay branch whether or not marking succeeded, so it can misdirect the user. The plain "pass --allow-partial" advice is kept only when fresh sources shrank and the flag is not set. dispatch_command records which semantic files were served from cache and passes that, along with the cache mode, prompt and out_root, to the guard on both the raw and clustered write paths. New tests in tests/test_cache.py and tests/test_unverified_semantic_shrink.py cover the marking and the degraded-replay messaging.

Worth a look

  • fd closed twice when replace fails, which can close an unrelated reused descriptor — graphify/cache.py:1925 · Escalate · medium
    • NOT verified (no proof, no reproducing execution) — needs human review
  • Short os.write can replace cache entry with truncated JSON — graphify/cache.py:1926 · Escalate · medium
    • NOT verified (no proof, no reproducing execution) — needs human review
  • Tempfile creation failure aborts best-effort semantic cache marking — graphify/cache.py:1920 · Escalate · medium
    • NOT verified (no proof, no reproducing execution) — needs human review
Analysis details — impact, health, verification

Impact & health

Graphify review

Impact — 3556 functions depend on the 418 functions this change touches.

Health — this change adds coupling hotspots:

  • worse: load_cached() — 72 callers, 10 callees
  • worse: save_semantic_cache() — 67 callers, 9 callees
  • worse: file_hash() — 67 callers, 7 callees
  • worse: cache_dir() — 26 callers, 3 callees
  • new: mark_semantic_cache_partial() — 6 callers, 6 callees
  • new: test_5083_cached_degraded_replay_is_marked_and_does_not_advise_allow_partial() — 0 callers, 6 callees

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

Test selection

Test selection

95 of 532 test file(s) selected (18%) via static blast radius.

  • tests/test_affected_cli.py — impact
  • tests/test_affected_seed_reference_forms.py — impact
  • tests/test_agents_platform.py — impact
  • tests/test_binary_media_words.py — impact
  • tests/test_cache.py — impact, changed-test
  • tests/test_cache_long_paths.py — impact
  • tests/test_cache_stale_import_target.py — impact
  • tests/test_cache_windows_case_4925.py — impact
  • tests/test_charmap_encoding.py — impact
  • tests/test_chunking.py — impact
  • tests/test_cli_export.py — impact
  • tests/test_cloud_cta.py — impact
  • tests/test_code_only_scope_4923.py — impact
  • tests/test_codebuddy.py — impact
  • tests/test_compact_graph_json.py — impact
  • tests/test_confidence_score_output.py — impact
  • tests/test_csharp_partial_classes.py — impact
  • tests/test_dedup_shrink_refuses_force_write.py — impact
  • tests/test_definition_file_portability.py — impact
  • tests/test_detect.py — impact
  • tests/test_devin.py — impact
  • tests/test_edge_also_seen.py — impact
  • tests/test_explain_cli.py — impact
  • tests/test_explain_same_file_tie.py — impact
  • tests/test_extract.py — impact
  • tests/test_extract_cache_location.py — impact
  • tests/test_extract_cli.py — impact
  • tests/test_extract_cost_ledger.py — impact
  • tests/test_global_add_tag_inference.py — impact
  • tests/test_god_nodes_cli.py — impact
  • tests/test_grammar_cache_key.py — impact
  • tests/test_hollow_chunks_arm_shrink_guard.py — impact
  • tests/test_hook_content_freshness.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_hook_strict_grep.py — impact
  • tests/test_ignore_file_encoding.py — impact
  • tests/test_incomplete_build_guard.py — impact
  • tests/test_incremental_mtime_collision.py — impact
  • tests/test_install.py — impact
  • tests/test_install_references.py — impact
  • tests/test_java_member_calls.py — impact
  • tests/test_js_member_collisions.py — impact
  • tests/test_language_override_lifecycle.py — impact
  • tests/test_language_overrides.py — impact
  • tests/test_linked_worktree_reconcile.py — impact
  • tests/test_llm_backends.py — impact
  • tests/test_lookup_exit_codes.py — impact
  • … and 45 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)

Formal verification

Could not verify: Could not verify \_handle\_unverified\_semantic\_shrink.

The verifier did not have enough to check \_handle\_unverified\_semantic\_shrink, 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 72 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)

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)

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

Comment thread graphify/cache.py
return saved


def mark_semantic_cache_partial(

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

fans out to 6 callees (efferent coupling); 6 callers depend on it (afferent coupling).

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

assert len(json.loads((out_dir / "graph.json").read_text(encoding="utf-8"))["nodes"]) == 24


def test_5083_cached_degraded_replay_is_marked_and_does_not_advise_allow_partial(

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

fans out to 6 callees (efferent coupling).

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

@safishamsi

Copy link
Copy Markdown
Member

Landed on v8 and shipped in 0.9.105 (now on PyPI). I cherry-picked your commit with -x so it keeps your authorship. Thanks for stopping a degraded semantic entry from pinning the corpus (#5083), @nothariharan.

@kpiq

kpiq commented Nov 10, 2026

Copy link
Copy Markdown

@nothariharan — following the #5101 lead onto the actual issue (#5083).

This is the fix we needed all night. We ran a full corpus rebuild with our fallback list across every model and hit precisely what you diagnosed in #5101: the cache would hold a plausible-looking 1-node degraded chunk with no partial flag, load_cached replayed it, the shrink guard refused the write, and (until we understood it) we reached for the --allow-partial lever. Your root-cause read made the trade-off legible for us.

Two things worth feeding back, from trying 0.9.105 against a large corpus:

  • The shield-against-regression works as described: after the shrink guard fires, the entry is marked partial, the cache forces a miss, and the next run re-extracts with the same content-hash key — clean entry overwrites. That's exactly the correct shape. Not being asked to fix anything we got.
  • We noted the residual honestly disclosed in the review: a brand-new document with no prior baseline in graph.json cannot be detected by this mechanism — there's nothing to compare against. We agree; we did not find another way around it either.

The 10-attempt loop we ran — every model unreachable to overwrite without --allow-partial on the first pass, then reconciled after the partial stamp kicked in — is exactly what this fix was for, and it validates the bet that the cache is authoritative only when it's clean.

Good work. Glad to see it landed in 0.9.105.

— kpiq

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

3 participants