Skip to content

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

Merged
samuv merged 5 commits into
sdk/06a-cursor-event-logfrom
sdk/06b-cursor-redis-grpcdriver
Aug 31, 2026
Merged

samuv merged 5 commits into
sdk/06a-cursor-event-logfrom
sdk/06b-cursor-redis-grpcdriver

Conversation

@samuv

@samuv samuv commented Aug 31, 2026

Copy link
Copy Markdown
Contributor

What

Migrates the Redis event log LIST → Stream and adds the remaining two port.CursorEventLog backends. PR 6b of the #821 stack — targets sdk/06a, not main. Completes Scenario 6, and with it 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:

  • No blocking read — follow degenerates to LLEN polling per watcher.
  • No stable per-entry identity — a position can only be an index, stable today only because nothing is ever trimmed from the head. That also means the log grows without bound, and 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 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 in metadata_index.go. 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.

This is mutation-tested. Reverting just that Lua change makes a stale cursor return records with error = <nil> — the exact silent corruption generations exist to convert into a loud failure:

legacy_list_migration_test.go:184: the generation key survived Delete; a recreated log would inherit the old basis
legacy_list_migration_test.go:199: a cursor from the deleted log's basis error = <nil>, want ErrCursorExpired

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 failure a "leave the old path alone" migration produces.

Driver protocol

Additive: AppendGap, a server-streaming ReadAfter, and a cursor field on the previously-empty AppendResponse — so an older driver stays a valid EventLog.

Cursor rejections travel as a google.rpc.ErrorInfo reason (ADR 0248's carrier, already a direct dependency) 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 — this client satisfies the port by construction — and ADR 0250 requires such a backend be reported unsupported rather than silently degraded.

ADR 0250 gains the consequence its draft missed

The one an operator of Redis Streams at size would raise first: a blocking XREAD occupies a pooled connection, and redisstore sets no PoolSize (go-redis defaults to 10 × GOMAXPROCS). 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.

Worth noting for the record: #822 asked reviewers to push on the LIST→Stream call and got engagement on three other points but none on this one, so the decision shipped unchallenged. The ADR is merged and I treated it as frozen; this residual is the one thing I'd have most wanted that second opinion on.

Documentation the datatype change silently falsified

None of these would have been caught by any gate — all three are prose, not links, and go vet typechecks:

  • user-docs/.../mecak8s.md told operators to run redis-cli LRANGE mecatl:events:<id> 0 -1, which now fails with WRONGTYPE.
  • docs/design/MECAK8S-PLAN.md — both the port→operations table and the per-method breakdown still described RPUSH/LRANGE.
  • redisstore.go's own header comments still reasoned about LIST atomicity.

AGENTS.md's redisstore entry now records the Stream migration and the generation-key deletion invariant.

No ADR 0027 resource rows — deliberately

ADR 0250 says every watcher needs an inventory row. None exists yet: this PR ships the storage seam, and nothing in production calls Follow until WatchSessionEvents lands in Scenario 7, which is where those rows belong.

Verification

Run on this branch in isolation:

  • task test — exit 0, 175 packages, 0 failures (exit code captured to a file; an earlier run of mine was SIGTERMed and a | tail pipeline masked it as success, so this is checked directly now).
  • task lint — clean, after fixing 5 revive findings (four methods that never touched their receiver, now free functions).
  • task api:check — green; no engine/ change in this PR.
  • task docs:check — 272 documents, 2383 references, 0 broken.
  • buf generate — verified idempotent, reproducing contracts/gen byte-for-byte.
  • go run ./cmd/mecademo — full offline session.

miniredis v2.38.0 supports XADD/XRANGE/blocking XREAD and XADD '*' inside a Lua EVAL, so the migration script is atomic and offline conformance covers it — the risk ADR 0250 named does not exist.

One bug worth flagging for anyone touching this code: in go-redis, XReadArgs.Block == 0 means block forever; a negative value omits BLOCK. The non-blocking drain must pass the negative sentinel, and the constant is named noBlock with that comment for the next reader.

Refs #821.

🤖 Generated with Claude Code

@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 Redis LIST->Stream migration and grpcdriver addition, and cross-checked against #868's findings since this stacks directly on top of it. The migration script, gap handling, and stream-ID validation (rejecting a malformed cursor before ever calling XREAD) are solid. Two notes: one advisory on the connection-pool mitigation, one flagging that this PR inherits #868's open items.

@samuv
samuv force-pushed the sdk/06b-cursor-redis-grpcdriver branch from b18d32f to f057506 Compare August 31, 2026 12:52
@JAORMX

JAORMX commented Aug 31, 2026

Copy link
Copy Markdown
Contributor

I pulled the stack into worktrees and ran a small expert review focused on the XREAD BLOCK concern. Consensus: keep Redis Streams and blocking watch, but do not make watchers share capacity with Save/Append.

Recommended v0.1 shape:

  • one ordinary Redis client/pool for durability and metadata operations;
  • one store-owned, bounded follow client/pool per credential generation;
  • approximately one socket per actively blocked watcher, not a full redis.Client per watcher;
  • a configurable, fail-fast per-process watcher admission limit; return a resumable/resource-exhausted error rather than waiting for a pool timeout;
  • retain the bounded XREAD BLOCK interval;
  • always use an internal bounded COUNT (for example 256), even when public ReadOptions.Limit == 0;
  • release the pooled connection and credential-generation lease before yielding records to a potentially slow transport consumer.

That structurally prevents watcher load from starving writes. Increasing the shared pool alone only moves the contention threshold, and the current adapter does not expose pool controls anyway.

The review also found three lifecycle/correctness concerns in the current implementation:

  1. ReadAfter acquires st.clients once for the entire iterator (cursoreventlog.go:207-244). A long-lived follower therefore pins an obsolete credential generation, while clientGenerations cannot retire it until the reference reaches zero (generation.go:42-68, 84-111). Acquisition should happen per bounded read cycle, with the response copied/decoded and the generation released before yield.
  2. Store.Close does not own/cancel active followers; generation shutdown deliberately leaves clients with live leases open (generation.go:120-155). A follow pool should have store-lifetime cancellation and bounded join/force-close semantics. Force-closing the isolated follow pool is safe because writes use another client.
  3. The durable log generation is checked only before entering the follow loop (cursoreventlog.go:216-243). Delete/recreate during a live follow can apply the old stream position to the replacement stream. Revalidate generation on every wake/batch and return ErrCursorExpired before yielding replacement-log records.

For later scale, collapse multiple local watchers behind per-session hubs, then shard sessions across multi-stream XREAD. Pub/Sub can optionally be a lossy wake-up hint followed by draining the durable Stream; it should never carry authoritative events. Consumer groups are not suitable because every watcher needs the full event stream.

So I would keep the LIST→Stream migration and XREAD approach, but change the resource boundary from “shared pool plus operator sizing” to “isolated bounded follow capacity.”

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
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 force-pushed the sdk/06b-cursor-redis-grpcdriver branch from f057506 to 6403413 Compare August 31, 2026 13:47
samuv added a commit that referenced this pull request Aug 31, 2026
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]>
@samuv

