Repository navigation
fix(jsonlstore): opaque session ids — review follow-ups on #464 - #491
Merged
Merged
Conversation
Co-Authored-By: Juan Antonio Osorio <[email protected]>
Co-Authored-By: Claude Opus 5 <[email protected]>
…lver Co-Authored-By: Claude Opus 5 <[email protected]>
…ne helper Co-Authored-By: Claude Opus 5 <[email protected]>
… invariant rationale Co-Authored-By: Claude Opus 5 <[email protected]>
Review corrections on the batched mechanical sweep: - Delete iterated familyOrder[:len(familyOrder)-1], which silently depended on the snapshot staying last: reordering familyOrder would have inverted the load-bearing removal order with no compile error. Spell out sidecarKinds instead. - legacySnapshot's doc comment said absent and not-owned "must be treated identically", which a reader could extend to the error case. Name the error as a third outcome that must be propagated, since folding it in would fail open on the ownership proof. - deliverySafeName's comment grouped flocklease.safeName in as "the same sanitizer". It is not: it excludes '.', caps the prefix at 40 runes, and hash-suffixes for injectivity. The layering rationale was also backwards (composition may import adapters; adapter-to-adapter is the real barrier). Co-Authored-By: Claude Opus 5 <[email protected]>
Review of the previous comment fix found it asserted a property the code lacks — the same class of confidently-wrong comment that commit set out to correct. - deliverySafeName's comment said injectivity is something "a lease requires and these two do not". False for the queue: jsonlstore pays for its lossy legacy stem with an ownership proof (it re-reads the id embedded in each snapshot line), but pendingLocked filters on format and delivered-seq only, never on rec.Note.SessionID. Two origin ids differing only in a sanitized rune therefore share one log and one ledger: each reads the other's notes, and either one's MarkDelivered marks the other's seq. Say so, and point at #441 rather than licensing a future maintainer to leave it. - Dropped the "byte-for-byte" phrasing: nothing pins the equality (both functions are unexported to each other), so a claim that precise will rot. They are identical by history, not by contract. - flocklease.safeName's comment called its encoding "injective" with ids that "never collide". The suffix is 64 bits of a SHA-256 digest over a lossy 40-char prefix, which is collision-RESISTANT, as the inline comment on the next line already said. Benign in this direction (a false collision over-serializes on one lock; it never yields two lease holders), but "never" was not true. Co-Authored-By: Claude Opus 5 <[email protected]>
Review found the preflight removal was a bad call on my part, not a bad implementation. os.Stat(src) is not a redundant round-trip that os.Rename's own ENOENT replaces; it does two jobs, and dropping it lost both: - Ordering. Statting the source FIRST is what makes an absent source return nil REGARDLESS of the destination — the interrupted-migration retry shape. Checking the destination first turns a legitimate retry into a spurious clash, which is why the replacement had to add a compensating os.Stat with a DISCARDED error. That swallowed every non-NotExist failure (EACCES, ENOTDIR, ELOOP, EIO) as "already migrated": migrateLegacyFamily then reported success while orphaning the legacy file — the same fail-open shape legacySnapshot's own doc comment warns against. - IsRegular. os.Rename will happily move a directory into the canonical namespace, after which every Load/Save/Append for that id fails with EISDIR forever while List silently omits it. A FIFO is worse: readSnapshotLine's os.Open blocks indefinitely waiting for a writer while Store.mu is held, deadlocking the whole store. Body restored byte-for-byte to a159f50. The added doc comment records why each half cannot be removed, so the next mechanical sweep does not propose it a second time. Co-Authored-By: Claude Opus 5 <[email protected]>
… pin sidecar drift Review of the restored rationale comments found one of them quantitatively wrong, and the sidecarKinds fix needed a test to mean anything. - List's restored COST paragraph claimed O(total store bytes). That was true of the PRE-baseline List, which full-scanned every file via decodeSessionID -> scanLastNonBlankLine, but a159f50 rewrote List onto scanSnapshotDir -> readLastLine, which seeks the last 64 KiB. For 500 sessions of 40 MB the comment implied ~20 GB of reads against an actual ~32 MB, and it contradicted metalist.go's own doc twenty lines away, which advertises O(N x last-line-read). State the real cost instead: one ReadDir per dir plus one tail read per snapshot, with the full-scan degradation named as the exception it is. - Restored the orphan note that a159f50 dropped and 26bf5b4 did not bring back. It is the REASON the sidecars-before-snapshot order is load-bearing (List enumerates only *.session.jsonl, so a sidecar without its snapshot can never be swept), and it existed nowhere after the rewrite. - Delete's comment enumerated "removed" and "idempotent success" but omitted the outcome where it returns an error having removed nothing. Named it as the third outcome, matching the standard set for legacySnapshot. - Added TestSidecarKindsIsFamilyOrderWithoutSnapshot. Splitting familyOrder and sidecarKinds into two literals removed the slice-expression footgun but relocated the drift risk: a fourth kind added to one and not the other compiles, passes every other test, and then silently orphans a file (Delete skips it) or strands one (migration skips it). Mutation-checked by reordering familyOrder, which fails the test. Co-Authored-By: Claude Opus 5 <[email protected]>
Closes ship-blockers 1, 2 and 4 from the review. All three had one cause: canonicalSnapshot answered "is this family mine?" and "is its snapshot parseable?" with a single error return, so callers that only needed the first inherited the second. A torn latest line is the state that exposed it, and it is routine — appendLine does one unsynced write of record+'\n', so any crash, SIGKILL or ENOSPC partway through leaves one. Consequences before this change: - Delete returned an error having removed nothing, violating port.PrunableStore's idempotence. The session became permanently unprunable: every retention sweep re-failed identically, and List skips undecodable files so nothing surfaced it again — an invisible, unreclaimable disk leak. - EventLog.Read failed for a byte-perfect events file, losing the durable log to a scratch on the snapshot beside it. The log exists to survive exactly that crash (ADR 0038 rehydration, ADR 0027 3b approval replay read it back). - Every Save/Append/ToolCall failed, on a full forward scan plus a complete sessnap decode of the snapshot PER APPENDED EVENT — quadratic in run length while holding Store.mu. canonicalOwnership now fails closed ONLY when the stored snapshot positively proves another owner (decodes, and the id differs — reachable solely by hand-copying a file into the canonical namespace, since the token is injective). Torn, empty and undecodable mean ownership UNPROVEN, not disproven: the path token already proves the family is ours, so proceed. This keeps TestCanonicalSnapshotOwnershipMismatchFailsClosed intact — the author's fail-closed posture was about proven mismatch, never about a torn line. The read is a bounded tail read, not a full scan, and the redundant sessnap decode is gone (Store.Load unmarshals the same bytes one frame later). Also fixes the torn-tail append itself, found by the self-heal test: appending record+'\n' onto a fragment with no terminating newline GLUED the two, so one interrupted write corrupted the following record too — and for the snapshot it destroyed the very append that would have repaired it, Load being last-line-wins. appendLine now emits a separating newline when the file does not end in one, bounding damage to the single interrupted record. Tests: torn-snapshot Delete/Read/Save, appendLine's three tail cases, and the corrupt-legacy write and sidecar-read paths, which had no coverage at either call site — the cells this change moves through. Known residual, unchanged and out of scope: a torn line in the EVENTS log still makes Read yield a trailing error after delivering every valid event. Whether a trailing fragment should be tolerated or fail loud is a separate decision. Co-Authored-By: Claude Opus 5 <[email protected]>
Closes ship-blocker 3. Two independent design passes converged on the same answer: the base64 codec was the wrong tool, not a tool needing a guard rail. encodeSessionToken was "sid-v1-" + RawURLBase64(whole id), which inflates 4/3 with no cap, so a filename hit NAME_MAX at 176 bytes of id — DOWN from 241 under the old 1:1 lossy scheme. Consequences: a pre-existing session with a 176-241 byte id became permanently unwritable after an upgrade (ENAMETOOLONG is not os.IsNotExist, so every Save/Append/ToolCall failed forever); a long provider-supplied child id was silently never persisted, because Engine.save discarded its error; and a long model-authored resume: id turned a clean not-found into a raw infrastructure error. The token is now the shape flocklease already uses here: a capped sanitized readable prefix plus a hash suffix, at 128 bits rather than 64. sid-v1-<up to 40 sanitized chars>-<32 hex of SHA-256> That is at most 94 bytes of filename for an id of ANY length, so the ceiling is gone rather than reported more politely. Capping the id instead would have left the broken session broken and promoted an encoding artifact into a contract that only one backend enforces — redisstore takes the same id happily. decodeSessionToken is DELETED. Its one non-test caller already read the logical id from the file's own contents and used the decode only to cross-check the stem; re-encoding forward proves the same thing, so reversibility bought nothing and cost the non-canonical-alias hazard that only exists because a codec is reversible. No operator workflow relied on it: troubleshooting.md already tells readers to take ids from file contents, and the readable prefix makes ls useful again. Zero migration: sid-v1 is on no released tag and not on main, so no deployed store contains one. Legacy families are untouched and now migrate FORWARD successfully at 241 bytes instead of hitting the ceiling. The legacy probe needed one more fix, found by the new conformance case rather than by any jsonlstore test: prepareWrite probes for a legacy family on every write, and legacySafeName is 1:1 with the id, so a 1024-byte id still died on os.Open of a 1024-byte legacy name. An unnameable legacy path means the pre-rewrite scheme could never have created that file, i.e. absence. Engine.save no longer discards its error. Nothing in the session.Event taxonomy reports a failed persist, so the operator log is its only home; the WARN is sticky per run (Run.saveWarned, not Engine — an Engine is shared across sessions) because a broken store fails every save. r.diag carries the session id and a child's role, which is exactly the correlation whose absence made the silent child loss undebuggable. AGENTS.md's "the loop emits exactly THREE lines" was already documentation rot — loop.go had nine LevelWarn sites when counted. Replaced with the rule that actually holds (a line is owed only when no session.Event owns the fact) plus the current list, so the next addition is a visible decision instead of a contradiction. Tests: the long-id round trip goes in storeconformance, so jsonlstore, redisstore, grpcdriver and memstore all inherit it — this is a property of the port contract, and stating it there is what caught the legacy-probe ceiling. Plus a bounded-length pin, injectivity across prefix-truncation neighbours, long-legacy-id forward migration, and a mutation-checked sticky-WARN oracle. Co-Authored-By: Claude Opus 5 <[email protected]>
deliverySafeName is lossy, so two origin session ids differing only in a
sanitized rune ("a/b" and "a_b") share one .delivery.jsonl and one ledger.
pendingLocked filtered on format and delivered-seq only, never on the record's
own SessionID, which cost three things at once:
- Pending returned the OTHER session's notes.
- The backlog cap counted the other session's notes against this session's
budget.
- Worst: the cap's `drop := pending[0]` marked the OTHER session's oldest note
as delivered. A note the victim had never seen was silently dropped, with a
WARN naming the wrong session. The new cap test demonstrates it — before the
fix the victim's own note is gone from its Pending and two of the noisy
origin's notes are there instead.
Fixed by proving ownership from the record rather than the filename, the same
discipline jsonlstore uses for its lossy legacy stem.
maxSeqLocked deliberately does NOT get the same filter, and now says so. The
delivered ledger records bare sequence numbers with no session id, so a shared
file has ONE ledger keyed by seq alone; scanning the whole file keeps colliding
origins' seqs disjoint, which is what makes that ledger unambiguous. Filtering
there would have both origins mint seq 1, and then either one's MarkDelivered
would mark the other's note — converting a read bug into a delivery bug. The
only cost is that a colliding origin's seqs start above 1, which no caller can
observe (seq is opaque and ordering-only).
The pre-existing isolation test used non-colliding ids, so it got two separate
files and passed vacuously; both new tests assert the sharing is real before
asserting anything about it, and both were mutation-checked by removing the
filter.
Not fixed here: the lossy stem itself. Giving this live format a bounded
injective stem is a migration, and it belongs with #441's own question about
which consumers should still name files from session ids.
Co-Authored-By: Claude Opus 5 <[email protected]>
The prefix is redundant with the sid-v1 directory, and two independent reviews proposed deleting it. Keeping it is the decision: a token should name its own scheme when it appears away from its directory — in a WARN, in an operator's find output, in a support bundle or backup listing. Costs 7 bytes of a budget with 161 to spare. Written down so the next review does not re-litigate it a third time. Co-Authored-By: Claude Opus 5 <[email protected]>
Brings the branch up to date with 23 commits of main (it was based on 3e7b647), including the caller-identity/ADR-0100 work that touches the same files this PR rewrites. Merged rather than rebased deliberately: a159f50 is authored by Juan Antonio Osorio and is the published remote tip, so a rebase would have rewritten a colleague's commit, detached any review comments anchored to it, and required a force-push to a shared PR branch. A merge preserves that commit byte-for-byte, resolves the overlap once instead of replaying it across 13 commits, and leaves the push a fast-forward. Six files overlapped. Five auto-merged; each was checked semantically rather than trusted because it compiled: - metalist.go — main added `meta.Owner = m.Owner` to MetaList's projection while this PR rewrote MetaList to project from snapshotFiles(). The auto-merge is faithful: main places the assignment inside the same knownStates guard, in the same position, so an unknown-state row still surfaces id/mtime with a nil Owner, which renders as unowned rather than as somebody else. Main also kept the -62135596800 zero-time comment that this PR had deleted and a later commit restored; the merged file has it exactly once. - engine/port/store.go — main's Owner field and this PR's reworded SessionMeta.ID doc comment coexist. api:check is green (the field was already recorded in engine/api/port.txt by main). - dispatch.go — main's owner propagation (caps.owner = sess.Owner) and this branch's save(ctx, r, sess) signature change are independent hunks. - schedulestore.go, IMPLEMENTATION-NOTES.md — independent hunks. AGENTS.md was the one real conflict: both sides rewrote the diagnostics bullet. Main's edit was a single rename (Engine.Run -> Engine.RunContent); this branch replaced the stale "exactly THREE lines" claim with the rule that actually holds plus the current list. Kept both. Gates on the merged tree: task lint (0 issues x 7 modules), task test, api:check, docs:check, and mecademo all green. Co-Authored-By: Claude Opus 5 <[email protected]>
Closes the documentation debt the review found. AGENTS.md requires a new ADR for a new decision and a same-PR user-docs update for operator-visible behaviour; this PR had done neither. ADR 0104 records the decision honestly, including that the FIRST attempt in this PR (a reversible base64 token) was replaced: it removed the collision and traded it for a length ceiling that made a pre-existing session permanently unwritable. An ADR that showed only the final answer would hide the most useful part. engine/port/store.go — SessionMeta.ID's contract was reworded by this PR to say the id must be "obtained from stored data rather than a physical filename or backend key", which describes ONE adapter's mechanism and makes two compliant adapters read as violations: redisstore recovers ids by trimming a fixed prefix and grpcdriver takes them off the wire, both losslessly. Restated as the testable invariant — the id must be byte-exact, and a LOSSY key obliges recovery from content — which binds jsonlstore and exonerates the others. user-docs — four pages documented the pre-rewrite layout, and extension-points/session-store.md was wrong even before this PR (it claimed "<id>.json" and that Delete removes "both files atomically"; there are three files, removed in a deliberate order, not atomically). They now show the real sid-v1 layout, state plainly that the filename is not the session id, and give the tail|jq loop for recovering ids from contents. mecated.md notes that an older store directory needs no migration step. ADR 0027 List 1 row 8 re-audited per that ADR's own rule: Delete's removal order now holds twice per call, once per family. Gates: lint (0 issues x 7 modules), task test, api:check, docs:check (0 unreachable — 0104 needed an index entry in docs/adr/README.md), site:build, and mecademo. llms.txt regenerated with GOPRIVATE set for the private matlatl module. Co-Authored-By: Claude Opus 5 <[email protected]>
jhrozek
added a commit
that referenced
this pull request
Aug 13, 2026
Rebasing onto origin/main pulled in #491, which moved jsonlstore session files under an owner-only sid-v1/ subdirectory. The stale-running-session e2e test's glob predated that change and stopped finding the seeded snapshot file; check both the pre- and post-#491 locations, mirroring the existing setSessionMtime test helper. Also regenerates llms.txt and picks up additive go.work.sum checksums from the rebase. Co-Authored-By: Claude Sonnet 5 <[email protected]>
7 tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Stacked on #464. Contains @JAORMX's
a159f50bunchanged (authorship intact) plus review follow-ups, based on currentmain.Based on
mainrather than onfix/issue-441deliberately: because this branch mergedmain, afix/issue-441base would compute the diff froma159f50band drag in ~26 commits of unrelated main work. Basing onmainmakes the diff exactlya159f50b+ the follow-ups.@JAORMX's call — accept, cherry-pick, or reject. Happy to split any part out or hand over the findings and let him drive.
Why this exists
#464 fixes a real bug:
legacySafeNameis lossy, so"a/b"and"a_b"shared one session file andLoadreturned whichever wrote last. A deep review confirmed the fix works and found four blocking issues introduced by the rewrite, plus documentation debt.Ship-blockers fixed
1, 2 and 4 share one cause —
canonicalSnapshotanswered "is this family mine?" and "is its snapshot parseable?" with a single error return, so callers needing only the first inherited the second. The trigger is routine:appendLinedoes one unsynced write, so any crash, SIGKILL or ENOSPC mid-write leaves a torn final line.Deletelostport.PrunableStore's idempotence. It returned an error having removed nothing — permanently, and invisibly, becauseListskips undecodable files. An unprunable disk leak from one interrupted write.EventLog.Readfailed for a byte-perfect events file when the snapshot beside it was torn. The log exists to survive exactly that crash (ADR 0038 rehydration, ADR 0027 3b approval replay read it back).ENAMETOOLONGis notos.IsNotExist, so a pre-existing session in that band became permanently unwritable on upgrade — and a long provider-supplied child id was silently never persisted, becauseEngine.savediscarded its error.sessnapdecode of the snapshot — per appended event, so quadratic in run length, all underStore.mu.How
canonicalOwnershipnow fails closed only on a proven mismatch (the stored id decodes and differs — reachable only by hand-planting a file, since the token is injective). Torn/empty/undecodable means ownership unproven, not disproven, so the operation proceeds.TestCanonicalSnapshotOwnershipMismatchFailsClosedpasses untouched — that posture was always about a proven mismatch, never a torn line.For 3, the codec is now the
flocklease.safeNameshape already in this repo — capped readable prefix + 128-bit hash — bounded at 94 bytes for an id of any length.decodeSessionTokenis deleted: its only non-test caller already read the id from file contents and merely needed to verify the stem, which re-encoding forward does just as well. Sincesid-v1never shipped, this cost zero migration.Also fixed
appendLine(found by a test asserting my own claim): appendingrecord + '\n'onto a fragment with no trailing newline glued them, so one interrupted write corrupted the following record — and for the snapshot, destroyed the very append that would have repaired it.FileDeliveryQueueserved a colliding origin's notes.pendingLockednever checkedrec.Note.SessionID. Worst symptom: the backlog cap'sdrop := pending[0]marked another session's oldest note delivered — a silent lost delivery, with a WARN naming the wrong session.maxSeqLockeddeliberately stays unfiltered (the ledger stores bare seqs with no session id, so per-file uniqueness is what keeps it unambiguous) and now says so.Engine.saveno longer discards its error — sticky once per run, onRunnotEngine(an Engine is shared across sessions).user-docs/× 4 pages documented the pre-rewrite layout;session-store.mdwas wrong even before this PR (claimed<id>.jsonand thatDeleteremoves "both files atomically" — it's three files, ordered, not atomic).SessionMeta.ID's reworded contract described one adapter's mechanism and maderedisstore/grpcdriverread as non-compliant. Restated as the testable invariant.LevelWarnsites). Replaced with the rule that holds.Tests
The long-id round trip went into
storeconformance, not jsonlstore — it's a property of the port contract, and stating it there immediately caught a second ceiling the codec fix alone missed:prepareWriteprobes for a legacy family on every write, andlegacySafeNameis 1:1, so a 1024-byte id still died on a 1024-byte legacy filename. A jsonlstore-only test would have passed.Also: torn-snapshot
Delete/Read/Save,appendLine's three tail cases, corrupt-legacy write and sidecar-read paths (neither had coverage at either call site), long-legacy-id forward migration, bounded-token length, injectivity across prefix-truncation neighbours, colliding-origin delivery isolation, and a mutation-checked sticky-WARN oracle. Several were mutation-checked by reverting the fix.Deliberately not done
CreateSessionnever pass anengine/agentvalidator.Readyield a trailing error after delivering every valid event. Tolerate-vs-fail-loud is a design call.delivery_queue/schedulestorelossy stems. Now guarded rather than removed; migrating them belongs with Session ids derived from unvalidated provider- and model-supplied text can collide in the store and falsify the identity model's path invariant #441's own question.docs/agent-identity-model.md's "already true" claim. Verified there is no SPIFFE code in the repo — it's a strawman doc that says so itself — so Session ids derived from unvalidated provider- and model-supplied text can collide in the store and falsify the identity model's path invariant #441's second consumer doesn't exist yet. Worth a one-line correction, but it's @JAORMX's doc to word.Verification
task lint(0 issues × 7 modules),task test,task api:check,task docs:check,task site:build,go run ./cmd/mecademo— all green. Notetask generateneedsGOPRIVATE='github.com/stacklok/*'for the private matlatl module, and a failed run truncatesllms.txtto zero bytes (the recipe redirects stdout).Closes #441.