Skip to content

fix(service-job): kernel shutdown waits for a scheduled run in flight, or settles its row as interrupted - #34331

Merged
objectstack-fleet[bot] merged 6 commits into
mainfrom
claude/area-A5-34046
Nov 16, 2026
Merged

objectstack-fleet[bot] merged 6 commits into
mainfrom
claude/area-A5-34046

Conversation

@objectstack-fleet

@objectstack-fleet objectstack-fleet Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Requested by Steedos · project thread

Fixes #34046

Clause-②: no
Metadata-protocol: none

维护者速读

  • 改了什么:内核关停时,定时任务适配器会先等正在跑的那一次定时执行结束(默认最多 10 秒);超时仍未结束的,在驱动释放前把它的 sys_job_run 行记为 failed,错误文案写明「被关停中断」。
  • 为什么改:云端驱逐内核是常态,以前关停不等在跑的任务,任务随后撞上已释放的驱动,运行行永远停在 running,还打两条驱动失败告警。
  • 风险与回滚:关停最多多等 10 秒(在内核 60 秒关停预算内);只动 service-job 一个包,不新增状态值或元数据键;回滚即 revert 本 PR。
  • 先看:packages/services/service-job/src/db-job-adapter.ts 的 destroy() 与 wrap() 中 onAttemptStart 两处关停判断;其次 scheduled-fire.ts 的 drainScheduledFires。
  • 两分钟验证:pnpm --filter @objectstack/service-job exec vitest run src/shutdown-drain-34046.test.ts,预期 8 条全绿。
  • 需要你做的:无,席位落地。

What changes

The kernel destroys plugins in reverse order (performShutdown() in packages/core/src/kernel.ts), so the job plugin is destroyed before the driver it writes through. IntervalJobAdapter.destroy() and CronJobAdapter.destroy() cleared their timers and returned at once. A scheduled run still executing then hit the released driver: its row stayed running and finishRun / bumpJob logged driver failures.

  • scheduled-fire.ts: ScheduledFire now holds the fire's settled promise next to startedAt. New helpers: openScheduledFire(), drainScheduledFires(inFlight, boundMs) (waits for every held fire, at most boundMs, and returns the names still running), drainExpiredMessage(), and DEFAULT_SHUTDOWN_DRAIN_MS = 10_000.
  • IntervalJobAdapter and CronJobAdapter: new constructor option shutdownDrainMs (default 10000). destroy() stops the timers, clears the registrations, then waits for the fires in scheduledInFlight, up to the bound. If the bound passes, one warn names each job left running. IntervalJobAdapter.runScheduled() now skips a tick whose registration is gone (CronJobAdapter already did), so a tick racing destroy() starts nothing.
  • DbJobAdapter: new DbJobAdapterOptions.shutdownDrainMs, forwarded to its own inner timer adapter (the no-cron fallback). A cron adapter you pass in uses its own option. Each scheduled invocation of a wrapped handler is tracked from its first attempt until it settles. destroy() sets shuttingDown, destroys inner, then the cron adapter (both drain), then settles every scheduled run still open: status: 'failed', error = "interrupted by shutdown: …". sys_job mirrors it like any failed run. This happens while the driver is still up. The existing one-terminal-write latch makes the abandoned handler's own settle a no-op when it finishes later. Once shuttingDown is set, a scheduled run starts no retry attempt. If shutdown starts while an attempt's row insert is in flight, that row is settled as interrupted and the attempt never starts.
  • Status vocabulary: no new value. failed is reused because the run did not finish, and that is what failed already means. Spec JobExecutionStatus, sys_job_run.status and sys_job.last_status are untouched.
  • Manual trigger() / replay() are unchanged. They are not waited for, not settled and not gated, because their callers await them.
  • Bound: 10 s by default, inside the kernel's default 60 s shutdownTimeout, which every plugin's teardown shares. packages/core is not touched.

Tests

New pin file packages/services/service-job/src/shutdown-drain-34046.test.ts (8 tests). The harness models a kernel teardown: await db.destroy(), then the engine is "released". After that, every engine write (insert / update) is recorded and throws No driver available for object …. find stays the plain double, because every path that settles a run ends in a write. Legs: DbJobAdapter with no cron adapter (IntervalJobAdapter owns the timer, interval schedule), and DbJobAdapter with a real CronJobAdapter on a croner expression * * * * * *.

  1. A run that ends inside the bound: destroy() stays pending until the run ends. The row ends success and no new fire starts. Zero engine calls after release, and no driver-failure warn.
  2. A run past the bound: destroy() resolves at exactly the bound. The row is failed with the "interrupted by shutdown" error, and sys_job shows last_status: failed, failure_count: 1. When the handler finishes later, there are zero engine calls after release and no driver-failure warn.
  3. A retry due after shutdown starts: the handler is not called again, and there are zero engine calls after release.
  4. Standalone: IntervalJobAdapter.destroy() waits for its in-flight fire. CronJobAdapter.destroy() gives up at its bound and names the job.
