Skip to content

Commit cc94e8a

Browse files
author
hzq
committed
Confirm approval wakes before readmitting parked runs
Bind the return to the queue to the parked run, its decisions and its event. A lost SQLite acknowledgement can then be recovered without repeating an approval or dispatching a tool twice. Recheck eligibility before dispatch and let cancellation and unrelated requests proceed while SQLite is busy.
1 parent 1f3178d commit cc94e8a

21 files changed

Lines changed: 1139 additions & 130 deletions

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ English · [简体中文](CHANGELOG.zh-CN.md)
44

55
## Unreleased
66

7+
- An approved tool no longer stalls until timeout if SQLite commits its return to the queue but loses the acknowledgement. The gateway confirms the original wake before running the tool, without requesting approval again.
78
- Queued and readmitted runs now confirm the stored start event before dispatch. Waiting for SQLite no longer blocks the gateway or prevents cancelling an attached start.
89

910
## 0.0.71 (2026-11-23)

‎CHANGELOG.zh-CN.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
## 未发布
66

7+
- 工具获批后,如果 SQLite 已将任务放回队列但提交回执丢失,网关会核对原记录并继续执行,不再卡到超时,也不要求重新审批。
78
- 排队运行首次启动或重新入场时,确认启动事件已落盘才派发;等 SQLite 写锁不会阻塞网关,也不会妨碍取消正在等锁的任务。
89

910
## 0.0.71(2026-11-23)

‎docs/stability.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -322,6 +322,15 @@ response API reports `effect_outcome_unknown` with the run ID and the run inspec
322322
`run_start_confirmed: false`. An authorized cancellation stops dispatch without claiming
323323
that cancellation is durable. Shutdown leaves unstarted work in its durable queue.
324324

325+
When a parked approval is ready, the gateway queues the same run without holding an
326+
execution slot while waiting for SQLite. A lost acknowledgement is checked against the
327+
parked run, its authorizing decisions and the exact queue event. Until confirmed, the
328+
response API reports `effect_outcome_unknown` and the run inspector shows
329+
`approval_wake_confirmed: false`. Only the local queue write can be retried; it never
330+
repeats an approval or a tool call. On readmission the gateway checks for denial or
331+
expiry again before dispatch. New queue records retain the event and decision evidence
332+
across restart. This boundary begins after a decision has been saved.
333+
325334
Kernel model turns use the same writer queue. Before sending, the gateway records the
326335
attempt and verifies that the durable run and the request handed to the worker still
327336
match. Cancellation while waiting prevents that send. Once a valid answer is ready

‎docs/zh-CN/stability.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,8 @@ worker 已产出的文件共用同一个写锁探测器,按 owner 轮流取锁
141141

142142
排队运行首次启动或重新入场时也异步等写锁。网关先核对排队快照、摘要和事件位置,再写入 `response.in_progress`;确认新快照、摘要和这条启动事件后才派发。每次入场另有一个不对外返回的标记,即使 SQLite 在同一毫秒复用了回滚的事件 ID,也不会误认另一笔启动。重试同一次本地写入时标记不变。丢失提交回执会读回核实,不直接判运行失败;只有证实回滚才重写本地启动事务。暂时无法确认时,响应返回 `effect_outcome_unknown` 和运行 ID,运行检查接口标记 `run_start_confirmed: false`。此时有权限的取消可阻止派发,但不谎报取消已落盘。关停时尚未启动的任务保留在持久队列中。
143143

144+
审批一旦落盘,内核让原任务重新入队;等待 SQLite 写锁不占执行槽。若入队回执丢失,网关核对原来的暂停记录、授权决定和那一条排队事件。无法确认时,响应返回 `effect_outcome_unknown`,运行检查接口标记 `approval_wake_confirmed: false`。重试只写本地队列,不重做审批或工具调用。重新派发前还会检查其他待办是否被拒或过期。新写入的队列记录在重启后也会核对原事件和授权依据;这些保证从审批决定已保存之后开始。
145+
144146
流式文本单独提交。创建输出消息和追加文本增量时异步等写锁;确认事件 ID、顺序和内容落盘后才通知订阅者。丢回执只读回核对,证明已回滚才重写原批次,不会重调模型。文本追加或单独结束输出消息的提交无法确认时,响应返回 `effect_outcome_unknown`,运行检查接口标记 `output_checkpoint_confirmed: false`。取消后不再接收新文本,终态等待已接收的文本处理完毕;进程崩溃仍可能丢掉尚未落盘的文本。
145147

146148
等锁的文本计入运行原有的输出上限;大批增量每写至多 1,024 条就让出事件循环,不合并对外事件。进度、审批和调用方工具帧等待前面的文本,单个运行最多缓冲 64 帧,JSON 合计不超过 1 MiB。超出任一限制以 `node_backpressure` 停止生产者;已经登记、正在等人决定的审批不占这个预算。

