Skip to content

Commit 48ee020

Browse files
author
hzq
committed
Page and retry legacy platform settlement
Bound startup reconciliation, verify account and run evidence before charging, and retry storage failures from the durable unsettled hold. Preserve repayment order within an account with unreadable legacy evidence.
1 parent de8008c commit 48ee020

8 files changed

Lines changed: 595 additions & 72 deletions

‎docs/stability.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -520,6 +520,12 @@ Background accounting checks its time budget between settlement or readback atte
520520
not wait synchronously for a SQLite writer. On contention it retries without advancing past the
521521
blocked charge. Each journal pass has a fixed upper bound, then checks for newly ready work,
522522
including runs that reached a terminal state behind its cursor.
523+
At startup, the developer platform checks legacy billing holds in bounded pages too. It does
524+
not settle a hold owned by the key journal or by an outstanding receipt check. A storage error
525+
leaves the same hold eligible for retry; a committed settlement is no longer an eligible hold.
526+
Unreadable billing evidence is not treated as a missing run or as permission to refund it.
527+
An invalid legacy row defers later holds on the same account so they cannot spend its balance
528+
first; holds on independent accounts can still settle.
523529

524530
- The storage schema version is `PRAGMA user_version` (currently 4). Every start migrates older
525531
databases inside one `BEGIN IMMEDIATE` transaction; a failure rolls back and leaves the database

‎src/gateway/platform-billing.ts‎

Lines changed: 71 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import type { DatabaseSync } from 'node:sqlite';
88
import type { RunStatus } from '../core/contracts.js';
99
import { Fault } from '../core/util.js';
10+
import { runSqliteWrite } from '../store/sqlite-write.js';
1011
import { prepared, transaction } from './platform-db.js';
1112

