Skip to content

feat(engine,store): port.CursorEventLog, its conformance suite, and two backends - #868

Merged
samuv merged 4 commits into
mainfrom
sdk/06a-cursor-event-log
Aug 31, 2026
Merged

samuv merged 4 commits into
mainfrom
sdk/06a-cursor-event-log

Conversation

@samuv

@samuv samuv commented Aug 31, 2026

Copy link
Copy Markdown
Contributor

What

port.CursorEventLog — durable positions over the event log — plus its shared conformance suite and the two local backends. PR 6a of the #821 stack; sdk/06b adds Redis and the gRPC driver. Scenario 6 of docs/acceptance/sdk-server-enablers.md, per ADR 0250.

Why

The engine ships two read paths and neither can replay-then-follow as one operation.

port.EventLog.Read is a complete, ordered, durable replay with no position and no follow — it reads the whole log and stops. Catching up and then watching means reading everything and then subscribing, and any event appended between those two steps is silently lost. There is no token meaning "resume from here".

ReadAfter closes that window: ReadOptions.Follow keeps the iterator open at the tail, and LogRecord.Live reports the replay/live boundary a follower needs to tell its caller it is caught up.

port.EventLog is untouched. CursorEventLog embeds it, so every cursor backend is usable anywhere an EventLog is expected and no existing consumer changes.

The three load-bearing properties

Cursors are generation-scoped. This is the whole reason the type exists rather than an int64. A positional cursor into a rebuilt log does not fail — it resolves happily to a real record that is simply not the one the client last saw, so the only symptom is wrong data much later. A generation mismatch converts that into ErrCursorExpired. A token that cannot be decoded is the distinct ErrCursorMalformed, because an expired cursor is retryable from the beginning while a malformed one indicates a bug or tampering that restarting would hide. Neither is ever coerced to a position. EncodeCursor/DecodeCursor live in port so the envelope and its tamper rejection have one implementation rather than one per backend.

The zero Cursor means the beginning of the log, not the latest. A first attach has no cursor and replaying a session's history is the common case; treating the zero value as "latest" would silently skip a whole transcript.

A gap marker is a log-record envelope variant, never a session.Event. A gap is a fact about delivery, so it occupies a real append position — cursors advance past it correctly — while the legacy Read skips it, preserving that port's contract of returning only events. session.Event, the proto Event message, and the kind-parity surface gain nothing (AC6.8 asserts that structurally, by walking both).

Backends

  • memstore — the reference, and the suite's own validation: no I/O, no encoding, no migration, so a failure there is a failure of the contract rather than of a storage detail. Uses close-and-replace channel broadcast so follow composes with context cancellation as sync.Cond would not.
  • jsonlstore — byte offsets (Seek is O(1); a line index would need a rescan), size-polled follow, and a record-boundary assertion as the tamper guard a byte offset needs.

Tests are mutation-verified, not just green

Each AC oracle was checked by breaking the property and confirming the failure:

Mutation Caught by
Drop the generation check in DecodeCursor TestADR_0250_StaleGenerationCursorExpires
Coerce a malformed cursor to "the beginning" TestADR_0250_TamperedCursorRejected
Leak gap records into the legacy Read TestADR_0250_EventLogContractUnbroken + ..._GapMarkerIsEnvelopeNotEvent
Widen the gap vocabulary to a field that exists proves both reflection walkers reach real fields rather than passing vacuously

Scenario 6 ships as two PRs

As one unit it is a new engine port plus a storage-format migration plus a proto change across four backends — a diff in which the additive port and the Redis datatype migration would each be reviewed less carefully than either deserves, and the migration is the call ADR 0250 itself names as its most expensive. The plan records the split and that AC6.1 and AC6.5 complete only at the end of 06b, since each is a claim about the full set of backends.

Also corrects six verify: names and eight Go comments still citing ADR 0246; #822 renumbered these records to 0248–0250 after main took 0244–0246.

Note for reviewers: the wider stack still has stale test names I deliberately did not touch — sdk/01 renamed to TestADR_0248_* but 02–05 kept TestADR_0244_*/0245_*, and the plan matches the latter. Fixing that would have meant touching already-merged work, so only Scenario 6 is corrected here.

Verification

Run on this branch in isolation, not at the stack tip:

  • task test — exit 0, 175 packages, 0 failures (exit code captured to a file, not read through a pipe that would mask it).
  • task lint — clean. It caught a real gocyclo 21 > 20 in readEventPage, fixed by extracting decodeEventPage, which also splits the lock-holding capture half from the decode half.
  • task api:check — regenerated; the surface diff is purely additive (no removals), so Added = minor per engine/COMPATIBILITY.md, with an engine/CHANGELOG.md entry.
  • go test ./docs/lint — green (note: task docs:check does not run TestRealDesignDocsCitations).
  • task docs:check — 0 broken links/anchors/orphans; llms.txt regenerated.
  • go run ./cmd/mecademo — full offline session (turn → tool.call → permission.ask + approval → result).

Refs #821.

🤖 Generated with Claude Code

@samuv samuv self-assigned this Aug 31, 2026

@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.

Reviewed the new port.CursorEventLog port, memstore/jsonlstore backends, and the shared conformance suite. Design and security posture are solid (no tamper/bounds/injection findings). Two blocking gaps, both about what the conformance suite fails to force every backend to prove rather than a bug in either shipped backend today — flagging before #869 (which stacks on top) inherits an unproven contract permanently. Several non-blocking suggestions follow.

Comment thread engine/port/cursoreventlog.go Resolved
Comment thread engine/port/cursoreventlog.go Resolved
Comment thread engine/port/cursoreventlog.go Resolved
Comment thread engine/port/cursoreventlog.go Resolved
Comment thread engine/port/cursoreventlog.go Resolved
samuv added a commit that referenced this pull request Aug 31, 2026
…ation

Review on #868 flagged that generation was never PROVEN session-scoped.
Reproducing it showed the gap was worse than unproven: it is live
silent-wrong-data on the legacy path, in both shipped backends.

    jsonlstore:  ReadAfter(sess-bbb, cursor-for-sess-aaa) -> [B-3 B-4 B-5]
    redisstore:  ReadAfter(sess-bbb, cursor-for-sess-aaa) -> [B-three B-four]

Both returned records with a nil error. A position is only meaningful
inside ONE log, and the generation check cannot separate two logs whenever
they share a basis value — which legacy logs do SYSTEMATICALLY, because a
log predating generations reports the EMPTY generation. So a cursor issued
for session A decoded cleanly against session B and resolved to a real but
wrong record. (Non-legacy logs were already safe: random per-log
generations differ. The exposure is exactly the upgrade window ADR 0250's
legacy story exists to keep serving.)

Fix: the cursor envelope carries the session id and DecodeCursor verifies
it. In port rather than per backend, because that is what makes the
guarantee structural — a backend cannot forget it, a new backend inherits
it, and it holds where a generation check structurally cannot. The
mismatch is ErrCursorMalformed, not ErrCursorExpired: nothing moved
underneath the caller, the cursor was never valid here.

Also from the same review:

- The conformance suite now proves the legacy port.EventLog.Append path
  lands in the cursor position space. Every backend's doc comment claimed
  it; nothing checked it, so a backend that special-cased Append into a
  side channel would pass the suite while hiding relay-written events from
  every follower.
- Cross-session rejection, and a gap consuming a Limit slot, are now
  conformance cases rather than per-backend accidents.
- Limit under Follow is documented and pinned as a TOTAL, not a
  per-wake-up budget. The two readings are indistinguishable until a
  follower quietly streams forever.
- Pure-garbage cursors must now be ErrCursorMalformed EXACTLY. Accepting
  "malformed or expired" let a backend collapse a distinction the port
  keeps deliberately; only an unresolvable position stays ambiguous.
- EncodeCursor's unreachable marshal-failure branch no longer falls back
  to the zero Cursor. The zero value means "replay from the beginning", so
  that fallback would turn an impossible bug into a silent full replay the
  consumer reads as an increment. It is now a value every DecodeCursor
  rejects.
- The expiry error no longer echoes the CURRENT generation, so a client
  able to trigger an expiry cannot fish the live basis out of it.
- jsonlstore's follow-cost comment claimed "one Stat per watcher per tenth
  of a second"; each tick is really ~2 opens + 2 tail probes + a header
  scan. Corrected rather than optimised, with the reason recorded: the
  heavy half IS the generation re-check that turns a recreated log under a
  live follower into ErrCursorExpired, and mecak8s follows through
  redisstore's XREAD (ADR 0048), not jsonlstore — so this is not the
  many-follower path. If that changes, the gate must compare inode too.

