Skip to content

Commit 769a790

Browse files
author
hzq
committed
Commit delegated runs and parent links atomically
Persist inherited execution context, the parent step and both lifecycle events before dispatch. Verify stored relationships during recovery and reconcile uncertain commit outcomes without replaying external work.
1 parent 9b1479a commit 769a790

18 files changed

Lines changed: 771 additions & 92 deletions

‎docs/architecture.md‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -162,14 +162,17 @@ Caller tool bridging reuses the same parking path; see [harness.md](harness.md).
162162

163163
**Delegation consistency** (`kernel/delegate.ts`):
164164

165-
- After a child run is submitted successfully and before waiting begins, the child run ID is registered on the step record's `childRunId`. When resume replay reaches this step it looks for that child run first: if it has completed, its result is used directly (usage and steps are committed in the same checkpoint and accumulated only once); if it is still queued, executing, or awaiting approval, it keeps waiting; if it is interrupted or its outcome is unknown, a step whose level is not read-only is recorded as `uncertain` and waits for human confirmation; if it ended as failed, cancelled, or incomplete, read-only and safely retryable steps are delegated again, and "effects unknown" steps wait for human confirmation. After a human checks it as "not executed", it is delegated again on resume.
165+
- The child record (including its depth, grants and inherited project), the parent step's `childRunId` and the `subagent.started` event commit together. A refused write cannot dispatch the child. The parent can already resolve the link at the first public notification.
166+
- On resume, a completed child's result and usage are reused once; an active child is reattached. Unknown effects still require human confirmation. A failed or cancelled child is delegated again only when its effect allows that, or a human reconciled it as not executed.
167+
- Reattachment checks the owner, caller, parent run and delegate step, not just a child ID. An unreadable or contradictory receipt is not treated as a missing run. A confirmed missing child may be retried automatically only for read-only work.
168+
- If SQLite loses the commit acknowledgement, the gateway checks the freshly allocated run ID before publishing. A confirmed commit is published once. If that read also fails, the parent stops with an uncertain step for reconciliation instead of guessing that no child exists.
166169
- When the wait is interrupted by the parent run being cancelled or the gateway closing, the child run is still cancelled as before; if the step level is not read-only it is recorded as `uncertain` (the child run may already have done something), and read-only is recorded as `failed`. When the gateway closes, the parent run therefore becomes `interrupted` / `effect_outcome_unknown`, and resuming is blocked at human confirmation; when the parent run is cancelled it still ends as `cancelled`. When a child run ends as `interrupted` or `effect_outcome_unknown` and the step level is not read-only, the parent run likewise enters the human confirmation flow.
167170
- Delegation manages its own timeout: a timeout reports `delegate_timeout` (504), the child run is cancelled, and the timer is cleaned up at the end.
168171
- Run slots: while the parent run waits for a child run it lends out its own run slot so the child run can enter. It is counted per parent run, lending out only one regardless of how many delegations are in parallel (0→1 lends, 1→0 takes back; when taking back and there is no free slot, it waits until there is one, and on abort or shutdown it takes back directly). Invariant: number of executing runs = number of runs holding run slots + number of parent runs that lent out run slots, and the number holding is within `[0, maxActiveRuns]` (it may briefly exceed only during abort teardown).
169-
- When the gateway resumes queued runs at startup, a queued child run whose parent run is no longer active (not in `queued` / `in_progress` / `requires_action`) is not executed and ends as `cancelled` with the error code `parent_interrupted` (the state machine does not allow `queued` to go directly to `interrupted`).
172+
- At startup a queued delegate needs an active parent and a matching parent step in the same owner and caller scope. For older checkpoints without a parent step ID, the gateway checks the child ID already stored on that parent's steps. An unlinked queued child is cancelled with `parent_interrupted`, not guessed from an agent name or sent to a worker.
170173
- A child run's artifacts are not merged into the parent run; they are given as references only in the `artifacts` of the delegation result (file ID, name, sha256, and download URL).
171174