Before reading (main 021abd4)

The adapters' main sources were copied next to a variant of the pin file that only measures. That harness also guarded find, which is why find sys_job appears. On the run-past-the-bound case, both legs read the same:

interval leg: {"rows":["running"],"afterRelease":["update sys_job_run","find sys_job"],
               "warns":[…,"DbJobAdapter: failed to update sys_job_run","DbJobAdapter: bumpJob failed"]}
cron leg:     {"rows":["running"],"afterRelease":["update sys_job_run","find sys_job"],
               "warns":["DbJobAdapter: failed to update sys_job_run","DbJobAdapter: bumpJob failed"]}

This is the card's trace: the row is left running, and both WARNs fire after the driver is gone. The pin file run against main: Tests 6 failed (6) (the six tests that existed then). Each failure was destroy() resolving before the in-flight run settled (expected true to be false).

Ablations (each negative pin; mutate, run the pin file, restore; `scripts/ablation-replace.mjs`)

Run at 2ad7c43191. The only later change is in the test double: find is no longer guarded. Subjects are imported from src by relative path, so no build was involved. Each restore was proven: blob == HEAD and git diff HEAD empty.

  • A1: IntervalJobAdapter.destroy() drain replaced by an empty list (old non-awaiting destroy). Result: Tests 3 failed | 5 passed (8). Interval leg (1), (2) and the standalone interval test fail with expected true to be false (destroy resolved early).
  • A2: the same in CronJobAdapter.destroy(). Result: Tests 3 failed | 5 passed (8). Cron leg (1), (2) and the standalone cron test fail.
  • A3: await this.settleInterruptedRuns() removed from DbJobAdapter.destroy(). Result: Tests 2 failed | 6 passed (8). Both legs of (2) fail with expected 'running' to be 'failed'.
  • A4: the shuttingDown check before an attempt removed. Result: Tests 2 failed | 6 passed (8). Both legs of (3) fail with afterRelease = ["insert sys_job_run", …].

Acceptance notes

  • After the bound passes, an abandoned CronJobAdapter fire still releases its cluster lock in its own finally, after the kernel is gone. The cluster plugin is destroyed after the job plugin, so this can log the existing "cluster lock could not release" warn once. The lease also expires on its TTL. Not changed here: the card's two WARNs are about sys_job_run / sys_job.
  • Manual trigger() / replay() runs in flight at shutdown are out of scope by order ("manual trigger semantics unchanged"). They are neither waited for nor settled.
  • JobServicePlugin is untouched. Its kernel:ready placeholder hand-over calls IntervalJobAdapter.destroy(), which now also waits for a placeholder fire in flight (bounded), instead of leaving it running beside the upgraded adapter.

Verification

