#12952·qwen-code

feat(managed-agent): Stage G authoritative Session history, writer fencing and takeover

Author: wenshaoCreated Sep 28, 2026Updated Sep 30, 2026
Labelspriority/P2type/feature-requestcategory/corescope/session-managementroadmap/session-managementroadmap/multi-agentneed-discussiondaemon

What would you like to be added?

A tracker for Stage G of #12380 — "Externalize authoritative Session history/checkpoints; prove writer fencing and takeover before removing owner affinity." G has no tracking issue and no claim, while B, D, FG6 and H each have one (#12737, #12867, #12872, #12827). This issue defines G's slices and exit checks, and states precisely which parts are already delivered so nobody rebuilds them.

Current state — 2026-09-28

Stage G has one slice delivered under its own label — #12693, listed in #12380's table as "Stage G (with B parts)", the TypeScript durable Managed Session authority — and beyond it the stage is not greenfield either. Verified on main:

Already exists on the Managed path

  • packages/core/src/managed-runtime/managed-session-storage.ts — the ManagedSessionJournalStore interface, whose ManagedSessionCommitReceipt carries transactionId / commandId / operation / firstSequence / lastSequence / committedSequence / replayed, and whose ManagedSessionActivationState carries activationId / epoch / workerId / phase / expiresAt / renewalSeq / installRef. Writer fencing at the Managed-session level is therefore already structural, not something G has to invent.
  • packages/core/src/managed-runtime/http-managed-session-store.ts — an HTTP-backed implementation, consumed by packages/cli/src/serve/hosted-harness-session.ts:281. createHttpManagedSessionStores returns { journalStore, resourceStore, close }, where journalStore is an HttpManagedSessionJournalStore implements ManagedSessionJournalStore posting to ${baseUrl}/internal/managed-session-store/v1/sessions/{sessionId}. On the Java side the migrations create real qwen_managed_session_journal_head and qwen_managed_session_journal_tx tables. Authoritative Session history for the Hosted path is therefore already externalized to the Java/MySQL Session Store — G does not need to extract it.
  • packages/core/src/managed-runtime/local-jsonl-managed-session-journal-store.ts — the local implementation, whose own header calls it "Local-file implementation retained for standalone CLI and development", and which takes an optional SessionWriterLease.
  • packages/core/src/services/session-writer-lease.ts — SessionWriterLease with LOCK_SCHEMA_VERSION = 2 and MANAGED_LOCK_SCHEMA_VERSION = 3, boot-id and pid-namespace liveness (readLocalBootId, readPidNamespaceId), verifiable-inode file identity, and transcript hash/append under O_NOFOLLOW | O_NONBLOCK. Landed via #10924 (mandatory writer fences) and #11207 (concurrent standalone daemons with session fencing); designs at docs/design/session-writer-lease-p0a.md and docs/design/daemon-session-maintenance-writer-lease.md.
  • managed-session-authority.ts, managed-session-record-sink.ts, managed-session-assembly.ts, and on the Java side a ManagedSessionStore whose fencesWritersAndReplaysExactTransactions is covered in ManagedSessionStoreIntegrationTest.

Already proven end to end

npm run test:e2e:managed-session-failover uses a local fake model, completes one Turn, kills the Spring and Hosted Harness process trees, deletes their old local homes, starts replacement owners against the same MySQL store, and verifies the second Turn sees the first Turn's prompt and answer. So durable-owner takeover across process loss plus home deletion is a running, deterministic check today.

