Skip to content

feat(control-plane, mocactl): an owner-scoped event stream, and watch follows it (#392) - #963

Merged
cwiklik merged 6 commits into
rossoctl:mainfrom
cwiklik:feat/392-events
Nov 20, 2026
Merged

cwiklik merged 6 commits into
rossoctl:mainfrom
cwiklik:feat/392-events

Conversation

@cwiklik

@cwiklik cwiklik commented Nov 20, 2026

Copy link
Copy Markdown
Contributor

Closes #392 (B6 of epic #378).

An owner-scoped SSE stream of turn state changes, resumable by cursor, and mocactl watch
switched over to it from its 5-second poll.

What it does

GET /v1/events?since=<cursor> streams the calling subject's own turn transitions. Each turn
frame carries the session, the turn, the new state, the reason and the gate summary; its id is
the cursor to resume from. A client that reconnects with its last cursor is served every
transition after it, exclusively — no replay of the one it already has, no hole.

mocactl watch opens the stream once and prints a line per reported change, keeping #381's
command surface (--tag, --json, exit 130 on Ctrl-C) and adding --since C for the hook.
Every --json line now carries cursor, which is what the hook stores.

How

One emit seam. Every turn transition already funnels through TurnStore
(create / markRunning / toTerminal), each gated by a CAS Lua script. That script now
returns the previous state, so "did this call actually move the turn?" is decidable inside the
store — the event is emitted only by the CAS winner. A redelivery that rewrites running over
running emits nothing, which is what makes "exactly one line per transition" a property rather
than a hope.

Owner-scoped by construction. The log is a Redis stream at
sh:cp:owner:<subjectHash(principal.sub)>:events. Isolation is structural: the key derives from
the authenticated subject, so there is no filter to get wrong and no cross-subject read to
forbid. The cursor is the XADD id.

Retention consistent with #390. XADD MAXLEN ~ 500 plus
EXPIRE = resultTtlSeconds + ttlMarginSeconds — the same window the turn records themselves
live in, so a cursor cannot outlive the turns it points at. When the requested cursor has already
been trimmed, the stream opens with a gap frame naming the oldest id it still has; watch
writes a note to stderr and carries on from there rather than silently resuming short.

Backpressure needed no new code. The control plane's writeStream already pulls an
AsyncIterable<string> body one frame at a time, so a slow consumer stalls the generator instead
of growing a buffer. The 15-second keepalive comment frame is also how a departed client is
detected; SseParser ignores comment frames, so the client never sees them.

The 60 s sweep is kept as a safety net, not as the mechanism: it covers a sync row (a local
child with no turn record, which emits no events), a deployment whose stream route is missing, and
the one-hour stream cap. A stream-reported state and a sweep-read state dedup through one map, so
the fallback cannot double-print.

Acceptance criteria → tests

Criterion Where
A client that reconnects with its cursor misses no transitions control-plane/test/turn-events.test.ts and the real-Redis half in test/turn-store-redis.test.ts — exclusive XRANGE (cursor, asserted against both backings
Another subject's events are never visible turn-events.test.ts, two subjects, both directions
watch --json emits exactly one line per transition mocactl/test/subagent-watch-events.test.ts — one line per reported change, no second line when the sweep re-reads a state the stream already reported, another session's and another turn's events ignored
Resume from a stored cursor same file: --since opens the stream at the given cursor
Degradation same file: the route 404s → falls back to sweeping; a trimmed cursor → the gap note, then recovery; Ctrl-C with the stream open → 130

queued and running are both honestly running on the existing status path, so a stream
queued event collapses into the baseline sweep's own running line. A finer queued line here
would differ from the line the sweep prints for the same unchanged turn — a spurious transition,
not information.

Verification

  • control-plane: 2039 passed, including turn-store-redis.test.ts (30) against real Redis — the
    half that can disagree with the fake about MAXLEN ~ and EXPIRE.
  • mocactl: 2189 passed.
  • make typecheck, make check-links clean. make lint clean except the Dockerfile hook, which
    needs a Docker daemon.
  • Contract: OpenAPI 1.34.0 adds TurnEvent and /v1/events; the route table test, the
    openapi-contract test (state enum + cursor shape) and mocactl's own client-coverage contract test
    all pin it.

Deliberately not verified

  • The compose end-to-end — no Docker daemon on the machine this was built on. The live wire
    path (the first running line arriving well under 60 s, the gap note on real bytes, a sync row's
    fallback) is proven only by unit tests with injected clocks.
  • Backpressure under a genuinely slow consumer. The pull-per-frame property is the router's,
    already relied on elsewhere; no new test holds a socket open and refuses to read.
  • The one-hour stream cap and watch's reopen-with-cursor branch — unit-tested with an
    injected clock, never over a real hour. A long-lived watch is the least-proven path here.
  • Retention expiry on the wire. The EXPIRE value is asserted; a cursor going stale by the
    clock running out is not.
  • A deployment without SH_ASYNC_DRAIN. Turns stay queued and emit a queued event only;
    that is the documented precondition, not a behaviour to assert.

Not in scope

Session-level events (session created/deleted) — #392 is turn transitions, and nothing consumes a
session event yet.

Assisted-By: Claude Code

…/events

An owner-scoped SSE stream of turn state changes, resumable by cursor (rossoctl#392).
The handler reads the caller's own event log -- the key derives from
principal.sub, so there is no path id to own and no filter to get wrong -- and
frames one `event: turn` per transition with its cursor as the SSE id.

Without `since` the stream starts from now. With a cursor it resumes
exclusively after it, so a reconnect repeats nothing; a cursor older than the
oldest retained entry gets one `event: gap` first, because the log is trimmed
to the record retention and the client has to know it lost ground. An idle
stream is kept alive with a comment frame once per heartbeat window, which is
also how the router notices a departed client.

Backpressure is the router's existing `writeStream`: the body is an
AsyncIterable pulled one frame at a time.

API 1.34.0.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: cwiklik <[email protected]>
`watch` follows GET /v1/events and prints one line per transition, so a turn
that starts and finishes between two reads still produces its `running` line.
A 60 s read (was 5 s) is left as the safety net for three cases the stream
cannot cover: a synchronous row, which has no turn and therefore no events; a
deployment whose control plane has no /v1/events; and an emit the server lost.
Both sources go through one dedup, so a transition seen by both is one line.

`--since` resumes after a cursor, and each --json line carries the cursor it
came from (null on a line from the read), which is what a reattach hook
stores. Part of rossoctl#392.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: cwiklik <[email protected]>
The how-to still described the poll `watch` had before rossoctl#392.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: cwiklik <[email protected]>
@cwiklik
cwiklik requested a review from pdettori as a code owner November 20, 2026 17:04
@pdettori pdettori added the ready-for-ai-review Request automated AI code review from clawgenti label Nov 20, 2026

@ingpaolodettori-dev ingpaolodettori-dev left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Review: an owner-scoped event stream, and watch follows it

GET /v1/events streams the caller's own turn transitions as SSE, resumable by cursor, and mocactl watch moves onto it with the 60 s sweep kept as a safety net. The plumbing is sound: one emit seam (create / markRunning / toTerminal), the CAS winner is the only emitter (the Lua's prev), the log key derives from subjectHash(principal.sub) so isolation is structural, writeStream already gives backpressure by pulling the generator one frame at a time, and the route is auth: 'api' + sessionScoped: false with requirePrincipal first. (cursor exclusive XRANGE, CURSOR_RE at the route, readSse, the 15 s keepalive and the hour cap all check out.

Two must-fixes, both about the event's content rather than its transport:

  1. reason and gate never reach an event. finalize's new detail parameter has no production caller: async-worker.ts:433, turn-claim.ts:212 and turn-handlers.ts:251 all pass three arguments, and only turn-store-contract.ts:152 passes four. So TurnEvent.reason / .gate are always absent on the wire, viewFromTurnEvent's gate branch is unreachable, and the CHANGELOG ("the terminal reason or the gate when there is one") and the PR body ("carries ... the reason and the gate summary") describe fields that are never written. The user-visible half is in mocactl watch: a failed turn's terminal line loses its reason, which main's poll did print.
  2. A cursor whose whole window expired is resumed silently. gap needs a non-empty oldest, so when the owner's stream key is gone a reconnect with since=<old cursor> gets no gap frame and then new events from a later id — the hole the frame exists to announce. That is the common long-gap case: EXPIRE is resultTtl + margin and is re-armed only on append. The CHANGELOG and the PR body promise "no hole"; your own "Deliberately not verified" names this exact path.

Plus one nit on the latency wording, and four non-blocking notes below.


Non-blocking notes

  • docs/reference/change-policy.md:25 — every earlier bump added its clause to the enumerated "..., then ..., added to it" sentence; this one moves to 1.34.0 and leaves the new route out of the list.
  • Session delete. deleteSessionTurns DELs the records and results, but the owner's event entries for those turns survive until EXPIRE/MAXLEN. If "retention consistent with #390" is meant to cover a delete, that is the gap; otherwise a sentence in the CHANGELOG settles it.
  • A lost EXPIRE. xAdd and expire are both inside the swallowed try, so an append that succeeds before a failed expire leaves a key with no TTL — bounded at 500 entries, but immortal, which the retention text does not allow. A MULTI/pipeline would make the pair atomic.
  • Cursor advance. cursor only moves over events whose session this watch holds, so a watch --tag on a subject that also runs other work replays up to 500 foreign events on each hourly reconnect. Harmless (they are skipped), but advancing the cursor on skipped events too would stop it.

Verification

  • Every production hunk read; the CAS table (s is non-nil on that path, so the array cannot truncate), the fake's inIdRange, the exclusive range, and the three readers all agree.
  • CI 17/17 green at 24fff49; branch merges cleanly into main (a159c4c). 4 commits, all Signed-off-by.
  • No .claude/ or .vscode/ changes, so no §4.4 inspection gate applies. No prompt-injection attempts found in the diff or the PR text.
  • I did not run the suites (pnpm is not installed in this sandbox); the two must-fixes are read from the code, not from a failing test.

now: number,
/** The leaf's own reason and gate, carried onto the event so a client needs no follow-up read
* (#392). Absent where the caller has no result in hand (the reaper's `lost`). */
detail?: { reason?: string; gate?: string },

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

must-fix — detail has no production caller, so reason/gate never reach an event.

finalize is called with three arguments everywhere it matters: packages/server/src/async-worker.ts:433, packages/server/src/turn-claim.ts:212, packages/control-plane/src/turn-handlers.ts:251. The only four-argument call is test/helpers/turn-store-contract.ts:152, which is why the suite is green while the field is always absent on the wire.

What that costs a client:

  • A failed turn's event carries state: 'failed' and nothing else, so viewFromTurnEvent (packages/mocactl/src/transport/async-turn.ts:135-138) renders it through terminalFromBody({status:'failed'}) with detail: undefined → mocactl watch --json prints "state":"failed","detail":null.
  • The stream then persists that in the ledger (subagent.ts:727), and the 60 s sweep treats the ledger as authoritative past terminal (subagent.ts:809), so the result's reason is never read. On main the poll printed failed workload_sandbox_unavailable; after this PR it prints failed. That is the one line a background monitor exists to surface.
  • if (e.gate) at async-turn.ts:134 is unreachable, and the CHANGELOG / OpenAPI / PR body all advertise the two fields.

Fix at the worker: LeafJobDeps.finalize (harness/src/leaf-job-runner.ts:79) currently carries only LeafResult['status'], but the call site has the whole LeafResult in hand — widen it to (turnId, status, detail?) and pass {reason: result.reason, gate: result.gate}. If that is meant for a follow-up, drop reason/gate from TurnEvent, the CHANGELOG and the PR body for now. Either way the test should drive a real worker finalize (or at least a finalize with a detail) rather than the store API alone, so this cannot regress silently again.

const from = since ?? (await turns.lastEventId(owner));
const oldest = await turns.firstEventId(owner);
// Retention moved past the client's cursor: say so rather than imply continuity it lost.
const gap = Boolean(since && oldest && compareCursor(since, oldest) < 0);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

must-fix — a cursor whose whole window expired is resumed with no gap.

oldest is '' when the owner's stream key does not exist (firstEventId, turn-store.ts:707-712), and this line needs it truthy. So a client that reconnects with since=<old cursor> after the key expired gets no gap frame, sits on an empty stream, and then receives new events from a later id — a silent hole, which is exactly what the frame is for.

That is not an exotic case: EXPIRE is resultTtlSeconds + ttlMarginSeconds (7 days by default) and is re-armed only by an append, so an owner idle for the window loses the whole log rather than its head — the most likely way for a resuming client to be discontinuous. The contract says the opposite (CHANGELOG 1.34.0: "Events are retained as long as a turn record ... A client whose cursor fell out of that window is told so by a gap frame"; PR body: "no replay of the one it already has, no hole"), and your "Deliberately not verified" section names this path as untested.

A since with nothing retained cannot be continuous:

const gap = Boolean(since && (!oldest || compareCursor(since, oldest) < 0));

and a test with an empty stream plus a cursor pins it — today the only gap case covered is a trimmed head with entries still present (turn-events.test.ts, "sends one gap frame when the cursor is older than the oldest retained event").

Comment thread docs/harness/reference/cli-mocactl.md Outdated
is meant to run as a background monitor rather than as an interactive wait. The ledger is re-read
each tick, so a `spawn --tag T` from another terminal joins a running `watch --tag T` — spawn
when its state or detail changes. It follows the owner-scoped event stream
`GET /v1/events` (#392), so a transition appears within milliseconds instead of at the next poll,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

nit — "within milliseconds" is an order of magnitude out. The stream is an XRANGE poll with EVENT_IDLE_MS = 1_000 (turn-handlers.ts:107); an event surfaces within about a second, or immediately if it lands while a backlog is being drained. The same wording is at docs/harness/how-to/use-mocactl.md:151. "within a second instead of at the next poll" is the honest version.

The async worker's finalize dep took `detail` but `processOne` never passed
it, so a `watch`ing client saw a bare `failed` with no reason and a `paused`
with no gate summary -- the one line a background monitor exists to surface.

The derivation now lives in `processOne`, the only place holding the whole
`LeafResult`, and the drain's integration test asserts the forwarding over
real Redis end to end (two leaves through `processOne`, then `readEvents`)
rather than through the store API alone, which is what let the gap hide: the
one-line dep was duplicated in the test fixture and in production wiring.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: cwiklik <[email protected]>
The gap check compared `since` against the oldest retained id only when the
log was non-empty, so the worst case -- every event the client was resuming
past has aged out, leaving nothing -- was the one case that reported no gap.

`since=0-0` stays exempt: it is "everything retained", the one cursor shape
the service never issues, so its holder is not resuming from a position it
was given and cannot have lost one. Exported as `FROM_START` rather than
spelled out at each use.

Also from the review: `watch` advances its cursor over events it filters
out, so a reopen no longer replays the subject's foreign rows, and the
reopened stream keeps its `onGap` handler. The xAdd/EXPIRE non-atomicity is
documented as a `shortcut:` -- bounded at EVENTS_MAXLEN entries, re-armed by
the owner's next transition -- rather than growing `CpRedisLike` a MULTI
nothing else needs.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: cwiklik <[email protected]>
@cwiklik

cwiklik commented Nov 20, 2026

Copy link
Copy Markdown
Contributor Author

Both must-fixes are in, pushed as f490ba6 and a01948f.

1. detail dropped between processOne and finalize — fixed. The derivation now lives in processOne (harness/src/leaf-job-runner.ts), the only call site holding the whole LeafResult: failed → {reason}, paused → {gate: gate.summary}, otherwise undefined. The other two finalize call sites (the pre-run cancel, and the reaper's lost in turn-claim.ts) have no result to derive from and were left alone.

You were right that the store-API test wasn't the test to add. The root cause was that the one-line finalize dep is written twice — once in packages/server/src/async-worker.ts and once in the drain's test fixture — so a dropped third argument was invisible from either side. So the new coverage is at both levels:

  • harness/test/leaf-job-runner.test.ts — a table test over the three LeafResult shapes, asserting what processOne hands finalize.
  • packages/server/test/async-drain.integration.test.ts — "carries a failed leaf's reason and a gate's summary onto the owner's event": two leaves through the real processOne against real Redis, then turns.readEvents(owner, '0-0', 50) must contain {reason:'bad_inputs'} and {gate:'writes outside the workspace'}. That's the end-to-end path a watching client actually reads.

2. Empty log never reported a gap — fixed, with one deliberate deviation from your one-liner. The condition is now:

const gap = Boolean(since && since !== FROM_START && (!oldest || compareCursor(since, oldest) < 0));

The literal version broke three existing tests, and the reason is worth keeping: '0-0' is "everything retained", and it's the one cursor shape the service never issues. A client sending it is not resuming from a position it was given, so it cannot have lost one — the gap frame answers "did my cursor fall out of the window", which a 0-0 caller hasn't asked. It's exported as FROM_START from turn-record.ts rather than spelled out at the use site, and documented in the OpenAPI since description and the CHANGELOG. One existing expectation (bob's '0-0' case) was updated to match; new test: "sends the gap frame when NOTHING is retained, not just when the head was trimmed".

The trimmed-head test also had a latent bug your review surfaced indirectly — it derived its cursor as ${oldest-1}-0, which computes to '0-0' against a fake that mints 1-0, 2-0, …. Now a literal '0-1' plus an explicit compareCursor(trimmed, oldest) < 0 assertion.

Nit — "within milliseconds" → "within about a second" in both cli-mocactl.md and use-mocactl.md, since EVENT_IDLE_MS is 1 s.

Non-blocking notes:

  • (a) change-policy enumeration — fixed.
  • (b) session-delete retention — the events key outlives a deleted session's record by design (it's owner-scoped, resultTtlSeconds + ttlMarginSeconds). Documented in the CHANGELOG rather than changed; a delete that also trimmed the log would strip other sessions' events from the same owner.
  • (c) xAdd/EXPIRE not atomic — documented as a shortcut: in turn-store.ts. An append that lands before a failed EXPIRE leaves the key with no TTL: bounded at EVENTS_MAXLEN entries and re-armed by the owner's next transition. Growing CpRedisLike and its fake a MULTI for the one pair that wants it didn't seem worth it — the comment says when to upgrade.
  • (d) cursor not advanced over filtered events — fixed, and it was a real bug: a reopen would replay up to the whole log of this subject's foreign rows. The cursor now advances for every event, before the byId filter. Test: "advances the cursor over skipped events, so a reopen replays none of them". Writing it also turned up that the reopened stream had lost its onGap handler (an async generator's body doesn't run until the first next(), which is why the first version of the test saw nothing) — both now come from one open() helper.

Suites after the fixes: control-plane 2040 passed / 4 skipped, server 609 passed, mocactl 2187 passed, harness 997 passed. make typecheck and make check-links clean. The compose end-to-end is still unverified — no Docker daemon here — as noted in the PR body.

Assisted-By: Claude Code

@cwiklik

cwiklik commented Nov 20, 2026

Copy link
Copy Markdown
Contributor Author

@ingpaolodettori-dev ready for re-review — both must-fixes and the nit are in (f490ba6, a01948f), the four non-blocking notes are answered in the comment above, and CI is 18/18 green on a01948f.

One thing worth your eye specifically: I did not take the literal one-line gap fix. since=0-0 is exempt, on the reasoning that the gap frame answers "did the cursor I was issued fall out of the window" and a 0-0 caller was never issued one. Details in the comment above; if you disagree, the exemption is one condition to drop.

Assisted-By: Claude Code

@ingpaolodettori-dev ingpaolodettori-dev left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Review: both must-fixes from the last review are closed

Re-review at a01948f, two commits (f490ba6, a01948f) and +215/−43 over 15 files since 24fff49. No inline comments: this records that the two blocking items and the three body notes are addressed, and nothing new needs a line of its own.

1. reason/gate now reach the wire

finalizeDetail(result) derives {reason} for failed and {gate: result.gate.summary} for paused from the LeafResult inside processOne (leaf-job-runner.ts:305-317) and hands it to deps.finalize (leaf-job-runner.ts:442). The one production wiring forwards it — armAsyncLeafWorker → turns.finalize(turnId, state, now, detail) (async-worker.ts:434-436) — and toTerminal puts it on the emitted event (turn-store.ts:690-698). I checked that no other wiring exists, and that the two remaining finalize call sites really have no result in hand (the reaper's lost, turn-claim.ts:212; the pre-run failed, turn-handlers.ts:252), which is what the new comment claims. viewFromTurnEvent's gate branch is reachable now, and watch gets the failure line back.

The new integration test pins this over the production wiring rather than the store API, which is the property that would have caught the original gap — a dep that drops the argument fails it.

2. The gap frame covers a lost whole log

gap is now since && since !== FROM_START && (!oldest || compareCursor(since, oldest) < 0) (turn-handlers.ts:403-410). An owner whose stream key expired — EXPIRE is re-armed only by an append, so this is the common long-gap case, not a corner — is told instead of resuming silently from a cursor the server can no longer place. FROM_START = '0-0' is exempt and genuinely never issued: XADD ids are <ms>-<seq> with ms > 0, and readEvents still opens with (0-0, which Redis serves as the whole stream. The new test covers both directions of the empty-log case (a 5-0 resumption gets the frame; no since on an empty log does not), and the older gap test now asserts its cursor precedes the oldest id rather than assuming a minting detail. CHANGELOG, both OpenAPI spots (the description and the since parameter) and the TurnEvent doc agree with the code.

Body notes from the last review

  • change-policy.md now closes the enumerated list with "then the owner-scoped event stream".
  • Session delete is stated in the CHANGELOG: events age out with the subject's log and may name a session that 404s.
  • Lost EXPIRE is recorded as a shortcut: comment beside the swallow (turn-store.ts:600-606), naming MULTI for when CpRedisLike grows one.
  • Cursor advance is fixed where it belongs: cursor = got.value.cursor now runs before the session/turn filter, so a watch --tag on a busy subject no longer replays foreign events on every hourly reopen — with a test that pins the reopen's since.
  • The onGap note moved into the shared open() closure, so a reopen (where a gap is likeliest) prints it too, and "within milliseconds" became "within about a second", which matches EVENT_IDLE_MS = 1_000.

Non-blocking

  • The PR body's "How" section still says "switched over to it from its 5-second poll" and describes gap only for a trimmed cursor. The sweep is 60 s (WATCH_SWEEP_MS), and gap now covers a lost whole log plus the 0-0 exemption — one sentence would keep the body in step with the CHANGELOG.
  • The branch is 16 behind main and still merges cleanly; control-plane 1.34.0 is free on main (1.33.0), so no version collision at this head.

@cwiklik
cwiklik merged commit 96168a9 into rossoctl:main Nov 20, 2026
18 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready-for-ai-review Request automated AI code review from clawgenti

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Coding-agent subagents B6: owner-scoped event stream of session and turn state

3 participants