fix: preserve Copy accounting across holds and retries
5 files changed,
+75
−6
.rastrillo/budgets.txt+2 −2internal/equipo/chat/copy_budget.go+2 −1internal/equipo/chat/copy_specialist_test.go+18 −0internal/runner/thin/copy_step.go+14 −2internal/runner/thin/copy_test.go+39 −1
CI passed — run details
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index d6ae3308..b0bde18e 100644 |
| --- a/.rastrillo/budgets.txt |
| +++ b/.rastrillo/budgets.txt |
| @@ -38,7 +38,7 @@ time internal/runner/provider 15s Plan 3 CI repair measured 10.346s for the full |
| perf GET /releases/* skip Verified runner release file downloads, not browser GET screens. |
| perf GET /install.sh skip Mac runners: the one-line bootstrap a terminal pipes to sh, not a browser screen. |
| time internal/runner/containment 15s Plan 3 loaded CI measured 10.817s; |
| -size internal/runner/thin 24951 16861 Copy validation lives in copydesk; contained execution and publication use the runner’s private state and launch helpers. |
| +size internal/runner/thin 24963 16899 Copy validation lives in copydesk; contained execution and publication use the runner’s private state and launch helpers. |
| time internal/thintest 240s Thin contract and page tests, the Assistant's and the models' included, share one harness. Measured 202s on a shared 16 CPU box (2026-11-13); CI runs two lanes. |
| time internal/runner/mac 30s Mac runners (Darwin worker): real process groups killed after a grace and proven gone (SIGTERM, SIGKILL, the marker sweep), and the probes run end to end with fake srt and xcodebuild, P6 killing. |
| time internal/runner/thin 45s Thin v1 slice 4 review: real git repositories for the merge and squash checks, a stalled fetch, and a 16 MiB candidate streamed through the review diff and the checks pack (about 5s). |
| @@ -56,7 +56,7 @@ perf GET /api/v1/tasks/{id} skip Thin v1 person API: bearer-only JSON for device |
| perf GET /api/v1/assistant/snapshot skip Assistant person API: bearer-only JSON for Base's chat, not a browser screen. |
| perf GET /api/v1/assistant/messages skip Assistant person API: bearer-only JSON for Base's chat, not a browser screen. |
| perf GET /api/v1/assistant/events skip Assistant event stream (Server-Sent Events), bearer-only and long-lived; not a screen. |
| -size internal/equipo/chat 26099 - Copy validation lives in copydesk; its authority, ledger and task transitions share the store transaction. |
| +size internal/equipo/chat 26100 - Copy validation lives in copydesk; its authority, ledger and task transitions share the store transaction. |
| perf GET /api/v1/questions/{id} skip Thin v1 person API: bearer-only JSON for devices; the browser reads questions on /tasks/{id}. |
| perf GET /api/v1/steps/{id}/log skip Thin v1 person API: bearer-only JSON for devices; the browser shows the log tail on /tasks/{id}. |
| perf GET /api/v1/connections/preference skip Connections slice 1 person API: bearer-only JSON for devices; the browser shows the preference on /conversation/connections. |
diff --git a/internal/equipo/chat/copy_budget.go b/internal/equipo/chat/copy_budget.go| index 80e5e27c..e8d0f3fb 100644 |
| --- a/internal/equipo/chat/copy_budget.go |
| +++ b/internal/equipo/chat/copy_budget.go |
| @@ -3,6 +3,7 @@ package chat |
| import ( |
| "amadan.net/oficina/equipo/internal/copydesk" |
| "amadan.net/oficina/equipo/internal/wire" |
| + "gorm.io/gorm" |
| "gorm.io/gorm/clause" |
| ) |
| @@ -42,5 +43,5 @@ func (t *txn) copyUsageReport(k taskRecord, s stepRecord, v *wire.StepReport) er |
| if err := t.reserveCopy(k, s); err != nil { |
| return err |
| } |
| - return t.db.Model(©AttemptRecord{}).Where("id = ?", stepAttempt(s)).Select("tokens", "known").Updates(©AttemptRecord{Tokens: c.Tokens, Known: c.UsageKnown}).Error |
| + return t.db.Model(©AttemptRecord{}).Where("id = ?", stepAttempt(s)).Select("tokens", "known").Updates(map[string]any{"tokens": gorm.Expr("MAX(tokens, ?)", c.Tokens), "known": c.UsageKnown}).Error |
| } |
diff --git a/internal/equipo/chat/copy_specialist_test.go b/internal/equipo/chat/copy_specialist_test.go| index dfd7e4f7..dece6632 100644 |
| --- a/internal/equipo/chat/copy_specialist_test.go |
| +++ b/internal/equipo/chat/copy_specialist_test.go |
| @@ -164,3 +164,21 @@ func TestCopyLearningDefersWithoutForgetting(t *testing.T) { |
| return err |
| })) |
| } |
| + |
| +func TestCopyUsageReportsCannotReplenishAllowance(t *testing.T) { |
| + r, _ := rosterRig(t) |
| + k := taskRecord{ID: "tk"} |
| + step := stepRecord{ID: "copy", Attempt: 1, CopyOwner: hkOwner, CopyRevision: 1, CandidateSHA: "head"} |
| + for _, n := range []int64{10000, 0, 8000} { |
| + r.must(r.tx(func(tx *txn) error { |
| + return tx.copyUsageReport(k, step, &wire.StepReport{Copy: &wire.CopyResult{Owner: hkOwner, Delegation: 1, Input: "head", Tokens: n, UsageKnown: true}}) |
| + })) |
| + } |
| + r.must(r.tx(func(tx *txn) error { |
| + left, known, err := tx.copyBudget(k.ID) |
| + if err == nil && (!known || left != copydesk.TaskTokens-10000) { |
| + t.Fatalf("later report replenished allowance: %d %v", left, known) |
| + } |
| + return err |
| + })) |
| +} |
diff --git a/internal/runner/thin/copy_step.go b/internal/runner/thin/copy_step.go| index 008a379e..3c80b166 100644 |
| --- a/internal/runner/thin/copy_step.go |
| +++ b/internal/runner/thin/copy_step.go |
| @@ -55,13 +55,16 @@ func (e *Engineer) copyStep(ctx context.Context, r stepRow, progress func(wire.S |
| } |
| rep.Copy = &wire.CopyResult{Owner: r.Copy.Owner, Delegation: r.Copy.Delegation, Input: r.CandidateSHA, Compared: r.Copy.Compared, UsageKnown: true, Extraction: copydesk.Extraction{Version: 1}, Review: copydesk.Review{Version: 1}} |
| if r.Phase == phaseCommitted { |
| + rep.Copy.UsageKnown = false |
| var raw string |
| if err := e.O.State.db.QueryRowContext(ctx, "SELECT result FROM copy_attempts WHERE step_id=? AND attempt=?", r.StepID, r.Attempt).Scan(&raw); err != nil { |
| return fail("policy_rejected") |
| } |
| - if json.Unmarshal([]byte(raw), &rep.Copy) != nil { |
| + var saved wire.CopyResult |
| + if json.Unmarshal([]byte(raw), &saved) != nil || saved.Owner != r.Copy.Owner || saved.Delegation != r.Copy.Delegation || saved.Input != r.CandidateSHA || saved.Extraction.Version != 1 || saved.Review.Version != 1 { |
| return fail("policy_rejected") |
| } |
| + rep.Copy = &saved |
| return e.publish(ctx, r, rep) |
| } |
| var recoverySignature *copydesk.Signature |
| @@ -119,6 +122,7 @@ func (e *Engineer) copyStep(ctx context.Context, r stepRow, progress func(wire.S |
| } else { |
| var spent, unknown int64 |
| if err := e.O.State.db.QueryRowContext(ctx, "SELECT COALESCE(SUM(c.spent),0),COALESCE(SUM(CASE WHEN c.known=0 THEN 1 ELSE 0 END),0) FROM copy_attempts c JOIN steps s ON s.step_id=c.step_id AND s.attempt=c.attempt WHERE s.task_id=?", r.TaskID).Scan(&spent, &unknown); err != nil || unknown > 0 || spent >= copydesk.TaskTokens { |
| + result.UsageKnown = false |
| return fail("policy_rejected") |
| } |
| if e.Conns == nil { |
| @@ -139,6 +143,7 @@ func (e *Engineer) copyStep(ctx context.Context, r stepRow, progress func(wire.S |
| } |
| n, _ := res.RowsAffected() |
| if n != 1 { |
| + result.UsageKnown = false |
| return fail("policy_rejected") |
| } |
| modelDir, err := os.MkdirTemp(e.O.Runner.WorkspaceRoot, "copy-model-") |
| @@ -175,6 +180,13 @@ func (e *Engineer) copyStep(ctx context.Context, r stepRow, progress func(wire.S |
| result.UsageKnown = false |
| progress(rep) |
| run := e.run(ctx, r, workspace.TaskTree{Dir: modelDir}, specialistRun{admit: admit, action: "inspect", binding: b, tools: copyTools, names: []string{"submit_review"}, permission: claude.ReadPermission, call: call, prompt: prompt, limit: 5 * time.Minute, noLog: true}) |
| + if run.reason == reasonHeld { |
| + if _, err := e.O.State.db.ExecContext(context.WithoutCancel(ctx), "DELETE FROM copy_attempts WHERE step_id=? AND attempt=? AND spent=0 AND known=0", r.StepID, r.Attempt); err != nil { |
| + return fail("provider_failed") |
| + } |
| + result.UsageKnown = true |
| + return heldGuard(rep, run) |
| + } |
| rep.Usage = run.usage(b, r.Attempt) |
| result.Tokens, result.UsageKnown = copyUsage(rep.Usage) |
| raw, _ := json.Marshal(result) |
| @@ -189,7 +201,7 @@ func (e *Engineer) copyStep(ctx context.Context, r stepRow, progress func(wire.S |
| if run.reason != "" { |
| return fail(run.reason) |
| } |
| - if !submitted || !result.UsageKnown || result.Tokens > min(int64(copydesk.PassTokens), r.Copy.Remaining) { |
| + if !submitted || !result.UsageKnown || result.Tokens > min(int64(copydesk.PassTokens), r.Copy.Remaining, int64(copydesk.TaskTokens)-spent) { |
| return fail("policy_rejected") |
| } |
diff --git a/internal/runner/thin/copy_test.go b/internal/runner/thin/copy_test.go| index eff1ac47..b3b764cf 100644 |
| --- a/internal/runner/thin/copy_test.go |
| +++ b/internal/runner/thin/copy_test.go |
| @@ -4,14 +4,17 @@ import ( |
| "amadan.net/oficina/equipo/internal/copydesk" |
| "amadan.net/oficina/equipo/internal/fakepi" |
| "amadan.net/oficina/equipo/internal/runner/forge" |
| + "amadan.net/oficina/equipo/internal/runner/metered" |
| "amadan.net/oficina/equipo/internal/runner/workspace" |
| "amadan.net/oficina/equipo/internal/wire" |
| "context" |
| + "database/sql" |
| "os" |
| "os/exec" |
| "path/filepath" |
| "strings" |
| "testing" |
| + "time" |
| ) |
| func TestCopyRunnerRejectsMissingDelegation(t *testing.T) { |
| @@ -56,7 +59,9 @@ func TestCopyCommandPreservesStructuredOutput(t *testing.T) { |
| } |
| } |
| -func TestCopyStructuredPassPublishesAndFlags(t *testing.T) { |
| +func TestCopyStructuredPassPublishesAndFlags(t *testing.T) { copyStructuredPass(t, false) } |
| +func TestCopyLateAdmissionRetries(t *testing.T) { copyStructuredPass(t, true) } |
| +func copyStructuredPass(t *testing.T, lateHold bool) { |
| install := fakePiInstall(t) |
| r := newMeteredRig(t, bigBudget, rigConn{local: piLocal, provider: wire.ProviderTensorX, harness: wire.HarnessPi, upstream: "https://api.tensorx.ai", model: "z-ai/glm-5.2", key: fakepi.TestKey}, func(e *Engineer) { e.Pi = PiOptions{Install: install} }) |
| goRoot, err := exec.Command("go", "env", "GOROOT").Output() |
| @@ -100,6 +105,28 @@ func TestCopyStructuredPassPublishesAndFlags(t *testing.T) { |
| if err := r.state.AcceptDispatch(r.ctx, "copy-pass", row.DispatchCommand); err != nil { |
| t.Fatal(err) |
| } |
| + if lateHold { |
| + r.e.beforeAdmit = func(local string) { |
| + if err := r.state.tx(r.ctx, func(tx *sql.Tx) error { |
| + _, err := metered.Admit(r.ctx, tx, local, metered.Holder{Step: "other", Attempt: 1, Role: metered.RoleReview, Model: "z-ai/glm-5.2"}, time.Now()) |
| + return err |
| + }); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + held := r.e.Exec(r.ctx, row, func(wire.StepReport) {}) |
| + if held.State != stepDeferred || held.Hold == nil || held.Copy == nil || !held.Copy.UsageKnown || held.Copy.Tokens != 0 { |
| + t.Fatalf("unlaunched call did not remain retryable: %+v, copy=%+v", held, held.Copy) |
| + } |
| + var count int |
| + if err := r.state.db.QueryRow("SELECT COUNT(*) FROM copy_attempts").Scan(&count); err != nil || count != 0 { |
| + t.Fatalf("held reservation retained: %d %v", count, err) |
| + } |
| + r.e.beforeAdmit = nil |
| + if _, err := r.state.db.Exec("UPDATE metered_slot SET holder='',role='' WHERE local_id=?", piLocal); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| rep := r.e.Exec(r.ctx, row, func(wire.StepReport) {}) |
| if rep.State != wire.StepDone || !rep.Pushed || rep.Copy == nil || len(rep.Copy.Review.Strings) != 1 || rep.Copy.Review.Strings[0].Flag == "" { |
| t.Fatalf("Copy failed: %+v", rep) |
| @@ -120,3 +147,14 @@ func TestCopyUsageDoesNotDoubleCountCachedInput(t *testing.T) { |
| t.Fatalf("cache counted twice: %d %v", n, known) |
| } |
| } |
| + |
| +func TestCopyCommittedReplayMissingUsageStaysUnknown(t *testing.T) { |
| + r := newPiRig(t, fakePiInstall(t), bigBudget) |
| + row := r.review |
| + row.Specialist, row.Phase = wire.SpecialistCopy, phaseCommitted |
| + row.Copy = &wire.CopyDispatch{Owner: connPerson, Delegation: 1, Remaining: copydesk.TaskTokens} |
| + rep := r.e.copyStep(r.ctx, row, func(wire.StepReport) {}) |
| + if rep.Copy == nil || rep.Copy.UsageKnown { |
| + t.Fatalf("missing persisted usage became known zero: %+v", rep.Copy) |
| + } |
| +} |