package metered import ( "context" "database/sql" "errors" "path/filepath" "sync" "testing" "time" "amadan.net/oficina/equipo/internal/wire" _ "modernc.org/sqlite" ) // The S1 finish line (connectors spec ยง11), with a fake harness: each // test runs attempts through the Meter the way a harness adapter does. const tx1 = "tensorx-1" func open(t *testing.T, dir string) *sql.DB { t.Helper() db, err := sql.Open("sqlite", "file:"+filepath.Join(dir, "thin.db")+"?_pragma=busy_timeout(5000)&_pragma=journal_mode(WAL)") if err != nil { t.Fatal(err) } db.SetMaxOpenConns(1) if _, err := db.Exec(Schema); err != nil { t.Fatal(err) } t.Cleanup(func() { db.Close() }) return db } type rig struct { t *testing.T dir string db *sql.DB m *Meter clock time.Time } func newRig(t *testing.T, day, month int64) *rig { r := &rig{t: t, dir: t.TempDir(), clock: time.Date(2026, 11, 12, 10, 0, 0, 0, time.UTC)} r.db = open(t, r.dir) r.m = r.meter() err := r.m.tx(context.Background(), func(tx *sql.Tx) error { if err := Add(context.Background(), tx, Conn{LocalID: tx1, Connection: "cn_1", Person: "p", Provider: wire.ProviderTensorX, Harness: wire.HarnessPi, Upstream: "https://api.tensorx.ai", Billing: wire.BillingMetered, Model: "z-ai/glm-5.3", Home: "/h", Currency: "USD", PriceVersion: Current[wire.ProviderTensorX], Budget: wire.Budget{Day: day, Month: month, Revision: 1}}, r.clock); err != nil { return err } // The allowed set (S5b): the one model, proven. if err := InitModels(context.Background(), tx, tx1, []string{"z-ai/glm-5.3"}, 1); err != nil { return err } return MarkModel(context.Background(), tx, tx1, "z-ai/glm-5.3", wire.ModelHealthy, "", r.clock) }) if err != nil { t.Fatal(err) } return r } func (r *rig) meter() *Meter { return &Meter{DB: r.db, Now: func() time.Time { return r.clock }, Gone: func(context.Context, string) error { return nil }} } // usage is a fake harness's report: input and output tokens on model. func usage(model string, attempt, in, out int64) wire.Usage { return wire.Usage{Provider: wire.ProviderTensorX, Connection: tx1, Model: model, Attempt: attempt, Outcome: wire.OutcomeReplied, Complete: true, InputTokens: &in, CachedInputTokens: new(int64), CacheWriteTokens: new(int64), OutputTokens: &out} } // harness is the fake: it reports rows and a proven exit. func harness(rows ...wire.Usage) func(context.Context, Launch) Result { return func(_ context.Context, l Launch) Result { if err := l.Namespace("ns-" + l.Holder.Step); err != nil { panic(err) } return Result{Usage: rows, Ending: Ending{Proven: true}} } } func (r *rig) run(h Holder, rows ...wire.Usage) Admission { r.t.Helper() a, _, err := r.m.Run(context.Background(), tx1, h, harness(rows...), nil) if err != nil { r.t.Fatal(err) } return a } func (r *rig) spend() wire.Spend { c, _, err := Get(context.Background(), r.db, tx1) if err != nil { r.t.Fatal(err) } s, err := SpendOf(context.Background(), r.db, c, r.clock) if err != nil { r.t.Fatal(err) } return s } func step(id string, role string) Holder { return Holder{Step: id, Attempt: 1, Role: role, Model: "z-ai/glm-5.3"} } // (a) The attempt after the reported spend crosses the budget is held, // until the next budget day; one step can overshoot, never two. func TestMeteredBudgetHoldsTheNextAttempt(t *testing.T) { r := newRig(t, 1_000_000, 10_000_000) // 0.4M input at 1.75 and 0.05M output at 4.50: 0.925 of the day's 1. if a := r.run(step("s1", RoleEngineering), usage("z-ai/glm-5.3", 1, 400_000, 50_000)); !a.Admitted { t.Fatalf("first held: %+v", a) } if s := r.spend(); s.Day != 925_000 || s.Unknown || s.Running { t.Fatalf("spend %+v", s) } // Under the budget still: admitted, and it crosses it. if a := r.run(step("s2", RoleReview), usage("z-ai/glm-5.3", 1, 100_000, 10_000)); !a.Admitted { t.Fatalf("second held: %+v", a) } ran := false a, _, err := r.m.Run(context.Background(), tx1, step("s3", RoleEngineering), func(context.Context, Launch) Result { ran = true; return Result{} }, nil) if err != nil || a.Admitted || a.Hold != HoldBudget || ran { t.Fatalf("after the budget: %+v ran=%v %v", a, ran, err) } if want := time.Date(2026, 11, 13, 0, 0, 0, 0, time.UTC); !a.WakeAt.Equal(want) { t.Fatalf("wakes %v", a.WakeAt) } // A new day: admitted again; this month's spend carries on. r.clock = r.clock.Add(24 * time.Hour) if a := r.run(step("s3", RoleEngineering), usage("z-ai/glm-5.3", 1, 1, 1)); !a.Admitted { t.Fatalf("next day held: %+v", a) } if s := r.spend(); s.Day != 7 || s.Month != 925_000+220_000+7 { t.Fatalf("next day spend %+v", s) } // The month's budget holds until the first of next month. r2 := newRig(t, 1_000_000, 1_000_000) r2.run(step("s1", RoleEngineering), usage("z-ai/glm-5.3", 1, 600_000, 0)) r2.clock = r2.clock.Add(24 * time.Hour) r2.run(step("s2", RoleEngineering), usage("z-ai/glm-5.3", 1, 600_000, 0)) r2.clock = r2.clock.Add(24 * time.Hour) if a := r2.run(step("s3", RoleEngineering)); a.Admitted || a.Hold != HoldBudget || !a.WakeAt.Equal(time.Date(2026, 12, 1, 0, 0, 0, 0, time.UTC)) { t.Fatalf("month: %+v", a) } // A raised budget, applied, admits; an older revision changes nothing. if ok, err := r.m.ApplyBudget(context.Background(), tx1, "cn_1", wire.Budget{Day: 900_000, Month: 9_000_000, Revision: 1}, nil); err != nil || ok { t.Fatalf("same revision applied: %v %v", ok, err) } if ok, err := r2.m.ApplyBudget(context.Background(), tx1, "cn_1", wire.Budget{Day: 2_000_000, Month: 5_000_000, Revision: 2}, nil); err != nil || !ok { t.Fatalf("raise: %v %v", ok, err) } if a := r2.run(step("s3", RoleEngineering)); a.Hold == HoldBudget { t.Fatalf("raised budget still holds: %+v", a) } } // (b) A concurrent Engineering, Review and question race on one metered // connection admits exactly one; the others are held busy and nothing of // theirs runs. func TestMeteredRaceAdmitsExactlyOne(t *testing.T) { for round := 0; round < 8; round++ { r := newRig(t, 1_000_000, 10_000_000) release := make(chan struct{}) var mu sync.Mutex ran := map[string]bool{} holds := map[string]string{} var wg sync.WaitGroup start := make(chan struct{}) for _, h := range []Holder{step("eng", RoleEngineering), step("rev", RoleReview), {Step: "q1", Attempt: 1, Role: RoleAsk, Model: "z-ai/glm-5.3"}} { wg.Add(1) go func() { defer wg.Done() <-start a, _, err := r.m.Run(context.Background(), tx1, h, func(ctx context.Context, l Launch) Result { mu.Lock() ran[h.Role] = true mu.Unlock() <-release return harness(usage("z-ai/glm-5.3", 1, 10, 1))(ctx, l) }, nil) if err != nil { t.Error(err) } mu.Lock() holds[h.Role] = a.Hold mu.Unlock() }() } close(start) // The two held return at once; the admitted one waits on release. deadline := time.Now().Add(5 * time.Second) for { mu.Lock() n := len(holds) mu.Unlock() if n == 2 || time.Now().After(deadline) { break } time.Sleep(time.Millisecond) } mu.Lock() if len(ran) != 1 || len(holds) != 2 { t.Fatalf("round %d: ran %v, held %v", round, ran, holds) } for role, hold := range holds { if hold != HoldBusy || ran[role] { t.Fatalf("round %d: %s held %q ran %v", round, role, hold, ran[role]) } } mu.Unlock() if s := r.spend(); !s.Running { t.Fatal("the slot is not held while the attempt runs") } close(release) wg.Wait() if s := r.spend(); s.Running || s.Unknown { t.Fatalf("after: %+v", s) } } } // (c) A crash between the harness's exit and its charge ends in // spend_unknown before anything else is admitted: until recovery the // slot is held; recovery proves the namespace gone, finds no charge and // pauses the connection, then releases the slot. func TestMeteredCrashBeforeChargeIsSpendUnknown(t *testing.T) { r := newRig(t, 1_000_000, 10_000_000) r.m.Fault = func(stage string) error { if stage == "exited" { return ErrStopped } return nil } if _, _, err := r.m.Run(context.Background(), tx1, step("s1", RoleEngineering), harness(usage("z-ai/glm-5.3", 1, 10, 1)), nil); !errors.Is(err, ErrStopped) { t.Fatalf("stopped: %v", err) } r.db.Close() // The next process, on the same thin.db. r.db = open(t, r.dir) var gone []string r.m = r.meter() r.m.Gone = func(_ context.Context, ns string) error { gone = append(gone, ns); return nil } if a := r.run(step("s2", RoleReview)); a.Admitted || a.Hold != HoldBusy { t.Fatalf("admitted before recovery: %+v", a) } // An exit that cannot be proven keeps the slot. r.m.Gone = func(context.Context, string) error { return errors.New("still running") } if err := r.m.Recover(context.Background()); err == nil { t.Fatal("recovered an unproven exit") } if a := r.run(step("s2", RoleReview)); a.Hold != HoldBusy { t.Fatalf("an unproven slot released: %+v", a) } r.m.Gone = func(_ context.Context, ns string) error { gone = append(gone, ns); return nil } if err := r.m.Recover(context.Background()); err != nil { t.Fatal(err) } if len(gone) != 1 || gone[0] != "ns-s1" { t.Fatalf("namespaces proven gone: %v", gone) } s := r.spend() if !s.Unknown || s.PauseRevision != 1 || s.Running || s.Day != 0 { t.Fatalf("after recovery %+v", s) } if a := r.run(step("s2", RoleReview)); a.Admitted || a.Hold != HoldSpendUnknown { t.Fatalf("admitted with spend unknown: %+v", a) } // A crash after the charge committed: recovery keeps the charge and // does not pause. r2 := newRig(t, 1_000_000, 10_000_000) h := step("s1", RoleEngineering) _, _, err := r2.m.Run(context.Background(), tx1, h, func(ctx context.Context, l Launch) Result { res := harness(usage("z-ai/glm-5.3", 1, 10, 1))(ctx, l) res.Proven = false return res }, nil) if err != nil { t.Fatal(err) } if s := r2.spend(); !s.Running || s.Day != 23 { t.Fatalf("charged, unproven: %+v", s) } if err := r2.m.Recover(context.Background()); err != nil { t.Fatal(err) } if s := r2.spend(); s.Running || s.Unknown || s.Day != 23 { t.Fatalf("recovered after the charge: %+v", s) } } // (d) Resume is bound to its pause: consumed once, and a stale or // repeated Resume leaves a newer pause in place. func TestMeteredStaleResumeLeavesTheNewerPause(t *testing.T) { r := newRig(t, 1_000_000, 10_000_000) ctx := context.Background() // An attempt with no usage figure pauses (revision 1). r.run(step("s1", RoleEngineering)) if s := r.spend(); !s.Unknown || s.PauseRevision != 1 { t.Fatalf("pause 1: %+v", s) } if ok, err := r.m.Resume(ctx, tx1, "cn_1", 1, nil); err != nil || !ok { t.Fatalf("resume 1: %v %v", ok, err) } // Another unknown spend: pause 2. r.run(step("s2", RoleEngineering), wire.Usage{Provider: wire.ProviderTensorX, Connection: tx1, Model: "z-ai/glm-5.3", Attempt: 1, Outcome: wire.OutcomeFailed}) if s := r.spend(); !s.Unknown || s.PauseRevision != 2 { t.Fatalf("pause 2: %+v", s) } // The first Resume again, replayed or stale, changes nothing. if ok, err := r.m.Resume(ctx, tx1, "cn_1", 1, nil); err != nil || ok { t.Fatalf("stale resume cleared: %v %v", ok, err) } if a := r.run(step("s3", RoleEngineering)); a.Hold != HoldSpendUnknown { t.Fatalf("admitted after a stale resume: %+v", a) } if ok, _ := r.m.Resume(ctx, tx1, "cn_1", 2, nil); !ok { t.Fatal("the current resume did nothing") } if ok, _ := r.m.Resume(ctx, tx1, "cn_1", 2, nil); ok { t.Fatal("a resume was consumed twice") } if a := r.run(step("s3", RoleEngineering), usage("z-ai/glm-5.3", 1, 1, 1)); !a.Admitted { t.Fatalf("held after the current resume: %+v", a) } } // (e) A resent usage row charges once: the ledger is keyed by the row's // own key. func TestMeteredResentUsageChargesOnce(t *testing.T) { r := newRig(t, 1_000_000, 10_000_000) ctx := context.Background() h := step("s1", RoleEngineering) row := usage("z-ai/glm-5.3", 1, 100_000, 0) if a, err := r.m.Admit(ctx, tx1, h, nil); err != nil || !a.Admitted { t.Fatal(a, err) } for i := 0; i < 3; i++ { if err := r.m.Finish(ctx, tx1, h, Result{Usage: []wire.Usage{row}}, nil); err != nil { t.Fatal(err) } } if err := r.m.Finish(ctx, tx1, h, Result{Usage: []wire.Usage{row}, Ending: Ending{Proven: true}}, nil); err != nil { t.Fatal(err) } if s := r.spend(); s.Day != 175_000 || s.Unknown { t.Fatalf("charged %+v", s) } // Another attempt of the same step is another row, charged too. h2 := Holder{Step: "s1", Attempt: 2, Role: RoleEngineering, Model: "z-ai/glm-5.3"} r.run(h2, usage("z-ai/glm-5.3", 2, 100_000, 0)) if s := r.spend(); s.Day != 350_000 { t.Fatalf("second attempt %+v", s) } } // (f) An unpriced model gives spend unknown, and so does an unpriceable // component; the row is reported with no cost. func TestMeteredUnpricedModelIsSpendUnknown(t *testing.T) { r := newRig(t, 1_000_000, 10_000_000) var reported []wire.Usage _, _, err := r.m.Run(context.Background(), tx1, step("s1", RoleEngineering), harness(usage("vendor/unpriced-1", 1, 10, 1)), func(_ *sql.Tx, rows []wire.Usage) error { reported = rows return nil }) if err != nil { t.Fatal(err) } if len(reported) != 1 || reported[0].CostMicros != nil || reported[0].PriceVersion != "tensorx-2026-11-12" || reported[0].Currency != "USD" { t.Fatalf("reported %+v", reported) } if s := r.spend(); !s.Unknown || s.Day != 0 { t.Fatalf("spend %+v", s) } if a := r.run(step("s2", RoleEngineering)); a.Hold != HoldSpendUnknown { t.Fatalf("admitted %+v", a) } r2 := newRig(t, 1_000_000, 10_000_000) cw := usage("z-ai/glm-5.3", 1, 10, 1) cw.CacheWriteTokens = new(int64) *cw.CacheWriteTokens = 5 r2.run(step("s1", RoleEngineering), cw) if s := r2.spend(); !s.Unknown { t.Fatalf("unpriced cache write: %+v", s) } // A slot is never released before its attempt's proof. r3 := newRig(t, 1_000_000, 10_000_000) h := step("s1", RoleEngineering) r3.m.Admit(context.Background(), tx1, h, nil) err = r3.m.tx(context.Background(), func(tx *sql.Tx) error { return Settle(context.Background(), tx, tx1, h, Ending{}) }) if !errors.Is(err, ErrNotProven) || !r3.spend().Running { t.Fatalf("settled unproven: %v", err) } // An attempt that started no harness spends nothing and pauses nothing. r3.m.tx(context.Background(), func(tx *sql.Tx) error { return Settle(context.Background(), tx, tx1, h, Ending{Proven: true, NotStarted: true}) }) if s := r3.spend(); s.Running || s.Unknown { t.Fatalf("not started: %+v", s) } } // Security round finding 1: an attempt is registered as running before // its admission commits, so a Recover in between (here, in the window // right after the commit) never releases its slot unproven, and nothing // else is admitted while it runs. func TestMeteredRecoverBetweenAdmissionAndLaunch(t *testing.T) { r := newRig(t, 1_000_000, 10_000_000) recovered := false r.m.Fault = func(stage string) error { if stage == "admitted" && !recovered { recovered = true if err := r.m.Recover(context.Background()); err != nil { t.Error(err) } } return nil } ran := false _, _, err := r.m.Run(context.Background(), tx1, step("s1", RoleEngineering), func(ctx context.Context, l Launch) Result { ran = true if s := r.spend(); !s.Running { t.Error("the slot was released between the admission and the launch") } if a, _ := r.m.Admit(ctx, tx1, step("s2", RoleReview), nil); a.Admitted { t.Error("a second attempt was admitted while the first ran") } return harness(usage("z-ai/glm-5.3", 1, 1, 1))(ctx, l) }, nil) if err != nil || !ran || !recovered { t.Fatalf("ran %v recovered %v %v", ran, recovered, err) } } // Security round finding 2: a holder already claiming the slot is not // let in again. Two runs with the same holder at once start one harness; // a second process (another Meter) finding the claim does not launch. func TestMeteredDuplicateHolderRunsOnce(t *testing.T) { r := newRig(t, 1_000_000, 10_000_000) h := step("s1", RoleEngineering) release := make(chan struct{}) var mu sync.Mutex runs := 0 var wg sync.WaitGroup for i := 0; i < 2; i++ { wg.Add(1) go func() { defer wg.Done() r.m.Run(context.Background(), tx1, h, func(ctx context.Context, l Launch) Result { mu.Lock() runs++ mu.Unlock() <-release return harness(usage("z-ai/glm-5.3", 1, 1, 1))(ctx, l) }, nil) }() } time.Sleep(200 * time.Millisecond) close(release) wg.Wait() if runs != 1 { t.Fatalf("the same holder ran %d times", runs) } // The claim, seen from a transaction of its own (another process): // claimed, not admitted. h2 := step("s2", RoleEngineering) if a, err := r.m.Admit(context.Background(), tx1, h2, nil); err != nil || !a.Admitted { t.Fatal(a, err) } other := r.meter() err := other.tx(context.Background(), func(tx *sql.Tx) error { a, err := Admit(context.Background(), tx, tx1, h2, r.clock) if err == nil && (a.Admitted || !a.Claimed) { t.Errorf("a claimed holder admitted again: %+v", a) } return err }) if err != nil { t.Fatal(err) } } // Security round finding 3: a retiring connection admits nothing, and // is removed only once its slot is free (its attempt charged or its // spend unknown). func TestMeteredRetireWaitsForTheSlot(t *testing.T) { r := newRig(t, 1_000_000, 10_000_000) ctx := context.Background() h := step("s1", RoleEngineering) if a, _ := r.m.Admit(ctx, tx1, h, nil); !a.Admitted { t.Fatal("not admitted") } if err := r.m.tx(ctx, func(tx *sql.Tx) error { return Retire(ctx, tx, tx1) }); err != nil { t.Fatal(err) } if a, _ := r.m.Admit(ctx, tx1, step("s2", RoleReview), nil); a.Admitted { t.Fatal("a retiring connection admitted an attempt") } if err := r.m.tx(ctx, func(tx *sql.Tx) error { return Remove(ctx, tx, tx1) }); !errors.Is(err, ErrSlotHeld) { t.Fatalf("removed with its slot held: %v", err) } if err := r.m.Finish(ctx, tx1, h, Result{Usage: []wire.Usage{usage("z-ai/glm-5.3", 1, 10, 1)}, Ending: Ending{Proven: true}}, nil); err != nil { t.Fatalf("the attempt's charge after retiring: %v", err) } if a, _ := r.m.Admit(ctx, tx1, step("s3", RoleReview), nil); a.Admitted { t.Fatal("a retiring connection with a free slot admitted an attempt") } if err := r.m.tx(ctx, func(tx *sql.Tx) error { return Remove(ctx, tx, tx1) }); err != nil { t.Fatal(err) } var charged int r.db.QueryRow("SELECT count(*) FROM budget_charge WHERE connection=?", tx1).Scan(&charged) if charged != 1 { t.Fatalf("charges %d", charged) } } // Security round finding 4: a budget or a Resume names the connection // it is for; one for another connection (an earlier one under the same // runner name) changes nothing. func TestMeteredBindingNamesTheConnection(t *testing.T) { r := newRig(t, 1_000_000, 10_000_000) ctx := context.Background() r.run(step("s1", RoleEngineering)) // spend unknown, pause 1 err := r.m.tx(ctx, func(tx *sql.Tx) error { if ok, err := ApplyBudget(ctx, tx, tx1, "cn_old", wire.Budget{Day: 5, Month: 9, Revision: 9}); err != nil || ok { t.Errorf("another connection's budget applied: %v %v", ok, err) } if ok, err := Resume(ctx, tx, tx1, "cn_old", 1); err != nil || ok { t.Errorf("another connection's resume consumed: %v %v", ok, err) } if ok, err := ApplyBudget(ctx, tx, tx1, "cn_1", wire.Budget{Day: 5, Month: 9, Revision: 9}); err != nil || !ok { t.Errorf("its own budget: %v %v", ok, err) } return nil }) if err != nil { t.Fatal(err) } if s := r.spend(); !s.Unknown { t.Fatal("resumed by another connection's frame") } }