Skip to content

Commit 756d3fa

Browse files
author
hzq
committed
Recover API key admission accounting online
Check the original run, creation event and key reservation after a lost commit acknowledgement. Publish or release accounting only on proof, without dispatching or resubmitting the run.
1 parent d25bdbe commit 756d3fa

10 files changed

Lines changed: 253 additions & 30 deletions

File tree

‎docs/operations.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -174,7 +174,7 @@ An unknown external write outcome blocks Resume. An authorized operator must exp
174174

175175
## Data retention and backups
176176

177-
Creating a run commits its initial event, key usage, any platform hold and its workflow stage link together. After a failed admission, retry with the same idempotency key. If a resume reservation fails, the original run stays interrupted and can be resumed again without consuming a new run. If only final accounting is delayed, the gateway retains the run and retries settlement, including at startup; it does not rerun the agent. An `OAASettlement` warning indicates a pending accounting write. Check storage health if it recurs.
177+
Creating a run commits its initial event, key usage, any platform hold and its workflow stage link together. After a confirmed admission failure, retry with the same idempotency key. For `effect_outcome_unknown`, check the original run ID instead of immediately retrying. The gateway rechecks admission accounting in the background without dispatching the run; a confirmed queued run can be cancelled by ID. If a resume reservation fails, the original run stays interrupted and can be resumed again without consuming a new run. If only final accounting is delayed, the gateway retains the run and retries settlement, including at startup; it does not rerun the agent. An `OAASettlement` warning indicates pending accounting. Check storage health if it recurs.
178178

179179
On `GET /metrics`, `oaa_run_outcomes_total{agent,status}` is the counter for completion and failure rates. It counts transitions into terminal states and survives history pruning and restarts. At first upgrade it starts from the terminal runs still retained, not already-deleted history. The older `oaa_runs_total`, `oaa_run_errors_total`, `oaa_run_tokens_total` and `oaa_tokens_total` series retain their names and snapshot values, but are gauges: do not apply `rate()` to them.
180180

‎docs/stability.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -509,7 +509,9 @@ An API key's in-memory active group is removed after its last run has a confirme
509509
Historical totals are read by key on demand, with at most 1,024 idle keys cached. Active or
510510
unconfirmed accounting is kept separately from this cache. An unconfirmed settlement still
511511
occupies its reservation. If admission cannot confirm its commit, the key keeps its last
512-
confirmed totals and rejects new accounting writes until a restart reloads durable state.
512+
confirmed totals and rejects new accounting writes while the gateway checks the original run,
513+
initial event and key reservation. A confirmed commit publishes accounting; a confirmed
514+
rollback unlocks the key without charging it. Readback never starts the run or resubmits it.
513515

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

