Skip to content

Commit 1c2b936

Browse files
author
hzq
committed
Deliver verified terminal events after lost commit acknowledgements
Reconcile the original checkpoint before waking waiters, streams and downstream consumers. Distinguish provable rollback from an unreadable outcome without repeating execution or settling unconfirmed usage.
1 parent bc9911d commit 1c2b936

21 files changed

Lines changed: 860 additions & 102 deletions

‎docs/stability.md‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -243,6 +243,17 @@ output that never reached storage is not reported as successful. An unconfirmed
243243
requires reconciliation. On shutdown, recovery uses the last committed state. A responding
244244
`/health` is not proof that new writes will succeed. These retries do not repair a corrupt database.
245245

246+
If SQLite committed a run's terminal state but lost the acknowledgement, the gateway checks
247+
the exact run, summary, terminal event batch and affected steps/approvals before publishing
248+
the original event IDs and wakeups. A waiting POST or SSE connection need not wait for a
249+
second event. A proven rollback may retry the local checkpoint only, never the producer.
250+
For an unreadable or conflicting witness, waiters receive `409 effect_outcome_unknown` with
251+
the run ID; an already-open stream ends with an observation error, not a success frame or a
252+
new replay cursor. The authorized `GET /v1/runs/:id` diagnostic still exposes the stored
253+
facts with `terminal_commit_confirmed: false`. The live gateway rechecks without rewriting
254+
the outcome or settling unconfirmed usage. A missing event alone does not prove rollback:
255+
its [SQLite AUTOINCREMENT](https://www.sqlite.org/autoinc.html) allocation may already be durable.
256+
246257
New HTTP run submissions (including media jobs and workflow drafts) wait for SQLite's writer
247258
without blocking the gateway. The wait is at most the connection timeout or five seconds,
248259
whichever is shorter. One FIFO admits at most eight waiting requests per owner and 64 in total;

‎docs/zh-CN/stability.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,8 @@ npm run soak -- --minutes 30 --concurrency 8 --retention-minutes 5 [--dir DIR] [
117117
`OAA_CHECKPOINT_RETRY` 表示正在等待本地写入,不是重跑模型或工具。已经落盘的输出可以正常完成;未能保存的输出不会被报告为成功。
118118
外部操作的结果无法确认时,仍需人工核对。关机后从最近一次已提交的状态恢复。`/health` 能响应不代表可以接受新的写入,重试也不会修复已损坏的数据库。
119119

120+
如果 SQLite 已提交终态但确认丢失,网关核对运行、摘要、原事件批次以及受影响的步骤和审批记录,再用原事件 ID 唤醒等待的 POST、SSE 和订阅者,不补写第二个事件。只有能证明回滚才重试本地检查点,不重跑模型或工具。证据不可读或矛盾时,等待者收到带运行 ID 的 `409 effect_outcome_unknown`;已打开的流以观察错误结束,不伪造成功帧或游标。授权的 `GET /v1/runs/:id` 仍可查看已存事实,并标记 `terminal_commit_confirmed: false`。网关在本次进程内继续只读核对,未确认前不结算用量。缺少某行事件本身不能证明事务回滚。
121+
120122
通过 HTTP 创建运行时(包括媒体任务和工作流草稿),网关异步等写锁,不让整个事件循环停下来。等待时间不超过连接超时和 5 秒中的较短者。
121123
等待队列先进先出,每个 owner 最多 8 个请求,全网关最多 64 个;请求体另按每个 owner 32 MiB、全网关 64 MiB 限制。
122124
超时或排满返回 `503 admission_busy` 和 `Retry-After: 1`,不创建任务或预占用量。已有结果的幂等重放不等写锁。

‎src/gateway/compat-stream.ts‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ import {
2929
} from './bridge.js';
3030
import { Fault } from '../core/util.js';
3131
import { isTerminalEvent } from '../core/events.js';
32+
import { terminalNotice } from '../store/terminal-publication.js';
3233
import {
3334
chatFinish,
3435
claudeErrorType,
@@ -73,6 +74,11 @@ export function streamEvents(
7374
} = {},
7475
): void {
7576
const release = options.release ?? streamSlots(store).acquire(req.principal);
77+
const issue = store.terminalPublications.issue(runId);
78+
if (issue) {
79+
release();
80+
throw issue;
81+
}
7682
const needsInitial =
7783
mode === 'chat' ||
7884
mode === 'claude' ||
@@ -193,6 +199,28 @@ export function streamEvents(
193199
let roleSent = false;
194200
let seenTerminal = false;
195201
const { close, write } = stream;
202+
// This is an observation error, not a durable run event. Never invent a cursor or a success frame.
203+
const onUnconfirmed = (fault: Fault) => {
204+
const error = { code: fault.code, message: fault.message, run_id: runId };
205+
if (mode === 'gemini') {
206+
writeGemini(
207+
JSON.stringify({
208+
error: { code: fault.status, status: geminiStatus(fault.status), message: fault.message },
209+
}),
210+
);
211+
if (jsonArray) write(']');
212+
} else if (isNdjson) write(JSON.stringify({ t: 'error', error }) + '\n');
213+
else if (mode === 'chat') write('data: ' + JSON.stringify({ error }) + '\n\n');
214+
else
215+
write(
216+
'event: error\ndata: ' +
217+
JSON.stringify({ type: 'error', error: { ...error, type: 'api_error' } }) +
218+
'\n\n',
219+
);
220+
close();
221+
};
222+
store.events.on(terminalNotice(runId), onUnconfirmed);
223+
stream.onClose(() => store.events.off(terminalNotice(runId), onUnconfirmed));
196224

197225
const writeUapFrame = (type: string, seq: number, payload: Record<string, unknown>) => {
198226
const json = JSON.stringify({ t: type, seq, ...payload });

‎src/gateway/protocol-routes.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,11 @@ export function registerProtocolRoutes(app: FastifyInstance, deps: ProtocolRoute
114114
if (invocation.images?.length) await releaseImageInputs(store, invocation);
115115
}
116116
reply.header('X-Run-ID', run.id);
117+
const uncertain = store.terminalPublications.issue(run.id);
118+
if (uncertain) {
119+
release?.();
120+
throw uncertain;
121+
}
117122
if (responseDialect === 'uap') reply.header('X-UAP-Version', '1.0');
118123
const toolsMode = clientToolsHeader(run);
119124
if (toolsMode) reply.header('X-OAA-Client-Tools', toolsMode);

‎src/gateway/run-routes.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -200,6 +200,7 @@ export function registerRunRoutes(app: FastifyInstance, context: RunRouteContext
200200
// `starting_after` 时服务端也跳过不大于它的帧。
201201
app.get('/v1/responses/:id', async (req, reply) => {
202202
const run = ownedRun(req);
203+
store.terminalPublications.requireConfirmed(run.id);
203204
const q = responseQuery.parse(req.query);
204205
if (q.stream !== 'true') return responseObject(run);
205206
streamEvents(req, reply, store, auth, run.id, 0, 'responses', false, run, {
@@ -213,6 +214,7 @@ export function registerRunRoutes(app: FastifyInstance, context: RunRouteContext
213214
return {
214215
response: responseObject(run),
215216
status: run.status,
217+
...(store.terminalPublications.issue(run.id) ? { terminal_commit_confirmed: false } : {}),
216218
error: run.error,
217219
route: run.route,
218220
steps: store.steps(run.id),

‎src/kernel/admission.ts‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import type { Run } from '../core/contracts.js';
66
import type { Store } from '../store/store.js';
77
import { WebhookCaptureUnavailable } from '../store/checkpoint.js';
8+
import { PendingTerminalCommit } from '../store/terminal-publication.js';
89
import type { NodeHub } from '../fabric/network.js';
910
import { responseObject } from './response-object.js';
1011
import * as clientTools from './client-tools.js';
@@ -229,17 +230,30 @@ export class Admission {
229230
this.clearParked(run.id);
230231
this.queue = this.queue.filter((id) => id !== run.id);
231232
},
233+
() => this.rt.releaseRun(run),
232234
);
233-
this.rt.releaseRun(run);
234235
}
235236
scheduleParked(runId: string): boolean {
236237
if (this.rt.closing() || this.tasks.has(runId) || !this.parked.has(runId)) return true;
237238
if (this.retrying.get(runId)) return false;
238239
try {
240+
const pending = this.rt.store.terminalPublications.issue(runId);
241+
if (pending) throw pending;
239242
this.checkParked(runId);
240243
this.retrying.delete(runId);
241244
return true;
242245
} catch (error) {
246+
if (error instanceof PendingTerminalCommit) {
247+
this.retrying.set(runId, true);
248+
void error.settlement.then((state) => {
249+
this.retrying.delete(runId);
250+
if (state === 'absent' && !this.rt.closing() && this.parked.has(runId)) {
251+
this.scheduleParked(runId);
252+
this.pump();
253+
}
254+
});
255+
return false;
256+
}
243257
if (
244258
!(
245259
error instanceof WebhookCaptureUnavailable ||

‎src/kernel/kernel.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -220,9 +220,14 @@ export class Kernel {
220220
async close(): Promise<void> {
221221
this.closing = true;
222222
this.store.fileWriter.stopCheckpoints();
223+
this.store.terminalPublications.stop();
223224
for (const c of this.controllers.values()) c.abort();
224225
await Promise.allSettled(this.admission.tasks.values());
225226
for (const runId of this.admission.parked.keys()) {
227+
if (this.store.terminalPublications.issue(runId)) {
228+
this.admission.clearParked(runId);
229+
continue;
230+
}
226231
const run = this.store.run(runId);
227232
if (run.status === 'requires_action' && !keepParkedOnRestart(this.store, run)) {
228233
try {

‎src/kernel/lifecycle.ts‎

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import type { Principal, Run } from '../core/contracts.js';
33
import { terminal, visibleSubject } from '../core/contracts.js';
44
import { responseObject } from './response-object.js';
55
import { Fault } from '../core/util.js';
6+
import { terminalNotice } from '../store/terminal-publication.js';
67
import { isTerminalEvent } from '../core/events.js';
78
import type { KernelRuntime } from './runtime.js';
89
import { authorize, checkProviderKey } from './submission.js';
@@ -40,11 +41,17 @@ export function finishOrphan(rt: KernelRuntime, run: Run, unlinked = false): voi
4041
: 'The parent run is no longer active; this queued sub-agent run was not started.',
4142
};
4243
delete run.checkpoint.suspension;
43-
rt.store.checkpointActions(run, 'expire', [], (view) => ({
44-
type: 'response.cancelled',
45-
data: { response: responseObject(view) },
46-
}));
47-
releaseRun(rt, run);
44+
rt.store.checkpointActions(
45+
run,
46+
'expire',
47+
[],
48+
(view) => ({
49+
type: 'response.cancelled',
50+
data: { response: responseObject(view) },
51+
}),
52+
undefined,
53+
() => releaseRun(rt, run),
54+
);
4855
}
4956
export function releaseRun(rt: KernelRuntime, run: Run): void {
5057
if (run.status === 'completed') rememberProjectResult(rt.store, run);
@@ -89,6 +96,7 @@ export function forgetProviderKey(rt: KernelRuntime, runId: string, status: Run[
8996
export async function cancel(rt: KernelRuntime, principal: Principal, runId: string): Promise<Run> {
9097
const run = rt.store.run(runId, principal.owner, visibleSubject(principal));
9198
authorize(principal, run.agentId, 'invoke');
99+
rt.store.terminalPublications.requireConfirmed(runId);
92100
if (terminal(run.status)) return run;
93101
if (run.status === 'queued') {
94102
rt.admission.finishParked(run, 'cancelled');
@@ -125,6 +133,7 @@ export function resume(
125133
): Run {
126134
const run = rt.store.run(runId, principal.owner, visibleSubject(principal));
127135
authorize(principal, run.agentId, 'invoke');
136+
rt.store.terminalPublications.requireConfirmed(runId);
128137
if (run.status !== 'interrupted')
129138
throw new Fault('not_resumable', 'Only interrupted responses can be resumed.', 409);
130139
if (providerKey !== undefined) {
@@ -231,11 +240,14 @@ export async function wait(
231240
return new Promise<Run>((resolve, reject) => {
232241
const cleanup = () => {
233242
rt.store.events.off(runId, onEvent);
243+
rt.store.events.off(terminalNotice(runId), onUnconfirmed);
234244
rt.shutdown.signal.removeEventListener('abort', onClose);
235245
signal?.removeEventListener('abort', onAbort);
236246
};
237247
const check = () => {
238248
try {
249+
const issue = rt.store.terminalPublications.issue(runId);
250+
if (issue) return onUnconfirmed(issue);
239251
const run = rt.store.run(runId);
240252
if (terminal(run.status) || (includeActions && run.status === 'requires_action')) {
241253
cleanup();
@@ -254,6 +266,10 @@ export async function wait(
254266
cleanup();
255267
reject(new Fault('shutting_down', 'Gateway is shutting down.', 503));
256268
};
269+
const onUnconfirmed = (fault: Fault) => {
270+
cleanup();
271+
reject(fault);
272+
};
257273
const onAbort = () => {
258274
cleanup();
259275
reject(
@@ -267,6 +283,7 @@ export async function wait(
267283
);
268284
};
269285
rt.store.events.on(runId, onEvent);
286+
rt.store.events.on(terminalNotice(runId), onUnconfirmed);
270287
rt.shutdown.signal.addEventListener('abort', onClose, { once: true });
271288
signal?.addEventListener('abort', onAbort, { once: true });
272289
if (rt.shutdown.signal.aborted) onClose();

‎src/kernel/terminal-checkpoint.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { terminal, type Run } from '../core/contracts.js';
22
import { sleep } from '../core/util.js';
33
import { isWriteContended, isWriteUnavailable } from '../store/checkpoint.js';
4+
import { PendingTerminalCommit } from '../store/terminal-publication.js';
45
import type { KernelRuntime } from './runtime.js';
56

67
/** Retry local persistence, never the model, tool or scheduler that produced the outcome. */
@@ -16,6 +17,7 @@ export async function commitTerminal(
1617
let lockDelay = 20;
1718
for (;;) {
1819
try {
20+
rt.store.terminalPublications.requireConfirmed(run.id);
1921
if (retry) {
2022
// A storage error may have been reported after the commit became durable.
2123
const saved = rt.store.run(run.id);
@@ -27,6 +29,15 @@ export async function commitTerminal(
2729
write(sawStorageOutage);
2830
return true;
2931
} catch (error) {
32+
if (error instanceof PendingTerminalCommit) {
33+
const state = await error.settlement;
34+
if (state === 'committed') return true;
35+
if (state === 'stopped' || rt.closing()) return false;
36+
// Only an independently proved rollback permits another local terminal write.
37+
sawStorageOutage = true;
38+
retry = false;
39+
continue;
40+
}
3041
if (!unavailable(error)) throw error;
3142
sawStorageOutage ||= isWriteUnavailable(error);
3243
if (rt.closing()) return false;

‎src/store/approval-rows.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,7 @@ export function changeApprovalRows(
9595
db: Db,
9696
run: { id: string; owner: string },
9797
actions: 'expire' | Approval[],
98+
evidence?: Map<string, string>,
9899
): Approval[] {
99100
if (actions === 'expire')
100101
return db
@@ -103,11 +104,17 @@ export function changeApprovalRows(
103104
WHERE run_id=? AND owner=? AND json_extract(payload,'$.status')='pending' RETURNING payload`,
104105
)
105106
.all(run.id, run.owner)
106-
.map((row) => JSON.parse(String(row.payload)));
107+
.map((row) => {
108+
const payload = String(row.payload),
109+
action = JSON.parse(payload) as Approval;
110+
evidence?.set(action.id, payload);
111+
return action;
112+
});
107113
for (const a of actions) {
108114
if (a.runId !== run.id || a.owner !== run.owner)
109115
throw new Fault('approval_not_found', 'Approval does not belong to this run.', 404);
110116
writeApprovalRow(db, a);
117+
evidence?.set(a.id, JSON.stringify(a));
111118
}
112119
return actions;
113120
}

0 commit comments

Comments
 (0)