Skip to content

Commit 82350d6

Browse files
author
hzq
committed
Publish streamed output without blocking or replaying its producer
Queue contended SQLite appends, verify their exact events before delivery, and preserve output order across cancellation and item completion. Batch inserts and bound control frames waiting for durable text.
1 parent 6290657 commit 82350d6

18 files changed

Lines changed: 1313 additions & 230 deletions

‎bench/streaming.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,10 @@ const sources: Record<string, string> = {};
3030
for (const file of [
3131
'src/store/store.ts',
3232
'src/store/output.ts',
33+
'src/store/output-batch.ts',
34+
'src/store/output-publication.ts',
35+
'src/store/file-writer.ts',
36+
'src/kernel/text-sink.ts',
3337
'src/kernel/kernel.ts',
3438
'src/gateway/server.ts',
3539
'src/gateway/protocol.ts',

‎docs/stability.md‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -323,6 +323,21 @@ with the run ID rather than suggesting a retry; `GET /v1/runs/:id` reports
323323
This protects the gateway's own handoff and checkpoint, not external provider billing or
324324
exactly-once delivery across a crash. Incremental text writes precede this checkpoint.
325325

326+
Streamed text has its own durable boundary. Opening an item and appending its deltas wait
327+
for the writer without blocking the gateway. Readers are notified only after the exact event
328+
IDs, order and contents are committed. On a lost acknowledgement the gateway checks those
329+
rows; only a proven rollback permits another local append. An unresolved append or standalone
330+
item completion reports `effect_outcome_unknown` and `output_checkpoint_confirmed: false`
331+
on the run inspector. It does not prompt the worker again. Cancellation stops new text;
332+
already accepted text drains before the terminal event. Process exit can still lose text
333+
that had not reached SQLite.
334+
335+
Buffered text counts toward the existing run output limit. Large bursts yield between batches
336+
of at most 1,024 deltas without combining their public events. Progress, approval and caller-tool
337+
frames wait behind preceding text; at most 64 such frames and 1 MiB of their JSON can wait per
338+
run. Exceeding either bound stops the producer with `node_backpressure`. A registered approval
339+
waiting for a user decision does not occupy this buffer.
340+
326341
The input journal rolls back abandoned materialization even after restart, independently of
327342
retention. It records deletion before unlinking and keeps the receipt until absence is confirmed.
328343
It does not sweep unmarked files. In particular, an empty filesystem entry left before the first

‎docs/zh-CN/stability.md‎

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

140140
内核发起模型调用前也异步等写锁。发送前核对已提交的运行记录和实际交给 worker 的请求;等锁时受理取消,就不会发出这次调用。有效回复准备好落盘后,对话、已报告的用量、待调用工具和输出结束事件一起提交。本地写入重试不会再调一次模型。若提交回执丢失,只核实原快照、摘要和事件 ID;无法确认时,响应接口返回 `effect_outcome_unknown` 和运行 ID,而不是要求重试;`GET /v1/runs/:id` 会标记 `model_checkpoint_confirmed: false`。有权限的调用方仍能取消后续执行。这不保证进程崩溃后外部供应商只执行或计费一次;流式文本增量写入也不在这笔事务中。
141141

142+
流式文本单独提交。创建输出消息和追加文本增量时异步等写锁;确认事件 ID、顺序和内容落盘后才通知订阅者。丢回执只读回核对,证明已回滚才重写原批次,不会重调模型。文本追加或单独结束输出消息的提交无法确认时,响应返回 `effect_outcome_unknown`,运行检查接口标记 `output_checkpoint_confirmed: false`。取消后不再接收新文本,终态等待已接收的文本处理完毕;进程崩溃仍可能丢掉尚未落盘的文本。
143+
144+
等锁的文本计入运行原有的输出上限;大批增量每写至多 1,024 条就让出事件循环,不合并对外事件。进度、审批和调用方工具帧等待前面的文本,单个运行最多缓冲 64 帧,JSON 合计不超过 1 MiB。超出任一限制以 `node_backpressure` 停止生产者;已经登记、正在等人决定的审批不占这个预算。
145+
142146
若登记已被替换,拒绝派发时也不能拿旧内存覆盖已有步骤结果或产物引用。若持久记录里的调用方、智能体或轮次本身已变,本进程不会替另一代运行写终态或结算,会明确告知等待者结果未确认。
143147

144148
新的临时输入有持久归属记录,重启后仍可回收,无需启用保留策略。

‎src/gateway/run-routes.ts‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -215,11 +215,13 @@ export function registerRunRoutes(app: FastifyInstance, context: RunRouteContext
215215
return {
216216
response: responseObject(run),
217217
status: run.status,
218-
...(issue?.boundary === 'model'
219-
? { model_checkpoint_confirmed: false }
220-
: issue
221-
? { terminal_commit_confirmed: false }
222-
: {}),
218+
...(issue?.boundary === 'output'
219+
? { output_checkpoint_confirmed: false }
220+
: issue?.boundary === 'model'
221+
? { model_checkpoint_confirmed: false }
222+
: issue
223+
? { terminal_commit_confirmed: false }
224+
: {}),
223225
error: run.error,
224226
route: run.route,
225227
steps: store.steps(run.id),

‎src/kernel/execute.ts‎

Lines changed: 67 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,9 @@ export async function execute(rt: KernelRuntime, runId: string, preloaded?: Run)
116116
// 外部智能体调用了调用方工具:之前的文本已作为一条输出消息结束,结束时不再整段补发。
117117
let callerSplit = false;
118118
const emit = async (event: WorkEvent): Promise<Record<string, unknown> | void> => {
119+
if (event.type !== 'text') checkAbort(controller.signal);
119120
if (event.type === 'text') {
121+
if (controller.signal.aborted) return;
120122
try {
121123
const delta = String(event.data.delta ?? '');
122124
if (
@@ -125,7 +127,8 @@ export async function execute(rt: KernelRuntime, runId: string, preloaded?: Run)
125127
!run.checkpoint.outputContract &&
126128
!orchestration
127129
) {
128-
pendingPreToolText += delta;
130+
if (writer.canBuffer(pendingPreToolText.length + delta.length))
131+
pendingPreToolText += delta;
129132
} else {
130133
writer.emit(delta);
131134
}
@@ -143,31 +146,36 @@ export async function execute(rt: KernelRuntime, runId: string, preloaded?: Run)
143146
await emit({ type: 'progress', data: tooLarge.progress });
144147
return { decision: tooLarge.decision };
145148
}
146-
writer.flush();
147-
if (
148-
external &&
149-
(agent.access?.approval === 'auto' || (!agent.access && agent.approvals === 'auto'))
150-
)
151-
return autoApprove(rt, run, event.data);
152-
if (activeApprovals++ === 0) approvalStart = Date.now();
153-
try {
154-
return await awaitApproval(
155-
rt,
156-
run,
157-
`native:${id('action')}`,
158-
'native',
159-
event.data,
160-
controller.signal,
161-
);
162-
} finally {
163-
if (--activeApprovals === 0) nativeApprovalMs += Date.now() - approvalStart;
164-
}
149+
return writer.control(event.data, async (details) => {
150+
checkAbort(controller.signal);
151+
if (
152+
external &&
153+
(agent.access?.approval === 'auto' || (!agent.access && agent.approvals === 'auto'))
154+
)
155+
return autoApprove(rt, run, details);
156+
if (activeApprovals++ === 0) approvalStart = Date.now();
157+
try {
158+
return await awaitApproval(
159+
rt,
160+
run,
161+
`native:${id('action')}`,
162+
'native',
163+
details,
164+
controller.signal,
165+
);
166+
} finally {
167+
if (--activeApprovals === 0) nativeApprovalMs += Date.now() - approvalStart;
168+
}
169+
});
165170
} else if (event.type === 'client_tool') {
166171
if (!external || !run.checkpoint.bridge) return { error: 'Caller tools are not bridged.' };
167172
// 中继报告智能体放弃了仍在等待的调用:结束那次等待,不登记新调用。
168173
if (event.data.abandoned === true) {
169-
abandonCallerTool(rt.store, run, event.data.relay_call_id);
170-
return {};
174+
return writer.control(event.data, (details) => {
175+
checkAbort(controller.signal);
176+
abandonCallerTool(rt.store, run, details.relay_call_id);
177+
return {};
178+
});
171179
}
172180
if (forcedExternalChoice && !forcedChoiceMet) {
173181
const calledName = typeof event.data.name === 'string' ? event.data.name : '';
@@ -184,33 +192,39 @@ export async function execute(rt: KernelRuntime, runId: string, preloaded?: Run)
184192
}
185193
}
186194
// 调用前的文本结束成一条输出消息:续接后的新文本开出新消息,`delivered` 按条推进。
187-
const finished = writer.finish('completed');
188-
if (finished.length) rt.store.checkpoint(run, finished);
189-
writer.close();
190-
callerSplit ||= run.output.length > 0;
191-
if (activeApprovals++ === 0) approvalStart = Date.now();
192-
try {
193-
return await awaitCallerTool(rt, run, event.data, controller.signal);
194-
} catch (error) {
195-
if (!controller.signal.aborted) {
196-
eventError ??= faultOf(error);
195+
return writer.control(
196+
event.data,
197+
async (details) => {
198+
checkAbort(controller.signal);
199+
callerSplit ||= run.output.length > 0;
200+
if (activeApprovals++ === 0) approvalStart = Date.now();
201+
try {
202+
return await awaitCallerTool(rt, run, details, controller.signal);
203+
} catch (error) {
204+
if (!controller.signal.aborted) {
205+
eventError ??= faultOf(error);
206+
controller.abort();
207+
}
208+
throw error;
209+
} finally {
210+
if (--activeApprovals === 0) nativeApprovalMs += Date.now() - approvalStart;
211+
}
212+
},
213+
(events) => rt.store.checkpointOutput(run, events),
214+
);
215+
} else {
216+
return writer.control(event.data, (details) => {
217+
checkAbort(controller.signal);
218+
const fault = recordProgress(rt.store, run.id, details, external);
219+
if (fault) {
220+
eventError ??= fault;
197221
controller.abort();
198222
}
199-
throw error;
200-
} finally {
201-
if (--activeApprovals === 0) nativeApprovalMs += Date.now() - approvalStart;
202-
}
203-
} else {
204-
writer.flush();
205-
const fault = recordProgress(rt.store, run.id, event.data, external);
206-
if (fault) {
207-
eventError ??= fault;
208-
controller.abort();
209-
}
223+
});
210224
}
211225
};
212226
try {
213-
if (!external) rt.store.modelTurns.track(run);
227+
rt.store.modelTurns.track(run);
214228
run.status = 'in_progress';
215229
run.error = null;
216230
rt.store.checkpoint(run, [], (view) => ({
@@ -242,8 +256,9 @@ export async function execute(rt: KernelRuntime, runId: string, preloaded?: Run)
242256
pass(input),
243257
);
244258
if (!run.checkpoint.outputContract) {
245-
const finished = writer.publishFinalOnce(answer);
246-
if (finished.length) rt.store.checkpoint(run, finished);
259+
const finished = await writer.publishFinalOnce(answer);
260+
if (eventError) throw eventError;
261+
if (finished.length) await rt.store.checkpointOutput(run, finished);
247262
writer.close();
248263
}
249264
} else answer = await pass(nativeInput);
@@ -283,7 +298,8 @@ export async function execute(rt: KernelRuntime, runId: string, preloaded?: Run)
283298
);
284299
}
285300
}
286-
const settled = settleStructuredOutput(rt, run, agent, writer, answer);
301+
const settled = await settleStructuredOutput(rt, run, agent, writer, answer);
302+
if (eventError) throw eventError;
287303
if (!settled.again) break;
288304
nativeInput = settled.nativeInput;
289305
}
@@ -319,6 +335,9 @@ export async function execute(rt: KernelRuntime, runId: string, preloaded?: Run)
319335
isWriteUnavailable,
320336
);
321337
} catch (error) {
338+
// Text accepted before cancellation or a worker error precedes any terminal event.
339+
const draining = writer.flush();
340+
if (draining) await draining;
322341
const suspended = error instanceof ApprovalSuspension || error instanceof SchedulingSuspension;
323342
if (suspended && !controller.signal.aborted && !rt.closing()) {
324343
const scheduling = error instanceof SchedulingSuspension;
@@ -382,7 +401,7 @@ export async function execute(rt: KernelRuntime, runId: string, preloaded?: Run)
382401
hadEventError: Boolean(eventError),
383402
};
384403
delete run.checkpoint.suspension;
385-
const finalEvents = stepIssue ? [] : writer.finish('incomplete');
404+
const finalEvents = stepIssue ? [] : await writer.finish('incomplete');
386405
releaseCommitted = await commitTerminal(
387406
rt,
388407
run,

‎src/kernel/lifecycle.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -96,8 +96,8 @@ export function forgetProviderKey(rt: KernelRuntime, runId: string, status: Run[
9696
export async function cancel(rt: KernelRuntime, principal: Principal, runId: string): Promise<Run> {
9797
const run = rt.store.run(runId, principal.owner, visibleSubject(principal));
9898
authorize(principal, run.agentId, 'invoke');
99-
if (rt.store.terminalPublications.issue(runId)?.boundary === 'model')
100-
rt.controllers.get(runId)?.abort();
99+
const boundary = rt.store.terminalPublications.issue(runId)?.boundary;
100+
if (boundary === 'model' || boundary === 'output') rt.controllers.get(runId)?.abort();
101101
rt.store.terminalPublications.requireConfirmed(runId);
102102
if (terminal(run.status)) return run;
103103
if (run.status === 'queued') {

‎src/kernel/model-turn.ts‎

Lines changed: 27 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -361,8 +361,8 @@ export async function runModelTurn(
361361
// 流式路径攒下的增量按流式的错误语义落盘;整段补发的文本保持原有的直接报错语义。
362362
if (!session.writer.open && answer.text) {
363363
session.writer.emit(answer.text);
364-
session.writer.flush(true);
365-
} else session.writer.flush();
364+
await session.writer.flush(true);
365+
} else await session.writer.flush();
366366
const failure = session.failure();
367367
if (failure) throw failure;
368368
const account = (view: Run) => {
@@ -386,26 +386,31 @@ export async function runModelTurn(
386386
502,
387387
);
388388
}
389-
await rt.store.modelTurns.finish(run, permit, session.writer.finish('completed'), (next) => {
390-
account(next);
391-
next.checkpoint.messages.push({
392-
role: 'assistant',
393-
content: answer.text,
394-
tool_calls: answer.calls,
395-
providerItems: providerState ? undefined : answer.providerItems,
396-
...(providerState ? { providerState } : {}),
397-
});
398-
if (providerState) next.checkpoint.modelInstructions ??= requestInstructions;
399-
next.checkpoint.pending = answer.calls;
400-
next.checkpoint.phase = answer.calls.length ? 'tools' : 'done';
401-
const completed = next.checkpoint.marks!.at(-1)!;
402-
Object.assign(completed, {
403-
dispatched: mark?.dispatched,
404-
end: mark?.end,
405-
status: 'completed',
406-
calls: answer.calls.length,
407-
});
408-
});
389+
await rt.store.modelTurns.finish(
390+
run,
391+
permit,
392+
await session.writer.finish('completed'),
393+
(next) => {
394+
account(next);
395+
next.checkpoint.messages.push({
396+
role: 'assistant',
397+
content: answer.text,
398+
tool_calls: answer.calls,
399+
providerItems: providerState ? undefined : answer.providerItems,
400+
...(providerState ? { providerState } : {}),
401+
});
402+
if (providerState) next.checkpoint.modelInstructions ??= requestInstructions;
403+
next.checkpoint.pending = answer.calls;
404+
next.checkpoint.phase = answer.calls.length ? 'tools' : 'done';
405+
const completed = next.checkpoint.marks!.at(-1)!;
406+
Object.assign(completed, {
407+
dispatched: mark?.dispatched,
408+
end: mark?.end,
409+
status: 'completed',
410+
calls: answer.calls.length,
411+
});
412+
},
413+
);
409414
session.pending(false);
410415
session.writer.close();
411416
checkAbort(signal);

‎src/kernel/native-turn.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -135,8 +135,8 @@ export async function runNativeAgent(
135135
// 流式路径攒下的增量按流式的错误语义落盘;整段补发的文本保持原有的直接报错语义。
136136
if (!session.writer.open && native.text && !session.split?.()) {
137137
session.writer.emit(native.text);
138-
session.writer.flush(true);
139-
} else session.writer.flush();
138+
await session.writer.flush(true);
139+
} else await session.writer.flush();
140140
const failure = session.failure();
141141
if (failure) throw failure;
142142
run.checkpoint.nativeState = { ...native.nativeState, nodeId: result.nodeId };
@@ -161,7 +161,7 @@ export async function runNativeAgent(
161161
await rt.store.checkpointNativeStep(
162162
run,
163163
nativeStep,
164-
session.writer.finish('completed'),
164+
await session.writer.finish('completed'),
165165
artifactIds,
166166
);
167167
} catch (error) {

‎src/kernel/structured-output.ts‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -28,21 +28,21 @@ export function resumableSession(state: Record<string, unknown> | undefined): bo
2828
/** The follow-up for an external agent when the previous answer was rejected; `undefined` for everything else. */
2929
export type Settled = { again: false } | { again: true; nativeInput?: string };
3030

31-
export function settleStructuredOutput(
31+
export async function settleStructuredOutput(
3232
rt: KernelRuntime,
3333
run: Run,
3434
agent: AgentDefinition,
3535
writer: RunTextSink,
3636
/** The text of the final answer: the last model message, or the external agent's reply. */
3737
answer: string,
38-
): Settled {
38+
): Promise<Settled> {
3939
const contract = run.checkpoint.outputContract;
4040
if (!contract) return { again: false };
4141
const verdict = checkAnswer(contract, answer, rt.outputSchemas);
4242
if (verdict.ok) {
4343
if (run.checkpoint.orchestration) {
4444
run.checkpoint.orchestration.finalText = verdict.text;
45-
rt.store.checkpoint(run, writer.publishFinalOnce(verdict.text));
45+
await rt.store.checkpointOutput(run, await writer.publishFinalOnce(verdict.text));
4646
writer.close();
4747
return { again: false };
4848
}
@@ -53,8 +53,8 @@ export function settleStructuredOutput(
5353
}
5454
writer.hold(false);
5555
writer.emit(verdict.text);
56-
writer.flush(true);
57-
rt.store.checkpoint(run, writer.finish('completed'));
56+
await writer.flush(true);
57+
await rt.store.checkpointOutput(run, await writer.finish('completed'));
5858
writer.close();
5959
return { again: false };
6060
}

0 commit comments

Comments
 (0)