Skip to content

parser: prefix-validated incremental parse for Claude JSONL appends - #744

Closed
avs-io wants to merge 2 commits into
getagentseal:mainfrom
avs-io:fix/703-incremental-claude-parse
Closed

avs-io wants to merge 2 commits into
getagentseal:mainfrom
avs-io:fix/703-incremental-claude-parse

Conversation

@avs-io

@avs-io avs-io commented Jul 18, 2026

Copy link
Copy Markdown
Collaborator

Draft, stacked on #743 (its base commit is that PR's branch — the diff shows both commits until #743 merges, at which point this rebases clean). Same deal as #743: stays a draft until you give the go-ahead.

Implements the revised item-5 design (latest comment on #703) — capability-gated v1, Claude only.

What changed

  • Claude CachedFile entries gain an optional checkpoint { parsedBytes, prefixSha256, version }. parsedBytes sits at the boundary before the current still-open turn (a turn only closes when the next non-empty user record arrives, and streaming-ID updates may still replace assistant messages inside it), so resume re-reads everything that can still change. The safety argument is written on the type.
  • Warm refresh of a changed Claude file: if size grew AND sha256 of bytes [0, parsedBytes) matches, parse only from the checkpoint and splice; anything else — shrunk, same-size change, hash mismatch, no checkpoint, read error — full re-parse of that file, exactly as today. If the suffix supersedes a streaming ID from a retained turn (rare cross-boundary shape), it also falls back to full parse rather than guessing.
  • No serialized parser state anywhere: dedup seeding reconstructs from cached turns as it already does; the overlap re-parse re-derives the open turn.
  • All other providers keep byte-identical behavior (snapshot/journal/SQLite/aggregate-cost sources per the design's provider audit). Cache schema v5→v6: one full parse to re-checkpoint, then incremental.
  • Runs entirely inside cache: strict cross-process gate for the warm session-cache refresh transaction #743's warm transaction gate, closing the shared-checkpoint concurrent-writer hole.

How tested

  • Parity suite (tests/parser-claude-incremental-parity.test.ts, 9 tests): incremental result must deep-equal a from-scratch parse across appended complete turns; append while a turn was open; streaming-ID last-wins updates; a later turn superseding a retained-turn ID (→ full parse); same-length prefix mutation (→ full parse); truncation; truncate-then-append-to-larger with matching size but changed bytes (proves the prefix hash is load-bearing — passes only because of the hash check); mtime-only touch; mcpInventory equality.
  • Full suite: 2171 passed with dist built.

Measured effect (synthetic, honest caveats)

52.4MB Claude JSONL + 100KB appended turn: warm incremental refresh 102ms vs 207ms full parse of the same bytes. This synthetic ratio is a floor, and it is sha256-bound (hashing the 52MB prefix is most of the 102ms): real Claude session files parse far slower per byte than they hash (object construction, turn grouping, dedup), and per-file today-corpora are typically well under this fixture's size, so the real-world win per tick is larger. Happy to attach real-corpus numbers if useful.

@iamtoruk

Copy link
Copy Markdown
Member

Full adversarial review completed (parity harness over 29 real files, 301 truncate-append boundary comparisons, adversarial synthetic attacks, perf and migration measurement). Verdict: the design is faithful to the #703 revised item-5 sketch and the fundamentals are strong (all 301 boundary comparisons deep-equal, checkpoint never lands mid-record, prefix hash load-bearing and mutation-verified, 2.4x CPU / 2.6-3.0x wall on real large files, clean v5-to-v6 migration with identical totals), but it cannot land as-is, for two reasons.

First, the branch predates two overlapping features now on main: the incremental-append parser (8326aee) and the rich session capture (title/prLinks/isSidechain/toolResultMeta/sessionMeta with new parseClaudeEntries and groupIntoTurns signatures). Force-merging would regress those captured fields; this needs a rework against current main rather than a resolution.

Second, the parity invariant breaks on the streamed-id straddle shape (one assistant id restated across a non-empty user record; 5 of 1672 real local files): a multi-poll refresh that checkpoints mid-stream loses a call and a turn or corrupts call timestamps at some alignments, because the supersede guard only covers ids in retained turns, not ids whose first occurrence drifted into the committed prefix. Important context: this shape diverges WORSE on main's own append path (over-count, reproduced), and that main-side bug is now fixed conservatively in #772 (full re-parse on any appended-vs-cached id overlap), which also sets the bar the checkpoint design should meet natively when reworked - your turn-boundary resume is better positioned than main's line-offset resume to handle it without a fallback.

Staying a draft per its own framing. For GO after rework: rebase onto current main preserving the captured fields, extend the supersede guard to ids from the dropped open turn (or adopt the #772 overlap fallback), and add a real-data straddle fixture to the parity suite. The 29-file parity harness methodology from this review is documented in the review record for reuse.

@ozymandiashh

Copy link
Copy Markdown
Collaborator

Read the draft end to end; the fence/read-only split and the checkpoint fallback rules (full parse on any suffix/retained-id collision, checkpoint as optimization never correctness) look right to me. Two data points while it's still in draft:

1. verifyStillOwner can be failed by the holder's own heartbeat, discarding a finished parse.

saveCache calls verifyStillOwner once at publication. That helper returns false whenever acquireTakeoverGuard() doesn't return 'created', and the guard file is legitimately held for a few ms at a time by the holder's own 10s heartbeat (same process, no self-recognition) and by any waiter probing a missing primary. A publication that lands inside one of those windows reads as fence-lost: RefreshFenceLostError, the whole in-memory parse is discarded, and parseAllSessions re-parses read-only. Correctness survives (that's the design), but it's a spurious full re-parse that would be near-impossible to diagnose from the outside, and the probability scales with slow filesystems where the guard lives longer. removeIfOwned already retries the guard up to 20 times for exactly this reason; verifyStillOwner is the one guard-taker with no retry. Giving it the same brief retry loop (or serializing heartbeat/verify through an in-process mutex, since they share the process) would close it.

2. Parallel-suite flake datapoint for the shipped lock, same subsystem.

On macOS 26.5.2 (M-series, APFS), tests/cache-refresh-lock.test.ts from the already-merged #743 fails several cases under a full parallel vitest run and passes cleanly in isolation, with the failing count varying run to run; reproduced on unmodified main repeatedly. Worth knowing before this PR adds cache-refresh-lock-process.test.ts with real child processes and 5s waitFor deadlines: the same parallel scheduling pressure will apply to those barriers. If flake shows up in CI here, it's plausibly the harness, not the lock.

@ozymandiashh ozymandiashh left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This draft should not be merged or mechanically rebased in its current form. Main already contains the stacked #743 lock work plus later hardening, incremental append, overlap protection, and rich session capture; this head conflicts in six core cache/parser files and would risk reintroducing older lock semantics.

Two correctness gaps also remain:

  • The incremental guard is built only from retained turns. A streamed ID whose first occurrence moved into the cached prefix while a later occurrence straddles the user boundary can escape the guard, losing or retimestamping a call across refreshes. Add a production-shaped straddle fixture.
  • verifyStillOwner can observe the guard held by its own heartbeat and treat it as ownership loss. Current main already solves this class by serializing owner-side operations.

Please either close this as superseded or redesign the still-missing streamed-ID fix directly from current main. Local head tests (23/23) and typecheck pass, but they do not cover the two scenarios above or current integration.

@iamtoruk

Copy link
Copy Markdown
Member

Closing this with a clear decision rather than letting the draft sit, and with thanks: the work here was serious and parts of it outlived the branch.

Where things landed since July:

What survives from this branch: the prefix-hash validation idea and the turn-boundary checkpoint design, which the review judged better positioned than line-offset resume to handle the straddle shape natively, without the #772 fallback. If that refinement ever becomes worth the rework (it would need rebuilding against the rich session capture parser signatures plus the landed incremental parser), this PR and its review record are the starting point, and the 29-file parity harness methodology documented there is reusable as-is.

Thanks again for the contribution and for keeping it honestly framed as a draft.

@iamtoruk iamtoruk closed this Aug 10, 2026
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.

3 participants