Repository navigation
CORE (signing sitting): store: tail-only append, append cost flat in chain length - #72
Conversation
…ded)
Every append re-read and re-parsed the whole chain twice: createStore()
built store.entries, then appendReceipt/appendReceiptGuarded reloaded it
under the lock to get the previous hash and next seq. Per-append cost grew
with chain length (E5: 93 ms median at 30k entries).
The candidate src/store module reads only the end of the file under the
lock and loads store.entries on first access. Any tail that is not a
well-formed, newline-terminated entry falls back to the old full-read path,
so the bytes written are identical in every case (tested byte for byte
against a reference implementation of the old path).
src/store is core and self-mod gated, so the change is staged, not landed:
- proposals/store-tail-append/index.js: exact bytes for src/store/index.js
- proposals/store-tail-append/store-tail-append.patch: the same as a diff
- proposals/store-tail-append/run-against-candidate.mjs: test-only module
hook to run the suite against the candidate without touching core
- test/store-tail-append.test.js: 29 tests; 9 need the landing and run as
todo until PENDING_LANDING is set to {}
- bench/store-append.js: per-append cost at 0 / 10k / 40k entries
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- B2: isHumanPrompt now decides "operator speaking" on the text that
survives the chapters view's noise strippers (claudeUserText, exported,
behaviour unchanged). A <system-reminder> or <local-command-*> user line
no longer closes the segment and files the next action as none.
- S1: KIND_ORDER matches the documented precedence (thinking-redacted
above text-inline-reasoning); a test pins every adjacent pair.
- S2: an unsigned empty or whitespace-only thinking block is now
thinking-empty (shallowest kind), never none, so the step agrees with
the parser's session.thinkingBlocks that a block existed.
- Store cost: appendReceiptGuarded(build, { withChain: false }). Ignored
by the current store; with the tail-only store (PR #72) the per-step
append stops reading the whole chain.
- Tests: fail-first system-reminder fixture, bare <think> tag, exact
partialLineBytes, each cursor-reset reason pinned (incl. path-changed),
no-session-id, tamper test self-contained with a guarded index.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Correct the "byte-identical in every case" claim (candidate docstring, test header): the paths diverge on seq when the parseable-line count is not tail.seq + 1 (an entry line before the last lost or added). Document why the fast path does not fall back there (detecting it is the full read). - Make the "corrupt line in the middle" fidelity scenario real (garbage between two valid entries), add blank-bytes-without-newline, and pin the divergence deliberately for replaced, deleted and duplicated lines. - Landing tripwire: npm test fails if the candidate is in place while PENDING_LANDING still marks tests todo, or the reverse. Under the candidate hook the pending tests run as ordinary tests and the tripwire asserts the redirect fired; the hook throws if either file is missing. - readChainTail docstring: 'empty' needs a trailing newline; lock note. - Bench and hook docs state the "after" command (absolute --import URL). - PROPOSAL.md: one-commit landing steps, the divergence, and the verifyChain seq-continuity gap as a separate core item (src/chain untouched). - Patch regenerated against main blob 4ae6197 (-> 463a5b8). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Second-family review (minimax-m3.1-flash): fixes and rejectionsPushed as a0e8be6. Each finding was checked against the code, and where a test could show it, by running one. Finding 1 (byte-identity claim false), fixed. Confirmed by running it: when the parseable-line count is not Finding 3 (fake "corrupt line in the middle" scenario), fixed. The scenario now puts garbage between two valid entries, and it is byte-identical. A new Finding 6 (todo tests make the suite blind), fixed.
Finding 4 ( Finding 7 (bench "after" not reproducible), fixed. The bench header and the PR body now give both commands. "After" is Finding 8 (hook can no-op silently), fixed. The hook now throws at load if either the live file or the candidate file is missing. It also sets a marker, and under that marker the tripwire asserts the imported store really is the candidate. A related doc bug turned up while running it: a relative Finding 9 (self-authored oracle), partly rejected. The fidelity test already compares the returned entries field by field ( Finding 10 (lock requirement only in a comment), rejected. Finding 5 (getter, later read error), no change. I agree with the reviewer that no fix is needed. Both effects are already in the PR body's risks. Finding 2 (
Patch. Tests run (this machine, node v24.18.0): Not merged, not approved. The core file still lands only under signature. |
- B2: isHumanPrompt now decides "operator speaking" on the text that
survives the chapters view's noise strippers (claudeUserText, exported,
behaviour unchanged). A <system-reminder> or <local-command-*> user line
no longer closes the segment and files the next action as none.
- S1: KIND_ORDER matches the documented precedence (thinking-redacted
above text-inline-reasoning); a test pins every adjacent pair.
- S2: an unsigned empty or whitespace-only thinking block is now
thinking-empty (shallowest kind), never none, so the step agrees with
the parser's session.thinkingBlocks that a block existed.
- Store cost: appendReceiptGuarded(build, { withChain: false }). Ignored
by the current store; with the tail-only store (PR #72) the per-step
append stops reading the whole chain.
- Tests: fail-first system-reminder fixture, bare <think> tag, exact
partialLineBytes, each cursor-reset reason pinned (incl. path-changed),
no-session-id, tamper test self-contained with a guarded index.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Applied in the live install, each step signed by the owner: - store: tail-only append (proposals/store-tail-append, #72); PENDING_LANDING flipped in the same change. Precondition: live chain 37,173 entries, seq continuous. - hooks: V3-02 session-open reach certificate (#70), V3-04 per-step reasoning (#69), V3-03 tool I/O digest (#71), applied from git's stored patches. - chain: canonicaliser keeps an own __proto__ key in the hash (found while fixing #70); existing hashes unchanged (live chain had zero such keys). - tests: hook-wiring todo markers removed. npm test: 1292 tests, 1292 pass, 0 fail, 0 todo. Deferred to the post-merge evaluation: the #68 matcher line-ending fix, the KNOWN-LIMITS pin re-stamp (needs re-verification of every limit), verifyChain seq continuity, keyed digests, R2 on every tool call. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Core change, staged and not landed.
src/storeis self-mod gated. The builder's Edit onsrc/store/index.jswas denied (no grant on file), so this branch does not modify it. The exact replacement file is atproposals/store-tail-append/index.js. It lands under signature at the sitting. Steps are below and inproposals/store-tail-append/PROPOSAL.md.Cause
Every append parsed the whole chain twice:
createStore()ranloadChain()to buildstore.entries. It read the whole file, split it, andJSON.parsed every line.appendReceipt()/appendReceiptGuarded()ranloadChain()again under the lock. That gaveseq = current.lengthandprevHash = current[last].hash.The append needs only the last entry's
hashand the nextseq. V3-04's step receipt callscreateStore(home).appendReceiptGuarded(() => captureStep(args))on every tool call, so it pays both reads each time.Change (candidate
src/store/index.js)readChainTail(baseDir)(new export). It reads backwards from EOF in 64 KB windows, doubling the window until it holds the whole last non-blank line. Then it parses only that line. It returns one of three results:empty: the file is missing, zero-length, or only blank bytes (space, tab, CR, LF) ending in\n. Blank bytes with no trailing newline (e.g." ") are ananomaly, because the next append would be glued on; the fallback handles that exactly as before.okwith the tail entry.anomaly: anything that is not a well-formed, newline-terminated entry.seq = tail.seq + 1andprevHash = tail.hash. Onemptythe append starts at genesis. Onanomalyit falls back to the old full-read path unchanged. Signing and hashing still go throughcreateChain().append(), andsrc/chainis untouched.store.entriesis loaded on first access (a getter), not increateStore(). Once loaded, it is kept in line with disk and keeps its array identity, as before:createStore()still createsreceipts/eagerly.appendReceiptGuarded(build, { withChain: false }). This is for callers that need the lock but not the chain:build()gets no arguments, and the append reads only the tail. The default is unchanged:build(current)gets the full chain and pays the full read. This option is opt-in, so V3-04 gets the flat cost only ifsrc/reasoningpasses{ withChain: false }. That is a one-line change in PR CORE (signing sitting): v3 V3-04: reasoning trace chained per step (R3) #69. It is not in this PR.reload(),verify()andloadChain()still read the full chain. Full verification is unchanged wherever it is used.Crash and concurrency handling
\n): reported asanomaly, so it never becomes the tail. The append takes the old full-read path, which links to the last parseable entry. Tested at five cut points.loadChaindrops it. The same happens when a complete last line has lost its trailing newline: that line and the next entry are both lost from the loaded view. This follows from how the old path writes, and the fidelity test shows the new path writes the same bytes. A test pins this behaviour. Fixing it changes chain bytes, so it is the owner's call and is out of scope here.line.trim()drops. Any other blank-looking line is an anomaly and falls back.withLock, asloadChainwas. In the new two-process test, A uses a long-lived store with a loadedentriesarray and B uses a fresh store per append withwithChain: false. They append 60 entries each, interleaved, onto a 500-entry chain. Afterwardsseqruns 0..619 with no gaps,verifyChainreturns ok, and A's in-memory view matches a prefix of disk. The existing 8-process test still passes.Fidelity, and the one divergence
test/store-tail-append.test.jsmakesDate.nowandcrypto.randomBytesdeterministic. Ed25519 signatures are already deterministic. The test runs the same append sequence twice:loadChain+createChain(keyPair, current.length, current)+appendEntry);Then it compares the returned entries field by field, the chain files byte for byte, and the verifier verdicts. It covers 12 starting states: no file, empty file, whitespace-only, clean, trailing blank lines, CRLF, torn last line, no trailing newline, garbage last line, non-entry JSON last line, a garbage line between two valid entries, and blank bytes with no trailing newline. It also runs a 300-append clean run that builds a fresh store per append. All are identical against the candidate. Run on the branch without the hook,
createStoreis main's real module, so the same tests also check the reference copy against main's realappendReceipt.The bytes are NOT identical in one class of file, and the earlier wording ("in every case") was wrong. When the number of parseable lines is not
tail.seq + 1, because an entry line before the last was lost or added (overwritten with garbage, deleted, or duplicated, by hand or by disk damage), the old path tookseq = parseable count(reusing or skipping a seq already on disk) and the tail path takestail.seq + 1.prevHashis the same on both. Such a chain already failsverifyChainat the gap (prevHash link), before and after the append, so the append does not turn a good chain bad. A chain written only by the store never falls in this class, including after a torn-tail glue. The test "the one documented divergence" pins it for all three variants (replaced, deleted, duplicated) and asserts the break stays where it was.The fast path does not fall back here: detecting the class needs the parseable-line count, which is the full read the fast path exists to avoid, and nothing in the tail carries it in O(1).
tail.seq + 1is also the safer value of the two.Before / after
The bench imports the LIVE
src/store/index.js, so on this branch a plain run measures main's module:node bench/store-append.jsNODE_OPTIONS="--import=file:///<repo>/proposals/store-tail-append/run-against-candidate.mjs" node bench/store-append.js(the same bench, run against the candidate through the test-only module hook)This machine, node v24.18.0, 40 steps per size. hook-step =
createStore(home)+appendReceiptGuarded(build, { withChain: false })(the V3-04 shape). append-only =appendReceipton one long-lived store. The synthetic entries are about 1.2 KB each, so these chains are larger per entry than the live one.A second "before" run gave 2.36 / 61.41 / 255.18 ms hook-step medians.
Tests
npm teston this branch as pushed (candidate not landed):NODE_OPTIONS="--import=file:///<repo>/proposals/store-tail-append/run-against-candidate.mjs" npm test(the suite run against the candidate through the test-only module hook; the URL must be absolute, because the MCP stdio e2e spawns its server in a temp cwd):With the hook active, the 12 tests that need the candidate run as ordinary tests, not
todo, so the against-candidate run can fail. The baseline on main was 1056 tests, 1056 pass.What is left failing, and why
todoon the branch (PENDING_LANDINGintest/store-tail-append.test.js). They need the candidate module:readChainTailexists,createStoredoes not read the chain, append reads only the tail, and the three divergence pins. Against the code onmainthey fail, which is the fail-first evidence, but they are reported as todo so the suite stays green. They pass against the candidate.npm testif the store module in place exportsreadChainTailwhilePENDING_LANDINGstill marks teststodo, and in the reverse case (flipped but not landed). Under the hook it instead asserts the redirect really fired, so a hook that silently no-ops fails the run. All three states were exercised by hand on a scratch copy of the test file.Landing at the sitting (one commit)
proposals/store-tail-append/store-tail-append.patch, the diff againstsrc/store/index.jsatmain(blob 4ae6197 -> 463a5b8). Before pushing,git apply --checkpassed on it. If a CRLF checkout trips it, add--ignore-whitespace, or use the full fileproposals/store-tail-append/index.js.src/store/index.jswithproposals/store-tail-append/index.js.PENDING_LANDING = {}intest/store-tail-append.test.js. Not in a follow-up: the tripwire failsnpm testuntil it is done.npm test. Expect 1090 pass, 0 todo.proposals/store-tail-append/. The hook and the patch are only useful before landing.src/reasoningpass{ withChain: false }.Risks
seqsource. The old path used the count of parseable lines. The new fast path usestail.seq + 1. These are equal on any chain written only by the store, including after a torn-tail glue. They differ in the class above (an entry line before the last lost or added). In that classverifyChainalready fails on the prevHash link, and the divergence is pinned by a test. The live chain has not been checked by this builder, which was told not to touch it. A one-line check at the sitting: last entry'sseq + 1should equal the number of parseable entries.verifyChainnever checksseqcontinuity (pre-existing insrc/chain, not touched here). A writer that signs a wrongseqwith intact links verifiesok. Written up as a separate core item for the owner's sitting inproposals/store-tail-append/PROPOSAL.md.store.entriesis now a getter, and it is loaded later. It is enumerable and has no setter, and nothing in the repo assigns to it. Two observable effects:entriesaccess or on append, not increateStore().src/mcp/server.js, which builds its store at module load, so its entry count is fresher, not older.store.entries(the gate, the grant checks inbin/hook-pre-tool-use.js, the setup counts) still read the whole chain once. That is inherent in what they do, and only the append got cheaper. Those calls stay O(n).appendReceiptGuardedwithout the option is still O(n). That is deliberate: its callers inspect the chain.run-against-candidate.mjs) redirects module resolution of the store in-process. It changes nothing on disk and is inert unless passed via--import. It throws at load if either the live or the candidate file is missing.Do not merge before the core file lands under signature.
🤖 Generated with Claude Code