Repository navigation
fix(cli): cancel one-shot SIGINT with terminal JSON - #1064
Conversation
613357e to
d208659
Compare
XuPeng-SH
left a comment
There was a problem hiding this comment.
建议 REQUEST_CHANGES。独立审查精确 head d2086596292a9346c572a3355a9c18a0c7516804,base/main 05ce15fbf016b751868cfadeedbceaa499648c90。认证账号为本 PR 作者 XuPeng-SH / 39627130,因此提交有正文的 COMMENT,不作自我批准。
发现 1 项阻塞问题(行内锚点 command_router.rs:2663):SIGINT 后的次级清理失败会覆盖已有 TurnFailure。真实 CLI 对照复现先发送 session_info、部分文本,再发送不同 session identity,在 exact-run cleanup 中发 SIGINT。未注入写失败时,最终 error 保留 server session identity changed within one request;仅对临时 events.jsonl 写入注入 ENOSPC 后,最终 error 只剩 stream-event file write failed: No space left on device (os error 28)。两组均 exit 3、failed/unverified、保留 observed partial、一次 chat、两次对同一 sigint-run 的取消;丢失的是已经观察到的原始 contract violation。2641–2648 的 native shutdown timeout 赋值存在相同覆盖方式(该分支为源码结论,未单独动态复现)。请在已有 Err 上保留原错误及 partial 分类/元数据并追加清理原因,仅在没有原 failure 时构造新 failure,并覆盖实际入口的双重失败回归。
已审查全部 15 个变更文件及真实 command router → turn facade → SSE host → 普通 Bash/file executor → sandbox supervisor、请求 session lease、native shutdown、最终 JSON/持久化调用链。普通 SSE host 安装与 observer 发布的是同一 Arc,查询使用该实例的 effective worktree,native executor 独立检查;未发现这部分把 native 根误当普通执行根或清除 quarantine。Linux 辅助枚举失败后继续原有有界 wait/reap,只有 ECHILD 可成功结算;超时/其他 wait 错误仍不能授权恢复。新成本主要为每请求的 token、增量状态和 executor 引用及既有有界取消 HTTP 调用,没有新增数据库存储路径或全局 session 串行锁。新增信号/阻塞 stdin/ownership 屏障有实际行为收益;上述覆盖错误是当前主要遗漏。
独立验证:
- Rust 1.97.0、locked、正常 debug,CLI build-info 精确为本 head、git_dirty=false;二进制 SHA-256
5cc8526cbc2df7656521e070a23a892dd527fe0f426575843a7ceede21e06f85。 - 8/8 公共 SIGINT 进程测试通过,含持有 stdin、无 run identity、第二次 SIGINT、本地 fence。默认文件系统沙箱把 /tmp 所有者映射为 nobody,导致准入失败;在只读核验真实宿主 /tmp=root:root/1777 后,以相同二进制在宿主重跑,通过且未改断言/协调根检查。
- 原样提取生产 settlement 循环(仅日志宏替身)的 6 项低层回归和 2 项真实 fork/waitpid 故障测试通过。另链接本 head 的生产 astra-sandbox 公共 supervisor 入口,实测 READY → SETTLED_ECHILD → EOF、exit 130,取消约 0.01s,延迟 marker 未发生。
- 上述真实 CLI ENOSPC 对照确认行内问题。产品源码/分支未修改或推送,未访问共享服务、调用付费模型或重跑远端 CI。
变更计数(按测试代码归属计入 cfg(test) 与分隔行,无文件重命名;剔除 params.rs 两行原样移动的说明注释):实现 +442/-112,净 +330;测试 +962/-1,净 +961;文档 +28/-0,净 +28。原始 numstat 分类为实现 +444/-114、测试 +962/-1、文档 +28/-0;等量移动不改变净额。测试删除是原调用被更明确的 options 替换,未删关键断言使之变绿。
提交前重新核验:head/main 未变、open、非 draft、mergeable=true、作者身份一致;全量 reviews/inline/comments/threads 为空,已按本 SHA/原始锚点去重。全分页 check-runs、statuses、workflow runs/jobs 核对当前 head;15 个 required 均来自 GitHub Actions App 15368,13 success,SDK/web 两项为当前 Static Checks workflow 条件及 scope 输出 sdk=false/web=false 所证实的 skip。Static Checks 39156422137、Test Suite 39156422135 成功。required 来源为 main 分支 protection 摘要;直接 protection API 为 integration 403,已读取全量两个 active rulesets 的详情,无额外 required status 规则。
限制:非 required live harness 39156421178 已 failure,18 完成/17 通过;安全摘要指出 missing-child-model negative control 实际先因缺少 /description 被拒绝,未证明模型身份检查发生。相关 schema/用例不在本 PR diff,不能无依据归因本 PR,也不以这项非 required 失败单独阻塞。实现方所报 83 项及 GLM 真服务取消/续跑未全部在本次重复;本次没有在线模型调用。续跑约 8.55s 额外开销仍未归因,不能宣称整体性能已解决。
| if !user_interrupted { | ||
| return Err(error); | ||
| } | ||
| turn_result = crate::cli::turn::turn_cancellation::fabricate_user_cancel_failure( |
There was a problem hiding this comment.
[P2] 次级清理失败不能替换已经观察到的原始 failure
这里在 user_interrupted 时无条件把 turn_result 替换为只含清理错误和增量快照的新 TurnFailure,已有 Err 的 error、failure_kind、error_code/error_metadata 等都会丢失。已用本 head 的真实 CLI 复现:loopback SSE 先绑定 sigint-session/sigint-run 并发送部分文本,再发 changed-session;在其 exact-run cleanup 中发 SIGINT。对照组最终 error 保留 “server session identity changed within one request”,仅给临时 events.jsonl 写入注入 ENOSPC 后,error 只剩 “stream-event file write failed: No space left on device (os error 28)”。两组均只有一次 chat、取消相同 exact run、exit 3/failed/unverified,部分文本仍在,但原始 contract violation 被掩盖。
请保留已有 Err 的原因和 partial 元数据,追加新的清理原因;没有原 failure 时才构造新 failure。2641–2648 的 native shutdown 超时分支也需按同一规则处理。现有保真测试直接调用 settle_one_shot_user_interrupt_result,未经过这里的覆盖赋值;需要补实际入口的双重失败回归。
4d528b1 to
30a5363
Compare
XuPeng-SH
left a comment
There was a problem hiding this comment.
建议 APPROVE。
独立 deep review 的唯一目标为 head c78f26f96d1233fd2d16e481e266e961f5810ad2,base/main 3c7141639dadafae199acb2e40d6424c71b4b0d4。认证身份与作者同为 XuPeng-SH / 39627130,所以提交有正文的 COMMENT 表达批准建议,不作自我 APPROVE。未发现当前完整 PR 中需要阻塞合入的实质问题;此意见不执行合并。
历史问题已重新核实关闭。 review 5564602564 的 原始 P2 锚 位于 d208 的 RIGHT/original_line=2663、original_position=428,现已 outdated。当前 command_router 的 apply_one_shot_cleanup_result / retain_one_shot_interruption_failure 保留已有 Err 的错误正文及完整 partial,只追加 root/native/writer 清理原因;空文本才回填已观察到的增量前缀。独立 cleanup veto 阻止干净 Cancelled、可恢复错误或 stdout closure 在清理失败后被重新升级为成功。native shutdown timeout 使用同一生产边界与原 join future。第一、第二次信号观察延续到 native/writer 清理;第二次信号的 veto 不会被稍后成功的清理抹掉,完成的信号 future 不再重复 poll。writer 的外部 abort handle 保留到结算结束。当前真实进程 ENOSPC 对照覆盖了原缺陷,而非只调用保真 helper。
完整范围与四维审查。 已复审 20 个文件、11 个 PR 提交,以及显式 Chat setup/stdin → Basic CLI facade → 单一 heap-pinned SSE 实现 → ordinary Bash/file executor → sandbox supervisor、captured-owner exact-run cancel、request session lease、native shutdown、event writer、终态 JSON 与 canonical replay 的实际调用链。
- 设计:沿用既有取消、租约和持久化 owner;observer 发布的 Arc 就是普通 SSE host 安装的实例,effective worktree 随该实例变化;native executor 的屏障单独检查。Server execution_settled 不能覆盖本地 ownership_unsettled,未放宽权限、清理 quarantine 或授权自动 replay。
- DB/并发/成本:没有新增 schema、查询实现、存储投影或全局 session 串行锁。新增状态是 request-local 引用、增量证据和信号/负面结算标记;跨 session 的 owner/lease 边界及捕获的认证身份保持。仅 --stdin 增加一个普通读取线程;取消复用已有受绝对 deadline 限制的 HTTP 结算路径,没有新增 per-token 网络调用或独立轮询任务。辅助枚举失败最多继续消耗原有两秒 helper 结算预算,不以空扫描或超时冒充 ECHILD。
- Clean Code:错误合并与 cleanup 观察集中到同一生产 helper,移除 forwarding-only wrapper,没有新增并行生命周期服务;SSE 与 base 的 heap-pinned owner 合并正确,未复制另一套流实现。新增实现承担可观察信号、失败保真及结算职责,新增测试与 CI 具有实际入口/维护收益;净增行数不是独立否决依据。
- Unhappy/boundary:核查未绑定 run、changed session、403/401 owner 边界、第二次信号、root drain、native 超时、writer ENOSPC、partial text、stdout 关闭、活子进程、EINTR/deadline、空/失败子枚举及正常 canonical partial replay。只有 ECHILD 产生正面 Linux helper settlement;失败仍禁止恢复。
独立核验的当前 CI 证据,不继承作者验收计数。 Test Suite 39205482345 / shared CLI job 117907307196 实际执行:
cargo nextest run --locked -p astra-cli --lib --bins --test cli_pipe --test process_supervisor --test shell_execution_boundaries --profile ci
日志明确 Starting 4942、Summary 4942 passed / 20 existing skipped;逐项 PASS 中 cli_pipe=20、process_supervisor=1、shell_execution_boundaries=5,共 26 个公共进程测试,包含 one_shot_sigint_keeps_identity_failure_when_event_writer_also_fails、SIGINT/held stdin/second signal/local fence,以及实际生产 helper 的 daemonized late writer containment。ENOSPC fixture 仅拦截临时 events.jsonl 中的指定 marker,真实 CLI 断言原 identity failure 与 ENOSPC 原因同时保留、text=observed partial、exit 3/failed/unverified、一次 chat、两次同一 exact run 的取消;干净中断则 exit 5 并 replay canonical commit。另 3 个 exact ignored native-supervisor smokes 为独立 strict invocation,日志 3/3 passed,不计入前述 4942 或把其余 skipped 计为通过。
该 job checkout 的 merge commit 4d99434754a71d62aabcc9e06dc15604073fa9f3 的两 parent 精确为上述 main/head,tree 与 c78f 完全相同:8194fcccd8c3a5fdbfb42d2c373016db5b5b8094;本地也验证 main 是 head 的 ancestor。因而当前 hosted 执行证据绑定本次审查源码,未借用旧 d208 二进制。CI 五个 protected CLI labels 依赖同一实际成功的 producer,未出现空成功替代测试或重复五次构建。当前命令的唯一覆盖契约在 test_ci_build_coverage,parallelism 删除的是重复旧命令断言,其 fail-closed producer/result 断言保留。
本地对精确 c78f 执行两个受影响 CI contract 模块:25/25 passed;用内存替换 workflow 文本的 18 个漏 target/过滤/改 profile/package/漏 MCP fixture 反例,18/18 被同一新 contract 拒绝。全 PR whitespace 检查通过,工作区产品代码未改动。未无假设重编译整套 Rust、远端重跑 CI、接触共享服务或调用付费模型。
变更计数(base/main 到 head;测试含 cfg(test) 及其分隔行,CI contract 归 CI,无文件重命名;排除 params.rs 两行原样移动的说明注释):
| 类别 | 新增 | 删除 | 净增 |
|---|---|---|---|
| 实现 | 622 | 126 | 496 |
| 测试 | 1674 | 3 | 1671 |
| 文档 | 42 | 3 | 39 |
| CI/workflow/contracts | 10 | 9 | 1 |
原始分类为实现 +624/-128,其余不变,合计原始 +2350/-143。移动不计为减量;删除的测试行属于 options/既有 helper 调用替换,未删原关键失败断言。CI 删除重复命令断言后,精确 tokenized 命令覆盖保留且已验证反例拒绝。
准入与限制。 开始及提交前重新核验 head/main、open/non-draft/mergeable、身份、required 来源与全分页 check-runs/statuses/runs/jobs、reviews/inline/comments/threads 及已有正文 SHA/原始锚。main 的 protection 摘要给出 15 个 App 15368 required,当前全部实际 success,无 scope skip 替代;直接 protection API 仍为 integration 403,两个 active rulesets 全量读取,无额外 required status 规则。Static Checks 39205482159 成功。当前 optional live harness 39205480880 日志为 18/18 passed,历史失败不沿用。
本次动态 Rust 证据来自独立回读上述当前 GitHub 实际执行记录;未在本地重新运行整套 Rust,也未将 PR 正文中的 4916/405/907、模型审查或作者发布声明直接当成本次独立验收。native shutdown timeout 的测试控制了生产 cleanup owner 的 future,没有声称真实完整 native provider 卡死实验;本 head 没有新做真实 provider 的 SIGINT + 同 session 续跑组合验收,不能把 d208 的历史 GLM 结果或尚未归因的约 8.55s 续跑开销当作当前性能结论。显式 Chat 的范围与 docs 一致,positional shorthand / --print 不扩展到本次 SIGINT 契约。
## Summary Fix the interactive cancellation/admission race reported in #1078. This does not publish a binary or change a running environment. - Retain the original physical response until its first accepted run identity is observed, then settle cancellation of that exact run within the existing ten-second total deadline. Never look up a cancellation target through the Session's active run. - Stop the opted-in SSE consumer at that identity before executing tools or approvals, including events in the same network chunk. Ordinary transport/callback detach still does not authorize Server cancellation. - Preserve visible recovery guidance for unconfirmed cancellation and retain drafts rejected by a busy execution slot. - Address the authenticated-send review finding: resolve credentials before invoking the existing per-attempt payload factory, so cancellation checks, budget refresh and sticky dispatch evidence occur after the asynchronous bearer wait, immediately before sending. Stopping during credential preparation cannot dispatch a new admission or retry; an already dispatched request retains its original response and ambiguous-delivery evidence. Rebased onto upstream `main` at `c08cf4bb2bb0a458d1fd8d923212f12e91b979a7`. The three existing commits replayed without conflicts or patch changes. ## Related issue Closes #1078 Related contracts: #867, #987 and #1064. This addresses explicit interactive cancellation, not automatic cancellation on internal failure. ## Change type - [ ] Feature - [x] Bug fix - [x] Documentation - [ ] Refactor or performance improvement - [x] Test - [ ] Build, CI, or maintenance ## User and compatibility impact Interactive Ctrl+C/TUI cancellation waits for confirmation of the exact admitted run within the existing ten-second budget. A second interrupt may force an unverified exit; that is not presented as confirmed cancellation. Cancellation while admission credentials are pending does not start a new Server execution when they resolve. No Server API, database schema, dependency, release version or configuration changes. Other SSE hosts retain default immediate-cancellation behavior. The existing public ThinClient method signatures are unchanged. No production/QA sessions were modified or cancelled. ## Architecture and complexity delta - Canonical owner changed or extended: the interactive stream owner coordinates drain and exact-run cancellation; shared `SseStreamHost` exposes an opt-in identity-only drain, defaulting to zero. ThinClient's existing authenticated send path owns the final per-attempt preparation boundary. - Existing implementations and callers searched: signal/TUI cancellation, shared SSE ingestion, incremental state, exact-run cancellation and captured auth owner, one-shot cancellation, failure accounting, admission rejection and ThinClient admission/retry callers. - Superseded code, states, tables, shims, or self-only tests removed: the detached interactive cancellation notifier and its one-time run-ID snapshot. No new state machine, table, global registry, Session-lookup fallback or cancellation protocol. - If parallel implementations remain, their boundary and retirement condition: none added. Single-attempt and retry admission share one private authenticated send helper; interactive cancellation reuses `cancel_exact_run_until_settled_with_deadline` and the existing recovery text. ## Verification Current rebased tree, using the canonical macOS temporary directory (`TMPDIR=/private/tmp`): - `cargo test --locked -p astra-cli --lib server_admission_ -- --nocapture`: **37 passed**, including the new real-entry HTTP regression. - `cargo test --locked -p astra-thin-client --lib`: **200 passed**. - `cargo build --locked -p astra-cli --bin mock_mcp_server`: passed; prepares the existing MCP fixture before the complete library inventory. - `cargo nextest run --locked -p astra-cli -p astra-thin-client -p astra-turn-core --lib --profile ci --test-threads 2 --retries 0 --status-level fail --final-status-level fail`: **8,500 passed, 23 skipped**; retries disabled. - `cargo clippy --locked -p astra-cli -p astra-thin-client -p astra-turn-core --all-targets -- -D warnings`: passed. - `cargo fmt --all -- --check`: passed. - `python3 -m unittest discover -s scripts/ci -p 'test_*.py'`: **132 tests, OK with 5 existing skips**. The first run without canonical `TMPDIR` had two macOS `/var` versus `/private/var` path comparisons fail; rerunning with the canonical directory passed without changing tests or assertions. - `python3 scripts/ci/validate_repository.py`: passed. - `git diff --check`: passed. Public entrypoint: the new regression calls the real `stream_chat_sse` against a local HTTP peer and a gated BearerProvider. It cancels while the first admission's bearer is pending (zero POSTs remain zero, with positive not-dispatched evidence), and while a retry's bearer is pending (one earlier POST remains one, with sticky dispatched evidence). It continues polling the same future after cancellation instead of dropping and recreating it. Other covered unhappy paths include delayed run identity, same-chunk tool/approval suppression, absolute grace deadline despite keepalives, unknown identity, rejected and pending cancellation, completion racing cancellation, and busy admission with draft recovery. Existing HTTP/SSE settlement coverage requires only the original response plus exact-run cancellation, with no local tool effect, Session lookup or replay. Earlier local runs disclosed an absent MCP fixture and an intermittent transcript-persistence assertion; neither was hidden by weakening assertions or adding skips. The fixture is now explicitly built before the full inventory. The prior optional live harness run reported 17/18, failing `flash_missing_child_model_fail_closed`; this follow-up does not claim that live run passed or rerun it. Database verification is not applicable: Server transitions, schema, queries and transactions are unchanged. Real Server/DB execution-slot, QA/production, native OS-signal/TUI, Windows/WSL, load and paid-provider validation were not run. Full-workspace and platform gates remain CI responsibilities. The existing macOS compact-unwind linker warning is not treated as a passing or failing assertion. ## Final checklist - [x] I added or updated tests at the layer that owns the behavior, or explained why no test is needed. - [x] I updated public or design documentation for contract changes, or the change needs no documentation update. - [x] I checked the diff for credentials, private URLs, customer data, generated files, and other sensitive information. - [x] The PR title follows the repository's Conventional Commit format. Approved-by: XuPeng-SH <[email protected]>
Summary
One-shot
astra chatcould terminate on SIGINT without terminal JSON, leaving callers unable to determine whether its exact Server run and local tools had stopped. Setup and held-open stdin also bypassed graceful interruption.Use the existing captured-owner exact-run cancellation, request lease and canonical settlement owners. Observe the actual ordinary SSE executor and its effective worktree independently from native delivery. The Linux supervisor continues its bounded wait/reap loop when auxiliary
/procenumeration fails; only kernelECHILDestablishes settlement.Keep both signal listeners active through native shutdown and event-writer settlement. A late first signal establishes the same request deadline and cannot publish ordinary success; a second signal remains a recovery veto even when subsequent cleanup succeeds. Join the same cleanup future without extending its deadline, and retain writer abort authority. Preserve the original failure classification, metadata and observed partial; append cleanup causes instead of replacing evidence.
Rebased onto
3c7141639including #1067. Executor observation is integrated into the single heap-pinned SSE implementation. The existing required shared CLI job now also executes the three offline public-process targets; dependent labels, fixture setup and JUnit reporting retain the same owner.Related issue
Closes #1060.
Addresses review 5564602564 and its double-failure finding: the real CLI ENOSPC control preserves the prior contract violation, partial text, exact root identity and failed/unverified result. Native shutdown timeout coverage uses the same production cleanup owner with controlled futures.
Change type
User and compatibility impact
Explicit one-shot Chat emits truthful interrupted or failed terminal JSON rather than exiting directly by SIGINT. JSON includes
interruption_reason. Unknown remote/local settlement remains failed and unverified; neither Server cancellation acknowledgement nor partial text clears a local ownership fence.No new configuration, dependency, persisted lifecycle state or compatibility path. Positional shorthand and
--printremain outside the explicit Chat contract of #1060.Architecture and complexity delta
--stdin; no extra per-token network request, database storage or global session lock. Existing cancellation HTTP and 10-second user-interrupt budget remain bounded. Auxiliary Linux enumeration failures may now consume the existing two-second settlement budget instead of falsely ending recovery early. No throughput or live-provider latency claim is made.Verification
Delivery source
c78f26f96d1233fd2d16e481e266e961f5810ad2, rebased merge base3c7141639dadafae199acb2e40d6424c71b4b0d4. Runtime validation source30a53636a; the subsequent CI-only correction leaves all Rust source, tests, dependencies and nextest profiles unchanged. Rust 1.97.0, locked dependencies, ordinary stack withRUST_MIN_STACKunset. Temporary runtime workspaces use ordinary disk paths outside protected application state.cargo nextest run --locked -p astra-cli --lib --bins --test cli_pipe --test process_supervisor --test shell_execution_boundaries --profile ci. Actual nextest listing confirms 4942 runnable tests and 20 existing ignored, including exactly the three integration targets (20 + 1 + 5). Listing is selection validation; the combined hosted execution is pending. The unchanged unit and process suites have the separate execution evidence below.cargo nextest run --locked -p astra-cli --lib --bins --profile ci: 4916 passed, 20 existing skipped.cargo nextest run --locked -p astra-cli --test cli_pipe --test process_supervisor --test shell_execution_boundaries --profile ci: 26 passed on final source. Includes SIGINT, held stdin, second signal, no run identity, local ownership fence, changed-session plus event-file ENOSPC, actual production supervisor containment and shell effect boundaries. Successful interrupted publication is replayed through the canonical conversation owner.astra-sandboxplus affected shell/ownership/invocation modules inastra-tools: 405 passed.cargo clippy --locked -p astra-cli -p astra-sandbox -p astra-tools --all-targets -- -D warnings: passed.RUSTFLAGS=-Zsanitizer=thread CARGO_INCREMENTAL=0 cargo +nightly-2026-10-12 nextest run -Zbuild-std --target x86_64-unknown-linux-gnu --locked -p astra-cli -p astra-sandbox -p astra-tools --lib --profile ci --test-threads 2 -E 'package(astra-sandbox) or test(cli::command_router::) or test(cli::chat_stream::) or test(cli::turn::) or test(tests::chat_stream_tests::) or test(/shell_ops|workspace_observation|invocation|worktree_tests|internal_detach|resume/)': 907 passed, no race report. Instrumented standard library and prebuilt instrumented MCP fixture; tests outside the expression are not counted as covered.make format-check,python3 scripts/ci/validate_repository.pyand full-PR whitespace validation: passed.gpt-6.1-sol/xhighruntime design and overall review, plus design and final review of the CI correction, reconciled with the complete PR. No unresolved material blockers remain.d20865962real-provider cancellation/continuation evidence is historical; no provider request or shared-service change was made for this final source. Controlled native-shutdown tests do not claim a full-native public timeout experiment, and deterministic canonical replay does not replace a new live combined cancellation/resume acceptance.~/.cache. Explicit Auto makes that fixture reach its intended SSE failure, and ordinary disk temporary roots preserve production protection. All original failure assertions remain. The first TSan run lacked the MCP fixture at nightly Cargo's test artifact lookup; it is not counted as a pass.Final checklist