Repository navigation
feat(control-plane, mocactl): an owner-scoped event stream, and watch follows it (#392) - #963
Conversation
Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
…/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]>
ingpaolodettori-dev
left a comment
There was a problem hiding this comment.
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:
reasonandgatenever reach an event.finalize's newdetailparameter has no production caller:async-worker.ts:433,turn-claim.ts:212andturn-handlers.ts:251all pass three arguments, and onlyturn-store-contract.ts:152passes four. SoTurnEvent.reason/.gateare always absent on the wire,viewFromTurnEvent'sgatebranch 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 inmocactl watch: a failed turn's terminal line loses its reason, which main's poll did print.- A cursor whose whole window expired is resumed silently.
gapneeds a non-emptyoldest, so when the owner's stream key is gone a reconnect withsince=<old cursor>gets nogapframe and then new events from a later id — the hole the frame exists to announce. That is the common long-gap case:EXPIREisresultTtl + marginand 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.
deleteSessionTurnsDELs the records and results, but the owner's event entries for those turns survive untilEXPIRE/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.xAddandexpireare both inside the swallowedtry, so an append that succeeds before a failedexpireleaves 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.
cursoronly moves over events whose session thiswatchholds, so awatch --tagon 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 (
sis non-nil on that path, so the array cannot truncate), the fake'sinIdRange, 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 (
pnpmis 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 }, |
There was a problem hiding this comment.
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, soviewFromTurnEvent(packages/mocactl/src/transport/async-turn.ts:135-138) renders it throughterminalFromBody({status:'failed'})withdetail: undefined→mocactl watch --jsonprints"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'sreasonis never read. On main the poll printedfailed workload_sandbox_unavailable; after this PR it printsfailed. 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); |
There was a problem hiding this comment.
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").
| 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, |
There was a problem hiding this comment.
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]>
|
Both must-fixes are in, pushed as f490ba6 and a01948f. 1. 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
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: The trimmed-head test also had a latent bug your review surfaced indirectly — it derived its cursor as Nit — "within milliseconds" → "within about a second" in both Non-blocking notes:
Suites after the fixes: control-plane 2040 passed / 4 skipped, server 609 passed, mocactl 2187 passed, harness 997 passed. Assisted-By: Claude Code |
|
@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. Assisted-By: Claude Code |
ingpaolodettori-dev
left a comment
There was a problem hiding this comment.
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
EXPIREis recorded as ashortcut:comment beside the swallow (turn-store.ts:600-606), naming MULTI for whenCpRedisLikegrows one. - Cursor advance is fixed where it belongs:
cursor = got.value.cursornow runs before the session/turn filter, so awatch --tagon a busy subject no longer replays foreign events on every hourly reopen — with a test that pins the reopen'ssince. - The
onGapnote moved into the sharedopen()closure, so a reopen (where a gap is likeliest) prints it too, and "within milliseconds" became "within about a second", which matchesEVENT_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
gaponly for a trimmed cursor. The sweep is 60 s (WATCH_SWEEP_MS), andgapnow covers a lost whole log plus the0-0exemption — one sentence would keep the body in step with the CHANGELOG. - The branch is 16 behind
mainand still merges cleanly; control-plane 1.34.0 is free onmain(1.33.0), so no version collision at this head.
Closes #392 (B6 of epic #378).
An owner-scoped SSE stream of turn state changes, resumable by cursor, and
mocactl watchswitched over to it from its 5-second poll.
What it does
GET /v1/events?since=<cursor>streams the calling subject's own turn transitions. Eachturnframe carries the session, the turn, the new state, the reason and the gate summary; its
idisthe 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 watchopens the stream once and prints a line per reported change, keeping #381'scommand surface (
--tag,--json, exit 130 on Ctrl-C) and adding--since Cfor the hook.Every
--jsonline now carriescursor, 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 nowreturns 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
runningoverrunningemits nothing, which is what makes "exactly one line per transition" a property ratherthan 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 fromthe 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 ~ 500plusEXPIRE = resultTtlSeconds + ttlMarginSeconds— the same window the turn records themselveslive in, so a cursor cannot outlive the turns it points at. When the requested cursor has already
been trimmed, the stream opens with a
gapframe naming the oldest id it still has;watchwrites a note to stderr and carries on from there rather than silently resuming short.
Backpressure needed no new code. The control plane's
writeStreamalready pulls anAsyncIterable<string>body one frame at a time, so a slow consumer stalls the generator insteadof growing a buffer. The 15-second keepalive comment frame is also how a departed client is
detected;
SseParserignores 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
control-plane/test/turn-events.test.tsand the real-Redis half intest/turn-store-redis.test.ts— exclusiveXRANGE (cursor, asserted against both backingsturn-events.test.ts, two subjects, both directionswatch --jsonemits exactly one line per transitionmocactl/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--sinceopens the stream at the given cursorqueuedandrunningare both honestlyrunningon the existing status path, so a streamqueuedevent collapses into the baseline sweep's ownrunningline. A finerqueuedline herewould differ from the line the sweep prints for the same unchanged turn — a spurious transition,
not information.
Verification
control-plane: 2039 passed, includingturn-store-redis.test.ts(30) against real Redis — thehalf that can disagree with the fake about
MAXLEN ~andEXPIRE.mocactl: 2189 passed.make typecheck,make check-linksclean.make lintclean except the Dockerfile hook, whichneeds a Docker daemon.
TurnEventand/v1/events; the route table test, theopenapi-contract test (state enum + cursor shape) and mocactl's own client-coverage contract test
all pin it.
Deliberately not verified
path (the first
runningline arriving well under 60 s, the gap note on real bytes, a sync row'sfallback) is proven only by unit tests with injected clocks.
already relied on elsewhere; no new test holds a socket open and refuses to read.
watch's reopen-with-cursor branch — unit-tested with aninjected clock, never over a real hour. A long-lived
watchis the least-proven path here.EXPIREvalue is asserted; a cursor going stale by theclock running out is not.
SH_ASYNC_DRAIN. Turns stay queued and emit aqueuedevent 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