| 1 | package metered |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "database/sql" |
| 6 | "errors" |
| 7 | "path/filepath" |
| 8 | "sync" |
| 9 | "testing" |
| 10 | "time" |
| 11 | |
| 12 | "amadan.net/oficina/equipo/internal/wire" |
| 13 | _ "modernc.org/sqlite" |
| 14 | ) |
| 15 | |
| 16 | // The S1 finish line (connectors spec §11), with a fake harness: each |
| 17 | // test runs attempts through the Meter the way a harness adapter does. |
| 18 | |
| 19 | const tx1 = "tensorx-1" |
| 20 | |
| 21 | func open(t *testing.T, dir string) *sql.DB { |
| 22 | t.Helper() |
| 23 | db, err := sql.Open("sqlite", "file:"+filepath.Join(dir, "thin.db")+"?_pragma=busy_timeout(5000)&_pragma=journal_mode(WAL)") |
| 24 | if err != nil { |
| 25 | t.Fatal(err) |
| 26 | } |
| 27 | db.SetMaxOpenConns(1) |
| 28 | if _, err := db.Exec(Schema); err != nil { |
| 29 | t.Fatal(err) |
| 30 | } |
| 31 | t.Cleanup(func() { db.Close() }) |
| 32 | return db |
| 33 | } |
| 34 | |
| 35 | type rig struct { |
| 36 | t *testing.T |
| 37 | dir string |
| 38 | db *sql.DB |
| 39 | m *Meter |
| 40 | clock time.Time |
| 41 | } |
| 42 | |
| 43 | func newRig(t *testing.T, day, month int64) *rig { |
| 44 | r := &rig{t: t, dir: t.TempDir(), clock: time.Date(2026, 11, 12, 10, 0, 0, 0, time.UTC)} |
| 45 | r.db = open(t, r.dir) |
| 46 | r.m = r.meter() |
| 47 | err := r.m.tx(context.Background(), func(tx *sql.Tx) error { |
| 48 | 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 { |
| 49 | return err |
| 50 | } |
| 51 | // The allowed set (S5b): the one model, proven. |
| 52 | if err := InitModels(context.Background(), tx, tx1, []string{"z-ai/glm-5.3"}, 1); err != nil { |
| 53 | return err |
| 54 | } |
| 55 | return MarkModel(context.Background(), tx, tx1, "z-ai/glm-5.3", wire.ModelHealthy, "", r.clock) |
| 56 | }) |
| 57 | if err != nil { |
| 58 | t.Fatal(err) |
| 59 | } |
| 60 | return r |
| 61 | } |
| 62 | |
| 63 | func (r *rig) meter() *Meter { |
| 64 | return &Meter{DB: r.db, Now: func() time.Time { return r.clock }, Gone: func(context.Context, string) error { return nil }} |
| 65 | } |
| 66 | |
| 67 | // usage is a fake harness's report: input and output tokens on model. |
| 68 | func usage(model string, attempt, in, out int64) wire.Usage { |
| 69 | 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} |
| 70 | } |
| 71 | |
| 72 | // harness is the fake: it reports rows and a proven exit. |
| 73 | func harness(rows ...wire.Usage) func(context.Context, Launch) Result { |
| 74 | return func(_ context.Context, l Launch) Result { |
| 75 | if err := l.Namespace("ns-" + l.Holder.Step); err != nil { |
| 76 | panic(err) |
| 77 | } |
| 78 | return Result{Usage: rows, Ending: Ending{Proven: true}} |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | func (r *rig) run(h Holder, rows ...wire.Usage) Admission { |
| 83 | r.t.Helper() |
| 84 | a, _, err := r.m.Run(context.Background(), tx1, h, harness(rows...), nil) |
| 85 | if err != nil { |
| 86 | r.t.Fatal(err) |
| 87 | } |
| 88 | return a |
| 89 | } |
| 90 | |
| 91 | func (r *rig) spend() wire.Spend { |
| 92 | c, _, err := Get(context.Background(), r.db, tx1) |
| 93 | if err != nil { |
| 94 | r.t.Fatal(err) |
| 95 | } |
| 96 | s, err := SpendOf(context.Background(), r.db, c, r.clock) |
| 97 | if err != nil { |
| 98 | r.t.Fatal(err) |
| 99 | } |
| 100 | return s |
| 101 | } |
| 102 | |
| 103 | func step(id string, role string) Holder { |
| 104 | return Holder{Step: id, Attempt: 1, Role: role, Model: "z-ai/glm-5.3"} |
| 105 | } |
| 106 | |
| 107 | // (a) The attempt after the reported spend crosses the budget is held, |
| 108 | // until the next budget day; one step can overshoot, never two. |
| 109 | func TestMeteredBudgetHoldsTheNextAttempt(t *testing.T) { |
| 110 | r := newRig(t, 1_000_000, 10_000_000) |
| 111 | // 0.4M input at 1.75 and 0.05M output at 4.50: 0.925 of the day's 1. |
| 112 | if a := r.run(step("s1", RoleEngineering), usage("z-ai/glm-5.3", 1, 400_000, 50_000)); !a.Admitted { |
| 113 | t.Fatalf("first held: %+v", a) |
| 114 | } |
| 115 | if s := r.spend(); s.Day != 925_000 || s.Unknown || s.Running { |
| 116 | t.Fatalf("spend %+v", s) |
| 117 | } |
| 118 | // Under the budget still: admitted, and it crosses it. |
| 119 | if a := r.run(step("s2", RoleReview), usage("z-ai/glm-5.3", 1, 100_000, 10_000)); !a.Admitted { |
| 120 | t.Fatalf("second held: %+v", a) |
| 121 | } |
| 122 | ran := false |
| 123 | a, _, err := r.m.Run(context.Background(), tx1, step("s3", RoleEngineering), func(context.Context, Launch) Result { ran = true; return Result{} }, nil) |
| 124 | if err != nil || a.Admitted || a.Hold != HoldBudget || ran { |
| 125 | t.Fatalf("after the budget: %+v ran=%v %v", a, ran, err) |
| 126 | } |
| 127 | if want := time.Date(2026, 11, 13, 0, 0, 0, 0, time.UTC); !a.WakeAt.Equal(want) { |
| 128 | t.Fatalf("wakes %v", a.WakeAt) |
| 129 | } |
| 130 | // A new day: admitted again; this month's spend carries on. |
| 131 | r.clock = r.clock.Add(24 * time.Hour) |
| 132 | if a := r.run(step("s3", RoleEngineering), usage("z-ai/glm-5.3", 1, 1, 1)); !a.Admitted { |
| 133 | t.Fatalf("next day held: %+v", a) |
| 134 | } |
| 135 | if s := r.spend(); s.Day != 7 || s.Month != 925_000+220_000+7 { |
| 136 | t.Fatalf("next day spend %+v", s) |
| 137 | } |
| 138 | // The month's budget holds until the first of next month. |
| 139 | r2 := newRig(t, 1_000_000, 1_000_000) |
| 140 | r2.run(step("s1", RoleEngineering), usage("z-ai/glm-5.3", 1, 600_000, 0)) |
| 141 | r2.clock = r2.clock.Add(24 * time.Hour) |
| 142 | r2.run(step("s2", RoleEngineering), usage("z-ai/glm-5.3", 1, 600_000, 0)) |
| 143 | r2.clock = r2.clock.Add(24 * time.Hour) |
| 144 | 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)) { |
| 145 | t.Fatalf("month: %+v", a) |
| 146 | } |
| 147 | // A raised budget, applied, admits; an older revision changes nothing. |
| 148 | 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 { |
| 149 | t.Fatalf("same revision applied: %v %v", ok, err) |
| 150 | } |
| 151 | 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 { |
| 152 | t.Fatalf("raise: %v %v", ok, err) |
| 153 | } |
| 154 | if a := r2.run(step("s3", RoleEngineering)); a.Hold == HoldBudget { |
| 155 | t.Fatalf("raised budget still holds: %+v", a) |
| 156 | } |
| 157 | } |
| 158 | |
| 159 | // (b) A concurrent Engineering, Review and question race on one metered |
| 160 | // connection admits exactly one; the others are held busy and nothing of |
| 161 | // theirs runs. |
| 162 | func TestMeteredRaceAdmitsExactlyOne(t *testing.T) { |
| 163 | for round := 0; round < 8; round++ { |
| 164 | r := newRig(t, 1_000_000, 10_000_000) |
| 165 | release := make(chan struct{}) |
| 166 | var mu sync.Mutex |
| 167 | ran := map[string]bool{} |
| 168 | holds := map[string]string{} |
| 169 | var wg sync.WaitGroup |
| 170 | start := make(chan struct{}) |
| 171 | for _, h := range []Holder{step("eng", RoleEngineering), step("rev", RoleReview), {Step: "q1", Attempt: 1, Role: RoleAsk, Model: "z-ai/glm-5.3"}} { |
| 172 | wg.Add(1) |
| 173 | go func() { |
| 174 | defer wg.Done() |
| 175 | <-start |
| 176 | a, _, err := r.m.Run(context.Background(), tx1, h, func(ctx context.Context, l Launch) Result { |
| 177 | mu.Lock() |
| 178 | ran[h.Role] = true |
| 179 | mu.Unlock() |
| 180 | <-release |
| 181 | return harness(usage("z-ai/glm-5.3", 1, 10, 1))(ctx, l) |
| 182 | }, nil) |
| 183 | if err != nil { |
| 184 | t.Error(err) |
| 185 | } |
| 186 | mu.Lock() |
| 187 | holds[h.Role] = a.Hold |
| 188 | mu.Unlock() |
| 189 | }() |
| 190 | } |
| 191 | close(start) |
| 192 | // The two held return at once; the admitted one waits on release. |
| 193 | deadline := time.Now().Add(5 * time.Second) |
| 194 | for { |
| 195 | mu.Lock() |
| 196 | n := len(holds) |
| 197 | mu.Unlock() |
| 198 | if n == 2 || time.Now().After(deadline) { |
| 199 | break |
| 200 | } |
| 201 | time.Sleep(time.Millisecond) |
| 202 | } |
| 203 | mu.Lock() |
| 204 | if len(ran) != 1 || len(holds) != 2 { |
| 205 | t.Fatalf("round %d: ran %v, held %v", round, ran, holds) |
| 206 | } |
| 207 | for role, hold := range holds { |
| 208 | if hold != HoldBusy || ran[role] { |
| 209 | t.Fatalf("round %d: %s held %q ran %v", round, role, hold, ran[role]) |
| 210 | } |
| 211 | } |
| 212 | mu.Unlock() |
| 213 | if s := r.spend(); !s.Running { |
| 214 | t.Fatal("the slot is not held while the attempt runs") |
| 215 | } |
| 216 | close(release) |
| 217 | wg.Wait() |
| 218 | if s := r.spend(); s.Running || s.Unknown { |
| 219 | t.Fatalf("after: %+v", s) |
| 220 | } |
| 221 | } |
| 222 | } |
| 223 | |
| 224 | // (c) A crash between the harness's exit and its charge ends in |
| 225 | // spend_unknown before anything else is admitted: until recovery the |
| 226 | // slot is held; recovery proves the namespace gone, finds no charge and |
| 227 | // pauses the connection, then releases the slot. |
| 228 | func TestMeteredCrashBeforeChargeIsSpendUnknown(t *testing.T) { |
| 229 | r := newRig(t, 1_000_000, 10_000_000) |
| 230 | r.m.Fault = func(stage string) error { |
| 231 | if stage == "exited" { |
| 232 | return ErrStopped |
| 233 | } |
| 234 | return nil |
| 235 | } |
| 236 | 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) { |
| 237 | t.Fatalf("stopped: %v", err) |
| 238 | } |
| 239 | r.db.Close() |
| 240 | // The next process, on the same thin.db. |
| 241 | r.db = open(t, r.dir) |
| 242 | var gone []string |
| 243 | r.m = r.meter() |
| 244 | r.m.Gone = func(_ context.Context, ns string) error { gone = append(gone, ns); return nil } |
| 245 | if a := r.run(step("s2", RoleReview)); a.Admitted || a.Hold != HoldBusy { |
| 246 | t.Fatalf("admitted before recovery: %+v", a) |
| 247 | } |
| 248 | // An exit that cannot be proven keeps the slot. |
| 249 | r.m.Gone = func(context.Context, string) error { return errors.New("still running") } |
| 250 | if err := r.m.Recover(context.Background()); err == nil { |
| 251 | t.Fatal("recovered an unproven exit") |
| 252 | } |
| 253 | if a := r.run(step("s2", RoleReview)); a.Hold != HoldBusy { |
| 254 | t.Fatalf("an unproven slot released: %+v", a) |
| 255 | } |
| 256 | r.m.Gone = func(_ context.Context, ns string) error { gone = append(gone, ns); return nil } |
| 257 | if err := r.m.Recover(context.Background()); err != nil { |
| 258 | t.Fatal(err) |
| 259 | } |
| 260 | if len(gone) != 1 || gone[0] != "ns-s1" { |
| 261 | t.Fatalf("namespaces proven gone: %v", gone) |
| 262 | } |
| 263 | s := r.spend() |
| 264 | if !s.Unknown || s.PauseRevision != 1 || s.Running || s.Day != 0 { |
| 265 | t.Fatalf("after recovery %+v", s) |
| 266 | } |
| 267 | if a := r.run(step("s2", RoleReview)); a.Admitted || a.Hold != HoldSpendUnknown { |
| 268 | t.Fatalf("admitted with spend unknown: %+v", a) |
| 269 | } |
| 270 | // A crash after the charge committed: recovery keeps the charge and |
| 271 | // does not pause. |
| 272 | r2 := newRig(t, 1_000_000, 10_000_000) |
| 273 | h := step("s1", RoleEngineering) |
| 274 | _, _, err := r2.m.Run(context.Background(), tx1, h, func(ctx context.Context, l Launch) Result { |
| 275 | res := harness(usage("z-ai/glm-5.3", 1, 10, 1))(ctx, l) |
| 276 | res.Proven = false |
| 277 | return res |
| 278 | }, nil) |
| 279 | if err != nil { |
| 280 | t.Fatal(err) |
| 281 | } |
| 282 | if s := r2.spend(); !s.Running || s.Day != 23 { |
| 283 | t.Fatalf("charged, unproven: %+v", s) |
| 284 | } |
| 285 | if err := r2.m.Recover(context.Background()); err != nil { |
| 286 | t.Fatal(err) |
| 287 | } |
| 288 | if s := r2.spend(); s.Running || s.Unknown || s.Day != 23 { |
| 289 | t.Fatalf("recovered after the charge: %+v", s) |
| 290 | } |
| 291 | } |
| 292 | |
| 293 | // (d) Resume is bound to its pause: consumed once, and a stale or |
| 294 | // repeated Resume leaves a newer pause in place. |
| 295 | func TestMeteredStaleResumeLeavesTheNewerPause(t *testing.T) { |
| 296 | r := newRig(t, 1_000_000, 10_000_000) |
| 297 | ctx := context.Background() |
| 298 | // An attempt with no usage figure pauses (revision 1). |
| 299 | r.run(step("s1", RoleEngineering)) |
| 300 | if s := r.spend(); !s.Unknown || s.PauseRevision != 1 { |
| 301 | t.Fatalf("pause 1: %+v", s) |
| 302 | } |
| 303 | if ok, err := r.m.Resume(ctx, tx1, "cn_1", 1, nil); err != nil || !ok { |
| 304 | t.Fatalf("resume 1: %v %v", ok, err) |
| 305 | } |
| 306 | // Another unknown spend: pause 2. |
| 307 | r.run(step("s2", RoleEngineering), wire.Usage{Provider: wire.ProviderTensorX, Connection: tx1, Model: "z-ai/glm-5.3", Attempt: 1, Outcome: wire.OutcomeFailed}) |
| 308 | if s := r.spend(); !s.Unknown || s.PauseRevision != 2 { |
| 309 | t.Fatalf("pause 2: %+v", s) |
| 310 | } |
| 311 | // The first Resume again, replayed or stale, changes nothing. |
| 312 | if ok, err := r.m.Resume(ctx, tx1, "cn_1", 1, nil); err != nil || ok { |
| 313 | t.Fatalf("stale resume cleared: %v %v", ok, err) |
| 314 | } |
| 315 | if a := r.run(step("s3", RoleEngineering)); a.Hold != HoldSpendUnknown { |
| 316 | t.Fatalf("admitted after a stale resume: %+v", a) |
| 317 | } |
| 318 | if ok, _ := r.m.Resume(ctx, tx1, "cn_1", 2, nil); !ok { |
| 319 | t.Fatal("the current resume did nothing") |
| 320 | } |
| 321 | if ok, _ := r.m.Resume(ctx, tx1, "cn_1", 2, nil); ok { |
| 322 | t.Fatal("a resume was consumed twice") |
| 323 | } |
| 324 | if a := r.run(step("s3", RoleEngineering), usage("z-ai/glm-5.3", 1, 1, 1)); !a.Admitted { |
| 325 | t.Fatalf("held after the current resume: %+v", a) |
| 326 | } |
| 327 | } |
| 328 | |
| 329 | // (e) A resent usage row charges once: the ledger is keyed by the row's |
| 330 | // own key. |
| 331 | func TestMeteredResentUsageChargesOnce(t *testing.T) { |
| 332 | r := newRig(t, 1_000_000, 10_000_000) |
| 333 | ctx := context.Background() |
| 334 | h := step("s1", RoleEngineering) |
| 335 | row := usage("z-ai/glm-5.3", 1, 100_000, 0) |
| 336 | if a, err := r.m.Admit(ctx, tx1, h, nil); err != nil || !a.Admitted { |
| 337 | t.Fatal(a, err) |
| 338 | } |
| 339 | for i := 0; i < 3; i++ { |
| 340 | if err := r.m.Finish(ctx, tx1, h, Result{Usage: []wire.Usage{row}}, nil); err != nil { |
| 341 | t.Fatal(err) |
| 342 | } |
| 343 | } |
| 344 | if err := r.m.Finish(ctx, tx1, h, Result{Usage: []wire.Usage{row}, Ending: Ending{Proven: true}}, nil); err != nil { |
| 345 | t.Fatal(err) |
| 346 | } |
| 347 | if s := r.spend(); s.Day != 175_000 || s.Unknown { |
| 348 | t.Fatalf("charged %+v", s) |
| 349 | } |
| 350 | // Another attempt of the same step is another row, charged too. |
| 351 | h2 := Holder{Step: "s1", Attempt: 2, Role: RoleEngineering, Model: "z-ai/glm-5.3"} |
| 352 | r.run(h2, usage("z-ai/glm-5.3", 2, 100_000, 0)) |
| 353 | if s := r.spend(); s.Day != 350_000 { |
| 354 | t.Fatalf("second attempt %+v", s) |
| 355 | } |
| 356 | } |
| 357 | |
| 358 | // (f) An unpriced model gives spend unknown, and so does an unpriceable |
| 359 | // component; the row is reported with no cost. |
| 360 | func TestMeteredUnpricedModelIsSpendUnknown(t *testing.T) { |
| 361 | r := newRig(t, 1_000_000, 10_000_000) |
| 362 | var reported []wire.Usage |
| 363 | _, _, 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 { |
| 364 | reported = rows |
| 365 | return nil |
| 366 | }) |
| 367 | if err != nil { |
| 368 | t.Fatal(err) |
| 369 | } |
| 370 | if len(reported) != 1 || reported[0].CostMicros != nil || reported[0].PriceVersion != "tensorx-2026-11-12" || reported[0].Currency != "USD" { |
| 371 | t.Fatalf("reported %+v", reported) |
| 372 | } |
| 373 | if s := r.spend(); !s.Unknown || s.Day != 0 { |
| 374 | t.Fatalf("spend %+v", s) |
| 375 | } |
| 376 | if a := r.run(step("s2", RoleEngineering)); a.Hold != HoldSpendUnknown { |
| 377 | t.Fatalf("admitted %+v", a) |
| 378 | } |
| 379 | r2 := newRig(t, 1_000_000, 10_000_000) |
| 380 | cw := usage("z-ai/glm-5.3", 1, 10, 1) |
| 381 | cw.CacheWriteTokens = new(int64) |
| 382 | *cw.CacheWriteTokens = 5 |
| 383 | r2.run(step("s1", RoleEngineering), cw) |
| 384 | if s := r2.spend(); !s.Unknown { |
| 385 | t.Fatalf("unpriced cache write: %+v", s) |
| 386 | } |
| 387 | // A slot is never released before its attempt's proof. |
| 388 | r3 := newRig(t, 1_000_000, 10_000_000) |
| 389 | h := step("s1", RoleEngineering) |
| 390 | r3.m.Admit(context.Background(), tx1, h, nil) |
| 391 | err = r3.m.tx(context.Background(), func(tx *sql.Tx) error { return Settle(context.Background(), tx, tx1, h, Ending{}) }) |
| 392 | if !errors.Is(err, ErrNotProven) || !r3.spend().Running { |
| 393 | t.Fatalf("settled unproven: %v", err) |
| 394 | } |
| 395 | // An attempt that started no harness spends nothing and pauses nothing. |
| 396 | r3.m.tx(context.Background(), func(tx *sql.Tx) error { |
| 397 | return Settle(context.Background(), tx, tx1, h, Ending{Proven: true, NotStarted: true}) |
| 398 | }) |
| 399 | if s := r3.spend(); s.Running || s.Unknown { |
| 400 | t.Fatalf("not started: %+v", s) |
| 401 | } |
| 402 | } |
| 403 | |
| 404 | // Security round finding 1: an attempt is registered as running before |
| 405 | // its admission commits, so a Recover in between (here, in the window |
| 406 | // right after the commit) never releases its slot unproven, and nothing |
| 407 | // else is admitted while it runs. |
| 408 | func TestMeteredRecoverBetweenAdmissionAndLaunch(t *testing.T) { |
| 409 | r := newRig(t, 1_000_000, 10_000_000) |
| 410 | recovered := false |
| 411 | r.m.Fault = func(stage string) error { |
| 412 | if stage == "admitted" && !recovered { |
| 413 | recovered = true |
| 414 | if err := r.m.Recover(context.Background()); err != nil { |
| 415 | t.Error(err) |
| 416 | } |
| 417 | } |
| 418 | return nil |
| 419 | } |
| 420 | ran := false |
| 421 | _, _, err := r.m.Run(context.Background(), tx1, step("s1", RoleEngineering), func(ctx context.Context, l Launch) Result { |
| 422 | ran = true |
| 423 | if s := r.spend(); !s.Running { |
| 424 | t.Error("the slot was released between the admission and the launch") |
| 425 | } |
| 426 | if a, _ := r.m.Admit(ctx, tx1, step("s2", RoleReview), nil); a.Admitted { |
| 427 | t.Error("a second attempt was admitted while the first ran") |
| 428 | } |
| 429 | return harness(usage("z-ai/glm-5.3", 1, 1, 1))(ctx, l) |
| 430 | }, nil) |
| 431 | if err != nil || !ran || !recovered { |
| 432 | t.Fatalf("ran %v recovered %v %v", ran, recovered, err) |
| 433 | } |
| 434 | } |
| 435 | |
| 436 | // Security round finding 2: a holder already claiming the slot is not |
| 437 | // let in again. Two runs with the same holder at once start one harness; |
| 438 | // a second process (another Meter) finding the claim does not launch. |
| 439 | func TestMeteredDuplicateHolderRunsOnce(t *testing.T) { |
| 440 | r := newRig(t, 1_000_000, 10_000_000) |
| 441 | h := step("s1", RoleEngineering) |
| 442 | release := make(chan struct{}) |
| 443 | var mu sync.Mutex |
| 444 | runs := 0 |
| 445 | var wg sync.WaitGroup |
| 446 | for i := 0; i < 2; i++ { |
| 447 | wg.Add(1) |
| 448 | go func() { |
| 449 | defer wg.Done() |
| 450 | r.m.Run(context.Background(), tx1, h, func(ctx context.Context, l Launch) Result { |
| 451 | mu.Lock() |
| 452 | runs++ |
| 453 | mu.Unlock() |
| 454 | <-release |
| 455 | return harness(usage("z-ai/glm-5.3", 1, 1, 1))(ctx, l) |
| 456 | }, nil) |
| 457 | }() |
| 458 | } |
| 459 | time.Sleep(200 * time.Millisecond) |
| 460 | close(release) |
| 461 | wg.Wait() |
| 462 | if runs != 1 { |
| 463 | t.Fatalf("the same holder ran %d times", runs) |
| 464 | } |
| 465 | // The claim, seen from a transaction of its own (another process): |
| 466 | // claimed, not admitted. |
| 467 | h2 := step("s2", RoleEngineering) |
| 468 | if a, err := r.m.Admit(context.Background(), tx1, h2, nil); err != nil || !a.Admitted { |
| 469 | t.Fatal(a, err) |
| 470 | } |
| 471 | other := r.meter() |
| 472 | err := other.tx(context.Background(), func(tx *sql.Tx) error { |
| 473 | a, err := Admit(context.Background(), tx, tx1, h2, r.clock) |
| 474 | if err == nil && (a.Admitted || !a.Claimed) { |
| 475 | t.Errorf("a claimed holder admitted again: %+v", a) |
| 476 | } |
| 477 | return err |
| 478 | }) |
| 479 | if err != nil { |
| 480 | t.Fatal(err) |
| 481 | } |
| 482 | } |
| 483 | |
| 484 | // Security round finding 3: a retiring connection admits nothing, and |
| 485 | // is removed only once its slot is free (its attempt charged or its |
| 486 | // spend unknown). |
| 487 | func TestMeteredRetireWaitsForTheSlot(t *testing.T) { |
| 488 | r := newRig(t, 1_000_000, 10_000_000) |
| 489 | ctx := context.Background() |
| 490 | h := step("s1", RoleEngineering) |
| 491 | if a, _ := r.m.Admit(ctx, tx1, h, nil); !a.Admitted { |
| 492 | t.Fatal("not admitted") |
| 493 | } |
| 494 | if err := r.m.tx(ctx, func(tx *sql.Tx) error { return Retire(ctx, tx, tx1) }); err != nil { |
| 495 | t.Fatal(err) |
| 496 | } |
| 497 | if a, _ := r.m.Admit(ctx, tx1, step("s2", RoleReview), nil); a.Admitted { |
| 498 | t.Fatal("a retiring connection admitted an attempt") |
| 499 | } |
| 500 | if err := r.m.tx(ctx, func(tx *sql.Tx) error { return Remove(ctx, tx, tx1) }); !errors.Is(err, ErrSlotHeld) { |
| 501 | t.Fatalf("removed with its slot held: %v", err) |
| 502 | } |
| 503 | 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 { |
| 504 | t.Fatalf("the attempt's charge after retiring: %v", err) |
| 505 | } |
| 506 | if a, _ := r.m.Admit(ctx, tx1, step("s3", RoleReview), nil); a.Admitted { |
| 507 | t.Fatal("a retiring connection with a free slot admitted an attempt") |
| 508 | } |
| 509 | if err := r.m.tx(ctx, func(tx *sql.Tx) error { return Remove(ctx, tx, tx1) }); err != nil { |
| 510 | t.Fatal(err) |
| 511 | } |
| 512 | var charged int |
| 513 | r.db.QueryRow("SELECT count(*) FROM budget_charge WHERE connection=?", tx1).Scan(&charged) |
| 514 | if charged != 1 { |
| 515 | t.Fatalf("charges %d", charged) |
| 516 | } |
| 517 | } |
| 518 | |
| 519 | // Security round finding 4: a budget or a Resume names the connection |
| 520 | // it is for; one for another connection (an earlier one under the same |
| 521 | // runner name) changes nothing. |
| 522 | func TestMeteredBindingNamesTheConnection(t *testing.T) { |
| 523 | r := newRig(t, 1_000_000, 10_000_000) |
| 524 | ctx := context.Background() |
| 525 | r.run(step("s1", RoleEngineering)) // spend unknown, pause 1 |
| 526 | err := r.m.tx(ctx, func(tx *sql.Tx) error { |
| 527 | if ok, err := ApplyBudget(ctx, tx, tx1, "cn_old", wire.Budget{Day: 5, Month: 9, Revision: 9}); err != nil || ok { |
| 528 | t.Errorf("another connection's budget applied: %v %v", ok, err) |
| 529 | } |
| 530 | if ok, err := Resume(ctx, tx, tx1, "cn_old", 1); err != nil || ok { |
| 531 | t.Errorf("another connection's resume consumed: %v %v", ok, err) |
| 532 | } |
| 533 | if ok, err := ApplyBudget(ctx, tx, tx1, "cn_1", wire.Budget{Day: 5, Month: 9, Revision: 9}); err != nil || !ok { |
| 534 | t.Errorf("its own budget: %v %v", ok, err) |
| 535 | } |
| 536 | return nil |
| 537 | }) |
| 538 | if err != nil { |
| 539 | t.Fatal(err) |
| 540 | } |
| 541 | if s := r.spend(); !s.Unknown { |
| 542 | t.Fatal("resumed by another connection's frame") |
| 543 | } |
| 544 | } |
| 545 | |