‎src/core/contracts.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -312,7 +312,12 @@ export type Checkpoint = {
312312
continuationBrief?: string;
313313
offeredTools?: string[];
314314
deadlineAt?: number;
315-
suspension?: { kind: 'approval' | 'scheduling'; approvalIds: string[] };
315+
suspension?: {
316+
kind: 'approval' | 'scheduling';
317+
approvalIds: string[];
318+
/** Private evidence for a queued approval continuation, discarded on admission. */
319+
wake?: { receipt: string; event: number; time: number; approvalIds: string[]; digest: string };
320+
};
316321
grantedAgents?: string[];
317322
delegationDepth?: number;
318323
/** Step that owns this delegated child. Older checkpoints can be matched by the recorded child ID. */

‎src/gateway/run-routes.ts‎

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -215,15 +215,17 @@ export function registerRunRoutes(app: FastifyInstance, context: RunRouteContext
215215
return {
216216
response: responseObject(run),
217217
status: run.status,
218-
...(issue?.boundary === 'start'
219-
? { run_start_confirmed: false }
220-
: issue?.boundary === 'output'
221-
? { output_checkpoint_confirmed: false }
222-
: issue?.boundary === 'model'
223-
? { model_checkpoint_confirmed: false }
224-
: issue
225-
? { terminal_commit_confirmed: false }
226-
: {}),
218+
...(issue?.boundary === 'wake'
219+
? { approval_wake_confirmed: false }
220+
: issue?.boundary === 'start'
221+
? { run_start_confirmed: false }
222+
: issue?.boundary === 'output'
223+
? { output_checkpoint_confirmed: false }
224+
: issue?.boundary === 'model'
225+
? { model_checkpoint_confirmed: false }
226+
: issue
227+
? { terminal_commit_confirmed: false }
228+
: {}),
227229
error: run.error,
228230
route: run.route,
229231
steps: store.steps(run.id),

‎src/kernel/admission.ts‎

Lines changed: 66 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,11 @@ import { Fault } from '../core/util.js';
77
import type { Store } from '../store/store.js';
88
import { WebhookCaptureUnavailable, isWriteUnavailable } from '../store/checkpoint.js';
99
import { PendingTerminalCommit } from '../store/terminal-publication.js';
10+
import { parkedDecisions } from '../store/parked-decisions.js';
11+
import { ParkedWakes } from './parked-wakes.js';
1012
import type { NodeHub } from '../fabric/network.js';
1113
import { responseObject } from './response-object.js';
12-
import * as clientTools from './client-tools.js';
14+
import { parkedFailure } from './client-tools.js';
1315
import { estimateStart, type Sample } from './queue-estimate.js';
1416
import { terminalEventType } from './run-state.js';
1517
import type { KernelLimits, QueueInsight } from './types.js';
@@ -52,7 +54,31 @@ export class Admission {
5254
/** Stored-duration fallback per owner+agent, refreshed at most every 5 s. */
5355
private storedDurations = new Map<string, { at: number; sample: number[] }>();
5456
private runKeys = new Map<string, string>();
55-
constructor(private readonly rt: AdmissionRuntime) {}
57+
readonly wakes: ParkedWakes;
58+
constructor(private readonly rt: AdmissionRuntime) {
59+
this.wakes = new ParkedWakes(rt.store, {
60+
closing: () => rt.closing(),
61+
parked: (id) => this.parked.has(id),
62+
queued: (id) => {
63+
this.enqueue(id);
64+
setImmediate(() => {
65+
if (!rt.closing() && this.parked.has(id)) {
66+
this.scheduleParked(id);
67+
this.pump();
68+
}
69+
});
70+
},
71+
retry: (id, immediate) => this.retryParked(id, immediate ? 0 : 1000),
72+
cancelLocked: (run) =>
73+
this.finishParked(
74+
run,
75+
'cancelled',
76+
'cancelled',
77+
'Execution was cancelled while awaiting approval.',
78+
'owned',
79+
),
80+
});
81+
}
5682
/** 运行槽计数的不变量检查:违反时记数并发出进程警告(测试通过 stats().breaches 断言)。 */
5783
private checkSlots(): void {
5884
if (this.active >= 0 && this.active <= this.rt.limits.maxActiveRuns) return;
@@ -262,6 +288,7 @@ export class Admission {
262288
status: 'failed' | 'cancelled' | 'interrupted' | 'incomplete',
263289
code?: string,
264290
message?: string,
291+
writer?: 'owned' | 'try',
265292
): void {
266293
run.status = status;
267294
if (code && message) run.error = { code, message };
@@ -279,17 +306,18 @@ export class Admission {
279306
this.queue = this.queue.filter((id) => id !== run.id);
280307
},
281308
() => this.rt.releaseRun(run),
309+
writer,
282310
);
283311
}
284312
scheduleParked(runId: string): boolean {
285313
if (this.rt.closing() || this.tasks.has(runId) || !this.parked.has(runId)) return true;
286-
if (this.retrying.get(runId)) return false;
314+
if (this.retrying.get(runId) || this.wakes.has(runId)) return false;
287315
try {
288316
const pending = this.rt.store.terminalPublications.issue(runId);
289317
if (pending) throw pending;
290318
this.checkParked(runId);
291-
this.retrying.delete(runId);
292-
return true;
319+
if (this.retrying.get(runId) === false) this.retrying.delete(runId);
320+
return !this.wakes.has(runId) && !this.retrying.get(runId);
293321
} catch (error) {
294322
if (error instanceof PendingTerminalCommit) {
295323
this.retrying.set(runId, true);
@@ -316,72 +344,67 @@ export class Admission {
316344
'A parked decision could not be checkpointed; scheduling will retry.',
317345
'OAAParkedCheckpoint',
318346
);
319-
this.retrying.set(runId, true);
320-
clearTimeout(this.parked.get(runId));
321-
this.parked.set(
322-
runId,
323-
setTimeout(() => {
324-
this.retrying.set(runId, false);
325-
this.scheduleParked(runId);
326-
this.pump();
327-
}, 1000).unref(),
328-
);
347+
this.retryParked(runId, 1000);
329348
return false;
330349
}
331350
}
351+
private retryParked(runId: string, ms: number) {
352+
if (this.rt.closing() || !this.parked.has(runId)) return;
353+
clearTimeout(this.parked.get(runId));
354+
this.retrying.set(runId, true);
355+
this.parked.set(
356+
runId,
357+
setTimeout(() => {
358+
this.retrying.set(runId, false);
359+
this.scheduleParked(runId);
360+
this.pump();
361+
}, ms).unref(),
362+
);
363+
}
332364
private checkParked(runId: string): void {
333-
const run = this.rt.store.run(runId);
334-
const deadline = run.checkpoint.deadlineAt ?? Infinity;
335-
const now = Date.now();
336-
if (!['requires_action', 'queued'].includes(run.status)) {
365+
const run = this.rt.store.parkedRun(runId);
366+
if (!run) {
367+
this.rt.store.terminalPublications.requireConfirmed(runId);
337368
this.clearParked(runId);
338369
return;
339370
}
371+
const deadline = run.checkpoint.deadlineAt ?? Infinity;
372+
const now = Date.now();
340373
if (now >= deadline) {
341374
this.finishParked(
342375
run,
343376
'incomplete',
344377
'run_timeout',
345378
'The run deadline expired while waiting.',
379+
'try',
346380
);
347381
return;
348382
}
349383
let wakeAt = deadline;
350384
if (run.checkpoint.suspension) {
351-
const actions = run.checkpoint.suspension.approvalIds.map((id) =>
352-
this.rt.store.getApproval(id, run.owner),
353-
);
354-
if (actions.some((a) => a.status === 'denied')) {
355-
this.finishParked(
356-
run,
357-
'failed',
358-
'permission_denied',
359-
'The API owner denied a pending tool call.',
360-
);
361-
return;
362-
}
363-
if (
364-
actions.some(
365-
(a) => a.status === 'expired' || (a.status === 'pending' && now >= a.expiresAt),
366-
)
367-
) {
368-
this.finishParked(run, 'failed', ...clientTools.parkedExpiry(actions));
385+
const decisions = parkedDecisions(this.rt.store, run),
386+
actions = decisions.actions;
387+
const failure = parkedFailure(actions, now);
388+
if (failure) {
389+
this.finishParked(run, 'failed', ...failure, 'try');
369390
return;
370391
}
371392
if (run.status === 'requires_action' && actions.some((a) => a.status === 'approved')) {
372-
run.status = 'queued';
373-
this.rt.store.checkpoint(run, [
374-
{ type: 'run.queued', data: { reason: 'approval_resolved' } },
375-
]);
376-
if (!this.parked.has(runId)) return;
377-
this.enqueue(run.id);
393+
clearTimeout(this.parked.get(runId));
394+
this.parked.set(runId, undefined);
395+
this.wakes.begin(run, decisions);
396+
return;
378397
}
379398
wakeAt = Math.min(
380399
deadline,
381400
...actions.filter((a) => a.status === 'pending').map((a) => a.expiresAt),
382401
);
383402
}
384403
clearTimeout(this.parked.get(runId));
404+
if (!Number.isFinite(wakeAt)) {
405+
this.parked.set(runId, undefined);
406+
return;
407+
}
385408
this.parked.set(
386409
runId,
387410
setTimeout(

‎src/kernel/client-tools.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -414,8 +414,14 @@ export function abandonCallerTool(store: Store, run: Run, relayCallId: unknown):
414414
store.approval(action);
415415
}
416416

417-
/** 挂起的待办过期时运行结束用的错误码:调用方工具是 `client_tool_timeout`,其余照旧。 */
418-
export function parkedExpiry(actions: Approval[]): [string, string] {
417+
/** Apply the same decision policy while parked and immediately before a resumed dispatch. */
418+
export function parkedFailure(actions: Approval[], now: number): [string, string] | undefined {
419+
if (actions.some((a) => a.status === 'denied'))
420+
return ['permission_denied', 'The API owner denied a pending tool call.'];
421+
if (
422+
!actions.some((a) => a.status === 'expired' || (a.status === 'pending' && now >= a.expiresAt))
423+
)
424+
return;
419425
return actions.some(
420426
(a) => a.kind === 'client_tool' && (a.status === 'expired' || a.status === 'pending'),
421427
)

‎src/kernel/execute.ts‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,8 @@ import type { KernelRuntime } from './runtime.js';
3131
import type { ExecutionSlice } from './types.js';
3232
import { checkExecution } from './submission.js';
3333
import { autoApprove, awaitApproval } from './approvals.js';
34-
import { abandonCallerTool, awaitCallerTool } from './client-tools.js';
34+
import { abandonCallerTool, awaitCallerTool, parkedFailure } from './client-tools.js';
35+
import { parkedDecisions } from '../store/parked-decisions.js';
3536
import { nativeStepId } from './native-turn.js';
3637
import { runAgentPass } from './agent-pass.js';
3738
import { orchestrationMode, runOrchestration } from './orchestration.js';
@@ -226,6 +227,27 @@ export async function execute(rt: KernelRuntime, run: Run, bundle: AgentBundle):
226227
};
227228
try {
228229
rt.admission.starting.add(runId);
230+
const parked = {
231+
id: runId,
232+
owner: run.owner,
233+
checkpoint: { suspension: run.checkpoint.suspension, deadlineAt },
234+
};
235+
const eligible =
236+
parked.checkpoint.suspension?.kind === 'approval'
237+
? () => {
238+
if (Date.now() >= deadlineAt) throw new ElapsedRunDeadline();
239+
const { actions } = parkedDecisions(rt.store, parked);
240+
const failure = parkedFailure(actions, Date.now());
241+
if (failure)
242+
throw new Fault(
243+
failure[0],
244+
failure[1],
245+
failure[0] === 'permission_denied' ? 403 : 408,
246+
);
247+
if (!actions.some((a) => a.status === 'approved'))
248+
throw rt.store.terminalPublications.detachedRun(runId, 'wake');
249+
}
250+
: undefined;
229251
const preparing = rt.store.runCheckpoints.startRun(
230252
run,
231253
deadlineAt,
@@ -234,9 +256,11 @@ export async function execute(rt: KernelRuntime, run: Run, bundle: AgentBundle):
234256
type: 'response.in_progress',
235257
data: { response: responseObject(view) },
236258
}),
259+
eligible,
237260
);
238261
const confirmed = typeof preparing === 'function' ? preparing : await preparing;
239262
if (!confirmed()) throw rt.store.terminalPublications.detachedRun(runId, 'start');
263+
eligible?.();
240264
started = true;
241265
rt.admission.starting.delete(runId);
242266
checkAbort(controller.signal);

‎src/kernel/kernel.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -220,11 +220,12 @@ export class Kernel {
220220
async close(): Promise<void> {
221221
this.closing = true;
222222
this.admission.stopAdmissionReads();
223+
const wakes = this.admission.wakes.stop();
223224
this.store.fileWriter.stopCheckpoints();
224225
this.store.runCheckpoints.stop();
225226
this.store.terminalPublications.stop();
226227
for (const c of this.controllers.values()) c.abort();
227-
await Promise.allSettled(this.admission.tasks.values());
228+
await Promise.allSettled([...this.admission.tasks.values(), ...wakes]);
228229
for (const runId of this.admission.parked.keys()) {
229230
if (this.store.terminalPublications.issue(runId)) {
230231
this.admission.clearParked(runId);
@@ -238,6 +239,7 @@ export class Kernel {
238239
'interrupted',
239240
'shutting_down',
240241
'The gateway shut down while awaiting approval. Explicit resume is required.',
242+
'try',
241243
);
242244
} catch (error) {
243245
if (!isCheckpointUnavailable(error)) throw error;

0 commit comments

Comments
 (0)