Repository navigation
Conversation
jhrozek
left a comment
There was a problem hiding this comment.
This is useful defense-in-depth against unsafe provider-derived child identifiers, but it does not address the underlying JSONL persistence issue: safeName remains lossy, so distinct logical session IDs can still share snapshot, audit, and event-log files.
The planned storage fix is adapter-local:
- Keep
SessionIDand model-visible child handles as opaque logical values. Neitherengine/agentnor Redis changes their identifier grammar. - For new JSONL records, derive a versioned, reversible, filesystem-safe physical token from the complete logical ID. Distinct logical IDs therefore receive distinct snapshot, tool-audit, and event-log file families.
- On read, first resolve the new-format location; if it is absent, fall back to the historical sanitized location and accept it only when the latest embedded snapshot ID exactly matches the requested logical ID.
- Route save, load, event append/read, tool-call audit, list/meta projection, and delete through the same resolver. Deletion must treat a mismatched legacy record as absent, never remove its sidecars.
This preserves existing sessions and published resume: handles, prevents future JSONL aliasing, and protects every source of a logical session ID—including Team/member and caller-created IDs—without imposing a filesystem grammar on provider tool-call IDs.
jhrozek
left a comment
There was a problem hiding this comment.
Inline follow-ups to my top-level review comment (storage refactor proposal).
| for i := 0; i < len(s); i++ { | ||
| c := s[i] | ||
| if (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || | ||
| (c >= '0' && c <= '9') || c == '.' || c == '_' || c == '-' { |
There was a problem hiding this comment.
Identifier grammar collision — validIdentifierSegment permits a leading . but JSONL changes a leading dot to _ in internal/adapter/store/jsonlstore/jsonlstore.go:438-440. As a result, both .child and _child pass the new validator yet persist under the same physical key. The validator therefore does not deliver its stated filename-safety property.
If this allowlist remains, reject leading-dot values (including . and ..) so accepted IDs are fixed points under the current filename mapping. The broader storage fix should still encode physical JSONL keys reversibly rather than rely on an agent-layer allowlist.
There was a problem hiding this comment.
Addressed in the rewritten branch. The agent-layer allowlist is gone. JSONL now keeps logical IDs opaque and writes canonical session families under the disjoint <store>/sid-v1/ namespace using a reversible token. Legacy root-level files are accepted only when the embedded snapshot ID matches exactly.
| // response boundary before the assistant turn can enter history or dispatch. One | ||
| // invalid identifier rejects the whole batch; the diagnostic is deliberately | ||
| // constant so provider-controlled identifiers, names, and arguments are not logged. | ||
| func recordAssistant(ctx context.Context, r *Run, sess *session.Session, asst session.Message) error { |
There was a problem hiding this comment.
Provider-neutral tool-call IDs — the new recordAssistant gate rejects an entire completed turn when any provider-owned tool-call ID is outside this ASCII filename grammar. Tool-call IDs are opaque pairing values, and most calls never derive a child session or touch JSONL; this can reject valid provider/custom-adapter output for ordinary tools.
Filename safety should be handled only when the JSONL adapter maps a logical SessionID to a physical file. That fixes all session-ID sources without changing the engine-wide provider tool-call contract.
There was a problem hiding this comment.
Agreed and addressed. recordAssistant and the provider tool-call ID grammar were removed entirely. Provider call IDs remain opaque; the collision fix now lives only in jsonlstore's logical-ID-to-physical-path resolver.
| return nil, session.NewToolError(callID, | ||
| "Subagent: `resume` cannot be combined with `agent` or `model` — a resumed subagent continues on the default explorer engine"), false | ||
| } | ||
| if !validIdentifierSegment(args.Resume) { |
There was a problem hiding this comment.
Resume compatibility — this validation runs before Store.Load, so a previously emitted and persisted handle such as subagent-call/1 becomes unresumable after upgrade. Those handles are model-visible durable references and may also be backed by Redis or another store with no filesystem restriction.
Keep resume: as an opaque logical ID and let JSONL resolve it through a new encoded-key location plus a verified legacy fallback. That preserves existing published handles while preventing physical-key aliasing.
There was a problem hiding this comment.
Addressed. The resume: validation was removed, so existing handles remain opaque and resumable. JSONL uses the new reversible location first, then falls back to a legacy file only when its latest embedded snapshot ID exactly matches the requested handle. Redis is unchanged.
Co-Authored-By: Juan Antonio Osorio <[email protected]>
|
Thanks — I reworked the PR around the adapter-local design you outlined. The replacement commit keeps logical session IDs, provider call IDs, and model-visible child handles opaque. JSONL now stores canonical snapshot/audit/event families under a versioned reversible namespace, validates embedded ownership before using legacy files, migrates matching legacy families on write, and routes save/load/events/audit/list/meta/delete through one resolver. Mismatched legacy records and sidecars are left untouched. Redis and the public engine API remain unchanged. I also added collision, compatibility, migration, canonical/legacy precedence, deletion-safety, Unicode, and corrupt-record coverage. |
|
Hi @JAORMX — we ran a deep review pass on this and it turned up more than fits in review comments, so rather than force-push your branch or drop 16 commits on it unasked, we've put the work in #491 for you to accept, cherry-pick, or reject. #491 contains your Four issues we'd call blocking, all introduced by the rewrite rather than pre-existing:
1, 2 and 4 share one cause: For 3 we replaced the codec with the Also in there: a torn-tail fix in Happy to split any of it out, hand over the findings and let you drive, or close #491 if you'd rather take a different direction. |
* fix(jsonlstore): preserve opaque session identifiers Co-Authored-By: Juan Antonio Osorio <[email protected]> * docs(flocklease,app): fix stale jsonlstore.safeName cross-references Co-Authored-By: Claude Opus 5 <[email protected]> * refactor(jsonlstore): drop dead branches and hand-rolled sort in resolver Co-Authored-By: Claude Opus 5 <[email protected]> * refactor(jsonlstore): fold the repeated legacy-ownership check into one helper Co-Authored-By: Claude Opus 5 <[email protected]> * refactor(jsonlstore): unify family order, drop duplicate dir, restore invariant rationale Co-Authored-By: Claude Opus 5 <[email protected]> * refactor(jsonlstore): make sidecar order explicit, correct two comments 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]> * docs(app,flocklease): stop claiming safety these sanitizers do not have 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]> * Revert "drop moveLegacyFile's stat preflight" — the stat is load-bearing 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]> * docs(jsonlstore): correct List's cost bound, restore the orphan note, 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]> * fix(jsonlstore): separate canonical ownership from snapshot validity 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]> * fix(jsonlstore): bound the session-id token; warn on failed persistence 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]> * fix(app): stop the delivery queue serving a colliding origin's notes 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]> * docs(jsonlstore): record why the token keeps its sid-v1 prefix 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]> * docs: record the naming decision as ADR 0104; fix stale operator docs 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]> --------- Co-authored-by: Juan Antonio Osorio <[email protected]> Co-authored-by: Claude Opus 5 <[email protected]>
Summary
Compatibility
Verification
task generatetask linttask testgo run ./cmd/mecademoCloses #441