Skip to content

fix(jsonlstore): finish durability guarantees - #786

Merged
JAORMX merged 5 commits into
mainfrom
issue-469-jsonl-durability
Aug 28, 2026
Merged

JAORMX merged 5 commits into
mainfrom
issue-469-jsonl-durability

Conversation

@JAORMX

@JAORMX JAORMX commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • make JSONL event/tool sidecar appends stable-storage aware, short-write safe, owner-only, and recoverable from a torn final record
  • enforce cross-process family serialization and durable ordering for deletion, legacy promotion, and migration checkpoints
  • harden sidecar and adapter-owned directory access against symlink/FIFO substitution
  • coalesce streamed text into bounded, UTF-8-safe durable records without changing client streaming or EventLog's at-most-once contract
  • add failure-injection, real process-interruption, deterministic multi-process contention, relay, and migration coverage
  • document the exact crash/power-loss boundary and legacy compatibility in ADR 0243, architecture notes, and user docs

Durability contract

  • snapshots retain the existing atomic-replace capability model
  • EventLog append fails closed unless file and directory sync are available
  • newline is the event-record commit marker; only an unterminated final fragment is discarded
  • complete corrupt records still fail loudly
  • oversized event records fail before mutation; streamed deltas are durably coalesced into bounded records
  • ToolCall remains best-effort on filesystems without sync support instead of systematically dropping audit records
  • destructive mutation syncs sidecars before snapshot authority and is retry-convergent
  • guarantees assume the underlying storage honors successful sync and atomic rename

Verification

  • all required GitHub checks green, including lint, race shards, docs, user docs, API compatibility, vulnerability scan, perf, and kind e2e
  • task lint
  • task docs
  • task site:build
  • go run ./cmd/mecademo
  • focused race/failure/multi-process JSONL store, relay, migration, and event-source tests
  • independent spec, architecture, security, duplication, and QA reviews; final blockers addressed

Closes #469

@jhrozek jhrozek left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Review: durability core is correct; the issues are around it

Five parallel lanes (POSIX durability, security, Go quality, architecture, docs+tests). Verified locally: go test -race ./internal/adapter/store/jsonlstore/... green (47s), go test ./docs/... green with cache cleared, ADR 0239 header + registration fine, llms.txt a clean regeneration. (golangci-lint was inconclusive here — my build cache hit no space left on device, unrelated to this PR.)

The crash-durability core holds. The dedicated POSIX lane found no HIGH or MEDIUM in the fsync ordering, the newline-commit-marker model, or the truncate-then-append repair, and walked the adversarial cases explicitly — including "truncate lost, write applied, new record shorter than the fragment it should have erased," which converges because a fragment is newline-free by construction. Read's section view is stable against a concurrent append and a concurrent unlink. migrateLegacyFamily syncs both distinct directories at every boundary. Delete's sidecars-before-authority ordering and the mutated reset are both right. The fd-based re-Stat() after O_NOFOLLOW|O_NONBLOCK genuinely closes the TOCTOU rather than narrowing it. Layering is clean and the port contract is clean — engine/port/eventlog.go:36-43 already required durable-before-nil, so this brings jsonlstore into compliance rather than drifting from it.

The test suite is strong: failure injection at each ordering point with retry-convergence assertions, env-gated re-exec interruption while holding the flock, and a 4-process contention test synchronised through os.Pipe barriers with payloads deliberately crossing the 32 KiB block boundary. No sleeps used as synchronisation.


The blocker is not in this diff

HIGH — every streamed token now costs two fsyncs and a flock round-trip on the relay goroutine.

Service.relayEvent (internal/adapter/server/service.go:4805) calls appendEvent unconditionally as its first statement, for every event. That taxonomy includes EvMessageDelta and EvReasoningDelta, emitted once per provider chunk (engine/agent/loop.go:1919). Post-PR each one runs: flock acquire → OpenRoot + Lstat + OpenFile → completeRecordSize + Stat → write → fsync(file) → openDir → fsync(dir) → flock release.

