oficina / equipo Public

Connections slice 1: review round, waiting state and effect replay

Astra's design review applied to what slice 1 built:
- a nonterminal waiting turn state for a turn held with no_connection;
- write tools recorded per turn before and after they run; a later
  attempt of the turn gets the recorded result, and an unseen result is
  reconciled under its earlier call id, which the instance replays;
- failover only after the old attempt's exit is proven;
- the new attempt's prompt says what the turn already did;
- returning to a connection starts afresh from the notebook and tail;
- only checked connections are chosen, checked on first use;
- quota, auth and transient Codex failures told apart;
- usage of attempts that ended without a reply is reported.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 076eba370286e2c1810bacc6976120d9a10ab5e2 parent ea315e2
22 files changed, +413 −70
  • internal/equipo/chat/movein.go +1 −1
  • internal/equipo/chat/notebook.go +1 −1
  • internal/equipo/chat/runner.go +7 −7
  • internal/equipo/chat/store.go +4 −4
  • internal/equipo/chat/tools.go +5 −3
  • internal/equipo/chat_page.go +1 −1
  • internal/equipo/static/chat-stream.js +2 −2
  • internal/headless/connections_test.go +1 −1
  • internal/runner/connect/choose.go +4 −4
  • internal/runner/connect/choose_test.go +7 −1
  • internal/runner/connect/limits.go +27 −8
  • internal/runner/thin/bridge.go +10 −0
  • internal/runner/thin/claude.go +30 −6
  • internal/runner/thin/codex.go +12 −6
  • internal/runner/thin/conns.go +42 −11
  • internal/runner/thin/effects.go +166 −0
  • internal/runner/thin/engine.go +15 −1
  • internal/runner/thin/failover.go +59 −10
  • internal/runner/thin/state.go +1 −1
  • internal/thintest/connections_contract_test.go +7 −2
  • internal/wire/api.go +8 −0
  • internal/wire/frames.go +3 −0