What is actually missing

  1. In-flight and continuation takeover. --inflight-failover and --continuation-failover still hardcode a not-yet-enabled throw in scripts/run-managed-agent-server-e2e.ts. The throw's stated reason is now stale — it blames "the Hosted Harness no-tool slice (#12713) refuses every tool call by design", but tool-capable Hosted turns did land (#12831 Workspace file tools 2026-09-27, #12848 foreground Shell 2026-09-28). The gate is still load-bearing, for a different reason: those turns are reachable only on a private path. toolProfile is read from the Harness's own session-create body (packages/cli/src/serve/hosted-harness-session.ts:243, restricted to hosted-workspace-files/1 / hosted-workspace-shell/1), and on the Java side it appears only in test code — HostedWorkspaceToolTurnIT.java:184 sets it by hand and drives the session through insertWorkspaceSessionCommand plus an EmbeddedRuntimeBroker bean, bypassing the public REST route. packages/sdk-java/managed-agent-server/src/main contains no reference to a tool profile at all. The E2E runner creates its sessions through the public POST /v1/agents/sessions with only agent_id / input / metadata, so it gets a no-tool session and the mode would fail exactly as the throw describes. This matches the boundaries #12754 and #12797 recorded: public bound-turn execution and capability broadcast stay closed.
  2. Takeover-time reconciliation scans. #12655 landed RuntimeBrokerService.reconcileExecution and RuntimeTransport.status, but listed takeover scans as out of scope and named this stage as the thing that would fence a stale record: an execution left IN_FLIGHT by a dead Broker stays there "until one of these fences it as UNKNOWN: a same-key retry, a cancel, or the Stage G takeover scan." Nothing scans today.
  3. Removing owner affinity. Cold restore still reads the persisted owner and refuses with session_execution_engine_unavailable (packages/cli/src/acp-integration/acpAgent.ts:1105) when no engine can run it. --session-failover starts a replacement owner deliberately; no path yet lets an arbitrary Harness pick a Session up. The proposal makes this the stage's exit, gated on proving fencing and takeover first.

Proposed slices

Slice Deliverable Exit check
G0 — public admission for a tool-capable Hosted Session Prerequisite for G1, and currently the real blocker behind the stale gate message. Let a Session created through the public POST /v1/agents/sessions select a tool profile and reach a Broker, instead of only the private path that HostedWorkspaceToolTurnIT drives by hand. This is the "public bound-turn execution" that #12754 and #12797 both left closed, so it may belong to the D or W line rather than to G — see question 6. A session created through the public route with a Workspace binding runs one Read/Write/Edit or foreground-Shell turn end to end, with no test code setting toolProfile and no embedded Broker bean.
G1 — ungate in-flight and continuation failover After G0: remove the not-yet-enabled throw, correct its now-inaccurate reason, make both modes runnable against the packaged stack, and wire them into the Hosted MySQL CI job. Update the README, which currently documents both as "gated: exits not-yet-enabled". The in-flight mode holds the first Broker :start after the Harness has durably committed its await_runtime checkpoint, kills both process trees, deletes their homes, and the replacement owner reuses the original executionCallId, executes the physical tool exactly once, continues the original Prompt without replay, and commits one public terminal event. The continuation mode kills the Harness after the first published text chunk and checks one tool execution, one further continuation, only the replacement's answer in the public transcript, and one terminal event. Deleting either assertion must fail its mode.
G2 — takeover reconciliation scan The scan a replacement owner runs at adoption: enumerate unsettled executions for the Sessions it is taking over, resolve each through the original Runtime generation's status, and settle or block. Bounded and resumable. An execution whose original generation answers settled with a valid result settles without executing, claiming or fencing a dispatch. One whose generation cannot answer stays blocked and is never replayed. A scan interrupted mid-batch resumes without re-resolving what it already settled.
G3 — replaceable Harness, owner affinity removed Let any Harness of the correct engine serve a Session, after fencing and takeover are proven by G1 and G2. Keep the typed refusal for a Session whose engine genuinely cannot run it. Two successive owners serve one Session with no operator-chosen affinity. A fenced former owner cannot mutate the newer binding or its journal. A Session with no runnable engine still fails closed with session_execution_engine_unavailable, and a Managed failure still causes no Legacy replay.

Order: G0 first, because G1 cannot run without it — and G0 may turn out to belong to the D or W line, which is worth settling before anyone claims it. G2 can start independently of G0/G1, since it is Broker-side and needs no tool-capable public session. G3 last, because removing affinity without a proven takeover scan turns every crash into an unreconciled UNKNOWN.

Out of scope

  • #11868 (externalize the event/journal core to the data plane). The proposal says it "aligns with stage G's authoritative Session storage, which is distinct from Java's public event/Item projection". It targets packages/acp-bridge/src/eventBus.ts (1,320 lines), compactionEngine.ts (1,430), transcript-replay.ts (2,196) and prompt-ledger.ts (276) — the ordinary/Legacy path, 5,222 lines in process. Its driver is capacity and data residency, not takeover. Completing #11868 does not complete G, and completing G does not complete #11868.
  • #12670 (an execution in flight at host reboot pins the LOST binding forever) and #12766 (a restarted Broker can neither adopt nor retire a local-process worker). Runtime-level, tracked separately, addressed by the W0e line (#12839 merged, #12865 and #12869 in draft).
  • #12740 (Hosted Harness lifecycle and recovery), whose six checkboxes cover prompt-admission failure, attachment shutdown/restart, resource bounds, durable prompt idempotency, deadline classification and per-turn cost. Some are G prerequisites; none is a G slice.
  • The ordinary-host Managed engine's own storage. It still uses the local JSONL store, and #12920 proposes deferring M2/M4–M6 behind Hosted — see question 1.
  • Multi-instance Java control plane and Kubernetes provisioning. #12692 lists Kubernetes provisioning as not validated and out of scope, and no merged slice claims multi-instance operation.

