Astra round 1: durable cleanups, step attempts, usage; preference
- Sign-out and a cancel that finds the connection saved are recorded in the transaction that consumes the frame and done again at startup; a late cancel lets go of the home lock before signing out. - A refused Engineering or Review attempt advances the step durably (usage per attempt, the instance takes the next attempt); with nothing left the step waits and resumes; Review fails over on a refused credential and marks it sign_in_again. - Codex usage: never subtract an unverified base; complete only with a verified base and the turn's completion seen; cancelled and timed out turns keep their usage; answers carry theirs. - The person's preference (Automatic, Claude or Codex): PUT/GET /api/v1/preferences, a durable frame to the runner, the choice moves a session to it at a turn's start; forget a signed-out record.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
31 files changed,
+1,149
−191
internal/equipo/chat/connections.go+113 −0internal/equipo/chat/http.go+38 −0internal/equipo/chat/questions.go+4 −0internal/equipo/chat/tasks.go+17 −4internal/fakeclaude/fake.go+9 −0internal/fakecodex/fake.go+13 −7internal/headless/ask_test.go+7 −0internal/headless/connections_test.go+178 −7internal/headless/env_test.go+22 −1internal/runner/connect/choose.go+33 −12internal/runner/connect/choose_test.go+25 −18internal/runner/connect/usage.go+91 −47internal/runner/connect/usage_test.go+45 −21internal/runner/thin/ask.go+9 −0internal/runner/thin/codex.go+9 −7internal/runner/thin/connector.go+114 −24internal/runner/thin/connector_test.go+194 −0internal/runner/thin/conns.go+49 −1internal/runner/thin/engineer.go+35 −15internal/runner/thin/judge.go+20 −12internal/runner/thin/link.go+7 −0internal/runner/thin/step.go+53 −10internal/thintest/client.go+19 −0internal/wire/connections.go+33 −0internal/wire/connections_test.go+1 −1internal/wire/frames.go+3 −1internal/wire/wire_test.go+2 −2internal/wire/wiretest/fixtures.go+3 −1internal/wire/wiretest/testdata/api/event-preference.json+1 −0internal/wire/wiretest/testdata/api/preferences.json+1 −0internal/wire/wiretest/testdata/frames/preference.json+1 −0
Intent
diff --git a/internal/equipo/chat/connections.go b/internal/equipo/chat/connections.go| index 7a40c82e..d15e45fa 100644 |
| --- a/internal/equipo/chat/connections.go |
| +++ b/internal/equipo/chat/connections.go |
| @@ -132,6 +132,15 @@ func (t *txn) connections(person string) ([]connectionRecord, error) { |
| // person: only the runner's own person's. |
| func (t *txn) helloConnections(l Lease, held []wire.HeldConnection) error { |
| person, runner := l.Runner.Person, l.Runner.RunnerID |
| + // The preference goes again with every hello: a runner with a fresh |
| + // state learns it, one that has it ignores the same revision. |
| + if value, _, revision, err := t.settingRevision(preferenceKey(person)); err != nil { |
| + return err |
| + } else if revision > 0 { |
| + if err := t.command(person, wire.FramePreference, wire.PreferenceCommand{Person: person, Provider: value, Revision: revision}); err != nil { |
| + return err |
| + } |
| + } |
| rows, err := t.connections(person) |
| if err != nil { |
| return err |
| @@ -235,10 +244,114 @@ func (t *txn) connectionReport(l Lease, v *wire.ConnectionReport) error { |
| return err |
| } |
| r.LocalID = v.LocalID |
| + // Connect again: the same account, signed out before, is this one |
| + // now; its old record goes. |
| + if r.Label != "" { |
| + if err := t.forgetSignedOut(r.Person, r.Provider, r.Label, r.ID); err != nil { |
| + return err |
| + } |
| + } |
| } |
| return t.saveConnection(&r, false) |
| } |
| +// forgetSignedOut removes the person's signed-out records of one account |
| +// (provider and label), except keep, each with its last event. |
| +func (t *txn) forgetSignedOut(person, provider, label, keep string) error { |
| + var rows []connectionRecord |
| + if err := t.db.Where("person = ? AND provider = ? AND label = ? AND state = ? AND id <> ?", person, provider, label, wire.ConnSignedOut, keep).Find(&rows).Error; err != nil { |
| + return err |
| + } |
| + for i := range rows { |
| + if err := t.forget(&rows[i]); err != nil { |
| + return err |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +// forget deletes a record the runner no longer holds; its event says |
| +// forgotten so every client drops it. |
| +func (t *txn) forget(r *connectionRecord) error { |
| + if err := t.db.Delete(&connectionRecord{}, "id = ?", r.ID).Error; err != nil { |
| + return err |
| + } |
| + r.Revision++ |
| + r.State, r.UpdatedAt = wire.ConnForgotten, t.now() |
| + return t.event(r.Person, wire.EventConnection, "connection", r.ID, r.Revision, "", "", 0, connectionView(*r)) |
| +} |
| + |
| +// Forget removes one of the person's connections that is signed out, or |
| +// an attempt that ended: the record only, the runner holds nothing of it. |
| +func (s *Store) Forget(ctx context.Context, person, id string) error { |
| + return s.tx(ctx, func(t *txn) error { |
| + if err := s.authority.CurrentPerson(ctx, t.db); err != nil { |
| + return err |
| + } |
| + var r connectionRecord |
| + if err := t.db.Where("id = ? AND person = ?", id, person).First(&r).Error; errors.Is(err, gorm.ErrRecordNotFound) { |
| + return ErrNotFound |
| + } else if err != nil { |
| + return err |
| + } |
| + if r.State != wire.ConnSignedOut && !(r.State == wire.ConnError && r.LocalID == "") { |
| + return ErrConflict |
| + } |
| + return t.forget(&r) |
| + }) |
| +} |
| + |
| +// preferenceKey is the person's preferred provider in chat_settings |
| +// ("" is Automatic). |
| +func preferenceKey(person string) string { return "prefer:" + person } |
| + |
| +// Preference reads the person's preference. |
| +func (s *Store) Preference(ctx context.Context, person string) (out wire.Preferences, err error) { |
| + err = s.read(ctx, func(tx *gorm.DB) error { |
| + if err := s.authority.CurrentPerson(ctx, tx); err != nil { |
| + return err |
| + } |
| + value, _, revision, err := (&txn{s: s, db: tx}).settingRevision(preferenceKey(person)) |
| + out = wire.Preferences{Provider: value, Revision: revision} |
| + return err |
| + }) |
| + return out, err |
| +} |
| + |
| +// SetPreference records the person's preference against the revision |
| +// they saw (ErrConflict when it moved) and tells their runner, so its |
| +// choice has it offline. The same preference again changes nothing. |
| +func (s *Store) SetPreference(ctx context.Context, person string, in wire.Preferences) (out wire.Preferences, err error) { |
| + if !wire.PreferenceProviders[in.Provider] { |
| + return out, ErrInvalid |
| + } |
| + err = s.tx(ctx, func(t *txn) error { |
| + if err := s.authority.CurrentPerson(ctx, t.db); err != nil { |
| + return err |
| + } |
| + value, _, revision, err := t.settingRevision(preferenceKey(person)) |
| + if err != nil { |
| + return err |
| + } |
| + if in.Revision != revision { |
| + return ErrConflict |
| + } |
| + if value == in.Provider && revision > 0 { |
| + out = wire.Preferences{Provider: value, Revision: revision} |
| + return nil |
| + } |
| + if revision, err = t.setSetting(preferenceKey(person), in.Provider, person); err != nil { |
| + return err |
| + } |
| + out = wire.Preferences{Provider: in.Provider, Revision: revision} |
| + if err := t.event(person, wire.EventPreference, "preference", person, revision, "", "", 0, out); err != nil { |
| + return err |
| + } |
| + return t.command(person, wire.FramePreference, wire.PreferenceCommand{Person: person, Provider: in.Provider, Revision: revision}) |
| + }) |
| + return out, err |
| +} |
| + |
| // Connections lists the person's own connections, every runner. |
| func (s *Store) Connections(ctx context.Context, person string) (out []wire.Connection, err error) { |
| out = []wire.Connection{} |
diff --git a/internal/equipo/chat/http.go b/internal/equipo/chat/http.go| index bf68c532..b5ebf8b5 100644 |
| --- a/internal/equipo/chat/http.go |
| +++ b/internal/equipo/chat/http.go |
| @@ -88,6 +88,9 @@ func (h *HTTP) Mount(r chi.Router) { |
| r.Get("/connections/{id}", h.thinOr("GET /connections/{id}", thinConnection, h.bearer(h.connection))) |
| r.Post("/connections/{id}/cancel", h.bearer(h.cancelConnection)) |
| r.Delete("/connections/{id}", h.thinOr("DELETE /connections/{id}", thinConnection, h.bearer(h.signOut))) |
| + r.Post("/connections/{id}/forget", h.bearer(h.forget)) |
| + r.Get("/preferences", h.bearer(h.preferences)) |
| + r.Put("/preferences", h.bearer(h.setPreferences)) |
| r.Get("/events", h.events) |
| } |
| @@ -138,6 +141,41 @@ func (h *HTTP) signOut(w http.ResponseWriter, r *http.Request, p personapi.Perso |
| writeJSON(w, http.StatusAccepted, out) |
| } |
| +// forget is POST /api/v1/connections/{id}/forget: a signed-out record, |
| +// or an attempt that ended, goes from the list (204). |
| +func (h *HTTP) forget(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) { |
| + if err := h.Store.Forget(r.Context(), p.Address, chi.URLParam(r, "id")); err != nil { |
| + h.fail(w, r, err) |
| + return |
| + } |
| + w.WriteHeader(http.StatusNoContent) |
| +} |
| + |
| +func (h *HTTP) preferences(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) { |
| + out, err := h.Store.Preference(r.Context(), p.Address) |
| + if err != nil { |
| + h.fail(w, r, err) |
| + return |
| + } |
| + writeJSON(w, 200, out) |
| +} |
| + |
| +// setPreferences is PUT /api/v1/preferences {provider, revision}: 409 |
| +// when the revision moved. |
| +func (h *HTTP) setPreferences(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) { |
| + var in wire.Preferences |
| + if err := readJSON(r, &in); err != nil { |
| + h.fail(w, r, err) |
| + return |
| + } |
| + out, err := h.Store.SetPreference(r.Context(), p.Address, in) |
| + if err != nil { |
| + h.fail(w, r, err) |
| + return |
| + } |
| + writeJSON(w, 200, out) |
| +} |
| + |
| func (h *HTTP) cancelConnection(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) { |
| out, err := h.Store.CancelConnection(r.Context(), p.Address, chi.URLParam(r, "id")) |
| if err != nil { |
diff --git a/internal/equipo/chat/questions.go b/internal/equipo/chat/questions.go| index e45bef49..e104bdd0 100644 |
| --- a/internal/equipo/chat/questions.go |
| +++ b/internal/equipo/chat/questions.go |
| @@ -431,6 +431,10 @@ func (t *txn) answer(l Lease, v *wire.AnswerReport) error { |
| } |
| case wire.QuestionFailed, wire.QuestionCancelled: |
| q.State, q.Reason = v.State, firstSet(v.Reason, v.State) |
| + // What an unanswered attempt used is recorded too. |
| + if err := t.recordUsage(q.Asker, "ask", q.TaskID, q.ID, "", v.Usage); err != nil { |
| + return err |
| + } |
| default: |
| return ErrInvalid |
| } |
diff --git a/internal/equipo/chat/tasks.go b/internal/equipo/chat/tasks.go| index 65efe3da..9d49d1fd 100644 |
| --- a/internal/equipo/chat/tasks.go |
| +++ b/internal/equipo/chat/tasks.go |
| @@ -771,7 +771,15 @@ func (t *txn) stepReport(l Lease, v *wire.StepReport) error { |
| if primary != l.Runner.RunnerID { |
| return ErrForbidden |
| } |
| - if v.Attempt != s.Attempt { |
| + advanced := false |
| + switch { |
| + case v.Attempt == s.Attempt: |
| + case v.Attempt == s.Attempt+1 && v.State == wire.StepRunning && !wire.StepTerminal(s.State): |
| + // The runner moved the step to its next attempt after the provider |
| + // refused this one and its exit was proven (spec §3): same brief, |
| + // another connection. |
| + advanced = true |
| + default: |
| return nil |
| } |
| k, err := t.loadTask(s.TaskID) |
| @@ -780,6 +788,9 @@ func (t *txn) stepReport(l Lease, v *wire.StepReport) error { |
| } |
| now := t.now() |
| changed := false |
| + if advanced { |
| + s.Attempt, changed = v.Attempt, true |
| + } |
| if wire.StepTerminal(s.State) { |
| // Only the termination proof may still arrive for an ended attempt. |
| if v.State == s.State && v.Termination && !s.Terminated { |
| @@ -940,9 +951,11 @@ func cleanFindings(in []wire.Finding) []wire.Finding { |
| // namespace of an earlier process survives: the step has ended. A |
| // dispatch it has not acked is still on its way. |
| func (t *txn) syncSteps(l Lease, held []wire.StepRun) error { |
| - have := map[string]bool{} |
| + // The runner holds a step at this attempt or a later one it moved to |
| + // itself (a failover the instance has not heard of yet). |
| + have := map[string]int64{} |
| for _, h := range held { |
| - have[h.StepID+"/"+itoa64(h.Attempt)] = true |
| + have[h.StepID] = max(have[h.StepID], h.Attempt) |
| } |
| var rows []stepRecord |
| if err := t.db.Where("person = ? AND state IN ?", l.Runner.Person, []string{wire.StepQueued, wire.StepRunning}).Find(&rows).Error; err != nil { |
| @@ -950,7 +963,7 @@ func (t *txn) syncSteps(l Lease, held []wire.StepRun) error { |
| } |
| for i := range rows { |
| s := rows[i] |
| - if have[s.ID+"/"+itoa64(s.Attempt)] { |
| + if have[s.ID] >= s.Attempt { |
| continue |
| } |
| var unacked int64 |
diff --git a/internal/fakeclaude/fake.go b/internal/fakeclaude/fake.go| index 884814d1..bc9bff89 100644 |
| --- a/internal/fakeclaude/fake.go |
| +++ b/internal/fakeclaude/fake.go |
| @@ -699,6 +699,12 @@ func (f *fake) serve(stdin io.Reader, stdout, stderr io.Writer) int { |
| refuse() |
| continue |
| } |
| + // reviewauth:<email> refuses a Review step's credential. |
| + if m := reviewAuthWord.FindStringSubmatch(prompt); m != nil && m[1] == accountEmail() && strings.HasPrefix(prompt, "[Equipo: review]") { |
| + emit(map[string]any{"type": "assistant", "session_id": f.session, "parent_tool_use_id": nil, "message": map[string]any{"model": f.model, "id": fmt.Sprintf("msg_auth_%d", turn), "type": "message", "role": "assistant", "content": []any{map[string]string{"type": "text", "text": "Invalid API key"}}}, "error": "authentication_failed", "uuid": fmt.Sprintf("assistant-%d", turn)}) |
| + emit(map[string]any{"type": "result", "subtype": "success", "is_error": true, "result": "Invalid API key", "session_id": session, "num_turns": 1, "usage": map[string]int{"input_tokens": 0, "output_tokens": 0}, "terminal_reason": "completed", "result_index": turn - 1, "uuid": fmt.Sprintf("result-%d", turn)}) |
| + continue |
| + } |
| if strings.HasPrefix(prompt, "[Equipo: engineering]") { |
| newest = "" |
| reply = f.engineer(prompt, turn, emit) |
| @@ -835,6 +841,9 @@ var authWord = regexp.MustCompile(`\bauthrefused:([^\s|]+@[^\s|]+[a-z])`) |
| // reviewLimitWord is reviewlimit:<email>, for a Review step only. |
| var reviewLimitWord = regexp.MustCompile(`\breviewlimit:([^\s|]+@[^\s|]+[a-z])`) |
| +// reviewAuthWord is reviewauth:<email>, for a Review step only. |
| +var reviewAuthWord = regexp.MustCompile(`\breviewauth:([^\s|]+@[^\s|]+[a-z])`) |
| + |
| // stepLimitWord is steplimit:<email>, for an Engineering step only. |
| var stepLimitWord = regexp.MustCompile(`\bsteplimit:([^\s|]+@[^\s|]+[a-z])`) |
diff --git a/internal/fakecodex/fake.go b/internal/fakecodex/fake.go| index 51810403..92aaf9fe 100644 |
| --- a/internal/fakecodex/fake.go |
| +++ b/internal/fakecodex/fake.go |
| @@ -440,6 +440,10 @@ func (s *server) runTurn(thread, turn, prompt string, stop chan struct{}) { |
| ms, _ := strconv.Atoi(m[1]) |
| pause = time.Duration(ms) * time.Millisecond |
| } |
| + // Two requests' worth: half before the pause, the rest at the end. |
| + half := tokens{Input: len(prompt) / 8, Cached: len(prompt) / 16, Output: len(text) / 8, Reasoning: 3} |
| + full := tokens{Input: len(prompt) / 4, Cached: len(prompt) / 8, Output: len(text) / 4, Reasoning: 7} |
| + rest := tokens{full.Input - half.Input, full.Cached - half.Cached, full.Output - half.Output, full.Reasoning - half.Reasoning} |
| msg := "msg_" + turn[:8] |
| s.notify("item/started", map[string]any{"threadId": thread, "turnId": turn, "item": map[string]any{"id": msg, "type": "agentMessage", "text": ""}}) |
| words := strings.SplitAfter(text, " ") |
| @@ -447,6 +451,11 @@ func (s *server) runTurn(thread, turn, prompt string, stop chan struct{}) { |
| for i := 0; i < len(words); i += third { |
| chunk := strings.Join(words[i:min(i+third, len(words))], "") |
| s.notify("item/agentMessage/delta", map[string]any{"threadId": thread, "turnId": turn, "itemId": msg, "delta": chunk}) |
| + if i == 0 { |
| + // The first request's usage, as the pinned app-server sends it |
| + // mid-turn: a cancelled turn has figures too. |
| + s.usage(thread, turn, s.total.plus(half), half) |
| + } |
| if pause > 0 && i == 0 { |
| select { |
| case <-stop: |
| @@ -463,13 +472,10 @@ func (s *server) runTurn(thread, turn, prompt string, stop chan struct{}) { |
| } |
| s.notify("item/completed", map[string]any{"threadId": thread, "turnId": turn, "item": map[string]any{"id": msg, "type": "agentMessage", "text": text}}) |
| s.record(thread, prompt, text) |
| - // Two notices for the turn, each with the thread's running total (as |
| - // the pinned app-server sends them), the second resent once. |
| - half := tokens{Input: len(prompt) / 8, Cached: len(prompt) / 16, Output: len(text) / 8, Reasoning: 3} |
| - full := tokens{Input: len(prompt) / 4, Cached: len(prompt) / 8, Output: len(text) / 4, Reasoning: 7} |
| - s.usage(thread, turn, s.total.plus(half), half) |
| - s.usage(thread, turn, s.total.plus(full), full) |
| - s.usage(thread, turn, s.total.plus(full), full) |
| + // The second notice for the turn, with the thread's running total (as |
| + // the pinned app-server sends them), resent once. |
| + s.usage(thread, turn, s.total.plus(full), rest) |
| + s.usage(thread, turn, s.total.plus(full), rest) |
| s.total = s.total.plus(full) |
| s.saveTotal(thread, turn) |
| s.notify("account/rateLimits/updated", map[string]any{"rateLimits": s.limits(false)}) |
diff --git a/internal/headless/ask_test.go b/internal/headless/ask_test.go| index 2e825168..a7320b1e 100644 |
| --- a/internal/headless/ask_test.go |
| +++ b/internal/headless/ask_test.go |
| @@ -92,6 +92,10 @@ func scenarioAsk(t *testing.T, env *Env) { |
| if !strings.HasPrefix(q1.Answer, "From my session: "+eng.Summary) || !strings.Contains(q1.Answer, "The change: +") || !strings.Contains(q1.Answer, "the panes") || !strings.Contains(q1.Answer, "README.md starts: ") { |
| t.Fatalf("engineering answer %q (its step said %q)", q1.Answer, eng.Summary) |
| } |
| + // The answer's usage is recorded, as a turn's is. |
| + if got := env.AskUsage(t, q1.ID); len(got) != 1 || got[0] != "replied/true" { |
| + t.Fatalf("answer usage %v", got) |
| + } |
| // The question's own namespace is recorded against it, for the proof |
| // of its exit. |
| if ns := env.AskNamespace(t, q1.ID); ns == "" { |
| @@ -137,6 +141,9 @@ func scenarioAsk(t *testing.T, env *Env) { |
| t.Fatal(err) |
| } |
| s.wait(t, "cancelled", time.Minute, func(c *thintest.Conversation) bool { return c.Questions[q4.ID].State == wire.QuestionCancelled }) |
| + if got := env.AskUsage(t, q4.ID); len(got) != 1 || !strings.HasPrefix(got[0], "cancelled/") { |
| + t.Fatalf("cancelled answer usage %v", got) |
| + } |
| Witness[t.Name()] = map[string]any{"task": id, "engineering": c1.seconds(), "review": c2.seconds()} |
| // The person merges; the task is done, and for 14 days (Paul, |
diff --git a/internal/headless/connections_test.go b/internal/headless/connections_test.go| index 8d198cc1..9a1f6927 100644 |
| --- a/internal/headless/connections_test.go |
| +++ b/internal/headless/connections_test.go |
| @@ -4,6 +4,7 @@ import ( |
| "context" |
| "crypto/rand" |
| "encoding/json" |
| + "fmt" |
| "net/http" |
| "net/url" |
| "os" |
| @@ -110,6 +111,9 @@ func TestHeadlessConnections(t *testing.T) { |
| {"C4_claude_sign_in", connClaudeSignIn}, |
| {"C5_engineering_failover", connEngineeringFailover}, |
| {"C5_review_failover", connReviewFailover}, |
| + {"C5_engineering_waits", connEngineeringWaits}, |
| + {"C5_review_auth", connReviewAuth}, |
| + {"P1_preference", connPreference}, |
| {"C6_no_connection", connNoConnection}, |
| } { |
| t.Run(sc.name, func(t *testing.T) { |
| @@ -345,7 +349,8 @@ func connEngineeringFailover(t *testing.T, env *Env, inst *thintest.Instance, r |
| sent := s.send(t, text) |
| id := s.taskOf(t, sent.Turn.ID) |
| step := s.step(t, id, 5*time.Minute, wire.StepDone, wire.StepFailed) |
| - if step.State != wire.StepDone || !step.Pushed || step.Account != "claude-2" || step.Attempt != 1 { |
| + // The refused attempt and the one that ran are two attempts. |
| + if step.State != wire.StepDone || !step.Pushed || step.Account != "claude-2" || step.Attempt != 2 { |
| t.Fatalf("step %+v", step) |
| } |
| if step.Switched == nil || step.Switched.From != "claude" || step.Switched.ResetsAt == nil { |
| @@ -355,11 +360,92 @@ func connEngineeringFailover(t *testing.T, env *Env, inst *thintest.Instance, r |
| if !strings.Contains(page, "Claude was limited") { |
| t.Fatal("the task page does not show the switch") |
| } |
| - var rows int |
| - _ = inst.DB.Writer().QueryRow("SELECT count(*) FROM chat_usage WHERE step_id = ? AND role = 'engineering' AND connection = 'claude-2'", step.ID).Scan(&rows) |
| - if rows != 1 { |
| - t.Fatalf("step usage rows %d", rows) |
| + if got := stepUsage(t, inst, step.ID); got != "1/failed/claude-1 2/replied/claude-2" { |
| + t.Fatalf("step usage rows %q", got) |
| + } |
| +} |
| + |
| +// stepUsage is a step's usage rows as attempt/outcome/connection. |
| +func stepUsage(t *testing.T, inst *thintest.Instance, step string) string { |
| + t.Helper() |
| + rows, err := inst.DB.Writer().Query("SELECT attempt, outcome, connection FROM chat_usage WHERE step_id = ? ORDER BY attempt", step) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer rows.Close() |
| + var out []string |
| + for rows.Next() { |
| + var attempt int64 |
| + var outcome, conn string |
| + if err := rows.Scan(&attempt, &outcome, &conn); err != nil { |
| + t.Fatal(err) |
| + } |
| + out = append(out, fmt.Sprintf("%d/%s/%s", attempt, outcome, conn)) |
| + } |
| + return strings.Join(out, " ") |
| +} |
| + |
| +// C5, nothing left: the only connection refuses an Engineering step on |
| +// quota. The step does not fail: its next attempt waits, and runs on its |
| +// own once a connection is added. |
| +func connEngineeringWaits(t *testing.T, env *Env, inst *thintest.Instance, r *localRunner) { |
| + r.start(t) |
| + s := open(t, env) |
| + s.keep() |
| + text := "tool:record_task:oficina/sample|Fix the README typo|teh\ntool:start_task:$task|Fix it. steplimit:" + thintest.Owner + " edit:README.md|teh panes|the panes" |
| + sent := s.send(t, text) |
| + id := s.taskOf(t, sent.Turn.ID) |
| + var eng wire.Step |
| + s.wait(t, "second attempt", 2*time.Minute, func(c *thintest.Conversation) bool { |
| + for _, st := range c.Tasks[id].Steps { |
| + if st.Specialist == wire.SpecialistEngineering { |
| + eng = c.Steps[st.ID] |
| + } |
| + } |
| + return eng.Attempt == 2 |
| + }) |
| + time.Sleep(3 * time.Second) |
| + if v := s.conv.Steps[eng.ID]; wire.StepTerminal(v.State) { |
| + t.Fatalf("the step ended with nothing to run it: %+v", v) |
| + } |
| + r.addAccount(t, "claude", "claude-2", second) |
| + step := s.step(t, id, 3*time.Minute, wire.StepDone, wire.StepFailed) |
| + if step.State != wire.StepDone || step.Account != "claude-2" || step.Attempt != 2 { |
| + t.Fatalf("step %+v", step) |
| + } |
| +} |
| + |
| +// C5, Review's credential refused: the review moves to another |
| +// connection as a new attempt, and the refused one needs signing in again. |
| +func connReviewAuth(t *testing.T, env *Env, inst *thintest.Instance, r *localRunner) { |
| + r.addAccount(t, "claude", "claude-2", second) |
| + r.start(t) |
| + s := open(t, env) |
| + s.keep() |
| + text := "tool:record_task:oficina/sample|Fix the README typo|teh\ntool:start_task:$task|Fix it. reviewauth:" + second + " edit:README.md|teh panes|the panes" |
| + sent := s.send(t, text) |
| + id := s.taskOf(t, sent.Turn.ID) |
| + var review wire.Step |
| + s.wait(t, "review done", 5*time.Minute, func(c *thintest.Conversation) bool { |
| + for _, st := range c.Tasks[id].Steps { |
| + if st.Specialist == wire.SpecialistReview && wire.StepTerminal(c.Steps[st.ID].State) { |
| + review = c.Steps[st.ID] |
| + return true |
| + } |
| + } |
| + return false |
| + }) |
| + if review.State != wire.StepDone || review.Account != "claude-1" || review.Attempt != 2 || review.Switched == nil { |
| + t.Fatalf("review %+v", review) |
| } |
| + s.wait(t, "sign in again", time.Minute, func(c *thintest.Conversation) bool { |
| + for _, v := range c.Connections { |
| + if v.LocalID == "claude-2" { |
| + return v.State == wire.ConnSignInAgain |
| + } |
| + } |
| + return false |
| + }) |
| } |
| // C6: nothing can answer: the turn is held with the no_connection card |
| @@ -420,7 +506,7 @@ func connReviewFailover(t *testing.T, env *Env, inst *thintest.Instance, r *loca |
| } |
| return false |
| }) |
| - if review.State != wire.StepDone || review.Verdict != wire.VerdictApprove || review.Account != "claude-1" || review.ReviewLabel != wire.ReviewSameAccount { |
| + if review.State != wire.StepDone || review.Verdict != wire.VerdictApprove || review.Account != "claude-1" || review.ReviewLabel != wire.ReviewSameAccount || review.Attempt != 2 { |
| t.Fatalf("review %+v", review) |
| } |
| if review.Switched == nil || review.Switched.From != "claude" { |
| @@ -486,7 +572,8 @@ func connUsageRows(t *testing.T, env *Env, inst *thintest.Instance, r *localRunn |
| got = usageRows(t, inst, cancelled.Turn.ID) |
| return len(got) > 0 |
| }) |
| - if len(got) != 1 || got[0].Outcome != wire.OutcomeCancelled || got[0].Complete { |
| + // What the cancelled turn used before the cancel is kept, not complete. |
| + if len(got) != 1 || got[0].Outcome != wire.OutcomeCancelled || got[0].Complete || got[0].Input == nil || *got[0].Input == 0 { |
| t.Fatalf("cancelled rows %+v", got) |
| } |
| } |
| @@ -711,3 +798,87 @@ func clipText(s string, n int) string { |
| } |
| return s[:n] + "…" |
| } |
| + |
| +// P1: the person prefers Codex. The coordinator, on Claude, moves to |
| +// Codex at the next turn (a boundary), with the switched line; Automatic |
| +// again keeps it where it is (stickiness). A stale revision is refused, |
| +// and a preference never overrides health: Codex limited, the turn runs |
| +// on Claude. A signed-out record can be forgotten. |
| +func connPreference(t *testing.T, env *Env, inst *thintest.Instance, r *localRunner) { |
| + r.addAccount(t, "codex", "codex-1", second) |
| + r.start(t) |
| + s := open(t, env) |
| + first := s.send(t, "Hello.") |
| + replyOf(t, s, first.Turn.ID) |
| + if c := s.conv.Turns[first.Turn.ID].Connection; c != "claude-1" { |
| + t.Fatalf("first turn on %s", c) |
| + } |
| + p, err := env.Client.Preferences(s.ctx) |
| + if err != nil || p.Provider != "" || p.Revision != 0 { |
| + t.Fatalf("preferences %+v %v", p, err) |
| + } |
| + if p, err = env.Client.SetPreferences(s.ctx, wire.Preferences{Provider: "codex"}); err != nil || p.Revision != 1 { |
| + t.Fatalf("set %+v %v", p, err) |
| + } |
| + if _, err = env.Client.SetPreferences(s.ctx, wire.Preferences{Provider: "claude"}); err == nil { |
| + t.Fatal("a stale revision was taken") |
| + } |
| + // The runner has it once the frame lands; the next turn moves. |
| + deadline := time.Now().Add(30 * time.Second) |
| + var moved wire.Message |
| + var turn wire.Turn |
| + for { |
| + sent := s.send(t, "Next.") |
| + moved = replyOf(t, s, sent.Turn.ID) |
| + turn = s.conv.Turns[sent.Turn.ID] |
| + if turn.Connection == "codex-1" || time.Now().After(deadline) { |
| + break |
| + } |
| + } |
| + if turn.Connection != "codex-1" || turn.Attempt != 1 || moved.Switched == nil || moved.Switched.To != "codex" { |
| + t.Fatalf("preferred turn %+v %+v", turn, moved.Switched) |
| + } |
| + if _, err = env.Client.SetPreferences(s.ctx, wire.Preferences{Provider: "", Revision: 1}); err != nil { |
| + t.Fatal(err) |
| + } |
| + time.Sleep(2 * time.Second) |
| + stay := s.send(t, "Again.") |
| + replyOf(t, s, stay.Turn.ID) |
| + if c := s.conv.Turns[stay.Turn.ID].Connection; c != "codex-1" { |
| + t.Fatalf("Automatic moved the session to %s", c) |
| + } |
| + // Preferred but limited: Claude answers. |
| + if _, err = env.Client.SetPreferences(s.ctx, wire.Preferences{Provider: "codex", Revision: 2}); err != nil { |
| + t.Fatal(err) |
| + } |
| + time.Sleep(2 * time.Second) |
| + held := s.send(t, "Limited now. limit:" + second) |
| + replyOf(t, s, held.Turn.ID) |
| + if c := s.conv.Turns[held.Turn.ID].Connection; c != "claude-1" { |
| + t.Fatalf("a limited preferred connection answered: %s", c) |
| + } |
| + // Signed out, then forgotten. |
| + var codex wire.Connection |
| + for _, v := range s.conv.Connections { |
| + if v.LocalID == "codex-1" { |
| + codex = v |
| + } |
| + } |
| + if _, err = env.Client.SignOut(s.ctx, codex.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + s.wait(t, "signed out", time.Minute, func(cv *thintest.Conversation) bool { return cv.Connections[codex.ID].State == wire.ConnSignedOut }) |
| + if err = env.Client.Forget(s.ctx, codex.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + list, _ := env.Client.Connections(s.ctx) |
| + for _, v := range list.Items { |
| + if v.ID == codex.ID { |
| + t.Fatal("the forgotten record stayed") |
| + } |
| + } |
| + s.wait(t, "forgotten in the stream", time.Minute, func(cv *thintest.Conversation) bool { |
| + _, ok := cv.Connections[codex.ID] |
| + return !ok |
| + }) |
| +} |
diff --git a/internal/headless/env_test.go b/internal/headless/env_test.go| index ff0855fa..ac47e12f 100644 |
| --- a/internal/headless/env_test.go |
| +++ b/internal/headless/env_test.go |
| @@ -7,6 +7,7 @@ import ( |
| "database/sql" |
| "encoding/hex" |
| "encoding/json" |
| + "fmt" |
| "io" |
| "log/slog" |
| "os" |
| @@ -100,7 +101,10 @@ type Env struct { |
| // AskNamespace is the containment namespace the runner recorded for |
| // a question's attempt (local only). |
| AskNamespace func(t *testing.T, question string) string |
| - turns *int |
| + // AskUsage is the outcomes of a question's recorded usage rows, with |
| + // whether each carried figures (local only). |
| + AskUsage func(t *testing.T, question string) []string |
| + turns *int |
| } |
| // Turn counts model turns so staging stays inside its budget. |
| @@ -312,6 +316,23 @@ func localEnv(t *testing.T) (*Env, *thintest.Instance, *localRunner) { |
| } |
| return ns |
| }, |
| + AskUsage: func(t *testing.T, question string) []string { |
| + rows, err := inst.DB.Writer().Query("SELECT outcome, input_tokens IS NOT NULL FROM chat_usage WHERE step_id = ? AND role = 'ask' ORDER BY attempt", question) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer rows.Close() |
| + var out []string |
| + for rows.Next() { |
| + var outcome string |
| + var figures bool |
| + if err := rows.Scan(&outcome, &figures); err != nil { |
| + t.Fatal(err) |
| + } |
| + out = append(out, fmt.Sprintf("%s/%v", outcome, figures)) |
| + } |
| + return out |
| + }, |
| KeptSessions: func(t *testing.T) int { |
| dirs, _ := filepath.Glob(filepath.Join(thin.SessionRoot(cfg), "*", "steps", "*")) |
| return len(dirs) |
diff --git a/internal/runner/connect/choose.go b/internal/runner/connect/choose.go| index 3f908080..9af97d11 100644 |
| --- a/internal/runner/connect/choose.go |
| +++ b/internal/runner/connect/choose.go |
| @@ -21,6 +21,7 @@ const ( |
| ReasonOnlyOption = "only_option" |
| ReasonHeadroom = "headroom" |
| ReasonFailover = "failover" |
| + ReasonPreference = "preference" |
| ) |
| // Connection states the choice reads (wire.Conn* values). |
| @@ -77,11 +78,14 @@ type Choice struct { |
| // usable now (healthy, or limited with its reset passed; never one |
| // connecting or unchecked), not in avoid. The current binding, when it is |
| // eligible, is kept: stickiness is a rule, a session leaves its |
| -// connection only on failure. Otherwise the one with the most reported |
| -// headroom, a connection whose provider reported nothing ranking below |
| -// any with a figure, then the configured order. ok is false when nothing |
| -// can run it. |
| -func Choose(cs []Candidate, role, current string, avoid []string, now time.Time) (Choice, bool) { |
| +// connection only on failure, with one exception: prefer (a provider, |
| +// "" for Automatic) names what the person prefers, and a session not on |
| +// it moves to it when it can answer. Callers ask at a natural boundary |
| +// only (a new turn, a new step), never mid-turn. Otherwise a preferred |
| +// connection first, then the one with the most reported headroom, a |
| +// connection whose provider reported nothing ranking below any with a |
| +// figure, then the configured order. ok is false when nothing can run it. |
| +func Choose(cs []Candidate, role, current, prefer string, avoid []string, now time.Time) (Choice, bool) { |
| var usable []Candidate |
| for _, c := range cs { |
| if Capable(c.Provider, role) && c.Usable(now) && !slices.Contains(avoid, c.ID) { |
| @@ -94,11 +98,33 @@ func Choose(cs []Candidate, role, current string, avoid []string, now time.Time) |
| if len(usable) == 1 { |
| return Choice{ID: usable[0].ID, Reason: ReasonOnlyOption}, true |
| } |
| + preferred := slices.ContainsFunc(usable, func(c Candidate) bool { return c.Provider == prefer }) |
| for _, c := range usable { |
| - if c.ID == current { |
| + if c.ID == current && (!preferred || c.Provider == prefer) { |
| return Choice{ID: c.ID, Reason: ReasonHeadroom}, true |
| } |
| } |
| + if preferred { |
| + var mine []Candidate |
| + for _, c := range usable { |
| + if c.Provider == prefer { |
| + mine = append(mine, c) |
| + } |
| + } |
| + return Choice{ID: roomiest(mine).ID, Reason: ReasonPreference}, true |
| + } |
| + reason := ReasonHeadroom |
| + if current != "" { |
| + // The connection that ran this last cannot now. |
| + reason = ReasonFailover |
| + } |
| + return Choice{ID: roomiest(usable).ID, Reason: reason}, true |
| +} |
| + |
| +// roomiest is the candidate with the most reported headroom: one whose |
| +// provider reported nothing ranks below any with a figure, then the |
| +// configured order. |
| +func roomiest(usable []Candidate) Candidate { |
| best := usable[0] |
| for _, c := range usable[1:] { |
| switch { |
| @@ -108,12 +134,7 @@ func Choose(cs []Candidate, role, current string, avoid []string, now time.Time) |
| best = c |
| } |
| } |
| - reason := ReasonHeadroom |
| - if current != "" { |
| - // The connection that ran this last cannot now. |
| - reason = ReasonFailover |
| - } |
| - return Choice{ID: best.ID, Reason: reason}, true |
| + return best |
| } |
| // NextCheck is the earliest time a limited candidate becomes usable, or |
diff --git a/internal/runner/connect/choose_test.go b/internal/runner/connect/choose_test.go| index ca5c1f82..900c4844 100644 |
| --- a/internal/runner/connect/choose_test.go |
| +++ b/internal/runner/connect/choose_test.go |
| @@ -23,28 +23,35 @@ func TestChoose(t *testing.T) { |
| cs []Candidate |
| role, current string |
| avoid []string |
| + prefer string |
| want, reason string |
| }{ |
| - {"one", []Candidate{claude}, RoleCoordinator, "", nil, "claude-a", ReasonOnlyOption}, |
| - {"none", []Candidate{limited(claude, now.Add(time.Hour))}, RoleCoordinator, "claude-a", nil, "", ""}, |
| - {"configured order first", []Candidate{claude, codex}, RoleCoordinator, "", nil, "claude-a", ReasonHeadroom}, |
| - {"reported headroom before unknown", []Candidate{claude, used(codex, 0.8)}, RoleCoordinator, "", nil, "codex-1", ReasonHeadroom}, |
| - {"most headroom", []Candidate{used(claude, 0.5), used(claude2, 0.2), used(codex, 0.4)}, RoleCoordinator, "", nil, "claude-2", ReasonHeadroom}, |
| - {"sticky", []Candidate{claude, codex}, RoleCoordinator, "codex-1", nil, "codex-1", ReasonHeadroom}, |
| - {"failover from limited", []Candidate{limited(claude, now.Add(time.Hour)), codex}, RoleCoordinator, "claude-a", nil, "codex-1", ReasonOnlyOption}, |
| - {"failover among several", []Candidate{limited(claude, now.Add(time.Hour)), claude2, codex}, RoleCoordinator, "claude-a", nil, "claude-2", ReasonFailover}, |
| - {"reset passed", []Candidate{limited(claude, now.Add(-time.Minute)), codex}, RoleCoordinator, "claude-a", nil, "claude-a", ReasonHeadroom}, |
| - {"limited without reset never by itself", []Candidate{limited(claude, time.Time{})}, RoleCoordinator, "", nil, "", ""}, |
| - {"stickiness is a rule", []Candidate{used(claude, 0.97), used(codex, 0.1)}, RoleCoordinator, "claude-a", nil, "claude-a", ReasonHeadroom}, |
| - {"failover to the most headroom", []Candidate{limited(claude, now.Add(time.Hour)), used(claude2, 0.7), used(codex, 0.2)}, RoleCoordinator, "claude-a", nil, "codex-1", ReasonFailover}, |
| - {"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 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, "", ""}, |
| + {"one", []Candidate{claude}, RoleCoordinator, "", nil, "", "claude-a", ReasonOnlyOption}, |
| + {"none", []Candidate{limited(claude, now.Add(time.Hour))}, RoleCoordinator, "claude-a", nil, "", "", ""}, |
| + {"configured order first", []Candidate{claude, codex}, RoleCoordinator, "", nil, "", "claude-a", ReasonHeadroom}, |
| + {"reported headroom before unknown", []Candidate{claude, used(codex, 0.8)}, RoleCoordinator, "", nil, "", "codex-1", ReasonHeadroom}, |
| + {"most headroom", []Candidate{used(claude, 0.5), used(claude2, 0.2), used(codex, 0.4)}, RoleCoordinator, "", nil, "", "claude-2", ReasonHeadroom}, |
| + {"sticky", []Candidate{claude, codex}, RoleCoordinator, "codex-1", nil, "", "codex-1", ReasonHeadroom}, |
| + {"failover from limited", []Candidate{limited(claude, now.Add(time.Hour)), codex}, RoleCoordinator, "claude-a", nil, "", "codex-1", ReasonOnlyOption}, |
| + {"failover among several", []Candidate{limited(claude, now.Add(time.Hour)), claude2, codex}, RoleCoordinator, "claude-a", nil, "", "claude-2", ReasonFailover}, |
| + {"reset passed", []Candidate{limited(claude, now.Add(-time.Minute)), codex}, RoleCoordinator, "claude-a", nil, "", "claude-a", ReasonHeadroom}, |
| + {"limited without reset never by itself", []Candidate{limited(claude, time.Time{})}, RoleCoordinator, "", nil, "", "", ""}, |
| + {"stickiness is a rule", []Candidate{used(claude, 0.97), used(codex, 0.1)}, RoleCoordinator, "claude-a", nil, "", "claude-a", ReasonHeadroom}, |
| + {"failover to the most headroom", []Candidate{limited(claude, now.Add(time.Hour)), used(claude2, 0.7), used(codex, 0.2)}, RoleCoordinator, "claude-a", nil, "", "codex-1", ReasonFailover}, |
| + {"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 is never chosen", []Candidate{{ID: "codex-1", Provider: "codex"}}, RoleCoordinator, "", nil, "", "", ""}, |
| + {"preference first", []Candidate{claude, used(codex, 0.9)}, RoleCoordinator, "", nil, "codex", "codex-1", ReasonPreference}, |
| + {"preference takes the session back at a boundary", []Candidate{claude, codex}, RoleCoordinator, "claude-a", nil, "codex", "codex-1", ReasonPreference}, |
| + {"on the preference already", []Candidate{claude, codex}, RoleCoordinator, "codex-1", nil, "codex", "codex-1", ReasonHeadroom}, |
| + {"preference never overrides health", []Candidate{claude, limited(codex, now.Add(time.Hour))}, RoleCoordinator, "claude-a", nil, "codex", "claude-a", ReasonOnlyOption}, |
| + {"preference among a provider's accounts by headroom", []Candidate{used(claude, 0.6), used(claude2, 0.1), codex}, RoleCoordinator, "", nil, "claude", "claude-2", ReasonPreference}, |
| + {"preference a role cannot use", []Candidate{claude, claude2, codex}, RoleEngineering, "claude-a", nil, "codex", "claude-a", ReasonHeadroom}, |
| + {"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) |
| + got, ok := Choose(tc.cs, tc.role, tc.current, tc.prefer, tc.avoid, now) |
| if ok != (tc.want != "") || got.ID != tc.want || got.Reason != tc.reason { |
| t.Fatalf("Choose = %+v %v, want %s %s", got, ok, tc.want, tc.reason) |
| } |
diff --git a/internal/runner/connect/usage.go b/internal/runner/connect/usage.go| index c802f707..d33f628a 100644 |
| --- a/internal/runner/connect/usage.go |
| +++ b/internal/runner/connect/usage.go |
| @@ -46,92 +46,136 @@ func (b Breakdown) minus(o Breakdown) (Breakdown, bool) { |
| return Breakdown{out[0], out[1], out[2], out[3], out[4]}, ok |
| } |
| +// plus is b with o's figures added, figure by figure; a figure neither |
| +// carried stays nil. |
| +func (b Breakdown) plus(o Breakdown) Breakdown { |
| + var out [5]*int64 |
| + add := o.fields() |
| + for i, v := range b.fields() { |
| + switch { |
| + case v == nil && add[i] == nil: |
| + continue |
| + case v == nil: |
| + n := *add[i] |
| + out[i] = &n |
| + case add[i] == nil: |
| + n := *v |
| + out[i] = &n |
| + default: |
| + n := *v + *add[i] |
| + out[i] = &n |
| + } |
| + } |
| + return Breakdown{out[0], out[1], out[2], out[3], out[4]} |
| +} |
| + |
| +// same reports whether two breakdowns carry the same figures. |
| +func same(a, b Breakdown) bool { |
| + x, y := a.fields(), b.fields() |
| + for i := range x { |
| + if (x[i] == nil) != (y[i] == nil) || x[i] != nil && *x[i] != *y[i] { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
| + |
| // CodexTally aggregates thread/tokenUsage/updated notices for one Codex |
| -// thread. Codex sends several per turn and repeats the last turn's after |
| -// thread/resume; the attempt's figure is its last total minus the total |
| -// seen before it began (the first total after a resume is the baseline), |
| -// so a resent notice changes nothing. A notice for another thread is |
| -// dropped. |
| -// |
| -// That baseline is verified only for a fresh thread (zero) or after this |
| -// process saw the previous turn's last total: the pinned app-server has |
| -// no read of a thread's token usage, and the first notice after a resume |
| -// may already include new use (Astra round 2), so an attempt on a resumed |
| -// thread is recorded complete: false, counted from the first total seen |
| -// (a lower bound). |
| +// thread (spec §6). Codex sends several per turn, each with the thread's |
| +// running total and the last request's figures, and the first notice |
| +// after a resume can already include new use, so a post-resume notice is |
| +// never subtracted. An attempt's figure is its last total minus a |
| +// verified pre-turn baseline: zero for a thread started here, or the |
| +// last total this process saw on the thread before the attempt began |
| +// (the previous turn's, including its late notices). Without one (a |
| +// resumed thread, whose total so far the pinned app-server cannot read) |
| +// the row is the sum of the attempt's own "last" figures, complete: |
| +// false. A row is complete only when the baseline was verified and the |
| +// turn's completion was observed after its notices. A notice for another |
| +// thread, or for a turn that is neither this attempt's nor the one |
| +// before it, is dropped, so a resent notice changes nothing. |
| type CodexTally struct { |
| - Thread string |
| - turn string |
| - base Breakdown |
| - baseKnown bool |
| - verified bool |
| - cur Breakdown |
| - seen bool |
| + Thread string |
| + turn, previous string |
| + base, cur Breakdown |
| + lasts Breakdown |
| + verified bool |
| + seen, ended bool |
| } |
| // NewCodexTally starts a tally for a thread: fresh (started here, zero |
| // so far) or resumed (its total so far unknown). |
| func NewCodexTally(thread string, fresh bool) *CodexTally { |
| - return &CodexTally{Thread: thread, baseKnown: fresh, verified: fresh} |
| + return &CodexTally{Thread: thread, verified: fresh} |
| } |
| -// CodexNotice decodes a thread/tokenUsage/updated notice. |
| -func CodexNotice(params json.RawMessage) (thread, turn string, total Breakdown, ok bool) { |
| +// CodexNotice decodes a thread/tokenUsage/updated notice: the thread's |
| +// running total and the last request's figures. |
| +func CodexNotice(params json.RawMessage) (thread, turn string, total, last Breakdown, ok bool) { |
| var v struct { |
| ThreadID string `json:"threadId"` |
| TurnID string `json:"turnId"` |
| TokenUsage struct { |
| Total *Breakdown `json:"total"` |
| + Last *Breakdown `json:"last"` |
| } `json:"tokenUsage"` |
| } |
| if json.Unmarshal(params, &v) != nil || v.TokenUsage.Total == nil { |
| - return "", "", Breakdown{}, false |
| + return "", "", Breakdown{}, Breakdown{}, false |
| + } |
| + if v.TokenUsage.Last != nil { |
| + last = *v.TokenUsage.Last |
| } |
| - return v.ThreadID, v.TurnID, *v.TokenUsage.Total, true |
| + return v.ThreadID, v.TurnID, *v.TokenUsage.Total, last, true |
| } |
| // Notice takes one notice. |
| -func (t *CodexTally) Notice(thread, turn string, total Breakdown) { |
| - if thread != t.Thread { |
| +func (t *CodexTally) Notice(thread, turn string, total, last Breakdown) { |
| + if thread != t.Thread || turn == "" { |
| return |
| } |
| - if t.turn != "" && turn == t.turn { |
| - if !t.baseKnown { |
| - // Nothing before it: this first total is the lower bound's base. |
| - t.base, t.baseKnown = total, true |
| + switch turn { |
| + case t.turn: |
| + if t.ended || t.seen && same(total, t.cur) { |
| + // After the completion, or the same notice again. |
| + return |
| } |
| t.cur, t.seen = total, true |
| - return |
| - } |
| - if !t.seen { |
| - // Before this attempt's own notices (a resume's replay): a base, |
| - // not a verified one. |
| - t.base, t.baseKnown, t.verified = total, true, false |
| + t.lasts = t.lasts.plus(last) |
| + case t.previous: |
| + // The turn before, late: its total is still this attempt's base. |
| + t.base = total |
| } |
| } |
| -// Begin starts an attempt on the thread's provider turn: its baseline is |
| -// the total seen so far. |
| +// Begin starts an attempt on the thread's provider turn. The last total |
| +// seen on the thread so far is its verified base; with none seen, a |
| +// thread started here stays at zero and a resumed one has no base. |
| func (t *CodexTally) Begin(turn string) { |
| if t.seen { |
| - // The previous turn's last total, seen here: a verified base. |
| - t.base, t.baseKnown, t.verified = t.cur, true, true |
| + t.base, t.verified = t.cur, true |
| + } |
| + if t.turn != "" { |
| + t.previous = t.turn |
| } |
| - t.turn, t.seen, t.cur = turn, false, Breakdown{} |
| + t.turn, t.seen, t.ended, t.cur, t.lasts = turn, false, false, Breakdown{}, Breakdown{} |
| } |
| +// End records that the attempt's turn completed: its notices are final. |
| +func (t *CodexTally) End() { t.ended = true } |
| + |
| // Row is the attempt's usage row (figures null when no notice was seen). |
| func (t *CodexTally) Row() wire.Usage { |
| if !t.seen { |
| return wire.Usage{} |
| } |
| - d, ok := t.cur.minus(t.base) |
| - if !ok { |
| - // The thread's total went back (a new thread): the notice is the |
| - // attempt's own. |
| - d = t.cur |
| + d, complete := t.lasts, false |
| + if t.verified { |
| + if since, ok := t.cur.minus(t.base); ok { |
| + d, complete = since, t.ended |
| + } |
| } |
| - return wire.Usage{InputTokens: d.Input, CachedInputTokens: d.Cached, CacheWriteTokens: d.CacheWrite, OutputTokens: d.Output, ReasoningOutputTokens: d.Reasoning, Complete: t.verified} |
| + return wire.Usage{InputTokens: d.Input, CachedInputTokens: d.Cached, CacheWriteTokens: d.CacheWrite, OutputTokens: d.Output, ReasoningOutputTokens: d.Reasoning, Complete: complete} |
| } |
| // ClaudeRows reads a stream-json result: one row per model in |
diff --git a/internal/runner/connect/usage_test.go b/internal/runner/connect/usage_test.go| index 7dfec230..dc740303 100644 |
| --- a/internal/runner/connect/usage_test.go |
| +++ b/internal/runner/connect/usage_test.go |
| @@ -11,17 +11,21 @@ import ( |
| ) |
| func notice(thread, turn, total string) json.RawMessage { |
| - return json.RawMessage(`{"threadId":"` + thread + `","turnId":"` + turn + `","tokenUsage":{"total":` + total + `,"last":{"inputTokens":1,"outputTokens":1}}}`) |
| + return noticeLast(thread, turn, total, `{"inputTokens":1,"outputTokens":1}`) |
| +} |
| + |
| +func noticeLast(thread, turn, total, last string) json.RawMessage { |
| + return json.RawMessage(`{"threadId":"` + thread + `","turnId":"` + turn + `","tokenUsage":{"total":` + total + `,"last":` + last + `}}`) |
| } |
| func feed(t *testing.T, tally *CodexTally, params ...json.RawMessage) { |
| t.Helper() |
| for _, p := range params { |
| - thread, turn, total, ok := CodexNotice(p) |
| + thread, turn, total, last, ok := CodexNotice(p) |
| if !ok { |
| t.Fatalf("notice %s", p) |
| } |
| - tally.Notice(thread, turn, total) |
| + tally.Notice(thread, turn, total, last) |
| } |
| } |
| @@ -57,6 +61,7 @@ func TestCodexTallyRecorded(t *testing.T) { |
| seen++ |
| feed(t, tally, m.Params) |
| } |
| + tally.End() |
| row := tally.Row() |
| if seen != 2 || !row.Complete || get(row.InputTokens) != 28254 || get(row.OutputTokens) != 142 || row.CachedInputTokens != nil || row.ReasoningOutputTokens != nil { |
| t.Fatalf("%d notices, row %+v", seen, row) |
| @@ -64,45 +69,64 @@ func TestCodexTallyRecorded(t *testing.T) { |
| } |
| func TestCodexTally(t *testing.T) { |
| - // A fresh process resumes a thread: the first total after |
| - // thread/resume (the previous turn's) is the baseline. |
| + // A fresh process resumes a thread: the replayed notice of the turn |
| + // before is not a verified base, so nothing is subtracted; the row is |
| + // the attempt's own "last" figures summed, complete false. Another |
| + // thread's notice and a resent one change nothing. |
| tally := NewCodexTally("th", false) |
| - feed(t, tally, notice("th", "old", `{"inputTokens":1000,"outputTokens":100,"cachedInputTokens":800}`)) |
| + feed(t, tally, notice("th", "old", `{"inputTokens":900,"outputTokens":100,"cachedInputTokens":800}`)) |
| tally.Begin("t2") |
| feed(t, tally, |
| - notice("th", "t2", `{"inputTokens":1500,"outputTokens":130,"cachedInputTokens":1100}`), |
| + noticeLast("th", "t2", `{"inputTokens":1500,"outputTokens":130,"cachedInputTokens":1100}`, `{"inputTokens":500,"outputTokens":30}`), |
| notice("other", "t2", `{"inputTokens":99999,"outputTokens":99999}`), |
| - notice("th", "t2", `{"inputTokens":1700,"outputTokens":150,"cachedInputTokens":1200}`), |
| - // A resent frame changes nothing. |
| - notice("th", "t2", `{"inputTokens":1700,"outputTokens":150,"cachedInputTokens":1200}`)) |
| + noticeLast("th", "t2", `{"inputTokens":1700,"outputTokens":150,"cachedInputTokens":1200}`, `{"inputTokens":200,"outputTokens":20}`), |
| + noticeLast("th", "t2", `{"inputTokens":1700,"outputTokens":150,"cachedInputTokens":1200}`, `{"inputTokens":200,"outputTokens":20}`)) |
| + tally.End() |
| row := tally.Row() |
| - if get(row.InputTokens) != 700 || get(row.OutputTokens) != 50 || get(row.CachedInputTokens) != 400 || row.Complete || row.CacheWriteTokens != nil { |
| + if get(row.InputTokens) != 700 || get(row.OutputTokens) != 50 || row.CachedInputTokens != nil || row.Complete { |
| t.Fatalf("resumed turn %+v", row) |
| } |
| - // The next turn in the same process starts from that total. |
| + // The next turn in the same process starts from that total: verified, |
| + // complete once its completion is seen. |
| tally.Begin("t3") |
| if r := tally.Row(); r.Complete || r.InputTokens != nil { |
| t.Fatalf("no notice yet: %+v", r) |
| } |
| feed(t, tally, notice("th", "t3", `{"inputTokens":1800,"outputTokens":160,"cachedInputTokens":1250}`)) |
| - if r := tally.Row(); get(r.InputTokens) != 100 || get(r.OutputTokens) != 10 || !r.Complete { |
| + if r := tally.Row(); get(r.InputTokens) != 100 || get(r.OutputTokens) != 10 || r.Complete { |
| + t.Fatalf("next turn before its completion %+v", r) |
| + } |
| + tally.End() |
| + if r := tally.Row(); get(r.InputTokens) != 100 || !r.Complete { |
| t.Fatalf("next turn (verified base) %+v", r) |
| } |
| - // Resumed with no notice before the turn: counted from its first |
| - // notice, a lower bound, never the thread's whole total. |
| + // A late notice of the turn before moves the base, not the figure. |
| + tally.Begin("t4") |
| + feed(t, tally, notice("th", "t3", `{"inputTokens":1900,"outputTokens":170}`), notice("th", "t4", `{"inputTokens":2000,"outputTokens":180}`)) |
| + tally.End() |
| + if r := tally.Row(); get(r.InputTokens) != 100 || get(r.OutputTokens) != 10 || !r.Complete { |
| + t.Fatalf("late notice %+v", r) |
| + } |
| + // Resumed with no notice before the turn: the first notice already |
| + // includes new use and is counted in full, never subtracted. |
| cold := NewCodexTally("th", false) |
| cold.Begin("t9") |
| - feed(t, cold, notice("th", "t9", `{"inputTokens":14054,"outputTokens":96}`), notice("th", "t9", `{"inputTokens":28254,"outputTokens":142}`)) |
| - if r := cold.Row(); get(r.InputTokens) != 14200 || r.Complete { |
| + feed(t, cold, noticeLast("th", "t9", `{"inputTokens":14054,"outputTokens":96}`, `{"inputTokens":14054,"outputTokens":96}`), noticeLast("th", "t9", `{"inputTokens":28254,"outputTokens":142}`, `{"inputTokens":14200,"outputTokens":46}`)) |
| + cold.End() |
| + if r := cold.Row(); get(r.InputTokens) != 28254 || get(r.OutputTokens) != 142 || r.Complete { |
| t.Fatalf("resumed without a base %+v", r) |
| } |
| - // A total that went back is the attempt's own. |
| + // A thread started here: zero is the verified base; a turn whose |
| + // completion was not seen (cancelled) is never complete. |
| fresh := NewCodexTally("new", true) |
| - feed(t, fresh, notice("new", "x", `{"inputTokens":5000,"outputTokens":5}`)) |
| fresh.Begin("y") |
| feed(t, fresh, notice("new", "y", `{"inputTokens":40,"outputTokens":4}`)) |
| - if r := fresh.Row(); get(r.InputTokens) != 40 { |
| - t.Fatalf("went back %+v", r) |
| + if r := fresh.Row(); get(r.InputTokens) != 40 || r.Complete { |
| + t.Fatalf("cancelled fresh turn %+v", r) |
| + } |
| + fresh.End() |
| + if r := fresh.Row(); !r.Complete { |
| + t.Fatalf("fresh turn %+v", r) |
| } |
| } |
diff --git a/internal/runner/thin/ask.go b/internal/runner/thin/ask.go| index 3aaa0f8f..44460bbc 100644 |
| --- a/internal/runner/thin/ask.go |
| +++ b/internal/runner/thin/ask.go |
| @@ -791,6 +791,15 @@ func (e *Engineer) answer(ctx context.Context, a askRow, progress func(wire.Answ |
| } |
| rep.Timing = &t |
| } |
| + // The answer's usage, whatever the outcome. |
| + outcome := wire.OutcomeFailed |
| + switch rep.State { |
| + case wire.QuestionAnswered: |
| + outcome = wire.OutcomeReplied |
| + case wire.QuestionCancelled: |
| + outcome = wire.OutcomeCancelled |
| + } |
| + rep.Usage = usageRows(res.tokens, bs[i], a.Attempt, outcome) |
| return rep |
| } |
diff --git a/internal/runner/thin/codex.go b/internal/runner/thin/codex.go| index 3e6d28c2..77c44557 100644 |
| --- a/internal/runner/thin/codex.go |
| +++ b/internal/runner/thin/codex.go |
| @@ -197,19 +197,20 @@ func (c *codexCoordinator) Turn(ctx context.Context, in TurnInput, emit func(str |
| for { |
| select { |
| case <-tctx.Done(): |
| + // What the turn used so far is kept (complete: false). |
| c.interrupt(p, turnID) |
| c.stop(false) |
| if ctx.Err() != nil { |
| - return TurnResult{Reason: "cancelled"} |
| + return TurnResult{Reason: "cancelled", Usage: usage()} |
| } |
| - return TurnResult{Reason: "turn_timeout"} |
| + return TurnResult{Reason: "turn_timeout", Usage: usage()} |
| case m, ok := <-p.rpc.Messages: |
| if !ok { |
| c.stop(false) |
| if ctx.Err() != nil { |
| - return TurnResult{Reason: "cancelled"} |
| + return TurnResult{Reason: "cancelled", Usage: usage()} |
| } |
| - return TurnResult{Reason: "provider_failed"} |
| + return TurnResult{Reason: "provider_failed", Usage: usage()} |
| } |
| mark(&timing.FirstEventMs) |
| if len(m.ID) > 0 { |
| @@ -269,8 +270,8 @@ func (c *codexCoordinator) Turn(ctx context.Context, in TurnInput, emit func(str |
| } |
| } |
| case "thread/tokenUsage/updated": |
| - if thread, turn, total, ok := connect.CodexNotice(m.Params); ok { |
| - p.tally.Notice(thread, turn, total) |
| + if thread, turn, total, last, ok := connect.CodexNotice(m.Params); ok { |
| + p.tally.Notice(thread, turn, total, last) |
| } |
| case "turn/completed": |
| var t struct { |
| @@ -281,11 +282,12 @@ func (c *codexCoordinator) Turn(ctx context.Context, in TurnInput, emit func(str |
| if json.Unmarshal(n.Turn, &t) != nil || t.ID != turnID { |
| continue |
| } |
| + p.tally.End() |
| if t.Status != "completed" { |
| proven := c.stop(false) |
| switch { |
| case ctx.Err() != nil || t.Status == "interrupted": |
| - return TurnResult{Reason: "cancelled"} |
| + return TurnResult{Reason: "cancelled", Usage: usage()} |
| case connect.CodexFailure(t.Error) == connect.FailQuota || seen != nil && seen.Limited: |
| l := connect.Limit{Limited: true} |
| if seen != nil { |
diff --git a/internal/runner/thin/connector.go b/internal/runner/thin/connector.go| index 13415f07..499f4fca 100644 |
| --- a/internal/runner/thin/connector.go |
| +++ b/internal/runner/thin/connector.go |
| @@ -22,6 +22,7 @@ import ( |
| const connectSchema = ` |
| CREATE TABLE IF NOT EXISTS connect_attempts (id TEXT PRIMARY KEY, person TEXT NOT NULL, provider TEXT NOT NULL, same_machine INTEGER NOT NULL DEFAULT 0, state TEXT NOT NULL, home TEXT NOT NULL DEFAULT '', local_id TEXT NOT NULL DEFAULT '', cancelled INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL); |
| +CREATE TABLE IF NOT EXISTS connect_cleanups (connection TEXT PRIMARY KEY, person TEXT NOT NULL, local_id TEXT NOT NULL, report INTEGER NOT NULL, created_at TEXT NOT NULL); |
| ` |
| // ConnectLimit ends an attempt the person did not finish (spec §2.1: ten |
| @@ -48,11 +49,54 @@ type Connector struct { |
| // Limit bounds an attempt (default ConnectLimit). |
| Limit time.Duration |
| + // spawn runs a cleanup in the background (a goroutine; tests replace |
| + // it to stop the process between a frame and its cleanup). |
| + spawn func(func()) |
| + |
| mu sync.Mutex |
| attempts map[string]context.CancelFunc |
| ctx context.Context |
| } |
| +// cleanup is a sign-out the connector owes: recorded in the transaction |
| +// that consumes its frame (or that finds a cancelled attempt saved), and |
| +// done again at startup until it is done. |
| +type cleanup struct { |
| + connection, person, local string |
| + report bool |
| +} |
| + |
| +func (c *Connector) background(f func()) { |
| + if c.spawn != nil { |
| + c.spawn(f) |
| + return |
| + } |
| + go f() |
| +} |
| + |
| +// owe records a cleanup in t. |
| +func owe(t *sql.Tx, k cleanup) error { |
| + report := 0 |
| + if k.report { |
| + report = 1 |
| + } |
| + _, err := t.Exec("INSERT INTO connect_cleanups(connection, person, local_id, report, created_at) VALUES(?,?,?,?,?) ON CONFLICT(connection) DO NOTHING", k.connection, k.person, k.local, report, now()) |
| + return err |
| +} |
| + |
| +// settle does one cleanup and, once done, forgets it; an attempt it |
| +// signed out is marked removed so its local id, reused later, is never |
| +// signed out again. |
| +func (c *Connector) settle(k cleanup) { |
| + if !c.remove(k.connection, k.person, k.local, k.report) { |
| + return |
| + } |
| + _, err := c.State.db.Exec("DELETE FROM connect_cleanups WHERE connection=?", k.connection) |
| + c.log("disconnect record", err) |
| + _, err = c.State.db.Exec("UPDATE connect_attempts SET state='removed' WHERE id=? AND state='done'", k.connection) |
| + c.log("disconnect record", err) |
| +} |
| + |
| func (c *Connector) log(msg string, err error) { |
| if c.Logger != nil && err != nil { |
| c.Logger.Warn(msg, "err", sanitize(err)) |
| @@ -84,6 +128,28 @@ func (c *Connector) Start(ctx context.Context) error { |
| c.removeHome(l.home) |
| c.finish(l.id, wire.ConnectionReport{Connection: l.id, Person: l.person, Provider: l.provider, State: wire.ConnError, Reason: "runner_offline"}) |
| } |
| + // An attempt saved and then cancelled, stopped before it was signed |
| + // out: owed now. Then every cleanup still owed. |
| + if _, err = c.State.db.ExecContext(ctx, "INSERT INTO connect_cleanups(connection, person, local_id, report, created_at) SELECT id, person, local_id, 0, ? FROM connect_attempts WHERE state='done' AND cancelled=1 AND local_id<>'' ON CONFLICT(connection) DO NOTHING", now()); err != nil { |
| + return err |
| + } |
| + rows, err = c.State.db.QueryContext(ctx, "SELECT connection, person, local_id, report FROM connect_cleanups ORDER BY created_at") |
| + if err != nil { |
| + return err |
| + } |
| + var owed []cleanup |
| + for rows.Next() { |
| + var k cleanup |
| + if err = rows.Scan(&k.connection, &k.person, &k.local, &k.report); err != nil { |
| + rows.Close() |
| + return err |
| + } |
| + owed = append(owed, k) |
| + } |
| + rows.Close() |
| + for _, k := range owed { |
| + c.background(func() { c.settle(k) }) |
| + } |
| return nil |
| } |
| @@ -120,35 +186,46 @@ func (c *Connector) Accept(ctx context.Context, frameID string, cmd wire.Connect |
| return nil |
| } |
| -// Cancel ends an attempt the person cancelled. |
| +// Cancel ends an attempt the person cancelled. The cancel is recorded in |
| +// the transaction that consumes the frame, so an attempt that succeeds |
| +// at the same moment sees it before it saves the connection, and one |
| +// already saved owes its sign-out from that same transaction. |
| func (c *Connector) Cancel(ctx context.Context, frameID string, cmd wire.CancelConnectCommand) error { |
| fresh := false |
| + var owed *cleanup |
| err := c.State.tx(ctx, func(t *sql.Tx) error { |
| var err error |
| - fresh, err = seen(t, frameID) |
| - return err |
| + if fresh, err = seen(t, frameID); err != nil || !fresh { |
| + return err |
| + } |
| + if _, err = t.Exec("UPDATE connect_attempts SET cancelled=1 WHERE id=?", cmd.Connection); err != nil { |
| + return err |
| + } |
| + var state, local, person string |
| + err = t.QueryRow("SELECT state, local_id, person FROM connect_attempts WHERE id=?", cmd.Connection).Scan(&state, &local, &person) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return nil |
| + } |
| + if err != nil || state != "done" || local == "" { |
| + return err |
| + } |
| + // Ended already: a success the person cancelled does not stand |
| + // (the instance dropped its report); it is signed out here. |
| + owed = &cleanup{connection: cmd.Connection, person: person, local: local} |
| + return owe(t, *owed) |
| }) |
| if err != nil || !fresh { |
| return err |
| } |
| - // Recorded first, so an attempt that succeeds at the same moment sees |
| - // it before it saves the connection. |
| - if _, err = c.State.db.ExecContext(ctx, "UPDATE connect_attempts SET cancelled=1 WHERE id=?", cmd.Connection); err != nil { |
| - return err |
| - } |
| c.mu.Lock() |
| cancel := c.attempts[cmd.Connection] |
| c.mu.Unlock() |
| if cancel != nil { |
| cancel() |
| - return nil |
| } |
| - // Ended already: a success the person cancelled does not stand (its |
| - // report was dropped by the instance); it is signed out here. |
| - var state, local, person string |
| - err = c.State.db.QueryRowContext(ctx, "SELECT state, local_id, person FROM connect_attempts WHERE id=?", cmd.Connection).Scan(&state, &local, &person) |
| - if err == nil && state == "done" && local != "" { |
| - go c.remove(cmd.Connection, person, local, false) |
| + if owed != nil { |
| + k := *owed |
| + c.background(func() { c.settle(k) }) |
| } |
| return nil |
| } |
| @@ -156,22 +233,26 @@ func (c *Connector) Cancel(ctx context.Context, frameID string, cmd wire.CancelC |
| // Disconnect signs a connection out (DELETE /connections/{id}). |
| func (c *Connector) Disconnect(ctx context.Context, frameID string, cmd wire.DisconnectCommand) error { |
| fresh := false |
| + k := cleanup{connection: cmd.Connection, person: cmd.Person, local: cmd.LocalID, report: true} |
| err := c.State.tx(ctx, func(t *sql.Tx) error { |
| var err error |
| - fresh, err = seen(t, frameID) |
| - return err |
| + if fresh, err = seen(t, frameID); err != nil || !fresh { |
| + return err |
| + } |
| + return owe(t, k) |
| }) |
| if err != nil || !fresh { |
| return err |
| } |
| - go c.remove(cmd.Connection, cmd.Person, cmd.LocalID, true) |
| + c.background(func() { c.settle(k) }) |
| return nil |
| } |
| // remove signs one of the person's connections out: the harness's own |
| // logout in its home (best effort), the binding dropped, the home |
| -// deleted, its state forgotten; then signed_out is reported. |
| -func (c *Connector) remove(connection, person, local string, report bool) { |
| +// deleted, its state forgotten; then signed_out is reported. false: the |
| +// binding could not be dropped, and the cleanup is owed still. |
| +func (c *Connector) remove(connection, person, local string, report bool) bool { |
| ctx, cancel := context.WithTimeout(context.Background(), time.Minute) |
| defer cancel() |
| b, ok := c.Conns.Binding(local) |
| @@ -179,7 +260,7 @@ func (c *Connector) remove(connection, person, local string, report bool) { |
| if report { |
| c.report(wire.ConnectionReport{Connection: connection, Person: person, LocalID: local, State: wire.ConnSignedOut}) |
| } |
| - return |
| + return true |
| } |
| if lock, err := os.Open(b.ProviderHome); err == nil { |
| if unix.Flock(int(lock.Fd()), unix.LOCK_EX) == nil { |
| @@ -189,7 +270,7 @@ func (c *Connector) remove(connection, person, local string, report bool) { |
| } |
| if _, err := runnersetup.RemoveAccountBinding(ctx, c.Runner.AccountBindingsPath, b.ID); err != nil { |
| c.log("disconnect binding", err) |
| - return |
| + return false |
| } |
| c.removeHome(b.ProviderHome) |
| c.Conns.Forget(b.ID) |
| @@ -197,6 +278,7 @@ func (c *Connector) remove(connection, person, local string, report bool) { |
| if report { |
| c.report(wire.ConnectionReport{Connection: connection, Person: person, LocalID: local, Provider: b.Provider, State: wire.ConnSignedOut}) |
| } |
| + return true |
| } |
| // logout runs the provider's own sign-out in the home. |
| @@ -354,10 +436,18 @@ func (c *Connector) run(ctx context.Context, cancel context.CancelFunc, cmd wire |
| r.Headroom = acct.Limits.Headroom |
| } |
| c.finish(cmd.Connection, r) |
| - // Cancelled while it was being saved: it does not stand. |
| + c.standOrGo(cmd, id, lock) |
| +} |
| + |
| +// standOrGo ends an attempt that saved its connection: one cancelled |
| +// while it was being saved does not stand. The attempt's lock on the |
| +// home is let go first: the sign-out takes the same lock. |
| +func (c *Connector) standOrGo(cmd wire.ConnectCommand, id string, lock *os.File) { |
| + lock.Close() |
| + var cancelled int |
| _ = c.State.db.QueryRow("SELECT cancelled FROM connect_attempts WHERE id=?", cmd.Connection).Scan(&cancelled) |
| if cancelled == 1 { |
| - c.remove(cmd.Connection, cmd.Person, id, false) |
| + c.settle(cleanup{connection: cmd.Connection, person: cmd.Person, local: id}) |
| } |
| } |
diff --git a/internal/runner/thin/connector_test.go b/internal/runner/thin/connector_test.go| new file mode 100644 |
| index 00000000..b4ce6bb5 |
| --- /dev/null |
| +++ b/internal/runner/thin/connector_test.go |
| @@ -0,0 +1,194 @@ |
| +package thin |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "os" |
| + "path/filepath" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/runner" |
| + "amadan.net/oficina/equipo/internal/wire" |
| + "golang.org/x/sys/unix" |
| +) |
| + |
| +const connPerson = "p@example.com" |
| + |
| +// connectorRig is a runner state, a bindings file with one Codex |
| +// connection of the person's (codex-1, its home under the accounts |
| +// root) and a connector over them that a test can restart. |
| +type connectorRig struct { |
| + t *testing.T |
| + state *State |
| + bindings, root string |
| + home string |
| + conns *Conns |
| + cfg runner.Config |
| + identity, bindingJ map[string]any |
| +} |
| + |
| +func newConnectorRig(t *testing.T) *connectorRig { |
| + dir := t.TempDir() |
| + r := &connectorRig{t: t, root: filepath.Join(dir, "accounts"), bindings: filepath.Join(dir, "config", "bindings.json")} |
| + for _, d := range []string{r.root, filepath.Dir(r.bindings), filepath.Join(dir, "state")} { |
| + if err := os.MkdirAll(d, 0700); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + var err error |
| + if r.state, err = OpenState(context.Background(), filepath.Join(dir, "state")); err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { r.state.Close() }) |
| + r.cfg = runner.Config{AccountBindingsPath: r.bindings, CodexPath: "/bin/true", ClaudePath: "/bin/true"} |
| + r.conns = &Conns{Runner: r.cfg, State: r.state} |
| + r.add() |
| + return r |
| +} |
| + |
| +// add (again) binds codex-1 in a fresh home. |
| +func (r *connectorRig) add() { |
| + r.home = filepath.Join(r.root, "codex-1") |
| + if err := os.MkdirAll(r.home, 0700); err != nil { |
| + r.t.Fatal(err) |
| + } |
| + identity := map[string]string{"account_id": "a@example.com", "home_id": "h-" + time.Now().Format("150405.000000000"), "provider_version": "1"} |
| + b := []map[string]any{{"id": "codex-1", "local_id": "codex-1", "label": "codex-1", "person_id": connPerson, "provider": "codex", "family": "gpt", "model": "gpt-6-astra", "account_id": "a@example.com", "provider_home": r.home, "kind": "subscription", "expected_identity": identity}} |
| + raw, _ := json.Marshal(b) |
| + if err := os.WriteFile(r.bindings, raw, 0600); err != nil { |
| + r.t.Fatal(err) |
| + } |
| +} |
| + |
| +// connector is the runner's connector; crashed: its background cleanups |
| +// never run, as if the process stopped right after the frame. |
| +func (r *connectorRig) connector(crashed bool) *Connector { |
| + c := &Connector{Runner: r.cfg, State: r.state, Conns: r.conns, Root: r.root, Owners: []string{connPerson}} |
| + c.spawn = func(f func()) { f() } |
| + if crashed { |
| + c.spawn = func(func()) {} |
| + } |
| + if err := c.Start(context.Background()); err != nil { |
| + r.t.Fatal(err) |
| + } |
| + return c |
| +} |
| + |
| +func (r *connectorRig) bound() bool { |
| + _, ok := r.conns.Binding("codex-1") |
| + return ok |
| +} |
| + |
| +func (r *connectorRig) signedOut() int { |
| + frames, _, err := r.state.Unacked(context.Background(), 0) |
| + if err != nil { |
| + r.t.Fatal(err) |
| + } |
| + n := 0 |
| + for _, f := range frames { |
| + var v wire.ConnectionReport |
| + if f.Type == wire.FrameConnection && json.Unmarshal(f.Data, &v) == nil && v.State == wire.ConnSignedOut { |
| + n++ |
| + } |
| + } |
| + return n |
| +} |
| + |
| +func (r *connectorRig) attempt(id, state string, cancelled int) { |
| + if _, err := r.state.db.Exec("INSERT INTO connect_attempts(id, person, provider, state, local_id, cancelled, created_at) VALUES(?,?,?,?,?,?,?)", id, connPerson, "codex", state, "codex-1", cancelled, now()); err != nil { |
| + r.t.Fatal(err) |
| + } |
| +} |
| + |
| +// Astra round 1, finding 4: a sign-out whose frame was consumed is done |
| +// even when the runner stops before the cleanup ran: the restarted |
| +// connector owes it, does it once, and reports signed_out. |
| +func TestConnectorSignOutSurvivesACrash(t *testing.T) { |
| + r := newConnectorRig(t) |
| + c := r.connector(true) |
| + if err := c.Disconnect(context.Background(), "f1", wire.DisconnectCommand{Connection: "cn_1", Person: connPerson, LocalID: "codex-1"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if !r.bound() { |
| + t.Fatal("the crashed connector signed out anyway") |
| + } |
| + r.connector(false) |
| + if r.bound() || r.signedOut() != 1 { |
| + t.Fatalf("after the restart: bound %v, %d signed_out reports", r.bound(), r.signedOut()) |
| + } |
| + if _, err := os.Stat(r.home); !os.IsNotExist(err) { |
| + t.Fatalf("the home stayed: %v", err) |
| + } |
| + // The same frame again changes nothing; a later start owes nothing. |
| + again := r.connector(false) |
| + if err := again.Disconnect(context.Background(), "f1", wire.DisconnectCommand{Connection: "cn_1", Person: connPerson, LocalID: "codex-1"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if r.signedOut() != 1 { |
| + t.Fatalf("%d signed_out reports", r.signedOut()) |
| + } |
| +} |
| + |
| +// Finding 4, cancel: a cancel that finds the attempt's connection saved |
| +// owes its sign-out from the transaction that consumes the frame; a |
| +// connection saved and then found cancelled is owed at startup. Once |
| +// done, the attempt's local id, reused by a later connection, is never |
| +// signed out again. |
| +func TestConnectorCancelSurvivesACrash(t *testing.T) { |
| + r := newConnectorRig(t) |
| + r.attempt("cn_2", "done", 0) |
| + c := r.connector(true) |
| + if err := c.Cancel(context.Background(), "f2", wire.CancelConnectCommand{Connection: "cn_2", Person: connPerson}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if !r.bound() { |
| + t.Fatal("the crashed connector signed out anyway") |
| + } |
| + r.connector(false) |
| + if r.bound() { |
| + t.Fatal("the cancelled connection stood after the restart") |
| + } |
| + // Saved, then the cancel seen, then the stop: owed at startup. |
| + r.add() |
| + r.attempt("cn_3", "done", 1) |
| + r.connector(false) |
| + if r.bound() { |
| + t.Fatal("a connection cancelled as it was saved stood after the restart") |
| + } |
| + // codex-1 again, a new connection: no restart signs it out. |
| + r.add() |
| + r.connector(false) |
| + if !r.bound() { |
| + t.Fatal("a later connection with the same local id was signed out") |
| + } |
| +} |
| + |
| +// Finding 3: the attempt holds its home's lock while it signs in; a |
| +// cancel that lands as the connection is saved signs it out without |
| +// waiting on that lock. |
| +func TestConnectorLateCancelLetsGoOfTheLock(t *testing.T) { |
| + r := newConnectorRig(t) |
| + r.attempt("cn_4", "done", 1) |
| + c := r.connector(true) |
| + lock, err := os.Open(r.home) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err = unix.Flock(int(lock.Fd()), unix.LOCK_EX|unix.LOCK_NB); err != nil { |
| + t.Fatal(err) |
| + } |
| + done := make(chan struct{}) |
| + go func() { |
| + c.standOrGo(wire.ConnectCommand{Connection: "cn_4", Person: connPerson, Provider: "codex"}, "codex-1", lock) |
| + close(done) |
| + }() |
| + select { |
| + case <-done: |
| + case <-time.After(10 * time.Second): |
| + t.Fatal("the late cancel waits on the attempt's own lock") |
| + } |
| + if r.bound() { |
| + t.Fatal("the cancelled connection stood") |
| + } |
| +} |
diff --git a/internal/runner/thin/conns.go b/internal/runner/thin/conns.go| index 4a282d76..731ddef0 100644 |
| --- a/internal/runner/thin/conns.go |
| +++ b/internal/runner/thin/conns.go |
| @@ -2,6 +2,7 @@ package thin |
| import ( |
| "context" |
| + "database/sql" |
| "encoding/json" |
| "errors" |
| "log/slog" |
| @@ -175,7 +176,11 @@ func (c *Conns) Choose(ctx context.Context, person, role, current string, avoid |
| cs = append(cs, c.candidate(b)) |
| } |
| c.mu.Unlock() |
| - choice, ok := connect.Choose(cs, role, current, avoid, c.clock()) |
| + prefer, err := c.Preference(ctx, person) |
| + if err != nil { |
| + return runner.AccountBinding{}, connect.Choice{}, err |
| + } |
| + choice, ok := connect.Choose(cs, role, current, prefer.Provider, avoid, c.clock()) |
| if !ok { |
| return runner.AccountBinding{}, connect.Choice{}, ErrNoConnection |
| } |
| @@ -187,6 +192,49 @@ func (c *Conns) Choose(ctx context.Context, person, role, current string, avoid |
| return runner.AccountBinding{}, connect.Choice{}, ErrNoConnection |
| } |
| +// Preference is the person's preference as the instance last sent it. |
| +func (c *Conns) Preference(ctx context.Context, person string) (wire.Preferences, error) { |
| + var p wire.Preferences |
| + raw, err := c.State.meta(ctx, "prefer:"+person) |
| + if err != nil || raw == "" { |
| + return p, err |
| + } |
| + return p, json.Unmarshal([]byte(raw), &p) |
| +} |
| + |
| +// Prefer records the person's preference (a durable frame, once); an |
| +// older revision than the one held changes nothing. |
| +func (c *Conns) Prefer(ctx context.Context, frameID string, cmd wire.PreferenceCommand) error { |
| + if !wire.PreferenceProviders[cmd.Provider] { |
| + return nil |
| + } |
| + err := c.State.tx(ctx, func(t *sql.Tx) error { |
| + fresh, err := seen(t, frameID) |
| + if err != nil || !fresh { |
| + return err |
| + } |
| + var raw string |
| + err = t.QueryRowContext(ctx, "SELECT value FROM meta WHERE key=?", "prefer:"+cmd.Person).Scan(&raw) |
| + if err != nil && !errors.Is(err, sql.ErrNoRows) { |
| + return err |
| + } |
| + var held wire.Preferences |
| + if raw != "" { |
| + _ = json.Unmarshal([]byte(raw), &held) |
| + } |
| + if cmd.Revision <= held.Revision { |
| + return nil |
| + } |
| + next, _ := json.Marshal(wire.Preferences{Provider: cmd.Provider, Revision: cmd.Revision}) |
| + _, err = t.ExecContext(ctx, "INSERT INTO meta(key,value) VALUES(?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value", "prefer:"+cmd.Person, string(next)) |
| + return err |
| + }) |
| + if err == nil { |
| + c.changed() |
| + } |
| + return err |
| +} |
| + |
| // Usable reports whether a connection may run now (healthy, not |
| // limited): a question pinned to its step's account asks this. |
| func (c *Conns) Usable(id string) bool { |
diff --git a/internal/runner/thin/engineer.go b/internal/runner/thin/engineer.go| index 60880a8a..945be096 100644 |
| --- a/internal/runner/thin/engineer.go |
| +++ b/internal/runner/thin/engineer.go |
| @@ -200,31 +200,26 @@ func (e *Engineer) Exec(ctx context.Context, r stepRow, progress func(wire.StepR |
| var err error |
| if b, err = e.engineerOn(ctx, r.Person, avoid); err != nil { |
| if errors.Is(err, ErrNoConnection) { |
| - // Every connection that could take it over is refused now. |
| - return fail(firstNonEmpty(res.reason, wire.ReasonNoConnection), true) |
| + // Nothing can take it (every connection that could is |
| + // refused now): the attempt waits, queued, and goes on its |
| + // own when one returns (spec §3). |
| + rep.State = stepDeferred |
| + return rep |
| } |
| return fail("account_unavailable", true) |
| } |
| rep.Family, rep.Account = b.Family, b.LocalID |
| res = e.run(ctx, r, tree, specialistRun{action: "implement", binding: b, tools: stepTools, names: []string{"submit_candidate", "ask_person", "submit_render"}, permission: claude.StepPermission, call: func(context.Context, string, string, json.RawMessage) (string, bool) { return stepToolText, false }, prompt: prompt, keep: e.keepDir(r), activity: e.stepActivity(r)}) |
| e.observe(b.ID, res) |
| - // Refused on quota: only once the namespace's exit is proven does |
| - // the step move on, on another connection, from a fresh tree. |
| + // Refused on quota or the credential: only once the namespace's |
| + // exit is proven does the step move on, as a new attempt advanced |
| + // durably first, on another connection, from a fresh tree. |
| if res.limit == nil && !res.auth || !res.terminated || ctx.Err() != nil || e.Conns == nil { |
| break |
| } |
| - if res.auth { |
| - e.Conns.SignInAgain(b.ID) |
| - if rep.Switched == nil { |
| - rep.Switched = &wire.Switched{From: b.Provider} |
| - } |
| - } else { |
| - e.Conns.Limit(b.ID, *res.limit) |
| - if rep.Switched == nil { |
| - rep.Switched = e.Conns.LimitedFrom(b.ID) |
| - } |
| + if !e.refused(ctx, &r, &rep, b, res) { |
| + return fail("provider_failed", true) |
| } |
| - rep.Usage = append(rep.Usage, res.usage(b, r.Attempt)...) |
| avoid = append(avoid, b.ID) |
| if prompt, reason = prepare(); reason != "" { |
| return fail(reason, true) |
| @@ -274,6 +269,31 @@ func (e *Engineer) Exec(ctx context.Context, r stepRow, progress func(wire.StepR |
| return rep |
| } |
| +// refused records a refused attempt (quota: limited; credential: sign |
| +// in again), keeps the first switched line, and advances the step to its |
| +// next attempt durably with the refused attempt's usage. false: the |
| +// advance could not be recorded. |
| +func (e *Engineer) refused(ctx context.Context, r *stepRow, rep *wire.StepReport, b runner.AccountBinding, res stepResult) bool { |
| + if res.auth { |
| + e.Conns.SignInAgain(b.ID) |
| + if rep.Switched == nil { |
| + rep.Switched = &wire.Switched{From: b.Provider} |
| + } |
| + } else { |
| + e.Conns.Limit(b.ID, *res.limit) |
| + if rep.Switched == nil { |
| + rep.Switched = e.Conns.LimitedFrom(b.ID) |
| + } |
| + } |
| + used := usageRows(res.tokens, b, r.Attempt, wire.OutcomeFailed) |
| + if err := e.O.State.advanceStep(context.WithoutCancel(ctx), r, used, *rep); err != nil { |
| + e.log("step attempt", err) |
| + return false |
| + } |
| + rep.Attempt = r.Attempt |
| + return true |
| +} |
| + |
| // recordKept records the session a step's run kept, if it kept one. |
| func (e *Engineer) recordKept(ctx context.Context, r stepRow, account string, res stepResult, candidate string) bool { |
| if res.kept <= 0 || res.session == "" { |
diff --git a/internal/runner/thin/judge.go b/internal/runner/thin/judge.go| index 2026dea4..7bacb72b 100644 |
| --- a/internal/runner/thin/judge.go |
| +++ b/internal/runner/thin/judge.go |
| @@ -675,11 +675,14 @@ func (e *Engineer) review(ctx context.Context, r stepRow, progress func(wire.Ste |
| defer os.RemoveAll(tree.GitDir) |
| defer os.RemoveAll(tree.Dir) |
| b, label, err := e.reviewer(ctx, r.Person, r.AvoidAccount) |
| + if errors.Is(err, ErrNoConnection) { |
| + // Nothing can review now: the step waits, queued, and goes on its |
| + // own when a connection returns (spec §3); the queue moves on. |
| + rep.State = stepDeferred |
| + return rep |
| + } |
| if err != nil { |
| rep.State, rep.Reason, rep.Termination = wire.StepFailed, "account_unavailable", true |
| - if errors.Is(err, ErrNoConnection) { |
| - rep.Reason = wire.ReasonNoConnection |
| - } |
| return rep |
| } |
| rep.Family, rep.Account = b.Family, b.LocalID |
| @@ -706,16 +709,21 @@ func (e *Engineer) review(ctx context.Context, r stepRow, progress func(wire.Ste |
| } |
| res := e.run(ctx, r, tree, specialistRun{action: "inspect", binding: b, tools: reviewTools, names: []string{"submit_review", "ask_person"}, permission: claude.ReadPermission, call: call, prompt: e.reviewPrompt(r, diff), keep: e.keepDir(r), activity: e.stepActivity(r)}) |
| e.observe(b.ID, res) |
| - // Refused on quota before a verdict: once the exit is proven, Review |
| - // runs again on the next connection the choice gives (the refused one |
| - // is limited now), with its own independence label. |
| - for res.limit != nil && res.terminated && ctx.Err() == nil && e.Conns != nil && verdictUnset(&mu, &verdict) { |
| - e.Conns.Limit(b.ID, *res.limit) |
| - if rep.Switched == nil { |
| - rep.Switched = e.Conns.LimitedFrom(b.ID) |
| - } |
| - rep.Usage = append(rep.Usage, res.usage(b, r.Attempt)...) |
| + // Refused on quota or the credential before a verdict: once the exit |
| + // is proven, Review runs again as a new attempt, advanced durably, on |
| + // the next connection the choice gives (the refused one is limited or |
| + // signed out now), with its own independence label; with none left |
| + // the attempt waits and goes on its own when one returns. |
| + for (res.limit != nil || res.auth) && res.terminated && ctx.Err() == nil && e.Conns != nil && verdictUnset(&mu, &verdict) { |
| + if !e.refused(ctx, &r, &rep, b, res) { |
| + rep.State, rep.Reason, rep.Termination = wire.StepFailed, "provider_failed", true |
| + return rep |
| + } |
| next, nextLabel, err := e.reviewer(ctx, r.Person, r.AvoidAccount) |
| + if errors.Is(err, ErrNoConnection) { |
| + rep.State = stepDeferred |
| + return rep |
| + } |
| if err != nil { |
| break |
| } |
diff --git a/internal/runner/thin/link.go b/internal/runner/thin/link.go| index 0e78622d..606dfef1 100644 |
| --- a/internal/runner/thin/link.go |
| +++ b/internal/runner/thin/link.go |
| @@ -496,6 +496,13 @@ func (l *Link) read(ctx context.Context, c *websocket.Conn) (time.Duration, erro |
| if err = l.Connector.Disconnect(ctx, f.ID, *v); err != nil { |
| return 0, err |
| } |
| + case *wire.PreferenceCommand: |
| + if l.Connector == nil || l.Connector.Conns == nil { |
| + continue |
| + } |
| + if err = l.Connector.Conns.Prefer(ctx, f.ID, *v); err != nil { |
| + return 0, err |
| + } |
| case *wire.CancelConnectCommand: |
| if l.Connector == nil { |
| continue |
diff --git a/internal/runner/thin/step.go b/internal/runner/thin/step.go| index 30b24a33..c26d3f18 100644 |
| --- a/internal/runner/thin/step.go |
| +++ b/internal/runner/thin/step.go |
| @@ -69,11 +69,13 @@ func (s *State) RequestStepCancel(ctx context.Context, frameID string, c wire.Ca |
| if err != nil || !fresh { |
| return err |
| } |
| - res, err := t.Exec("UPDATE steps SET cancel=1 WHERE step_id=? AND attempt=? AND state=?", c.StepID, c.Attempt, runRunning) |
| + // The runner may have moved the step on to a later attempt (a |
| + // refusal failed over) before the instance heard: that one stops. |
| + res, err := t.Exec("UPDATE steps SET cancel=1 WHERE step_id=? AND attempt>=? AND state=?", c.StepID, c.Attempt, runRunning) |
| if err != nil { |
| return err |
| } |
| - if n, _ := res.RowsAffected(); n == 1 { |
| + if n, _ := res.RowsAffected(); n > 0 { |
| return nil |
| } |
| body, _ := json.Marshal(wire.DispatchCommand{Person: c.Person, TaskID: c.TaskID, StepID: c.StepID, Attempt: c.Attempt, Findings: []wire.Finding{}}) |
| @@ -117,7 +119,7 @@ func (s *State) nextStep(ctx context.Context) (stepRow, bool, error) { |
| // again then. The first deferral's time is kept (deferredSince). |
| func (s *State) deferStep(ctx context.Context, r stepRow, after time.Duration) error { |
| now := time.Now() |
| - _, err := s.db.ExecContext(ctx, "UPDATE steps SET not_before=?, deferred_since=CASE WHEN deferred_since='' THEN ? ELSE deferred_since END WHERE step_id=? AND attempt=? AND state=?", stamp(now.Add(after)), stamp(now), r.StepID, r.Attempt, runRunning) |
| + _, err := s.db.ExecContext(ctx, "UPDATE steps SET not_before=?, deferred_since=CASE WHEN deferred_since='' THEN ? ELSE deferred_since END WHERE step_id=? AND attempt>=? AND state=?", stamp(now.Add(after)), stamp(now), r.StepID, r.Attempt, runRunning) |
| return err |
| } |
| @@ -148,7 +150,7 @@ func (s *State) nextDue(ctx context.Context) (time.Time, bool) { |
| // stepCancelled re-reads an attempt's cancel mark. |
| func (s *State) stepCancelled(ctx context.Context, r stepRow) bool { |
| var cancel int |
| - _ = s.db.QueryRowContext(ctx, "SELECT cancel FROM steps WHERE step_id=? AND attempt=?", r.StepID, r.Attempt).Scan(&cancel) |
| + _ = s.db.QueryRowContext(ctx, "SELECT MAX(cancel) FROM steps WHERE step_id=? AND attempt>=? AND state=?", r.StepID, r.Attempt, runRunning).Scan(&cancel) |
| return cancel == 1 |
| } |
| @@ -176,7 +178,8 @@ func (s *State) ReportStep(ctx context.Context, r stepRow, rep wire.StepReport) |
| if !rep.Termination { |
| next = runPending |
| } |
| - res, err := t.Exec("UPDATE steps SET state=?, final_state=?, final_reason=? WHERE step_id=? AND attempt=? AND state=?", next, rep.State, rep.Reason, r.StepID, r.Attempt, runRunning) |
| + // The report's attempt: the step may have moved on from r's. |
| + res, err := t.Exec("UPDATE steps SET state=?, final_state=?, final_reason=? WHERE step_id=? AND attempt=? AND state=?", next, rep.State, rep.Reason, r.StepID, max(rep.Attempt, r.Attempt), runRunning) |
| if err != nil { |
| return err |
| } |
| @@ -188,6 +191,42 @@ func (s *State) ReportStep(ctx context.Context, r stepRow, rep wire.StepReport) |
| }) |
| } |
| +// advanceStep moves a running step to its next attempt after the |
| +// provider refused this one (quota or credential) and its exit was |
| +// proven (spec §3, Engineering mid-step): durably, before anything runs |
| +// on the next connection. The refused attempt's usage and the new |
| +// attempt (running, with the switched line) are reported in the same |
| +// transaction; the instance takes the step to the new attempt. |
| +func (s *State) advanceStep(ctx context.Context, r *stepRow, used []wire.Usage, rep wire.StepReport) error { |
| + next := r.DispatchCommand |
| + next.Attempt++ |
| + body, err := json.Marshal(next) |
| + if err != nil { |
| + return err |
| + } |
| + err = s.tx(ctx, func(t *sql.Tx) error { |
| + res, err := t.Exec("UPDATE steps SET attempt=attempt+1, body=?, phase='', ns_id='' WHERE step_id=? AND attempt=? AND state=?", string(body), r.StepID, r.Attempt, runRunning) |
| + if err != nil { |
| + return err |
| + } |
| + if n, _ := res.RowsAffected(); n != 1 { |
| + return errors.New("step not held") |
| + } |
| + if len(used) > 0 { |
| + if err = s.enqueue(t, wire.FrameUsage, "", wire.UsageReport{StepID: r.StepID, Rows: used}); err != nil { |
| + return err |
| + } |
| + } |
| + rep.Attempt, rep.State, rep.Reason = next.Attempt, wire.StepRunning, "" |
| + return s.enqueue(t, wire.FrameStep, "", rep) |
| + }) |
| + if err == nil { |
| + r.DispatchCommand = next |
| + r.Phase = phaseNone |
| + } |
| + return err |
| +} |
| + |
| // stepAcked finishes an attempt once the instance acked its final report. |
| func stepAcked(t *sql.Tx, body string) error { |
| var r wire.StepReport |
| @@ -362,8 +401,12 @@ type StepEngine struct { |
| mu sync.Mutex |
| wake chan struct{} |
| cancel context.CancelFunc |
| - cur string |
| - wg sync.WaitGroup |
| + // cur is the step (or "ask:" question) running now and curAttempt |
| + // the attempt it was taken at; a step moves to later attempts while |
| + // it runs (a refusal fails over), so a cancel for any of them stops it. |
| + cur string |
| + curAttempt int64 |
| + wg sync.WaitGroup |
| } |
| // Probe re-checks attempts whose termination is pending; a verified exit |
| @@ -450,7 +493,7 @@ func (e *StepEngine) CancelAsk(question string, attempt int64) { |
| func (e *StepEngine) Cancel(step string, attempt int64) { |
| e.mu.Lock() |
| defer e.mu.Unlock() |
| - if e.cur == step+"/"+itoa(attempt) && e.cancel != nil { |
| + if e.cur == step && attempt >= e.curAttempt && e.cancel != nil { |
| e.cancel() |
| } |
| } |
| @@ -559,7 +602,7 @@ func (e *StepEngine) askOne(ctx context.Context, a askRow) { |
| actx, cancel := context.WithCancel(ctx) |
| defer cancel() |
| e.mu.Lock() |
| - e.cancel, e.cur = cancel, "ask:"+a.QuestionID+"/"+itoa(a.Attempt) |
| + e.cancel, e.cur, e.curAttempt = cancel, "ask:"+a.QuestionID, a.Attempt |
| e.mu.Unlock() |
| defer func() { |
| e.mu.Lock() |
| @@ -615,7 +658,7 @@ func (e *StepEngine) runOne(ctx context.Context, r stepRow) { |
| sctx, cancel := context.WithCancel(ctx) |
| defer cancel() |
| e.mu.Lock() |
| - e.cancel, e.cur = cancel, r.key() |
| + e.cancel, e.cur, e.curAttempt = cancel, r.StepID, r.Attempt |
| e.mu.Unlock() |
| defer func() { |
| e.mu.Lock() |
diff --git a/internal/thintest/client.go b/internal/thintest/client.go| index be37fe85..95cd031c 100644 |
| --- a/internal/thintest/client.go |
| +++ b/internal/thintest/client.go |
| @@ -193,6 +193,21 @@ func (c *Client) SignOut(ctx context.Context, id string) (out wire.Connection, e |
| return out, c.do(ctx, "DELETE", "/api/v1/connections/"+id, nil, &out) |
| } |
| +// Preferences reads the person's preference. |
| +func (c *Client) Preferences(ctx context.Context) (out wire.Preferences, err error) { |
| + return out, c.do(ctx, "GET", "/api/v1/preferences", nil, &out) |
| +} |
| + |
| +// SetPreferences changes it, against the revision read. |
| +func (c *Client) SetPreferences(ctx context.Context, in wire.Preferences) (out wire.Preferences, err error) { |
| + return out, c.do(ctx, "PUT", "/api/v1/preferences", in, &out) |
| +} |
| + |
| +// Forget removes a signed-out connection's record. |
| +func (c *Client) Forget(ctx context.Context, id string) error { |
| + return c.do(ctx, "POST", "/api/v1/connections/"+id+"/forget", nil, nil) |
| +} |
| + |
| // CancelConnection ends an attempt. |
| func (c *Client) CancelConnection(ctx context.Context, id string) (out wire.Connection, err error) { |
| return out, c.do(ctx, "POST", "/api/v1/connections/"+id+"/cancel", nil, &out) |
| @@ -419,6 +434,10 @@ func (c *Conversation) Apply(e wire.Event) bool { |
| if json.Unmarshal(e.Data, &v) == nil { |
| if old, ok := c.Connections[v.ID]; !ok || v.Revision > old.Revision { |
| c.Connections[v.ID] = v |
| + if v.State == wire.ConnForgotten { |
| + // The last event of a record the person removed. |
| + delete(c.Connections, v.ID) |
| + } |
| applied = true |
| } |
| } |
diff --git a/internal/wire/connections.go b/internal/wire/connections.go| index baa92844..93003744 100644 |
| --- a/internal/wire/connections.go |
| +++ b/internal/wire/connections.go |
| @@ -15,6 +15,9 @@ const ( |
| ConnSignInAgain = "sign_in_again" |
| ConnError = "error" |
| ConnSignedOut = "signed_out" |
| + // ConnForgotten is only ever an event's: the person removed a record |
| + // the runner no longer holds, and clients drop it. |
| + ConnForgotten = "forgotten" |
| ) |
| // Providers and kinds a slice 1 connection may have. |
| @@ -121,8 +124,38 @@ const ( |
| FrameConnection = "connection" |
| // FrameDisconnect (instance to runner, durable) signs a connection out. |
| FrameDisconnect = "disconnect" |
| + // FramePreference (instance to runner, durable) carries the person's |
| + // preference, so the runner's choice has it offline. |
| + FramePreference = "preference" |
| ) |
| +// Preferences is GET and PUT /api/v1/preferences: the provider the |
| +// person prefers to answer, "" for Automatic. A preference orders the |
| +// choice among connections that can answer now; it never overrides |
| +// health, and a coordinator session moves to it only at the start of a |
| +// turn (spec §3, "The preference"). Slice 1 keeps one per person, by |
| +// provider; per-role rows come with routing (slice 3). Revision is the |
| +// one the change was made against on PUT. |
| +type Preferences struct { |
| + Provider string `json:"provider"` |
| + Revision int64 `json:"revision"` |
| +} |
| + |
| +// PreferenceProviders are the values Preferences.Provider may take. |
| +var PreferenceProviders = map[string]bool{"": true, "claude": true, "codex": true} |
| + |
| +// EventPreference fires when the person's preference changes; Data is |
| +// the Preferences. |
| +const EventPreference = "preference" |
| + |
| +// PreferenceCommand is the person's preference for the runner. A command |
| +// with a revision below the one the runner holds changes nothing. |
| +type PreferenceCommand struct { |
| + Person string `json:"person"` |
| + Provider string `json:"provider"` |
| + Revision int64 `json:"revision"` |
| +} |
| + |
| // DisconnectCommand signs one of the person's connections out: the |
| // harness's own logout, the home deleted, the binding gone. The runner |
| // answers with a connection report in state signed_out. |
diff --git a/internal/wire/connections_test.go b/internal/wire/connections_test.go| index e3654f4a..98a5bdd6 100644 |
| --- a/internal/wire/connections_test.go |
| +++ b/internal/wire/connections_test.go |
| @@ -63,7 +63,7 @@ func TestConnectionTypesCarryNoSecrets(t *testing.T) { |
| // TestConnectionFixturesCarryNoSecrets: the recorded documents a native |
| // app replays hold no secret-shaped key either. |
| func TestConnectionFixturesCarryNoSecrets(t *testing.T) { |
| - for _, name := range []string{"api/connections.json", "api/connection-connecting-codex.json", "api/connect-request.json", "api/event-connection.json", "frames/connect.json", "frames/cancel_connect.json", "frames/connection.json", "frames/hello.json", "frames/reply-usage.json", "frames/usage.json", "frames/disconnect.json", "frames/sync.json"} { |
| + for _, name := range []string{"api/connections.json", "api/connection-connecting-codex.json", "api/connect-request.json", "api/event-connection.json", "frames/connect.json", "frames/cancel_connect.json", "frames/connection.json", "frames/hello.json", "frames/reply-usage.json", "frames/usage.json", "frames/disconnect.json", "frames/sync.json", "frames/preference.json", "api/preferences.json", "api/event-preference.json"} { |
| raw := strings.ToLower(string(wiretest.Fixture(name))) |
| for _, bad := range []string{"token\"", "secret", "credential", "password", "sealed", "_key", "api_key", "access_token", "refresh"} { |
| if strings.Contains(raw, bad) { |
diff --git a/internal/wire/frames.go b/internal/wire/frames.go| index 2bfca1f2..b0b76690 100644 |
| --- a/internal/wire/frames.go |
| +++ b/internal/wire/frames.go |
| @@ -59,7 +59,7 @@ type Frame struct { |
| // Durable reports whether a frame must be acked and resent until acked. |
| func (f Frame) Durable() bool { |
| switch f.Type { |
| - case FrameMessage, FrameCancel, FrameReply, FrameTurn, FrameToolCall, FrameToolResult, FrameMoveIn, FrameNotebook, FrameReset, FrameDispatch, FrameCancelStep, FrameStep, FrameRecheck, FrameWatchMerge, FrameMerged, FrameAsk, FrameCancelAsk, FrameAnswer, FrameForgetTask, FrameBranch, FrameConnect, FrameCancelConnect, FrameConnection, FrameUsage, FrameDisconnect: |
| + case FrameMessage, FrameCancel, FrameReply, FrameTurn, FrameToolCall, FrameToolResult, FrameMoveIn, FrameNotebook, FrameReset, FrameDispatch, FrameCancelStep, FrameStep, FrameRecheck, FrameWatchMerge, FrameMerged, FrameAsk, FrameCancelAsk, FrameAnswer, FrameForgetTask, FrameBranch, FrameConnect, FrameCancelConnect, FrameConnection, FrameUsage, FrameDisconnect, FramePreference: |
| return true |
| } |
| return false |
| @@ -144,6 +144,8 @@ func (f Frame) Decode() (any, error) { |
| v = &UsageReport{} |
| case FrameDisconnect: |
| v = &DisconnectCommand{} |
| + case FramePreference: |
| + v = &PreferenceCommand{} |
| case FrameStepActivity: |
| v = &StepActivityReport{} |
| default: |
diff --git a/internal/wire/wire_test.go b/internal/wire/wire_test.go| index d44f78db..83b6397d 100644 |
| --- a/internal/wire/wire_test.go |
| +++ b/internal/wire/wire_test.go |
| @@ -33,7 +33,7 @@ func TestFrameFixturesRoundTrip(t *testing.T) { |
| t.Fatalf("%s: round trip\n got %s\nwant %s", name, out, raw) |
| } |
| } |
| - for _, kind := range []string{wire.FrameWelcome, wire.FrameMessage, wire.FrameCancel, wire.FrameDrain, wire.FrameAck, wire.FrameHello, wire.FrameSync, wire.FrameDelta, wire.FrameReply, wire.FrameTurn, wire.FrameLease, wire.FrameToolCall, wire.FrameToolResult, wire.FrameActivity, wire.FrameMoveIn, wire.FrameNotebook, wire.FrameReset, wire.FrameDispatch, wire.FrameCancelStep, wire.FrameStep, wire.FrameRecheck, wire.FrameWatchMerge, wire.FrameMerged, wire.FrameAsk, wire.FrameCancelAsk, wire.FrameAnswer, wire.FrameForgetTask, wire.FrameBranch, wire.FrameConnect, wire.FrameCancelConnect, wire.FrameConnection, wire.FrameUsage, wire.FrameDisconnect, wire.FrameStepActivity} { |
| + for _, kind := range []string{wire.FrameWelcome, wire.FrameMessage, wire.FrameCancel, wire.FrameDrain, wire.FrameAck, wire.FrameHello, wire.FrameSync, wire.FrameDelta, wire.FrameReply, wire.FrameTurn, wire.FrameLease, wire.FrameToolCall, wire.FrameToolResult, wire.FrameActivity, wire.FrameMoveIn, wire.FrameNotebook, wire.FrameReset, wire.FrameDispatch, wire.FrameCancelStep, wire.FrameStep, wire.FrameRecheck, wire.FrameWatchMerge, wire.FrameMerged, wire.FrameAsk, wire.FrameCancelAsk, wire.FrameAnswer, wire.FrameForgetTask, wire.FrameBranch, wire.FrameConnect, wire.FrameCancelConnect, wire.FrameConnection, wire.FrameUsage, wire.FrameDisconnect, wire.FrameStepActivity, wire.FramePreference} { |
| if !seen[kind] { |
| t.Fatalf("no fixture for frame %s", kind) |
| } |
| @@ -73,7 +73,7 @@ func TestParseFrameRefusesUnknownFieldsAndTypes(t *testing.T) { |
| } |
| func TestDurableFrames(t *testing.T) { |
| - for kind, want := range map[string]bool{wire.FrameMessage: true, wire.FrameCancel: true, wire.FrameReply: true, wire.FrameTurn: true, wire.FrameToolCall: true, wire.FrameToolResult: true, wire.FrameActivity: false, wire.FrameDelta: false, wire.FrameHello: false, wire.FrameSync: false, wire.FrameAck: false, wire.FrameWelcome: false, wire.FrameDrain: false} { |
| + for kind, want := range map[string]bool{wire.FrameMessage: true, wire.FrameCancel: true, wire.FrameReply: true, wire.FrameTurn: true, wire.FrameToolCall: true, wire.FrameToolResult: true, wire.FrameActivity: false, wire.FrameDelta: false, wire.FrameHello: false, wire.FrameSync: false, wire.FrameAck: false, wire.FrameWelcome: false, wire.FrameDrain: false, wire.FramePreference: true} { |
| if (wire.Frame{Type: kind}).Durable() != want { |
| t.Fatalf("%s durable=%v", kind, !want) |
| } |
diff --git a/internal/wire/wiretest/fixtures.go b/internal/wire/wiretest/fixtures.go| index 992e464e..890eb5f8 100644 |
| --- a/internal/wire/wiretest/fixtures.go |
| +++ b/internal/wire/wiretest/fixtures.go |
| @@ -55,7 +55,7 @@ func APIType(name string) any { |
| return &wire.CancelAccepted{} |
| case "error-conflict.json": |
| return &wire.Error{} |
| - case "event-delta.json", "event-turn.json", "event-runner.json", "event-card.json", "event-project.json", "event-activity.json", "event-coordinator.json", "event-task.json", "event-step.json", "event-question.json", "event-connection.json", "event-step-activity.json": |
| + case "event-delta.json", "event-turn.json", "event-runner.json", "event-card.json", "event-project.json", "event-activity.json", "event-coordinator.json", "event-task.json", "event-step.json", "event-question.json", "event-connection.json", "event-step-activity.json", "event-preference.json": |
| return &wire.Event{} |
| case "project.json": |
| return &wire.Project{} |
| @@ -95,6 +95,8 @@ func APIType(name string) any { |
| return &wire.Connection{} |
| case "connect-request.json": |
| return &wire.Connect{} |
| + case "preferences.json": |
| + return &wire.Preferences{} |
| case "duplicate-request.json": |
| return &wire.MarkDuplicate{} |
| } |
diff --git a/internal/wire/wiretest/testdata/api/event-preference.json b/internal/wire/wiretest/testdata/api/event-preference.json| new file mode 100644 |
| index 00000000..d91c5e44 |
| --- /dev/null |
| +++ b/internal/wire/wiretest/testdata/api/event-preference.json |
| @@ -0,0 +1 @@ |
| +{"cursor":43,"type":"preference","resource":"preference","id":"owner@example.com","revision":2,"data":{"provider":"codex","revision":2}} |
diff --git a/internal/wire/wiretest/testdata/api/preferences.json b/internal/wire/wiretest/testdata/api/preferences.json| new file mode 100644 |
| index 00000000..f589f50d |
| --- /dev/null |
| +++ b/internal/wire/wiretest/testdata/api/preferences.json |
| @@ -0,0 +1 @@ |
| +{"provider":"codex","revision":2} |
diff --git a/internal/wire/wiretest/testdata/frames/preference.json b/internal/wire/wiretest/testdata/frames/preference.json| new file mode 100644 |
| index 00000000..44293bf5 |
| --- /dev/null |
| +++ b/internal/wire/wiretest/testdata/frames/preference.json |
| @@ -0,0 +1 @@ |
| +{"id":"c44","type":"preference","data":{"person":"owner@example.com","provider":"codex","revision":2}} |