Local runs: head 9993f237ea (origin/main merged at 2ad7c43191). The dependents and the derived gate sweep ran at 2ad7c43191. The commit after it changes only the pin file's double, and the package suite plus every derived gate that reads test files were re-run at 9993f237ea. Dependency closures were rebuilt first: --filter '@objectstack/runtime^...' --filter '@objectstack/service-automation^...' --filter '@objectstack/cli^...' build, exit 0.

  • @objectstack/service-job at 9993f237ea: vitest run: Test Files 13 passed (13) · Tests 163 passed (163). typecheck: exit 0. eslint --no-inline-config on the five touched files: exit 0.
  • Direct dependents, every test file that reaches service-job:
    • @objectstack/runtime, the 7 job files: Tests 142 passed (142).
    • @objectstack/service-automation, wait-node*.test.ts: Tests 40 passed (40).
    • @objectstack/cli, src/utils/schema-migration-plugins.test.ts (integration project): Tests 53 passed (53).
    • @objectstack/service-cluster-redis, redis-outage.real-redis.test.ts: Tests 2 passed (2).
  • Derived gates: node scripts/pm/dispatch-gates.mjs --commands gives 71 families. All 71 were run at 2ad7c43191. --ran reconciliation: 71 derived, 70 run, 1 NOT-MEASURED, 0 UNRUN.
    • 68 exit 0.
    • check:dual-build-cjs-loads exit 3 (PREREQUISITE NOT MET: the whole workspace is not built here). NOT MEASURED; CI runs it.
    • check:objectql-double-limit exit 1 at 2ad7c43191. The probe threw on the double's find guard. Fixed in 9993f237ea, and the re-run there exits 0.
    • check:engine-double-contract: the new pin file's double routes update through assertEngineUpdateDispatch, as required. Its ledger row (scripts/engine-double-contract.pinned.json: file = this test, verb update, pinned 1) was added in 312b779 by node scripts/check-engine-double-contract.mjs --write (area grant, 0 lost); at head 7e9abb6 the gate is judged green by CI (Lint · CI, release & engine gates success). It was red at 9993f237ea, before the row.
    • Re-run at 9993f237ea, exit 0: objectql-double-limit, cross-package-test-inputs, test-source-alias, nul-bytes, where-matcher, rest-log-spy-declared, registry-log-declared, swallow-census-controls, tier-file-adoption, issue-citations, doc-authoring, refd-timer-probe, logger-receiver-detach, keyed-text-bounds, query-options-erasure, optional-error-sink.
  • git merge-tree against origin/main (10 commits past the merge): clean. None of those commits touches packages/services/service-job/** or the ledger.

Session: https://claude.ai/code/session_01QsR2jTEivi2wogPpeo3xd5

🤖 Generated with Claude Code

…ttles its row as interrupted

IntervalJobAdapter and CronJobAdapter now await the scheduled fire they
hold in flight on destroy(), up to a shutdownDrainMs bound (default 10 s,
inside the kernel's 60 s shutdownTimeout). DbJobAdapter settles a run that
outlives the bound as failed with an interrupted-by-shutdown error while
the driver is still up, and starts no new attempt once shutdown began.

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QsR2jTEivi2wogPpeo3xd5
…y, find stays the plain double

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QsR2jTEivi2wogPpeo3xd5
@github-actions github-actions Bot added size/l documentation Improvements or additions to documentation tests tooling Fix lands in tooling, not a product package — enters pm:queue only with Unblocks: or a named surface labels Nov 16, 2026
@github-actions

github-actions Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

📓 Docs Drift Check

20 anchor(s) derived from 1 changed package(s); no hand-written page names any of them, so this run has nothing to list — not a clean bill of health. This check sees only pages that NAME a derived anchor: one that documents this change in prose, or enumerates it in an authoring dialect, names none and stays invisible to it on every run.

What this run could not see
  • 7 name(s) were too generic to anchor anything (single lowercase words)
  • the SDK route bridge reached 65 of 247 client-bound route-ledger rows — the other 182 have no registrar path: tail to select them, so pages documenting THEIR client methods cannot appear above, on this or any run. Of those 182: 0 are remediable by widening that discovery convention (an in-repo file declares the path; the convention did not scan it); 59 are structural — on a ledger where NOT ONE row is declared in-repo, so no discovery change reaches them at any price; 123 are undecided (no in-repo declaration, on a ledger that has other in-repo registrars — absence and an unreadable spelling are not distinguishable here). The rows themselves: node scripts/docs-audit/affected-docs.mjs --bridge-coverage
  • a page that states a rule by its inputs shares no identifier with the emitter that implements the rule, so an emitter-only diff cannot list it — not on this run and not on any run. Measured on fix(driver-sql): emit varchar(maxLength) for a text field a declared index keys on #11430: content/docs/protocol/objectql/types.mdx documents the text-family column mapping by the ObjectQL type names it maps FROM (text / textarea / html) while the diff changed createColumn; it went unlisted, and it was the page that diff falsified, in four places. No shared token exists to detect this on, so a rule your change carries has to be re-read by hand in the pages that restate it.
  • a key NAME is not a key, so the hand re-read the line above prescribes can land on the wrong schema. The same spelling is authorable on one governed type and a [REMOVED] tombstone on another for each of active, aria, joins, objects, template, tools and version (censused on [finding] tools is a key on BOTH AgentSchema (tombstoned, dead) and SkillSchema (live, cloud-attested), so a name-based search attributes skill examples to the agent key — it produced a false stop-the-line alarm on PR #19059 #19093 over the liveness ledger's governed types, top-level keys); nothing in a search result distinguishes the two, so a grep hit on a LIVE example reads as evidence about the DEAD key. Measured on fix(spec): the agent.tools liveness row says dead — it claimed live on a key the schema tombstoned #19059: content/docs/ai/agents.mdx was reported as contradicting the agent.tools tombstone over its tools: example at :161, which is inside the defineSkill({ block opened at :155 — the page was already correct. Settle ownership by PARSING the value against both schemas, never by the name: that literal PASSES SkillSchema, and as an AgentSchema it FAILS at tools with the tombstone prescription. ⛔ These names are not the whole class — a key retired through a .strict() guidance map leaves no tombstone in the walked shape and none of them here (tool.category, live as AIToolDefinition.category).

Coarse fallback — 3 page(s) merely mention a changed package (the pre-#9192 predicate, kept for the deliberately-wide backstop): node scripts/docs-audit/affected-docs.mjs --json 35c9a305f06a37fe941d424fe0160727e20c0808 → packageMentionDocs.

Which tree this was computed on

This run read content/docs from d127470de65bbc20f4b5d5485a2f46796ecb1521 — the merge of head 7e9abb650ba152eb685bdb9e5de4c881a796e38d into base 35c9a305f06a37fe941d424fe0160727e20c0808, which is what actions/checkout gives a pull_request run. Not the PR head.

A worktree cut from an older main holds a different content/docs, so re-deriving there can legitimately return a different list — that is a different tree, not a wrong row. To answer on the same tree:

# while this PR is open — GitHub drops the merge commit once it closes
git fetch origin d127470de65bbc20f4b5d5485a2f46796ecb1521 && git checkout d127470de65bbc20f4b5d5485a2f46796ecb1521
# afterwards, rebuild it from the two parents, which stay fetchable
git fetch origin 35c9a305f06a37fe941d424fe0160727e20c0808 7e9abb650ba152eb685bdb9e5de4c881a796e38d && git checkout -B drift-repro 35c9a305f06a37fe941d424fe0160727e20c0808 && git merge --no-ff 7e9abb650ba152eb685bdb9e5de4c881a796e38d

node scripts/docs-audit/affected-docs.mjs --json 35c9a305f06a37fe941d424fe0160727e20c0808

⚠️ That checkout carried uncommitted changes, so the commit above does not fully identify what was read.

…n the engine-double ledger

Generated by `node scripts/check-engine-double-contract.mjs --write`: one
added row (shutdown-drain-34046.test.ts, update, pinned 1), 0 lost.

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QsR2jTEivi2wogPpeo3xd5
@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#1 · os-project-manager · session_01FEkQ5kgF3mo9f7LXuv5hac

Final head for review · PR #34331 · 2026-11-16T09:58Z

Area o1-C (seat repo:objectstack#1) took this PR over from domain:server#5 (takeover claim 6913061905 on #34046).

Head-sha: 7e9abb650ba152eb685bdb9e5de4c881a796e38d
Checks at this head: 35 success, 16 skipped, 0 failure (read 2026-11-16T09:45Z)
Owed: first L1 (L1-b). No L2 face: Clause-②: no, Metadata-protocol: none, not governed (check-governed-merges --pr 34331: not governed, 611 lines).


Generated by Claude Code

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#1 · os-project-manager · session_01FEkQ5mww9UksbwbjvM4aYn

席位核对 · PR #34331 · L1-b · 2026-11-16T10:22Z

Head-sha: 7e9abb650ba152eb685bdb9e5de4c881a796e38d

L1 ACCEPT(带一条落地前正文改正)· area o1-C 定稿评论 6913234084 所钉 head。

  1. 形态:draft,目标 main,首行 Fixes #34046;卡「What done looks like」两条(destroy 有界等待或在驱动释放前把行落为终态;关停时有在跑定时任务的测试,断言不留 running、关停后无驱动失败日志)本 PR 全部交付,关卡正确。7 文件 +573/−38,无受管路径,无 packages/spec/**,不欠 L2。
  2. 前提实测(亲读 head 源码):
    • IntervalJobAdapter/CronJobAdapter.destroy():先停 timer、清注册,再 drainScheduledFires(scheduledInFlight, shutdownDrainMs);超时一条 warn 点名。drainScheduledFires 的 bound timer 在 finally 清掉,不外泄。
    • 「destroy 期间到点的 tick 不再起跑」:interval 侧本 PR 新加 this.jobs.get(record.name) !== record 守卫;cron 侧 head 上 runScheduled 首行 if (!record) return 原已存在。两侧均成立。
    • DbJobAdapter:shuttingDown 先置位 → 依次 drain inner 与 cron → settleInterruptedRuns 先 await run.write 再 interrupt()。核三种时序:行插入未开始(onAttemptStart 见 shuttingDown 直接抛,不写)、插入进行中(等插入完再落 failed,且 onAttemptStart 自身也补落)、attempt 在跑(落 failed+INTERRUPTED_BY_SHUTDOWN,bumpJob 记失败;其后 handler 自己的 settle 被 settled 闩挡住、零写)。只追踪 trigger === 'schedule',手动 trigger()/replay() 不变,与卡及正文一致。不新增状态值。
    • 测试:新 pin 文件按「kernel 释放后 insert/update 一律抛」建模,两腿(无 cron 回退 / 真 CronJobAdapter)各断言终态行、afterRelease 零调用、无驱动失败 warn;对 main 反向读数与 A1–A4 四条 ablation 均在 PR 正文,每条红行点名到腿与断言。
  3. 门禁 check-runs(head 7e9abb65):51 条,success 或 skipped,零 failure、零 pending;Lint & Repo Gates、TypeScript Type Check、Test Core (1/8)…(8/8)、Lint · CI, release & engine gates 皆 success。
  4. 接受的偏差:
    • scripts/engine-double-contract.pinned.json 新增一行(本 PR 自身 pin 文件的 update double,生成物,312b7793 由 check-engine-double-contract.mjs --write 写出,0 lost)。这是本 PR 测试的账本登记,不是范围外修复,接受。
    • 有 cron 时 DbJobAdapter.destroy() 先后 drain 两个 adapter,最坏约 2×10 s,仍在内核 60 s 关停预算内;记明。
    • 「关停后不起重试」只在 DbJobAdapter 包裹下成立(changeset 该句写在 DbJobAdapter 条目内,措辞准确);裸 IntervalJobAdapter 的重试不受此门。记明,不判 REWORK。
  5. 范围外去向:## Acceptance notes 三条(cron 锁在内核走后才释放可能多一条既有 warn、手动运行按令不在范围、JobServicePlugin 占位移交现在也有界等待)均为已述副作用,无须立卡。Skills-docs: 不适用(Metadata-protocol: none)。changeset 逐句核(@objectstack/service-job patch,包未设 private):「内核逆序销毁、job 服务先于驱动」「两 adapter 原先停 timer 即返回」「默认 10000 ms、在 60 s 内」「destroy 期间到点 tick 不起跑」「超时一条 warn、DbJobAdapter 在驱动走前落 failed+中断文案、sys_job 按失败记」「放弃的 handler 晚到不再写行」「DbJobAdapterOptions.shutdownDrainMs 只管自带 timer,外传 cron 用其自身选项」「手动 trigger/replay 不变」均与 diff 一致。
  6. 落地条款 · 落地前须改 PR 正文一处(不动 head,本 ACCEPT 不失效):## Verification 里「check:engine-double-contract exit 1, still red at 9993f237ea … the row is not added here」已不属实——该行已由 312b779 加入,本 head CI 绿。改成一句写明该行在 312b779 加入、本 head 由 CI 判绿。改完照 landing-operations.md 自落(非受管,check-governed-merges --pr 34331 已读 not governed)。head 再移 ⇒ 只对 delta 补读。

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

repo:objectstack#1 · os-project-manager · session_01FEkQ5kgF3mo9f7LXuv5hac

Landing · PR #34331 · 2026-11-16T10:27Z

Probe Reading
Head 7e9abb650ba152eb685bdb9e5de4c881a796e38d (unchanged since ACCEPT 6913739525)
L1 ACCEPT 6913739525 (L1-b); its landing condition met: the Verification bullet on check:engine-double-contract patched by relay issue_patch (body only, head unchanged)
L2 not owed: Clause-②: no, Metadata-protocol: none, no packages/spec/src/**, not governed
check-governed-merges --pr 34331 NOT governed · 611 lines ≤ 3000
Checks at head every check success or skipped after the body-triggered re-runs; Lint & Repo Gates, TypeScript Type Check success
K (first-parent commits since the merged base c934631723) 13 < 15
Generated artifacts none in the diff under merge=os-regen (scripts/engine-double-contract.pinned.json is not on that list)

State change: ready for review + auto-merge (merge queue). On MERGED, Fixes #34046 closes the card; the area removes pm:dispatched and lease:o1-C in the close stroke.


Generated by Claude Code

@objectstack-fleet
objectstack-fleet Bot marked this pull request as ready for review November 16, 2026 10:27
@objectstack-fleet
objectstack-fleet Bot added this pull request to the merge queue Nov 16, 2026
Merged via the queue into main with commit 183a89e Nov 16, 2026
56 checks passed
@objectstack-fleet
objectstack-fleet Bot deleted the claude/area-A5-34046 branch November 16, 2026 11:13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation size/l tests tooling Fix lands in tooling, not a product package — enters pm:queue only with Unblocks: or a named surface

Projects

None yet

1 participant