Skip to content

Commit 183a89e

Browse files
fix(service-job): kernel shutdown waits for a scheduled run in flight, or settles its row as interrupted (#34331)
<!-- claude-projects-attribution: {"github_login":"zhuangjianguo"} --> _Requested by **Steedos** · [project thread](https://claude.ai/code/project/chan_018ETKaNwMZCNRYD7D8Q9Ubb?thread=cmsg_018ETKaNwMZCNRYD7D8Q9UbbTGhxJSYAmQXU7efVdNqrpw)_ 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. <details><summary>Before reading (main 021abd4)</summary> 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`). </details> <details><summary>Ablations (each negative pin; mutate, run the pin file, restore; `scripts/ablation-replace.mjs`)</summary> 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", …]`. </details> ## 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](https://claude.com/claude-code) <!-- signed: repo:objectstack#1 · os-project-manager · session_01FEkQ5kgF3mo9f7LXuv5hac --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 6cc3f97 commit 183a89e

7 files changed

Lines changed: 573 additions & 38 deletions

File tree

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
---
2+
'@objectstack/service-job': patch
3+
---
4+
5+
fix(service-job): kernel shutdown waits for a scheduled job run already in flight, or settles its run row as interrupted
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
The kernel destroys plugins in reverse order, so the job service is destroyed before the driver it writes through. `IntervalJobAdapter.destroy()` and `CronJobAdapter.destroy()` stopped their timers and returned at once, while a scheduled run could still be executing. That run then met the released driver: its body failed, its `sys_job_run` row could not be updated and stayed `running` for good, and the `sys_job` counters were not bumped (`DbJobAdapter: failed to update sys_job_run`, `DbJobAdapter: bumpJob failed`). In the cloud runtime a kernel is evicted routinely, so every eviction with a scheduled run in flight could leave such a row.
11+
12+
- Both timer adapters now wait in `destroy()` for the scheduled run they hold in flight, for at most `shutdownDrainMs` (a new constructor option, default 10000 ms, inside the kernel's 60 s `shutdownTimeout`). A run that ends inside that bound writes its own terminal row as before. A tick that comes due while `destroy()` runs does not start a new run.
13+
- A run still going when the bound passes is named in one `warn`. If it runs under `DbJobAdapter`, its row is settled before the driver goes: `status: 'failed'`, with an `error` that says it was interrupted by shutdown, and `sys_job` records it like any other failed run. No new status value is added. When the abandoned handler finishes later, nothing more is written. No scheduled run starts a retry attempt after shutdown has begun.
14+
- `DbJobAdapterOptions.shutdownDrainMs` sets the bound for the adapter's own timer (the fallback used when there is no cron adapter). A cron adapter you pass in uses its own option.
15+
- Manual `trigger()` and `replay()` runs are not changed. Their callers await them.

‎packages/services/service-job/src/cron-job-adapter.ts‎

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,14 @@ import type {
1010
JobRunTrigger,
1111
} from '@objectstack/spec/contracts';
1212
import { runWithPolicy, JobTimeoutError } from './run-with-policy.js';
13-
import { skippedTickMessage, type ScheduledFire } from './scheduled-fire.js';
13+
import {
14+
DEFAULT_SHUTDOWN_DRAIN_MS,
15+
drainExpiredMessage,
16+
drainScheduledFires,
17+
openScheduledFire,
18+
skippedTickMessage,
19+
type ScheduledFire,
20+
} from './scheduled-fire.js';
1421

1522
/**
1623
* Monotonic counter that makes every adapter instance's registry prefix unique
@@ -77,6 +84,12 @@ export interface CronJobAdapterOptions {
7784
namespace?: string;
7885
/** Surface for registry-level anomalies (a reclaimed job name) and cluster-lock outages. */
7986
logger?: { warn(msg: string, meta?: unknown): void; info?(msg: string, meta?: unknown): void };
87+
/**
88+
* How long `destroy()` waits for a scheduled run already in flight before it
89+
* returns without it, in milliseconds (default 10000). Keep it inside the
90+
* kernel's `shutdownTimeout`, which every plugin's teardown shares.
91+
*/
92+
shutdownDrainMs?: number;
8093
}
8194

8295
interface CronJobRecord {
@@ -112,6 +125,7 @@ export class CronJobAdapter implements IJobService {
112125
* (#31811). See {@link CronJobAdapter.runScheduled}.
113126
*/
114127
private readonly scheduledInFlight = new Map<string, ScheduledFire>();
128+
private readonly shutdownDrainMs: number;
115129

116130
/**
117131
* This instance's prefix in croner's PROCESS-GLOBAL name registry.
@@ -132,6 +146,7 @@ export class CronJobAdapter implements IJobService {
132146
this.cluster = options.cluster;
133147
this.leaseMs = options.leaseMs ?? 60_000;
134148
this.logger = options.logger;
149+
this.shutdownDrainMs = options.shutdownDrainMs ?? DEFAULT_SHUTDOWN_DRAIN_MS;
135150
this.registryNamespace = `${sanitizeNamespaceLabel(options.namespace)}#${++ADAPTER_SEQUENCE}.${Math.random()
136151
.toString(36)
137152
.slice(2, 8)}`;
@@ -236,12 +251,25 @@ export class CronJobAdapter implements IJobService {
236251
* holds. Called from `DbJobAdapter.destroy()` and `JobServicePlugin.destroy()`
237252
* — i.e. from the kernel eviction chain, which until #8362 stopped one level
238253
* above this method and left every evicted kernel's timers running forever.
254+
*
255+
* Then wait for the scheduled fires still in flight, for at most
256+
* `shutdownDrainMs`. The kernel destroys the driver AFTER this plugin, so a
257+
* fire handed back still running meets a released driver and its run record
258+
* is never settled. The registrations are cleared first, so a tick racing
259+
* this finds no job and starts nothing; a fire still going when the bound
260+
* passes is named in one `warn` and left to finish on its own, and
261+
* `DbJobAdapter` settles its run row before the driver goes. Manual
262+
* `trigger()` runs are not waited for: their caller awaits them.
239263
*/
240264
async destroy(): Promise<void> {
241265
for (const rec of this.jobs.values()) {
242266
try { rec.task?.stop(); } catch { /* ignore */ }
243267
}
244268
this.jobs.clear();
269+
const leftRunning = await drainScheduledFires(this.scheduledInFlight, this.shutdownDrainMs);
270+
if (leftRunning.length > 0) {
271+
this.logger?.warn(drainExpiredMessage('CronJobAdapter', leftRunning, this.shutdownDrainMs));
272+
}
245273
}
246274

247275
/**
@@ -281,12 +309,13 @@ export class CronJobAdapter implements IJobService {
281309
}
282310
// Set before the first await, so a tick landing while this one is still
283311
// asking for the lock reads it too.
284-
const fire: ScheduledFire = { startedAt: new Date().toISOString() };
312+
const { fire, finish } = openScheduledFire();
285313
this.scheduledInFlight.set(name, fire);
286314
try {
287315
await this.runElected(name, record);
288316
} finally {
289317
if (this.scheduledInFlight.get(name) === fire) this.scheduledInFlight.delete(name);
318+
finish();
290319
}
291320
}
292321

‎packages/services/service-job/src/db-job-adapter.ts‎

Lines changed: 142 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -83,11 +83,52 @@ export interface DbJobAdapterOptions {
8383
* row's own `last_status` / `run_count` / `failure_count` counters.
8484
*/
8585
recordRuns?: boolean;
86+
/**
87+
* How long `destroy()` waits for a scheduled run already in flight on the
88+
* adapter's own timer (the no-cron fallback) before settling its row as
89+
* interrupted, in milliseconds (default 10000). A `cron` adapter passed in
90+
* brings its own bound (`CronJobAdapterOptions.shutdownDrainMs`).
91+
*/
92+
shutdownDrainMs?: number;
8693
}
8794

8895
/** Terminal statuses a finished run can land in — everything except `running`. */
8996
type TerminalStatus = 'success' | 'failed' | 'degraded' | 'timeout';
9097

98+
/**
99+
* A scheduled run of one wrapped handler, from the start of its first attempt
100+
* until it settles — what {@link DbJobAdapter.destroy} settles as interrupted
101+
* when the run outlives the shutdown drain.
102+
*/
103+
interface OpenScheduledRun {
104+
/** The attempt whose `sys_job_run` row is open, once its start was recorded. */
105+
current?: { id?: string; settled: boolean; startedMs: number };
106+
/** The bookkeeping write in progress — the row insert or the terminal write. */
107+
write?: Promise<unknown>;
108+
/** Settle the open attempt's row as interrupted by shutdown; a no-op once it is settled. */
109+
interrupt(): Promise<void>;
110+
}
111+
112+
/**
113+
* The `error` a scheduled run's row carries when the shutdown drain ended
114+
* before the run did. Its `status` is `failed`: the run did not finish, which
115+
* is what that status already says — no status of its own is minted for it.
116+
*/
117+
const INTERRUPTED_BY_SHUTDOWN =
118+
'interrupted by shutdown: the job service shut down while this scheduled run was in flight, ' +
119+
'and the run had not finished when the shutdown drain ended. It may have done part of its work.';
120+
121+
/**
122+
* Why a scheduled run's next attempt never started: the job service began
123+
* shutting down first. It reaches the timer adapter's in-memory history only —
124+
* nothing after shutdown writes a row.
125+
*/
126+
function shutdownBeforeAttempt(name: string, attempt: number): Error {
127+
return new Error(
128+
`Job "${name}": attempt ${attempt} of its scheduled run was not started because the job service is shutting down.`,
129+
);
130+
}
131+
91132
/**
92133
* The options handed DOWN to the timer adapter.
93134
*
@@ -249,6 +290,10 @@ export class DbJobAdapter implements IJobService {
249290
private readonly recordRuns: boolean;
250291
/** job name → its `replay()` pre-flight (#14501). See {@link ReplayGuard}. */
251292
private readonly replayGuards = new Map<string, ReplayGuard>();
293+
/** Scheduled runs whose row may still need settling — see {@link DbJobAdapter.destroy}. */
294+
private readonly openScheduledRuns = new Set<OpenScheduledRun>();
295+
/** Set when `destroy()` begins: no scheduled run starts another attempt after it. */
296+
private shuttingDown = false;
252297

253298
constructor(args: {
254299
engine: JobEngineLike;
@@ -261,7 +306,11 @@ export class DbJobAdapter implements IJobService {
261306
this.recordRuns = args.options?.recordRuns ?? true;
262307
// The logger reaches `inner` so its skipped-tick line (#31811) is heard on
263308
// the no-cron fallback, where `inner` owns the timer.
264-
this.inner = new IntervalJobAdapter({ maxExecutions: args.options?.maxExecutions, logger: args.logger });
309+
this.inner = new IntervalJobAdapter({
310+
maxExecutions: args.options?.maxExecutions,
311+
logger: args.logger,
312+
shutdownDrainMs: args.options?.shutdownDrainMs,
313+
});
265314
this.cron = args.cron;
266315
}
267316

@@ -541,9 +590,38 @@ export class DbJobAdapter implements IJobService {
541590
*
542591
* `IJobService` does not declare `destroy()`, so the call is structural,
543592
* exactly like the `cancel` forwarding above.
593+
*
594+
* **A scheduled run in flight is waited for, or settled — never handed to a
595+
* released driver.** The kernel destroys plugins in reverse order, so the
596+
* driver goes AFTER this returns. Each timer adapter's `destroy()` waits for
597+
* the scheduled fire it holds, up to its `shutdownDrainMs`; a run that ends
598+
* inside that bound writes its own terminal row as usual. A run still going
599+
* when the bound passes has its open row settled here, while the driver is
600+
* still up, as `failed` with an `error` that says it was interrupted by
601+
* shutdown (and `sys_job` mirrors it like any failed run) — so no row is left
602+
* `running`, and when the abandoned handler does finish, its settle finds
603+
* the row already terminal and writes nothing. No scheduled run starts
604+
* another attempt once this has begun. Manual `trigger()` / `replay()` runs
605+
* are untouched: their caller awaits them.
544606
*/
545607
async destroy(): Promise<void> {
608+
this.shuttingDown = true;
546609
await this.inner.destroy();
610+
await this.destroyCron();
611+
await this.settleInterruptedRuns();
612+
}
613+
614+
/** Settle every scheduled run still open after the drain — see {@link DbJobAdapter.destroy}. */
615+
private async settleInterruptedRuns(): Promise<void> {
616+
for (const run of [...this.openScheduledRuns]) {
617+
// A row insert or terminal write already under way finishes first, so
618+
// the run is never settled twice and its insert is never orphaned.
619+
try { await run.write; } catch { /* its own catch logged it */ }
620+
await run.interrupt();
621+
}
622+
}
623+
624+
private async destroyCron(): Promise<void> {
547625
const cron = this.cron as (IJobService & { destroy?: () => Promise<void> }) | undefined;
548626
if (!cron || typeof cron.destroy !== 'function') return;
549627
try {
@@ -640,46 +718,78 @@ export class DbJobAdapter implements IJobService {
640718
): JobHandler {
641719
const wrapped: JobHandler = async (ctx) => {
642720
const trigger = runTriggerOf(wrapped, ctx);
721+
const scheduled = trigger === 'schedule';
643722
// Per-FIRE state: one of these closures exists per invocation, so two
644723
// overlapping fires of the same job never share a run row.
645-
let current: { id?: string; settled: boolean } | undefined;
724+
const fire: OpenScheduledRun = {
725+
interrupt: async () => {
726+
const startedMs = fire.current?.startedMs;
727+
await settle('failed', INTERRUPTED_BY_SHUTDOWN, startedMs === undefined ? undefined : Date.now() - startedMs);
728+
// Already settled by its own path? Then that terminal write may still
729+
// be under way — the driver has to outlast it too.
730+
await fire.write;
731+
},
732+
};
733+
const tracked = <T>(write: Promise<T>): Promise<T> => {
734+
fire.write = write;
735+
return write;
736+
};
646737

647738
const settle = async (status: TerminalStatus, error?: string, durationMs?: number) => {
648-
const run = current;
649-
// One terminal write per row. Nothing reaches here twice today; the
650-
// latch is what keeps that true as this seam grows (#7734).
739+
const run = fire.current;
740+
// One terminal write per row. Shutdown is the second path that can
741+
// reach here for one row — `destroy()` settling a run that outlived
742+
// the drain, then that run's own handler finishing — and the latch is
743+
// what makes the later of the two write nothing (#7734).
651744
if (!run || run.settled) return;
652745
run.settled = true;
653-
if (run.id) await this.finishRun(run.id, status, error, durationMs);
654-
await this.bumpJob(name, status, error);
746+
await tracked((async () => {
747+
if (run.id) await this.finishRun(run.id, status, error, durationMs);
748+
await this.bumpJob(name, status, error);
749+
})());
655750
};
656751

657-
// [ADR-0153 D7] The handler is told this attempt's `sys_job_run` row:
658-
// `current` is set by `onAttemptStart`, which runs before each attempt.
659-
return await runWithPolicy<void | JobRunOutcome>(name, () => handler(current?.id ? { ...ctx, runId: current.id } : ctx), options, {
660-
onAttemptStart: async (attempt) => {
661-
current = { id: this.recordRuns ? await this.startRun(name, trigger, attempt) : undefined, settled: false };
662-
},
663-
onAttemptSettled: async (_attempt, result) => {
664-
if (result.ok) {
665-
const outcome = result.value;
666-
if (outcome && outcome.outcome === 'degraded') {
667-
// Not a failure: the reason rides the existing `error` column and
668-
// `failure_count` stays flat (decided on #7072, recorded in the
669-
// `JobExecutionStatus` TSDoc). A reader must gate on `status`
670-
// before reading that column as a failure.
671-
await settle('degraded', outcome.reason, result.durationMs);
672-
} else {
673-
await settle('success', undefined, result.durationMs);
752+
if (scheduled) this.openScheduledRuns.add(fire);
753+
try {
754+
// [ADR-0153 D7] The handler is told this attempt's `sys_job_run` row:
755+
// `current` is set by `onAttemptStart`, which runs before each attempt.
756+
return await runWithPolicy<void | JobRunOutcome>(name, () => handler(fire.current?.id ? { ...ctx, runId: fire.current.id } : ctx), options, {
757+
onAttemptStart: async (attempt) => {
758+
if (scheduled && this.shuttingDown) throw shutdownBeforeAttempt(name, attempt);
759+
const startedMs = Date.now();
760+
const id = this.recordRuns ? await tracked(this.startRun(name, trigger, attempt)) : undefined;
761+
fire.current = { id, settled: false, startedMs };
762+
// Shutdown began while the row was being written: settle the row
763+
// now, while `destroy()` is still holding the driver for this run,
764+
// and never start the attempt itself.
765+
if (scheduled && this.shuttingDown) {
766+
await fire.interrupt();
767+
throw shutdownBeforeAttempt(name, attempt);
674768
}
675-
return;
676-
}
677-
const msg = result.error instanceof Error ? result.error.message : String(result.error);
678-
// `timeout` vs `failed` is the distinction `JobExecutionStatus` has
679-
// always declared and the durable record never carried.
680-
await settle(result.timedOut ? 'timeout' : 'failed', msg, result.durationMs);
681-
},
682-
});
769+
},
770+
onAttemptSettled: async (_attempt, result) => {
771+
if (result.ok) {
772+
const outcome = result.value;
773+
if (outcome && outcome.outcome === 'degraded') {
774+
// Not a failure: the reason rides the existing `error` column and
775+
// `failure_count` stays flat (decided on #7072, recorded in the
776+
// `JobExecutionStatus` TSDoc). A reader must gate on `status`
777+
// before reading that column as a failure.
778+
await settle('degraded', outcome.reason, result.durationMs);
779+
} else {
780+
await settle('success', undefined, result.durationMs);
781+
}
782+
return;
783+
}
784+
const msg = result.error instanceof Error ? result.error.message : String(result.error);
785+
// `timeout` vs `failed` is the distinction `JobExecutionStatus` has
786+
// always declared and the durable record never carried.
787+
await settle(result.timedOut ? 'timeout' : 'failed', msg, result.durationMs);
788+
},
789+
});
790+
} finally {
791+
this.openScheduledRuns.delete(fire);
792+
}
683793
};
684794
return wrapped;
685795
}

0 commit comments

Comments
 (0)