oficina / equipo Public

Turn batching: batches fit one frame; a failed frame lets runners retry

Astra round 1 (gpt-6-astra, high) asked for changes. It found two
mechanical defects, fixed here, and one product question, left open.

- One frame each: a runner reads at most 256 KiB and refuses a larger
  frame on every resend. A message joins the newest waiting batch only
  while that batch's own part (its words twice, escaped, and its files)
  fits batchRoom; otherwise it starts the next batch, which goes after
  it, in order. dispatch drops the oldest tail messages until the
  command fits (fitTail), and the tail never holds a batch still
  waiting.
- A store error applying a runner frame closed with CloseRevoked, so a
  real runner stopped as if revoked. Now it closes with 1011: the
  runner reconnects and resends the frame. ErrForbidden keeps
  CloseRevoked; a revoked credential is still refused at the handshake
  (403). Old runners reconnect on any other close code.
- Contracts: TestBatchSplitsToFitTheFrame, and headless
  TestHeadlessBatchAfterRefusedReply with the real runner.
- Open: the rules say each waiting message shows the queued marker. The
  branch keeps thinking-stale's one note under the latest.
- Progress note with every mutation and the spend figures:
  docs/superpowers/plans/TURNBATCH-PROGRESS.md.
- Budgets: internal/equipo/chat 14100, internal/headless tests 8520,
  internal/thintest tests 13400.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 209327c85f11a0e2c8c11ea933eb08ab30e69d2a parent fd22d42
7 files changed, +310 −11
  • .rastrillo/budgets.txt +3 −3
  • docs/superpowers/plans/TURNBATCH-PROGRESS.md +87 −0
  • docs/superpowers/specs/2026-11-11-equipo-turn-batching.md +21 −2
  • internal/equipo/chat/store.go +74 −5
  • internal/equipo/chat/stream.go +8 −1
  • internal/headless/batching_test.go +43 −0
  • internal/thintest/batching_contract_test.go +74 −0

CI passed — run details

diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index 8cd1a464..2f9e70ed 100644
--- a/.rastrillo/budgets.txt
+++ b/.rastrillo/budgets.txt
@@ -49,7 +49,7 @@ perf GET /api/v1/notebook skip Thin v1 person API: bearer-only JSON for devices;
perf GET /api/v1/thinking skip Thin v1 person API: bearer-only JSON for devices; the browser reads thinking words on /settings/thinking.
perf GET /api/v1/tasks skip Thin v1 person API: bearer-only JSON for devices; the browser reads tasks through /tasks.
perf GET /api/v1/tasks/{id} skip Thin v1 person API: bearer-only JSON for devices; the browser reads a task through /tasks/{id}.
-size internal/equipo/chat 14050 - The re-run ruling (recheckMayMerge, refreshAfterRecheck, about 70 lines); measured 13981. Merge authority thin v1 adds the gate's store side (mergeauth.go: authorizeMerge before dispatch and at each hub request, the fence for runners below the merge-facts protocol, the ask card in Equipo's words, the ships question, receipts with Undo, the policy tool and API, about 1000 lines); the gate is pure, in internal/equipo/mergegate, but its inputs and audit must be read and written inside the store's transactions. Measured 13204. Mac recheck runs a waiting task's needs_macos checks again when a Mac that fits arrives (macrecheck.go, about 90 lines); measured 12485. Spend 1 merged onto Projects UX: measured 12376 with both. Spend 1 adds a task's spend from its usage rows (TaskSpend, about 60 lines) and the usage rows' round; measured 12047. Projects UX adds per-person project stars with the auto-star reconciliation, the person's and the coordinator's star_project (stars.go, about 210 lines) and the project's own repository in its view; measured 12206. Claude's sign-in by a link adds the code route beside the token's in SendSecret, the sign-in prompt and the kind it becomes (about 40 lines); measured 11933. Mac runners slices A and B add per-runner mailboxes, placement, withdrawal, the offline rule, the runners view, transfers and publication (runners.go, transfers.go, about 1100 lines). Composer attachments add uploads, the message link, the mailbox relay with chunk frames hydrated from the stored file, and serving (attachments.go, attachments_http.go, about 330 lines); the link and relay run inside the send and dispatch transactions, so they live beside them; sniffing and stripping are pure, in internal/attach. Measured 10292. Merged with UX1 thinking words (f2602d3), measured 9801. Housekeeping slice 1 adds the loop's ledger and state machine, the housekeeping principal's checks inside the shared store functions, reservations, Pause, quiet hours, the digest, claim recovery and the API (housekeeping.go, housekeeping_control.go, housekeeping_http.go, about 1,350 lines); the checks must run inside the store's transactions, so they live beside them; the detectors themselves are pure, in internal/equipo/housekeeping. Measured 9637. Thin v1 UX1 thinking words adds the per-person set and its API (thinking.go, about 100 lines); measured 8305. Connections slice 1 review round 2: the mutation ledger matches record_task by subject only and refuses an ambiguous call with the earlier operations, the preference and forget (about 120 lines); measured 8236. Thin v1 UX1 round 3 adds Equipo combining duplicate tasks reversibly (duplicates.go: detection, the in-transaction fold checks, fold, Undo, about 400 lines) and headlines on findings and steps (headline.go); measured 7898. Connections slice 1 adds connection records from hello and attempts, the connect mailbox, the API, usage rows and the turn's mutation ledger (connections.go and tools.go, about 600 lines); measured 7400 after merging UX1. Thin v1 UX1 adds step activity lines, duplicates and their fold, the coordinator at work on a task, project facts from the runner catalog and open merge cards for the pages (inner.go, about 330 lines); measured 6610 with slice 4c's review fixes. Thin v1 slice 4c adds the merge policy, the merge card, the rebase round and duplicate reports (merge.go, about 380 lines). Thin v1 instance core: conversation, projects, tasks, review and, from slice 4b, questions to the specialists (questions.go, about 470 lines) share one store, transaction and event log; splitting would export the transaction internals. Measured 5514 source lines; revisit at the slice 7 sweep.
+size internal/equipo/chat 14100 - Turn batching adds turnText, the frame fit (fitTail, batchFull) and the stranded-turn recovery in sync (about 115 lines); measured 14095. The re-run ruling (recheckMayMerge, refreshAfterRecheck, about 70 lines); measured 13981. Merge authority thin v1 adds the gate's store side (mergeauth.go: authorizeMerge before dispatch and at each hub request, the fence for runners below the merge-facts protocol, the ask card in Equipo's words, the ships question, receipts with Undo, the policy tool and API, about 1000 lines); the gate is pure, in internal/equipo/mergegate, but its inputs and audit must be read and written inside the store's transactions. Measured 13204. Mac recheck runs a waiting task's needs_macos checks again when a Mac that fits arrives (macrecheck.go, about 90 lines); measured 12485. Spend 1 merged onto Projects UX: measured 12376 with both. Spend 1 adds a task's spend from its usage rows (TaskSpend, about 60 lines) and the usage rows' round; measured 12047. Projects UX adds per-person project stars with the auto-star reconciliation, the person's and the coordinator's star_project (stars.go, about 210 lines) and the project's own repository in its view; measured 12206. Claude's sign-in by a link adds the code route beside the token's in SendSecret, the sign-in prompt and the kind it becomes (about 40 lines); measured 11933. Mac runners slices A and B add per-runner mailboxes, placement, withdrawal, the offline rule, the runners view, transfers and publication (runners.go, transfers.go, about 1100 lines). Composer attachments add uploads, the message link, the mailbox relay with chunk frames hydrated from the stored file, and serving (attachments.go, attachments_http.go, about 330 lines); the link and relay run inside the send and dispatch transactions, so they live beside them; sniffing and stripping are pure, in internal/attach. Measured 10292. Merged with UX1 thinking words (f2602d3), measured 9801. Housekeeping slice 1 adds the loop's ledger and state machine, the housekeeping principal's checks inside the shared store functions, reservations, Pause, quiet hours, the digest, claim recovery and the API (housekeeping.go, housekeeping_control.go, housekeeping_http.go, about 1,350 lines); the checks must run inside the store's transactions, so they live beside them; the detectors themselves are pure, in internal/equipo/housekeeping. Measured 9637. Thin v1 UX1 thinking words adds the per-person set and its API (thinking.go, about 100 lines); measured 8305. Connections slice 1 review round 2: the mutation ledger matches record_task by subject only and refuses an ambiguous call with the earlier operations, the preference and forget (about 120 lines); measured 8236. Thin v1 UX1 round 3 adds Equipo combining duplicate tasks reversibly (duplicates.go: detection, the in-transaction fold checks, fold, Undo, about 400 lines) and headlines on findings and steps (headline.go); measured 7898. Connections slice 1 adds connection records from hello and attempts, the connect mailbox, the API, usage rows and the turn's mutation ledger (connections.go and tools.go, about 600 lines); measured 7400 after merging UX1. Thin v1 UX1 adds step activity lines, duplicates and their fold, the coordinator at work on a task, project facts from the runner catalog and open merge cards for the pages (inner.go, about 330 lines); measured 6610 with slice 4c's review fixes. Thin v1 slice 4c adds the merge policy, the merge card, the rebase round and duplicate reports (merge.go, about 380 lines). Thin v1 instance core: conversation, projects, tasks, review and, from slice 4b, questions to the specialists (questions.go, about 470 lines) share one store, transaction and event log; splitting would export the transaction internals. Measured 5514 source lines; revisit at the slice 7 sweep.
perf GET /api/v1/questions/{id} skip Thin v1 person API: bearer-only JSON for devices; the browser reads questions on /tasks/{id}.
perf GET /api/v1/steps/{id}/log skip Thin v1 person API: bearer-only JSON for devices; the browser shows the log tail on /tasks/{id}.
perf GET /api/v1/connections/preference skip Connections slice 1 person API: bearer-only JSON for devices; the browser shows the preference on /conversation/connections.
@@ -61,6 +61,6 @@ perf GET /conversation/attachments/{id} skip Composer attachments: the bytes of
perf GET /conversation/attachments/{id}/preview skip Composer attachments: an image thumbnail inside the conversation; a file, not a screen.
perf GET /api/v1/runners skip Mac runners person API: bearer-only JSON for devices; the browser shows runners in the Team section.
time cmd/equipo-runner 60s Mac runners slice B: TestReleaseRunnerHasNoFakeWorker builds the release runner exactly as make release-runner does and the thin package under the testbuild tag (measured 11.9s locally with a warm cache).
-size internal/headless - 8475 Turn batching adds TestHeadlessTurnBatching (three messages behind a slow turn through the real runner and fake CLI: the one next turn, its input, the bubbles and note, the usage rows and the spend lines, about 145 lines); measured 8475. Merge authority extends 4c_checks_card to end in Equipo's own merge, measured by the real runner, with its receipt (about 30 lines); measured 8330. Claude's sign-in by a link adds its end-to-end, contained-launch and real runner kill tests (signin_test.go, signin_contained_test.go, about 400 lines); measured 8090.
-size internal/thintest - 13325 Turn batching adds its contracts (the crash between turns, the stranded recovery, failed, cancelled, interrupted and retried turns, the cancelled batch and the note clearing; about 330 lines); measured 13325. Merge authority merged onto Machines in Settings, with the re-run ruling's cases and stale thinking lines: measured 12998. Merge authority thin v1 adds its contracts (mergeauth_contract_test.go, about 650 lines) the protocol-aware rigs and the Mac re-run contract (macrecheck_mergeauth_contract_test.go) and the review fixes' contracts; measured 12535 with main merged. Mac recheck adds its enrolment, skip and outcome contracts (macrecheck_contract_test.go, about 210 lines); measured 11537. Machines in Settings adds its fixture, page and browser tests (machines_fixture_test.go, machines_pages_test.go, machines_browser_test.go, about 160 lines); measured 11759. Mac recheck adds its enrolment, skip and outcome contracts (macrecheck_contract_test.go, about 210 lines); measured 11537. Stale thinking lines merged onto Machines in Settings: measured 11967. Machines in Settings adds its fixture, page and browser tests (machines_fixture_test.go, machines_pages_test.go, machines_browser_test.go, about 160 lines); measured 11759. Stale thinking lines add their browser drive (stale_thinking_browser_test.go, about 200 lines) and the queued test now checks the note; measured 11795. Mac recheck adds its enrolment, skip and outcome contracts (macrecheck_contract_test.go, about 210 lines); measured 11537. Spend 1 merged onto the four UI branches: measured 11325. Spend 1 marks overcounting Claude rows (about 120 lines); it adds the task page's spend contract and the 0059 upgrade (spend_pages_test.go, about 100 lines) and the fix round feedback by protocol (about 40); measured 10224. The team panel merged onto Projects UX and the Settings UX pass: measured 11064 with all three. The team panel adds its page contract and the drawer's browser drive at 1280 and 390 (team_panel_test.go, team_panel_browser_test.go, about 300 lines); measured 10235. Projects UX merged onto the Settings UX pass: measured 10768 with both. Projects UX adds the Projects page contracts (order, quiet fold, filter, stars and Undo, the coordinator's star, repository counts, whole words), the decision cards' Mac and Ask about this contracts and their browser drive (projects_pages_test.go, projects_browser_test.go, about 330 lines); measured 10321. The Settings UX pass adds the Settings pattern's page contracts and the savebar, Housekeeping groups and Teams browser drives (settings_ux_pages_test.go, settings_ux_browser_test.go, about 430 lines); measured 10390. Claude's sign-in by a link adds the code contract (signin_contract_test.go: the card, the code route's refusals, the wrong-code card, the kind it becomes and the canary sweep, about 220 lines); measured 9896. The Connections Add page and the Settings rail add their page contracts and the rail's browser drive (connections_add_pages_test.go, settings_rail_pages_test.go, about 230 lines); measured 9676. Claude setup tokens add the token and Check again contracts; measured 9444 with the composer and Mac lines merged. The instant thinking line adds its browser drive (instant_browser_test.go, about 230 lines); measured 9064 with the composer and Mac lines merged. Mac runners add the role, scoping, migration, placement, withdrawal, transfer and publication contracts (about 900 test lines) beside the thin v1 contracts; one package keeps one instance harness.
+size internal/headless - 8520 Turn batching adds TestHeadlessTurnBatching (three messages behind a slow turn through the real runner and fake CLI: the one next turn, its input, the bubbles and note, the usage rows and the spend lines) and TestHeadlessBatchAfterRefusedReply (the real runner reconnects after a refused reply), about 190 lines; measured 8518. Merge authority extends 4c_checks_card to end in Equipo's own merge, measured by the real runner, with its receipt (about 30 lines); measured 8330. Claude's sign-in by a link adds its end-to-end, contained-launch and real runner kill tests (signin_test.go, signin_contained_test.go, about 400 lines); measured 8090.
+size internal/thintest - 13400 Turn batching adds its contracts (the crash between turns, the stranded recovery, failed, cancelled, interrupted and retried turns, the cancelled batch, the note clearing and batches split to fit one frame; about 400 lines); measured 13399. Merge authority merged onto Machines in Settings, with the re-run ruling's cases and stale thinking lines: measured 12998. Merge authority thin v1 adds its contracts (mergeauth_contract_test.go, about 650 lines) the protocol-aware rigs and the Mac re-run contract (macrecheck_mergeauth_contract_test.go) and the review fixes' contracts; measured 12535 with main merged. Mac recheck adds its enrolment, skip and outcome contracts (macrecheck_contract_test.go, about 210 lines); measured 11537. Machines in Settings adds its fixture, page and browser tests (machines_fixture_test.go, machines_pages_test.go, machines_browser_test.go, about 160 lines); measured 11759. Mac recheck adds its enrolment, skip and outcome contracts (macrecheck_contract_test.go, about 210 lines); measured 11537. Stale thinking lines merged onto Machines in Settings: measured 11967. Machines in Settings adds its fixture, page and browser tests (machines_fixture_test.go, machines_pages_test.go, machines_browser_test.go, about 160 lines); measured 11759. Stale thinking lines add their browser drive (stale_thinking_browser_test.go, about 200 lines) and the queued test now checks the note; measured 11795. Mac recheck adds its enrolment, skip and outcome contracts (macrecheck_contract_test.go, about 210 lines); measured 11537. Spend 1 merged onto the four UI branches: measured 11325. Spend 1 marks overcounting Claude rows (about 120 lines); it adds the task page's spend contract and the 0059 upgrade (spend_pages_test.go, about 100 lines) and the fix round feedback by protocol (about 40); measured 10224. The team panel merged onto Projects UX and the Settings UX pass: measured 11064 with all three. The team panel adds its page contract and the drawer's browser drive at 1280 and 390 (team_panel_test.go, team_panel_browser_test.go, about 300 lines); measured 10235. Projects UX merged onto the Settings UX pass: measured 10768 with both. Projects UX adds the Projects page contracts (order, quiet fold, filter, stars and Undo, the coordinator's star, repository counts, whole words), the decision cards' Mac and Ask about this contracts and their browser drive (projects_pages_test.go, projects_browser_test.go, about 330 lines); measured 10321. The Settings UX pass adds the Settings pattern's page contracts and the savebar, Housekeeping groups and Teams browser drives (settings_ux_pages_test.go, settings_ux_browser_test.go, about 430 lines); measured 10390. Claude's sign-in by a link adds the code contract (signin_contract_test.go: the card, the code route's refusals, the wrong-code card, the kind it becomes and the canary sweep, about 220 lines); measured 9896. The Connections Add page and the Settings rail add their page contracts and the rail's browser drive (connections_add_pages_test.go, settings_rail_pages_test.go, about 230 lines); measured 9676. Claude setup tokens add the token and Check again contracts; measured 9444 with the composer and Mac lines merged. The instant thinking line adds its browser drive (instant_browser_test.go, about 230 lines); measured 9064 with the composer and Mac lines merged. Mac runners add the role, scoping, migration, placement, withdrawal, transfer and publication contracts (about 900 test lines) beside the thin v1 contracts; one package keeps one instance harness.
perf GET /api/v1/projects/{id}/merge-policy skip Merge authority person API: bearer-only JSON for devices; the browser reads the policy on /projects/{id}.
diff --git a/docs/superpowers/plans/TURNBATCH-PROGRESS.md b/docs/superpowers/plans/TURNBATCH-PROGRESS.md
new file mode 100644
index 00000000..3a43905f
--- /dev/null
+++ b/docs/superpowers/plans/TURNBATCH-PROGRESS.md
@@ -0,0 +1,87 @@
+# Turn batching: progress
+
+Branch `turn-batching` from main 03f8a91. Design note:
+`docs/superpowers/specs/2026-11-11-equipo-turn-batching.md`.
+
+## Done
+
+1. **Finding.** The instance already batched messages sent during a turn
+ into one next turn (64cd2ce). The gap was that the messages were not
+ distinct: `Text` was the words joined by blank lines, and the files
+ were one list for the whole turn.
+2. **Change** (instance only, no wire, fixture or migration change):
+ `turnText` sets each message of a batch apart, with its files. `sync`
+ starts a stranded queued turn.
+3. **Failing first.** `TestHeadlessTurnBatching` (real runner, fake CLI,
+ thintest instance) failed on main for the input check. The output is
+ in commit fd22d42.
+4. **Contracts** (`internal/thintest/batching_contract_test.go`, protocol
+ 1 runner): `TestBatchCrashBetweenTurns`, `TestBatchStrandedRecovers`,
+ `TestBatchAfterTurnEnds` (failed, cancelled, interrupted),
+ `TestBatchWaitsForRetriedTurn`, `TestBatchCancelledWhileWaiting`,
+ `TestBatchMarkerClearsTogether`, `TestBatchSplitsToFitTheFrame`, and
+ headless `TestHeadlessBatchAfterRefusedReply` (real runner).
+5. **Astra round 1** (gpt-6-astra, high): REQUEST CHANGES, three
+ Important findings.
+ - Oversized batches could exceed the 256 KiB frame, and the runner
+ would refuse them on every resend. Fixed: batches split to fit, the
+ tail is trimmed to fit, and a waiting batch is kept out of an
+ earlier batch's tail.
+ - A store error on a runner frame closed with `CloseRevoked`, which
+ stops a real runner. Fixed: the close is now 1011 (retryable);
+ `ErrForbidden` still closes `CloseRevoked`.
+ - Queued marker on each bubble: this is a product question, left for
+ the controller. The branch keeps the single note from the
+ thinking-stale fix.
+
+## Mutations
+
+Each guard was broken once, with the targeted runs below, then restored.
+Command: `CGO_ENABLED=0 nice -n 10 go test ./internal/thintest -run
+'^(TestBatch|TestQueuedMessagesJoinOneTurn$)'` and, where shown, `go test
+./internal/headless -run '^TestHeadlessTurnBatching$'`.
+
+| Guard | Mutation | Died |
+|---|---|---|
+| Ordering | dispatch reads the batch `seq DESC` | thintest: CrashBetweenTurns "batch lacks alpha in place", StrandedRecovers and others; headless: "turn input lacks Message 1 of 3" |
+| Distinct messages | `turnText` joins the words as before | the same tests in both packages |
+| One next turn | every message opens a turn of its own (`fresh := true`) | thintest: "message 2: ... MessageIDs:[one id]" in every TestBatch |
+| One at a time (send) | a message dispatches beside the running turn | thintest: "message 2" in every TestBatch |
+| One at a time (end and recovery) | `dispatchNext` ignores a turn in flight | thintest: CrashBetweenTurns, the batch frame arrived during the held turn |
+| Atomic end and next | `reply` commits when the next dispatch fails | thintest: CrashBetweenTurns "the reply was acked with the next turn refused" |
+| Recovery | `sync` no longer calls `dispatchNext` | thintest: StrandedRecovers "no next turn" |
+| Marker clearing | the line's holder may be a turn that ended | thintest: MarkerClearsTogether "the note stayed after the turn picked the messages up" (headless survives: its runner acks at once) |
+| One note | every waiting bubble gets the note | thintest: MarkerClearsTogether; headless: "queued note not once under the latest message" |
+| Frame fit (split) | a batch never fills up | thintest: SplitsToFitTheFrame "12 large messages made batches of [one]" |
+| Frame fit (tail) | the tail is never trimmed | thintest: SplitsToFitTheFrame "message too big: read limited at 262145 bytes" |
+| Tail excludes waiting batches | the tail takes every other turn's messages | thintest: SplitsToFitTheFrame "batch 1's tail holds a message still waiting" |
+| Retryable close | a failed frame closes `CloseRevoked` again | headless: BatchAfterRefusedReply "runner stopped: runner credential refused" |
+
+## Spend (fake CLI, input tokens are prompt length / 4)
+
+| Case | Turns after the slow one | Input tokens |
+|---|---|---|
+| main, three messages during a slow turn | 1 | 102 |
+| this branch, the same | 1 | 154 (+52 for the batch line and headers) |
+| the same three words, each after the last reply | 3 | 2, 3, 3 |
+
+The fake does not model the fixed context every real turn pays (about
+17k input tokens on staging, 77% cached), so the third row understates
+real spend: three turns pay that context three times, and a batch pays
+it once. Usage stays per turn: one row for the batch turn and none for
+any single message (`TestHeadlessTurnBatching`).
+
+## Verification
+
+- Targeted: the contracts above, `TestQueuedMessagesJoinOneTurn`,
+ `TestCancel`, `TestMailboxResendAndGenerations`, `TestDrainAndRestart`,
+ `TestSecondaryRunnerSyncIgnored`, `TestContractAttachments`,
+ `TestContractStorageFullInWords`, the move-in contracts,
+ `TestContractConversation`, `TestSendIdempotency`, `TestChatPage`,
+ `TestReplacedConnectionFenced`, headless `6_quick_messages`.
+- Browser, one at a time: `TestBrowserInstantThinking*`,
+ `TestBrowserThinkingLinesClear`, `TestBrowserDraftStreamsFormatted`.
+ All pass.
+- `make budget`, vet, staticcheck on the changed packages, and
+ `TestReleaseCopyReviewed` with `EQUIPO_RELEASE_COPY_CHECK=1` (no UI
+ strings changed).
diff --git a/docs/superpowers/specs/2026-11-11-equipo-turn-batching.md b/docs/superpowers/specs/2026-11-11-equipo-turn-batching.md
index 88436105..22aebc2b 100644
--- a/docs/superpowers/specs/2026-11-11-equipo-turn-batching.md
+++ b/docs/superpowers/specs/2026-11-11-equipo-turn-batching.md
@@ -51,8 +51,8 @@ could not check this, because I did not read staging.
## The change
-All of it is in the instance's turn building. There is no wire, protocol,
-fixture or migration change.
+All of it is on the instance, mostly in its turn building. There is no
+wire, protocol, fixture or migration change.
- `dispatch` builds `Text` with `turnText`. One message is sent exactly as
before. Several messages are sent as:
@@ -76,6 +76,23 @@ fixture or migration change.
- `sync`, after it reconciles, calls `dispatchNext` for the person.
`dispatchNext` does nothing while a turn is in flight. A stranded queued
turn therefore starts on the runner's next connection, exactly once.
+- **One frame each** (Astra round 1). A runner reads at most
+ `wire.MaxFrameBytes` (256 KiB) and refuses a larger frame every time it
+ is resent. Each message is up to 16 KiB and goes in twice (`Text` and
+ `PersonText`), JSON-escaped. A message joins the newest waiting batch
+ only while the batch's own part fits `batchRoom` (the frame less 64
+ KiB). Otherwise it starts the next batch, which goes after the first,
+ one turn at a time and in order. `dispatch` drops the oldest tail
+ messages until the command fits (`fitTail`). The tail never holds the
+ messages of a batch still waiting behind the one being sent.
+- **A failed runner frame is retryable** (Astra round 1). A store error
+ while applying a runner frame used to close the socket with
+ `CloseRevoked`, so a real runner stopped as if its credential had been
+ revoked. Now it closes with 1011 (internal error): the runner
+ reconnects with backoff and resends the unacked frame. `ErrForbidden`
+ keeps `CloseRevoked`. A credential revoked meanwhile is refused at the
+ handshake (403), and every runner version maps that to revoked. Old
+ runners treat any other close code as a reason to reconnect.
## Crash, retry and end cases
@@ -86,6 +103,8 @@ fixture or migration change.
| End committed without its successor | The next `sync` dispatches it once. A second sync does nothing. | `TestBatchStrandedRecovers` |
| Running turn fails, is cancelled, or is lost across a runner reconnect | The batch goes next, once. The ended turn keeps only its own message. | `TestBatchAfterTurnEnds` |
| Running turn retried (attempt 2) | The batch keeps waiting. A message sent during the retry joins it. A late attempt-1 reply is ignored. The batch goes once, after attempt 2 replies. | `TestBatchWaitsForRetriedTurn` |
+| The instance refuses the next turn (a store error) with a real runner | The reply rolls back and the socket closes 1011. The runner reconnects and resends the reply, and the batch goes once. | `TestHeadlessBatchAfterRefusedReply` |
+| Batch too big for one frame | It is split into several batches, sent one after another, in order. Each frame fits. | `TestBatchSplitsToFitTheFrame` |
| Batch cancelled while it waits | All of its messages end `cancelled` together, unsent. The next message gets a turn of its own. | `TestBatchCancelledWhileWaiting` |
| Bubbles and the queued note | Each message keeps its own bubble in the queued turn. One note sits under the latest one, as the thinking-stale fix did. The note clears for all of them when the batch's frame goes out, before the ack. | `TestBatchMarkerClearsTogether`, `TestHeadlessTurnBatching` |
diff --git a/internal/equipo/chat/store.go b/internal/equipo/chat/store.go
index eadefeb9..15ff0ba4 100644
--- a/internal/equipo/chat/store.go
+++ b/internal/equipo/chat/store.go
@@ -260,8 +260,11 @@ func (t *txn) dispatch(r *turnRecord) error {
if len(mine) == 0 && r.Kind == wire.TurnPerson {
return ErrInvalid
}
+ // The tail is what went before: never this turn's messages, nor those
+ // of a batch still waiting behind it (a batch too big for one frame
+ // goes as several turns, one after another).
var prior []messageRecord
- if err := t.db.Where("person = ? AND turn_id <> ?", r.Person, r.ID).Order("seq DESC").Limit(wire.MaxTailMessages).Find(&prior).Error; err != nil {
+ if err := t.db.Where("person = ? AND turn_id <> ? AND turn_id NOT IN (SELECT id FROM chat_turns WHERE person = ? AND dispatched = ? AND state = ?)", r.Person, r.ID, r.Person, false, wire.TurnQueued).Order("seq DESC").Limit(wire.MaxTailMessages).Find(&prior).Error; err != nil {
return err
}
tail := make([]wire.TailMessage, 0, len(prior))
@@ -291,10 +294,68 @@ func (t *txn) dispatch(r *turnRecord) error {
}
now := t.now()
r.Dispatched, r.DispatchedAt = true, &now
- if err := t.command(r.Person, wire.FrameMessage, wire.MessageCommand{Person: r.Person, TurnID: r.ID, Attempt: r.Attempt, Kind: r.Kind, Text: turnText(texts, attached), PersonText: own, Tail: tail, Attachments: files}); err != nil {
+ cmd := wire.MessageCommand{Person: r.Person, TurnID: r.ID, Attempt: r.Attempt, Kind: r.Kind, Text: turnText(texts, attached), PersonText: own, Tail: tail, Attachments: files}
+ if cmd.Tail, err = fitTail(cmd); err != nil {
return err
}
- return nil
+ return t.command(r.Person, wire.FrameMessage, cmd)
+}
+
+// frameRoom is what a message command's body may take: the frame limit
+// less its envelope (id and type).
+const frameRoom = wire.MaxFrameBytes - 1<<10
+
+// fitTail drops the oldest tail messages until the command fits one
+// frame: a runner refuses a larger frame, every time it is resent.
+func fitTail(cmd wire.MessageCommand) ([]wire.TailMessage, error) {
+ raw, err := json.Marshal(cmd)
+ if err != nil {
+ return nil, err
+ }
+ size, tail := len(raw), cmd.Tail
+ for len(tail) > 0 && size > frameRoom {
+ one, err := json.Marshal(tail[0])
+ if err != nil {
+ return nil, err
+ }
+ size, tail = size-len(one)-1, tail[1:]
+ }
+ return tail, nil
+}
+
+// batchRoom bounds the person's own part of a batch (its words twice, as
+// Text and PersonText, and its files), leaving room for answer prefixes
+// and some tail.
+const batchRoom = wire.MaxFrameBytes - 64<<10
+
+// batchFull reports whether a queued turn has no room left for one more
+// message: its text and its number of files. A full batch stays as it is;
+// the message starts the next batch, which goes after it.
+func (t *txn) batchFull(turn, text string, files int) (bool, error) {
+ var rows []messageRecord
+ if err := t.db.Select("id", "text").Where("turn_id = ? AND role = ?", turn, wire.RolePerson).Find(&rows).Error; err != nil {
+ return false, err
+ }
+ ids := make([]string, 0, len(rows))
+ texts := []string{text}
+ for _, m := range rows {
+ ids, texts = append(ids, m.ID), append(texts, m.Text)
+ }
+ var held int64
+ if len(ids) > 0 {
+ if err := t.db.Model(&fileRecord{}).Where("message_id IN ?", ids).Count(&held).Error; err != nil {
+ return false, err
+ }
+ }
+ size := 256 + 512*(int(held)+files)
+ for _, text := range texts {
+ raw, err := json.Marshal(text)
+ if err != nil {
+ return false, err
+ }
+ size += 2*len(raw) + 64
+ }
+ return size > batchRoom, nil
}
// turnText is what the coordinator reads for a turn's messages. One
@@ -359,7 +420,8 @@ func bodyHash(text string) string {
}
// Send records a person message. While a turn is in flight, new messages
-// join one queued turn, which goes to the coordinator as a single frame.
+// join one queued turn, which goes to the coordinator as a single frame
+// (several, one turn after another, when they would not fit one).
func (s *Store) Send(ctx context.Context, person string, in wire.SendMessage) (out wire.Sent, created bool, err error) {
// A message is words, attachments or both.
if in.Text = strings.TrimSpace(in.Text); in.Text == "" && len(in.Attachments) == 0 || len(in.Text) > wire.MaxMessageBytes || !utf8.ValidString(in.Text) || strings.ContainsRune(in.Text, 0) {
@@ -409,11 +471,18 @@ func (t *txn) send(person, key, text string, files []string, before func(message
}
now := t.now()
var turn turnRecord
- err = t.db.Where("person = ? AND dispatched = ? AND state = ? AND coalesce(kind, '') = ''", person, false, wire.TurnQueued).Order("created_at, id").First(&turn).Error
+ // The message joins the newest waiting batch, unless that batch would
+ // no longer fit one frame.
+ err = t.db.Where("person = ? AND dispatched = ? AND state = ? AND coalesce(kind, '') = ''", person, false, wire.TurnQueued).Order("created_at DESC, id DESC").First(&turn).Error
fresh := errors.Is(err, gorm.ErrRecordNotFound)
if err != nil && !fresh {
return out, false, err
}
+ if !fresh {
+ if fresh, err = t.batchFull(turn.ID, text, len(files)); err != nil {
+ return out, false, err
+ }
+ }
if fresh {
turn = turnRecord{ID: newID("t_"), Person: person, State: wire.TurnQueued, Attempt: 1, CreatedAt: now, UpdatedAt: now}
if err = t.db.Create(&turn).Error; err != nil {
diff --git a/internal/equipo/chat/stream.go b/internal/equipo/chat/stream.go
index 821ef57a..691b253a 100644
--- a/internal/equipo/chat/stream.go
+++ b/internal/equipo/chat/stream.go
@@ -208,9 +208,16 @@ func (rc *runnerConn) read(ctx context.Context) websocket.StatusCode {
return wire.CloseSuperseded
case errors.Is(err, ErrInvalid):
return websocket.StatusPolicyViolation
- case err != nil && !errors.Is(err, ErrNotFound):
+ case errors.Is(err, ErrForbidden):
rc.log("runner frame", err)
return wire.CloseRevoked
+ case err != nil && !errors.Is(err, ErrNotFound):
+ // The frame's transaction rolled back and it stays unacked. The
+ // runner reconnects and sends it again; a credential revoked
+ // meanwhile is refused at the handshake (403), which is how
+ // every runner learns it is revoked.
+ rc.log("runner frame", err)
+ return websocket.StatusInternalError
}
if f.Durable() {
ack, _ := wire.NewFrame("a"+f.ID, wire.FrameAck, wire.Ack{ID: f.ID})
diff --git a/internal/headless/batching_test.go b/internal/headless/batching_test.go
index 4c2f83d7..20e24470 100644
--- a/internal/headless/batching_test.go
+++ b/internal/headless/batching_test.go
@@ -4,6 +4,7 @@ import (
"encoding/json"
"strings"
"testing"
+ "time"
"amadan.net/oficina/equipo/internal/thintest"
"amadan.net/oficina/equipo/internal/wire"
@@ -143,3 +144,45 @@ func logSpend(t *testing.T, inst *thintest.Instance, label, turn string) int64 {
t.Logf("spend %s: turn %s, %d usage rows, %d input tokens, %d cached", label, turn, rows, input, cached)
return rows
}
+
+// TestHeadlessBatchAfterRefusedReply: when the instance cannot start the
+// next turn, the reply that ended the slow one rolls back with it. The
+// real runner is not told it was revoked: it reconnects, sends the reply
+// again once the instance can take it, and the batch goes once.
+func TestHeadlessBatchAfterRefusedReply(t *testing.T) {
+ env, inst, r := localEnv(t)
+ r.start(t)
+ s := open(t, env)
+ s.keep()
+ busy := s.send(t, "Take your time with this one. sleep:3000")
+ s.waitTurn(t, busy.Turn.ID, wire.TurnRunning)
+ a, b := s.send(t, "alpha first"), s.send(t, "bravo second")
+ db := inst.DB.Writer()
+ if _, err := db.Exec(`CREATE TRIGGER refuse_next BEFORE INSERT ON runner_commands WHEN NEW.kind = 'message' BEGIN SELECT RAISE(ABORT, 'refused'); END`); err != nil {
+ t.Fatal(err)
+ }
+ for deadline := time.Now().Add(time.Minute); strings.Count(inst.Logs(), "refused") < 2; time.Sleep(100 * time.Millisecond) {
+ if time.Now().After(deadline) {
+ t.Fatal("the reply was never refused twice")
+ }
+ }
+ select {
+ case err := <-r.done:
+ t.Fatalf("the runner stopped: %v", err)
+ default:
+ }
+ if st, err := env.Client.Turn(s.ctx, busy.Turn.ID); err != nil || st.State != wire.TurnRunning {
+ t.Fatalf("slow turn %+v %v while its successor is refused", st, err)
+ }
+ if _, err := db.Exec(`DROP TRIGGER refuse_next`); err != nil {
+ t.Fatal(err)
+ }
+ replyOf(t, s, busy.Turn.ID)
+ reply := replyOf(t, s, a.Turn.ID)
+ if b.Turn.ID != a.Turn.ID || !strings.Contains(reply.Text, "You sent 2 messages: 1/2 alpha first; 2/2 bravo second.") {
+ t.Fatalf("batch %s/%s answered %q", a.Turn.ID, b.Turn.ID, reply.Text)
+ }
+ if cmds := messageCommands(t, inst, a.Turn.ID); len(cmds) != 1 {
+ t.Fatalf("%d frames for the batch", len(cmds))
+ }
+}
diff --git a/internal/thintest/batching_contract_test.go b/internal/thintest/batching_contract_test.go
index 67df9461..adc4825b 100644
--- a/internal/thintest/batching_contract_test.go
+++ b/internal/thintest/batching_contract_test.go
@@ -2,6 +2,7 @@ package thintest
import (
"context"
+ "fmt"
"strings"
"testing"
"time"
@@ -325,3 +326,76 @@ func TestBatchMarkerClearsTogether(t *testing.T) {
}
bubbles(page)
}
+
+// Messages that would not fit one frame together go as several batches,
+// one turn after another, in order. Each frame fits (the runner reads at
+// most wire.MaxFrameBytes): the oldest tail goes first, and a later
+// batch's messages are never in an earlier one's tail.
+func TestBatchSplitsToFitTheFrame(t *testing.T) {
+ r := newRig(t)
+ runner := r.dial(0)
+ busy, err := r.client.Send(r.ctx, "one", "k0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ f, _, _ := runner.Expect(r.ctx, wire.FrameMessage)
+ runner.Send(r.ctx, "a0", wire.FrameAck, wire.Ack{ID: f.ID})
+ r.turnIs(busy.Turn.ID, wire.TurnRunning)
+ var texts []string
+ turns := map[string][]string{}
+ var order []string
+ for i := range 12 {
+ // Near the largest message, with characters JSON escapes (the
+ // person API reads at most twice the limit).
+ text := fmt.Sprintf("m%02d %s%s", i+1, strings.Repeat("x", wire.MaxMessageBytes-2008), strings.Repeat("<", 2000))
+ s, err := r.client.Send(r.ctx, text, fmt.Sprintf("kb%d", i))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, ok := turns[s.Turn.ID]; !ok {
+ order = append(order, s.Turn.ID)
+ }
+ turns[s.Turn.ID] = append(turns[s.Turn.ID], text)
+ texts = append(texts, text)
+ }
+ if len(order) < 2 || len(turns[order[0]]) < 2 {
+ t.Fatalf("12 large messages made batches of %v", order)
+ }
+ end := wire.Reply{TurnID: busy.Turn.ID, Attempt: 1, Text: "first"}
+ var got []string
+ for i, batch := range order {
+ runner.Send(r.ctx, fmt.Sprintf("rep%d", i), wire.FrameReply, end)
+ mf, body, err := runner.Expect(r.ctx, wire.FrameMessage)
+ if err != nil {
+ t.Fatalf("batch %d: %v", i+1, err)
+ }
+ cmd := body.(*wire.MessageCommand)
+ if cmd.TurnID != batch || len(cmd.PersonText) != len(turns[batch]) {
+ t.Fatalf("batch %d is %s with %d messages", i+1, cmd.TurnID, len(cmd.PersonText))
+ }
+ for _, m := range cmd.Tail {
+ for _, later := range order[i+1:] {
+ for _, text := range turns[later] {
+ if m.Text == text {
+ t.Fatalf("batch %d's tail holds a message still waiting", i+1)
+ }
+ }
+ }
+ }
+ if len(cmd.Tail) == 0 || cmd.Tail[len(cmd.Tail)-1].Text != end.Text {
+ t.Fatalf("batch %d's tail lost the newest reply", i+1)
+ }
+ got = append(got, cmd.PersonText...)
+ runner.Send(r.ctx, fmt.Sprintf("ab%d", i), wire.FrameAck, wire.Ack{ID: mf.ID})
+ r.turnIs(batch, wire.TurnRunning)
+ end = wire.Reply{TurnID: batch, Attempt: 1, Text: fmt.Sprintf("reply %d", i+1)}
+ }
+ if len(got) != len(texts) {
+ t.Fatalf("%d of %d messages reached the coordinator", len(got), len(texts))
+ }
+ for i := range texts {
+ if got[i] != texts[i] {
+ t.Fatalf("message %d out of place", i+1)
+ }
+ }
+}