Repository navigation
feat(trajectory): record native tool execution lifecycles - #13836
Conversation
E2E test report / E2E 验收报告All six scenarios passed on macOS with Node 24.14.1, an isolated QWEN_HOME/runtime/workspace, and a controlled local OpenAI-compatible provider. The daemon, ACP transport, SDK, read/shell tools, and native agents were real; provider responses were fixtures. This does not establish commercial model behavior, deployment, or hosted CI results. 六个场景全部通过。环境为 macOS、Node 24.14.1、隔离 QWEN_HOME/runtime/工作区及受控本地 OpenAI-compatible provider。Daemon、ACP、SDK、read/shell 工具和原生代理真实执行,provider 响应为 fixture。该结果不代表商业模型、部署或托管 CI 验证。
The 21 lifecycle frames matched complete ownership and payload across live transport, disk, and replay. SDK terminal states matched. Every recorded frame was checked with timing enabled and disabled; every live frame was checked against normalization and the existing transcript store so it did not modify tool cards. 21 个生命周期帧的完整归属与 payload 在实时、落盘和回放三层一致,SDK 终态一致。每个落盘帧都检查了 timing 开关,每个实时帧都检查了 normalizer 与既有 transcript store,未改变工具卡片。 The native concurrency case executed two parent agent calls and two child reads. Two later child calls reused provider IDs and were rejected by existing duplicate-call protection; their lifecycle state was not_started/error. They are occurrences, not additional executions. Parent replay used transcript pages; child replay used the SDK subagent snapshot. Child transcript pagination is not covered: the existing virtual child endpoint returns 404. 原生并发场景实际执行两个父 agent 调用和两个 child read。Child 后续两次重用 provider ID 的调用被既有去重保护拒绝,生命周期为 not_started/error,不能计为执行。父会话使用 transcript 分页回放;子会话使用 SDK 子会话快照。子会话分页未覆盖,现有虚拟子会话端点返回 404。 Build artifacts used for final verification / 最终验收构建 SHA256:
The 47 submitted source files were checked against the final source SHA256 manifest before commit and again after the commit hooks. Fixture provider and daemon processes were cleaned up. No visible UI changed, so before/after screenshots are not applicable. 47 个提交源文件在提交前与提交 hook 后均核对了最终源 SHA256 清单。测试自有 provider 和 daemon 进程已清理。本次没有可见 UI 变化,不适用前后截图。 Acceptance fix verification / 验收修复复测Updated head: 更新提交: |
🩺 serve daemon A/BBuilt the PR base vs this PR head
|
| field | PR base (before) | this PR (after) |
|---|---|---|
activeWorkStaleMs |
6 |
5 |
— Qwen Code · serve A/B
|
Thanks for the PR! Template looks good ✓ — every required heading is present, and the Risk & Scope section is unusually honest about what was not validated. Problem: grounded, not theoretical. The trajectory surface already ships in Direction: aligned. This mirrors an existing, accepted pattern in the repo — Size: 2709 changed lines across 47 files and 6 packages, breaking down as 1070 production lines / 27 files (410 of those on core paths), 1639 test lines / 20 files, 0 generated/schema. Core paths and a cross-package span both trip the Stage 0 gate, but this is a Approach: the producer side and the compatibility guards feel correctly scoped — I could not find a consumer you missed. My one scope question is the SDK reducer. Risk: Stage 1e matched — Moving on to code review. 🔍 中文说明感谢贡献! 模板完整 ✓ —— 所有必需小节齐全,Risk & Scope 对"未验证内容"的说明相当坦诚。 问题: 真实存在,不是理论性加固。轨迹视图已经在 方向: 对齐。这个做法与仓库中已被接受的既有模式一致 —— 规模: 47 个文件、6 个 package、共 2709 行改动,其中 生产代码 1070 行 / 27 文件(核心路径 410 行)、测试 1639 行 / 20 文件、生成/schema 0 行。核心路径与跨 package 都触发了 Stage 0 门槛,但这是 方案: 生产者侧与兼容性防护的范围划分是合理的 —— 我没有找到你漏掉的消费者。唯一的范围疑问是 SDK reducer。 风险: Stage 1e 命中 —— 进入代码审查 🔍 — Qwen Code · qwen3.8-max-2026-09-02 Reviewed at |
Code reviewI wrote my own baseline before opening the diff: mint a per-execution UUID at the point the scheduler actually calls The compatibility sweep holds up. That is the load-bearing part of a change that adds a new frame type to three transports, so I did not take it on faith. I enumerated every production consumer independently: all 16 Two things I want to raise, neither a blocker on its own. 1. The 2. Also checked and found fine, so you don't have to re-verify: the sequenceDiagram
participant P1 as CoreToolScheduler
participant P2 as AgentCore
participant P3 as SubAgentTracker
participant P4 as ToolCallEmitter
participant P5 as ChatRecordingService
participant P6 as transcript replay
participant P7 as ACP consumers
Note over P1: approval and preparation happen earlier, outside this window
P1->>P2: onToolExecutionStarted (callId, epoch)
P2->>P2: lifecycle.start mints executionId and freezes startedAt
P2->>P3: TOOL_OUTPUT_UPDATE (empty chunk, lifecycle started)
P3->>P4: emitLifecycle (started)
P4->>P7: tool_call_update with _meta.toolLifecycle, no status and no content
P4->>P5: recordUiTelemetryEvent (tool_lifecycle)
P1->>P1: invocation.execute settles
P1->>P2: onToolExecutionSettled (callId, status, durationMs)
Note over P2: executionDurationMs freezes here, a later hook failure cannot change it
P2->>P3: TOOL_RESULT (lifecycle ended)
P3->>P4: emitLifecycle (ended)
P4->>P7: terminal frame, executionStatus kept separate from outcome
P6->>P7: replay re-emits both frames only when includeTiming is set
Files changed (30 of 47 shown)
Test evidenceThis is an unattended CI run, so per the gate rules I did not build, run, or execute anything from this PR — the evidence below is the PR's own CI, read through the API for commit I have not re-run your numbers. The 597 AgentCore/scheduler/lifecycle regressions, the 1300-test CLI run, the 72/72 emitter suite and the six controlled-provider E2E scenarios are your claims, not evidence I verified — and the six outdated late-update assertions you found and corrected are exactly the kind of thing that only a full suite run would surface, which is still in flight. Final CI results for
One row per check name (latest run); skipped checks omitted; failures sort first. / 每个检查名一行(取最新一次运行),省略 skipped,失败项排在最前。 Not verified: whether the late post-cancellation tool card from finding 1 actually renders in a client. That is the one claim here that neither the diff nor the suite settles, and your own test detaches the listener before it fires. Sandboxed verification would settle it: Real-scenario tmux testing: N/A — unattended CI run, and the gate forbids executing PR-derived code here. Live behaviour belongs to the isolated 中文说明代码审查 在读 diff 之前我先写了自己的基线方案:在调度器真正调用 兼容性排查站得住脚。 这是给三种传输新增帧类型时最关键的部分,所以我没有采信而是自己核了一遍:我独立枚举了全部 16 处 有两点要提,单独看都不是拦截项。 1. 2. 以下我也查过、确认没问题,你不必重复验证: 测试证据 这是无人值守的 CI 运行,按门槛规则我没有构建、运行或执行本 PR 的任何代码 —— 下面的证据来自 PR 自己的 CI,通过 API 读取 commit 我没有复跑你的数字。597 项 AgentCore/scheduler/lifecycle 回归、1300 项 CLI 测试、72/72 emitter 套件、六个受控 provider E2E 场景,都是你的声明,不是我验证过的证据 —— 而你发现并修正的那六条过期的 late-update 断言,恰恰是只有完整套件跑一遍才会暴露的东西,而它还在跑。 未验证:finding 1 中那张取消后的迟到工具卡片是否真的会在客户端渲染出来。 这是本 PR 中唯一一个 diff 和测试套件都无法定论的主张,而你自己的测试在它触发前就摘掉了监听。沙箱验证可以定论: 真实场景 tmux 测试:N/A —— 无人值守 CI 运行,且门槛规则禁止在此执行 PR 派生代码。实时行为应由上面那个隔离的 — Qwen Code · qwen3.8-max-2026-09-02 Reviewed at |
|
Confidence: 3/5 — the design and the compatibility work are genuinely solid, but I have one cancellation-behaviour question I cannot resolve from the diff, and the suite that would surface it is still running. Stepping back: this is not a PR I'm approving because I ran out of objections. The hard part of adding a frame type to three transports is proving that nothing else renders it, and that proof holds — I enumerated the consumers myself rather than trusting the diff, and every unguarded one is inert by construction. The What keeps me at 3 rather than 4 is finding 1 in Stage 2. Relaxing the abort guard in The secondary reason is simply timing: @qqqys you own ⏸️ Not approving on this run. 中文说明Confidence: 3/5 —— 设计与兼容性工作确实扎实,但我有一个从 diff 无法定论的取消行为疑问,而能暴露它的测试套件还在跑。 退一步看:这不是一个"因为找不到反对理由所以批准"的 PR。给三种传输新增帧类型,最难的部分是证明其它地方都不会渲染它,而这个证明成立 —— 消费者是我自己枚举核实的,不是采信 diff,每一处未加防护的都在结构上必然无效。 让我停在 3 分而不是 4 分的,是 Stage 2 的 finding 1。放宽 次要原因就是时机: @qqqys 你是 ⏸️ 本次运行不予批准。 — Qwen Code · qwen3.8-max-2026-09-02 Reviewed at |
chiga0
left a comment
There was a problem hiding this comment.
Review — feat(trajectory): record native tool execution lifecycles
Tier: Deep (new persisted telemetry format, concurrency + lifecycle state machine, cross-package contract)
Verdict: APPROVE — no blockers. One minor finding rides along.
What was checked
| Dimension | Result |
|---|---|
| Core state machine (start/finish idempotency, ended flag) | ✅ clean |
| Dual-finish race (onToolExecutionSettled vs TOOL_RESULT handler) | ✅ clean |
| Clock-skew guard (Math.max(startedAt ?? 0, Date.now())) | ✅ clean |
| Drain timer logic (TOOL_LIFECYCLE_DRAIN_MS, drainTimer.unref()) | ✅ clean |
| Consumer frame exclusion (event.name === 'tool_lifecycle') | ✅ clean |
| Wire-bridge frame exclusion (meta.toolLifecycle + !status + !content) | ✅ clean |
| Fork session remap (sessionId updated, no promptId remap for tool events) | ✅ clean |
| SDK type contract vs core type (3-variant discriminated union) | ✅ symmetric |
| SubAgentTracker toolKey uniqueness ([subagentId, round, callId]) | ✅ clean |
| LRU eviction in reduceToolLifecycle | ✅ correct |
| Approval refused path (Session.ts + agent-core.ts: finish('error','not_started')) | ✅ clean |
| persist: false path (transcript writer receives events via emitter, not direct DB) | ✅ clean |
Dual-finish race resolution
The interaction between onToolExecutionSettled and the TOOL_RESULT batch handler is correct:
- Normal flow:
onToolExecutionSettledrecords results but skips finish (emittedCallIds.has = false) → TOOL_RESULT handler calls finish with execution info. - Cancellation-while-running: TOOL_RESULT emitted first → handler sees
startedLifecycles.has && !execution, skips finish, adds to emittedCallIds →onToolExecutionSettledsees emittedCallIds.has = true, callsfinish('cancelled', status, durationMs). - Guard in tool-lifecycle.ts:
if (ended) return undefinedmakes all subsequent finish() calls no-ops regardless of race order.
R1-1 (minor) — recordedLifecycle FIFO eviction breaks dedup past 256 tool calls
The dedup set evicts the oldest key once it exceeds 512 entries. Since each execution produces two keys (uuid:started and uuid:ended), the limit is effectively 256 complete tool executions per session. Past that point, a re-delivered started event (e.g. from a replay or transport retry) for an evicted execution would pass the has() check and be double-appended to the JSONL transcript.
This doesn't affect drain correctness — pendingLifecycle is a separate Set and is never evicted. The risk is low for typical sessions, but the 512 cap and TOOL_LIFECYCLE_DRAIN_MS are uncoordinated: a 30-second drain window could stay open through more than 512 events in a high-throughput subagent scenario.
Suggestion: Track dedup by executionId only (one entry per execution, removed on ended) rather than per phase, which halves the effective entry count and makes the cleanup natural.
Informational — normalizer.ts applies stricter lifecycle-frame filter
All other lifecycle-frame consumers (sse.ts, compactionEngine.ts, channel bridges) check two conditions to skip: meta.toolLifecycle && !status && !content. The normalizer adds !title && !kind — a superset that's slightly more conservative and avoids discarding a tool_call_update that coincidentally carries both a lifecycle token and real display content. This is a positive divergence, not a bug.
| if (event.phase === 'started') pendingLifecycle.add(event.executionId); | ||
| else pendingLifecycle.delete(event.executionId); | ||
| if (recordedLifecycle.size > 512) | ||
| recordedLifecycle.delete(recordedLifecycle.values().next().value!); |
There was a problem hiding this comment.
R1-1 (minor): FIFO eviction at 512 entries can break phase-level dedup past 256 complete tool executions in a session. A re-delivered started event for an evicted execution would pass the has() check and be appended twice to the JSONL transcript.
The pendingLifecycle Set (which governs drain correctness) is separate and unaffected. The practical risk is low for typical sessions, but the 512 cap and 30-second drain window are uncoordinated.
Suggestion: Track by executionId only (remove on ended phase) rather than by executionId:phase, halving the effective slot usage and making cleanup self-evident.
yiliang114
left a comment
There was a problem hiding this comment.
Approving — CI is green on 6f294b3 (the ubuntu test run that was still in flight during triage has since passed), and the one open question from the triage review resolves in this PR's favor.
On the relaxed abort guard in SubAgentTracker.createToolResultHandler (abortSignal.aborted && !this.toolStates.has(this.toolKey(event))): I traced the cancel path at this head. Abort fires propagateAbort, but tracker cleanup only runs later via earlyErrorResponse / the normal completion path. In that window a subagent tool that actually completed emits TOOL_RESULT while still tracked, and the relaxed guard lets emitResult close the card exactly once — the key is deleted on first emit, so it cannot render twice, and a call whose TOOL_CALL arrived after abort was never inserted into toolStates at all. Base behavior dropped that result and left the card dangling in_progress for the rest of the transcript. The lifecycle terminal cannot replace this close either: those frames are metadata-only (status/content undefined, pinned by the added test), so the only user-visible card close comes from emitResult. Reads as intended behavior to me, and reverting the guard would reintroduce the dangling card.
Non-blocking: approvalNotified is still keyed by raw callId while toolStates moved to the composite key two lines above — pre-existing and cosmetic (worst case one suppressed "Waiting for permission" progress update on cross-round callId reuse), but worth aligning at some point.
One disclosure: my bounded security pass over the diff (frame parsers / transport surface) failed to produce output, so that dimension is not independently covered by this review. CI Lint & Static is green and the strict frame parsers do reject malformed not_started frames carrying timing fields, but I am not claiming a full security sweep.
|
Released in v0.25.1. |
What this PR does
Records versioned tool execution lifecycle metadata for main tools and native Qwen subagents, persists it with the owning session, and exposes bounded SDK state for live updates and replay. Each admitted call receives an independent execution identity. Approval and preparation remain separate from actual execution; execution duration stops when the actual execution settles, while the final call outcome can still reflect a later hook failure.
The metadata travels independently of existing tool cards and results. Replay, compaction, session recovery, usage accounting, channel bridges, the IDE, and daemon consumers preserve their existing behavior when these frames appear.
Why it's needed
Trajectory timing currently cannot reliably distinguish approval waits from execution, identify repeated call IDs across agents, or preserve a late execution result after cancellation. This provides the execution evidence needed for the next trajectory stages without enabling the live trajectory UI in this PR.
Reviewer Test Plan
Verify that a successful or failed execution has one start and one terminal event, while a refused or rejected call is recorded as not started with no execution duration. Approval waits should not increase execution duration. A successful execution followed by a failing post-hook should retain successful execution status and a failed final outcome.
Verify that repeated provider call IDs across native agents remain independently owned. Cancelling the parent after a child starts should preserve the child's actual terminal event without duplicating tool results. Replayed terminal state should match live SDK state, and metadata should not create cards, messages, or usage entries.
The acceptance fix also covers cancellation after execution has settled but before post-processing completes: the terminal event keeps execution success and final cancellation. The independent counterexample passed after failing on the original head, and all 597 AgentCore, scheduler, and lifecycle-helper regressions passed. Workspace build, bundle, typecheck, changed-file lint/format, and the six controlled-provider E2E scenarios were rerun after the fix.
How to verify
Use a daemon session with SDK lifecycle inspection and timing-enabled transcript replay. Exercise successful reads, missing-file errors, approval refusal, cancellation after execution starts, concurrent native agents, and native child cancellation. Compare live metadata, recorded JSONL, and replay state. With timing disabled, lifecycle replay should be omitted.
Local validation completed on the frozen source submitted here: workspace build and typecheck; changed-file lint, formatting, and diff checks; focused core, CLI, ACP, SDK, channel, IDE, and replay regressions. The broad CLI run passed 1,300 tests and identified six outdated late-update count assertions; those assertions were corrected and the eight relevant cases passed on rerun. The final emitter suite passed 72/72. This is incremental package validation, not a claim that the entire repository test suite passed. The workspace build used an 8 GB Node heap after the root script's 4 GB CLI compilation limit ran out of memory.
Independent E2E ran six scenarios through the real daemon, ACP, SDK, and native tools with an isolated workspace and a controlled local OpenAI-compatible provider. All six passed, with 21 lifecycle frames consistent across live transport, recorded JSONL, and replay. A separate comment gives the scenario counts and evidence boundaries.
Evidence (Before & After)
N/A: this PR changes lifecycle transport and persistence, with no visible UI change. Before, timing could include approval and preparation and could not reliably identify execution occurrences. After, actual execution has independent identity and duration, and rejected calls explicitly remain not started.
Tested on
Environment (optional)
Node 24.14.1, frozen pnpm dependencies, isolated QWEN_HOME and daemon runtime. The provider is a fixture; tools and the daemon/ACP/SDK path are real. No commercial model validation is claimed.
Risk & Scope
Linked Issues
None.
中文说明
本 PR 做了什么
为主工具和原生 Qwen 子代理记录带版本的工具执行生命周期元数据,按所属会话持久化,并提供有界 SDK 状态供实时更新和回放使用。每次接纳的调用有独立执行标识。审批与准备阶段和真实执行分开;执行耗时在真实执行结束时冻结,最终调用结果仍可体现后续 hook 失败。
元数据独立于既有工具卡片和结果传递。回放、压缩、会话恢复、用量统计、channel 桥接、IDE 和 daemon 消费者在收到这些帧时保持既有行为。
为什么需要
现有轨迹计时无法可靠区分审批等待与执行,无法区分跨代理重复 call ID,也无法在取消后保留迟到的真实执行结果。本 PR 为后续轨迹阶段提供执行证据,本次不启用实时轨迹 UI。
评审者测试计划
验证成功或失败的执行各有一次开始和终态事件;审批拒绝或被拒绝的调用记录为未开始,没有执行耗时。审批等待不应增加执行耗时。执行成功但 post-hook 失败时,应同时保留执行成功状态和最终调用失败结果。
验证不同原生代理重复使用 provider call ID 时归属独立。子代理开始后取消父会话,应保留子代理真实终态且不重复工具结果。回放终态应与实时 SDK 状态一致,元数据不应创建卡片、消息或用量记录。
验收修复还覆盖了执行已结算、后置处理尚未完成时取消:终态保留执行成功和最终取消。独立反例在原提交失败、修复后通过;AgentCore、scheduler 和生命周期 helper 的 597 项回归全部通过。修复后重跑了 workspace build、bundle、typecheck、改动文件 lint/格式检查及六个受控 provider E2E 场景。
如何验证
使用 daemon 会话、SDK 生命周期检查和开启 timing 的 transcript 回放。覆盖成功读取、文件不存在错误、审批拒绝、真实执行开始后取消、原生代理并发和原生子代理取消。比较实时元数据、实际 JSONL 和回放状态。关闭 timing 时不应回放生命周期。
本次提交的冻结源代码已完成本地验证:workspace build 与 typecheck;改动文件 lint、格式和 diff 检查;core、CLI、ACP、SDK、channel、IDE 与回放的定向回归。较大范围 CLI 测试通过 1,300 项,并发现六项旧的迟到更新数量断言;修正后相关八项重跑通过。最终 emitter 全文件测试 72/72 通过。这是分包增量验证,不代表全仓测试全部通过。根脚本的 CLI 编译在 4 GB 堆限制下内存不足,随后使用 8 GB Node 堆完成 workspace build。
独立 E2E 在隔离工作区使用受控本地 OpenAI-compatible provider,通过真实 daemon、ACP、SDK 和原生工具执行六个场景,全部通过。21 个生命周期帧在实时传输、实际 JSONL 和回放三层一致。单独评论列出场景数量与证据边界。
证据(前后对比)
不适用:本 PR 修改生命周期传输与持久化,没有可见 UI 变化。之前,计时可能包含审批与准备,不能可靠识别每次执行。之后,真实执行具有独立标识与耗时,被拒绝的调用明确保持未开始。
测试平台
环境(可选)
Node 24.14.1、冻结 pnpm 依赖、隔离 QWEN_HOME 和 daemon runtime。Provider 为 fixture;工具及 daemon/ACP/SDK 链路真实。未宣称商业模型验证。
风险与范围
关联 Issue
无。