Repository navigation
fix(serve): resume committed file results after runtime retirement - #14059
Conversation
Co-authored-by: Qwen-Coder <[email protected]>
Linux Hosted core acceptance — final combined candidateAll 11 independent final runs passed: 3 real VM reboot arms, 1 public API run (8 JUnit cases, 0 failures/errors/skips), 1 running foreground Shell loop, and all 6 canonical G3 modes (allow, deny, cancel, expiry, continuation, freeze). These are 8 JUnit cases plus 10 fully executed standalone script scenarios. Repeated historical baseline runs are excluded from this final count. The frozen production baseline is main
Actual reboot evidenceEach arm began with a physically live original worker, held owner, SETTLED execution and dispatch generation 1. The parent independently read PID/start ticks, SQL, file bytes and boot identity before a force VM stop/start. The same MySQL datadir and original stored pin/deadline were retained; no business SQL was changed to admit recovery.
The final public API run passed 8/8 cases on both public surfaces, including the new native-file close regression under the Shell profile. The running Shell loop independently observed parent/child/process-group disappearance after cancel, complete/committed cancelled output, the same Session's next approved Shell/Read Turn, physical worker close and all 71 resource hashes/history retained. G3 freeze actually SIGCONT-resumed the old Harness and confirmed healthy but fenced behavior: generation-2 journal/boot/terminal/text and old-generation transaction count 21 were unchanged. Final ScopeRetired-result model continuation is limited to 中文验收说明最终组合候选的 11 次独立运行全部通过:3 次真实 VM 重启、1 次公开 API(8 个 JUnit cases、0 失败/错误/跳过)、1 次运行中前台 Shell 和 G3 的 allow/deny/cancel/expiry/continuation/freeze 六模式。合计 8 个 JUnit cases 与 10 个全部实际执行的独立脚本场景,历史基线重复运行不计入最终数量。 固定 main 三个真实重启分别验证已提交 Edit 续跑、恢复后请求新 Write 被明确拒绝、首次 Read 没有文件历史。每次重启前独立核验原 worker 的 PID/start ticks、持有者、SQL SETTLED/dispatch1、物理文件和 boot;使用同一 MySQL datadir 和未改动的 pin/deadline,未改业务 SQL 准入恢复。三个场景均保留原执行/结果、同 Session 下一 Write/Read Turn 使用 generation 2、旧清理不能清新 holder,公开 close 自身物理退役新 worker 并保留历史。新 Write 拒绝场景原 Turn 为已知 FAILED,而 Session 保持 ACTIVE。 公开 API 两种 surface 的 8 个案例通过;运行中 Shell 的父子进程与进程组取消、输出提交、同 Session 下一个已审批 Shell/Read、worker 物理关闭及全部 71 个资源身份/摘要与公开历史保留通过。G3 freeze 实际唤醒旧 Harness 并确认 health;新代 journal/boot/终态/文本和旧代事务数 21 均不变。最终 /proc 未发现残留 Java/Node 或 canonical 临时 MySQL。此为单实例 Linux 受控模型的功能/故障验收,不代表生产、真实模型/外部 OSS、Shell/MCP/Hook 冷恢复扩展、多主机/多控制面 HA 或裸机未刷新掉电验收。退役原 Turn 的新物理工作需要新 Turn;未知效果等证据不足路径保持阻塞。 |
🩺 serve daemon A/BBuilt the PR base vs this PR head ✅ No response changes against the PR base across 12 scenario(s). — Qwen Code · serve A/B |
chiga0
left a comment
There was a problem hiding this comment.
Review — fix(serve): resume committed file results after runtime retirement
No blocking findings. Approval blockers: none.
Scope
Source files reviewed: all 6 changed files.
Cross-file context obtained: HostedWorkspaceBroker.release() + constructor (verified release does not need .warm() called first), readHostedFileHistory(), canSettleHostedFileHistory() full body, oweHostedTurnCleanup() full body, finish() / cleanup() / acquire() surrounding context in hosted-workspace-tool-turn.ts.
NOT reviewed: the execute() method body (not changed by this PR; too large to fetch in full); reconcileHostedTurnCleanup callers beyond what is in the diff.
Execution: working tree unavailable — tests and mutation probes not run.
Checked areas
cleanupIdentity refactor (hosted-turn-cleanup.ts)
Extracted the exact inline logic from oweHostedTurnCleanup — originalId computation, Buffer.byteLength hash gate, cleanupId choice — into a shared function. Both callers (oweHostedTurnCleanup and confirmReplacedHostedTurnOwner) call it with the same arguments; the key derivation is identical. No logic change.
confirmReplacedHostedTurnOwner (hosted-turn-cleanup.ts:135–183)
- Uses the same
cleanupIdentitykey asoweHostedTurnCleanup, so the event-lookup and the owe-debt writer share the same ID space. Contract symmetric (class 1 check: writer atoweHostedTurnCleanup, reader here — both endpoints match). broker.runtime === undefinedearly return is correct: warm may return no runtime if the broker is unreachable.- Descriptor validation:
promptId,runtimeSessionId,workspaceGenerationall checked against the live broker's values.readDescriptoradditionally validatesruntimeSessionId === hostedRuntimeSessionId(promptId)and generation numeric bounds. - Same-binding early return (
descriptor.bindingId === broker.runtime.bindingId && ...) correctly skips release if the warm reply returned the same runtime identity — non-retired case. - New
HostedWorkspaceBrokerfor the release call:release()uses onlythis.identity.runtimeSessionId(set in constructor) and the passed{ bindingId, generation }— it does not readbroker.runtime. Calling withoutwarm()is safe here.
New block in resumeCommittedResults (hosted-workspace-tool-turn.ts:1990–2052)
- Entry guard:
!saved?.pendingTurn && !saved?.pendingUndo && !hooks && !mcp && profile === HOSTED_WORKSPACE_FILE_PROFILE— cleanly separate from the existingsaved?.pendingTurnpath. - Inner condition:
items.every(settled && native-tool)prevents non-native or unsettled items from matching;(saved || items.every(read_only))enforces that Write/Edit require a committed file history record. canSettleHostedFileHistorycalled with synthetic{ pendingUndo: null, pendingTurn: this.promptId, pendingMessageId: items.at(-1)!.modelMessageId }— validates that the authorization checkpoint is consistent with this turn's saved request. Usingitems.at(-1)!for multi-batch is correct: the design requires the latest assistant message (verified bymode = 'retired-multi-batch'test).item.outcomeRef!non-null assertion is safe: the outerevery(item.state === 'settled')check already guaranteesoutcomeRef !== null(parser contract confirmed incanSettleHostedFileHistorycomment).- All errors inside the
tryare re-thrown asHostedToolRecoveryRequiredError, keeping the turn fail-closed. - On success:
retiredOwnerResults = true,cleanupOwed = true,uncertain = false— all three set atomically before return.
acquire() guard (hosted-workspace-tool-turn.ts:2059–2065)
Sets this.uncertain = false before throwing. This is intentional: the caller (execute()) does not need to enter recovery because the outcome is fully known (no acquisition was attempted). Test mode = 'retired-new-call' confirms the error text 'Submit remaining tool work in a new Turn.' propagates unwrapped, and that finish() + cleanup() still succeed afterward.
finish() changes (hosted-workspace-tool-turn.ts:6890–6931)
if (!this.acquired && !this.retiredOwnerResults) return;— correct gate: the retired path (acquired = false, retiredOwnerResults = true) must still settle the model continuation.if (!this.acquired) return;aftersettleConsumedRuntimeContinuation()— correct early return: no broker release is needed (the release was already done byconfirmReplacedHostedTurnOwner); cleanup debt is reconciled later incleanup().cleanup()is unchanged:cleanupOwed = truesends it throughreconcileHostedTurnCleanup, which confirms the descriptor after the durable Turn terminal. This matches the PR design requirement ("retain cleanup asoweduntil the original Turn terminal commits").
State lifecycle (class 7)
Enumerated reachable states for retiredOwnerResults = true:
- After
resumeCommittedResults:retiredOwnerResults = true,cleanupOwed = true,acquired = false,uncertain = false. execute()→acquire()guard throws'Submit remaining tool work...'withuncertain = false. No zombie: the error is clean, not recovery-blocking.finish(): settles continuation, returns early.retiredOwnerResultsnot cleared (consistent with the existingcleanupOwedpath whereacquiredalso stays set throughfinish()).cleanup(): reconciles the owed descriptor. No resource leak.
canSettleHostedFileHistory signature relaxation (hosted-file-history.ts:148–152)
Relaxes the parameter from HostedFileHistoryRecord to Pick<..., 'pendingTurn' | 'pendingUndo' | 'pendingMessageId'>. The function body reads only these three fields; existing callers that pass a full HostedFileHistoryRecord continue to satisfy the pick. Backward-compatible.
Test coverage (hosted-recovery.test.ts)
The parameterized it.each across 9 modes replaces and extends the single prior test. Modes cover: normal snapshot recovery (snapshot), retired-owner success (retired), new-call rejection (retired-new-call), lost release reply (retired-release-lost), corrupt outcome resource (retired-corrupt-outcome), workspace generation drift (retired-workspace-changed), read-only batch with no file history (retired-read-only), missing Write/Edit history (retired-write-history-missing), and multi-batch continuation (retired-multi-batch). The failure modes that must remain blocked all assert rejects.toThrow('Hosted tool turn requires recovery') before finish(). The acquire call-count assertions (1 for retired paths, 2 for snapshot) verify that the retired path skips the second acquisition.
Cross-check against existing reviews
Author's 3-arm reboot acceptance comment: real VM stop/start with unchanged MySQL datadir, three scenarios (Edit, immediate new Write rejection, Read-only no file history). qwen-code-review-bot A/B: no response surface change across 12 scenarios. No other human reviewer findings to resolve.
Unreviewed dimensions (not approval-blocking)
execute()body not read — not in this diff; the file history / cleanup commit ordering during normal execution is not directly observable from the changed lines. Themode = 'retired-write-history-missing'test case blocks the case where Write history is absent, which is the safety-relevant direction.- Execution probes not run (working tree unavailable).
- macOS / Windows behavior explicitly out of scope per PR.
Reviewed with AI assistance.
yiliang114
left a comment
There was a problem hiding this comment.
Re-reviewed at 2fbe5a0. The committed-result recovery path is bounded as claimed — canSettleHostedFileHistory re-derives authorization from authority+sink (promptId/turnId, results_ready phase, every item settled, assistant/result parity) and confirmReplacedHostedTurnOwner re-checks promptId/runtimeSessionId/workspaceGeneration plus that the owner is actually replaced; both failures fall through to the guarded acquire(), so I found no way to admit recovery with an unverified precondition, and the retired-owner guard inside acquire() covers the dispatch callers, so a retired Turn cannot dispatch physical work.
Two non-blocking (P2) observations inline: the new admission path skips the workspace-context read that the sibling takeover bypass performs, and the recovery release leaves the cleanup record owed for reconcileHostedTurnCleanup to release a second time. Neither blocks; the second is worth a word from you on the broker's repeat-release behavior.
CI note (not a code finding): on this head two checks are red — Test (ubuntu-latest, Node 22.x) fails in packages/channels/email/src/email-channel.test.ts:355 and Real daemon E2E / Java 11 — both unrelated to this diff, which only touches packages/cli/src/serve.
| bindingId: descriptor.bindingId, | ||
| generation: descriptor.generation, | ||
| }); | ||
| return true; |
There was a problem hiding this comment.
[P2] This physical release is not recorded as confirmed. The new function releases the original owner's {bindingId, generation} and returns true, but leaves the hosted.cleanup event at state: 'owed' (line 156 only reads the state, never commits). reconcileHostedTurnCleanup (line 228+) then re-issues the identical release({ bindingId: descriptor.bindingId, generation: descriptor.generation }) at line 271 once the Turn reaches terminal — the gate at 255-258 (turn.settled with turnId === descriptor.promptId) is satisfied by this same Turn's own settle. If the broker does not treat a repeat release of an already-released binding as released: true, that second call throws Runtime Session release is unconfirmed. and the debt never converges.
The recovery suite only exercises reconcileHostedTurnCleanup's own idempotency (it commits confirmed, so a second call skips), not this cross-path pair. Worth either committing confirmed here, or confirming the broker's repeat-release idempotency.
| this.retiredOwnerResults = true; | ||
| this.cleanupOwed = true; | ||
| this.uncertain = false; | ||
| return; |
There was a problem hiding this comment.
[P2] This return skips the workspace-context read. The sibling takeover bypass a few lines above documents that acquire() is the context slot's writer and compensates for bypassing it:
// The acquire() path this bypasses is the context slot's writer: a
// takeover-built Session holds no text yet, so read once here under
// the same latch. A read failure never blocks the turn.
if (this.context?.read() === undefined && signal)
await this.fetchWorkspaceContext(signal);
return;This new recovery return (setting retiredOwnerResults/cleanupOwed and returning) does not, so a resumed retired Turn whose context slot is still empty is dispatched with no workspace context. Mirroring the sibling's read-once (failure non-blocking) would keep the two bypasses consistent.
…untime replacement Review follow-up for #14265 (#13753 I3). - The G3 step-3 path (#14059) resumes a results_ready checkpoint without reacquiring a retired Runtime owner, but it accepted only hosted-workspace-files/1. A snapshot child's read profile fell through to acquire(), which failed with "Cleanup Runtime owner changed.", so a load driving runtime recovery returned 503. The read profile now takes the same path: its batch is always read_file and glob, the batch that path already resumes without file history. - isHostedWorkspaceSearchProfile is back to the /2 profiles only; approval pre-approves glob through the new isHostedWorkspaceGlobProfile. - HOSTED_WORKSPACE_READ_TOOLS takes read_file by name, not by position. - A team member launched as a snapshot is told only of the isolation the host serves. - The Java profile literal moves to WorkspaceToolProfiles.READ. - Docs: the I3 design and the G3 step-3 recovery note name the read profile.
|
Released in v0.25.2. |
* feat(managed-agent): read-only snapshot children (#13753 I3) A hosted parent can launch a child agent with isolation "snapshot": the child reads a frozen copy of the parent's working tree, taken when it starts, and nothing it does reaches the parent's Workspace. This is the last slice of #13753, and it records as final that serialized sharing needs no value of its own: the storage lease already admits one holder at a time. The copy is a child Workspace prepared as a worktree child's is. The child bound to it gets a new hosted profile, hosted-workspace-read/1, which declares read_file and glob and nothing else, whatever lanes, orchestration or MCP the Session has. The store sets that profile from the row's mode in the transaction that checks the copy is ready, so no caller can bind a copy to a profile that writes; the tool turn refuses every undeclared call before the Broker is acquired. A snapshot's child Workspace records its mode in the request of its child Workspace operation, written once and never rewritten; a request that names none is a worktree's, so worktree rows read exactly as before and no schema change is needed. A snapshot never merges: the relay asks only its discard and holds no settlement for it, the store records a stray merge ask as a discard, and its result commits with no workspace member. A relay that meets a mode it does not serve settles the run never started instead of creating it shared. A snapshot child has no message lane, so send_message refuses it while it runs and a later message continues it as a new snapshot; a team member, which trades messages with its leader, cannot be a snapshot. A separate switch, child-snapshots-enabled (off by default, requires child Workspaces), adds childSnapshots to every hosted create and load; only a Session carrying both flags offers or admits snapshot. A replica from before this change would create a snapshot run as a shared writer, so the switch goes on only after every replica runs this version; the design gives the rollback procedure. The I1 and I2 designs gain notes, and the I2 design's decisions 5 and 8 now name the give-up of an unbound row as the one relay discard of completed work (#13905 item 1). * fix(managed-agent): resume a snapshot child's committed reads after Runtime replacement Review follow-up for #14265 (#13753 I3). - The G3 step-3 path (#14059) resumes a results_ready checkpoint without reacquiring a retired Runtime owner, but it accepted only hosted-workspace-files/1. A snapshot child's read profile fell through to acquire(), which failed with "Cleanup Runtime owner changed.", so a load driving runtime recovery returned 503. The read profile now takes the same path: its batch is always read_file and glob, the batch that path already resumes without file history. - isHostedWorkspaceSearchProfile is back to the /2 profiles only; approval pre-approves glob through the new isHostedWorkspaceGlobProfile. - HOSTED_WORKSPACE_READ_TOOLS takes read_file by name, not by position. - A team member launched as a snapshot is told only of the isolation the host serves. - The Java profile literal moves to WorkspaceToolProfiles.READ. - Docs: the I3 design and the G3 step-3 recovery note name the read profile. * fix(managed-agent): address the second review of snapshot children Pin the new Row.snapshot() accessor in the lock-order audit's exact exemption set, which main's stricter pin turned red after the merge. A running snapshot on a closing Session now gets the closing refusal, so nothing promises a continuation that admission would refuse. The read profile's read_file lookup now throws at module load when the file tools lose read_file; spreading the failed lookup would have declared a tool with no name. Add the tests the review found missing: both sides of the glob predicate, a launch body naming shared, the snapshot flag without child Workspaces, unqualified launches on a snapshot-capable host, the legal boot configuration, and foreground, folded and notified snapshot results carrying no workspace line. Update the design's file inventory, its post-merge lanes and the replaced-Runtime validation wording. * fix(managed-agent): give a snapshot child no skill catalog Main's static Skills put skill instructions into every Session whose agent definition publishes Skills. The read profile declares only read_file and glob, so a snapshot child would be told to use a skill tool it refuses, and an undeclared call fails the Turn. A read-profile Session now drops the catalog once its profile resolves, on create and on load. The design records the exclusion and that a snapshot child still inherits its agent definition's hooks.
What this PR does
A Hosted file Session can resume its saved model request after a trusted host reboot retires the original Runtime, when its native tool results and required file history are already committed. Recovery verifies the original cleanup descriptor and explicit Broker release confirmation, keeps its cleanup debt until the original Turn terminal, and preserves the original tool identities and results. Further physical work requested in that retired Turn fails before acquisition or dispatch and can run in a new Turn in the same Session.
Why it's needed
Recovery previously warmed a replacement Runtime and then tried to acquire the old Turn owner. Comparing the replacement to the old cleanup descriptor produced
Cleanup Runtime owner changed, leaving load at HTTP 503 despite a settled original Edit, committed file history and trusted reboot stop evidence. The fix removes that unnecessary acquisition for the bounded committed-result case while retaining fail-closed handling for missing history, unreadable outcomes, ambiguous release, changed Workspace generation and unsupported profiles.Reviewer Test Plan
How to verify
Run the packaged Linux Harness with a real Java control plane, Broker, durable worker and disposable MySQL. Hold the model continuation after an Edit result and file history commit, force reboot the Linux host, then restore the same Session and saved request. Confirm one original execution/dispatch, unchanged file bytes, original-owner release, model request parity, a successful next-Turn Write/Read on a newer Runtime generation, old-release fencing against its holder, and close that physically stops that new worker and retains history.
Repeat with a Read-only first batch that has no file-history record. Also have the recovered model immediately request a valid Write: it must create no execution or file, the original Turn must settle as a known failure with the Session ACTIVE, and the next Turn must still execute and close. Unknown release responses, corrupt outcomes, missing Write history and Workspace generation drift must remain blocked. Multi-batch results must use the latest assistant message rather than the first accumulated checkpoint item.
Linux build, bundle, typecheck, focused ESLint and 299 tests across the recovery, tool-turn and file-history suites passed. Actual reboot results and exact artifact hashes are recorded in the separate E2E report comment. These are local qualification results; CI is reported separately.
Evidence (Before & After)
Before: a real changed Linux boot retired the old worker and kept its settled Edit receipt, dispatch generation 1 and
xx, but Session load repeatedly returned 503 withCleanup Runtime owner changed. After: the same recovery boundary admits load and drives the exact saved request without replaying Edit, and a fresh next Turn and physical close complete. The immediate new-Write case settles normally as a known failure without side effects and permits the next Turn.Tested on
Environment (optional)
Ubuntu 26.04 arm64 in Lima, Linux 7.0.0-38-generic, Node 22.22.1, OpenJDK 21.0.12.1 and native MySQL 8.4.11. Production main baseline is
07461c0e575f6b61da675538299df78d730b593fplus this fix. The combined Linux acceptance server also includes the independently scoped native-file close fix in #14045. Model inference uses a deterministic local provider fixture; results are persisted through real production services and MySQL.Risk & Scope
hosted-workspace-files/1without Hooks/MCP, a nonempty settled native batch in the current Prompt'sresults_readycheckpoint, assistant/result parity, readable original outcomes, committed Write/Edit history, unchanged Workspace generation and explicit release of the validated original owner. Read/Glob-only batches may lack file history. Cleanup remains owed until the durable Turn terminal.Linked Issues
Related to #12380 and #12952.
中文说明
本 PR 做了什么
可信主机重启使原 Runtime 退役后,只要原生工具结果和所需文件历史已经提交,Hosted 文件 Session 就可以继续已保存的模型请求。恢复校验原 cleanup descriptor 和 Broker 明确的释放确认,将清理债务保留到原 Turn 终态提交,并保留原工具身份与结果。该已退役 Turn 若继续请求物理工作,会在 acquire 或 dispatch 前失败;这些工作可以在同一 Session 的新 Turn 执行。
为什么需要
原恢复路径先 warm 替代 Runtime,再尝试 acquire 旧 Turn 的 owner。替代 Runtime 与旧 cleanup descriptor 比较后报
Cleanup Runtime owner changed,即使原 Edit 已结算、文件历史已提交且可信重启停止证据完整,load 仍返回 HTTP 503。本修复仅在有完整已提交结果的限定场景中去掉不必要的 acquire;历史缺失、结果不可读、释放不明确、Workspace generation 改变和不支持的 profile 仍保持阻塞。评审测试计划
如何验证
在 Linux 上运行打包 Harness、真实 Java 控制面、Broker、durable worker 和可丢弃 MySQL。在 Edit 结果与文件历史提交后暂停模型 continuation,强制重启 Linux 主机,再恢复同一个 Session 与已保存请求。核验原执行与 dispatch 均只有一次、文件字节不变、原 owner 释放、模型请求一致、下一 Turn 在更新的 Runtime generation 上成功 Write/Read、旧释放不能影响新 holder,以及 close 物理停止新 worker 并保留历史。
再次覆盖首次只做 Read、尚无文件历史记录的批次。还要让恢复模型立即请求一个有效 Write:它不得生成执行或文件,原 Turn 必须结算为已知失败而 Session 保持 ACTIVE,下一 Turn 仍可执行并关闭。释放响应未知、结果损坏、Write 历史缺失和 Workspace generation 改变仍须阻塞。多批次结果必须使用最新 assistant 消息,不能取累积 checkpoint 中的第一项。
Linux build、bundle、typecheck、聚焦 ESLint 以及 recovery、tool-turn 和 file-history 三个套件的 299 个测试通过。实际重启结果和精确产物摘要记录在独立 E2E 报告评论中。这些是本地验收结果;CI 单独报告。
证据(修改前后)
修改前:真实变化的 Linux boot 使旧 worker 退役,并保留已结算 Edit 收据、dispatch generation 1 和
xx,但 Session load 持续返回 503,原因为Cleanup Runtime owner changed。修改后:同一恢复边界允许 load,并驱动精确的已保存请求而不重放 Edit,随后新 Turn 和物理 close 都可完成。立即请求新 Write 的场景没有副作用,按已知失败正常结算,并允许下一 Turn。测试平台
环境(可选)
Lima 中的 Ubuntu 26.04 arm64、Linux 7.0.0-38-generic、Node 22.22.1、OpenJDK 21.0.12.1 和原生 MySQL 8.4.11。生产 main 基线为
07461c0e575f6b61da675538299df78d730b593f加本修复。组合 Linux 验收的 server 还包含独立限定范围的原生文件 close 修复 #14045。模型推理采用本地确定性 provider 夹具;结果通过真实生产服务和 MySQL 持久化。风险与范围
hosted-workspace-files/1、当前 Prompt 的results_readycheckpoint 中非空且已结算的原生批次、完整 assistant/result 对应关系、可读原 outcome、已提交 Write/Edit 历史、不变的 Workspace generation,以及经校验原 owner 的明确释放。全 Read/Glob 批次允许没有文件历史。清理仍欠付到持久 Turn 终态提交。关联议题
关联 #12380 和 #12952。