Each new oracle is mutation-verified: dropping the session check, zeroing
the encode fallback, reporting a foreign session as Expired, and making
legacy Append invisible to cursors each fail the intended assertion.

ADR 0250 decision 3 is updated in place — its status is Proposed, so it is
not yet frozen — and the CHANGELOG entry describes the shipped two-axis
scoping. Still Added/minor: the port is unreleased, so no consumer sees a
signature change.

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

Signed-off-by: Samuele Verzi <[email protected]>
@samuv
samuv force-pushed the sdk/06a-cursor-event-log branch from 0dd9bac to 6153783 Compare August 31, 2026 12:52
samuv added a commit that referenced this pull request Aug 31, 2026
Threads the session id through the four cursor sites so redisstore satisfies
the port's session check (added in the parent commit after review of #868):
the Stream append, the ReadAfter decode, the Stream page stamp, and the
legacy LIST page stamp.

Adds the legacy-LIST regression test for the bug that review surfaced and
this branch reproduced. It belongs here rather than only in the shared
conformance suite, whose cross-session case runs over Stream logs: the
legacy path is where the bug was actually live, and it is the WORSE half.
Two legacy logs both report the EMPTY generation — that is what keeps
pre-ADR-0250 logs readable — so the generation check cannot separate them,
and unlike jsonlstore's byte offset a list INDEX needs no boundary
alignment to land on a real record. Before the fix:

    ReadAfter(sess-bbb, cursor-for-sess-aaa) -> [B-three B-four] err=<nil>

Mutation-verified: removing the port's session check reproduces exactly
that output in the new test. The test also asserts B still reads correctly
with its OWN legacy cursor, so the fix is not a blanket refusal of legacy
cursors.

grpcdriver needs no change: it never calls EncodeCursor, forwarding the
opaque token, so it inherits the check from whichever backend the driver
wraps. Confirmed by the shared suite — all four new conformance cases pass
against it.

AC6.4 in the acceptance plan now states the session axis and names its four
verify tests, so the property is gated at the plan level rather than only in
code.

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

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

JAORMX commented Aug 31, 2026

Copy link
Copy Markdown
Contributor

I pulled both stacked PRs into worktrees and reviewed the cursor contract together with the Redis implementation.

The additive CursorEventLog direction in this PR looks sound, and Redis Streams remain the right durable primitive. One contract-level point worth pinning before more backends arrive: ReadOptions.Limit == 0 should mean an unbounded sequence, not permission for a backend to fetch an unbounded storage response. The Redis implementation currently omits XREAD COUNT in that case. I suggest adding a conformance case or clarifying the port comment so implementations may and should page internally while continuing to yield until cancellation/end.

It would also be valuable for the shared conformance suite to prove early iterator exit/cancellation releases backend resources promptly. That becomes load-bearing for a blocking backend, where a consumer stopping iteration must release its connection and any backend-generation lease.

These are compatible with the existing API; I am not suggesting replacing Follow or moving away from Streams.

samuv added a commit that referenced this pull request Aug 31, 2026
… mid-follow

A cursor read validates the log's generation at entry, which catches a cold
attach with a stale cursor but says nothing about a FOLLOWER: it has already
passed that check and is parked at the tail when the basis moves under it. A
backend that reads the generation once and trusts it for the life of the
iterator passes the existing cold-attach case and silently streams the
replacement log's records.

memstore and jsonlstore both re-check per cycle already, each with a comment
explaining why. redisstore does not. That divergence on a documented contract
point is invisible to any single backend's tests, which is exactly what the
shared suite is for — so the case goes there: append, follow, Reset, append,
and assert ErrCursorExpired rather than a replacement record, a clean end, or
an infrastructure-shaped error. Mutation-verified: removing memstore's
per-cycle check fails it.

Raised in review on #869 against redisstore. This is the third finding of one
shape (a claim in the port doc-comment with no suite case behind it), after the
session-scoping hole on #868 — the pattern, not the instance, is the thing to
notice.

Also states two ReadOptions contract terms whose natural reading is the wrong
one, both raised in review on #868:

  - a POSITIVE Limit is a TOTAL budget for the call, not per-wake-up: reaching
    it ends the read even with Follow set. This was TESTED but never actually
    documented, despite a reply on #868 claiming otherwise.

  - Limit == 0 bounds the SEQUENCE, not the FETCH. It is not permission to pull
    an unbounded response out of storage in one round trip; a backend may, and
    for a large log should, page internally while continuing to yield.

No API surface change (api:check clean) — doc comments, one conformance case,
and the CHANGELOG bullet for the unreleased port.

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
Threads the session id through the four cursor sites so redisstore satisfies
the port's session check (added in the parent commit after review of #868):
the Stream append, the ReadAfter decode, the Stream page stamp, and the
legacy LIST page stamp.

Adds the legacy-LIST regression test for the bug that review surfaced and
this branch reproduced. It belongs here rather than only in the shared
conformance suite, whose cross-session case runs over Stream logs: the
legacy path is where the bug was actually live, and it is the WORSE half.
Two legacy logs both report the EMPTY generation — that is what keeps
pre-ADR-0250 logs readable — so the generation check cannot separate them,
and unlike jsonlstore's byte offset a list INDEX needs no boundary
alignment to land on a real record. Before the fix:

    ReadAfter(sess-bbb, cursor-for-sess-aaa) -> [B-three B-four] err=<nil>

Mutation-verified: removing the port's session check reproduces exactly
that output in the new test. The test also asserts B still reads correctly
with its OWN legacy cursor, so the fix is not a blanket refusal of legacy
cursors.

grpcdriver needs no change: it never calls EncodeCursor, forwarding the
opaque token, so it inherits the check from whichever backend the driver
wraps. Confirmed by the shared suite — all four new conformance cases pass
against it.

AC6.4 in the acceptance plan now states the session axis and names its four
verify tests, so the property is gated at the plan level rather than only in
code.

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
A follower captured the generation once at attach and trusted it for the life
of the iterator, so a log deleted and recreated underneath it kept streaming —
from the REPLACEMENT log, with no error. The new conformance case fails on this
backend today with "handed record 'new basis' from the REPLACEMENT log": not a
hang, not a misclassified error, actual silent wrong data.

The check has to run AFTER the read, not before. A blocking XREAD straddles
time: Redis wakes a blocked client on an XADD to the key, and because stream IDs
are wall-clock derived a replacement log's first entry sorts after the
follower's position — so one reply legitimately carries a record from a log that
did not exist when the cycle began, and a pre-read check passes in exactly that
case. Verifying afterwards cannot be raced the same way: if the record came from
the replacement log, its basis was already stored when it was written.

logBasis carries the anchored/not-anchored distinction jsonlstore already needed
for the same reason. The EMPTY generation is a real value reported by both a
not-yet-created log and a legacy one, so a follower attaching before the first
append must ADOPT the generation that append mints rather than read it as a
reset. Without it every such follower gets a spurious expiry — which is what the
first version of this commit did to the concurrency conformance case.

The legacy LIST path had the same shape with a WORSE trigger. It re-read the
list each tick without re-checking the key type, so the migration — guaranteed
on the log's next append, i.e. during exactly the upgrade window this path
exists to serve — turned LRANGE into WRONGTYPE, reaching the consumer wrapped as
an infrastructure fault. "Your positions are now stream IDs, restart" and "Redis
is unwell, retry" call for opposite responses. It is the same WRONGTYPE that
broke the k8s e2e earlier in this stack: code holding a datatype assumption
across a migration.

Also, per review on #868: ReadOptions.Limit == 0 bounds the SEQUENCE, not the
FETCH. Passing the caller's zero through omitted XREAD COUNT entirely, so a
watcher on a long transcript had Redis materialise the whole log in one reply.
Capped internally at readPageSize with the loop paging past it; asserted at the
wire with a go-redis hook, because internal paging is invisible through
iter.Seq2 and therefore cannot be a conformance case.

And per review on #869, the lease is acquired per cycle and released BEFORE the
caller yields, so a follower parked for hours cannot pin a retired credential
generation open and a slow transport consumer holds no pooled connection. That
partially addresses the shutdown concern as a side effect — Store.Close no
longer waits out its grace with a client pinned — but NOT the whole of it: the
store still does not own its followers and cannot cancel an in-flight blocking
read. The test says so rather than implying otherwise by passing.

Every new test mutation-verified. The Close test was VACUOUS as first written —
it asserted a generous timeout, and Close returns within its 2s grace either
way, so it passed with the lease deliberately held; it now asserts the
"timed_out" shutdown diagnostic and fails on that mutation.