‎src/gateway/auth.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,9 @@ export class Auth {
178178
stageKeyRun(...args: Parameters<KeyAccounting['stage']>) {
179179
return this.accounting.stage(...args);
180180
}
181+
holdKeyRun(...args: Parameters<KeyAccounting['holdAdmission']>) {
182+
this.accounting.holdAdmission(...args);
183+
}
181184
rejoinKeyRun(...args: Parameters<KeyAccounting['rejoin']>) {
182185
this.accounting.rejoin(...args);
183186
}

‎src/gateway/key-accounting.ts‎

Lines changed: 50 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { terminal, type RunStatus } from '../core/contracts.js';
33
import { Fault } from '../core/util.js';
44
import type { UsagePublication } from '../kernel/types.js';
55
import { isWriteUnavailable } from '../store/checkpoint.js';
6-
import { UnconfirmedRunCommit } from '../store/run-creation.js';
6+
import { UnconfirmedRunCommit, type UnconfirmedAdmissionCommit } from '../store/run-creation.js';
77
import { withSavepoint } from '../store/savepoint.js';
88
import type { Store } from '../store/store.js';
99
import type { AccountKeyPolicy } from './key-types.js';
@@ -38,13 +38,19 @@ type Settlement = {
3838
minimumTokens: number;
3939
};
4040
type HeldSettlement = Settlement & { issue: UnconfirmedRunCommit };
41+
type HeldAdmission = {
42+
owner: string;
43+
issue: UnconfirmedAdmissionCommit;
44+
publication: UsagePublication;
45+
};
4146

4247
export class KeyAccounting {
4348
private timer?: NodeJS.Timeout;
4449
private warned = false;
4550
private recoveryAfter = '0';
4651
private retrySweep = false;
4752
private readonly held = new Map<string, HeldSettlement>();
53+
private readonly admissions = new Map<string, HeldAdmission>();
4854
constructor(
4955
private store: Store,
5056
private usage: KeyUsage,
@@ -59,6 +65,43 @@ export class KeyAccounting {
5965
if (account && agent !== undefined) this.platform()?.beginRun(account, run, agent);
6066
return this.usage.stageBegin(keyId, owner, run);
6167
}
68+
holdAdmission(
69+
keyId: string,
70+
owner: string,
71+
issue: UnconfirmedAdmissionCommit,
72+
publication: UsagePublication,
73+
): void {
74+
this.admissions.set(keyId, { owner, issue, publication });
75+
this.store.accountingReadbacks.add(issue.runId);
76+
this.schedule(5000);
77+
}
78+
private inspectAdmission(keyId: string, { owner, issue }: HeldAdmission) {
79+
const seen = issue.inspect();
80+
if (seen === 'unknown') return seen;
81+
try {
82+
const row = this.store
83+
.prepare('SELECT owner,key_id FROM api_key_pending_runs WHERE run_id=?')
84+
.get(issue.runId);
85+
if (seen === 'committed' ? row?.owner === owner && row.key_id === keyId : !row) return seen;
86+
} catch {
87+
// A run and its key reservation must agree before publishing either outcome.
88+
}
89+
return 'unknown';
90+
}
91+
private recoverAdmissions(): void {
92+
for (let n = Math.min(this.admissions.size, RECOVERY_PAGE); n > 0; n--) {
93+
const [key, ticket] = this.admissions.entries().next().value!;
94+
const seen = this.inspectAdmission(key, ticket);
95+
this.admissions.delete(key);
96+
if (seen === 'unknown') this.admissions.set(key, ticket);
97+
else {
98+
this.store.accountingReadbacks.delete(ticket.issue.runId);
99+
// Publish only accounting, never rerun submission or enqueue from a readback timer.
100+
if (seen === 'committed') ticket.publication();
101+
else ticket.publication.discard();
102+
}
103+
}
104+
}
62105
begin(...args: Parameters<KeyAccounting['stage']>): void {
63106
let staged: UsagePublication | undefined;
64107
try {
@@ -232,6 +275,7 @@ export class KeyAccounting {
232275
}
233276
recover(): void {
234277
try {
278+
this.recoverAdmissions();
235279
for (let n = Math.min(this.held.size, RECOVERY_PAGE); n > 0; n--) {
236280
const [key, ticket] = this.held.entries().next().value!;
237281
const seen = this.inspect(ticket);
@@ -274,7 +318,7 @@ export class KeyAccounting {
274318
this.retrySweep = true;
275319
}
276320
this.recoveryAfter = '0';
277-
if (this.retrySweep || this.held.size) this.schedule(5000);
321+
if (this.retrySweep || this.held.size || this.admissions.size) this.schedule(5000);
278322
else this.warned = false;
279323
this.retrySweep = false;
280324
}
@@ -296,7 +340,7 @@ export class KeyAccounting {
296340
if (delay && !this.warned) {
297341
this.warned = true;
298342
process.emitWarning(
299-
'Run accounting could not commit; pending settlements will be retried.',
343+
'Run accounting could not be confirmed; pending writes will be checked again.',
300344
'OAASettlement',
301345
);
302346
}
@@ -310,5 +354,8 @@ export class KeyAccounting {
310354
this.timer = undefined;
311355
for (const ticket of this.held.values()) this.store.accountingReadbacks.delete(ticket.run);
312356
this.held.clear();
357+
for (const ticket of this.admissions.values())
358+
this.store.accountingReadbacks.delete(ticket.issue.runId);
359+
this.admissions.clear();
313360
}
314361
}

‎src/kernel/submission.ts‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,11 @@ import { asRoutingStrategy, resolveSemanticProfile } from './routing.js';
1919
import { Fault, canonical, faultOf, id, scopeDenied, sha } from '../core/util.js';
2020
import { LIMITS } from '../core/limits.js';
2121
import type { SubmissionOptions, UsagePublication } from './types.js';
22-
import { replayId, UnconfirmedRunCommit } from '../store/run-creation.js';
22+
import {
23+
replayId,
24+
UnconfirmedAdmissionCommit,
25+
UnconfirmedRunCommit,
26+
} from '../store/run-creation.js';
2327
import { agentFallbackChain, routeInspector, toTopologyHint } from './fallback.js';
2428
import { portableSessions, prepareRunHandoff } from './handoff.js';
2529
import type { KernelRuntime } from './runtime.js';
@@ -574,7 +578,10 @@ export function submit(
574578
delegate,
575579
);
576580
} catch (error) {
577-
if (!(error instanceof UnconfirmedRunCommit) && !rt.store.db.isTransaction) account?.discard();
581+
if (error instanceof UnconfirmedAdmissionCommit && account && principal.keyId)
582+
rt.auth()?.holdKeyRun(principal.keyId, principal.owner, error, account);
583+
else if (!(error instanceof UnconfirmedRunCommit) && !rt.store.db.isTransaction)
584+
account?.discard();
578585
throw error;
579586
}
580587
if (!created.created) linkStage?.(created.run);

‎src/kernel/types.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
/** 内核各模块共用的类型(只含类型)。kernel.ts 再导出其中对外的名字。 */
22
import type { Principal, Run, RunStatus } from '../core/contracts.js';
3-
import type { ParentStepStart } from '../store/run-creation.js';
3+
import type { ParentStepStart, UnconfirmedAdmissionCommit } from '../store/run-creation.js';
44
import type { RunWriteMode } from '../store/write-lock.js';
55
import type { ExecutionPool } from './execution-pool.js';
66

@@ -50,6 +50,12 @@ export type KernelAuth = {
5050
runId: string,
5151
agent?: string,
5252
): UsagePublication | undefined;
53+
holdKeyRun(
54+
keyId: string,
55+
owner: string,
56+
issue: UnconfirmedAdmissionCommit,
57+
staged: UsagePublication,
58+
): void;
5359
/** Throws when the run's own key may not continue it (see Auth.checkResume). */
5460
checkResume(
5561
p: Principal,

‎src/store/run-creation.ts‎

Lines changed: 83 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import type { DatabaseSync, StatementSync } from 'node:sqlite';
2-
import { LEGACY_SUBJECT, type ExecutionStep, type Run } from '../core/contracts.js';
2+
import { LEGACY_SUBJECT, type ExecutionStep, type Run, type RunEvent } from '../core/contracts.js';
33
import { Fault } from '../core/util.js';
44
import { bi } from '../core/locale.js';
55
import type { EventInput } from './output.js';
@@ -60,33 +60,102 @@ export class UnconfirmedRunCommit extends Fault {
6060
);
6161
}
6262
}
63-
/** An I/O failure can arrive after COMMIT. Only a confirmed row permits normal publication. */
63+
64+
export class UnconfirmedAdmissionCommit extends UnconfirmedRunCommit {
65+
constructor(
66+
runId: string,
67+
parentStep: ExecutionStep | undefined,
68+
readonly inspect: () => 'committed' | 'absent' | 'unknown',
69+
) {
70+
super(runId, parentStep);
71+
}
72+
}
73+
74+
const readAdmission = `SELECT r.owner,r.subject,e.run_id AS event_run,e.type,e.time,
75+
(SELECT seq FROM sqlite_sequence WHERE name='events') AS event_high_water
76+
FROM (SELECT 1)
77+
LEFT JOIN runs r ON r.id=$run
78+
LEFT JOIN events e ON e.id=$event`;
79+
80+
function admissionProof(
81+
store: Statements & { db: DatabaseSync },
82+
run: string,
83+
owner: string,
84+
subject: string,
85+
event: number,
86+
type: string,
87+
time: number,
88+
): UnconfirmedAdmissionCommit['inspect'] {
89+
return () => {
90+
if (store.db.isTransaction) return 'unknown';
91+
try {
92+
const row = store.prepare(readAdmission).get({ run, event })!;
93+
if (
94+
row.owner === owner &&
95+
row.subject === subject &&
96+
row.event_run === run &&
97+
row.type === type &&
98+
row.time === time
99+
)
100+
return 'committed';
101+
// A rolled-back event ID can be reused, but a committed ID cannot. A missing
102+
// ID below the high-water mark is not proof of rollback (it may have been deleted).
103+
const highWater = row.event_high_water;
104+
const reused = typeof row.event_run === 'string' && row.event_run !== run;
105+
const notReached =
106+
highWater === null ||
107+
(typeof highWater === 'number' &&
108+
Number.isSafeInteger(highWater) &&
109+
highWater >= 0 &&
110+
highWater < event);
111+
if (row.owner === null && (reused || (row.event_run === null && notReached))) return 'absent';
112+
} catch {
113+
// Unreadable evidence is not proof of either outcome.
114+
}
115+
return 'unknown';
116+
};
117+
}
118+
119+
/** An I/O failure can arrive after COMMIT. Only confirmed evidence permits publication. */
64120
export function commitNewRun(
65121
store: Statements & { db: DatabaseSync },
66122
run: Run,
67123
parent?: ParentStepStart,
124+
event?: RunEvent,
68125
) {
69126
try {
70127
store.db.exec('COMMIT');
71128
} catch (error) {
72129
if (store.db.isTransaction || !isWriteUnavailable(error)) throw error;
130+
const step: ExecutionStep | undefined = parent && {
131+
...parent.step,
132+
childRunId: run.id,
133+
status: 'uncertain',
134+
error: 'effect_outcome_unknown',
135+
};
136+
const subject = run.subject ?? LEGACY_SUBJECT;
137+
if (event) {
138+
const inspect = admissionProof(
139+
store,
140+
run.id,
141+
run.owner,
142+
subject,
143+
event.id,
144+
event.type,
145+
event.time,
146+
);
147+
const seen = inspect();
148+
if (seen === 'committed') return;
149+
if (seen === 'absent') throw error;
150+
throw new UnconfirmedAdmissionCommit(run.id, step, inspect);
151+
}
73152
let saved;
74153
try {
75154
saved = store
76155
.prepare('SELECT 1 FROM runs WHERE id=? AND owner=? AND subject=?')
77-
.get(run.id, run.owner, run.subject ?? LEGACY_SUBJECT);
156+
.get(run.id, run.owner, subject);
78157
} catch {
79-
throw new UnconfirmedRunCommit(
80-
run.id,
81-
parent
82-
? {
83-
...parent.step,
84-
childRunId: run.id,
85-
status: 'uncertain',
86-
error: 'effect_outcome_unknown',
87-
}
88-
: undefined,
89-
);
158+
throw new UnconfirmedRunCommit(run.id, step);
90159
}
91160
if (!saved) throw error;
92161
}

‎src/store/store.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -512,7 +512,7 @@ export class Store {
512512
);
513513
const event = initial ? this.insertEvent(run.id, initial) : undefined;
514514
const publishAdmission = stageAdmission?.();
515-
commitNewRun(this, run, parentStart);
515+
commitNewRun(this, run, parentStart, event);
516516
this.provisionalInputs.adopt(run.fileIds);
517517
publishAdmission?.();
518518
this.rememberOwner(run.id, run.owner);

‎test/admission-atomicity.test.ts‎

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,75 @@ test('failed admission commits neither the run nor key/ledger usage; retry of th
9090
}
9191
});
9292

93+
test('online readback releases a rolled-back admission only after proving it absent', async (t) => {
94+
const s = await setup();
95+
try {
96+
s.store.publish('owner', makeBundle(agent()));
97+
const key = s.auth.authenticate('Bearer ' + token).keyId!;
98+
const db = s.store.db;
99+
const exec = db.exec.bind(db);
100+
const prepare = s.store.prepare.bind(s.store);
101+
let armed = false;
102+
let lost = false;
103+
let readable = false;
104+
db.function('arm_admission', () => {
105+
if (!lost) armed = true;
106+
return 1;
107+
});
108+
db.exec(`CREATE TEMP TRIGGER arm_admission AFTER INSERT ON runs
109+
BEGIN SELECT arm_admission(); END`);
110+
t.mock.method(db, 'exec', (sql: string) => {
111+
if (!armed || sql !== 'COMMIT') return exec(sql);
112+
armed = false;
113+
lost = true;
114+
exec('ROLLBACK');
115+
throw Object.assign(new Error('fixture missing admission acknowledgement'), {
116+
code: 'ERR_SQLITE_ERROR',
117+
errcode: 10,
118+
});
119+
});
120+
t.mock.method(s.store, 'prepare', (sql: string) => {
121+
if (!readable && sql.includes(' AS event_high_water'))
122+
throw new Error('fixture cannot read admission');
123+
return prepare(sql);
124+
});
125+
const invoke = () =>
126+
s.request(
127+
'POST',
128+
'/v1/responses',
129+
{
130+
model: 'agent/test',
131+
input: 'fixture',
132+
},
133+
token,
134+
{ 'idempotency-key': 'rolled-back-admission' },
135+
);
136+
const first = await invoke();
137+
assert.equal(first.statusCode, 409, first.body);
138+
const id = first.json().error.run_id as string;
139+
assert.ok(s.store.accountingReadbacks.has(id));
140+
assert.equal(s.store.allRuns().length, 0);
141+
s.auth.accounting.recover();
142+
assert.ok(s.store.accountingReadbacks.has(id));
143+
assert.equal((await invoke()).statusCode, 409);
144+
assert.equal(s.driver.calls, 0);
145+
146+
readable = true;
147+
s.auth.accounting.recover();
148+
assert.ok(!s.store.accountingReadbacks.has(id));
149+
assert.deepEqual(s.auth.keyUsage(key), { usedRuns: 0, usedTokens: 0, activeRuns: 0 });
150+
assert.equal(s.driver.calls, 0, 'rollback proof does not retry the request');
151+
const retry = await invoke();
152+
assert.equal(retry.statusCode, 200, retry.body);
153+
assert.notEqual(retry.json().id, id);
154+
assert.equal((await invoke()).json().id, retry.json().id);
155+
assert.equal(s.driver.calls, 1);
156+
assert.deepEqual(s.auth.keyUsage(key), { usedRuns: 1, usedTokens: 15, activeRuns: 0 });
157+
} finally {
158+
await s.cleanup();
159+
}
160+
});
161+
93162
test('failed final accounting keeps its marker and survives a prune and restart without re-executing the model', async () => {
94163
const s = await setup();
95164
let next: Awaited<ReturnType<typeof createGateway>> | undefined;

0 commit comments

Comments
 (0)