Questions before implementation

  1. Does G cover only the Hosted path? The ordinary-host Managed engine still uses local-jsonl-managed-session-journal-store.ts, and #12920 proposes deferring M2/M4–M6 behind the first Hosted slice. If that deferral holds, G3's "any Harness" means any Hosted Harness, and the ordinary path keeps local storage plus owner affinity. This needs settling before G3 is scoped, and #12920 is not merged yet (its only change request is an automated review note about a formatting check that could not run, not a maintainer objection).
  2. Is --session-failover sufficient proof of writer fencing, or does G need a fencing-specific gate? The existing mode proves a replacement owner can resume; it does not prove a concurrent former owner is refused. G3's exit check assumes the latter is gated somewhere — if it is not, that gate is part of G3, not a prerequisite.
  3. Does G3 depend on multi-instance work that is explicitly out of scope today? Removing owner affinity is only meaningful if a second Harness can be reached. #12692 leaves Kubernetes provisioning unvalidated and nothing merged claims multi-instance operation, so "any Harness" may in practice mean "any Harness on one host". If so, G3 should say that rather than imply cross-host takeover.
  4. Should G2's scan run only at adoption, or also periodically? #12655 named startup and takeover. A periodic scan is a policy decision with a cost, and an on-demand-only reconciler leaves an UNKNOWN execution blocked until someone asks.
  5. Who owns G? B, D, FG6 and H each have a tracker and a claim (#12737, #12867, #12872, #12827). G has neither, and it is currently used as a deferral bucket: #12380's own table defers Turn takeover to Stage G in at least three rows (#12839's "Stage G Turn takeover stays separate", and the W0e-2 and W0e-3 rows that list Hosted Turn takeover and continuation as out of scope), and #12655 named a Stage G takeover scan as the thing that would fence a stale IN_FLIGHT record.
  6. Does G own G0, or does the D/W line? Public admission for a tool-capable Hosted Session is a prerequisite for G1, but it is also exactly what #12754 ("公开的绑定轮次/生命周期门与能力广播保持关闭") and #12797 ("有绑定的会话仍不能执行消息") recorded as their deferred boundary. If D or W claims it, G1 simply waits on that slice and G shrinks to G2+G3. If nobody claims it, G1 is blocked indefinitely by a gate whose stated reason no longer matches reality. Either way it needs an owner, and today it has none.

Why is this needed?

Without a tracker, G behaves as a bucket that other slices defer into while nothing schedules out of it. Two concrete consequences are already visible:

  • The --inflight-failover and --continuation-failover modes have been gated since #12801 made them exit immediately, and no CI job runs either — the three test:e2e:managed-*-failover scripts exist only in package.json. The gate's stated reason is now inaccurate, which is worse than no message at all: it points a reader at the no-tool slice, when the actual blocker is that the public route cannot select a tool profile. Because no issue owns this, the inaccurate reason has survived the two PRs that made it outdated, and the proposal's acceptance criteria for process loss still have no runnable proof.
  • #12655 shipped an on-demand reconciler and explicitly parked startup/takeover scans in "stage G". With no tracker, that parking has no exit condition, so an UNKNOWN execution stays blocked until a caller happens to poll it.

G is also the stage the proposal puts last for a reason: it is the one that lets a Session outlive its process. Everything merged so far — durable owner records, writer leases, HTTP-backed journals, fenced repositories, the --session-failover proof — was built to make G3 safe rather than to defer it. Recording what already exists is what makes G2 and G3, the two slices that are genuinely G's, small enough to claim; and G0 needs an owner whoever ends up holding it.

中文

希望增加什么

为 #12380 的 G 阶段建一个跟踪 issue —— 「外置权威 Session 历史/checkpoint;先证明 writer fencing 和 takeover,再取消 owner 粘性」。G 既没有跟踪 issue、也没有人认领,而 B、D、FG6、H 各自都有(#12737、#12867、#12872、#12827)。本 issue 定义 G 的切片与退出检查,并写清哪些部分已经交付,免得有人重做。

当前状态 — 2026-09-28

G 阶段只有一个以自己名义交付的切片 —— #12693,在 #12380 的状态表里标为「Stage G (with B parts)」,即 TypeScript 的持久 Managed Session authority —— 除此之外它也不是空地。以下均在 main 上核实:

Managed 路径上已经存在的

  • packages/core/src/managed-runtime/managed-session-storage.ts —— ManagedSessionJournalStore 接口,其 ManagedSessionCommitReceipt 带 transactionId / commandId / operation / firstSequence / lastSequence / committedSequence / replayed,其 ManagedSessionActivationState 带 activationId / epoch / workerId / phase / expiresAt / renewalSeq / installRef。也就是说,Managed 会话层面的 writer fencing 已经是结构性的,不需要 G 去发明。
  • packages/core/src/managed-runtime/http-managed-session-store.ts —— HTTP 实现,由 packages/cli/src/serve/hosted-harness-session.ts:281 使用。createHttpManagedSessionStores 返回 { journalStore, resourceStore, close },其中 journalStore 是一个 HttpManagedSessionJournalStore implements ManagedSessionJournalStore,POST 到 ${baseUrl}/internal/managed-session-store/v1/sessions/{sessionId}。Java 侧的迁移建出了真实的 qwen_managed_session_journal_head 与 qwen_managed_session_journal_tx 两张表。所以 Hosted 路径的权威 Session 历史已经外置到 Java/MySQL 的 Session Store —— G 不需要再去「抽取」它。
  • packages/core/src/managed-runtime/local-jsonl-managed-session-journal-store.ts —— 本地实现,其文件头自述为「Local-file implementation retained for standalone CLI and development」,并接受一个可选的 SessionWriterLease。
  • packages/core/src/services/session-writer-lease.ts —— SessionWriterLease,含 LOCK_SCHEMA_VERSION = 2 与 MANAGED_LOCK_SCHEMA_VERSION = 3、boot-id 与 pid-namespace 存活判断(readLocalBootId、readPidNamespaceId)、可验证 inode 的文件身份,以及在 O_NOFOLLOW | O_NONBLOCK 下的 transcript 哈希与追加。由 #10924(强制 writer fence)与 #11207(带会话 fencing 的并发 standalone daemon)落地;设计见 docs/design/session-writer-lease-p0a.md 与 docs/design/daemon-session-maintenance-writer-lease.md。
  • managed-session-authority.ts、managed-session-record-sink.ts、managed-session-assembly.ts;Java 侧的 ManagedSessionStore,其 fencesWritersAndReplaysExactTransactions 在 ManagedSessionStoreIntegrationTest 中有覆盖。

已经被端到端证明的

npm run test:e2e:managed-session-failover 用本地假模型跑完一个 Turn,杀掉 Spring 与 Hosted Harness 两棵进程树、删掉它们原有的本地 home,再对同一个 MySQL store 启动替代 owner,并验证第二个 Turn 能看到第一个 Turn 的 prompt 与回答。所以「进程丢失 + home 被删之后的持久 owner 接管」今天就是一个可跑的确定性检查。

真正缺的

  1. in-flight 与 continuation 接管。 --inflight-failover 与 --continuation-failover 在 scripts/run-managed-agent-server-e2e.ts 里仍硬编码抛 not-yet-enabled。这个 throw 写的理由已经过期 —— 它归咎于「the Hosted Harness no-tool slice (#12713) refuses every tool call by design」,但可带工具的 Hosted 轮次确实已经落地(#12831 Workspace 文件工具 2026-09-27、#12848 前台 Shell 2026-09-28)。可门禁本身仍然有效,只是原因变了: 那些轮次只能从一条私有路径到达。toolProfile 是从 Harness 自己的建会话请求体里读的(packages/cli/src/serve/hosted-harness-session.ts:243,且限定为 hosted-workspace-files/1 / hosted-workspace-shell/1),而在 Java 侧它只出现在测试代码里 —— HostedWorkspaceToolTurnIT.java:184 手工设定它,并经 insertWorkspaceSessionCommand 加一个 EmbeddedRuntimeBroker bean 驱动会话,绕开公开 REST 路由。packages/sdk-java/managed-agent-server/src/main 里对工具 profile 的引用是零。E2E runner 是经公开的 POST /v1/agents/sessions 建会话的,body 只有 agent_id / input / metadata,因此拿到的是一个无工具会话,模式会恰好按 throw 描述的那样失败。这与 #12754、#12797 记录的边界一致:公开的绑定轮次执行与能力广播仍然关闭。
  2. 接管时对账扫描。 #12655 落地了 RuntimeBrokerService.reconcileExecution 与 RuntimeTransport.status,但把 takeover 扫描列为不在范围内,并点名本阶段就是那个会给陈旧记录上栅栏的东西:一个被死掉的 Broker 留在 IN_FLIGHT 的执行会一直停在那里,「until one of these fences it as UNKNOWN: a same-key retry, a cancel, or the Stage G takeover scan」。今天没有任何扫描。
  3. 取消 owner 粘性。 冷恢复仍然读持久化的 owner,在没有引擎能跑它时以 session_execution_engine_unavailable 拒绝(packages/cli/src/acp-integration/acpAgent.ts:1105)。--session-failover 是刻意启动一个替代 owner;今天没有任何路径让一个任意 Harness 把会话接过去。提案把这一条作为本阶段的退出门槛,并要求先证明 fencing 与 takeover。

拆分

切片 交付物 退出检查
G0 — 可带工具的 Hosted 会话的公开准入 G1 的前置,也是那道过期门禁信息背后真正的阻塞。让一个经公开 POST /v1/agents/sessions 创建的会话能够选择工具 profile 并接到 Broker,而不是只能走 HostedWorkspaceToolTurnIT 手工驱动的那条私有路径。这正是 #12754 与 #12797 都留着没开的「公开的绑定轮次执行」,所以它可能属于 D 线或 W 线而不是 G —— 见问题 6。 一个经公开路由创建、带 Workspace 绑定的会话能端到端跑完一次 Read/Write/Edit 或前台 Shell 轮次,且没有测试代码去设 toolProfile、没有 embedded Broker bean。
G1 — 解禁 in-flight 与 continuation failover 在 G0 之后:拆掉 not-yet-enabled throw、改正它现已不准确的理由,让两个模式都能在打包后的栈上跑,并接进 Hosted MySQL 的 CI 任务。同时更新 README —— 它现在把两者都写成「gated: exits not-yet-enabled」。 in-flight 模式在 Harness 已持久提交 await_runtime checkpoint 之后扣住第一个 Broker :start,杀掉两棵进程树、删掉它们的 home,替代 owner 复用原 executionCallId、只执行一次物理工具、不重放地续接原 Prompt,并提交一个公开终态事件。continuation 模式在 continuation 写出第一段公开文本后强杀 Harness,检查工具只执行一次、替代方再发一次 continuation、公开记录只保留替代方的回答、Turn 只有一个终态事件。删掉任一断言都必须让该模式失败。
G2 — 接管时对账扫描 替代 owner 在接管时跑的扫描:枚举它要接管的会话里未结算的执行,逐个经原 Runtime 代数的 status 解决,然后结算或阻塞。有界、可续。 原代数带着有效结果回答 settled 的执行会被结算,且不执行、不 claim、不 fence 任何派发。原代数无法回答的保持阻塞、绝不重放。批次中途被打断的扫描可以续跑,且不重复解决已结算的部分。
G3 — Harness 可替换,取消 owner 粘性 在 G1、G2 证明 fencing 与 takeover 之后,让正确引擎的任意 Harness 都能服务一个会话;对确实没有引擎能跑的会话保留那个类型化拒绝。 两个先后接手的 owner 服务同一个会话,且不依赖运维选定粘性。被 fence 掉的前 owner 无法改动更新的绑定或其 journal。没有可运行引擎的会话仍以 session_execution_engine_unavailable fail closed,且 Managed 失败仍不会导致 Legacy 重放。

顺序:G0 最先,因为没有它 G1 根本跑不起来 —— 而 G0 有可能属于 D 线或 W 线,这一点值得在有人认领之前先定。G2 可以独立于 G0/G1 开工,因为它在 Broker 侧,不需要可带工具的公开会话。G3 最后,因为没有经过证明的接管扫描就取消粘性,会让每