172-
Change log: 2026-11-10 side-effect levels of delegation steps; 2026-11-11 delegation consistency.
175+
Change log: 2026-11-10 side-effect levels of delegation steps; 2026-11-11 delegation consistency; 2026-11-21 atomic child admission and recovery of older queues.
173176

174177
### 3.8 Handoff and fallback agents
175178

‎docs/protocol.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -788,7 +788,7 @@ Error codes and response shapes do not depend on language; only the text of `mes
788788
| `run_not_attached` | 409 | The run shows as in progress but is not executing in this gateway process (inconsistent data, or held by another process); the cancel request was not accepted |
789789
| `run_key_inactive` | 409 | The key that owns the run has expired, been revoked or deleted (or its account no longer exists), so the run cannot be resumed. This appears when the owner's admin key resumes another key's run; when the original key resumes by itself, expiry and revocation are already rejected at authentication with `key_expired` / `unauthorized` |
790790
| `invalid_reconciliation` | 409 | No matching step is waiting for reconciliation |
791-
| `effect_outcome_unknown` | 409 | The outcome of an operation with side effects is unconfirmed (the run is marked interrupted) |
791+
| `effect_outcome_unknown` | 409 | A side effect is unconfirmed and the executing run is interrupted. If the run-creation commit itself cannot be confirmed or read back, the error includes the allocated `run_id`: inspect it before resubmitting; do not assume that no run exists. |
792792
| `gateway_restarted` | — | A gateway restart interrupted execution (run error code) |
793793
| `run_timeout` | — | The run passed its deadline (run error code, status incomplete) |
794794
| `cancelled` | 409 | The task was cancelled |

‎docs/zh-CN/architecture.md‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -162,14 +162,17 @@ Open Agent API 对外提供的是**智能体的能力**,而不仅仅是模型
162162

163163
**委托一致性**(`kernel/delegate.ts`):
164164

165-
- 子运行提交成功后、开始等待前,子运行 ID 登记在步骤记录的 `childRunId` 上。恢复重放到这一步时先找这个子运行:已完成就直接用它的结果(用量与步骤在同一个检查点里提交,只累加一次);仍在排队、执行或等审批就继续等;已中断或结果未知时,等级不是只读的步骤记为 `uncertain`,等人工确认;以失败、取消或未完成结束时,只读与可安全重试的步骤重新委托,「影响未知」的步骤等人工确认。人工核对为「未执行」后,恢复时重新委托。
165+
- 子运行(含委托深度、授权和继承的项目)、父步骤的 `childRunId` 与 `subagent.started` 事件在同一笔事务提交。写入失败不会派发子任务;第一次对外通知时,父步骤就能找到子运行。
166+
- 恢复时直接复用已完成子运行的结果,用量只计一次;仍活跃的子运行继续等待。结果未知的副作用仍需人工核对。失败或取消的子运行,只有副作用等级允许,或人工确认为「未执行」时,才重新委托。
167+
- 重新挂接会核对 owner、调用方、父运行和委托步骤,不只核对子运行 ID。记录读不出或关联互相矛盾,不当作「从没运行过」;确认找不到原子运行时,也只有只读任务可以自动重试。
168+
- SQLite 提交应答丢失时,网关按这次分配的运行 ID 回读;确认提交才派发一次。如果连回读也失败,父运行以待核对的步骤中断,而不是假设子任务没有创建。
166169
- 等待被父运行取消或网关关闭打断时,子运行照旧被取消;步骤等级不是只读就记 `uncertain`(子运行可能已经做了事),只读记 `failed`。网关关闭时父运行因此成为 `interrupted` / `effect_outcome_unknown`,恢复被拦在人工确认;父运行被取消时仍以 `cancelled` 结束。子运行以 `interrupted` 或 `effect_outcome_unknown` 结束、且步骤等级不是只读时,父运行同样进入人工确认流程。
167170
- 委托自己管理超时:超时报 `delegate_timeout`(504),子运行被取消,定时器在结束时清理。
168171
- 运行槽:父运行等子运行时借出自己的运行槽,让子运行能入场。按父运行计数,无论并行多少个委托只借出一个(0→1 借出,1→0 领回;领回时没有空位就等到有空位,中止或关闭时直接领回)。不变量:执行中的运行数 = 占用运行槽的运行数 + 借出运行槽的父运行数,且占用数在 `[0, maxActiveRuns]` 内(只在中止拆除时可能短暂超出)。
169-
- 网关启动恢复排队运行时,父运行已经不活跃(不在 `queued` / `in_progress` / `requires_action`)的排队子运行不再执行,以 `cancelled` 结束,错误码 `parent_interrupted`(状态机不允许 `queued` 直接到 `interrupted`)。
172+
- 启动时,排队的委托必须能找到仍活跃、同 owner 且同调用方的父运行,以及明确指向它的父步骤。旧检查点没有父步骤编号时,只核对该父运行步骤里实际记录的子运行 ID;未关联的排队子运行以 `cancelled` 和 `parent_interrupted` 结束,不按智能体名称猜测或派发。
170173
- 子运行的产物不并入父运行,只在委托结果的 `artifacts` 里给出引用(文件 ID、名称、sha256 与下载地址)。
171174

172-
变更记录:2026-11-10 委托步骤的副作用等级;2026-11-11 委托一致性。
175+
变更记录:2026-11-10 委托步骤的副作用等级;2026-11-11 委托一致性;2026-11-21 子任务原子准入与旧队列恢复。
173176

174177
### 3.8 交接与备选智能体
175178

‎docs/zh-CN/protocol.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -812,7 +812,7 @@ HTTP 错误响应默认使用形状 `{"error":{"code":"…","message":"…","typ
812812
| `run_not_attached` | 409 | 运行显示为进行中,但不在本网关进程中执行(数据不一致或由别的进程持有),取消请求没有被受理 |
813813
| `run_key_inactive` | 409 | 运行所属的密钥已过期、被吊销或已删除(或其账号已不存在),不能恢复。由 owner 的管理员密钥代为恢复别人的运行时出现;原密钥自己发起恢复时,过期与吊销在鉴权阶段就以 `key_expired` / `unauthorized` 拒绝 |
814814
| `invalid_reconciliation` | 409 | 没有匹配的待核对步骤 |
815-
| `effect_outcome_unknown` | 409 | 有副作用的操作结果未确认(运行记为 interrupted) |
815+
| `effect_outcome_unknown` | 409 | 执行中的副作用无法确认,运行记为 interrupted。若运行创建时提交应答丢失且无法回读,错误中附分配的 `run_id`;先按 ID 查询,不要当作未创建而直接重发。 |
816816
| `gateway_restarted` | — | 网关重启导致执行中断(运行错误码) |
817817
| `run_timeout` | — | 运行超过截止时间(运行错误码,状态 incomplete) |
818818
| `cancelled` | 409 | 任务已取消 |

‎src/core/contracts.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -313,6 +313,8 @@ export type Checkpoint = {
313313
suspension?: { kind: 'approval' | 'scheduling'; approvalIds: string[] };
314314
grantedAgents?: string[];
315315
delegationDepth?: number;
316+
/** Step that owns this delegated child. Older checkpoints can be matched by the recorded child ID. */
317+
parentStepId?: string;
316318
keyId?: string;
317319
/** Highest execution level the submitting key allowed; delegated sub-runs inherit it. */
318320
execution?: ExecutionLevel;

‎src/gateway/compat-errors.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import { errorClassStatus, errorEntry, faultMessage } from '../core/errors.js';
1818
import { processLocale, requestLocale, type Locale, type LocalText } from '../core/locale.js';
1919
import { Fault, RetryLaterFault } from '../core/util.js';
2020
import { ParamFault } from '../core/param-fault.js';
21+
import { UnconfirmedRunCommit } from '../store/run-creation.js';
2122
import { fromGoogleClient, isGeminiPath } from './gemini.js';
2223

2324
/** 带参数名或运行 ID 的错误:`param` 进 OpenAI 的 `error.param`,`runId` 说明运行已经创建。 */
@@ -103,7 +104,8 @@ export function errorBody(
103104
locale: Locale = processLocale(),
104105
): Record<string, unknown> {
105106
const message = faultMessage(fault, locale);
106-
const extra = fault instanceof CompatFault ? fault : undefined;
107+
const extra =
108+
fault instanceof CompatFault || fault instanceof UnconfirmedRunCommit ? fault : undefined;
107109
const runId = extra?.runId ? { run_id: extra.runId } : {};
108110
// 类别按错误码的语义选(服务一侧的运行错误码为 500 一类),HTTP 状态与重试头不受影响。
109111
const kind = errorClassStatus(fault.code, status);

‎src/kernel/delegate.ts‎

Lines changed: 44 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
* 委托步骤:把一次工具调用交给子智能体,作为一个后台子运行执行,父运行等它结束。
33
*
44
* 一致性规则(docs/architecture.md「委托步骤的副作用等级」):
5-
* - 子运行提交成功后、开始等待前,子运行 ID 登记在步骤记录的 `childRunId` 上。
5+
* - 子运行、其继承的检查点、父步骤的 childRunId 和开始事件一起提交,提交后才允许派发。
66
* - 恢复重放到这一步时先找已登记的子运行:已完成直接取结果;仍活跃继续等;已中断或结果未知
77
* (等级不是 read)则步骤为 uncertain,等人工确认;失败、取消或未完成时,等级为 read /
88
* idempotent-write 才重新委托,unknown 也要人工确认。
@@ -29,16 +29,18 @@ import type { Store } from '../store/store.js';
2929
import type { Invocation } from './invocation.js';
3030
import { addUsage, stepIdFor } from './run-state.js';
3131
import { contractInstruction } from './output-contract.js';
32+
import type { DelegateAdmission } from './types.js';
33+
import { UnconfirmedRunCommit } from '../store/run-creation.js';
3234

3335
/** 委托需要的内核能力。由 Kernel 显式提供,不暴露它的私有字段。 */
3436
export interface DelegateRuntime {
3537
readonly store: Store;
3638
submit(
3739
principal: Principal,
3840
invocation: Invocation,
39-
idem?: string,
40-
providerKey?: string,
41-
trace?: TraceContext,
41+
providerKey: string | undefined,
42+
trace: TraceContext | undefined,
43+
delegate: DelegateAdmission,
4244
): Run;
4345
wait(runId: string, includeActions: boolean, signal: AbortSignal): Promise<Run>;
4446
cancel(principal: Principal, runId: string): Promise<Run>;
@@ -190,11 +192,21 @@ export async function callDelegate(
190192
if (existing?.childRunId) {
191193
let prior: Run | undefined;
192194
try {
193-
prior = store.run(existing.childRunId);
194-
} catch {
195-
// A missing prior child run means the delegate starts fresh.
195+
prior = store.run(existing.childRunId, run.owner, run.subject ?? LEGACY_SUBJECT);
196+
} catch (error) {
197+
// An unreadable receipt is not evidence that no execution took place. Even a
198+
// confirmed missing child can be replayed without reconciliation only for a read.
199+
if (!(error instanceof Fault && error.code === 'run_not_found'))
200+
unconfirmed('persistence_failed', existing.childRunId);
201+
if (step.effect !== 'read') unconfirmed('run_not_found', existing.childRunId);
196202
}
197203
if (prior) {
204+
if (
205+
prior.metadata['oaa.parent_run_id'] !== run.id ||
206+
prior.metadata['oaa.delegate_name'] !== delegate.name ||
207+
(prior.checkpoint.parentStepId !== undefined && prior.checkpoint.parentStepId !== stepId)
208+
)
209+
unconfirmed('invalid_step_checkpoint', prior.id);
198210
const decision = replayDecision(step.effect, prior);
199211
if (decision === 'reuse') return finish(store, run, delegate, step, prior, slice);
200212
if (decision === 'uncertain')
@@ -204,15 +216,18 @@ export async function callDelegate(
204216
}
205217

206218
step.status = 'running';
207-
store.step(step, {
208-
type: 'subagent.started',
209-
data: {
210-
step_id: stepId,
211-
delegate: delegate.name,
212-
target_agent: delegate.agent,
213-
depth,
214-
},
215-
});
219+
if (childRun)
220+
store.step(step, {
221+
type: 'subagent.started',
222+
data: {
223+
step_id: stepId,
224+
delegate: delegate.name,
225+
target_agent: delegate.agent,
226+
depth,
227+
child_run_id: childRun.id,
228+
reattached: true,
229+
},
230+
});
216231

217232
if (!childRun) {
218233
try {
@@ -250,26 +265,27 @@ export async function callDelegate(
250265
'oaa.delegate_name': delegate.name,
251266
},
252267
},
253-
undefined,
254268
childKey,
255269
run.trace ? childTraceContext(run.trace) : undefined,
270+
{ step, depth, project: run.checkpoint.project },
256271
);
257272
} catch (err) {
258-
const f = faultOf(err);
273+
// An unconfirmed COMMIT may already contain the link. The parent terminal
274+
// checkpoint preserves the uncertain step atomically; never replace it with a failure.
275+
if (err instanceof UnconfirmedRunCommit) throw err;
276+
const f =
277+
err instanceof Error && 'code' in err && err.code === 'ERR_SQLITE_ERROR'
278+
? new Fault(
279+
'persistence_failed',
280+
'The delegated run could not be stored with its parent step.',
281+
500,
282+
)
283+
: faultOf(err);
259284
fail('failed', f.code);
260285
throw f;
261286
}
262-
childRun.checkpoint.delegationDepth = depth;
263-
if (run.checkpoint.project) {
264-
childRun.checkpoint.project = { ...run.checkpoint.project };
265-
const last = childRun.checkpoint.messages.at(-1);
266-
if (last?.role === 'user') last.content += run.checkpoint.project.context;
267-
}
268-
childRun.checkpoint.grantedAgents = [...grantedAgents];
269-
store.save(childRun);
270-
// 登记子运行:之后无论怎样中断,恢复时都能重新挂上它。
287+
// The durable link already exists; later updates use the same child in this execution.
271288
step.childRunId = childRun.id;
272-
store.step(step);
273289
}
274290
const child = childRun;
275291
rt.prioritize(child.id);

‎src/kernel/durability.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import { projectPrincipal } from './project-memory.js';
1212
import { projects } from '../store/projects.js';
1313
import { workflowAllowsChildRecovery } from '../store/task-workflows.js';
1414
import { recoveryCandidates, isRecoveryCause } from '../store/recovery-candidates.js';
15+
import { delegateRecoveryBlock } from '../store/run-creation.js';
1516

1617
export function durability(
1718
agent: AgentDefinition,
@@ -48,6 +49,12 @@ export function recoverDurable(
4849
if (!policy || run.status !== 'interrupted' || !isRecoveryCause(run.error?.code)) continue;
4950
let attempted = false;
5051
try {
52+
if (delegateRecoveryBlock(rt.store, run, false))
53+
throw new Fault(
54+
'reconciliation_required',
55+
'No matching parent step confirms this delegated run; it was not replayed.',
56+
409,
57+
);
5158
if (!workflowAllowsChildRecovery(rt.store, run))
5259
throw new Fault(
5360
'reconciliation_required',

0 commit comments

Comments
 (0)