Public: anyone can read this; the crew can change it.
Sentinel: shared:01m23vygyffx5hg2f5vm8r74sr:iv8v0a9c0m is past its budget: trevato/forge: "two processes on one data directory start each run once > the crew is queued on each issue once, whiche… #16677
Check · Review · Land · Live done — Landed and live in production.
torque/forge:torque/16663-sentinel-shared-01m23vygyffx5hg2f5vm8r74 → main 0 commits fork
2 files
changed +72
−16
src/core/allocation.ts +40 −15
| @@ -216,19 +216,27 @@ const subscriptionScopes = (db: Database, repoId: string): { bet: string | null; | ||
| 216 | 216 | ) |
| 217 | 217 | .all(repoId); |
| 218 | 218 | |
| 219 | interface Owed { | |
| 220 | readonly id: string; | |
| 221 | readonly cost: number; | |
| 222 | readonly issue: string | null; | |
| 223 | readonly at: string; | |
| 224 | } | |
| 225 | ||
| 219 | 226 | /** |
| 220 | * Bring the ledger up to `now`, appending what is owed and nothing else, so | |
| 221 | * the same state gives the same entries: the week's refill (after expiring | |
| 222 | * what the last week left), and each finished run's cost not yet entered, | |
| 223 | * drawn from the subscription fund first and from cash for the rest. | |
| 227 | * What the ledger lacks for the week opening at `start`: the finished runs not yet charged, | |
| 228 | * whether the week was refilled, the weekly sum, and the drift a changed daily ceiling left. | |
| 224 | 229 | */ |
| 225 | export function settle(db: Database, repoId: string, dailyCeilingUsd: number, now: Date): void { | |
| 226 | const start = weekStart(now); | |
| 227 | const week = start.toISOString().slice(0, 10); | |
| 230 | function owing( | |
| 231 | db: Database, | |
| 232 | repoId: string, | |
| 233 | dailyCeilingUsd: number, | |
| 234 | start: Date, | |
| 235 | ): { owed: Owed[]; refilled: boolean; weekly: number; drift: number } { | |
| 228 | 236 | // Runs that began in the week before still settle; older ones are history. |
| 229 | 237 | const since = new Date(start.getTime() - 7 * 86_400_000); |
| 230 | 238 | const owed = db |
| 231 | .query<{ id: string; cost: number; issue: string | null; at: string }, [string, string]>( | |
| 239 | .query<Owed, [string, string]>( | |
| 232 | 240 | `SELECT r.id AS id, r.cost_usd AS cost, r.issue_id AS issue, |
| 233 | 241 | COALESCE(r.finished_at, r.started_at, r.created_at) AS at FROM run r |
| 234 | 242 | WHERE r.repo_id = ?1 AND r.id >= ?2 AND r.kind = 'agent' AND r.cost_usd > 0 |
| @@ -241,12 +249,26 @@ export function settle(db: Database, repoId: string, dailyCeilingUsd: number, no | ||
| 241 | 249 | .query<{ n: number }, [string, string]>( |
| 242 | 250 | "SELECT COUNT(*) AS n FROM allocation_entry WHERE repo_id = ?1 AND kind = 'weekly' AND week = ?2", |
| 243 | 251 | ) |
| 244 | .get(repoId, week)?.n === 1; | |
| 252 | .get(repoId, start.toISOString().slice(0, 10))?.n === 1; | |
| 245 | 253 | const weekly = weeklyUnits(db, repoId, dailyCeilingUsd); |
| 246 | 254 | // With no weekly allocation set, the week's allocation follows the daily ceiling as it is |
| 247 | 255 | // changed: the drift between seven of it and what was refilled is entered as one signed grant. |
| 248 | 256 | const drift = refilled && !weeklySet(db, repoId) ? weekly - allocatedSince(db, repoId, start) : 0; |
| 249 | if (owed.length === 0 && drift === 0 && (refilled || weekly === 0)) return; | |
| 257 | return { owed, refilled, weekly, drift }; | |
| 258 | } | |
| 259 | ||
| 260 | /** | |
| 261 | * Bring the ledger up to `now`, appending what is owed and nothing else, so | |
| 262 | * the same state gives the same entries: the week's refill (after expiring | |
| 263 | * what the last week left), and each finished run's cost not yet entered, | |
| 264 | * drawn from the subscription fund first and from cash for the rest. | |
| 265 | */ | |
| 266 | export function settle(db: Database, repoId: string, dailyCeilingUsd: number, now: Date): void { | |
| 267 | const start = weekStart(now); | |
| 268 | const week = start.toISOString().slice(0, 10); | |
| 269 | // Read without a lock first: most calls owe nothing and write nothing. | |
| 270 | const first = owing(db, repoId, dailyCeilingUsd, start); | |
| 271 | if (first.owed.length === 0 && first.drift === 0 && (first.refilled || first.weekly === 0)) return; | |
| 250 | 272 | // A run's entry is stamped when the run ended, and a run that ended before this week opened is |
| 251 | 273 | // paid before the reset expires what that week left, never from this week's fresh fund. |
| 252 | 274 | const stamp = (at: string): Date => { |
| @@ -269,6 +291,11 @@ export function settle(db: Database, repoId: string, dailyCeilingUsd: number, no | ||
| 269 | 291 | append(db, { repoId, bet, kind: "run", fund: "cash", units: -fromCash, at, ...(fromSub > 0 ? {} : { runId: run.id }), note: fromSub > 0 ? `run ${run.id} cost beyond the subscription fund` : "run cost at list price" }); |
| 270 | 292 | }; |
| 271 | 293 | transact(db, () => { |
| 294 | // Read again under the write lock (#16663): during a roll the process beside this one may | |
| 295 | // have refilled the week or charged a run since the read above. Acting on that stale read | |
| 296 | // expired the other's fresh refill as last week's remainder, and the week's own refill then | |
| 297 | // met the unique index: the balance stood at $0 until Monday. | |
| 298 | const { owed, refilled, weekly, drift } = owing(db, repoId, dailyCeilingUsd, start); | |
| 272 | 299 | for (const run of owed) if (before(run)) charge(run); |
| 273 | 300 | if (drift !== 0) |
| 274 | 301 | append(db, { repoId, kind: "grant", fund: "subscription", units: drift, at: now, note: "daily ceiling changed: the week's allocation follows" }); |
| @@ -276,11 +303,9 @@ export function settle(db: Database, repoId: string, dailyCeilingUsd: number, no | ||
| 276 | 303 | for (const s of subscriptionScopes(db, repoId)) |
| 277 | 304 | if (s.n > 0) |
| 278 | 305 | append(db, { repoId, bet: s.bet, kind: "expiry", fund: "subscription", units: -s.n, at: start, note: "the week's reset" }); |
| 279 | try { | |
| 280 | append(db, { repoId, kind: "weekly", fund: "subscription", units: weekly, at: start, week, note: "weekly allocation" }); | |
| 281 | } catch { | |
| 282 | // A second process refilled this week first (the unique index); the allocation stands once. | |
| 283 | } | |
| 306 | // `refilled` was read under this lock, so no other process can have refilled since; were the | |
| 307 | // unique index met anyway, the throw rolls the expiry back with it. | |
| 308 | append(db, { repoId, kind: "weekly", fund: "subscription", units: weekly, at: start, week, note: "weekly allocation" }); | |
| 284 | 309 | } |
| 285 | 310 | for (const run of owed) if (!before(run)) charge(run); |
| 286 | 311 | }); |
test/allocation.test.ts +32 −1
| @@ -15,7 +15,7 @@ import { createApp, type App } from "../src/app.ts"; | ||
| 15 | 15 | import type { Repo } from "../src/core/repos.ts"; |
| 16 | 16 | import { createRun } from "../src/core/runs.ts"; |
| 17 | 17 | import type { User } from "../src/core/users.ts"; |
| 18 | import type { Database } from "bun:sqlite"; | |
| 18 | import { Database } from "bun:sqlite"; | |
| 19 | 19 | import { serve, type Servers } from "../src/http/server.ts"; |
| 20 | 20 | import { |
| 21 | 21 | balanceOf, |
| @@ -127,6 +127,37 @@ describe("the ledger", () => { | ||
| 127 | 127 | expect(ledger(app.db, repo.id).filter((e) => e.kind === "run").map((e) => e.units).sort()).toEqual([-1_250_000, -500_000]); |
| 128 | 128 | }); |
| 129 | 129 | |
| 130 | test("two processes settling at once refill the week once and expire nothing (#16663)", async () => { | |
| 131 | const repo = await mint(3); | |
| 132 | spend(repo, 0.25); | |
| 133 | // The process beside this one, on its own connection to the same file, settles in the gap | |
| 134 | // between this one's unlocked read and its write lock: what a roll does. | |
| 135 | const beside = new Database(app.db.filename); | |
| 136 | beside.exec("PRAGMA busy_timeout = 5000"); | |
| 137 | let interleaved = false; | |
| 138 | const racing = new Proxy(app.db, { | |
| 139 | get(target, key) { | |
| 140 | if (key === "transaction" && !interleaved) { | |
| 141 | interleaved = true; | |
| 142 | settle(beside, repo.id, 3, WED); | |
| 143 | } | |
| 144 | const value = Reflect.get(target, key, target) as unknown; | |
| 145 | return typeof value === "function" ? value.bind(target) : value; | |
| 146 | }, | |
| 147 | }); | |
| 148 | try { | |
| 149 | settle(racing, repo.id, 3, WED); | |
| 150 | } finally { | |
| 151 | beside.close(); | |
| 152 | } | |
| 153 | expect(interleaved).toBe(true); | |
| 154 | const kinds = ledger(app.db, repo.id).map((e) => e.kind).sort(); | |
| 155 | expect(kinds).toEqual(["run", "weekly"]); | |
| 156 | // $3 a day is $21 a week, less the one $0.25 run, charged once. | |
| 157 | expect(balanceOf(app.db, repo.id).total).toBe(21 * UNIT - 250_000); | |
| 158 | expect(mayStart(app.db, repo.id, 3, WED).ok).toBe(true); | |
| 159 | }); | |
| 160 | ||
| 130 | 161 | test("entries are append only", async () => { |
| 131 | 162 | const repo = await mint(1); |
| 132 | 163 | settle(app.db, repo.id, 1, WED); |
new above
offline