Skip to content

fix(#1294): 补齐核心服务 SIGTERM 优雅退出、Compose init 与发布失败入口恢复 - #1295

Merged
zhaozhaozz merged 2 commits into
mainfrom
fix/1294-graceful-shutdown-and-deploy-ingress
Nov 24, 2026
Merged

zhaozhaozz merged 2 commits into
mainfrom
fix/1294-graceful-shutdown-and-deploy-ingress

Conversation

@zhaozhaozz

Copy link
Copy Markdown
Collaborator

Closes #1294

问题摘要

近期线上发布(v0.4.7、v0.4.10、v0.4.11)连续出现 cannot stop container: ... tried to kill container, but did not receive an exit event 并在中断后导致公网 HTTP 530(Cloudflare 1033)。历史发布日志显示:

  • webhook 每次发布均跑满默认 10s 宽限期撞上 SIGKILL;
  • manager 多次因旧 bot 保持的 keep-alive/在途请求阻塞 server.close() 跑满 100s 撞上 SIGKILL;
  • bot 在最近连续 7 个版本(v0.4.5–v0.4.11)均跑满 100s 撞上 SIGKILL,同时跳过 store.close();
  • docker compose up -d --force-recreate 会先将 tunnel 重建并停在 Created 状态,后续任一服务停止失败即导致公网 530。

改动内容

  1. webhook/main.mjs:新增幂等 SIGTERM/SIGINT 处理,关闭 proxy(8791)与 metrics(8794)两个 HTTP 服务并立即调用 closeIdleConnections(),3s 排空后 closeAllConnections()、5s 硬兜底退出(严格低于 Docker 默认 10s 宽限期)。
  2. manager/main.mjs:补齐 SIGTERM/SIGINT 重入保护、立即 closeIdleConnections()、5s 排空后 closeAllConnections(),并增加 80s 硬退出上限(严格低于 stop_grace_period: 100s)与关闭异常捕获。
  3. src/main.ts(bot):补齐立即 closeIdleConnections()、5s 排空后 closeAllConnections()、停止 StallMonitor、使用 Promise.allSettled 保证 store.close() 执行,并将硬退出上限从与 stop_grace_period 重合的 100s 下调至 80s。
  4. docker/compose.yaml:为四个核心常驻服务(bot、manager、webhook、tunnel)统一启用 init: true。
  5. .github/workflows/release.yml:在 Deploy 失败 EXIT trap 中新增 recover_ingress,仅对处于 created 状态的规范名 webhook、tunnel 容器按序拉起,保留原始失败退出码与 docker compose ps -a 诊断输出,避免局部停止失败演变为公网 530。
  6. 测试与文档:
    • 新增 test/ut/workflows/graceful-shutdown.test.mjs 覆盖 webhook 退出状态机、compose.yaml init/宽限期不变量、bot/manager 退出契约及 release.yml 入口恢复逻辑;
    • 更新 test/st/src/onboarding/onboarding-tunnel.test.mjs 沙箱 mock;
    • 同步更新 docs/features/deployment-and-operations.md 与 docs/design/architecture.md。

验证结果

  • npm run check:通过(777 files)
  • npm run build:通过
  • npm test -- test/ut/workflows/graceful-shutdown.test.mjs test/ut/workflows/release-workflow-timeouts.test.mjs test/st/src/onboarding/onboarding-tunnel.test.mjs:12/12 通过
  • docker compose -f docker/compose.yaml config --quiet & + docker/compose.build.yaml:通过
  • .github/workflows/release.yml 远端 SCRIPT 块 bash -n 语法检查:通过

@zhaozhaozz

Copy link
Copy Markdown
Collaborator Author

Reviewed head: c563bceeb4017fc1199efa3b99f2dbbbdec35fe7 (tree c562afb0, 9 files +192 −11, one linear commit on 3696412e, no merges; main has no changes to these files since the base).

Not enqueued: two blocking items and two nits below.

Blocking 1 — the required unit check is red

  • Where: unit shard 1 / 2 (run), failing test test/ut/src/channels/assistant-computer-turns.test.mjs:161.
  • Expected: [1, 'idle'] after first.warm(); await first.close().
  • Actual: [1, 'busy'] (AssertionError; 1438 tests pass, 1 fails), so the aggregate unit job is red.
  • This diff does not cause it: nothing here touches src/channels/, src/service-roles/ or that test, and the code and test are byte-identical to 3696412e. On this head I ran node --test --test-name-pattern="a harness turn takes its computer early" test/ut/src/channels/assistant-computer-turns.test.mjs five times: 5/5 pass.
  • Likely pre-existing race in main: AssistantComputer.close() (src/service-roles/assistant-computers.ts) snapshots this.held and returns without awaiting an in-flight warm() acquisition. When the early take is still between the manager PUT and this.held = true, the test sees the lease busy while close() skips the release, so the idle release lands after close() has resolved. On a loaded runner this window is observable.
  • Action: rerun the failed unit job and get a green run. If it reproduces, track it as a separate flake in assistant-computers.ts; it is out of scope for this PR. I will not queue while a required check is red.

Blocking 2 — recover_ingress cannot restore the leftover shape this script itself documents

.github/workflows/release.yml:221-232 starts a container only when its name equals /<project>-<service>-<number> and its state is created. But release.yml:244-248 and test/docker/deploy/deploy-recovery-docker.mjs:36,88-90 record that an interrupted recreate leaves the replacement as <old id>_<project>-<service>-<number>, including the "only the never-started replacement is left" case where no canonical container exists at all.

  • Expected: after a failed up -d --force-recreate that left the public entry down, the EXIT trap brings ingress back (that is what docs/features/deployment-and-operations.md:98 now promises: "避免公网进入 HTTP 530").
  • Actual: when the leftover is the temporary-named replacement, or the canonical container was already removed, the loop matches nothing and ingress stays down.
  • Fix (either): inside the trap, when a target has no canonical container in running/created state, also docker start its created replacement (the next deploy removes non-canonical containers anyway, release.yml:249-256); or narrow the docs sentence to the canonical-name case. A webhook/tunnel stand-in case in test/docker/deploy/deploy-recovery-docker.mjs would keep this honest.
  • If the v0.4.7/v0.4.10/v0.4.11 logs show the container left in created did carry the canonical name, please paste those docker compose ps -a lines here; that would settle the code question and only the wording would need a tweak.

Nits (non-blocking)

  • docs/design/architecture.md:28 claims all four services "立即关闭空闲 HTTP keep-alive 连接…在 stop_grace_period 之前自主退出". That holds for bot, manager and webhook; tunnel is cloudflared, which this repository does not control, and it has no stop_grace_period override. Worth splitting the sentence so tunnel is only credited with init: true.
  • Closes #1294 closes the issue at merge time, but the proof for this change is the next production release actually stopping without SIGKILL and without 530. Refs #1294 would keep the issue open until that release run is checked; your call.

Verified on this head

  • Diff is exactly the nine files above; linear single commit, no merge commits, no stray verification artifacts, no credentials in the diff; docs/features/ and docs/design/ both updated.
  • The new test/ut/workflows/graceful-shutdown.test.mjs is discovered by test/framework/test-plan.mjs and ran in CI (set graceful-shutdown ... passed in shard 1); locally with test/ut/workflows/release-workflow-timeouts.test.mjs it is 8/8. The init: true and shutdownLimitMs < stop_grace_period invariants are read from the real docker/compose.yaml (80 s < 100 s for bot and manager, webhook 5 s hard exit < the default 10 s), and the webhook state machine (idempotent second signal, closeIdleConnections, closeAllConnections at 3 s, exit 0) is exercised behaviourally rather than by text matching.
  • webhook/main.mjs now registers both servers before the handlers and closes both; test/st/src/onboarding/onboarding-tunnel.test.mjs still drives the metrics bridge through handlers[1], which is unchanged by renaming the second server.
  • bot exits 0 even when an individual shutdown hook rejects (Promise.allSettled, store.close() in a try), and the new stalls.stop() is the real StallMonitor.stop().

@agent-ci-infra-bot agent-ci-infra-bot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed commit: c563bce
Coverage: PR #1295; 9 changed file(s)

for target in webhook tunnel; do
for id in $(docker compose ps -a -q "$target" 2>/dev/null || true); do
read -r name canonical state < <(docker inspect --format '{{.Name}} {{index .Config.Labels "com.docker.compose.project"}}-{{index .Config.Labels "com.docker.compose.service"}}-{{index .Config.Labels "com.docker.compose.container-number"}} {{.State.Status}}' "$id" 2>/dev/null || true)
if [ "$name" = "/$canonical" ] && [ "$state" = created ]; then

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(medium)恢复窗口只覆盖 created,exited 残留仍会留 530。

up -d --force-recreate 对单个服务的顺序是 stop → rm → create → start,而整条 up 被 timeout -k 30s 35m 包住(CLI 在 35m 收到 SIGTERM、30s 后被 SIGKILL)。若 CLI 在某个入口服务「stop 已完成、还没 rm」之间被终止,或被终止时该服务正报 cannot stop container ... did not receive an exit event(本次事故的原话),残留状态是 exited 而不是 created:这一行的判断会跳过它,trap 什么都不拉起,公网依旧是 530,而这正是本 PR 要消除的后果。

docker start 对 exited 容器同样有效,把条件放宽为「规范名且不在 running」(created / exited)即可覆盖该窗口,风险仍被 canonical 名与失败路径双重限制;只有「rm 之后、create 之前」容器完全不存在这一窗口无法在 trap 里补齐,适合在注释中说明。建议连同 exited 用例一起补上。

const script = deployStep.run;

assert.match(script, /recover_ingress\(\)\s*\{[\s\S]*?for target in webhook tunnel;/, 'restores webhook before tunnel');
assert.ok(script.includes('[ "$name" = "/$canonical" ] && [ "$state" = created ]'), 'only starts canonical containers stuck in created state');

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(medium)新增的入口恢复行为只有源码文本断言,没有可执行验收。

这条断言(以及第 113/115 行)只是在 Deploy 脚本文本里 grep 片段:把 docker start 换成别的命令、把 canonical 判定写反、让 docker compose ps -a -q "$target" 取错服务,文本仍然逐字匹配,测试仍会通过——即它无法保护本 PR 新增的运行时行为。

仓库已有跑「这段真实脚本」的验收脚本 test/docker/deploy/deploy-recovery-docker.mjs(npm run test:deploy:docker;CONTRIBUTING.md:73 与 docs/design/testing-architecture.md:14 都把 test/docker/ 定义为部署与恢复验收,独立于 npm test,CI 不跑)。它当前只起了 manager/bot 两个替身、只断言失败时打印 ps -a。既然本 PR 新增的正是入口恢复,建议在该脚本里补 webhook/tunnel 替身(现有 entrypoint: ['sh','-c',"trap '' TERM INT; touch /tmp/ready; while :; do sleep 1; done"] 可直接复用),并断言:处于 created 的规范名入口容器在失败 trap 后被拉起,非规范名(<oldid>_<project>-webhook-1)不被拉起。

我这边没有 Docker(docker: command not found),无法代跑该脚本,故作为覆盖建议提出,而不是指出既有用例失败。

@agent-ci-infra-bot

agent-ci-infra-bot Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

第 2 次检视,更新于 2026-11-24 03:32 UTC,检视提交 6a42cc9

检视结论(第 2 轮:head 6a42cc9b / base e52008a4,10 文件 +194 −12,2 个线性提交,无合并提交)

未发现阻塞性缺陷。 上一轮提出的两条 medium 建议中,F1 我撤回为缺陷(代码范围与 #1294 明确写下的修复范围一致),F2 作为非阻塞覆盖建议保留。与上一轮被检视的 c563bcee 相比,实际内容变更只有 3 行测试等待条件(rebase 只位移了上下文)。

前轮发现状态

  • F1(release.yml:225,恢复窗口只覆盖 created)→ answered(撤回为缺陷,thread 4668979906 保留):修复核心服务 SIGTERM 优雅退出缺失及发布中断导致公网 530 的问题 #1294 的「修复范围」原文即为「对规范名且处于 created 状态的 webhook/tunnel 入口容器执行兜底拉起」,事故现场也是 up -d --force-recreate 先把 tunnel 重建为未启动的 Created 后因后续停止失败而停摆。代码执行的正是这条范围:docker compose ps -a -q <service> 取 Compose 自己的容器,canonical 名比对 + created 判定 + docker start,恢复顺序 webhook→tunnel,|| true 不覆盖原始退出码。exited 残留(stop 成功、rm 前被打断)是更窄的另一类窗口,不属于本 PR 的缺陷,宜作为独立改进单独收口。
  • F2(test/ut/workflows/graceful-shutdown.test.mjs:114)→ open(非阻塞):新增的入口恢复行为目前仍只有 Deploy 脚本的文本断言;可执行验收依旧是 npm run test:deploy:docker(test/docker/deploy/deploy-recovery-docker.mjs),它还没有 webhook/tunnel 替身,因此「created 的规范名入口被拉起、非规范名不被拉起」没有运行期断言。该脚本独立于 npm test 且 CI 不跑,所以不阻塞合并,但这仍是本 PR 新增运行时行为唯一缺少的可执行保护(现有 stand() 的 entrypoint: ['sh','-c',"trap '' TERM INT; touch /tmp/ready; while :; do sleep 1; done"] 与 converged() 可直接复用)。

已验证(本 head)

  1. 12/12 check runs success:unit(138192312538)、unit shard 1 / 2(138188943337)、unit shard 2 / 2(138188943649)、e2e(138188943241)、CodeQL、四个镜像 job、Analyze×3;PR mergeable_state: clean、merged: false。上一轮 red 的 unit shard 1 / 2 在本 head 已绿。
  2. 上轮失败的因已修在因上,不是重跑掩盖:test/ut/src/channels/assistant-computer-turns.test.mjs:265 现在同时等 f.service.active.has('turn-1') 与 manager 侧 lease.state === 'busy' 才 warm(); await close();AssistantComputer.computer() 在同一次取用里同时置 held = true 与 service.active.set(turn, ...),所以 active 是「控制面已登记该 turn」的正确信号。close() 之后的断言 [puts, f.computers.leases.get(f.owner).state] === [1,'idle'] 未被放宽,仍能抓住「close 不释放租约」的回归;同一用例后半段「turn 在 take 过程中结束(second/atStart 段)应归还并变 idle」的分支原样保留,修复没有削弱它。
  3. 变更面核对:/commits/6a42cc9b 显示该提交只改 1 个文件(+2 −1),即上述等待条件与一行注释;我在新 head 上整段重读了 release.yml,recover_ingress 与上轮逐字一致;docker/compose.yaml、webhook/main.mjs、manager/main.mjs、src/main.ts、两份文档的 hunk 未变(rebase 仅位移上下文,src/main.ts 偏移来自 main 新增的 legacy-memory 迁移重试,其 setTimeout(..., 30_000).unref() 受 stopping 保护,无需额外退出钩子)。
  4. 作者后续评论中的数字与我的观察一致:head 树 69b2094f、2 个提交、10 文件 +194 −12、全部必需检查为 success。

未执行 / 无法独立复现

  • npm run test:deploy:docker(test/docker/deploy/deploy-recovery-docker.mjs)与本机 docker compose config:本环境没有 Docker(docker: command not found),作者所述的 compose 校验我无法代跑。
  • 完整 npm test / npm run check 未在本地复现(无构建产物),以 CI 的 unit 与两个 shard 结果为准。

之前的行内意见仍未解决 2 条:.github/workflows/release.yml:225、test/ut/workflows/graceful-shutdown.test.mjs:114。

Reviewed commit: 6a42cc9
Coverage: PR #1295; 10 changed file(s)

@zhaozhaozz

Copy link
Copy Markdown
Collaborator Author

Correction to one nit in my earlier review: I withdraw the docs/design/architecture.md:28 suggestion. tunnel/main.mjs is repo-controlled (the Node wrapper around cloudflared, present since d9127f44) and already kills its child and exits within 500 ms on SIGTERM/SIGINT, so crediting all four services with an in-grace-period exit is accurate. No doc change is needed there.

Status otherwise unchanged: head is still c563bcee, unit shard 1 / 2 is still red on this head (unit aggregate failure, mergeable_state: blocked), so the PR stays out of the queue until that job is rerun green.

main has moved to 3a93e03c (8 commits). It edited docs/features/deployment-and-operations.md only in the volume/backup section, not the sentence this PR adds, and none of the other files this PR touches — no rebase is needed for correctness, the merge queue rebases anyway.

One note on the two inline medium comments: the exited leftover and the <old id>_<project>-<service>-<n> leftover have the same minimal fix. Today the trap only starts a container whose name is the canonical one and whose state is created, so an ingress service left in exited state, or left only as a temporary-named replacement, restores nothing. If the target has no canonical container in running/created, docker start whatever docker compose ps -a -q <target> returns for that service; the next deploy already sweeps non-canonical containers (release.yml:249-256). One branch closes all three shapes, and test/docker/deploy/deploy-recovery-docker.mjs is the right place to pin it.

@zhaozhaozz
zhaozhaozz force-pushed the fix/1294-graceful-shutdown-and-deploy-ingress branch from c563bce to 6a42cc9 Compare November 24, 2026 03:12
@zhaozhaozz

Copy link
Copy Markdown
Collaborator Author

Rebased onto origin/main (e52008a4) and fixed the deterministic test race that failed unit shard 1 / 2 in test/ut/src/channels/assistant-computer-turns.test.mjs.

Root cause

In a harness turn takes its computer early (#1254), the test waited on manager-side lease.state === 'busy' before calling await first.close(). On loaded hosts (and 10/10 locally), the manager sets lease.state = 'busy' before the HTTP PUT response reaches the control plane and sets this.held = true / service.active, so close() returned immediately while the post-close POST /release was still in flight, leaving lease.state === 'busy' at the assertion.

Fix

Wait for f.service.active.has('turn-1') && f.computers.leases.get(f.owner)?.state === 'busy' before calling first.warm(); await first.close().

Local verification (head 6a42cc9b48fc9a378cfbba3e889680eae12c85cd)

  • npm run check -> exit 0 (782 runtime JS files passed)
  • npm test -- test/ut/src/channels/assistant-computer-turns.test.mjs test/ut/workflows/graceful-shutdown.test.mjs test/st/src/onboarding/onboarding-tunnel.test.mjs -> exit 0 (22/22 passed, including 14/14 in assistant-computer-turns)
  • 5 consecutive reruns of test/ut/src/channels/assistant-computer-turns.test.mjs -> 5/5 passed (14/14 each)
  • docker compose -f docker/compose.yaml config --quiet && docker compose -f docker/compose.yaml -f docker/compose.build.yaml config --quiet -> exit 0

@zhaozhaozz
zhaozhaozz added this pull request to the merge queue Nov 24, 2026
@zhaozhaozz

Copy link
Copy Markdown
Collaborator Author

Reviewed head: 6a42cc9b48fc9a378cfbba3e889680eae12c85cd (tree 7ba4bbd4, rebased onto 89a5c564, 10 files +194 −12, two linear commits, no merges).

Both earlier blocking items are closed and all six required checks pass, so this head is enqueued with expectedHeadOid 6a42cc9b48fc9a378cfbba3e889680eae12c85cd (queue position 1, state QUEUED).

  • The unit shard 1 / 2 failure is fixed at its cause, not by rerunning. test/ut/src/channels/assistant-computer-turns.test.mjs:265 now waits for f.service.active.has('turn-1') in addition to the manager lease. That is the right signal: AssistantComputer.computer() sets this.held = true and service.active.set(turn, this) together when the take completes (src/service-roles/assistant-computers.ts:539), and the file's own comment says the turn is not in active until that call returns, so the test can no longer call close() between the manager's PUT and the control-plane held flag. The assertion after close() is untouched, so a close() that stops releasing still fails it. unit shard 1 / 2 is green on this head.
  • recover_ingress is scoped correctly after all. 修复核心服务 SIGTERM 优雅退出缺失及发布中断导致公网 530 的问题 #1294's own root-cause statement is that up -d --force-recreate recreates tunnel first and leaves it as an unstarted canonical container before a later stop failure aborts the run ("第一时间将 tunnel 重建为未启动的 Created 状态…导致 tunnel 停摆,引发 HTTP 530"), and the issue's fix scope asks for exactly "对规范名且处于 created 状态的 webhook/tunnel 入口容器执行兜底拉起". The trap does that, and docs/features/deployment-and-operations.md:98 words the guarantee the same way (canonical entry container in created state). I am withdrawing my earlier request to widen it to temporary-named or exited leftovers: those shapes are not the reported failure, and widening the sweep is a separate improvement, not a defect in this change.

Remaining follow-ups, none blocking (the first mirrors the unresolved inline thread):

  • An ingress container that ends exited (the stop-failure path can leave it that way) is still not restarted, so routes served by that service can stay broken until the next deploy even though the tunnel itself is restored. Extending the sweep to exited canonical containers and pinning it in test/docker/deploy/deploy-recovery-docker.mjs would close it.
  • The graceful-shutdown test asserts the entry-recovery fragment by matching the workflow text; the executable acceptance path for that behaviour is npm run test:deploy:docker.

Verified on this head: the rebased commit 8d6c2df4 is byte-identical to the previously reviewed c563bcee apart from blob hashes and the shifted src/main.ts hunk context (main added the legacy-memory migration retry, whose setTimeout(..., 30_000).unref() is guarded by stopping and needs no extra shutdown hook); 6a42cc9b adds only the three-line test change above; release.yml, docker/compose.yaml, webhook/main.mjs, manager/main.mjs, src/main.ts and both docs are unchanged from what I reviewed; test/st/src/onboarding/onboarding-tunnel.test.mjs still drives handlers[1] after the second server was renamed; and none of the six required checks is red.

@zhaozhaozz

Copy link
Copy Markdown
Collaborator Author

Correction to the line above: the tree of reviewed head 6a42cc9b48fc9a378cfbba3e889680eae12c85cd is 69b2094f, not the value I wrote. Everything else in that comment stands, and the queue entry is unchanged.

Merged via the queue into main with commit b113992 Nov 24, 2026
12 checks passed
@zhaozhaozz
zhaozhaozz deleted the fix/1294-graceful-shutdown-and-deploy-ingress branch November 24, 2026 03:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

修复核心服务 SIGTERM 优雅退出缺失及发布中断导致公网 530 的问题

1 participant