Costs, stated rather than hidden: a TYPE plus a GET per cycle, so an idle
follower issues three commands per followBlock rather than one. Not cacheable —
a cached basis is precisely the stale basis the check exists to catch.

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

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

samuv commented Aug 31, 2026

Copy link
Copy Markdown
Contributor Author

Both points landed — thanks. Detail on the Redis side is in my reply on #869; the port-level halves are here in 21b922a7.

ReadOptions.Limit == 0 should bound the sequence, not the storage response. Agreed and adopted as the stated contract. The port now says it explicitly: zero means "yield until the log ends or the context is cancelled", and is not permission to pull an unbounded response out of storage in one round trip; a backend may, and for a large log should, page internally while continuing to yield.

One amendment to the suggestion, since you offered "a conformance case or clarifying the port comment" — it can only be the comment. Internal paging is invisible through iter.Seq2: a backend that pages and one that doesn't yield byte-identical sequences, so no conformance case can distinguish them. That's why the port comment carries the contract and the enforcement sits at the wire in the backend's own tests (a go-redis hook asserting COUNT is present on every XREAD), plus a crossing-a-page-boundary test for the silent-truncation risk a cap introduces. I also documented that the choice of page size is a backend decision rather than a contract term, so this doesn't read as an obligation a future backend must match numerically.

Prompt resource release on early iterator exit. Agreed that it becomes load-bearing for a blocking backend, and partly there now: the connection lease is acquired per read cycle and released before records are yielded, so a consumer that stops iterating — or merely consumes slowly — no longer holds a pooled connection or pins a credential generation. What's still missing is the store-side half: Store.Close cannot yet cancel or join an in-flight blocking read. That's tracked in #876 along with the isolated follow pool, since both need the same store-owned follower lifecycle.

I haven't added a conformance case for early-exit release, and I'd rather not add a weak one. The property is about backend-internal resources, so at the port level I can only assert that breaking out of the iterator doesn't error or hang — which passes whether or not anything was released. A test that can't fail on the behaviour it names is worse than no test; I learned that again this round, having written exactly such a test for Store.Close and only caught it by mutation. If you have a shape in mind that a leaking backend would actually fail, I'll take it.

samuv added a commit that referenced this pull request Aug 31, 2026
Threads the session id through the four cursor sites so redisstore satisfies
the port's session check (added in the parent commit after review of #868):
the Stream append, the ReadAfter decode, the Stream page stamp, and the
legacy LIST page stamp.

Adds the legacy-LIST regression test for the bug that review surfaced and
this branch reproduced. It belongs here rather than only in the shared
conformance suite, whose cross-session case runs over Stream logs: the
legacy path is where the bug was actually live, and it is the WORSE half.
Two legacy logs both report the EMPTY generation — that is what keeps
pre-ADR-0250 logs readable — so the generation check cannot separate them,
and unlike jsonlstore's byte offset a list INDEX needs no boundary
alignment to land on a real record. Before the fix:

    ReadAfter(sess-bbb, cursor-for-sess-aaa) -> [B-three B-four] err=<nil>

Mutation-verified: removing the port's session check reproduces exactly
that output in the new test. The test also asserts B still reads correctly
with its OWN legacy cursor, so the fix is not a blanket refusal of legacy
cursors.

grpcdriver needs no change: it never calls EncodeCursor, forwarding the
opaque token, so it inherits the check from whichever backend the driver
wraps. Confirmed by the shared suite — all four new conformance cases pass
against it.

AC6.4 in the acceptance plan now states the session axis and names its four
verify tests, so the property is gated at the plan level rather than only in
code.

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
A follower captured the generation once at attach and trusted it for the life
of the iterator, so a log deleted and recreated underneath it kept streaming —
from the REPLACEMENT log, with no error. The new conformance case fails on this
backend today with "handed record 'new basis' from the REPLACEMENT log": not a
hang, not a misclassified error, actual silent wrong data.

The check has to run AFTER the read, not before. A blocking XREAD straddles
time: Redis wakes a blocked client on an XADD to the key, and because stream IDs
are wall-clock derived a replacement log's first entry sorts after the
follower's position — so one reply legitimately carries a record from a log that
did not exist when the cycle began, and a pre-read check passes in exactly that
case. Verifying afterwards cannot be raced the same way: if the record came from
the replacement log, its basis was already stored when it was written.

logBasis carries the anchored/not-anchored distinction jsonlstore already needed
for the same reason. The EMPTY generation is a real value reported by both a
not-yet-created log and a legacy one, so a follower attaching before the first
append must ADOPT the generation that append mints rather than read it as a
reset. Without it every such follower gets a spurious expiry — which is what the
first version of this commit did to the concurrency conformance case.

The legacy LIST path had the same shape with a WORSE trigger. It re-read the
list each tick without re-checking the key type, so the migration — guaranteed
on the log's next append, i.e. during exactly the upgrade window this path
exists to serve — turned LRANGE into WRONGTYPE, reaching the consumer wrapped as
an infrastructure fault. "Your positions are now stream IDs, restart" and "Redis
is unwell, retry" call for opposite responses. It is the same WRONGTYPE that
broke the k8s e2e earlier in this stack: code holding a datatype assumption
across a migration.

Also, per review on #868: ReadOptions.Limit == 0 bounds the SEQUENCE, not the
FETCH. Passing the caller's zero through omitted XREAD COUNT entirely, so a
watcher on a long transcript had Redis materialise the whole log in one reply.
Capped internally at readPageSize with the loop paging past it; asserted at the
wire with a go-redis hook, because internal paging is invisible through
iter.Seq2 and therefore cannot be a conformance case.

And per review on #869, the lease is acquired per cycle and released BEFORE the
caller yields, so a follower parked for hours cannot pin a retired credential
generation open and a slow transport consumer holds no pooled connection. That
partially addresses the shutdown concern as a side effect — Store.Close no
longer waits out its grace with a client pinned — but NOT the whole of it: the
store still does not own its followers and cannot cancel an in-flight blocking
read. The test says so rather than implying otherwise by passing.

Every new test mutation-verified. The Close test was VACUOUS as first written —
it asserted a generous timeout, and Close returns within its 2s grace either
way, so it passed with the lease deliberately held; it now asserts the
"timed_out" shutdown diagnostic and fails on that mutation.

Costs, stated rather than hidden: a TYPE plus a GET per cycle, so an idle
follower issues three commands per followBlock rather than one. Not cacheable —
a cached basis is precisely the stale basis the check exists to catch.

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
…ation

Review on #868 flagged that generation was never PROVEN session-scoped.
Reproducing it showed the gap was worse than unproven: it is live
silent-wrong-data on the legacy path, in both shipped backends.

    jsonlstore:  ReadAfter(sess-bbb, cursor-for-sess-aaa) -> [B-3 B-4 B-5]
    redisstore:  ReadAfter(sess-bbb, cursor-for-sess-aaa) -> [B-three B-four]

Both returned records with a nil error. A position is only meaningful
inside ONE log, and the generation check cannot separate two logs whenever
they share a basis value — which legacy logs do SYSTEMATICALLY, because a
log predating generations reports the EMPTY generation. So a cursor issued
for session A decoded cleanly against session B and resolved to a real but
wrong record. (Non-legacy logs were already safe: random per-log
generations differ. The exposure is exactly the upgrade window ADR 0250's
legacy story exists to keep serving.)

Fix: the cursor envelope carries the session id and DecodeCursor verifies
it. In port rather than per backend, because that is what makes the
guarantee structural — a backend cannot forget it, a new backend inherits
it, and it holds where a generation check structurally cannot. The
mismatch is ErrCursorMalformed, not ErrCursorExpired: nothing moved
underneath the caller, the cursor was never valid here.

Also from the same review:

- The conformance suite now proves the legacy port.EventLog.Append path
  lands in the cursor position space. Every backend's doc comment claimed
  it; nothing checked it, so a backend that special-cased Append into a
  side channel would pass the suite while hiding relay-written events from
  every follower.
- Cross-session rejection, and a gap consuming a Limit slot, are now
  conformance cases rather than per-backend accidents.
- Limit under Follow is documented and pinned as a TOTAL, not a
  per-wake-up budget. The two readings are indistinguishable until a
  follower quietly streams forever.
- Pure-garbage cursors must now be ErrCursorMalformed EXACTLY. Accepting
  "malformed or expired" let a backend collapse a distinction the port
  keeps deliberately; only an unresolvable position stays ambiguous.
- EncodeCursor's unreachable marshal-failure branch no longer falls back
  to the zero Cursor. The zero value means "replay from the beginning", so
  that fallback would turn an impossible bug into a silent full replay the
  consumer reads as an increment. It is now a value every DecodeCursor
  rejects.
