Skip to content

Commit cc79e3d

Browse files
author
hzq
committed
Walk startup recovery snapshots in bounded pages
Batch run IDs without retaining checkpoints, quarantine unreadable snapshots, and preserve safe cancellation of orphaned delegated runs.
1 parent 8386d8b commit cc79e3d

11 files changed

Lines changed: 362 additions & 39 deletions

File tree

‎bench/recovery-scan.ts‎

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
import assert from 'node:assert/strict';
2+
import { mkdtemp, rm } from 'node:fs/promises';
3+
import { tmpdir } from 'node:os';
4+
import path from 'node:path';
5+
import { parseArgs } from 'node:util';
6+
import { Store } from '../src/store/store.js';
7+
8+
const { values } = parseArgs({
9+
options: {
10+
runs: { type: 'string', default: '768' },
11+
chars: { type: 'string', default: '98304' },
12+
mode: { type: 'string', default: 'bounded' },
13+
},
14+
});
15+
const runs = Number(values.runs);
16+
const chars = Number(values.chars);
17+
assert.ok(Number.isInteger(runs) && runs >= 1 && runs <= 4096);
18+
assert.ok(Number.isInteger(chars) && chars >= 1 && chars <= 190_000);
19+
assert.ok(values.mode === 'bounded' || values.mode === 'materialized');
20+
const gc = global.gc;
21+
assert.ok(gc, 'Run with node --expose-gc');
22+
const root = await mkdtemp(path.join(tmpdir(), 'oaa-recovery-scan-'));
23+
let store: Store | undefined;
24+
try {
25+
store = new Store(root);
26+
const db = store.db;
27+
const insert = db.prepare(
28+
'INSERT INTO runs(id,owner,agent_id,session_id,status,payload) VALUES(?,?,?,?,?,?)',
29+
);
30+
const baseline = db.prepare(
31+
'INSERT INTO run_output_baselines(run_id,cursor,payload) VALUES(?,0,?)',
32+
);
33+
const suffix = 'x'.repeat(chars);
34+
db.exec('BEGIN IMMEDIATE');
35+
for (let i = 0; i < runs; i++) {
36+
const id = 'fixture-' + i;
37+
insert.run(
38+
id,
39+
'owner',
40+
'agent/fixture',
41+
id,
42+
'queued',
43+
JSON.stringify({
44+
id,
45+
owner: 'owner',
46+
agentId: 'agent/fixture',
47+
sessionId: id,
48+
status: 'queued',
49+
digest: 'fixture',
50+
input: id + suffix,
51+
updatedAt: 0,
52+
route: { id: 'fixture', model: 'fixture' },
53+
metadata: {},
54+
fileIds: [],
55+
artifactIds: [],
56+
checkpoint: { messages: [{ role: 'user', content: id + suffix }] },
57+
}),
58+
);
59+
baseline.run(id, '[]');
60+
}
61+
db.exec('COMMIT');
62+
gc();
63+
const before = process.memoryUsage().heapUsed;
64+
const candidates =
65+
values.mode === 'materialized'
66+
? store.allRuns(['queued', 'requires_action'])
67+
: store.recoveryRuns(['queued', 'requires_action']);
68+
let visited = 0;
69+
let peak = 0;
70+
for (const run of candidates) {
71+
assert.equal(run.id, 'fixture-' + visited++);
72+
assert.equal(run.checkpoint.messages[0]!.content.length, run.id.length + chars);
73+
if (visited === 1 || visited === runs || visited % 64 === 0) {
74+
gc();
75+
peak = Math.max(peak, process.memoryUsage().heapUsed - before);
76+
assert.equal(run.input.length, run.id.length + chars);
77+
}
78+
}
79+
assert.equal(visited, runs);
80+
console.log(
81+
JSON.stringify({
82+
runs,
83+
chars,
84+
mode: values.mode,
85+
visited,
86+
sampled_post_gc_heap_delta_bytes: peak,
87+
}),
88+
);
89+
} finally {
90+
store?.close();
91+
await rm(root, { recursive: true, force: true });
92+
}