diff --git a/internal/equipo/chat/movein.go b/internal/equipo/chat/movein.go
index 7b04ce43..fbac5152 100644
--- a/internal/equipo/chat/movein.go
+++ b/internal/equipo/chat/movein.go
@@ -65,7 +65,7 @@ func (t *txn) moveIn(l Lease, v *wire.MoveIn) error {
return err
}
var n int64
- if err := t.db.Model(&turnRecord{}).Where("person = ? AND state IN ? AND coalesce(kind, '') <> ''", person, []string{wire.TurnQueued, wire.TurnRunning}).Count(&n).Error; err != nil || n > 0 {
+ if err := t.db.Model(&turnRecord{}).Where("person = ? AND state IN ? AND coalesce(kind, '') <> ''", person, wire.InFlight).Count(&n).Error; err != nil || n > 0 {
return err
}
// The coordinator state here is the authority on introductions: one
diff --git a/internal/equipo/chat/notebook.go b/internal/equipo/chat/notebook.go
index 528f474e..8f8fe507 100644
--- a/internal/equipo/chat/notebook.go
+++ b/internal/equipo/chat/notebook.go
@@ -101,7 +101,7 @@ func (s *Store) ResetCoordinator(ctx context.Context, person string) (out wire.C
return err
}
var busy int64
- if err := t.db.Model(&turnRecord{}).Where("person = ? AND state IN ?", person, []string{wire.TurnQueued, wire.TurnRunning}).Count(&busy).Error; err != nil {
+ if err := t.db.Model(&turnRecord{}).Where("person = ? AND state IN ?", person, wire.InFlight).Count(&busy).Error; err != nil {
return err
}
if busy > 0 {
diff --git a/internal/equipo/chat/runner.go b/internal/equipo/chat/runner.go
index 53ce95da..d875086b 100644
--- a/internal/equipo/chat/runner.go
+++ b/internal/equipo/chat/runner.go
@@ -365,16 +365,16 @@ func (t *txn) report(l Lease, v *wire.TurnReport) error {
return nil
}
switch v.State {
- case wire.TurnRunning:
- // Running again on a new attempt (recovery, a failover), or held
- // for a connection (no_connection) and going again ("").
- if v.Reason != "" && v.Reason != wire.ReasonNoConnection {
+ case wire.TurnRunning, wire.TurnWaiting:
+ // Running again on a new attempt (recovery, a failover), held for a
+ // connection (waiting, no_connection), or going again (running).
+ if v.State == wire.TurnRunning && v.Reason != "" || v.State == wire.TurnWaiting && v.Reason != wire.ReasonNoConnection {
return ErrInvalid
}
- if v.Attempt == r.Attempt && r.State == wire.TurnRunning && r.Reason == v.Reason {
+ if v.Attempt == r.Attempt && r.State == v.State {
return nil
}
- r.State, r.Attempt, r.Reason = wire.TurnRunning, v.Attempt, v.Reason
+ r.State, r.Attempt, r.Reason = v.State, v.Attempt, v.Reason
return t.saveTurn(&r)
case wire.TurnFailed, wire.TurnCancelled:
r.State, r.Reason, r.Attempt = v.State, v.Reason, v.Attempt
@@ -418,7 +418,7 @@ func (t *txn) sync(l Lease, v *wire.Sync) error {
held[run.TurnID] = true
}
var running []turnRecord
- if err := t.db.Where("person = ? AND state = ?", l.Runner.Person, wire.TurnRunning).Find(&running).Error; err != nil {
+ if err := t.db.Where("person = ? AND state IN ?", l.Runner.Person, []string{wire.TurnRunning, wire.TurnWaiting}).Find(&running).Error; err != nil {
return err
}
for _, r := range running {
diff --git a/internal/equipo/chat/store.go b/internal/equipo/chat/store.go
index ee04f16f..edf039dc 100644
--- a/internal/equipo/chat/store.go
+++ b/internal/equipo/chat/store.go
@@ -223,7 +223,7 @@ const personFirst = "CASE WHEN coalesce(kind, '') = '' THEN 0 ELSE 1 END, create
// flight, the person's own turns first.
func (t *txn) dispatchNext(person string) error {
var busy int64
- if err := t.db.Model(&turnRecord{}).Where("person = ? AND dispatched = ? AND state IN ?", person, true, []string{wire.TurnQueued, wire.TurnRunning}).Count(&busy).Error; err != nil {
+ if err := t.db.Model(&turnRecord{}).Where("person = ? AND dispatched = ? AND state IN ?", person, true, wire.InFlight).Count(&busy).Error; err != nil {
return err
}
if busy != 0 {
@@ -314,7 +314,7 @@ func (t *txn) send(person, key, text string, before func(messageRecord) error) (
}
}
var busy int64
- if err = t.db.Model(&turnRecord{}).Where("person = ? AND dispatched = ? AND state IN ?", person, true, []string{wire.TurnQueued, wire.TurnRunning}).Count(&busy).Error; err != nil {
+ if err = t.db.Model(&turnRecord{}).Where("person = ? AND dispatched = ? AND state IN ?", person, true, wire.InFlight).Count(&busy).Error; err != nil {
return out, false, err
}
if busy == 0 {
@@ -336,7 +336,7 @@ func (t *txn) send(person, key, text string, before func(messageRecord) error) (
// person's turn goes next; the move-in continues in a new turn after it.
func (t *txn) yieldTurns(person string) error {
var rows []turnRecord
- if err := t.db.Where("person = ? AND dispatched = ? AND state IN ? AND coalesce(kind, '') <> '' AND (yield IS NULL OR yield = ?)", person, true, []string{wire.TurnQueued, wire.TurnRunning}, false).Find(&rows).Error; err != nil {
+ if err := t.db.Where("person = ? AND dispatched = ? AND state IN ? AND coalesce(kind, '') <> '' AND (yield IS NULL OR yield = ?)", person, true, wire.InFlight, false).Find(&rows).Error; err != nil {
return err
}
for i := range rows {
@@ -463,7 +463,7 @@ func (s *Store) Snapshot(ctx context.Context, person string) (out wire.Snapshot,
out.Messages = append(out.Messages, messageView(rows[i]))
}
var turns []turnRecord
- if e = tx.Where("person = ? AND (state IN ? OR id IN (SELECT turn_id FROM chat_messages WHERE person = ? ORDER BY seq DESC LIMIT ?))", person, []string{wire.TurnQueued, wire.TurnRunning}, person, wire.MaxTailMessages).Order("created_at, id").Find(&turns).Error; e != nil {
+ if e = tx.Where("person = ? AND (state IN ? OR id IN (SELECT turn_id FROM chat_messages WHERE person = ? ORDER BY seq DESC LIMIT ?))", person, wire.InFlight, person, wire.MaxTailMessages).Order("created_at, id").Find(&turns).Error; e != nil {
return e
}
out.Turns = make([]wire.Turn, 0, len(turns))
diff --git a/internal/equipo/chat/tools.go b/internal/equipo/chat/tools.go
index 9ecbe449..b41d6ef5 100644
--- a/internal/equipo/chat/tools.go
+++ b/internal/equipo/chat/tools.go
@@ -75,10 +75,12 @@ func argsHash(raw json.RawMessage) string {
}
// replay answers a repeated call id with the stored result, only for the
-// same turn, attempt, tool and arguments, and only while the turn still
-// runs for this primary runner: authority is checked now, not then.
+// same turn, tool and arguments, from this attempt or an earlier one (a
+// turn that moved connection reconciles what its earlier attempt did,
+// never running it twice), and only while the turn still runs for this
+// primary runner: authority is checked now, not then.
func (t *txn) replay(l Lease, v *wire.ToolCall, prior toolCallRecord, args string) (wire.ToolResult, error) {
- if prior.TurnID != v.TurnID || prior.Attempt != v.Attempt || prior.Name != v.Name || prior.ArgsHash != args {
+ if prior.TurnID != v.TurnID || prior.Attempt > v.Attempt || prior.Name != v.Name || prior.ArgsHash != args {
return refused("invalid", toolBadInput), nil
}
r, err := t.ownTurn(l, v.TurnID)
diff --git a/internal/equipo/chat_page.go b/internal/equipo/chat_page.go
index 8a8960d2..a79af57b 100644
--- a/internal/equipo/chat_page.go
+++ b/internal/equipo/chat_page.go
@@ -205,7 +205,7 @@ func (a *application) chatPage(w http.ResponseWriter, r *http.Request) {
for i, t := range snap.Turns {
if !wire.Terminal(t.State) {
view.Waiting = append(view.Waiting, t)
- if t.Reason == wire.ReasonNoConnection && view.NoConnection == nil {
+ if t.State == wire.TurnWaiting && view.NoConnection == nil {
lines, err := a.store.Chat().NoConnection(ctx, address)
if err != nil {
a.failure(w, r, chatError(err))
diff --git a/internal/equipo/static/chat-stream.js b/internal/equipo/static/chat-stream.js
index f49d472c..a59e5a73 100644
--- a/internal/equipo/static/chat-stream.js
+++ b/internal/equipo/static/chat-stream.js
@@ -434,7 +434,7 @@
feed.insertBefore(own, waiting);
scroll();
} else if (type === "turn") {
- if (v.state === "queued" || v.state === "running") {
+ if (v.state === "queued" || v.state === "running" || v.state === "waiting") {
var shownDraft = bubble(v.id, v.kind);
if (drafts[v.id] && drafts[v.id].attempt !== v.attempt) {
// The refused attempt's words go; the next attempt's follow.
@@ -444,7 +444,7 @@
}
// Held for a connection, or going again: the card is the server's.
var held = !!feed.querySelector('[data-no-connection="' + CSS.escape(v.id) + '"]');
- if ((v.reason === "no_connection") !== held) refresh().catch(function () { location.reload(); });
+ if ((v.state === "waiting") !== held) refresh().catch(function () { location.reload(); });
} else if (v.state === "replied" && !v.reply_id) {
// A turn that ended with nothing to say (an empty explore).
delete drafts[v.id];
diff --git a/internal/headless/connections_test.go b/internal/headless/connections_test.go
index e92d95ac..5791a336 100644
--- a/internal/headless/connections_test.go
+++ b/internal/headless/connections_test.go
@@ -361,7 +361,7 @@ func connNoConnection(t *testing.T, env *Env, inst *thintest.Instance, r *localR
sent := s.send(t, "Hello. limit:"+thintest.Owner)
s.wait(t, "held", time.Minute, func(cv *thintest.Conversation) bool {
v := cv.Turns[sent.Turn.ID]
- return v.State == wire.TurnRunning && v.Reason == wire.ReasonNoConnection
+ return v.State == wire.TurnWaiting && v.Reason == wire.ReasonNoConnection
})
page := inst.Get(t, "/conversation")
if !strings.Contains(page, "data-no-connection") || !strings.Contains(page, "Nothing can answer right now. Claude resets") || strings.Contains(page, "Send your message again") {
diff --git a/internal/runner/connect/choose.go b/internal/runner/connect/choose.go
index ad0b8cab..708446f0 100644
--- a/internal/runner/connect/choose.go
+++ b/internal/runner/connect/choose.go
@@ -27,7 +27,6 @@ const (
const (
StateHealthy = "healthy"
StateLimited = "limited"
- stateUnknown = ""
lowHeadroom = 0.9
coolOff = 15 * time.Minute
coolOffLonger = time.Hour
@@ -56,11 +55,12 @@ type Candidate struct {
Known bool
}
-// Usable reports whether a connection may be chosen at now: healthy (or
-// not yet checked), or limited with its reset passed.
+// Usable reports whether a connection may be chosen at now: healthy, or
+// limited with its reset passed. A connection not yet checked is not (its
+// keeper checks it before choosing); one connecting is not one yet.
func (c Candidate) Usable(now time.Time) bool {
switch c.State {
- case StateHealthy, stateUnknown:
+ case StateHealthy:
return true
case StateLimited:
return !c.ResetsAt.IsZero() && !now.Before(c.ResetsAt)
diff --git a/internal/runner/connect/choose_test.go b/internal/runner/connect/choose_test.go
index 651e1c4e..754dd44a 100644
--- a/internal/runner/connect/choose_test.go
+++ b/internal/runner/connect/choose_test.go
@@ -40,7 +40,8 @@ func TestChoose(t *testing.T) {
{"engineering skips codex", []Candidate{limited(claude, now.Add(time.Hour)), codex}, RoleEngineering, "", nil, "", ""},
{"avoid", []Candidate{claude, claude2}, RoleEngineering, "", []string{"claude-a"}, "claude-2", ReasonOnlyOption},
{"signed out never", []Candidate{{ID: "claude-a", Provider: "claude", State: "sign_in_again"}, codex}, RoleCoordinator, "claude-a", nil, "codex-1", ReasonOnlyOption},
- {"unchecked counts as healthy", []Candidate{{ID: "codex-1", Provider: "codex"}}, RoleCoordinator, "", nil, "codex-1", ReasonOnlyOption},
+ {"unchecked is never chosen", []Candidate{{ID: "codex-1", Provider: "codex"}}, RoleCoordinator, "", nil, "", ""},
+ {"connecting is never chosen", []Candidate{{ID: "codex-1", Provider: "codex", State: "connecting"}}, RoleCoordinator, "", nil, "", ""},
} {
t.Run(tc.name, func(t *testing.T) {
got, ok := Choose(tc.cs, tc.role, tc.current, tc.avoid, now)
@@ -104,6 +105,11 @@ func TestCodexRateLimits(t *testing.T) {
if !l.Limited || !l.ResetsAt.IsZero() {
t.Fatalf("reached without a reset: %+v", l)
}
+ for raw, want := range map[string]string{`{"message":"x","codexErrorInfo":"usageLimitExceeded"}`: FailQuota, `{"message":"x","codexErrorInfo":"unauthorized"}`: FailAuth, `{"message":"x","codexErrorInfo":"rateLimitExceeded"}`: FailTransient, `{"message":"x","codexErrorInfo":"serverOverloaded"}`: FailTransient, `{"message":"x","codexErrorInfo":{"httpConnectionFailed":{"httpStatusCode":502}}}`: FailTransient, `{"message":"x"}`: FailTransient} {
+ if got := CodexFailure([]byte(raw)); got != want {
+ t.Fatalf("%s: %s, want %s", raw, got, want)
+ }
+ }
if !CodexQuotaError([]byte(`{"message":"x","codexErrorInfo":"usageLimitExceeded"}`)) || CodexQuotaError([]byte(`{"message":"x","codexErrorInfo":"rateLimitExceeded"}`)) || CodexQuotaError([]byte(`{"message":"x","codexErrorInfo":{"httpConnectionFailed":{}}}`)) {
t.Fatal("quota error")
}
diff --git a/internal/runner/connect/limits.go b/internal/runner/connect/limits.go
index 25cb6c91..2b2b492c 100644
--- a/internal/runner/connect/limits.go
+++ b/internal/runner/connect/limits.go
@@ -132,16 +132,35 @@ func CodexRateLimits(raw json.RawMessage) (Limit, string, bool) {
return l, plan, true
}
-// CodexQuotaError reports whether a failed turn's error is the account's
-// usage limit (codexErrorInfo usageLimitExceeded), as opposed to a
-// transient rate limit or any other failure.
-func CodexQuotaError(turnError json.RawMessage) bool {
+// Failure classes of a turn that did not complete (spec §2.7): quota
+// (the account's usage limit: move to another connection, limited until
+// the reset), auth (the provider refused the credential: move, and the
+// connection needs signing in again) and transient (a rate limit, an
+// overloaded server, a dropped stream: no move, the turn fails).
+const (
+ FailQuota = "quota"
+ FailAuth = "auth"
+ FailTransient = "transient"
+)
+
+// CodexFailure classifies a failed turn's error (codexErrorInfo).
+func CodexFailure(turnError json.RawMessage) string {
var e struct {
Info json.RawMessage `json:"codexErrorInfo"`
}
- if json.Unmarshal(turnError, &e) != nil {
- return false
- }
var s string
- return json.Unmarshal(e.Info, &s) == nil && s == "usageLimitExceeded"
+ if json.Unmarshal(turnError, &e) != nil || json.Unmarshal(e.Info, &s) != nil {
+ return FailTransient
+ }
+ switch s {
+ case "usageLimitExceeded":
+ return FailQuota
+ case "unauthorized":
+ return FailAuth
+ }
+ return FailTransient
}
+
+// CodexQuotaError reports whether a failed turn's error is the account's
+// usage limit (codexErrorInfo usageLimitExceeded).
+func CodexQuotaError(turnError json.RawMessage) bool { return CodexFailure(turnError) == FailQuota }
diff --git a/internal/runner/thin/bridge.go b/internal/runner/thin/bridge.go
index 4d448a62..f4e99735 100644
--- a/internal/runner/thin/bridge.go
+++ b/internal/runner/thin/bridge.go
@@ -56,6 +56,16 @@ func (b *bridge) Call(ctx context.Context, person, turn string, attempt int64, n
useID = "u" + strings.ToLower(rand.Text())
}
base := turn + "/" + itoa(attempt) + "/" + useID
+ if writeTool(name) {
+ return b.ledgered(ctx, turn, attempt, name, base, args, func(base string, args json.RawMessage) (string, bool) {
+ return b.call(ctx, person, turn, attempt, name, base, args)
+ })
+ }
+ return b.call(ctx, person, turn, attempt, name, base, args)
+}
+
+// call runs one tool under its call id (base).
+func (b *bridge) call(ctx context.Context, person, turn string, attempt int64, name, base string, args json.RawMessage) (string, bool) {
call := wire.ToolCall{CallID: base, TurnID: turn, Attempt: attempt, Name: name, Args: args}
switch name {
case wire.ToolCreateProject:
diff --git a/internal/runner/thin/claude.go b/internal/runner/thin/claude.go
index ebb3ee20..62f4f559 100644
--- a/internal/runner/thin/claude.go
+++ b/internal/runner/thin/claude.go
@@ -205,6 +205,9 @@ type claudeProcess struct {
tool *toolSocket
workspace string
scratch string
+ // exitErr is Wait's verdict, read only after exited closes: nil only
+ // when the containment verified the namespace's exit.
+ exitErr error
}
func (c *coordBase) log(msg string, err error) {
@@ -418,11 +421,13 @@ func (c *claudeCoordinator) Turn(ctx context.Context, in TurnInput, emit func(st
case "turn.completed", "turn.failed":
res, ok := claude.ParseResult(ev.Payload)
if !ok || res.Failed {
- c.stop(false)
+ proven := c.stop(false)
// Refused on quota: the provider said so with a
- // rejected rate limit in this turn.
+ // rejected rate limit in this turn. Another
+ // connection may take the turn over only once this
+ // attempt's exit is proven.
if seen != nil && seen.Limited {
- return TurnResult{Reason: "limited", Limit: seen}
+ return TurnResult{Reason: "limited", Limit: seen, Proven: proven}
}
return TurnResult{Reason: "provider_failed", Seen: seen}
}
@@ -555,6 +560,9 @@ func (c *coordBase) prompt(fresh bool, in TurnInput, catalog []wire.RepoInfo) (s
case wire.TurnExplore:
b.WriteString("\n" + explorePrompt(c.desk.State().Namespaces, ns, catalog) + c.o.MoveInNote)
default:
+ if len(in.Done) > 0 {
+ b.WriteString("\n" + doneNote(in.Done))
+ }
if b.Len() == 0 {
return in.Text, nil
}
@@ -563,6 +571,19 @@ func (c *coordBase) prompt(fresh bool, in TurnInput, catalog []wire.RepoInfo) (s
return b.String(), ns
}
+// doneNote tells a turn running again what it already did, so the person
+// gets one task, one question, one change: calling one of these again
+// returns its recorded result and does nothing more.
+func doneNote(done []string) string {
+ var b strings.Builder
+ b.WriteString("[Equipo: you already started answering this message on another connection, which stopped. Already done in this turn (do not repeat them; calling one again only returns its result):\n")
+ for _, d := range done {
+ b.WriteString("- " + d + "\n")
+ }
+ b.WriteString("Carry on from there.]\n")
+ return b.String()
+}
+
// namespacesOf lists the namespaces the catalog reaches, sorted.
func namespacesOf(catalog []wire.RepoInfo) []string {
out := []string{}
@@ -809,7 +830,7 @@ func (c *claudeCoordinator) start(ctx context.Context) (err error) {
go func() {
wctx, done := context.WithCancel(context.Background())
defer done()
- _, _ = p.process.Wait(wctx)
+ _, p.exitErr = p.process.Wait(wctx)
close(p.exited)
}()
c.proc = p
@@ -819,11 +840,12 @@ func (c *claudeCoordinator) start(ctx context.Context) (err error) {
// stop ends the process. A clean stop closes stdin and waits for the CLI
// to exit; otherwise the namespace is killed. Either way the exit is
// observed by the containment before the copy and scratch are removed.
-func (c *claudeCoordinator) stop(clean bool) {
+func (c *claudeCoordinator) stop(clean bool) bool {
p := c.proc
if p == nil {
- return
+ return true
}
+ proven := p.process == nil
c.proc = nil
if p.process != nil {
if clean {
@@ -836,6 +858,7 @@ func (c *claudeCoordinator) stop(clean bool) {
p.cancel()
select {
case <-p.exited:
+ proven = p.exitErr == nil
case <-time.After(30 * time.Second):
c.log("coordinator stop", errors.New("exit not observed"))
}
@@ -844,6 +867,7 @@ func (c *claudeCoordinator) stop(clean bool) {
}
}
c.cleanup(p)
+ return proven
}
func (c *claudeCoordinator) cleanup(p *claudeProcess) {
diff --git a/internal/runner/thin/codex.go b/internal/runner/thin/codex.go
index 12dbefaf..30ffee86 100644
--- a/internal/runner/thin/codex.go
+++ b/internal/runner/thin/codex.go
@@ -80,6 +80,7 @@ type codexProcess struct {
policy provider.Policy
tool *toolSocket
scratch string
+ exitErr error
}
func (c *codexCoordinator) Close() {
@@ -289,17 +290,19 @@ func (c *codexCoordinator) Turn(ctx context.Context, in TurnInput, emit func(str
}
usage.Model = c.account.Model
if t.Status != "completed" {
- c.stop(false)
+ proven := c.stop(false)
switch {
case ctx.Err() != nil || t.Status == "interrupted":
return TurnResult{Reason: "cancelled"}
- case connect.CodexQuotaError(t.Error) || seen != nil && seen.Limited:
+ case connect.CodexFailure(t.Error) == connect.FailQuota || seen != nil && seen.Limited:
l := connect.Limit{Limited: true}
if seen != nil {
l = *seen
l.Limited = true
}
- return TurnResult{Reason: "limited", Limit: &l, Plan: plan}
+ return TurnResult{Reason: "limited", Limit: &l, Plan: plan, Proven: proven}
+ case connect.CodexFailure(t.Error) == connect.FailAuth:
+ return TurnResult{Reason: "sign_in_again", SignIn: true, Proven: proven}
}
return TurnResult{Reason: "provider_failed", Seen: seen, Plan: plan}
}
@@ -415,7 +418,7 @@ func (c *codexCoordinator) start(ctx context.Context) (err error) {
p.rpc = connect.NewAppServer(p.process.Stdout(), p.process.Stdin())
go func() { _, _ = io.Copy(io.Discard, io.LimitReader(p.process.Stderr(), 1<<20)) }()
go func() {
- _, _ = p.process.Wait(context.Background())
+ _, p.exitErr = p.process.Wait(context.Background())
close(p.exited)
}()
sctx, done := context.WithTimeout(ctx, 30*time.Second)
@@ -481,11 +484,12 @@ func (c *codexCoordinator) start(ctx context.Context) (err error) {
// stop ends the process; the exit is observed by the containment before
// the copy and scratch are removed.
-func (c *codexCoordinator) stop(clean bool) {
+func (c *codexCoordinator) stop(clean bool) bool {
p := c.proc
if p == nil {
- return
+ return true
}
+ proven := p.process == nil
c.proc = nil
if p.process != nil {
if clean {
@@ -498,12 +502,14 @@ func (c *codexCoordinator) stop(clean bool) {
p.cancel()
select {
case <-p.exited:
+ proven = p.exitErr == nil
case <-time.After(30 * time.Second):
c.log("codex coordinator stop", errors.New("exit not observed"))
}
c.syncOut(p)
}
c.cleanup(p)
+ return proven
}
func (c *codexCoordinator) cleanup(p *codexProcess) {
diff --git a/internal/runner/thin/conns.go b/internal/runner/thin/conns.go
index 95233960..4a282d76 100644
--- a/internal/runner/thin/conns.go
+++ b/internal/runner/thin/conns.go
@@ -159,6 +159,16 @@ func (c *Conns) Choose(ctx context.Context, person, role, current string, avoid
return runner.AccountBinding{}, connect.Choice{}, err
}
mine := c.Mine(person)
+ // Only a checked connection is chosen: one never checked (just added
+ // by the terminal login, or first seen after a restage) is checked now.
+ for _, b := range mine {
+ c.mu.Lock()
+ unknown := c.live[b.ID].State == ""
+ c.mu.Unlock()
+ if unknown && connect.Capable(b.Provider, role) {
+ c.checkOne(ctx, b)
+ }
+ }
c.mu.Lock()
var cs []connect.Candidate
for _, b := range mine {
@@ -306,8 +316,9 @@ func (c *Conns) Held() []wire.HeldConnection {
// fails marks the connection sign_in_again (the provider revoked it) or
// error; one that succeeds clears both.
func (c *Conns) Loop(ctx context.Context) {
- // The first check waits so it does not contend with a first turn.
- wait := 2 * time.Minute
+ // The first check waits a little so it does not contend with a first
+ // turn (a turn checks a connection it would choose itself).
+ wait := 20 * time.Second
for {
select {
case <-ctx.Done():
@@ -328,21 +339,29 @@ func (c *Conns) Check(ctx context.Context) {
if b.Provider != "claude" && b.Provider != "codex" {
continue
}
- direct, err := c.Runner.DirectBinding(b)
- if err == nil {
- var lease *provider.AccountLease
- lease, err = provider.OpenRuntimeCopy(ctx, direct, c.Refresh, c.LockWait)
- if lease != nil {
- lease.Close()
- }
- }
+ c.checkOne(ctx, b)
if ctx.Err() != nil {
return
}
- c.checked(b.ID, err)
}
}
+// checkOne refreshes one connection with its CLI under the source lock.
+func (c *Conns) checkOne(ctx context.Context, b runner.AccountBinding) {
+ direct, err := c.Runner.DirectBinding(b)
+ if err == nil {
+ var lease *provider.AccountLease
+ lease, err = provider.OpenRuntimeCopy(ctx, direct, c.Refresh, c.LockWait)
+ if lease != nil {
+ lease.Close()
+ }
+ }
+ if ctx.Err() != nil {
+ return
+ }
+ c.checked(b.ID, err)
+}
+
// checked records one refresh's outcome.
func (c *Conns) checked(id string, err error) {
c.mu.Lock()
@@ -351,6 +370,10 @@ func (c *Conns) checked(id string, err error) {
switch {
case err == nil && (cs.State == wire.ConnSignInAgain || cs.State == wire.ConnError || cs.State == ""):
cs.State = wire.ConnHealthy
+ case errors.Is(err, provider.ErrAccountBusy) && cs.State == "":
+ // Another process holds the home's lock for its own refresh: the
+ // account is in use, so it is signed in.
+ cs.State = wire.ConnHealthy
case errors.Is(err, provider.ErrLoginRequired):
cs.State = wire.ConnSignInAgain
case err != nil && !errors.Is(err, provider.ErrAccountBusy):
@@ -368,6 +391,14 @@ func (c *Conns) checked(id string, err error) {
}
}
+// SignInAgain records a provider's refusal of a connection's credential.
+func (c *Conns) SignInAgain(id string) {
+ if c.load(context.Background()) != nil {
+ return
+ }
+ c.checked(id, provider.ErrLoginRequired)
+}
+
// Forget drops a connection's state (it was signed out or never finished).
func (c *Conns) Forget(id string) {
c.mu.Lock()
diff --git a/internal/runner/thin/effects.go b/internal/runner/thin/effects.go
new file mode 100644
index 00000000..ad817b0c
--- /dev/null
+++ b/internal/runner/thin/effects.go
@@ -0,0 +1,166 @@
+package thin
+
+import (
+ "context"
+ "database/sql"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "slices"
+ "strings"
+)
+
+// Exactly-once across attempts. A turn that moves to another connection
+// runs again as a new attempt in a new session, and that model may call
+// the same tools again. Every write tool's effect is recorded here before
+// it runs and with its result after; in a later attempt of the same turn
+// a call of a tool the turn already ran is answered from that record and
+// never runs twice. A recorded call whose result the runner never saw is
+// reconciled by sending it again under its own call id: the instance
+// answers a call id it has seen with its stored result.
+
+const effectSchema = `
+CREATE TABLE IF NOT EXISTS turn_effects (turn_id TEXT NOT NULL, attempt INTEGER NOT NULL, seq INTEGER NOT NULL, name TEXT NOT NULL, args TEXT NOT NULL, call_id TEXT NOT NULL, done INTEGER NOT NULL DEFAULT 0, result TEXT NOT NULL DEFAULT '', is_error INTEGER NOT NULL DEFAULT 0, replayed_in INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (turn_id, attempt, seq));
+`
+
+// writeTools change something outside the model's session.
+var writeTools = []string{"add_project", "create_project", "set_project_home", "ask_person", "write_note", "record_task", "add_finding", "start_task", "cancel_task", "add_report"}
+
+func writeTool(name string) bool { return slices.Contains(writeTools, name) }
+
+// effect is one recorded write.
+type effect struct {
+ Turn, Name, Args, CallID, Result string
+ Attempt, Seq int64
+ Done, IsError bool
+}
+
+func canonArgs(raw json.RawMessage) string {
+ var v any
+ if json.Unmarshal(raw, &v) == nil {
+ raw, _ = json.Marshal(v)
+ }
+ return string(raw)
+}
+
+// startEffect records a write before it runs.
+func (s *State) startEffect(ctx context.Context, turn string, attempt int64, name string, args json.RawMessage, callID string) (int64, error) {
+ var seq int64
+ err := s.tx(ctx, func(t *sql.Tx) error {
+ if err := t.QueryRow("SELECT coalesce(max(seq),0)+1 FROM turn_effects WHERE turn_id=? AND attempt=?", turn, attempt).Scan(&seq); err != nil {
+ return err
+ }
+ _, err := t.Exec("INSERT INTO turn_effects(turn_id, attempt, seq, name, args, call_id) VALUES(?,?,?,?,?,?)", turn, attempt, seq, name, canonArgs(args), callID)
+ return err
+ })
+ return seq, err
+}
+
+// endEffect records a write's result.
+func (s *State) endEffect(ctx context.Context, turn string, attempt, seq int64, result string, isError bool) error {
+ _, err := s.db.ExecContext(context.WithoutCancel(ctx), "UPDATE turn_effects SET done=1, result=?, is_error=? WHERE turn_id=? AND attempt=? AND seq=?", result, isError, turn, attempt, seq)
+ return err
+}
+
+// earlierEffect claims the write an earlier attempt of the turn made that
+// this call repeats: the same tool with the same arguments, else the
+// earliest unclaimed one of that tool. It is claimed for this attempt,
+// so each recorded write answers one call.
+func (s *State) earlierEffect(ctx context.Context, turn string, attempt int64, name string, args json.RawMessage) (effect, bool, error) {
+ var out effect
+ found := false
+ err := s.tx(ctx, func(t *sql.Tx) error {
+ rows, err := t.Query("SELECT attempt, seq, name, args, call_id, done, result, is_error FROM turn_effects WHERE turn_id=? AND attempt<? AND name=? AND replayed_in=0 ORDER BY attempt, seq", turn, attempt, name)
+ if err != nil {
+ return err
+ }
+ var all []effect
+ for rows.Next() {
+ e := effect{Turn: turn}
+ if err = rows.Scan(&e.Attempt, &e.Seq, &e.Name, &e.Args, &e.CallID, &e.Done, &e.Result, &e.IsError); err != nil {
+ rows.Close()
+ return err
+ }
+ all = append(all, e)
+ }
+ rows.Close()
+ if len(all) == 0 {
+ return nil
+ }
+ out, found = all[0], true
+ want := canonArgs(args)
+ for _, e := range all {
+ if e.Args == want {
+ out = e
+ break
+ }
+ }
+ _, err = t.Exec("UPDATE turn_effects SET replayed_in=? WHERE turn_id=? AND attempt=? AND seq=?", attempt, turn, out.Attempt, out.Seq)
+ return err
+ })
+ return out, found, err
+}
+
+// doneEarlier lists what earlier attempts of the turn already did, for
+// the new attempt's prompt.
+func (s *State) doneEarlier(ctx context.Context, turn string, attempt int64) []string {
+ rows, err := s.db.QueryContext(ctx, "SELECT name, done, result, is_error FROM turn_effects WHERE turn_id=? AND attempt<? ORDER BY attempt, seq", turn, attempt)
+ if err != nil {
+ return nil
+ }
+ defer rows.Close()
+ var out []string
+ for rows.Next() {
+ var name, result string
+ var done, isError bool
+ if rows.Scan(&name, &done, &result, &isError) != nil {
+ return out
+ }
+ switch {
+ case !done:
+ out = append(out, name+": sent; its result is replayed if you call it again")
+ case isError:
+ out = append(out, name+": refused: "+clip(strings.TrimSpace(result), 200))
+ default:
+ out = append(out, name+": "+clip(strings.TrimSpace(result), 300))
+ }
+ }
+ return out
+}
+
+// errNotRecorded: an effect could not be recorded, so it does not run.
+var errNotRecorded = errors.New("tool effect not recorded")
+
+// ledgered runs a write tool once per turn across attempts: a repeat in
+// a later attempt is answered from the record (or, when the earlier
+// result was never seen, by the instance from its own record under the
+// earlier call id); a new write is recorded before and after it runs.
+func (b *bridge) ledgered(ctx context.Context, turn string, attempt int64, name, base string, args json.RawMessage, run func(base string, args json.RawMessage) (string, bool)) (string, bool) {
+ prior, ok, err := b.State.earlierEffect(ctx, turn, attempt, name, args)
+ if err != nil {
+ b.log("tool effect", err)
+ return toolTimeout, true
+ }
+ if ok {
+ if prior.Done {
+ return prior.Result, prior.IsError
+ }
+ // Sent before, answer unseen: the same call id again.
+ text, isError := run(prior.CallID, json.RawMessage(prior.Args))
+ if !(isError && text == toolTimeout) {
+ b.log("tool effect", b.State.endEffect(ctx, turn, prior.Attempt, prior.Seq, text, isError))
+ }
+ return text, isError
+ }
+ seq, err := b.State.startEffect(ctx, turn, attempt, name, args, base)
+ if err != nil {
+ b.log("tool effect", fmt.Errorf("%w: %v", errNotRecorded, err))
+ return toolTimeout, true
+ }
+ text, isError := run(base, args)
+ // No answer is not a result: the next attempt reconciles it.
+ if !(isError && text == toolTimeout) {
+ b.log("tool effect", b.State.endEffect(ctx, turn, attempt, seq, text, isError))
+ }
+ return text, isError
+}
diff --git a/internal/runner/thin/engine.go b/internal/runner/thin/engine.go
index f71e8a52..c93a7793 100644
--- a/internal/runner/thin/engine.go
+++ b/internal/runner/thin/engine.go
@@ -28,6 +28,10 @@ type TurnInput struct {
Received time.Time
// Activity reports thinking or a tool starting, by tool name only.
Activity func(kind, tool string)
+ // Done is what earlier attempts of this turn already did (tools and
+ // their recorded results), for a turn running again after it moved
+ // connection or after a restart.
+ Done []string
}
// TurnResult is a reply, or a failure with a fixed reason code. Limit is
@@ -42,8 +46,17 @@ type TurnResult struct {
Limit *connect.Limit
Seen *connect.Limit
Plan string
+ // SignIn: the provider refused the credential (the connection needs
+ // signing in again); the turn moves like a quota refusal.
+ SignIn bool
+ // Proven: the attempt's process exit was verified by the containment
+ // (set with Limit or SignIn); only then may another connection take
+ // the turn.
+ Proven bool
// Switched is set by the engine when the turn moved connection.
Switched *wire.Switched
+ // Failed is the usage of an attempt that ended without a reply.
+ Failed *wire.Usage
}
// ConnChooser is what the engine asks about connections (Conns).
@@ -52,6 +65,7 @@ type ConnChooser interface {
Limit(id string, l connect.Limit) time.Time
Observe(id string, l connect.Limit, plan string)
LimitedFrom(id string) *wire.Switched
+ SignInAgain(id string)
NextCheck(person string) time.Time
}
@@ -248,7 +262,7 @@ func (e *Engine) runOne(person string, w *worker, r run) {
if res.Reason == "cancelled" {
state = wire.TurnCancelled
}
- err = e.State.Report(e.ctx, r, nil, &wire.TurnReport{TurnID: r.TurnID, Attempt: r.Attempt, State: state, Reason: res.Reason})
+ err = e.State.Report(e.ctx, r, nil, &wire.TurnReport{TurnID: r.TurnID, Attempt: r.Attempt, State: state, Reason: res.Reason, Usage: res.Failed})
}
e.log("runner report", err)
e.Notify()
diff --git a/internal/runner/thin/failover.go b/internal/runner/thin/failover.go
index c6a2168c..37365085 100644
--- a/internal/runner/thin/failover.go
+++ b/internal/runner/thin/failover.go
@@ -54,6 +54,12 @@ func (e *Engine) converse(ctx context.Context, person string, w *worker, r *run,
w.coord.Close()
w.coord = nil
}
+ // A session the conversation went on without is stale: coming
+ // back to a connection starts afresh from the notebook and the
+ // tail, never resumes a session that missed turns.
+ if last, _ := e.State.meta(ctx, "conn:"+person); last != "" && last != b.ID {
+ e.log("runner session", e.State.deleteSession(ctx, person))
+ }
c, err := e.Open(person, b)
if err != nil {
e.log("coordinator open", err)
@@ -63,14 +69,30 @@ func (e *Engine) converse(ctx context.Context, person string, w *worker, r *run,
}
_ = choice
var offset int64
- res := w.coord.Turn(ctx, TurnInput{Person: person, TurnID: r.TurnID, Kind: r.Kind, Attempt: r.Attempt, Text: r.Text, PersonText: r.PersonText, Tail: r.Tail, Received: r.Received, Activity: act}, func(text string) {
+ var done []string
+ if r.Attempt > 1 {
+ done = e.State.doneEarlier(ctx, r.TurnID, r.Attempt)
+ }
+ res := w.coord.Turn(ctx, TurnInput{Person: person, TurnID: r.TurnID, Kind: r.Kind, Attempt: r.Attempt, Text: r.Text, PersonText: r.PersonText, Tail: r.Tail, Received: r.Received, Activity: act, Done: done}, func(text string) {
e.Emit(wire.DeltaReport{TurnID: r.TurnID, Attempt: r.Attempt, Offset: offset, Text: text})
offset += int64(len(text))
})
if e.Conns != nil && res.Seen != nil {
e.Conns.Observe(b.ID, *res.Seen, res.Plan)
}
- if res.Limit == nil || ctx.Err() != nil || e.Conns == nil {
+ if res.Limit != nil && e.Conns != nil {
+ e.Conns.Limit(b.ID, *res.Limit)
+ }
+ if res.SignIn && e.Conns != nil {
+ e.Conns.SignInAgain(b.ID)
+ }
+ if res.Reason != "" {
+ res.Failed = attemptUsage(res, b)
+ }
+ if res.Limit == nil && !res.SignIn || !res.Proven || ctx.Err() != nil || e.Conns == nil {
+ if res.Reason == "" && e.Conns != nil {
+ e.log("runner session", e.State.setMeta(context.WithoutCancel(ctx), "conn:"+person, b.ID))
+ }
res.Usage.Provider, res.Usage.Connection = b.Provider, b.ID
if res.Usage.Model == "" {
res.Usage.Model = b.Model
@@ -81,14 +103,17 @@ func (e *Engine) converse(ctx context.Context, person string, w *worker, r *run,
}
return res
}
- // Refused on quota: the attempt is over (its process stopped).
- e.Conns.Limit(b.ID, *res.Limit)
+ // Refused on quota, and the attempt's exit proven: a new attempt,
+ // advanced durably before anything runs, on the next connection.
if switched == nil {
switched = e.Conns.LimitedFrom(b.ID)
+ if res.SignIn {
+ switched = &wire.Switched{From: b.Provider}
+ }
}
w.coord.Close()
w.coord = nil
- if err := e.State.Retry(e.ctx, r); err != nil {
+ if err := e.State.Retry(e.ctx, r, attemptUsage(res, b)); err != nil {
e.log("runner retry", err)
return TurnResult{Reason: "limited"}
}
@@ -99,6 +124,20 @@ func (e *Engine) converse(ctx context.Context, person string, w *worker, r *run,
}
}
+// attemptUsage is an attempt's token use with what ran it, or nil when
+// the harness reported none.
+func attemptUsage(res TurnResult, b runner.AccountBinding) *wire.Usage {
+ u := res.Usage
+ if u.InputTokens+u.OutputTokens+u.CachedInputTokens+u.CacheWriteTokens+u.ReasoningOutputTokens == 0 {
+ return nil
+ }
+ u.Provider, u.Connection = b.Provider, b.ID
+ if u.Model == "" {
+ u.Model = b.Model
+ }
+ return &u
+}
+
// choose asks Conns for the person's coordinator connection; without
// Conns (engine tests) every turn runs on a zero binding.
func (e *Engine) choose(ctx context.Context, person, current string) (runner.AccountBinding, connect.Choice, error) {
@@ -125,12 +164,16 @@ func (e *Engine) waitConnection(ctx context.Context, person string, w *worker) b
return true
}
-// Hold reports a running turn as waiting for a connection (reason
-// no_connection) or, with an empty reason, as going again. The run stays
-// held; only the instance's view changes.
+// Hold reports a held turn as waiting for a connection (reason
+// no_connection) or, with an empty reason, as running again. The run
+// stays held here; only the instance's view changes.
func (s *State) Hold(ctx context.Context, r run, reason string) error {
+ state := wire.TurnRunning
+ if reason != "" {
+ state = wire.TurnWaiting
+ }
return s.tx(ctx, func(t *sql.Tx) error {
- return s.enqueue(t, wire.FrameTurn, r.TurnID, wire.TurnReport{TurnID: r.TurnID, Attempt: r.Attempt, State: wire.TurnRunning, Reason: reason})
+ return s.enqueue(t, wire.FrameTurn, r.TurnID, wire.TurnReport{TurnID: r.TurnID, Attempt: r.Attempt, State: state, Reason: reason})
})
}
@@ -138,7 +181,7 @@ func (s *State) Hold(ctx context.Context, r run, reason string) error {
// refused: the instance learns of it (state running, the new attempt)
// in the same transaction, so a draft of the old attempt is dropped and
// a cancel names the new one.
-func (s *State) Retry(ctx context.Context, r *run) error {
+func (s *State) Retry(ctx context.Context, r *run, used *wire.Usage) error {
err := s.tx(ctx, func(t *sql.Tx) error {
res, err := t.Exec("UPDATE runs SET attempt=attempt+1 WHERE turn_id=? AND attempt=? AND state=?", r.TurnID, r.Attempt, runRunning)
if err != nil {
@@ -147,6 +190,12 @@ func (s *State) Retry(ctx context.Context, r *run) error {
if n, _ := res.RowsAffected(); n != 1 {
return errors.New("run not held")
}
+ if used != nil {
+ // What the refused attempt used, recorded against it.
+ if err = s.enqueue(t, wire.FrameTurn, r.TurnID, wire.TurnReport{TurnID: r.TurnID, Attempt: r.Attempt, State: wire.TurnRunning, Usage: used}); err != nil {
+ return err
+ }
+ }
return s.enqueue(t, wire.FrameTurn, r.TurnID, wire.TurnReport{TurnID: r.TurnID, Attempt: r.Attempt + 1, State: wire.TurnRunning})
})
if err == nil {
diff --git a/internal/runner/thin/state.go b/internal/runner/thin/state.go
index d674606b..c6a867d1 100644
--- a/internal/runner/thin/state.go
+++ b/internal/runner/thin/state.go
@@ -54,7 +54,7 @@ func OpenState(ctx context.Context, dir string) (*State, error) {
return nil, err
}
d.SetMaxOpenConns(1)
- if _, err = d.ExecContext(ctx, schema+stepSchema+watchSchema+askSchema+connSchema+connectSchema); err != nil {
+ if _, err = d.ExecContext(ctx, schema+stepSchema+watchSchema+askSchema+connSchema+connectSchema+effectSchema); err != nil {
d.Close()
return nil, err
}
diff --git a/internal/thintest/connections_contract_test.go b/internal/thintest/connections_contract_test.go
index 5b3d8b46..0317c60a 100644
--- a/internal/thintest/connections_contract_test.go
+++ b/internal/thintest/connections_contract_test.go
@@ -160,11 +160,16 @@ func TestContractHeldTurnAndSwitch(t *testing.T) {
}
runner.Send(r.ctx, "a-1", wire.FrameAck, wire.Ack{ID: f.ID})
turn := sent.Turn.ID
- runner.Send(r.ctx, "r-hold", wire.FrameTurn, wire.TurnReport{TurnID: turn, Attempt: 1, State: wire.TurnRunning, Reason: wire.ReasonNoConnection})
+ runner.Send(r.ctx, "r-hold", wire.FrameTurn, wire.TurnReport{TurnID: turn, Attempt: 1, State: wire.TurnWaiting, Reason: wire.ReasonNoConnection})
r.wait("held", func(c *Conversation) bool {
v := c.Turns[turn]
- return v.State == wire.TurnRunning && v.Reason == wire.ReasonNoConnection
+ return v.State == wire.TurnWaiting && v.Reason == wire.ReasonNoConnection
})
+ // A message sent while it waits joins the queue behind it.
+ later, err := r.client.Send(r.ctx, "still there?", "k-held-2")
+ if err != nil || later.Turn.State != wire.TurnQueued || later.Turn.ID == turn {
+ t.Fatalf("second message %+v %v", later.Turn, err)
+ }
page := r.inst.Get(t, "/conversation")
if !strings.Contains(page, "data-no-connection") || !strings.Contains(page, "Nothing can answer right now.") || strings.Contains(page, "Send your message again") {
t.Fatalf("held card missing from the page")
diff --git a/internal/wire/api.go b/internal/wire/api.go
index 320dc25b..fe5bec21 100644
--- a/internal/wire/api.go
+++ b/internal/wire/api.go
@@ -16,6 +16,11 @@ import (
const (
TurnQueued = "queued"
TurnRunning = "running"
+ // TurnWaiting is a dispatched turn held by its runner because nothing
+ // the person connected can answer now (reason no_connection). It is
+ // not an ending: the turn goes on its own when a connection returns,
+ // and the person may cancel it.
+ TurnWaiting = "waiting"
TurnReplied = "replied"
TurnFailed = "failed"
TurnCancelled = "cancelled"
@@ -121,6 +126,9 @@ const (
)
// Terminal reports whether a turn state is final.
+// InFlight are the states of a turn that has not ended.
+var InFlight = []string{TurnQueued, TurnRunning, TurnWaiting}
+
func Terminal(state string) bool {
return state == TurnReplied || state == TurnFailed || state == TurnCancelled
}
diff --git a/internal/wire/frames.go b/internal/wire/frames.go
index bb438ffa..55ffe048 100644
--- a/internal/wire/frames.go
+++ b/internal/wire/frames.go
@@ -441,6 +441,9 @@ type TurnReport struct {
Attempt int64 `json:"attempt"`
State string `json:"state"`
Reason string `json:"reason"`
+ // Usage is what this attempt used when it ended without a reply
+ // (failed, cancelled, or refused on quota before a failover), or null.
+ Usage *Usage `json:"usage"`
}
// Failure reasons a runner may report. Anything else is refused.