- The expiry error no longer echoes the CURRENT generation, so a client
  able to trigger an expiry cannot fish the live basis out of it.
- jsonlstore's follow-cost comment claimed "one Stat per watcher per tenth
  of a second"; each tick is really ~2 opens + 2 tail probes + a header
  scan. Corrected rather than optimised, with the reason recorded: the
  heavy half IS the generation re-check that turns a recreated log under a
  live follower into ErrCursorExpired, and mecak8s follows through
  redisstore's XREAD (ADR 0048), not jsonlstore — so this is not the
  many-follower path. If that changes, the gate must compare inode too.

Each new oracle is mutation-verified: dropping the session check, zeroing
the encode fallback, reporting a foreign session as Expired, and making
legacy Append invisible to cursors each fail the intended assertion.

ADR 0250 decision 3 is updated in place — its status is Proposed, so it is
not yet frozen — and the CHANGELOG entry describes the shipped two-axis
scoping. Still Added/minor: the port is unreleased, so no consumer sees a
signature change.

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
… mid-follow

A cursor read validates the log's generation at entry, which catches a cold
attach with a stale cursor but says nothing about a FOLLOWER: it has already
passed that check and is parked at the tail when the basis moves under it. A
backend that reads the generation once and trusts it for the life of the
iterator passes the existing cold-attach case and silently streams the
replacement log's records.

memstore and jsonlstore both re-check per cycle already, each with a comment
explaining why. redisstore does not. That divergence on a documented contract
point is invisible to any single backend's tests, which is exactly what the
shared suite is for — so the case goes there: append, follow, Reset, append,
and assert ErrCursorExpired rather than a replacement record, a clean end, or
an infrastructure-shaped error. Mutation-verified: removing memstore's
per-cycle check fails it.

Raised in review on #869 against redisstore. This is the third finding of one
shape (a claim in the port doc-comment with no suite case behind it), after the
session-scoping hole on #868 — the pattern, not the instance, is the thing to
notice.

Also states two ReadOptions contract terms whose natural reading is the wrong
one, both raised in review on #868:

  - a POSITIVE Limit is a TOTAL budget for the call, not per-wake-up: reaching
    it ends the read even with Follow set. This was TESTED but never actually
    documented, despite a reply on #868 claiming otherwise.

  - Limit == 0 bounds the SEQUENCE, not the FETCH. It is not permission to pull
    an unbounded response out of storage in one round trip; a backend may, and
    for a large log should, page internally while continuing to yield.

No API surface change (api:check clean) — doc comments, one conformance case,
and the CHANGELOG bullet for the unreleased port.

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

Signed-off-by: Samuele Verzi <[email protected]>
@samuv
samuv force-pushed the sdk/06a-cursor-event-log branch from 99803ee to 0debb84 Compare August 31, 2026 15:44
samuv added a commit that referenced this pull request Aug 31, 2026
Threads the session id through the four cursor sites so redisstore satisfies
the port's session check (added in the parent commit after review of #868):
the Stream append, the ReadAfter decode, the Stream page stamp, and the
legacy LIST page stamp.

Adds the legacy-LIST regression test for the bug that review surfaced and
this branch reproduced. It belongs here rather than only in the shared
conformance suite, whose cross-session case runs over Stream logs: the
legacy path is where the bug was actually live, and it is the WORSE half.
Two legacy logs both report the EMPTY generation — that is what keeps
pre-ADR-0250 logs readable — so the generation check cannot separate them,
and unlike jsonlstore's byte offset a list INDEX needs no boundary
alignment to land on a real record. Before the fix:

    ReadAfter(sess-bbb, cursor-for-sess-aaa) -> [B-three B-four] err=<nil>

Mutation-verified: removing the port's session check reproduces exactly
that output in the new test. The test also asserts B still reads correctly
with its OWN legacy cursor, so the fix is not a blanket refusal of legacy
cursors.

grpcdriver needs no change: it never calls EncodeCursor, forwarding the
opaque token, so it inherits the check from whichever backend the driver
wraps. Confirmed by the shared suite — all four new conformance cases pass
against it.

AC6.4 in the acceptance plan now states the session axis and names its four
verify tests, so the property is gated at the plan level rather than only in
code.

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
A follower captured the generation once at attach and trusted it for the life
of the iterator, so a log deleted and recreated underneath it kept streaming —
from the REPLACEMENT log, with no error. The new conformance case fails on this
backend today with "handed record 'new basis' from the REPLACEMENT log": not a
hang, not a misclassified error, actual silent wrong data.

The check has to run AFTER the read, not before. A blocking XREAD straddles
time: Redis wakes a blocked client on an XADD to the key, and because stream IDs
are wall-clock derived a replacement log's first entry sorts after the
follower's position — so one reply legitimately carries a record from a log that
did not exist when the cycle began, and a pre-read check passes in exactly that
case. Verifying afterwards cannot be raced the same way: if the record came from
the replacement log, its basis was already stored when it was written.

logBasis carries the anchored/not-anchored distinction jsonlstore already needed
for the same reason. The EMPTY generation is a real value reported by both a
not-yet-created log and a legacy one, so a follower attaching before the first
append must ADOPT the generation that append mints rather than read it as a
reset. Without it every such follower gets a spurious expiry — which is what the
first version of this commit did to the concurrency conformance case.

The legacy LIST path had the same shape with a WORSE trigger. It re-read the
list each tick without re-checking the key type, so the migration — guaranteed
on the log's next append, i.e. during exactly the upgrade window this path
exists to serve — turned LRANGE into WRONGTYPE, reaching the consumer wrapped as
an infrastructure fault. "Your positions are now stream IDs, restart" and "Redis
is unwell, retry" call for opposite responses. It is the same WRONGTYPE that
broke the k8s e2e earlier in this stack: code holding a datatype assumption
across a migration.

Also, per review on #868: ReadOptions.Limit == 0 bounds the SEQUENCE, not the
FETCH. Passing the caller's zero through omitted XREAD COUNT entirely, so a
watcher on a long transcript had Redis materialise the whole log in one reply.
Capped internally at readPageSize with the loop paging past it; asserted at the
wire with a go-redis hook, because internal paging is invisible through
iter.Seq2 and therefore cannot be a conformance case.

And per review on #869, the lease is acquired per cycle and released BEFORE the
caller yields, so a follower parked for hours cannot pin a retired credential
generation open and a slow transport consumer holds no pooled connection. That
partially addresses the shutdown concern as a side effect — Store.Close no
longer waits out its grace with a client pinned — but NOT the whole of it: the
store still does not own its followers and cannot cancel an in-flight blocking
read. The test says so rather than implying otherwise by passing.

Every new test mutation-verified. The Close test was VACUOUS as first written —
it asserted a generous timeout, and Close returns within its 2s grace either
way, so it passed with the lease deliberately held; it now asserts the
"timed_out" shutdown diagnostic and fails on that mutation.

Costs, stated rather than hidden: a TYPE plus a GET per cycle, so an idle
follower issues three commands per followBlock rather than one. Not cacheable —
a cached basis is precisely the stale basis the check exists to catch.

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
…ation

Review on #868 flagged that generation was never PROVEN session-scoped.
Reproducing it showed the gap was worse than unproven: it is live
silent-wrong-data on the legacy path, in both shipped backends.

    jsonlstore:  ReadAfter(sess-bbb, cursor-for-sess-aaa) -> [B-3 B-4 B-5]
    redisstore:  ReadAfter(sess-bbb, cursor-for-sess-aaa) -> [B-three B-four]

Both returned records with a nil error. A position is only meaningful
inside ONE log, and the generation check cannot separate two logs whenever
they share a basis value — which legacy logs do SYSTEMATICALLY, because a
log predating generations reports the EMPTY generation. So a cursor issued
for session A decoded cleanly against session B and resolved to a real but
wrong record. (Non-legacy logs were already safe: random per-log
generations differ. The exposure is exactly the upgrade window ADR 0250's
legacy story exists to keep serving.)

Fix: the cursor envelope carries the session id and DecodeCursor verifies
it. In port rather than per backend, because that is what makes the
guarantee structural — a backend cannot forget it, a new backend inherits
it, and it holds where a generation check structurally cannot. The
mismatch is ErrCursorMalformed, not ErrCursorExpired: nothing moved
underneath the caller, the cursor was never valid here.

Also from the same review:

- The conformance suite now proves the legacy port.EventLog.Append path
  lands in the cursor position space. Every backend's doc comment claimed
  it; nothing checked it, so a backend that special-cased Append into a
  side channel would pass the suite while hiding relay-written events from
  every follower.
- Cross-session rejection, and a gap consuming a Limit slot, are now
  conformance cases rather than per-backend accidents.