‎docs/stability.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -214,6 +214,15 @@ by 0.8 MB/min; after them, by 0.008 and 0.0 MB/min.
214214

215215
## 2. Crash recovery semantics
216216

217+
Startup walks recovery IDs in row order, 64 at a time with a fixed upper row ID.
218+
It loads one run snapshot at a time and does not keep a SQLite cursor open across recovery
219+
writes. Unreadable or mismatched snapshots remain in storage, are not dispatched, and do
220+
not prevent other runs from recovering. A scope-mismatched queued child can still be
221+
cancelled if the catalog proves it has no active parent link in scope. A database-wide read
222+
failure still aborts startup.
223+
`node --expose-gc dist/bench/recovery-scan.js --mode bounded` measures retained heap for
224+
the scan on a temporary catalog; `--mode materialized` runs the former bulk-load pattern.
225+
217226
What a run looks like after the gateway stops, by how it stopped:
218227

219228
| Run state at the stop | Graceful stop (SIGTERM, `oaa stop`) | Crash (SIGKILL, power loss) |

‎docs/zh-CN/stability.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,8 @@ npm run soak -- --minutes 30 --concurrency 8 --retention-minutes 5 [--dir DIR] [
9696

9797
## 2. 崩溃恢复语义
9898

99+
启动恢复按行序每批读取 64 个运行 ID,固定本轮行号上界,再逐个加载快照;恢复写入时不挂着 SQLite 读取游标。不可读或与目录归属不一致的快照不派发,其他运行仍可恢复。目录证据确认没有同作用域活跃父任务委托关系的排队子任务,仍可按原规则取消;其余异常快照保留原记录。数据库整体读失败仍会终止启动。`node --expose-gc dist/bench/recovery-scan.js --mode bounded` 在临时库测扫描保留的堆内存,`--mode materialized` 对照原来一次读完的方式。
100+
99101
网关停止后,运行呈现的状态取决于停止方式:
100102

101103
| 停止时的运行状态 | 正常停止(SIGTERM、`oaa stop`) | 崩溃(SIGKILL、断电) |

‎src/gateway/key-usage.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ export class KeyUsage {
3434
// 升级前的版本在运行中断时已经把它的累计 token 整体计入密钥:第一次建表时据此补记,
3535
// 这些运行之后恢复并结束,只再计差额。终态的运行不会再收尾,不需要补记。
3636
if (!seeded)
37-
for (const run of store.allRuns(['interrupted'])) {
37+
for (const run of store.recoveryRuns(['interrupted'])) {
3838
const keyId = run.checkpoint.keyId;
3939
const tokens = Math.max(0, Math.floor(run.usage?.total_tokens ?? 0));
4040
if (keyId && tokens > 0)

‎src/kernel/durability.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,8 @@ export function recoverDurable(
4545
resume: (principal: Principal, id: string) => Run,
4646
) {
4747
for (const id of recoveryCandidates(rt.store)) {
48-
const run = rt.store.run(id);
48+
const run = rt.store.recoveryRun(id);
49+
if (!run) continue;
4950
const policy = run.checkpoint.durability;
5051
if (!policy || run.status !== 'interrupted' || !isRecoveryCause(run.error?.code)) continue;
5152
let attempted = false;
@@ -96,8 +97,8 @@ export function recoverDurable(
9697
} catch (error) {
9798
const code = faultOf(error).code;
9899
if (!attempted && run.metadata['oaa.recovery'] === code) continue;
99-
const current = rt.store.run(id);
100-
if (current.status !== 'interrupted' || !current.checkpoint.durability) continue;
100+
const current = rt.store.recoveryRun(id);
101+
if (current?.status !== 'interrupted' || !current.checkpoint.durability) continue;
101102
if (attempted) current.checkpoint.durability.attempts++;
102103
current.metadata['oaa.recovery'] = code;
103104
rt.store.save(current);

‎src/kernel/lifecycle.ts‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,19 @@ import { recoveryNeedsReconciliation } from '../store/step-recovery.js';
1717

1818
export function start(rt: KernelRuntime): void {
1919
recoverDurable(rt, (principal, id) => resume(rt, principal, id, undefined, 'automatic'));
20-
for (const run of rt.store.allRuns(['queued', 'requires_action'])) {
20+
const cancelMismatchedChild = (run: Run) => {
21+
if (
22+
!run.metadata['oaa.parent_run_id'] ||
23+
rt.store.terminalPublications.issue(run.id) ||
24+
!registrationIsIntact(rt.store, run)
25+
)
26+
return false;
27+
const blocked = delegateRecoveryBlock(rt.store, run);
28+
if (!blocked) return false;
29+
finishOrphan(rt, run, blocked === 'unlinked');
30+
return true;
31+
};
32+
for (const run of rt.store.recoveryRuns(['queued', 'requires_action'], cancelMismatchedChild)) {
2133
if (
2234
rt.store.terminalPublications.issue(run.id) ||
2335
(run.status === 'queued' && !registrationIsIntact(rt.store, run))

‎src/store/output.ts‎

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,9 @@ export type Projection = {
1818
base: number;
1919
baseline: string;
2020
};
21+
const invalidOutput = () =>
22+
new Fault('invalid_output_event', 'Invalid output event transition.', 500);
23+
2124
export function replayOutput(
2225
db: { prepare(sql: string): StatementSync },
2326
runId: string,
@@ -31,6 +34,11 @@ export function replayOutput(
3134
let messages = JSON.parse(baseline) as OutputMessage[],
3235
cursor = base,
3336
updatedAt = 0;
37+
if (
38+
!Array.isArray(messages) ||
39+
messages.some((m) => !m || typeof m.id !== 'string' || typeof m.text !== 'string')
40+
)
41+
throw invalidOutput();
3442
for (const event of db
3543
.prepare(
3644
`SELECT id,type,time,payload FROM events WHERE run_id=? AND id>? AND type IN (${projectedTypesSql}) ORDER BY id`,
@@ -51,9 +59,10 @@ export const isOutputEvent = (type: string) =>
5159
// The durable stream is the source of truth for text, not a second mutable snapshot.
5260
export function projectOutput(messages: OutputMessage[], event: EventInput): OutputMessage[] {
5361
if (!isOutputEvent(event.type)) return messages;
54-
const invalid = () => new Fault('invalid_output_event', 'Invalid output event transition.', 500);
62+
if (!event.data || typeof event.data !== 'object' || Array.isArray(event.data))
63+
throw invalidOutput();
5564
const index = event.data.output_index;
56-
if (typeof index !== 'number' || !Number.isSafeInteger(index) || index < 0) throw invalid();
65+
if (typeof index !== 'number' || !Number.isSafeInteger(index) || index < 0) throw invalidOutput();
5766
const item = event.data.item as Record<string, unknown> | undefined;
5867
if (event.type === 'response.output_item.added') {
5968
if (
@@ -68,19 +77,19 @@ export function projectOutput(messages: OutputMessage[], event: EventInput): Out
6877
!Array.isArray(item.content) ||
6978
item.content.length !== 0
7079
)
71-
throw invalid();
80+
throw invalidOutput();
7281
return [...messages, { id: item.id, text: '', status: 'in_progress' }];
7382
}
7483
const message = messages[index];
75-
if (!message || (message.status && message.status !== 'in_progress')) throw invalid();
84+
if (!message || (message.status && message.status !== 'in_progress')) throw invalidOutput();
7685
let next: OutputMessage;
7786
if (event.type === 'response.output_text.delta') {
7887
if (
7988
event.data.item_id !== message.id ||
8089
event.data.content_index !== 0 ||
8190
typeof event.data.delta !== 'string'
8291
)
83-
throw invalid();
92+
throw invalidOutput();
8493
next = { ...message, text: message.text + event.data.delta, status: 'in_progress' };
8594
} else {
8695
const content = item?.content as { type?: unknown; text?: unknown }[] | undefined;
@@ -94,7 +103,7 @@ export function projectOutput(messages: OutputMessage[], event: EventInput): Out
94103
content[0]?.type !== 'output_text' ||
95104
content[0]?.text !== message.text
96105
)
97-
throw invalid();
106+
throw invalidOutput();
98107
next = { ...message, status: item!.status as 'completed' | 'incomplete' };
99108
}
100109
return messages.map((m, i) => (i === index ? next : m));

‎src/store/recovery-candidates.ts‎

Lines changed: 24 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import type { DatabaseSync, StatementSync } from 'node:sqlite';
2+
import type { RunStatus } from '../core/contracts.js';
23

34
const reasons = new Set(['gateway_restarted', 'shutting_down', 'cancelled']);
45
export const isRecoveryCause = (code?: string) => !!code && reasons.has(code);
@@ -10,21 +11,31 @@ export function indexRecoveryCandidates(db: DatabaseSync) {
1011
db.exec(`CREATE INDEX IF NOT EXISTS run_auto_recovery ON runs(status) WHERE ${recoverable}`);
1112
}
1213

13-
/** No live SQLite iterator spans a resume write. Requeued rows disappear from this index. */
14-
export function* recoveryCandidates(store: {
15-
prepare(sql: string): StatementSync;
16-
}): Generator<string> {
17-
let after: number | undefined;
18-
for (;;) {
19-
const rows = store
20-
.prepare(
21-
`SELECT rowid AS position,id FROM runs WHERE ${recoverable}
22-
${after === undefined ? '' : 'AND rowid>?'} ORDER BY rowid LIMIT 64`,
23-
)
24-
.all(...(after === undefined ? [] : [after]));
14+
type Reader = { prepare(sql: string): StatementSync };
15+
16+
/** Only IDs are batched. No live SQLite iterator spans a recovery write. */
17+
function* scanRunIds(store: Reader, where: string, args: readonly string[] = []) {
18+
const ceiling = store.prepare('SELECT CAST(max(rowid) AS TEXT) AS bound FROM runs').get()?.bound;
19+
if (ceiling == null) return;
20+
const last = BigInt(String(ceiling));
21+
let first = -(2n ** 63n);
22+
const page = store.prepare(
23+
`SELECT CAST(rowid AS TEXT) AS position,id FROM runs
24+
WHERE rowid BETWEEN ? AND ? AND (${where}) ORDER BY rowid LIMIT 64`,
25+
);
26+
while (first <= last) {
27+
const rows = page.all(first, last, ...args);
2528
if (!rows.length) return;
26-
after = Number(rows.at(-1)!.position);
29+
first = BigInt(String(rows.at(-1)!.position)) + 1n;
2730
for (const row of rows) yield String(row.id);
2831
if (rows.length < 64) return;
2932
}
3033
}
34+
35+
export function recoveryCandidates(store: Reader): Generator<string> {
36+
return scanRunIds(store, recoverable);
37+
}
38+
39+
export function startupRunIds(store: Reader, statuses: readonly RunStatus[]): Generator<string> {
40+
return scanRunIds(store, `status IN (${statuses.map(() => '?').join(',')})`, statuses);
41+
}

‎src/store/run-read.ts‎

Lines changed: 74 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import type { StatementSync } from 'node:sqlite';
1+
import type { SQLOutputValue, StatementSync } from 'node:sqlite';
22
import { LEGACY_SUBJECT, type Run } from '../core/contracts.js';
33
import { Fault } from '../core/util.js';
44
import type { Projection } from './output.js';
@@ -19,6 +19,77 @@ const scheduling = `SELECT r.owner,r.subject,r.agent_id,r.session_id,r.status,r.
1919
const queued = scheduling + "r.status='queued'",
2020
parked = scheduling + "r.status IN ('requires_action','queued')";
2121
type Scope = { owner?: string; subject?: string };
22+
const matchesIndexedRun = (run: Run, row: Record<string, SQLOutputValue>, id: string) =>
23+
run?.checkpoint &&
24+
Array.isArray(run.checkpoint.messages) &&
25+
run.metadata &&
26+
run.route &&
27+
typeof run.digest === 'string' &&
28+
run.id === id &&
29+
run.owner === row.owner &&
30+
run.status === row.status &&
31+
run.agentId === row.agent_id &&
32+
run.sessionId === row.session_id;
33+
const matchesSubject = (run: Run, subject: string) =>
34+
run.subject == null || run.subject === subject;
35+
36+
/** A mismatched subject is never returned as a recoverable run. The scheduler can
37+
* use the indexed subject only to retire a queued child with no scoped parent. */
38+
export function readRecoveryRun(
39+
store: Reader,
40+
id: string,
41+
project: Project,
42+
cancelMismatchedChild?: (run: Run) => boolean,
43+
): Run | undefined {
44+
const row = store
45+
.prepare('SELECT owner,subject,agent_id,session_id,status,payload FROM runs WHERE id=?')
46+
.get(id);
47+
if (!row) return;
48+
const subject = String(row.subject ?? LEGACY_SUBJECT);
49+
const quarantine = () => {
50+
store.terminalPublications.detachedRun(id);
51+
return undefined;
52+
};
53+
let run: Run;
54+
let wrongSubject: boolean;
55+
try {
56+
run = JSON.parse(String(row.payload)) as Run;
57+
if (
58+
!matchesIndexedRun(run, row, id) ||
59+
typeof run.metadata !== 'object' ||
60+
Array.isArray(run.metadata) ||
61+
Object.values(run.metadata).some((value) => typeof value !== 'string') ||
62+
typeof run.input !== 'string' ||
63+
typeof run.route.id !== 'string' ||
64+
typeof run.route.model !== 'string' ||
65+
!Array.isArray(run.fileIds) ||
66+
!Array.isArray(run.artifactIds) ||
67+
(run.checkpoint.keyId !== undefined && typeof run.checkpoint.keyId !== 'string') ||
68+
(run.checkpoint.parentStepId !== undefined &&
69+
typeof run.checkpoint.parentStepId !== 'string') ||
70+
(run.checkpoint.suspension && !Array.isArray(run.checkpoint.suspension.approvalIds))
71+
)
72+
return quarantine();
73+
wrongSubject = !matchesSubject(run, subject);
74+
if (wrongSubject && (!cancelMismatchedChild || run.status !== 'queued')) return quarantine();
75+
const projection = project(id, run.owner);
76+
run.subject = subject;
77+
run.output = projection.messages.map((m) => ({ ...m }));
78+
run.updatedAt = Math.max(run.updatedAt, projection.updatedAt);
79+
} catch (error) {
80+
if (
81+
error instanceof SyntaxError ||
82+
(error instanceof Fault &&
83+
(error.code === 'invalid_output_event' || error.code === 'run_not_found'))
84+
)
85+
return quarantine();
86+
throw error;
87+
}
88+
if (!wrongSubject) return run;
89+
if (!cancelMismatchedChild?.(run)) return quarantine();
90+
return undefined;
91+
}
92+
2293
export function readRun(store: Reader, id: string, project: Project, scope: Scope): Run;
2394
export function readRun(
2495
store: Reader,
@@ -63,17 +134,8 @@ export function readRun(
63134
const subject = String(row.subject ?? LEGACY_SUBJECT);
64135
if (
65136
admit &&
66-
(!run?.checkpoint ||
67-
!Array.isArray(run.checkpoint.messages) ||
68-
!run.metadata ||
69-
!run.route ||
70-
typeof run.digest !== 'string' ||
71-
run.id !== id ||
72-
run.owner !== row.owner ||
73-
run.status !== row.status ||
74-
run.agentId !== row.agent_id ||
75-
run.sessionId !== row.session_id ||
76-
(run.subject != null && run.subject !== subject) ||
137+
(!matchesIndexedRun(run, row, id) ||
138+
!matchesSubject(run, subject) ||
77139
typeof row.summary !== 'string')
78140
) {
79141
store.terminalPublications.detachedRun(id, boundary);

0 commit comments

Comments
 (0)