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

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

torque/forge:torque/16663-sentinel-shared-01m23vygyffx5hg2f5vm8r74 → main 0 commits fork

  • Merged. torque/16663-sentinel-shared-01m23vygyffx5hg2f5vm8r74 was merged into main as 1919ee3.

Review

Sign in to review this change.
2 files changed +72 −16
src/core/allocation.ts +40 −15
@@ -216,19 +216,27 @@ const subscriptionScopes = (db: Database, repoId: string): { bet: string | null;
216216 )
217217 .all(repoId);
218218
219 interface Owed {
220 readonly id: string;
221 readonly cost: number;
222 readonly issue: string | null;
223 readonly at: string;
224 }
225
219226 /**
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.
224229 */
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 } {
228236 // Runs that began in the week before still settle; older ones are history.
229237 const since = new Date(start.getTime() - 7 * 86_400_000);
230238 const owed = db
231 .query<{ id: string; cost: number; issue: string | null; at: string }, [string, string]>(
239 .query<Owed, [string, string]>(
232240 `SELECT r.id AS id, r.cost_usd AS cost, r.issue_id AS issue,
233241 COALESCE(r.finished_at, r.started_at, r.created_at) AS at FROM run r
234242 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
241249 .query<{ n: number }, [string, string]>(
242250 "SELECT COUNT(*) AS n FROM allocation_entry WHERE repo_id = ?1 AND kind = 'weekly' AND week = ?2",
243251 )
244 .get(repoId, week)?.n === 1;
252 .get(repoId, start.toISOString().slice(0, 10))?.n === 1;
245253 const weekly = weeklyUnits(db, repoId, dailyCeilingUsd);
246254 // With no weekly allocation set, the week's allocation follows the daily ceiling as it is
247255 // changed: the drift between seven of it and what was refilled is entered as one signed grant.
248256 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;
250272 // A run's entry is stamped when the run ended, and a run that ended before this week opened is
251273 // paid before the reset expires what that week left, never from this week's fresh fund.
252274 const stamp = (at: string): Date => {
@@ -269,6 +291,11 @@ export function settle(db: Database, repoId: string, dailyCeilingUsd: number, no
269291 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" });
270292 };
271293 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);
272299 for (const run of owed) if (before(run)) charge(run);
273300 if (drift !== 0)
274301 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
276303 for (const s of subscriptionScopes(db, repoId))
277304 if (s.n > 0)
278305 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" });
284309 }
285310 for (const run of owed) if (!before(run)) charge(run);
286311 });
test/allocation.test.ts +32 −1
@@ -15,7 +15,7 @@ import { createApp, type App } from "../src/app.ts";
1515 import type { Repo } from "../src/core/repos.ts";
1616 import { createRun } from "../src/core/runs.ts";
1717 import type { User } from "../src/core/users.ts";
18 import type { Database } from "bun:sqlite";
18 import { Database } from "bun:sqlite";
1919 import { serve, type Servers } from "../src/http/server.ts";
2020 import {
2121 balanceOf,
@@ -127,6 +127,37 @@ describe("the ledger", () => {
127127 expect(ledger(app.db, repo.id).filter((e) => e.kind === "run").map((e) => e.units).sort()).toEqual([-1_250_000, -500_000]);
128128 });
129129
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
130161 test("entries are append only", async () => {
131162 const repo = await mint(1);
132163 settle(app.db, repo.id, 1, WED);

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs