Skip to content

Commit de8008c

Browse files
author
hzq
committed
Time-slice background accounting recovery
Retry SQLite writer contention without skipping journal entries. Bound each sweep, retain pending receipt checks, and let key accounting own journalled platform charges.
1 parent 480b8e1 commit de8008c

10 files changed

Lines changed: 556 additions & 117 deletions

‎docs/stability.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -516,6 +516,10 @@ In the usual sparse case, settlement recovery looks up terminal candidates witho
516516
queued or active admissions. A dense backlog uses the original ordered journal pagination.
517517
The candidate catalog changes in the same transaction as its source rows; the accounting
518518
journal remains the source of truth and retains its original layout and order.
519+
Background accounting checks its time budget between settlement or readback attempts and does
520+
not wait synchronously for a SQLite writer. On contention it retries without advancing past the
521+
blocked charge. Each journal pass has a fixed upper bound, then checks for newly ready work,
522+
including runs that reached a terminal state behind its cursor.
519523

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

‎src/gateway/key-accounting.ts‎

Lines changed: 48 additions & 91 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,9 @@ import { withSavepoint } from '../store/savepoint.js';
99
import { runSqliteWrite } from '../store/sqlite-write.js';
1010
import type { Store } from '../store/store.js';
1111
import { KeyQuotaResets, type StageQuota } from './key-quota-resets.js';
12+
import { KeySettlementRecovery } from './key-settlement-recovery.js';
1213
import type { AccountKeyPolicy } from './key-types.js';
1314
import type { KeyUsage } from './key-usage.js';
14-
import { keySettlements } from './key-settlement-candidates.js';
15-
16-
const RECOVERY_PAGE = 64;
1715

1816
type AccountingWitness = {
1917
pendingOwner: string | null;
@@ -45,13 +43,10 @@ type HeldAdmission = {
4543
};
4644

4745
export class KeyAccounting {
48-
private timer?: NodeJS.Timeout;
49-
private warned = false;
50-
private recoveryAfter = '0';
51-
private retrySweep = false;
5246
private readonly held = new Map<string, HeldSettlement>();
5347
private readonly admissions = new Map<string, HeldAdmission>();
5448
private readonly resets: KeyQuotaResets;
49+
private readonly recovery: KeySettlementRecovery;
5550
constructor(
5651
private store: Store,
5752
private usage: KeyUsage,
@@ -63,7 +58,23 @@ export class KeyAccounting {
6358
usage,
6459
(owner, key) => this.assertResettable(owner, key),
6560
(owner, key, run, total, status) => this.settle(key, owner, run, total, status),
66-
() => this.schedule(5000),
61+
() => this.recovery.request(),
62+
);
63+
this.recovery = new KeySettlementRecovery(
64+
store,
65+
[
66+
{ size: () => this.resets.waitingReadbacks, next: () => this.resets.recoverOne() },
67+
{ size: () => this.admissions.size, next: () => this.recoverAdmission() },
68+
{ size: () => this.held.size, next: () => this.recoverHeld() },
69+
],
70+
(r) =>
71+
this.settle(
72+
String(r.key_id),
73+
String(r.owner),
74+
String(r.run_id),
75+
Number(r.total_tokens),
76+
r.status as RunStatus,
77+
),
6778
);
6879
}
6980

@@ -114,7 +125,7 @@ export class KeyAccounting {
114125
): void {
115126
this.admissions.set(keyId, { owner, issue, publication });
116127
this.store.accountingReadbacks.add(issue.runId);
117-
this.schedule(5000);
128+
this.recovery.request();
118129
}
119130
private inspectAdmission(keyId: string, { owner, issue }: HeldAdmission) {
120131
const seen = issue.inspect();
@@ -129,18 +140,16 @@ export class KeyAccounting {
129140
}
130141
return 'unknown';
131142
}
132-
private recoverAdmissions(): void {
133-
for (let n = Math.min(this.admissions.size, RECOVERY_PAGE); n > 0; n--) {
134-
const [key, ticket] = this.admissions.entries().next().value!;
135-
const seen = this.inspectAdmission(key, ticket);
136-
this.admissions.delete(key);
137-
if (seen === 'unknown') this.admissions.set(key, ticket);
138-
else {
139-
this.store.accountingReadbacks.delete(ticket.issue.runId);
140-
// Publish only accounting, never rerun submission or enqueue from a readback timer.
141-
if (seen === 'committed') ticket.publication();
142-
else ticket.publication.discard();
143-
}
143+
private recoverAdmission(): void {
144+
const [key, ticket] = this.admissions.entries().next().value!;
145+
const seen = this.inspectAdmission(key, ticket);
146+
this.admissions.delete(key);
147+
if (seen === 'unknown') this.admissions.set(key, ticket);
148+
else {
149+
this.store.accountingReadbacks.delete(ticket.issue.runId);
150+
// Publish only accounting, never rerun submission or enqueue from a readback timer.
151+
if (seen === 'committed') ticket.publication();
152+
else ticket.publication.discard();
144153
}
145154
}
146155
begin(...args: Parameters<KeyAccounting['stage']>): void {
@@ -188,11 +197,11 @@ export class KeyAccounting {
188197
.get(run, owner, keyId);
189198
} catch {
190199
// The durable admission journal can be retried once storage is readable.
191-
this.requestSweep();
200+
this.recovery.request();
192201
return;
193202
}
194203
if (!pending) throw error;
195-
this.requestSweep();
204+
this.recovery.request();
196205
}
197206
}
198207
private requireSettled(keyId: string, owner?: string) {
@@ -321,60 +330,28 @@ export class KeyAccounting {
321330
const issue = new UnconfirmedRunCommit(run);
322331
this.held.set(keyId, { ...ticket, issue });
323332
this.store.accountingReadbacks.add(run);
324-
this.schedule(5000);
333+
this.recovery.request();
325334
throw issue;
326335
}
327336
publish!();
328337
}
329338
recover(): void {
330-
let pendingResets = false;
331-
try {
332-
pendingResets = this.resets.recover();
333-
this.recoverAdmissions();
334-
for (let n = Math.min(this.held.size, RECOVERY_PAGE); n > 0; n--) {
335-
const [key, ticket] = this.held.entries().next().value!;
336-
const seen = this.inspect(ticket);
337-
this.held.delete(key);
338-
if (seen === 'absent') this.usage.discardStage(key, ticket.run);
339-
if (seen === 'unknown') this.held.set(key, ticket);
340-
else if (seen === 'absent' && ticket.prior.pendingKey === null) {
341-
try {
342-
this.settle(key, ticket.owner, ticket.run, ticket.total, ticket.status);
343-
} catch {
344-
if (!this.held.has(key)) this.held.set(key, ticket);
345-
}
346-
}
347-
if (!this.held.has(key)) this.store.accountingReadbacks.delete(ticket.run);
348-
}
349-
// Only admissions in the journal are recoverable. Never estimate old, possibly reset usage.
350-
const rows = keySettlements(this.store, this.recoveryAfter, RECOVERY_PAGE);
351-
for (const r of rows) {
352-
try {
353-
this.settle(
354-
String(r.key_id),
355-
String(r.owner),
356-
String(r.run_id),
357-
Number(r.total_tokens),
358-
r.status as RunStatus,
359-
);
360-
} catch {
361-
this.retrySweep = true;
362-
}
363-
}
364-
// Visit later rows before retrying a page that could not settle.
365-
if (rows.length === RECOVERY_PAGE) {
366-
this.recoveryAfter = String(rows.at(-1)!.recovery_ordinal);
367-
this.schedule(0);
368-
return;
339+
this.recovery.recover();
340+
}
341+
private recoverHeld(): void {
342+
const [key, ticket] = this.held.entries().next().value!;
343+
const seen = this.inspect(ticket);
344+
this.held.delete(key);
345+
if (seen === 'absent') this.usage.discardStage(key, ticket.run);
346+
if (seen === 'unknown') this.held.set(key, ticket);
347+
else if (seen === 'absent' && ticket.prior.pendingKey === null) {
348+
try {
349+
this.settle(key, ticket.owner, ticket.run, ticket.total, ticket.status);
350+
} catch {
351+
if (!this.held.has(key)) this.held.set(key, ticket);
369352
}
370-
} catch {
371-
this.retrySweep = true;
372353
}
373-
this.recoveryAfter = '0';
374-
if (this.retrySweep || this.held.size || this.admissions.size || pendingResets)
375-
this.schedule(5000);
376-
else this.warned = false;
377-
this.retrySweep = false;
354+
if (!this.held.has(key)) this.store.accountingReadbacks.delete(ticket.run);
378355
}
379356
assertResettable(owner: string, keyId: string): void {
380357
this.requireSettled(keyId, owner);
@@ -389,29 +366,9 @@ export class KeyAccounting {
389366
stopResets(): void {
390367
this.resets.stop();
391368
}
392-
private requestSweep() {
393-
// A newly terminal run may be behind a page cursor while another sweep is already queued.
394-
if (this.recoveryAfter !== '0') this.retrySweep = true;
395-
this.schedule(5000);
396-
}
397-
private schedule(delay: number) {
398-
if (this.timer) return;
399-
if (delay && !this.warned) {
400-
this.warned = true;
401-
process.emitWarning(
402-
'Run accounting could not be confirmed; pending writes will be checked again.',
403-
'OAASettlement',
404-
);
405-
}
406-
this.timer = setTimeout(() => {
407-
this.timer = undefined;
408-
this.recover();
409-
}, delay).unref();
410-
}
411369
close() {
412370
this.stopResets();
413-
clearTimeout(this.timer);
414-
this.timer = undefined;
371+
this.recovery.close();
415372
for (const ticket of this.held.values()) this.store.accountingReadbacks.delete(ticket.run);
416373
this.held.clear();
417374
for (const ticket of this.admissions.values())

‎src/gateway/key-quota-resets.ts‎

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import type { UsagePublication } from '../kernel/types.js';
66
import { isWriteContended } from '../store/checkpoint.js';
77
import { runSqliteWrite } from '../store/sqlite-write.js';
88
import type { Store } from '../store/store.js';
9+
import { withoutSqliteBusyWait } from '../store/write-lock.js';
910
import { keySettlementsForKey } from './key-settlement-candidates.js';
1011
import type { KeyUsage, KeyUsageView } from './key-usage.js';
1112

@@ -84,9 +85,7 @@ export class KeyQuotaResets {
8485
private slice(reset: Reset, stage: StageQuota): boolean {
8586
const { db } = this.store;
8687
if (db.isTransaction) throw busy();
87-
const timeout = Number(db.prepare('PRAGMA busy_timeout').get()!.timeout);
88-
try {
89-
if (timeout) db.exec('PRAGMA busy_timeout=0');
88+
return withoutSqliteBusyWait(db, () => {
9089
this.assertSettled(reset.owner, reset.key);
9190
const end = performance.now() + 4;
9291
const rows = keySettlementsForKey(this.store, reset.owner, reset.key, PAGE);
@@ -102,9 +101,7 @@ export class KeyQuotaResets {
102101
if (performance.now() >= end) break;
103102
}
104103
return false;
105-
} finally {
106-
if (timeout) db.exec(`PRAGMA busy_timeout=${timeout}`);
107-
}
104+
});
108105
}
109106

110107
private readReceipt({ owner, key }: Reset): string | null {
@@ -193,22 +190,29 @@ export class KeyQuotaResets {
193190
return true;
194191
}
195192

196-
recover(): boolean {
197-
let pending = false;
193+
get waitingReadbacks(): number {
194+
let count = 0;
195+
for (const reset of this.active.values()) if (reset.ticket) count++;
196+
return count;
197+
}
198+
199+
recoverOne(): void {
198200
for (const reset of this.active.values()) {
199201
const { ticket } = reset;
200202
if (!ticket) continue;
201203
const result = this.inspect(reset, ticket);
202-
if (result === 'unknown') pending = true;
203-
else {
204+
if (result === 'unknown') {
205+
this.active.delete(reset.key);
206+
this.active.set(reset.key, reset);
207+
} else {
204208
if (result === 'committed') {
205209
ticket.usage();
206210
ticket.publish();
207211
} else ticket.usage.discard();
208212
this.active.delete(reset.key);
209213
}
214+
return;
210215
}
211-
return pending;
212216
}
213217

214218
stop(): void {

‎src/gateway/key-settlement-candidates.ts‎

Lines changed: 28 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -61,15 +61,35 @@ type Catalog = { prepare(sql: string): StatementSync };
6161

6262
// Sorting a sparse set is cheap. On a large backlog, keep seeking in journal order
6363
// instead of making every page scan and sort the whole terminal set again.
64-
export function keySettlements(store: Catalog, after: string, size: number) {
64+
export function keySettlementCeiling(store: Catalog): string | null {
65+
const row = store
66+
.prepare('SELECT CAST(max(rowid) AS TEXT) AS bound FROM api_key_pending_runs')
67+
.get();
68+
return row?.bound == null ? null : String(row.bound);
69+
}
70+
71+
export function hasKeySettlements(store: Catalog): boolean {
72+
return !!store.prepare(`SELECT 1 FROM ${ready} LIMIT 1`).get();
73+
}
74+
75+
export function keySettlements(
76+
store: Catalog,
77+
after: string | null,
78+
size: number,
79+
through?: string,
80+
) {
6581
const dense = store.prepare(`SELECT 1 FROM ${ready} LIMIT 1 OFFSET ?`).get(size * 4);
66-
return store
67-
.prepare(
68-
dense
69-
? journal + ' AND p.rowid>CAST(? AS INTEGER) ORDER BY p.rowid LIMIT ?'
70-
: pendingKeySettlementPage,
71-
)
72-
.all(after, size);
82+
let sql = dense ? journal : candidates;
83+
const args: string[] = [];
84+
if (after !== null) {
85+
sql += ' AND p.rowid>CAST(? AS INTEGER)';
86+
args.push(after);
87+
}
88+
if (through !== undefined) {
89+
sql += ' AND p.rowid<=CAST(? AS INTEGER)';
90+
args.push(through);
91+
}
92+
return store.prepare(sql + ' ORDER BY p.rowid LIMIT ?').all(...args, size);
7393
}
7494

7595
export function keySettlementsForKey(store: Catalog, owner: string, keyId: string, size: number) {

0 commit comments

Comments
 (0)