A single 2k-token turn issues hundreds of file+directory fsync pairs, serialised on the goroutine that also drives the client stream. It contends with Engine.save, which takes the same family flock (jsonlstore.go:520), so snapshot persistence now queues behind delta fsyncs, and back-pressure propagates into the loop's guarded-send/hardAbort machinery. ADR 0239's Consequences says only "Syncing and lock-held prefix capture add I/O and contention" — it never confronts that Append's sole production caller is a per-token path.

The obvious fix does not work. Skipping the delta kinds at the relay would break ADR 0038: eventsource.Fold reconstructs assistant text by concatenating the deltas (engine/adapter/eventsource/eventsource.go:341, f.curText += ev.Text). There is no other source in the log — RecordAssistant isn't an event, it lands in the snapshot, and the log's whole purpose is to stand alone. So this needs a real design call: group-commit across a turn, coalescing deltas into one per-turn text record at the relay, or explicitly accepting the cost with a measurement. Not an edit — worth its own ADR note either way.

Don't relax the adapter to fix it; the port demands fail-closed durability and that half is right.


Remaining findings are inline. Rough shape: 3 HIGH (this one, the legacy-Save doc mismatch, the ToolCall audit drop), 6 MEDIUM, ~12 LOW/INFO. The three HIGHs and the ADR-0027 revert are the ones I'd gate on; the rest are mechanical.

Comment thread docs/adr/0239-jsonl-durability.md Resolved
Comment thread docs/adr/0027-cloud-native.md Resolved
@JAORMX
JAORMX force-pushed the issue-469-jsonl-durability branch from b19f612 to b4a9337 Compare August 28, 2026 12:23
@JAORMX
JAORMX merged commit 392fe1a into main Aug 28, 2026
21 checks passed
@JAORMX
JAORMX deleted the issue-469-jsonl-durability branch August 28, 2026 13:26
samuv added a commit that referenced this pull request Aug 31, 2026
main landed ADR 0243 (Local JSONL durability boundaries, #786) while this
branch was in flight, so both claimed 0243. ADR numbering is monotonic and
records are frozen on merge; the landed one keeps the number and the
unmerged one moves. docs/lint's TestRealADRNumberUniqueness is the gate that
catches this, and it is why the collision surfaced as a test failure rather
than as two files quietly sharing an identity.

Renumbered highest-first so 0244 -> 0245 could not collide with the
0243 -> 0244 it was about to vacate:

  0243 SDK compatibility and error contract -> 0244
  0244 Durable run identity                 -> 0245
  0245 Durable cursors and watch            -> 0246

Also updates every cross-reference and the acceptance plan's verify: test
names (TestADR_0243_* -> TestADR_0244_*, and so on), which ac-trace resolves
against the tree.

llms.txt regenerated; it conflicted because main regenerated it too. Per
AGENTS.md a generated file is never hand-merged — this took main's side and
re-ran task docs:llms.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

Signed-off-by: Samuele Verzi <[email protected]>
samuv added a commit that referenced this pull request Aug 31, 2026
)

* docs: ADRs 0243-0245 + acceptance plan for the SDK server enablers

Design record for the Go-side server contracts the TypeScript SDK (#821)
is built on. No production code yet — this is the frozen decision record
and the verification contract the nine-PR stack is measured against.

ADR 0243 — SDK compatibility discovery and the typed error contract.
GetServerInfo answers "what is this server?" without a probe session, and
keeps `capabilities` (what the operator enabled) separate from `features`
(what the build implements): conflating them makes a --no-bash deployment
look like version skew. Features and error codes are open strings, not
proto enums, so a new one is a minor SDK release rather than a wire-compat
event — the discipline the event taxonomy already settled for
EvNoProgress/StopBudget.

ADR 0244 — Durable run identity. A host-minted, colon-free run id fed into
the existing RunRequest.AskIDDiscriminator, whose ADR 0044 contract is
already written in terms of a run id ("A durable host passes its own
RunID") and which nothing supplies today. Persisted on the snapshot so an
awaiting resume is the SAME run; stamped on Event at the relay chokepoint,
Actor-style, so the loop stays storage-agnostic. An empty RunID is a
meaning — session-scoped, not run-scoped — enforced by a closed set that
today holds exactly the three schedule.* types.

ADR 0245 — Durable cursors and the watch transport. port.CursorEventLog is
additive; the Redis event log moves LIST -> Stream because a LIST cannot
express a durable cross-process follow and positional cursors become wrong
data the day anyone adds retention. Gap markers are log-record envelope
variants surfaced as a delivery phase, never a session.Event, so the event
union and kind-parity gate are untouched. The append-gap guarantee is
deliberately weaker than #821 asked for: cross-process gap detection is not
achievable, and the ADR states the residual rather than shipping an
absolute a Redis outage falsifies.

The acceptance plan carries 9 scenarios / 60 numbered ACs with verify:
proofs, delivered as a linear stack of nine PRs — linear because six units
edit harness.proto and five edit http.go, and contracts/gen is committed.

Refs #821, #761.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

Signed-off-by: Samuele Verzi <[email protected]>

* docs: regenerate llms.txt for ADRs 0243-0245 + the SDK server-enablers plan

llms.txt is generated and goes stale the instant docs change; the CI docs
job caught it on this PR. Regenerated with `task docs:llms`.

Verified with the strict gate: 264 documents, 2312 references — 0 broken
links, 0 broken anchors, 0 ambiguous, 0 orphans, 0 unreachable.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

Signed-off-by: Samuele Verzi <[email protected]>

* docs: renumber the SDK ADRs 0243-0245 -> 0244-0246

main landed ADR 0243 (Local JSONL durability boundaries, #786) while this
branch was in flight, so both claimed 0243. ADR numbering is monotonic and
records are frozen on merge; the landed one keeps the number and the
unmerged one moves. docs/lint's TestRealADRNumberUniqueness is the gate that
catches this, and it is why the collision surfaced as a test failure rather
than as two files quietly sharing an identity.

Renumbered highest-first so 0244 -> 0245 could not collide with the
0243 -> 0244 it was about to vacate:

  0243 SDK compatibility and error contract -> 0244
  0244 Durable run identity                 -> 0245
  0245 Durable cursors and watch            -> 0246

Also updates every cross-reference and the acceptance plan's verify: test
names (TestADR_0243_* -> TestADR_0244_*, and so on), which ac-trace resolves
against the tree.

llms.txt regenerated; it conflicted because main regenerated it too. Per
AGENTS.md a generated file is never hand-merged — this took main's side and
re-ran task docs:llms.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

Signed-off-by: Samuele Verzi <[email protected]>

* docs: ADR 0245 — the LOOP stamps Event.RunID, not the relay

Corrects decision 4 before the record freezes. The ADR is Status: Proposed
and unmerged, which is exactly the window this kind of finding is supposed
to land in.

Decision 4 said stamp Event.RunID "at the single relay chokepoint,
Actor-style". Contact with the code says there is no such chokepoint:

  - Service.relayEvent has 4 callers but takes session.Event BY VALUE, so it
    cannot mutate the copy its caller hands to toProto.
  - Five further recorder.Observe sites bypass relayEvent entirely (the gRPC
    drain-to-discard path, three HTTP paths, schedule.go).
  - Actor works only because it is LOG-ONLY: persistence genuinely has one
    chokepoint in appendEvent. RunID must also reach the client wire — the
    SDK resolves a started run on the first run-ID-bearing event — and the
    wire path never passes through appendEvent.

So "stamp at the relay" means stamping at ~9 sites by hand: the per-surface
drift class AGENTS.md records as having already fired three times.

The semantic argument for the Actor precedent does not transfer either.
Actor stays out of the loop because the loop "knows nothing about
principals" — a real domain boundary. A run id is not external metadata: the
run is the loop's own concept, and the loop already labels every event it
emits with run-scoped identity (ev.Seq = r.seq.Add(1)) at exactly the two
sites in question. RunID belongs on the next line.

Decision 2 changes with it: the id now reaches the engine as a new
RunRequest.RunID, and the engine derives the ask discriminator from it when
AskIDDiscriminator is empty. The host still sets ONE field, and ADR 0044's
"a durable host passes its own RunID" is now satisfied literally rather than
by coincidence. AskIDDiscriminator is retained and gains no second writer, so
a future need for a discriminator that is NOT the run id can still set it
explicitly — the derivation is a default, not a constraint.

The cost is recorded honestly in Consequences: engine/agent now carries an
identifier it did not have, and the accepted bound is narrow — the loop may
stamp the id and derive the discriminator from it, and nothing else. It must
never branch on it, log it, send it to a provider, or reach storage with it.

Acceptance plan AC4.2/AC4.3 are updated to match; AC4.3 inverts from "the
loop never stamps RunID" to "every emitted event carries it, stamped at
Run.emit/emitOrAbort".

Refs #821.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

Signed-off-by: Samuele Verzi <[email protected]>

* docs: address review on the SDK ADRs and acceptance plan

Four fixes from the #822 review, plus a renumber forced by main.

RENUMBERED 0244-0246 -> 0248-0250. main landed its own 0244 (full request +
manual compaction), 0245 (safe build diagnostics), 0246 (goccy YAML parser)
while this stack was open, so the SDK ADRs collided with three real records.
0248-0250 are the next free numbers. This is the second time these three have
moved; the first was the off-by-one below.

THE BLOCKING REVIEW ITEM: the ADR index numbered the three new entries
0243/0244/0245 while linking to files 0244-/0245-/0246-, and its "0243" collided
with the already-existing ADR 0243 (local JSONL durability boundaries). The ADR
bodies were numbered correctly and cross-referenced each other correctly
throughout; only the index was wrong.

ADR 0248 (was 0244) decision 7 said gRPC "returns the same string in a status
detail" without saying what the detail is. It is now pinned to
google.rpc.ErrorInfo, with the two reasons that made it the right carrier: it
authors no new proto in contracts/proto (harness.proto is touched by most of the
stack, and each extra edit is another conflict surface), and AIP-193's
reason+domain+metadata shape is decodable by generic gRPC tooling with no
mecatl-specific knowledge.

That surfaced a casing decision the ADR was leaving for the parity gate to
discover: AIP-193 conventionally spells reason in UPPER_SNAKE_CASE, but AC2.2
requires the IDENTICAL string on both transports. Parity wins, lower_snake_case
on both sides, and the departure from the convention is now stated up front
rather than found as a test failure by whoever implements the second transport.

ADR 0249 (was 0245) decision 1 validated the run id only as colon-free, which
moved ADR 0044's CWE-863 replay guard from internally-guaranteed (an atomic
r<serial> counter, uniqueness impossible to violate by construction) to
caller-trusted. The decision now records what was actually built: 128 bits of
crypto/rand at one call site. It also records the alternative that was weighed —
a host-supplied label plus a session-minted monotonic counter — and why the
random id is stronger: a monotonic counter has to survive restarts and replicas
to stay monotonic, which moves the burden onto a persistence scheme that can
itself be got wrong, while 128 random bits collide negligibly however the
process is restarted or replicated.

AC2.4 claimed no problem body carries a secret, but the guard walks only the
harness-authored halves (code, title, type). detail/error carry the server's own
err.Error(), bounded and UTF-8-repaired but not content-scrubbed. The AC now
says that, and says why scrubbing is the wrong control there: it would corrupt
the diagnostic without being a real defence, since the obligation belongs with
the backend that raises the error and knows which value is sensitive.

Gates: docs/lint green (ADR number uniqueness included); matlatl check --strict
green (271 documents, 2368 references, 0 broken).

Refs #821.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

Signed-off-by: Samuele Verzi <[email protected]>

---------

Signed-off-by: Samuele Verzi <[email protected]>
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.

store: finish JSONL durability guarantees

2 participants