samuv commented Aug 31, 2026

Copy link
Copy Markdown
Contributor Author

Thanks — I verified all three lifecycle findings against the code rather than taking the line references on trust, and all three hold. Finding 3 turned out to be a live bug, and worse than described. Fixed in 6403413c; the deferred capacity work is now #876.

Finding 3 — basis checked only before the follow loop. Confirmed, and it was silent wrong data, not a latent risk. The new conformance case fails on the pre-fix backend with:

a follower whose log was reset was handed record "new basis" from the REPLACEMENT log
instead of ErrCursorExpired — this is the silent-wrong-data case generations exist to prevent

Two things you didn't hit that came out of fixing it.

The check has to run AFTER the read, not before. My first attempt did exactly what you suggested — revalidate per cycle, before the XREAD — and it still handed over the replacement record. 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 didn't exist when the cycle began, and the pre-read check passes in precisely that case. Verifying afterwards can't be raced the same way — if the record came from the replacement log, its basis was already stored when it was written.

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 in-place migration — guaranteed on the log's next append, i.e. during exactly the upgrade window that 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. Now ErrCursorExpired, with its own regression test since the shared suite necessarily runs over Streams.

One trap worth flagging for #876: 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. Getting this wrong gave every such follower a spurious expiry — it broke the concurrency conformance case in my first pass. jsonlstore already carried the distinction; redisstore now has the matching logBasis.

Finding 1 — whole-iterator acquire. Confirmed: defer release() spanned the iterator, and retireAndClaimCloseLocked returns nil while refs != 0, so a long-lived follower pinned a retired generation indefinitely. Now acquired per cycle and released before yielding, so a slow transport consumer holds no pooled connection either. It wants the same cycle boundary as finding 3, so they landed as one change.