- Limit under Follow is documented and pinned as a TOTAL, not a
  per-wake-up budget. The two readings are indistinguishable until a
  follower quietly streams forever.
- Pure-garbage cursors must now be ErrCursorMalformed EXACTLY. Accepting
  "malformed or expired" let a backend collapse a distinction the port
  keeps deliberately; only an unresolvable position stays ambiguous.
- EncodeCursor's unreachable marshal-failure branch no longer falls back
  to the zero Cursor. The zero value means "replay from the beginning", so
  that fallback would turn an impossible bug into a silent full replay the
  consumer reads as an increment. It is now a value every DecodeCursor
  rejects.
- The expiry error no longer echoes the CURRENT generation, so a client
  able to trigger an expiry cannot fish the live basis out of it.
- jsonlstore's follow-cost comment claimed "one Stat per watcher per tenth
  of a second"; each tick is really ~2 opens + 2 tail probes + a header
  scan. Corrected rather than optimised, with the reason recorded: the
  heavy half IS the generation re-check that turns a recreated log under a
  live follower into ErrCursorExpired, and mecak8s follows through
  redisstore's XREAD (ADR 0048), not jsonlstore — so this is not the
  many-follower path. If that changes, the gate must compare inode too.

Each new oracle is mutation-verified: dropping the session check, zeroing
the encode fallback, reporting a foreign session as Expired, and making
legacy Append invisible to cursors each fail the intended assertion.

ADR 0250 decision 3 is updated in place — its status is Proposed, so it is
not yet frozen — and the CHANGELOG entry describes the shipped two-axis
scoping. Still Added/minor: the port is unreleased, so no consumer sees a
signature change.

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
… mid-follow

A cursor read validates the log's generation at entry, which catches a cold
attach with a stale cursor but says nothing about a FOLLOWER: it has already
passed that check and is parked at the tail when the basis moves under it. A
backend that reads the generation once and trusts it for the life of the
iterator passes the existing cold-attach case and silently streams the
replacement log's records.

memstore and jsonlstore both re-check per cycle already, each with a comment
explaining why. redisstore does not. That divergence on a documented contract
point is invisible to any single backend's tests, which is exactly what the
shared suite is for — so the case goes there: append, follow, Reset, append,
and assert ErrCursorExpired rather than a replacement record, a clean end, or
an infrastructure-shaped error. Mutation-verified: removing memstore's
per-cycle check fails it.

Raised in review on #869 against redisstore. This is the third finding of one
shape (a claim in the port doc-comment with no suite case behind it), after the
session-scoping hole on #868 — the pattern, not the instance, is the thing to
notice.

Also states two ReadOptions contract terms whose natural reading is the wrong
one, both raised in review on #868:

  - a POSITIVE Limit is a TOTAL budget for the call, not per-wake-up: reaching
    it ends the read even with Follow set. This was TESTED but never actually
    documented, despite a reply on #868 claiming otherwise.

  - Limit == 0 bounds the SEQUENCE, not the FETCH. It is not permission to pull
    an unbounded response out of storage in one round trip; a backend may, and
    for a large log should, page internally while continuing to yield.

No API surface change (api:check clean) — doc comments, one conformance case,
and the CHANGELOG bullet for the unreleased port.

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

Signed-off-by: Samuele Verzi <[email protected]>
@samuv
samuv force-pushed the sdk/06a-cursor-event-log branch from 0debb84 to 7e18a7e Compare August 31, 2026 17:38
samuv added a commit that referenced this pull request Aug 31, 2026
Threads the session id through the four cursor sites so redisstore satisfies
the port's session check (added in the parent commit after review of #868):
the Stream append, the ReadAfter decode, the Stream page stamp, and the
legacy LIST page stamp.

Adds the legacy-LIST regression test for the bug that review surfaced and
this branch reproduced. It belongs here rather than only in the shared
conformance suite, whose cross-session case runs over Stream logs: the
legacy path is where the bug was actually live, and it is the WORSE half.
Two legacy logs both report the EMPTY generation — that is what keeps
pre-ADR-0250 logs readable — so the generation check cannot separate them,
and unlike jsonlstore's byte offset a list INDEX needs no boundary
alignment to land on a real record. Before the fix:

    ReadAfter(sess-bbb, cursor-for-sess-aaa) -> [B-three B-four] err=<nil>

Mutation-verified: removing the port's session check reproduces exactly
that output in the new test. The test also asserts B still reads correctly
with its OWN legacy cursor, so the fix is not a blanket refusal of legacy
cursors.

grpcdriver needs no change: it never calls EncodeCursor, forwarding the
opaque token, so it inherits the check from whichever backend the driver
wraps. Confirmed by the shared suite — all four new conformance cases pass
against it.

AC6.4 in the acceptance plan now states the session axis and names its four
verify tests, so the property is gated at the plan level rather than only in
code.

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
A follower captured the generation once at attach and trusted it for the life
of the iterator, so a log deleted and recreated underneath it kept streaming —
from the REPLACEMENT log, with no error. The new conformance case fails on this
backend today with "handed record 'new basis' from the REPLACEMENT log": not a
hang, not a misclassified error, actual silent wrong data.

The check has to run AFTER the read, not before. A blocking XREAD straddles
time: Redis wakes a blocked client on an XADD to the key, and because stream IDs
are wall-clock derived a replacement log's first entry sorts after the
follower's position — so one reply legitimately carries a record from a log that
did not exist when the cycle began, and a pre-read check passes in exactly that
case. Verifying afterwards cannot be raced the same way: if the record came from
the replacement log, its basis was already stored when it was written.

logBasis carries the anchored/not-anchored distinction jsonlstore already needed
for the same reason. The EMPTY generation is a real value reported by both a
not-yet-created log and a legacy one, so a follower attaching before the first
append must ADOPT the generation that append mints rather than read it as a
reset. Without it every such follower gets a spurious expiry — which is what the
first version of this commit did to the concurrency conformance case.

The legacy LIST path had the same shape with a WORSE trigger. It re-read the
list each tick without re-checking the key type, so the migration — guaranteed
on the log's next append, i.e. during exactly the upgrade window this path
exists to serve — turned LRANGE into WRONGTYPE, reaching the consumer wrapped as
an infrastructure fault. "Your positions are now stream IDs, restart" and "Redis
is unwell, retry" call for opposite responses. It is the same WRONGTYPE that
broke the k8s e2e earlier in this stack: code holding a datatype assumption
across a migration.

Also, per review on #868: ReadOptions.Limit == 0 bounds the SEQUENCE, not the
FETCH. Passing the caller's zero through omitted XREAD COUNT entirely, so a
watcher on a long transcript had Redis materialise the whole log in one reply.
Capped internally at readPageSize with the loop paging past it; asserted at the
wire with a go-redis hook, because internal paging is invisible through
iter.Seq2 and therefore cannot be a conformance case.

And per review on #869, the lease is acquired per cycle and released BEFORE the
caller yields, so a follower parked for hours cannot pin a retired credential
generation open and a slow transport consumer holds no pooled connection. That
partially addresses the shutdown concern as a side effect — Store.Close no
longer waits out its grace with a client pinned — but NOT the whole of it: the
store still does not own its followers and cannot cancel an in-flight blocking
read. The test says so rather than implying otherwise by passing.

Every new test mutation-verified. The Close test was VACUOUS as first written —
it asserted a generous timeout, and Close returns within its 2s grace either
way, so it passed with the lease deliberately held; it now asserts the
"timed_out" shutdown diagnostic and fails on that mutation.

Costs, stated rather than hidden: a TYPE plus a GET per cycle, so an idle
follower issues three commands per followBlock rather than one. Not cacheable —
a cached basis is precisely the stale basis the check exists to catch.

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

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

@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.

Approving. Re-reviewed the whole stack at 7e18a7e3d; every finding from my earlier round is addressed, and I verified the fixes in the code rather than taking the replies at face value.

Both blocking items closed. The legacy-Append gap now has its own conformance case, and session scoping is enforced in port.DecodeCursor rather than per backend — which is the right layer, since it means a new backend inherits it instead of having to remember it. Your finding that this was live silent-wrong-data on the legacy path, not merely unproven, was the more important half; thanks for reproducing it before fixing.

Non-blocking: six fixed and verified — the strict/ambiguous split, Limit+Follow as a documented total budget (with the test asserting the context did not expire, so a hang can't pass), the gap-consumes-a-slot case, cursorEncodeFailed = "!", and the generation dropped from the expiry message. On the round-trip note I was wrong: cursoreventlog_test.go already had it and I was reading the conformance suite.

On the declined jsonlstore stat gate — I agree with you, don't add it. The per-call re-verification is what converts a delete/recreate under a live follower into ErrCursorExpired, so gating it trades a correctness guard for constant factors, and the many-follower deployment goes through redisstore anyway. The comment carrying the reason plus the inode requirement is the right outcome.

I also read the two commits that landed after my round. 0237a72e7 (per-cycle basis re-verification, caught by the divergence between backends) belongs in the shared suite exactly where you put it. 7e18a7e3d is a good catch on my behalf too — that assertion was unsound from the start for every backend, and the ordering argument for why appending on every tick prevents the transition it waits for is correct.

CI is green on this SHA. Only thing outstanding is a conflict in the generated llms.txt against main (one commit behind). Rebase, take either side, re-run task docs:llms, and merge — no need to come back to me.

samuv added 3 commits August 31, 2026 22:20
…wo backends

The storage seam for replay-then-follow. `port.EventLog` is a complete, ordered,
durable replay with no position and no follow — it reads the whole log and stops
— so catching up and then watching means reading everything and THEN
subscribing, and any event appended between those two steps is silently lost.
There is no token meaning "resume from here".

`port.CursorEventLog` adds one: an append reports where the record landed, and
`ReadAfter` resumes strictly after a position, optionally staying open at the
tail. `EventLog` is untouched and `CursorEventLog` EMBEDS it, so every cursor
backend is usable anywhere an `EventLog` is expected and no existing consumer
changes.

Three properties are load-bearing and each has its own oracle:

Cursors are generation-scoped. A positional cursor into a rebuilt log does not
fail — it resolves happily to a real record that is simply not the one the
client last saw, so the only symptom is wrong data much later. A generation
mismatch converts that into `ErrCursorExpired`, and a token that cannot be
decoded is the DISTINCT `ErrCursorMalformed`, because an expired cursor is
retryable from the beginning while a malformed one indicates a bug or tampering
that restarting would hide. Neither is ever coerced to a position.
`EncodeCursor`/`DecodeCursor` live in `port` so the envelope and its tamper
rejection have ONE implementation rather than one per backend.

The zero `Cursor` means the BEGINNING of the log, not the latest. A first attach
has no cursor and replaying a session's history is the common case; treating the
zero value as "latest" would silently skip a whole transcript.

A gap marker is a log-record ENVELOPE variant, never a `session.Event`. A gap is
a fact about delivery rather than something that happened in the run, so it
occupies a real append position — cursors advance past it correctly — while the
legacy `Read` SKIPS it, preserving that port's contract of returning only
events. `session.Event`, the proto `Event` message, and the kind-parity surface
gain nothing.

Backends here are memstore (the reference: no I/O, no encoding, no migration, so
a failure there is a failure of the contract rather than of a storage detail)
and jsonlstore (byte offsets, since `Seek` is O(1) where a line index would need
a rescan; size-polled follow; a record-boundary assertion as the tamper guard a
byte offset needs). Redis and the gRPC driver follow in 06b.

The AC-named tests are mutation-verified rather than assumed: dropping the
generation check, coercing a malformed cursor to "the beginning", and leaking gap
records into the legacy `Read` each make them fail, and the reflection walkers
are shown to reach real fields rather than passing vacuously.

Scenario 6 now ships as two PRs. As one unit it is a new engine port plus a
storage-format migration plus a proto change across four backends — a diff in
which the additive port and the Redis datatype migration would each be reviewed
less carefully than either deserves. The plan records the split, and that AC6.1
and AC6.5 complete only at the end of 06b since each is a claim about the full
set of backends.

Also corrects six `verify:` names and eight Go comments still citing ADR 0246;

Refs #821.

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

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

Review on #868 flagged that generation was never PROVEN session-scoped.
Reproducing it showed the gap was worse than unproven: it is live
silent-wrong-data on the legacy path, in both shipped backends.

    jsonlstore:  ReadAfter(sess-bbb, cursor-for-sess-aaa) -> [B-3 B-4 B-5]
    redisstore:  ReadAfter(sess-bbb, cursor-for-sess-aaa) -> [B-three B-four]

Both returned records with a nil error. A position is only meaningful
inside ONE log, and the generation check cannot separate two logs whenever
they share a basis value — which legacy logs do SYSTEMATICALLY, because a
log predating generations reports the EMPTY generation. So a cursor issued
for session A decoded cleanly against session B and resolved to a real but
wrong record. (Non-legacy logs were already safe: random per-log
generations differ. The exposure is exactly the upgrade window ADR 0250's
legacy story exists to keep serving.)

Fix: the cursor envelope carries the session id and DecodeCursor verifies
it. In port rather than per backend, because that is what makes the
guarantee structural — a backend cannot forget it, a new backend inherits
it, and it holds where a generation check structurally cannot. The
mismatch is ErrCursorMalformed, not ErrCursorExpired: nothing moved
underneath the caller, the cursor was never valid here.

Also from the same review:

- The conformance suite now proves the legacy port.EventLog.Append path
  lands in the cursor position space. Every backend's doc comment claimed
  it; nothing checked it, so a backend that special-cased Append into a
  side channel would pass the suite while hiding relay-written events from
  every follower.
- Cross-session rejection, and a gap consuming a Limit slot, are now
  conformance cases rather than per-backend accidents.
- Limit under Follow is documented and pinned as a TOTAL, not a
  per-wake-up budget. The two readings are indistinguishable until a
  follower quietly streams forever.
- Pure-garbage cursors must now be ErrCursorMalformed EXACTLY. Accepting
  "malformed or expired" let a backend collapse a distinction the port
  keeps deliberately; only an unresolvable position stays ambiguous.
- EncodeCursor's unreachable marshal-failure branch no longer falls back
  to the zero Cursor. The zero value means "replay from the beginning", so
  that fallback would turn an impossible bug into a silent full replay the
  consumer reads as an increment. It is now a value every DecodeCursor
  rejects.
- The expiry error no longer echoes the CURRENT generation, so a client
  able to trigger an expiry cannot fish the live basis out of it.
- jsonlstore's follow-cost comment claimed "one Stat per watcher per tenth
  of a second"; each tick is really ~2 opens + 2 tail probes + a header
  scan. Corrected rather than optimised, with the reason recorded: the
  heavy half IS the generation re-check that turns a recreated log under a
  live follower into ErrCursorExpired, and mecak8s follows through
  redisstore's XREAD (ADR 0048), not jsonlstore — so this is not the
  many-follower path. If that changes, the gate must compare inode too.

Each new oracle is mutation-verified: dropping the session check, zeroing
the encode fallback, reporting a foreign session as Expired, and making
legacy Append invisible to cursors each fail the intended assertion.

ADR 0250 decision 3 is updated in place — its status is Proposed, so it is
not yet frozen — and the CHANGELOG entry describes the shipped two-axis
scoping. Still Added/minor: the port is unreleased, so no consumer sees a
signature change.

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

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

A cursor read validates the log's generation at entry, which catches a cold
attach with a stale cursor but says nothing about a FOLLOWER: it has already
passed that check and is parked at the tail when the basis moves under it. A
backend that reads the generation once and trusts it for the life of the
iterator passes the existing cold-attach case and silently streams the
replacement log's records.

memstore and jsonlstore both re-check per cycle already, each with a comment
explaining why. redisstore does not. That divergence on a documented contract
point is invisible to any single backend's tests, which is exactly what the
shared suite is for — so the case goes there: append, follow, Reset, append,
and assert ErrCursorExpired rather than a replacement record, a clean end, or
an infrastructure-shaped error. Mutation-verified: removing memstore's
per-cycle check fails it.

Raised in review on #869 against redisstore. This is the third finding of one
shape (a claim in the port doc-comment with no suite case behind it), after the
session-scoping hole on #868 — the pattern, not the instance, is the thing to
notice.

Also states two ReadOptions contract terms whose natural reading is the wrong
one, both raised in review on #868:

  - a POSITIVE Limit is a TOTAL budget for the call, not per-wake-up: reaching
    it ends the read even with Follow set. This was TESTED but never actually
    documented, despite a reply on #868 claiming otherwise.

  - Limit == 0 bounds the SEQUENCE, not the FETCH. It is not permission to pull
    an unbounded response out of storage in one round trip; a backend may, and
    for a large log should, page internally while continuing to yield.

No API surface change (api:check clean) — doc comments, one conformance case,
and the CHANGELOG bullet for the unreleased port.

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

Signed-off-by: Samuele Verzi <[email protected]>
…f assuming it

The follow case asserted that a record appended during a follow is marked Live.
But live flips on the follower's first EMPTY read, and "the follower has reached
the tail" is not observable from the test — so an append landing before the
follower's second read is classified as replay, which is CORRECT per the
contract: a batch arriving before the first empty result is still replay, however
recently it was written.

The assertion was therefore unsound for every backend from the start. It passed
thousands of local runs because the window is sub-millisecond; the per-cycle
basis re-verification added in this stack widened it enough that a loaded CI
runner under -race lost the race, on redisstore.

Now the precondition is established rather than assumed: wait for the follower to
go idle, THEN append, and retry with a doubling backoff until a record comes back
Live.

The ORDERING is the substance. A first version of this loop appended on every
tick with a fixed short pause, which kept the stream permanently non-empty and so
prevented the very transition it was waiting for — it failed against a follower
made artificially slow, never once seeing Live in 20 attempts. Appending only
after a wait, and doubling that wait, converges instead: a cycle's length is a
backend detail the suite cannot know, and a constant tuned to one backend
silently stops holding for the next.

Validated against the failure mode rather than against a green run: with a 250ms
delay injected before the follower's second read, the previous assertion fails
with CI's exact message and this one passes. Both directions remain
mutation-verified — a backend that never sets Live exhausts the bound, one that
sets it during replay fails the existing replay assertion.

Not fixed by making the implementation flip live on a partial page. That is a
sound inference and would close the window at its source, but it is a behaviour
change beyond this round's findings, and the defect was in what the test assumed
— which every future backend inherits.

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

Signed-off-by: Samuele Verzi <[email protected]>
@samuv
samuv force-pushed the sdk/06a-cursor-event-log branch from 7e18a7e to ab5e010 Compare August 31, 2026 20:30
samuv added a commit that referenced this pull request Aug 31, 2026
Threads the session id through the four cursor sites so redisstore satisfies
the port's session check (added in the parent commit after review of #868):
the Stream append, the ReadAfter decode, the Stream page stamp, and the
legacy LIST page stamp.

Adds the legacy-LIST regression test for the bug that review surfaced and
this branch reproduced. It belongs here rather than only in the shared
conformance suite, whose cross-session case runs over Stream logs: the
legacy path is where the bug was actually live, and it is the WORSE half.
Two legacy logs both report the EMPTY generation — that is what keeps
pre-ADR-0250 logs readable — so the generation check cannot separate them,
and unlike jsonlstore's byte offset a list INDEX needs no boundary
alignment to land on a real record. Before the fix:

    ReadAfter(sess-bbb, cursor-for-sess-aaa) -> [B-three B-four] err=<nil>

Mutation-verified: removing the port's session check reproduces exactly
that output in the new test. The test also asserts B still reads correctly
with its OWN legacy cursor, so the fix is not a blanket refusal of legacy
cursors.

grpcdriver needs no change: it never calls EncodeCursor, forwarding the
opaque token, so it inherits the check from whichever backend the driver
wraps. Confirmed by the shared suite — all four new conformance cases pass
against it.

AC6.4 in the acceptance plan now states the session axis and names its four
verify tests, so the property is gated at the plan level rather than only in
code.

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
A follower captured the generation once at attach and trusted it for the life
of the iterator, so a log deleted and recreated underneath it kept streaming —
from the REPLACEMENT log, with no error. The new conformance case fails on this
backend today with "handed record 'new basis' from the REPLACEMENT log": not a
hang, not a misclassified error, actual silent wrong data.

The check has to run AFTER the read, not before. A blocking XREAD straddles
time: Redis wakes a blocked client on an XADD to the key, and because stream IDs
are wall-clock derived a replacement log's first entry sorts after the
follower's position — so one reply legitimately carries a record from a log that
did not exist when the cycle began, and a pre-read check passes in exactly that
case. Verifying afterwards cannot be raced the same way: if the record came from
the replacement log, its basis was already stored when it was written.

logBasis carries the anchored/not-anchored distinction jsonlstore already needed
for the same reason. The EMPTY generation is a real value reported by both a
not-yet-created log and a legacy one, so a follower attaching before the first
append must ADOPT the generation that append mints rather than read it as a
reset. Without it every such follower gets a spurious expiry — which is what the
first version of this commit did to the concurrency conformance case.

The legacy LIST path had the same shape with a WORSE trigger. It re-read the
list each tick without re-checking the key type, so the migration — guaranteed
on the log's next append, i.e. during exactly the upgrade window this path
exists to serve — turned LRANGE into WRONGTYPE, reaching the consumer wrapped as
an infrastructure fault. "Your positions are now stream IDs, restart" and "Redis
is unwell, retry" call for opposite responses. It is the same WRONGTYPE that
broke the k8s e2e earlier in this stack: code holding a datatype assumption
across a migration.

Also, per review on #868: ReadOptions.Limit == 0 bounds the SEQUENCE, not the
FETCH. Passing the caller's zero through omitted XREAD COUNT entirely, so a
watcher on a long transcript had Redis materialise the whole log in one reply.
Capped internally at readPageSize with the loop paging past it; asserted at the
wire with a go-redis hook, because internal paging is invisible through
iter.Seq2 and therefore cannot be a conformance case.

And per review on #869, the lease is acquired per cycle and released BEFORE the
caller yields, so a follower parked for hours cannot pin a retired credential
generation open and a slow transport consumer holds no pooled connection. That
partially addresses the shutdown concern as a side effect — Store.Close no
longer waits out its grace with a client pinned — but NOT the whole of it: the
store still does not own its followers and cannot cancel an in-flight blocking
read. The test says so rather than implying otherwise by passing.

Every new test mutation-verified. The Close test was VACUOUS as first written —
it asserted a generous timeout, and Close returns within its 2s grace either
way, so it passed with the lease deliberately held; it now asserts the
"timed_out" shutdown diagnostic and fails on that mutation.

Costs, stated rather than hidden: a TYPE plus a GET per cycle, so an idle
follower issues three commands per followBlock rather than one. Not cacheable —
a cached basis is precisely the stale basis the check exists to catch.

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

Signed-off-by: Samuele Verzi <[email protected]>
@samuv
samuv merged commit 8dc73bb into main Aug 31, 2026
22 checks passed
@samuv
samuv deleted the sdk/06a-cursor-event-log branch August 31, 2026 20:44
samuv added a commit that referenced this pull request Aug 31, 2026
…am (#869)

* feat(redisstore,grpcdriver): migrate the Redis event log LIST -> Stream

Completes Scenario 6: the two remaining CursorEventLog backends, and with them
AC6.1 (all four backends on one shared suite) and AC6.5 (durable cross-process
follow, proved over JSONL and Redis).

WHY THE DATATYPE CHANGED. The Redis event log was a LIST, which gives ordering
and nothing else a durable follower needs. There is no blocking read, so follow
degenerates to LLEN polling per watcher. There is no stable per-entry identity,
so a position can only be an INDEX — stable today only because nothing is ever
trimmed from the head, which also means the log grows without bound and that the
day anyone adds retention every outstanding cursor silently addresses a different
event. Not an error: wrong data.

A STREAM answers all three. XADD IDs are opaque, monotonic and durable, so they
ARE cursors with nothing invented. XREAD BLOCK is the cross-process blocking
follow multi-replica attachment requires. XREAD COUNT gives bounded paging the
unbounded LRANGE 0 -1 never could. And XTRIM MINID makes future retention safe
precisely BECAUSE IDs are not positional.

MIGRATION. A legacy LIST stays READABLE — Read and ReadAfter both dispatch on the
key's actual type, so an upgraded binary serves a log it has never written to,
and reading never mutates. The session's next append migrates it in place inside
ONE Lua EVAL: the LRANGE, the DEL, the re-XADDs, the generation mint and the new
append are atomic together, because separately two concurrent appenders could
both read the pre-migration LIST and lose entries, or mint two bases for one log.
Keeping the key NAME is what lets the existing delete/rebuild scripts survive —
DEL is datatype-agnostic.

The generation key is the subtle half. Positions change from list indices to
stream IDs across the migration, and index 1 and stream ID 1-0 are both
"valid" — so a cursor carried across must not resolve. A legacy log reports the
EMPTY generation, so its cursors expire the moment an append mints a real one.
For the same reason `mecatl:events-gen:<id>` is threaded into BOTH delete Lua
scripts: if it survived a delete, a recreated log would inherit the old basis and
a cursor from the PREVIOUS log would resolve against the new one. Mutation-tested
— reverting just that Lua change makes a stale cursor return records with a nil
error, which is the exact silent corruption generations exist to convert into a
loud failure.

There is ONE write path. Append delegates to AppendEvent and drops the cursor
rather than keeping its own RPUSH: two write paths would have to agree on the
datatype, and the first append through the other one would meet a WRONGTYPE.

The driver protocol gains AppendGap and a server-streaming ReadAfter, plus a
cursor on the existing AppendResponse — additive on a previously-empty message,
so an older driver stays a valid EventLog. Cursor rejections travel as a
google.rpc.ErrorInfo reason (ADR 0248's carrier) rather than a bare status code,
because InvalidArgument also means "session_id is required": mapping by code
alone would report a request-shape bug as a corrupt cursor and send the consumer
to restart from the beginning for nothing. A driver that has not opted in answers
UNIMPLEMENTED, which the client restores as ErrDriverCursorUnsupported — a type
assertion cannot answer that question across a wire, and ADR 0250 requires such a
backend be reported unsupported rather than silently degraded.

ADR 0250 gains the consequence its draft missed, and the one an operator of Redis
Streams at size would raise first: a blocking XREAD occupies a pooled connection,
and that pool is shared with Save/Append, so watchers compete with the write path
rather than merely using spare capacity. Follow blocks in bounded slices and
re-acquires between them, which bounds the hold and makes cancellation prompt but
does not make it free. Recorded as sizing guidance, with the reasoning for not
adding a second pool.

Also corrects documentation that the datatype change silently falsified — none of
which any gate would have caught, since all three are prose rather than links:
the mecak8s runbook told operators to run `redis-cli LRANGE mecatl:events:<id>
0 -1`, which now fails with WRONGTYPE; MECAK8S-PLAN's operations table and
per-method breakdown still described RPUSH/LRANGE; and redisstore's own header
comments still reasoned about LIST atomicity.

No watcher resource is inventoried in ADR 0027 yet because none exists: this PR
ships the storage seam, and nothing in production calls Follow until
WatchSessionEvents lands in Scenario 7, which is where those rows belong.

Refs #821.

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

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

* fix(e2e): read the Redis event log as a Stream in the k8s caller-identity e2e

The LIST -> Stream migration (ADR 0250) left one LIST-shaped reader behind:
eventActors shelled `redis-cli LRANGE mecatl:events:<id> 0 -1`, which now
returns WRONGTYPE. The error text was fed straight into json.Unmarshal, so
the k8s e2e failed with `invalid character 'W' looking for beginning of
value`. Nothing in `task test` compiles this file — it is behind the
`kind_e2e` build tag — so only the kind job could catch it.

Read with XRANGE instead. redis-cli's raw (non-TTY) output flattens each
stream entry to three lines (entry id, field name, value), so the parse
walks in strides of three and ASSERTS that shape rather than scanning for
JSON-looking lines: a stride that silently resynchronised would hide
exactly the datatype drift this parse exists to catch. Verified against a
real Redis (not miniredis, which cannot reproduce redis-cli's output
formatting) by driving the real redisstore append path and parsing the real
command output.

Also skip gap-marker records. AppendGap has no production caller yet, so a
gap cannot appear today, but the record kind now EXISTS — and a gap
carries no `ev` by design, which would trip the envelope's non-empty
assertion. Skipping it keeps the first genuinely-failed append on a healthy
cluster from surfacing as a confusing failure of an identity assertion.

The helper's fail-loud discipline is why this arrived as a named parse
error rather than a 90-second Eventually timeout; the doc comment now
records the Stream shape as the third trap alongside the two an earlier
draft hit.

Docs: three prose references still described the event log as RPUSH/LRANGE
(the user-docs mecak8s storage table and two spots in MECAK8S-PLAN). No
gate covers prose, so they were silently falsified by the datatype change.
ADR 0048's RPUSH/LRANGE line is left alone — ADRs are frozen, and ADR 0250
supersedes that decision.

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

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

* fix(redisstore): scope Redis event-log cursors to the session

Threads the session id through the four cursor sites so redisstore satisfies
the port's session check (added in the parent commit after review of #868):
the Stream append, the ReadAfter decode, the Stream page stamp, and the
legacy LIST page stamp.

Adds the legacy-LIST regression test for the bug that review surfaced and
this branch reproduced. It belongs here rather than only in the shared
conformance suite, whose cross-session case runs over Stream logs: the
legacy path is where the bug was actually live, and it is the WORSE half.
Two legacy logs both report the EMPTY generation — that is what keeps
pre-ADR-0250 logs readable — so the generation check cannot separate them,
and unlike jsonlstore's byte offset a list INDEX needs no boundary
alignment to land on a real record. Before the fix:

    ReadAfter(sess-bbb, cursor-for-sess-aaa) -> [B-three B-four] err=<nil>

Mutation-verified: removing the port's session check reproduces exactly
that output in the new test. The test also asserts B still reads correctly
with its OWN legacy cursor, so the fix is not a blanket refusal of legacy
cursors.

grpcdriver needs no change: it never calls EncodeCursor, forwarding the
opaque token, so it inherits the check from whichever backend the driver
wraps. Confirmed by the shared suite — all four new conformance cases pass
against it.

AC6.4 in the acceptance plan now states the session axis and names its four
verify tests, so the property is gated at the plan level rather than only in
code.

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

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

* fix(redisstore): re-verify the log basis per read cycle, after the read

A follower captured the generation once at attach and trusted it for the life
of the iterator, so a log deleted and recreated underneath it kept streaming —
from the REPLACEMENT log, with no error. The new conformance case fails on this
backend today with "handed record 'new basis' from the REPLACEMENT log": not a
hang, not a misclassified error, actual silent wrong data.

The check has to run AFTER the read, not before. A blocking XREAD straddles
time: Redis wakes a blocked client on an XADD to the key, and because stream IDs
are wall-clock derived a replacement log's first entry sorts after the
follower's position — so one reply legitimately carries a record from a log that
did not exist when the cycle began, and a pre-read check passes in exactly that
case. Verifying afterwards cannot be raced the same way: if the record came from
the replacement log, its basis was already stored when it was written.

logBasis carries the anchored/not-anchored distinction jsonlstore already needed
for the same reason. The EMPTY generation is a real value reported by both a
not-yet-created log and a legacy one, so a follower attaching before the first
append must ADOPT the generation that append mints rather than read it as a
reset. Without it every such follower gets a spurious expiry — which is what the
first version of this commit did to the concurrency conformance case.

The legacy LIST path had the same shape with a WORSE trigger. It re-read the
list each tick without re-checking the key type, so the migration — guaranteed
on the log's next append, i.e. during exactly the upgrade window this path
exists to serve — turned LRANGE into WRONGTYPE, reaching the consumer wrapped as
an infrastructure fault. "Your positions are now stream IDs, restart" and "Redis
is unwell, retry" call for opposite responses. It is the same WRONGTYPE that
broke the k8s e2e earlier in this stack: code holding a datatype assumption
across a migration.

Also, per review on #868: ReadOptions.Limit == 0 bounds the SEQUENCE, not the
FETCH. Passing the caller's zero through omitted XREAD COUNT entirely, so a
watcher on a long transcript had Redis materialise the whole log in one reply.
Capped internally at readPageSize with the loop paging past it; asserted at the
wire with a go-redis hook, because internal paging is invisible through
iter.Seq2 and therefore cannot be a conformance case.

And per review on #869, the lease is acquired per cycle and released BEFORE the
caller yields, so a follower parked for hours cannot pin a retired credential
generation open and a slow transport consumer holds no pooled connection. That
partially addresses the shutdown concern as a side effect — Store.Close no
longer waits out its grace with a client pinned — but NOT the whole of it: the
store still does not own its followers and cannot cancel an in-flight blocking
read. The test says so rather than implying otherwise by passing.

Every new test mutation-verified. The Close test was VACUOUS as first written —
it asserted a generous timeout, and Close returns within its 2s grace either
way, so it passed with the lease deliberately held; it now asserts the
"timed_out" shutdown diagnostic and fails on that mutation.

Costs, stated rather than hidden: a TYPE plus a GET per cycle, so an idle
follower issues three commands per followBlock rather than one. Not cacheable —
a cached basis is precisely the stale basis the check exists to catch.

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

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

* docs(acceptance): state the mid-follow basis re-verification under AC6.3

AC6.3 asserted that a cursor from a prior generation expires, which the existing
proof only established for a COLD attach. The finding on #869 was about a live
follower — already past the entry-point check, parked at the tail — so the AC as
written did not gate the case that was actually broken.

Extends the criterion rather than adding a new one: it is the same guarantee over
a wider set of states. Records the two non-obvious parts, both of which cost a
wrong first implementation: the check must run AFTER the read, because a blocking
XREAD straddles a delete/recreate, and the legacy path's trigger is the in-place
migration rather than a delete, which makes it the likelier of the two.

Both cited verify paths were run as -run targets, so the proofs are runnable
rather than plausible-looking names.

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.

3 participants