Spend: leave out overcounting Claude rows; Codex usage confirmed per turn
Before ProtocolSpend the runner read Claude's modelUsage, the session's running total, as a turn's own use. Engineering, Review and token checks ran one result per session and are exact; coordinator turns and answers were not. Those rows are upper bounds, so they are marked, not rewritten: migration 0059 sets overcount on every earlier Claude coordinator and answer row, and the instance sets it on such rows from a runner below ProtocolSpend. Sums leave them out: the task page says "Earlier usage not shown" (work.spend_left_out, COPY REVIEW REQUIRED) and today's tokens on Connections skip them. Nothing else reads chat_usage (housekeeping charges its own ledger; failover and headroom use the provider's limits on the runner). Codex: TestCodexTallyRecordedPerTurn replays the recorded app-server turn as later turns of one thread and of a resumed thread; each row is the turn's own use, never the running total.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
15 files changed,
+175
−29
.rastrillo/budgets.txt+1 −1docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md+1 −0internal/equipo/chat/connections.go+21 −10internal/equipo/chat/questions.go+2 −2internal/equipo/chat/runner.go+1 −1internal/equipo/chat/tasks.go+1 −1internal/equipo/copy.go+1 −0internal/equipo/migrations/0059_usage_round_turns.sql+2 −0internal/equipo/migrations/schema.sql+1 −1internal/equipo/templates/work_task.html+1 −1internal/equipo/work_pages.go+2 −1internal/equipo/work_spend.go+8 −5internal/equipo/work_spend_test.go+8 −4internal/runner/connect/usage_test.go+55 −0internal/thintest/spend_pages_test.go+70 −2
CI passed — run details
Intent
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index 29f875d2..9d7ab56e 100644 |
| --- a/.rastrillo/budgets.txt |
| +++ b/.rastrillo/budgets.txt |
| @@ -62,4 +62,4 @@ perf GET /conversation/attachments/{id}/preview skip Composer attachments: an im |
| perf GET /api/v1/runners skip Mac runners person API: bearer-only JSON for devices; the browser shows runners in the Team section. |
| time cmd/equipo-runner 60s Mac runners slice B: TestReleaseRunnerHasNoFakeWorker builds the release runner exactly as make release-runner does and the thin package under the testbuild tag (measured 11.9s locally with a warm cache). |
| size internal/headless - 8300 Claude's sign-in by a link adds its end-to-end, contained-launch and real runner kill tests (signin_test.go, signin_contained_test.go, about 400 lines); measured 8090. |
| -size internal/thintest - 10200 Spend 1 adds the task page's spend contract and the 0059 upgrade (spend_pages_test.go, about 100 lines) and the fix round feedback by protocol (about 40); measured 10104. Claude's sign-in by a link adds the code contract (signin_contract_test.go: the card, the code route's refusals, the wrong-code card, the kind it becomes and the canary sweep, about 220 lines); measured 9896. The Connections Add page and the Settings rail add their page contracts and the rail's browser drive (connections_add_pages_test.go, settings_rail_pages_test.go, about 230 lines); measured 9676. Claude setup tokens add the token and Check again contracts; measured 9444 with the composer and Mac lines merged. The instant thinking line adds its browser drive (instant_browser_test.go, about 230 lines); measured 9064 with the composer and Mac lines merged. Mac runners add the role, scoping, migration, placement, withdrawal, transfer and publication contracts (about 900 test lines) beside the thin v1 contracts; one package keeps one instance harness. |
| +size internal/thintest - 10300 Spend 1 marks overcounting Claude rows (about 120 lines); it adds the task page's spend contract and the 0059 upgrade (spend_pages_test.go, about 100 lines) and the fix round feedback by protocol (about 40); measured 10224. Claude's sign-in by a link adds the code contract (signin_contract_test.go: the card, the code route's refusals, the wrong-code card, the kind it becomes and the canary sweep, about 220 lines); measured 9896. The Connections Add page and the Settings rail add their page contracts and the rail's browser drive (connections_add_pages_test.go, settings_rail_pages_test.go, about 230 lines); measured 9676. Claude setup tokens add the token and Check again contracts; measured 9444 with the composer and Mac lines merged. The instant thinking line adds its browser drive (instant_browser_test.go, about 230 lines); measured 9064 with the composer and Mac lines merged. Mac runners add the role, scoping, migration, placement, withdrawal, transfer and publication contracts (about 900 test lines) beside the thin v1 contracts; one package keeps one instance harness. |
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md| index e1093650..69e72480 100644 |
| --- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| +++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| @@ -5887,6 +5887,7 @@ records remain unchanged. |
| | `work.spend_step` | %s: %s tokens (%s cached) | Spend 1 (task page and specialist panel) | Runtime; COPY REVIEW REQUIRED | |
| | `work.spend_step_uncached` | %s: %s tokens | Spend 1 (task page and specialist panel) | Runtime; COPY REVIEW REQUIRED | |
| | `work.spend_questions` | Questions | Spend 1 (task page and specialist panel) | Runtime; COPY REVIEW REQUIRED | |
| +| `work.spend_left_out` | Earlier usage not shown | Spend 1 (task page) | Runtime; COPY REVIEW REQUIRED | |
| | `work.spend_steps` | Tokens each step used | Spend 1 (task page and specialist panel) | Runtime; COPY REVIEW REQUIRED | |
| ## Task 21 |
diff --git a/internal/equipo/chat/connections.go b/internal/equipo/chat/connections.go| index 00e4d61d..11e1b49c 100644 |
| --- a/internal/equipo/chat/connections.go |
| +++ b/internal/equipo/chat/connections.go |
| @@ -75,6 +75,11 @@ type usageRecord struct { |
| // Turns is how many model requests the attempt made (null: unknown). |
| Round int |
| Turns *int64 |
| + // Overcount: a Claude coordinator turn's or answer's row from a runner |
| + // before ProtocolSpend, which read the session's running total |
| + // (modelUsage) as the turn's own. It is at most what was used, often |
| + // more; sums leave it out and say so. |
| + Overcount bool |
| // Figures the harness did not report stay null, never zero. |
| InputTokens *int64 |
| CachedInputTokens *int64 |
| @@ -672,12 +677,12 @@ var usageOutcomes = map[string]bool{wire.OutcomeReplied: true, wire.OutcomeFaile |
| // recordUsage keeps one row per attempt and model, keyed so a resent |
| // frame changes nothing. turn is a coordinator turn, step a step or a |
| // question; round the step's fix round. |
| -func (t *txn) recordUsage(person, role, task, step, turn string, round int, rows []wire.Usage) error { |
| +func (t *txn) recordUsage(protocol int, person, role, task, step, turn string, round int, rows []wire.Usage) error { |
| for _, u := range rows { |
| if !usageOutcomes[u.Outcome] || u.Attempt < 1 || len(u.Model) > 200 || len(u.Connection) > 200 || u.Turns != nil && *u.Turns < 0 { |
| return ErrInvalid |
| } |
| - r := usageRecord{Person: person, Connection: u.Connection, Provider: u.Provider, Model: u.Model, Role: role, TaskID: task, StepID: step, TurnID: turn, Attempt: u.Attempt, Outcome: u.Outcome, Complete: u.Complete, InputTokens: u.InputTokens, CachedInputTokens: u.CachedInputTokens, CacheWriteTokens: u.CacheWriteTokens, OutputTokens: u.OutputTokens, ReasoningOutputTokens: u.ReasoningOutputTokens, Round: round, Turns: u.Turns, RecordedAt: t.now()} |
| + r := usageRecord{Person: person, Connection: u.Connection, Provider: u.Provider, Model: u.Model, Role: role, TaskID: task, StepID: step, TurnID: turn, Attempt: u.Attempt, Outcome: u.Outcome, Complete: u.Complete, InputTokens: u.InputTokens, CachedInputTokens: u.CachedInputTokens, CacheWriteTokens: u.CacheWriteTokens, OutputTokens: u.OutputTokens, ReasoningOutputTokens: u.ReasoningOutputTokens, Round: round, Turns: u.Turns, Overcount: protocol < wire.ProtocolSpend && u.Provider == "claude" && (role == "coordinator" || role == "ask"), RecordedAt: t.now()} |
| if err := t.db.Clauses(clause.OnConflict{DoNothing: true}).Create(&r).Error; err != nil { |
| return err |
| } |
| @@ -703,7 +708,7 @@ func (t *txn) usageReport(l Lease, v *wire.UsageReport) error { |
| if _, err := t.ownTurn(l, v.TurnID); err != nil { |
| return err |
| } |
| - return t.recordUsage(person, "coordinator", "", "", v.TurnID, 0, v.Rows) |
| + return t.recordUsage(l.Protocol, person, "coordinator", "", "", v.TurnID, 0, v.Rows) |
| case v.StepID != "" && v.TurnID == "" && v.QuestionID == "": |
| var s stepRecord |
| if err := t.db.Where("id = ? AND person = ?", v.StepID, person).First(&s).Error; errors.Is(err, gorm.ErrRecordNotFound) { |
| @@ -711,7 +716,7 @@ func (t *txn) usageReport(l Lease, v *wire.UsageReport) error { |
| } else if err != nil { |
| return err |
| } |
| - return t.recordUsage(person, s.Specialist, s.TaskID, s.ID, "", s.Round, v.Rows) |
| + return t.recordUsage(l.Protocol, person, s.Specialist, s.TaskID, s.ID, "", s.Round, v.Rows) |
| case v.QuestionID != "" && v.TurnID == "" && v.StepID == "": |
| q, err := t.ownQuestion(l, v.QuestionID) |
| if err != nil { |
| @@ -721,14 +726,14 @@ func (t *txn) usageReport(l Lease, v *wire.UsageReport) error { |
| if err != nil { |
| return err |
| } |
| - return t.recordUsage(person, "ask", q.TaskID, q.ID, "", round, v.Rows) |
| + return t.recordUsage(l.Protocol, person, "ask", q.TaskID, q.ID, "", round, v.Rows) |
| case v.CheckID != "" && v.TurnID == "" && v.StepID == "" && v.QuestionID == "": |
| // A token connection's health check: a real request on the |
| // person's own connection, keyed by the check so each counts. |
| if len(v.CheckID) > 200 { |
| return ErrInvalid |
| } |
| - return t.recordUsage(person, "check", "", v.CheckID, "", 0, v.Rows) |
| + return t.recordUsage(l.Protocol, person, "check", "", v.CheckID, "", 0, v.Rows) |
| } |
| return ErrInvalid |
| } |
| @@ -772,12 +777,14 @@ func (s *Spend) add(o Spend) { |
| } |
| // TaskSpend is a task's recorded usage: in all, per step, and for the |
| -// questions asked about it. Rows is how many usage rows there were. |
| +// questions asked about it. Rows is how many usage rows it counts; |
| +// Left out says rows were left out because they overcount. |
| type TaskSpend struct { |
| Total Spend |
| Steps map[string]Spend |
| Questions Spend |
| Rows int |
| + LeftOut bool |
| } |
| // TaskSpend reads a task's usage rows for anyone on the team who can |
| @@ -798,6 +805,11 @@ func (s *Store) TaskSpend(ctx context.Context, person, id string) (out TaskSpend |
| return err |
| } |
| for _, r := range rows { |
| + if r.Overcount { |
| + out.LeftOut = true |
| + continue |
| + } |
| + out.Rows++ |
| one := rowSpend(r) |
| out.Total.add(one) |
| if r.Role == "ask" { |
| @@ -808,7 +820,6 @@ func (s *Store) TaskSpend(ctx context.Context, person, id string) (out TaskSpend |
| out.Steps[r.StepID] = step |
| } |
| } |
| - out.Rows = len(rows) |
| return nil |
| }) |
| return out, err |
| @@ -835,7 +846,7 @@ func figure(p *int64) int64 { |
| } |
| // UsageToday sums the person's recorded tokens (input and output) per |
| -// connection since midnight UTC. |
| +// connection since midnight UTC, without rows that overcount. |
| func (s *Store) UsageToday(ctx context.Context, person string) (map[string]int64, error) { |
| out := map[string]int64{} |
| err := s.read(ctx, func(tx *gorm.DB) error { |
| @@ -844,7 +855,7 @@ func (s *Store) UsageToday(ctx context.Context, person string) (map[string]int64 |
| N int64 |
| } |
| day := s.now().UTC().Truncate(24 * time.Hour) |
| - if err := tx.Raw("SELECT connection, sum(coalesce(input_tokens,0) + coalesce(output_tokens,0)) AS n FROM chat_usage WHERE person = ? AND recorded_at >= ? GROUP BY connection", person, day).Scan(&rows).Error; err != nil { |
| + if err := tx.Raw("SELECT connection, sum(coalesce(input_tokens,0) + coalesce(output_tokens,0)) AS n FROM chat_usage WHERE person = ? AND recorded_at >= ? AND NOT coalesce(overcount, 0) GROUP BY connection", person, day).Scan(&rows).Error; err != nil { |
| return err |
| } |
| for _, r := range rows { |
diff --git a/internal/equipo/chat/questions.go b/internal/equipo/chat/questions.go| index 1f5628b2..69c6d5e8 100644 |
| --- a/internal/equipo/chat/questions.go |
| +++ b/internal/equipo/chat/questions.go |
| @@ -431,7 +431,7 @@ func (t *txn) answer(l Lease, v *wire.AnswerReport) error { |
| if err != nil { |
| return err |
| } |
| - if err := t.recordUsage(q.Asker, "ask", q.TaskID, q.ID, "", round, v.Usage); err != nil { |
| + if err := t.recordUsage(l.Protocol, q.Asker, "ask", q.TaskID, q.ID, "", round, v.Usage); err != nil { |
| return err |
| } |
| if v.Timing != nil { |
| @@ -445,7 +445,7 @@ func (t *txn) answer(l Lease, v *wire.AnswerReport) error { |
| if err != nil { |
| return err |
| } |
| - if err := t.recordUsage(q.Asker, "ask", q.TaskID, q.ID, "", round, v.Usage); err != nil { |
| + if err := t.recordUsage(l.Protocol, q.Asker, "ask", q.TaskID, q.ID, "", round, v.Usage); err != nil { |
| return err |
| } |
| default: |
diff --git a/internal/equipo/chat/runner.go b/internal/equipo/chat/runner.go| index ba5ce8e6..3114e7db 100644 |
| --- a/internal/equipo/chat/runner.go |
| +++ b/internal/equipo/chat/runner.go |
| @@ -398,7 +398,7 @@ func (t *txn) reply(l Lease, v *wire.Reply) error { |
| for _, u := range v.Usage { |
| r.Connection = u.Connection |
| } |
| - if err := t.recordUsage(r.Person, "coordinator", "", "", r.ID, 0, v.Usage); err != nil { |
| + if err := t.recordUsage(l.Protocol, r.Person, "coordinator", "", "", r.ID, 0, v.Usage); err != nil { |
| return err |
| } |
| // A move-in or explore turn with nothing to say posts nothing. |
diff --git a/internal/equipo/chat/tasks.go b/internal/equipo/chat/tasks.go| index b8ba8444..d2d92d76 100644 |
| --- a/internal/equipo/chat/tasks.go |
| +++ b/internal/equipo/chat/tasks.go |
| @@ -947,7 +947,7 @@ func (t *txn) stepReport(l Lease, v *wire.StepReport) error { |
| } |
| } else { |
| if wire.StepTerminal(v.State) { |
| - if err := t.recordUsage(s.Person, s.Specialist, s.TaskID, s.ID, "", s.Round, v.Usage); err != nil { |
| + if err := t.recordUsage(l.Protocol, s.Person, s.Specialist, s.TaskID, s.ID, "", s.Round, v.Usage); err != nil { |
| return err |
| } |
| } |
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go| index 434bf820..c2e82f7a 100644 |
| --- a/internal/equipo/copy.go |
| +++ b/internal/equipo/copy.go |
| @@ -585,6 +585,7 @@ var pageCopy = map[string]string{ |
| "work.spend_step": "%s: %s tokens (%s cached)", // COPY REVIEW REQUIRED |
| "work.spend_step_uncached": "%s: %s tokens", // COPY REVIEW REQUIRED |
| "work.spend_questions": "Questions", // COPY REVIEW REQUIRED |
| + "work.spend_left_out": "Earlier usage not shown", // COPY REVIEW REQUIRED |
| "work.spend_steps": "Tokens each step used", // COPY REVIEW REQUIRED |
| "work.checks.passed": "Checks passed (%s)", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| "work.checks.failed": "Checks failed (%s, exit %d)", // COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
diff --git a/internal/equipo/migrations/0059_usage_round_turns.sql b/internal/equipo/migrations/0059_usage_round_turns.sql| index 4afb87e2..79190413 100644 |
| --- a/internal/equipo/migrations/0059_usage_round_turns.sql |
| +++ b/internal/equipo/migrations/0059_usage_round_turns.sql |
| @@ -1,2 +1,4 @@ |
| ALTER TABLE chat_usage ADD COLUMN round integer; |
| ALTER TABLE chat_usage ADD COLUMN turns integer; |
| +ALTER TABLE chat_usage ADD COLUMN overcount numeric; |
| +UPDATE chat_usage SET overcount = 1 WHERE provider = 'claude' AND role IN ('coordinator', 'ask'); |
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql| index 1611e9fd..15148b11 100644 |
| --- a/internal/equipo/migrations/schema.sql |
| +++ b/internal/equipo/migrations/schema.sql |
| @@ -609,7 +609,7 @@ CREATE INDEX chat_question_task ON chat_questions(task_id); |
| CREATE UNIQUE INDEX chat_question_key ON chat_questions(task_id, asker, idempotency_key); |
| CREATE TABLE chat_connections (id text PRIMARY KEY, person text, runner_id text, local_id text, provider text, kind text, label text, state text, reason text, plan text, headroom text, prompt text, revision integer, created_at datetime, updated_at datetime, expires_at datetime, expires_estimated numeric); |
| CREATE INDEX chat_connection_person ON chat_connections(person); |
| -CREATE TABLE chat_usage (id integer PRIMARY KEY, person text, connection text, provider text, model text, role text, task_id text, step_id text, turn_id text, attempt integer, outcome text, complete numeric, input_tokens integer, cached_input_tokens integer, cache_write_tokens integer, output_tokens integer, reasoning_output_tokens integer, recorded_at datetime, round integer, turns integer); |
| +CREATE TABLE chat_usage (id integer PRIMARY KEY, person text, connection text, provider text, model text, role text, task_id text, step_id text, turn_id text, attempt integer, outcome text, complete numeric, input_tokens integer, cached_input_tokens integer, cache_write_tokens integer, output_tokens integer, reasoning_output_tokens integer, recorded_at datetime, round integer, turns integer, overcount numeric); |
| CREATE INDEX chat_usage_person ON chat_usage(person, recorded_at); |
| CREATE UNIQUE INDEX chat_usage_key ON chat_usage(turn_id, step_id, attempt, connection, model); |
| CREATE INDEX chat_tool_call_turn ON chat_tool_calls(turn_id, op); |
diff --git a/internal/equipo/templates/work_task.html b/internal/equipo/templates/work_task.html| index e7da7331..e079d082 100644 |
| --- a/internal/equipo/templates/work_task.html |
| +++ b/internal/equipo/templates/work_task.html |
| @@ -10,7 +10,7 @@ |
| </div> |
| {{template "track-full" .}} |
| <p equipo-t-summary data-summary>{{if .Live}}{{template "mark" ""}}{{end}}<span data-stage-line>{{.Summary}}</span></p> |
| -{{with .Spend}}<p equipo-quiet data-spend>{{.}}</p>{{end}} |
| +{{with .Spend}}<p equipo-quiet data-spend>{{.}}</p>{{end}}{{with .SpendNote}}<p equipo-quiet data-spend-note>{{.}}</p>{{end}} |
| {{with .Dup}}{{if not $.Thin.Task.Decision}}<p equipo-dup>{{icon "alert-triangle"}}<span>{{copy "work.dup"}} <a href="/tasks/{{.ID}}">{{.Title}}</a>{{if not $.Thin.Task.Mine}} {{printf (copy "work.dup_decides") $.Thin.Task.Creator.Name}}{{end}}</span></p>{{end}}{{end}} |
| {{with .Folded}}<div equipo-combined data-folded>{{icon "check-circle"}}<span>{{copy "work.combined_line"}} <a href="/tasks/{{.Into.ID}}">{{.Into.Title}}</a>.</span>{{if $.Thin.Task.Mine}}<form method="post" action="/tasks/{{$.Thin.Task.ID}}/uncombine"><input type="hidden" name="from" value="task"><button equipo-link type="submit" data-uncombine>{{copy "chat.card.undo"}}</button></form>{{end}}</div>{{end}} |
| {{range .Combined}}<div equipo-combined data-combined="{{.ID}}">{{icon "check-circle"}}<span>{{printf (copy "work.combined_here") .Title}} <a href="/tasks/{{.ID}}">{{copy "work.combined_open"}}</a></span>{{if $.Thin.Task.Mine}}<form method="post" action="/tasks/{{.ID}}/uncombine"><input type="hidden" name="from" value="task"><input type="hidden" name="task" value="{{$.Thin.Task.ID}}"><button equipo-link type="submit" data-uncombine>{{copy "chat.card.undo"}}</button></form>{{end}}</div>{{end}} |
diff --git a/internal/equipo/work_pages.go b/internal/equipo/work_pages.go| index 76effcf9..41192a1a 100644 |
| --- a/internal/equipo/work_pages.go |
| +++ b/internal/equipo/work_pages.go |
| @@ -57,6 +57,7 @@ type taskLine struct { |
| Summary string |
| Timeline []timelineItem |
| Spend string |
| + SpendNote string |
| StepSpend []spendLine |
| } |
| @@ -477,7 +478,7 @@ func (a *application) workTask(w http.ResponseWriter, r *http.Request) bool { |
| v.Summary, v.Timeline = summaryOf(t, v), timelineOf(t, v) |
| // What it used; an unreadable sum shows nothing, never zero. |
| if sp, err := a.store.Chat().TaskSpend(ctx, address, id); err == nil { |
| - v.Spend, v.StepSpend = spendOf(t, sp) |
| + v.Spend, v.SpendNote, v.StepSpend = spendOf(t, sp) |
| } |
| data.Thin.Task, data.Title, data.RequestID = v, "nav.tasks", rand.Text() |
| data.Thin.Thread, data.ChatStream = threadOf(t, address, cursor), true |
diff --git a/internal/equipo/work_spend.go b/internal/equipo/work_spend.go| index 9e03b3da..c86b7b63 100644 |
| --- a/internal/equipo/work_spend.go |
| +++ b/internal/equipo/work_spend.go |
| @@ -16,12 +16,15 @@ type spendLine struct { |
| // spendOf is what a task used, in words: the task's quiet line and, in |
| // step order, one line per step that recorded usage (then the questions |
| -// asked about it). Nothing when no usage was recorded. |
| -func spendOf(t wire.Task, sp chat.TaskSpend) (string, []spendLine) { |
| +// asked about it). Nothing when no usage was recorded. note says rows |
| +// were left out because they overcount (an older runner's answers). |
| +func spendOf(t wire.Task, sp chat.TaskSpend) (total, note string, lines []spendLine) { |
| + if sp.LeftOut { |
| + note = copyText("work.spend_left_out") |
| + } |
| if sp.Rows == 0 { |
| - return "", nil |
| + return "", note, nil |
| } |
| - var lines []spendLine |
| for _, s := range t.Steps { |
| one, ok := sp.Steps[s.ID] |
| if !ok { |
| @@ -36,7 +39,7 @@ func spendOf(t wire.Task, sp chat.TaskSpend) (string, []spendLine) { |
| if sp.Questions != (chat.Spend{}) { |
| lines = append(lines, spendLine{Step: "questions", Line: spendWords(sp.Questions, copyText("work.spend_questions"))}) |
| } |
| - return spendWords(sp.Total, ""), lines |
| + return spendWords(sp.Total, ""), note, lines |
| } |
| // spendWords is one sum in words: the task's line when name is empty, |
diff --git a/internal/equipo/work_spend_test.go b/internal/equipo/work_spend_test.go| index cde63876..f06b818f 100644 |
| --- a/internal/equipo/work_spend_test.go |
| +++ b/internal/equipo/work_spend_test.go |
| @@ -17,8 +17,8 @@ func TestSpendWords(t *testing.T) { |
| } |
| task := wire.Task{Steps: []wire.Step{{ID: "s1", Specialist: wire.SpecialistEngineering}, {ID: "s2", Specialist: wire.SpecialistChecks}, {ID: "s3", Specialist: wire.SpecialistEngineering, Round: 1}}} |
| sp := chat.TaskSpend{Rows: 3, Total: chat.Spend{Tokens: 50_000, Partial: true}, Steps: map[string]chat.Spend{"s1": {Tokens: 40_000, Cached: 30_000}, "s3": {Tokens: 9_000, Partial: true}}, Questions: chat.Spend{Tokens: 1_000}} |
| - total, lines := spendOf(task, sp) |
| - if total != "Used at least 50k tokens" { |
| + total, note, lines := spendOf(task, sp) |
| + if total != "Used at least 50k tokens" || note != "" { |
| t.Fatalf("total %q", total) |
| } |
| want := []spendLine{{"s1", "Engineering: 40k tokens (30k cached)"}, {"s3", "Engineering, fix round 1: at least 9k tokens"}, {"questions", "Questions: 1k tokens"}} |
| @@ -30,7 +30,11 @@ func TestSpendWords(t *testing.T) { |
| t.Fatalf("line %d %+v, want %+v", i, lines[i], want[i]) |
| } |
| } |
| - if total, lines := spendOf(task, chat.TaskSpend{}); total != "" || lines != nil { |
| - t.Fatalf("no rows: %q %+v", total, lines) |
| + if total, note, lines := spendOf(task, chat.TaskSpend{}); total != "" || note != "" || lines != nil { |
| + t.Fatalf("no rows: %q %q %+v", total, note, lines) |
| + } |
| + // Rows left out because they overcount: said, never summed. |
| + if total, note, lines := spendOf(task, chat.TaskSpend{LeftOut: true}); total != "" || note != "Earlier usage not shown" || lines != nil { |
| + t.Fatalf("left out: %q %q %+v", total, note, lines) |
| } |
| } |
diff --git a/internal/runner/connect/usage_test.go b/internal/runner/connect/usage_test.go| index 7b910102..590c7ab4 100644 |
| --- a/internal/runner/connect/usage_test.go |
| +++ b/internal/runner/connect/usage_test.go |
| @@ -221,3 +221,58 @@ func TestClaudeRowsPerResult(t *testing.T) { |
| } |
| } |
| } |
| + |
| +// The recorded app-server's notice carries the thread's running total |
| +// (and the last request's figures). A tally's row is per turn, never |
| +// that running total: the recorded turn replayed as a second turn of |
| +// the same thread (its totals continuing from the first's, as the |
| +// app-server reports them) gives the same figures again, verified and |
| +// complete; replayed in a process that resumed the thread (no base), it |
| +// is the sum of the turn's own requests it saw, never complete. |
| +func TestCodexTallyRecordedPerTurn(t *testing.T) { |
| + raw, err := os.ReadFile("../provider/codex/testdata/probe.jsonl") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var notices []json.RawMessage |
| + for _, line := range strings.Split(string(raw), "\n") { |
| + var m struct { |
| + Method string `json:"method"` |
| + Params json.RawMessage `json:"params"` |
| + } |
| + if json.Unmarshal([]byte(line), &m) == nil && m.Method == "thread/tokenUsage/updated" { |
| + notices = append(notices, m.Params) |
| + } |
| + } |
| + if len(notices) != 2 { |
| + t.Fatalf("%d notices", len(notices)) |
| + } |
| + // turn replays the recorded notices as turn id, its totals offset by |
| + // what the thread had used before it. |
| + turn := func(tally *CodexTally, id string, base, baseOut int64) { |
| + tally.Begin(id) |
| + for _, p := range notices { |
| + thread, _, total, last, ok := CodexNotice(p) |
| + if !ok { |
| + t.Fatal("notice") |
| + } |
| + in, out := *total.Input+base, *total.Output+baseOut |
| + total.Input, total.Output = &in, &out |
| + tally.Notice(thread, id, total, last) |
| + } |
| + tally.End() |
| + } |
| + same := NewCodexTally("thread-1", true) |
| + turn(same, "turn-1", 0, 0) |
| + first := same.Row() |
| + turn(same, "turn-2", 28254, 142) |
| + second := same.Row() |
| + if get(first.InputTokens) != 28254 || get(second.InputTokens) != 28254 || get(second.OutputTokens) != 142 || !second.Complete || get(second.Turns) != 2 { |
| + t.Fatalf("per turn in one process: first %+v second %+v", first, second) |
| + } |
| + resumed := NewCodexTally("thread-1", false) |
| + turn(resumed, "turn-3", 56508, 284) |
| + if r := resumed.Row(); get(r.InputTokens) != 14200 || r.Complete || get(r.Turns) != 2 { |
| + t.Fatalf("resumed: %+v", r) |
| + } |
| +} |
diff --git a/internal/thintest/spend_pages_test.go b/internal/thintest/spend_pages_test.go| index b53139af..5c9fc947 100644 |
| --- a/internal/thintest/spend_pages_test.go |
| +++ b/internal/thintest/spend_pages_test.go |
| @@ -4,8 +4,10 @@ import ( |
| "database/sql" |
| "io" |
| "log/slog" |
| + "strconv" |
| "strings" |
| "testing" |
| + "time" |
| "amadan.net/oficina/equipo/internal/wire" |
| "amadan.net/rastrillo/rastrillo/db" |
| @@ -100,18 +102,84 @@ func TestContractMigrationUsageRoundTurns(t *testing.T) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - for _, q := range []string{"ALTER TABLE chat_usage DROP COLUMN round", "ALTER TABLE chat_usage DROP COLUMN turns", "DELETE FROM rastrillo_migrations WHERE id LIKE 'equipo/0059_%'"} { |
| + for _, q := range []string{"ALTER TABLE chat_usage DROP COLUMN round", "ALTER TABLE chat_usage DROP COLUMN turns", "ALTER TABLE chat_usage DROP COLUMN overcount", "DELETE FROM rastrillo_migrations WHERE id LIKE 'equipo/0059_%'"} { |
| if _, err := d0.Writer().Exec(q); err != nil { |
| t.Fatalf("%s: %v", q, err) |
| } |
| } |
| + // A row an older runner sent for an answer on Claude: read from the |
| + // session's running total, so it overcounts. |
| + if _, err := d0.Writer().Exec("INSERT INTO chat_usage(person, connection, provider, model, role, task_id, step_id, turn_id, attempt, outcome, complete, input_tokens, cached_input_tokens, cache_write_tokens, output_tokens, recorded_at) VALUES(?, 'claude-a', 'claude', 'claude-opus-5-5', 'ask', ?, 'q_old', '', 1, 'replied', 1, 500, 90000, 100, 400, ?)", Owner, id, time.Now().UTC()); err != nil { |
| + t.Fatal(err) |
| + } |
| d0.Close() |
| r.inst.Restart(t) |
| + var over []bool |
| + rows, err := r.inst.DB.Writer().Query("SELECT coalesce(overcount, 0) FROM chat_usage WHERE task_id = ? ORDER BY provider", id) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for rows.Next() { |
| + var v bool |
| + rows.Scan(&v) |
| + over = append(over, v) |
| + } |
| + rows.Close() |
| + if len(over) != 2 || !over[0] || over[1] { |
| + t.Fatalf("overcount after the upgrade (claude, codex): %v", over) |
| + } |
| var round, turns sql.NullInt64 |
| if err := r.inst.DB.Writer().QueryRow("SELECT round, turns FROM chat_usage WHERE step_id = ?", d.StepID).Scan(&round, &turns); err != nil || round.Valid || turns.Valid { |
| t.Fatalf("migrated row: round %v turns %v %v", round, turns, err) |
| } |
| - if page := r.get(owner, "/tasks/"+id, 200); !strings.Contains(page, `<p equipo-quiet data-spend>Used 10k tokens (4k cached)</p>`) { |
| + if page := r.get(owner, "/tasks/"+id, 200); !strings.Contains(page, `<p equipo-quiet data-spend>Used 10k tokens (4k cached)</p><p equipo-quiet data-spend-note>Earlier usage not shown</p>`) || strings.Contains(page, "Questions:") { |
| t.Fatalf("task page after the upgrade:\n%s", page) |
| } |
| } |
| + |
| +// A Claude answer's row from a runner before ProtocolSpend overcounts |
| +// (it read the session's running total): the task page leaves it out |
| +// and says so, and so does today's usage on Connections. From a runner |
| +// at ProtocolSpend it counts. |
| +func TestPagesSpendLeavesOutOvercount(t *testing.T) { |
| + for _, proto := range []int{wire.Protocol1, wire.Protocol2, wire.ProtocolSpend} { |
| + t.Run(strconv.Itoa(proto), func(t *testing.T) { |
| + r := newToolRig(t) |
| + if proto > wire.Protocol1 { |
| + gen := r.runner.Welcome.Generation |
| + r.runner.Close() |
| + h := primaryHello(gen) |
| + h.Protocol = proto |
| + p, err := DialRunnerHello(r.ctx, r.inst.URL, r.rig.runner, h) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(p.Close) |
| + r.runner = p |
| + } |
| + base, cand := strings.Repeat("1", 40), strings.Repeat("2", 40) |
| + id, _, _ := r.askableTask("o", base, cand) |
| + q, err := r.client.Ask(r.ctx, id, "What did you change?", "", "k1") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + r.expect(wire.FrameAsk) |
| + used := []wire.Usage{{Provider: "claude", Connection: "claude-a", Model: "claude-opus-5-5", Attempt: 1, Outcome: wire.OutcomeReplied, Complete: true, InputTokens: tokens(500), CachedInputTokens: tokens(9000), CacheWriteTokens: tokens(100), OutputTokens: tokens(400)}} |
| + r.answer("o-q", wire.AnswerReport{TaskID: id, QuestionID: q.ID, Attempt: 1, State: wire.QuestionAnswered, Text: "I fixed the typo.", Usage: used}) |
| + page := r.get(r.inst.Cookie(), "/tasks/"+id, 200) |
| + today, err := r.inst.Store.Chat().UsageToday(r.ctx, Owner) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if proto < wire.ProtocolSpend { |
| + if !strings.Contains(page, `<p equipo-quiet data-spend-note>Earlier usage not shown</p>`) || strings.Contains(page, "data-spend>") || strings.Contains(page, "data-spend-step=") || today["claude-a"] != 0 { |
| + t.Fatalf("an older runner's answer counted (today %v):\n%s", today, page) |
| + } |
| + return |
| + } |
| + if !strings.Contains(page, `<p equipo-quiet data-spend>Used 10k tokens (9k cached)</p>`) || !strings.Contains(page, `<li data-spend-step="questions">Questions: 10k tokens (9k cached)</li>`) || strings.Contains(page, "data-spend-note") || today["claude-a"] != 900 { |
| + t.Fatalf("a current runner's answer (today %v):\n%s", today, page) |
| + } |
| + }) |
| + } |
| +} |