Skip to content

CORE (signing sitting): store: tail-only append, append cost flat in chain length - #72

Merged
githubscum merged 2 commits into
mainfrom
lotor-lane/store-tail-append
Oct 22, 2026
Merged

githubscum merged 2 commits into
mainfrom
lotor-lane/store-tail-append

Conversation

@githubscum

@githubscum githubscum commented Oct 22, 2026 •

Copy link
Copy Markdown
Owner

Core change, staged and not landed. src/store is self-mod gated. The builder's Edit on src/store/index.js was denied (no grant on file), so this branch does not modify it. The exact replacement file is at proposals/store-tail-append/index.js. It lands under signature at the sitting. Steps are below and in proposals/store-tail-append/PROPOSAL.md.

Cause

Every append parsed the whole chain twice:

  1. createStore() ran loadChain() to build store.entries. It read the whole file, split it, and JSON.parsed every line.
  2. appendReceipt() / appendReceiptGuarded() ran loadChain() again under the lock. That gave seq = current.length and prevHash = current[last].hash.

The append needs only the last entry's hash and the next seq. V3-04's step receipt calls createStore(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 an anomaly, because the next append would be glued on; the fallback handles that exactly as before.
    • ok with the tail entry.
    • anomaly: anything that is not a well-formed, newline-terminated entry.
  • Appends read only the tail, under the same lock. seq = tail.seq + 1 and prevHash = tail.hash. On empty the append starts at genesis. On anomaly it falls back to the old full-read path unchanged. Signing and hashing still go through createChain().append(), and src/chain is untouched.
  • store.entries is loaded on first access (a getter), not in createStore(). Once loaded, it is kept in line with disk and keeps its array identity, as before:
    • If the cached array already ends at the entry the append linked to, the store pushes the new entry.
    • Otherwise another process appended in between, and the store re-reads under the lock.
    • createStore() still creates receipts/ 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 if src/reasoning passes { 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() and loadChain() still read the full chain. Full verification is unchanged wherever it is used.

Crash and concurrency handling

  • Torn last line (crash mid-write, no trailing \n): reported as anomaly, 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.
  • Pre-existing behaviour, kept on purpose and flagged here. The old path writes the new entry straight after the torn bytes. The two glue into one unparseable line, and loadChain drops 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.
  • No trailing newline, unparseable last line, or a last line that is JSON but not an entry: each falls back to the old path, so the bytes written are identical.
  • CRLF and trailing blank lines: handled on the fast path. Space, tab, CR and LF lines are treated as blank, which is a subset of what line.trim() drops. Any other blank-looking line is an anomaly and falls back.
  • Concurrent appenders: the tail is read inside withLock, as loadChain was. In the new two-process test, A uses a long-lived store with a loaded entries array and B uses a fresh store per append with withChain: false. They append 60 entries each, interleaved, onto a 500-entry chain. Afterwards seq runs 0..619 with no gaps, verifyChain returns 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.js makes Date.now and crypto.randomBytes deterministic. Ed25519 signatures are already deterministic. The test runs the same append sequence twice:

  • once through a reference copy of the old append path (loadChain + createChain(keyPair, current.length, current) + appendEntry);
  • once through the store.

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, createStore is main's real module, so the same tests also check the reference copy against main's real appendReceipt.

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 took seq = parseable count (reusing or skipping a seq already on disk) and the tail path takes tail.seq + 1. prevHash is the same on both. Such a chain already fails verifyChain at 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 + 1 is 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:

  • "before": node bench/store-append.js
  • "after": NODE_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 = appendReceipt on one long-lived store. The synthetic entries are about 1.2 KB each, so these chains are larger per entry than the live one.

chain entries chain size hook-step median (before -> after) hook-step p95 (before -> after) append-only median (before -> after)
0 0.0 MB 2.70 -> 1.90 ms 5.83 -> 3.06 ms 1.46 -> 1.12 ms
10,000 12.2 MB 63.51 -> 1.86 ms 73.44 -> 2.23 ms 31.47 -> 1.07 ms
40,000 48.9 MB 274.75 -> 1.87 ms 362.05 -> 4.84 ms 138.33 -> 1.01 ms

A second "before" run gave 2.36 / 61.41 / 255.18 ms hook-step medians.

Tests

npm test on this branch as pushed (candidate not landed):

ℹ tests 1090 ℹ pass 1078 ℹ fail 0 ℹ cancelled 0 ℹ todo 12

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):

ℹ tests 1090 ℹ pass 1090 ℹ fail 0 ℹ cancelled 0 ℹ todo 0

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

  • 12 tests are todo on the branch (PENDING_LANDING in test/store-tail-append.test.js). They need the candidate module: readChainTail exists, createStore does not read the chain, append reads only the tail, and the three divergence pins. Against the code on main they fail, which is the fail-first evidence, but they are reported as todo so the suite stays green. They pass against the candidate.
  • Landing tripwire. A test fails npm test if the store module in place exports readChainTail while PENDING_LANDING still marks tests todo, 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.
  • No pin or freshness stamp was re-stamped. None failed.

Landing at the sitting (one commit)

  1. Review proposals/store-tail-append/store-tail-append.patch, the diff against src/store/index.js at main (blob 4ae6197 -> 463a5b8). Before pushing, git apply --check passed on it. If a CRLF checkout trips it, add --ignore-whitespace, or use the full file proposals/store-tail-append/index.js.
  2. Run the check from Risks below on the live chain.
  3. Under signature, replace src/store/index.js with proposals/store-tail-append/index.js.
  4. In the same commit, set PENDING_LANDING = {} in test/store-tail-append.test.js. Not in a follow-up: the tripwire fails npm test until it is done.
  5. Run npm test. Expect 1090 pass, 0 todo.
  6. Optionally delete proposals/store-tail-append/. The hook and the patch are only useful before landing.
  7. Before wiring V3-04, have src/reasoning pass { withChain: false }.

Risks

  • seq source. The old path used the count of parseable lines. The new fast path uses tail.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 class verifyChain already 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's seq + 1 should equal the number of parseable entries.
  • verifyChain never checks seq continuity (pre-existing in src/chain, not touched here). A writer that signs a wrong seq with intact links verifies ok. Written up as a separate core item for the owner's sitting in proposals/store-tail-append/PROPOSAL.md.
  • store.entries is 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:
    • A read error on the chain now surfaces on first entries access or on append, not in createStore().
    • A store that has not been read yet shows the chain as of first access, not as of construction. This affects src/mcp/server.js, which builds its store at module load, so its entry count is fresher, not older.
  • Gate-path cost is unchanged. Callers that read store.entries (the gate, the grant checks in bin/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).
  • appendReceiptGuarded without the option is still O(n). That is deliberate: its callers inspect the chain.
  • The torn-tail glue (see above) is a pre-existing data-loss path on crash. It is not fixed here. Candidate for KNOWN-LIMITS.
  • The test-only module hook (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

…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>
githubscum added a commit that referenced this pull request Oct 22, 2026
- 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>
@githubscum

Copy link
Copy Markdown
Owner Author

Second-family review (minimax-m3.1-flash): fixes and rejections

Pushed as a0e8be6. Each finding was checked against the code, and where a test could show it, by running one. src/store and src/chain were not touched; the candidate under proposals/ and the tests were.

Finding 1 (byte-identity claim false), fixed. Confirmed by running it: when the parseable-line count is not tail.seq + 1 (an entry line before the last replaced by garbage, deleted, or duplicated), the old path picks seq = count and the tail path picks tail.seq + 1. prevHash is the same, and verification fails at the gap either way. One correction to the review: garbage inserted between valid entries does not diverge, because nothing is lost and the count still matches. The divergence needs a lost or added entry. The candidate docstring, the test header and the PR body now say this. The fast path does not fall back in this case, and this is documented in the code: detecting it 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 + 1 is also the safer value, because the count reuses or skips a seq already on disk.

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 blank bytes only, no trailing newline scenario was added too. A new describe, "the one documented divergence", pins the replaced, deleted and duplicated variants. It asserts both seqs, the shared prevHash, that the bytes differ, and that verifyChain breaks at the same index before and after.

Finding 6 (todo tests make the suite blind), fixed.

  • A landing tripwire test makes npm test fail in two cases: the store in place exports readChainTail while PENDING_LANDING still marks tests todo, or PENDING_LANDING is {} while the candidate has not landed.
  • With the candidate hook active, the tests that need the candidate run as ordinary tests, not todo. So the against-candidate run can now fail, where before both runs reported identical totals.
  • The landing steps (PR body, new proposals/store-tail-append/PROPOSAL.md, test comment) say the flip goes in the same commit as the file replacement.
  • I exercised all three states by hand on a scratch copy of the test file. Flipped without landing: fails. Candidate in place with tests still todo: fails. Candidate in place and flipped: 34/34 pass.

Finding 4 ('empty' docstring), fixed. Confirmed: " " with no newline returns anomaly. The docstring now says this, and the readChainTail test asserts it.

Finding 7 (bench "after" not reproducible), fixed. The bench header and the PR body now give both commands. "After" is NODE_OPTIONS="--import=file:///<repo>/proposals/store-tail-append/run-against-candidate.mjs" node bench/store-append.js. I smoke-ran both at sizes 0 and 2000 to confirm the command works. The table numbers are still the original author's.

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 --import path makes the MCP stdio e2e children (temp cwd) die with ERR_MODULE_NOT_FOUND, which shows up as 4 cancelled tests. Every usage line now says to use an absolute file URL.

Finding 9 (self-authored oracle), partly rejected. The fidelity test already compares the returned entries field by field (deepStrictEqual) as well as the bytes. On the branch run without the hook, createStore is main's real module, so every fidelity scenario already checks oldAppend against main's real appendReceipt. This now passes for all 12 scenarios plus the 300-append run. I documented this in the test header and changed no code. After landing, that cross-check becomes history, which is acceptable.

Finding 10 (lock requirement only in a comment), rejected. readChainTail is read-only. The race needs a write, and the existing public exports loadChain + appendEntry already allow exactly the same unlocked read-then-write. Renaming a core export guards against nothing the API does not already allow. The docstring now states the lock rule and the equivalence.

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 (verifyChain never checks seq continuity), not fixed here, by design. This is pre-existing core in src/chain, and this PR does not touch it. It is written up as a separate core item for the owner's sitting in proposals/store-tail-append/PROPOSAL.md. Suggested check:

Inside the existing loop in verifyChain, after the signature check, require Number.isSafeInteger(entry.seq) && entry.seq === i; otherwise return { ok: false, brokenAt: i, reason: 'seq discontinuity at entry i: expected i, got <seq>' }. verifyChain already assumes a full chain from genesis (entry 0 must carry the genesis prevHash), so seq === i is the matching invariant, and every store-written chain as loadChain sees it satisfies it (the concurrency tests assert seq runs 0..n-1, and a torn-tail glue reuses the lost seq, so the loaded view stays contiguous). Before landing, scan the live chain for seq !== index; a hit means the check would turn a currently verifying chain red, which is a finding to resolve first, not a reason to drop the check. Add a chain test that signs a valid entry with a skipped seq and expects brokenAt at it.

Patch. store-tail-append.patch was regenerated against main blob 4ae6197 (now -> 463a5b8, which matches the committed candidate). It differs from a fresh git diff of the two files only in its path headers, and git apply --check passes in the clone.

Tests run (this machine, node v24.18.0):

npm test (branch):          ℹ tests 1090 ℹ pass 1078 ℹ fail 0 ℹ cancelled 0 ℹ todo 12
npm test (against candidate, absolute-URL hook):
                            ℹ tests 1090 ℹ pass 1090 ℹ fail 0 ℹ cancelled 0 ℹ todo 0

Not merged, not approved. The core file still lands only under signature.

@githubscum
githubscum merged commit a20a0f2 into main Oct 22, 2026
githubscum added a commit that referenced this pull request Oct 22, 2026
- 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>
githubscum added a commit that referenced this pull request Oct 22, 2026
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>
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.

1 participant