1213
export type LedgerKind = 'run' | 'redeem' | 'grant' | 'adjust';
@@ -29,6 +30,12 @@ export type LedgerRecord = {
2930
export type RunRecord = LedgerRecord & { accountId: string; price: PriceMicro };
3031
/** Micro-point prices recorded on a run row when the run starts. */
3132
export type PriceMicro = { perRun: number; per1kTokens: number };
33+
export type UnsettledHold = {
34+
id: string;
35+
runId: string | null;
36+
accountId: string;
37+
agent: string | null;
38+
};
3239
export type UsageBucket = { runs: number; tokens: number; spent: number };
3340
export type UsageRecord = {
3441
totals: UsageBucket;
@@ -53,6 +60,14 @@ const bucketOf = (row: Record<string, unknown>): UsageBucket => ({
5360

5461
const DAY = 86_400_000;
5562
const utcDate = (ms: number) => new Date(ms).toISOString().slice(0, 10);
63+
const unsettled = "owner=? AND kind='run' AND status='in_progress'";
64+
const holdColumns = 'CAST(id AS TEXT) AS id,run_id,account_id,agent';
65+
const hold = (row: Record<string, unknown>): UnsettledHold => ({
66+
id: String(row.id),
67+
runId: row.run_id === null ? null : String(row.run_id),
68+
accountId: String(row.account_id),
69+
agent: row.agent === null ? null : String(row.agent),
70+
});
5671

5772
/** Amount owed for a run in micro-points, rounded up to a whole micro-point. */
5873
export function runCharge(price: PriceMicro, status: RunStatus, tokens: number): number {
@@ -94,11 +109,14 @@ export class PlatformBilling {
94109
};
95110
}
96111
private addBalance(accountId: string, delta: number): number {
97-
prepared(this.db, 'UPDATE platform_accounts SET balance=balance+? WHERE id=? AND owner=?').run(
112+
const changed = runSqliteWrite(
113+
prepared(this.db, 'UPDATE platform_accounts SET balance=balance+? WHERE id=? AND owner=?'),
98114
delta,
99115
accountId,
100116
this.owner,
101117
);
118+
if (Number(changed.changes) !== 1)
119+
throw new Fault('persistence_failed', 'The platform account balance was not updated.', 500);
102120
return this.balance(accountId);
103121
}
104122
/** Posts a non-run entry and moves the balance by `amount` (one transaction). */
@@ -178,23 +196,42 @@ export class PlatformBilling {
178196
*/
179197
settleRun(runId: string, status: RunStatus, tokens: number): void {
180198
transaction(this.db, () => {
181-
const row = prepared(this.db, 'SELECT * FROM platform_ledger WHERE run_id=? AND owner=?').get(
182-
runId,
183-
this.owner,
184-
);
199+
const row = prepared(
200+
this.db,
201+
`SELECT CAST(id AS TEXT) AS id,account_id,amount,balance_after,payload
202+
FROM platform_ledger WHERE run_id=? AND owner=? AND kind='run'`,
203+
).get(runId, this.owner);
185204
if (!row) return;
186-
const prior = this.parse(row);
187-
const price = JSON.parse(String(row.payload)) as PriceMicro;
205+
const price = JSON.parse(String(row.payload)) as PriceMicro | null;
206+
if (
207+
!price ||
208+
!Number.isSafeInteger(price.perRun) ||
209+
price.perRun < 0 ||
210+
!Number.isSafeInteger(price.per1kTokens) ||
211+
price.per1kTokens < 0
212+
)
213+
throw new Fault('persistence_failed', 'The reserved platform price is invalid.', 500);
188214
const accountId = String(row.account_id);
189-
const charged = -prior.amount;
215+
const priorAmount = Number(row.amount);
216+
const charged = -priorAmount;
190217
const ceiling = Math.max(charged, charged + this.balance(accountId));
191218
const amount = -Math.min(runCharge(price, status, tokens), ceiling);
192-
const delta = amount - prior.amount;
193-
const after = delta ? this.addBalance(accountId, delta) : prior.balanceAfter;
194-
prepared(
195-
this.db,
196-
'UPDATE platform_ledger SET amount=?,balance_after=?,tokens=?,status=? WHERE id=?',
197-
).run(amount, after, Math.max(0, Math.floor(tokens)), status, prior.id);
219+
const delta = amount - priorAmount;
220+
const after = delta ? this.addBalance(accountId, delta) : Number(row.balance_after);
221+
const changed = runSqliteWrite(
222+
prepared(
223+
this.db,
224+
`UPDATE platform_ledger
225+
SET amount=?,balance_after=?,tokens=?,status=? WHERE id=CAST(? AS INTEGER)`,
226+
),
227+
amount,
228+
after,
229+
Math.max(0, Math.floor(tokens)),
230+
status,
231+
String(row.id),
232+
);
233+
if (Number(changed.changes) !== 1)
234+
throw new Fault('persistence_failed', 'The platform run charge was not recorded.', 500);
198235
});
199236
}
200237
/**
@@ -380,13 +417,28 @@ export class PlatformBilling {
380417
).get(this.owner, accountId, runId);
381418
return row ? this.runRecord(row) : undefined;
382419
}
383-
/** Run IDs whose row has not been settled yet (startup reconciliation). */
384-
unsettledRuns(): string[] {
420+
unsettledCeiling(): string | null {
421+
const bound = prepared(
422+
this.db,
423+
`SELECT CAST(max(id) AS TEXT) AS bound FROM platform_ledger WHERE ${unsettled}`,
424+
).get(this.owner)?.bound;
425+
return bound == null ? null : String(bound);
426+
}
427+
unsettledPage(after: string | null, through: string, size: number): UnsettledHold[] {
428+
const start = after === null ? '' : ' AND id>CAST(? AS INTEGER)';
385429
return prepared(
386430
this.db,
387-
"SELECT run_id FROM platform_ledger WHERE owner=? AND kind='run' AND status='in_progress' ORDER BY id",
431+
`SELECT ${holdColumns} FROM platform_ledger WHERE ${unsettled}${start}
432+
AND id<=CAST(? AS INTEGER) ORDER BY id LIMIT ?`,
388433
)
389-
.all(this.owner)
390-
.map((row) => String(row.run_id));
434+
.all(this.owner, ...(after === null ? [] : [after]), through, size)
435+
.map(hold);
436+
}
437+
unsettledHold(id: string): UnsettledHold | undefined {
438+
const row = prepared(
439+
this.db,
440+
`SELECT ${holdColumns} FROM platform_ledger WHERE ${unsettled} AND id=CAST(? AS INTEGER)`,
441+
).get(this.owner, id);
442+
return row && hold(row);
391443
}
392444
}

‎src/gateway/platform-db.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@ CREATE TABLE IF NOT EXISTS platform_code_uses(code_id TEXT NOT NULL,account_id T
7070
CREATE TABLE IF NOT EXISTS platform_ledger(id INTEGER PRIMARY KEY AUTOINCREMENT,owner TEXT NOT NULL,account_id TEXT NOT NULL,kind TEXT NOT NULL,amount INTEGER NOT NULL,balance_after INTEGER NOT NULL,run_id TEXT UNIQUE,agent TEXT,tokens INTEGER NOT NULL DEFAULT 0,status TEXT,note TEXT,payload TEXT NOT NULL,created_at INTEGER NOT NULL);
7171
CREATE INDEX IF NOT EXISTS platform_ledger_account ON platform_ledger(account_id,id);
7272
CREATE INDEX IF NOT EXISTS platform_ledger_time ON platform_ledger(owner,created_at);
73+
CREATE INDEX IF NOT EXISTS platform_unsettled_runs ON platform_ledger(owner,id) WHERE kind='run' AND status='in_progress';
7374
CREATE TABLE IF NOT EXISTS platform_references(owner TEXT NOT NULL,reference TEXT NOT NULL,entry_id INTEGER NOT NULL UNIQUE,created_at INTEGER NOT NULL,PRIMARY KEY(owner,reference));
7475
CREATE TABLE IF NOT EXISTS platform_reset_codes(account_id TEXT PRIMARY KEY,owner TEXT NOT NULL,hash TEXT NOT NULL,expires_at INTEGER NOT NULL,created_at INTEGER NOT NULL);
7576
CREATE TABLE IF NOT EXISTS platform_rate_limits(bucket TEXT NOT NULL,key TEXT NOT NULL,window_start INTEGER NOT NULL,count INTEGER NOT NULL,expires_at INTEGER NOT NULL,PRIMARY KEY(bucket,key));
@@ -81,10 +82,12 @@ CREATE TABLE IF NOT EXISTS platform_verification_secrets(owner TEXT PRIMARY KEY,
8182
/** Runs `fn` in one IMMEDIATE transaction (or inside the caller's, if one is open). */
8283
export function transaction<T>(db: DatabaseSync, fn: () => T): T {
8384
if (db.isTransaction) return fn();
84-
db.exec('BEGIN IMMEDIATE');
8585
try {
86+
db.exec('BEGIN IMMEDIATE');
8687
const result = fn();
8788
db.exec('COMMIT');
89+
if (db.isTransaction)
90+
throw new Fault('persistence_failed', 'The platform transaction is still open.', 500);
8891
return result;
8992
} catch (error) {
9093
if (db.isTransaction) db.exec('ROLLBACK');

0 commit comments

Comments
 (0)