Finding 2 — Store.Close doesn't own followers. Confirmed, and only partly addressed. The per-cycle lease removes the leak: Close no longer waits out its grace with a client pinned, which TestCloseDoesNotWaitOnAParkedFollower asserts via the shutdown diagnostic. But the store still doesn't own its followers, can't cancel an in-flight blocking read, and can't join them — that's in #876, and stated in the test's doc comment so a passing test doesn't imply more than it proves.

Worth admitting: that test was vacuous as I first wrote it. It asserted a generous wall-clock timeout, and Close returns within its 2s grace either way, so it passed with the lease deliberately held. Only mutating the code exposed it.

XREAD COUNT omitted when Limit == 0. Correct, fixed with an internal cap of 256 and the loop paging past it. One amendment to your suggestion: this can't be a conformance case. Internal paging is invisible through iter.Seq2 — identical records come out either way — so it's asserted at the wire with a go-redis hook instead, plus a crossing-a-page-boundary test for the truncation risk a cap introduces. The port now documents Limit == 0 as bounding the sequence, not the fetch.

Early-exit resource release is the one item I haven't covered and haven't filed: worth doing, but it lands naturally with #876's store-owned lifecycle rather than before it. Say if you'd rather see it tracked separately.

Every new test is mutation-verified — including the negative case where removing the session check reproduces the original [B-three B-four] err=<nil>.

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 force-pushed the sdk/06b-cursor-redis-grpcdriver branch from daa6e1f to 07b6edc Compare August 31, 2026 14:18
samuv added a commit that referenced this pull request Aug 31, 2026
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]>
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
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 force-pushed the sdk/06b-cursor-redis-grpcdriver branch from 07b6edc to 3c7a05f Compare August 31, 2026 15:44
samuv added a commit that referenced this pull request Aug 31, 2026
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]>
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
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
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]>
@samuv
samuv force-pushed the sdk/06b-cursor-redis-grpcdriver branch from 3c7a05f to 4b142bc Compare August 31, 2026 17:38

@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 at 4b142bce4 and verified the fixes in the code rather than taking the replies at face value.

Sequencing note — resolved as asked. Both of #868's blocking findings landed there before this, and I've approved #868. Your read on redisstore was right: it had the session-scoping and single-write-path halves correct individually, so the change here was small. The redisstore-specific legacy-LIST regression test is the right addition — the shared suite's cross-session case runs over Stream logs, and the legacy LIST is where the bug was actually live.

Pool contention — agree with deferring, and #876 is the right outcome. A dedicated follow pool on top of a datatype migration is a config change with its own failure modes; better as its own PR. The issue captures the shape well, and recording why consumer groups don't fit is the part that stops this being re-litigated in six months.

What you found while restructuring the follower loop is the more valuable half of this PR. A follower capturing the generation once at attach and streaming a replacement log's records is silent wrong data, and the argument for why the check must run after the read rather than before it — a blocking XREAD straddles time, so a pre-read check passes in exactly the racing case — is correct and not obvious. The readPageSize cap with a wire-level assertion via a go-redis hook is the right call too, given internal paging can't be a conformance case. And noting that the Close test was vacuous as first written, rather than quietly fixing it, is appreciated.

One nit, non-blocking and no need to hold the merge: ADR 0250 still reads "a bound the operator can already set" at the point where the deferral is argued. You identified that clause as false in the thread — redisstore exposes no pool controls — and the pushback recorded immediately after does correct it in context, but the sentence still states it as if it stood. Worth a few words when something else takes you into that file.

CI is green and this is mergeable. Merge after #868 lands.

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]>
samuv added 4 commits August 31, 2026 22:20
…tity 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]>
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]>
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]>
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]>
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/06b-cursor-redis-grpcdriver branch from 4b142bc to 5b3120a Compare August 31, 2026 20:30
@samuv
samuv merged commit bd1fb4a into main Aug 31, 2026
23 checks passed
@samuv
samuv deleted the sdk/06b-cursor-redis-grpcdriver branch August 31, 2026 20:44
samuv added a commit that referenced this pull request Aug 31, 2026
…wo backends (#868)

* feat(engine,store): port.CursorEventLog, its conformance suite, and two 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]>

* fix(port): scope event-log cursors to the session, not only the generation

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]>

* fix(port,conformance): force every backend to re-verify the log basis 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]>

* test(conformance): establish the live-boundary precondition instead of 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]>

---------

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