@proofoftech/flowsafe 0.19.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (172) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README.md +15 -0
  3. package/deployment-identity-protocol.d.mts +45 -1
  4. package/deployment-identity-protocol.mjs +169 -5
  5. package/dist/agent-host/index.d.ts +1 -1
  6. package/dist/agent-host/index.d.ts.map +1 -1
  7. package/dist/agent-host/index.js.map +1 -1
  8. package/dist/agent-host/router.d.ts.map +1 -1
  9. package/dist/agent-host/router.js +6 -2
  10. package/dist/agent-host/router.js.map +1 -1
  11. package/dist/agent-host/thread-host.d.ts +11 -0
  12. package/dist/agent-host/thread-host.d.ts.map +1 -1
  13. package/dist/agent-host/thread-host.js +53 -1
  14. package/dist/agent-host/thread-host.js.map +1 -1
  15. package/dist/agent-host/thread-topology.d.ts +35 -1
  16. package/dist/agent-host/thread-topology.d.ts.map +1 -1
  17. package/dist/agent-host/thread-topology.js +103 -7
  18. package/dist/agent-host/thread-topology.js.map +1 -1
  19. package/dist/agent-runner/durable-agent-runner.d.ts +19 -4
  20. package/dist/agent-runner/durable-agent-runner.d.ts.map +1 -1
  21. package/dist/agent-runner/durable-agent-runner.js +58 -28
  22. package/dist/agent-runner/durable-agent-runner.js.map +1 -1
  23. package/dist/approval-api/d1-store.d.ts.map +1 -1
  24. package/dist/approval-api/d1-store.js +6 -3
  25. package/dist/approval-api/d1-store.js.map +1 -1
  26. package/dist/approval-api/principal-identity.d.ts +32 -0
  27. package/dist/approval-api/principal-identity.d.ts.map +1 -0
  28. package/dist/approval-api/principal-identity.js +69 -0
  29. package/dist/approval-api/principal-identity.js.map +1 -0
  30. package/dist/approval-api/principal.d.ts +9 -12
  31. package/dist/approval-api/principal.d.ts.map +1 -1
  32. package/dist/approval-api/principal.js +9 -45
  33. package/dist/approval-api/principal.js.map +1 -1
  34. package/dist/approval-api/router.d.ts.map +1 -1
  35. package/dist/approval-api/router.js +9 -1
  36. package/dist/approval-api/router.js.map +1 -1
  37. package/dist/approval-api/service.d.ts +19 -0
  38. package/dist/approval-api/service.d.ts.map +1 -1
  39. package/dist/approval-api/service.js +41 -10
  40. package/dist/approval-api/service.js.map +1 -1
  41. package/dist/approval-api/types.d.ts +12 -0
  42. package/dist/approval-api/types.d.ts.map +1 -1
  43. package/dist/approval-api/types.js +12 -0
  44. package/dist/approval-api/types.js.map +1 -1
  45. package/dist/background-tasks/host.d.ts +127 -14
  46. package/dist/background-tasks/host.d.ts.map +1 -1
  47. package/dist/background-tasks/host.js +579 -50
  48. package/dist/background-tasks/host.js.map +1 -1
  49. package/dist/background-tasks/index.d.ts +2 -2
  50. package/dist/background-tasks/index.d.ts.map +1 -1
  51. package/dist/background-tasks/index.js +11 -6
  52. package/dist/background-tasks/index.js.map +1 -1
  53. package/dist/background-tasks/routes.d.ts +19 -2
  54. package/dist/background-tasks/routes.d.ts.map +1 -1
  55. package/dist/background-tasks/routes.js +4 -4
  56. package/dist/background-tasks/routes.js.map +1 -1
  57. package/dist/deployment-identity-protocol.d.ts +2 -2
  58. package/dist/deployment-identity-protocol.d.ts.map +1 -1
  59. package/dist/deployment-identity-protocol.js +1 -1
  60. package/dist/deployment-identity-protocol.js.map +1 -1
  61. package/dist/do-runner/cause-chain.d.ts +53 -0
  62. package/dist/do-runner/cause-chain.d.ts.map +1 -0
  63. package/dist/do-runner/cause-chain.js +96 -0
  64. package/dist/do-runner/cause-chain.js.map +1 -0
  65. package/dist/do-runner/d1-storage.d.ts +109 -5
  66. package/dist/do-runner/d1-storage.d.ts.map +1 -1
  67. package/dist/do-runner/d1-storage.js +289 -44
  68. package/dist/do-runner/d1-storage.js.map +1 -1
  69. package/dist/do-runner/deployment-identity.d.ts +29 -5
  70. package/dist/do-runner/deployment-identity.d.ts.map +1 -1
  71. package/dist/do-runner/deployment-identity.js +23 -6
  72. package/dist/do-runner/deployment-identity.js.map +1 -1
  73. package/dist/do-runner/do-error-response.d.ts +4 -23
  74. package/dist/do-runner/do-error-response.d.ts.map +1 -1
  75. package/dist/do-runner/do-error-response.js +19 -24
  76. package/dist/do-runner/do-error-response.js.map +1 -1
  77. package/dist/do-runner/do-status-error.d.ts +37 -0
  78. package/dist/do-runner/do-status-error.d.ts.map +1 -0
  79. package/dist/do-runner/do-status-error.js +42 -0
  80. package/dist/do-runner/do-status-error.js.map +1 -0
  81. package/dist/do-runner/durable-object.d.ts +2 -1
  82. package/dist/do-runner/durable-object.d.ts.map +1 -1
  83. package/dist/do-runner/durable-object.js +205 -19
  84. package/dist/do-runner/durable-object.js.map +1 -1
  85. package/dist/do-runner/execution-fence.d.ts +335 -0
  86. package/dist/do-runner/execution-fence.d.ts.map +1 -0
  87. package/dist/do-runner/execution-fence.js +534 -0
  88. package/dist/do-runner/execution-fence.js.map +1 -0
  89. package/dist/do-runner/index.d.ts +10 -3
  90. package/dist/do-runner/index.d.ts.map +1 -1
  91. package/dist/do-runner/index.js +16 -3
  92. package/dist/do-runner/index.js.map +1 -1
  93. package/dist/do-runner/init.d.ts +82 -1
  94. package/dist/do-runner/init.d.ts.map +1 -1
  95. package/dist/do-runner/init.js +58 -3
  96. package/dist/do-runner/init.js.map +1 -1
  97. package/dist/do-runner/inventory.d.ts +294 -0
  98. package/dist/do-runner/inventory.d.ts.map +1 -0
  99. package/dist/do-runner/inventory.js +811 -0
  100. package/dist/do-runner/inventory.js.map +1 -0
  101. package/dist/do-runner/notification-predicate.d.ts +8 -0
  102. package/dist/do-runner/notification-predicate.d.ts.map +1 -0
  103. package/dist/do-runner/notification-predicate.js +9 -0
  104. package/dist/do-runner/notification-predicate.js.map +1 -0
  105. package/dist/do-runner/runtime.d.ts +83 -0
  106. package/dist/do-runner/runtime.d.ts.map +1 -1
  107. package/dist/do-runner/runtime.js +131 -4
  108. package/dist/do-runner/runtime.js.map +1 -1
  109. package/dist/do-runner/start-idempotency.d.ts +508 -0
  110. package/dist/do-runner/start-idempotency.d.ts.map +1 -0
  111. package/dist/do-runner/start-idempotency.js +886 -0
  112. package/dist/do-runner/start-idempotency.js.map +1 -0
  113. package/dist/goals/objective-routes.d.ts +14 -0
  114. package/dist/goals/objective-routes.d.ts.map +1 -1
  115. package/dist/goals/objective-routes.js +45 -24
  116. package/dist/goals/objective-routes.js.map +1 -1
  117. package/dist/host-kit/do-run-topology.d.ts +15 -0
  118. package/dist/host-kit/do-run-topology.d.ts.map +1 -1
  119. package/dist/host-kit/do-run-topology.js +22 -1
  120. package/dist/host-kit/do-run-topology.js.map +1 -1
  121. package/dist/host-kit/flowsafe-worker.d.ts +11 -0
  122. package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
  123. package/dist/host-kit/flowsafe-worker.js +343 -62
  124. package/dist/host-kit/flowsafe-worker.js.map +1 -1
  125. package/dist/host-kit/host-approval-service.d.ts +20 -0
  126. package/dist/host-kit/host-approval-service.d.ts.map +1 -1
  127. package/dist/host-kit/host-approval-service.js +6 -0
  128. package/dist/host-kit/host-approval-service.js.map +1 -1
  129. package/dist/host-kit/index.d.ts +2 -2
  130. package/dist/host-kit/index.d.ts.map +1 -1
  131. package/dist/host-kit/index.js +1 -1
  132. package/dist/host-kit/index.js.map +1 -1
  133. package/dist/host-kit/run-route-error.d.ts +18 -0
  134. package/dist/host-kit/run-route-error.d.ts.map +1 -1
  135. package/dist/host-kit/run-route-error.js +23 -0
  136. package/dist/host-kit/run-route-error.js.map +1 -1
  137. package/dist/host-kit/run-router.d.ts +58 -1
  138. package/dist/host-kit/run-router.d.ts.map +1 -1
  139. package/dist/host-kit/run-router.js +120 -11
  140. package/dist/host-kit/run-router.js.map +1 -1
  141. package/dist/host-kit/stream-router.d.ts.map +1 -1
  142. package/dist/host-kit/stream-router.js +18 -9
  143. package/dist/host-kit/stream-router.js.map +1 -1
  144. package/dist/schedules/router.d.ts +15 -0
  145. package/dist/schedules/router.d.ts.map +1 -1
  146. package/dist/schedules/router.js +47 -17
  147. package/dist/schedules/router.js.map +1 -1
  148. package/dist/schedules/tick.d.ts +13 -0
  149. package/dist/schedules/tick.d.ts.map +1 -1
  150. package/dist/schedules/tick.js +59 -39
  151. package/dist/schedules/tick.js.map +1 -1
  152. package/dist/signal-providers/host-do.d.ts +12 -1
  153. package/dist/signal-providers/host-do.d.ts.map +1 -1
  154. package/dist/signal-providers/host-do.js +28 -3
  155. package/dist/signal-providers/host-do.js.map +1 -1
  156. package/dist/signal-providers/webhook-route.d.ts +14 -0
  157. package/dist/signal-providers/webhook-route.d.ts.map +1 -1
  158. package/dist/signal-providers/webhook-route.js +28 -5
  159. package/dist/signal-providers/webhook-route.js.map +1 -1
  160. package/dist/signals/notification-dispatch.d.ts +13 -0
  161. package/dist/signals/notification-dispatch.d.ts.map +1 -1
  162. package/dist/signals/notification-dispatch.js +20 -1
  163. package/dist/signals/notification-dispatch.js.map +1 -1
  164. package/dist/signals/notifications-d1.d.ts +8 -0
  165. package/dist/signals/notifications-d1.d.ts.map +1 -1
  166. package/dist/signals/notifications-d1.js +15 -9
  167. package/dist/signals/notifications-d1.js.map +1 -1
  168. package/dist/signals/thread-do-routes.d.ts.map +1 -1
  169. package/dist/signals/thread-do-routes.js +86 -18
  170. package/dist/signals/thread-do-routes.js.map +1 -1
  171. package/package.json +1 -1
  172. package/scripts/seed-deployment-identity.mjs +22 -4
@@ -1,27 +1,34 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
- // Track B (M-003): host a Mastra BackgroundTaskManager on a Durable Object, and
3
- // survive DO eviction BY CONSTRUCTION (DL-015).
2
+ // Host a Mastra BackgroundTaskManager on a Durable Object and survive eviction
3
+ // BY CONSTRUCTION.
4
4
  //
5
- // THE RECOVERY SEAM (spike B-S2, pinned against @mastra/core 1.50.0 dist —
6
- // validation finding R-002). `recoverStaleTasks()` and `handleResume` are
7
- // PRIVATE and `getStorage()` is async, so the alarm CANNOT call
8
- // `recoverStaleTasks()` directly. But it does not need to: the PUBLIC async
9
- // `manager.init(pubsub)` fires `recoverStaleTasks()` internally (manager.d.ts:21
10
- // -> chunk .init -> `await this.recoverStaleTasks()`), guarded by its own
11
- // initPromise so it runs once per manager INSTANCE. A DO evicted mid-task leaves
12
- // its task row 'running'/'pending' in D1; when the DO is next instantiated (a
13
- // FRESH manager), `boot()` re-registers the static tool executors, starts the
14
- // workflow workers, and only then calls `init(pubsub)`. Init's recovery resets a
5
+ // THE RECOVERY SEAM, pinned against @mastra/core 1.50.0 dist.
6
+ // `recoverStaleTasks()` and `handleResume` are PRIVATE, and `getStorage()` is
7
+ // async, so the alarm CANNOT call `recoverStaleTasks()` directly. It does not
8
+ // need to: the PUBLIC async `manager.init(pubsub)` fires `recoverStaleTasks()`
9
+ // internally. Its manager.d.ts:21 -> chunk .init path awaits
10
+ // `this.recoverStaleTasks()`, guarded by its own initPromise so it runs once
11
+ // per manager INSTANCE. A DO evicted mid-task leaves its task row
12
+ // 'running'/'pending' in D1. When the DO is next instantiated with a FRESH
13
+ // manager, `boot()` re-registers the static tool executors, starts the workflow
14
+ // workers, and only then calls `init(pubsub)`. Init's recovery resets a
15
15
  // stranded 'running' task (maxRetries > 0) to 'pending' and re-dispatches it;
16
- // starting workers first guarantees that the workflow event published by that
17
- // dispatch has a subscriber. Its workflow step resolves the executor by tool
18
- // name via the re-registered static registry (the cross-process path core ships
19
- // `registerStaticExecutor` for). The DO ALARM is what WAKES an evicted DO so
20
- // this happens without waiting for a request. No private method is ever called;
21
- // the seam is `registerStaticExecutor` + `startWorkers()` + `init(pubsub)`, all
22
- // public.
16
+ // starting workers first guarantees that the workflow event has a subscriber.
17
+ // Its workflow step resolves the executor by tool name via the re-registered
18
+ // static registry: the cross-process path core ships `registerStaticExecutor`
19
+ // for this. The DO ALARM WAKES an evicted DO so this happens without waiting
20
+ // for a request. No private method is ever called; the seam is
21
+ // `registerStaticExecutor` + `startWorkers()` + `init(pubsub)`, all public.
23
22
  //
24
- // v1 policy (DL-005/P8): connectors are foreground-only, so approval-carrying
23
+ // THE FENCE SPLITS THAT SEAM IN TWO. `registerStaticExecutor` claims
24
+ // nothing and always runs; `startWorkers()` + `init(pubsub)` are what make this
25
+ // instance a dispatcher, and behind a closed deployment execution fence they
26
+ // are held back entirely — init's recovery would otherwise fail every stranded
27
+ // row outright and re-claim every pending one. The held-back phase is retried
28
+ // on every later boot (request or alarm), so reopening the fence is all it
29
+ // takes to resume. See #ensureDispatching.
30
+ //
31
+ // v1 policy: connectors are foreground-only, so approval-carrying
25
32
  // tools never enter this suspend/resume topology. Background suspend/resume
26
33
  // stays available for NON-gated tools (e.g. a long research tool awaiting an
27
34
  // external webhook); such a task's resume mints no capability.
@@ -36,8 +43,11 @@
36
43
  // row. The specialized store and TTL purge therefore delete the internal
37
44
  // snapshot before deleting the task row.
38
45
  import { BackgroundTaskManager, } from '@mastra/core/background-tasks';
46
+ import { EXECUTION_FENCE_SUSPEND_KEY } from '../do-runner/execution-fence.js';
47
+ import { admitsDrainableExecution, ExecutionFencedError, readExecutionFence, } from '../do-runner/index.js';
39
48
  import { finiteNonnegativeNumber, nonnegativeSafeInteger, positiveSafeInteger, } from '../numeric-config.js';
40
49
  import { backgroundTasksStore, DURABLE_OBJECT_BACKGROUND_TASKS_D1, SERIALIZED_WORKFLOWS_D1, } from './d1-storage.js';
50
+ export { EXECUTION_FENCE_SUSPEND_KEY } from '../do-runner/execution-fence.js';
41
51
  function validateManagerConfig(config) {
42
52
  if (!config)
43
53
  return;
@@ -80,22 +90,189 @@ function validateManagerConfig(config) {
80
90
  positiveSafeInteger(cleanup.cleanupIntervalMs, 'backgroundTasks.manager.cleanup.cleanupIntervalMs');
81
91
  }
82
92
  }
93
+ /**
94
+ * Was this row parked by the backstop, rather than suspended by its own tool?
95
+ * The distinction is the whole safety of the sweep: a task awaiting a webhook
96
+ * is suspended on purpose and must stay that way.
97
+ */
98
+ function isFenceParked(task) {
99
+ const payload = task.suspendPayload;
100
+ return (typeof payload === 'object' &&
101
+ payload !== null &&
102
+ EXECUTION_FENCE_SUSPEND_KEY in payload);
103
+ }
104
+ /**
105
+ * How many fence-parked tasks ONE BOOT re-drives.
106
+ *
107
+ * Sized as a boot-path budget rather than a queue-drain rate: each resume is a
108
+ * publish onto the topic the manager just subscribed to, and the boot this
109
+ * blocks is what every request on the deployment is waiting behind. The
110
+ * remainder is not dropped — it stays `suspended`, marked, and inspectable
111
+ * through the read routes — and the ALARM lane below is what drains it, so a
112
+ * deployment reopening with a large parked queue starts moving on its first
113
+ * request without that request paying for the whole queue.
114
+ *
115
+ * Exported for the test that pins the boot/alarm budget boundary, and kept off
116
+ * `./index.js` — the only export map entry this directory has — so it stays
117
+ * package-internal rather than becoming a number a consumer can depend on.
118
+ */
119
+ export const MAX_FENCE_RESUMES_PER_PASS = 25;
120
+ /**
121
+ * How many one ALARM re-drives — the lane convergence actually rides on.
122
+ *
123
+ * Ten boot-budgets, because an alarm is a background duty and nothing is
124
+ * waiting behind it, unlike a boot. This is what makes the sweep terminate
125
+ * rather than merely make progress: the alarm recurs (the host arms it for
126
+ * `cleanup()` already), each wake drains up to this many, and the invocation
127
+ * itself keeps scanning until a scan finds nothing left to resume.
128
+ */
129
+ const MAX_FENCE_RESUMES_PER_ALARM = 250;
130
+ /**
131
+ * The hard bound on how many LIST queries one sweep invocation may issue.
132
+ *
133
+ * The sweep pages, and paging is what keeps an old parked cohort reachable
134
+ * once newer tool-suspends sit ahead of it in the scan order. Bounding the
135
+ * scans rather than only the resumes is what keeps a pathological mix — many
136
+ * thousands of tool-suspended rows and one stale parked cohort behind them —
137
+ * from turning a single wake into an unbounded read loop.
138
+ *
139
+ * A wake that hits this bound WITHOUT resuming anything has proved only that
140
+ * the first `MAX_FENCE_RESUME_SCANS * FENCE_RESUME_SCAN_PAGE` rows carry no
141
+ * marker, so it records where it stopped (`#sweepScanFloor`) and the next wake
142
+ * continues from there. Restarting every wake at page 0 instead would re-read
143
+ * the same prefix forever, and a cohort parked behind that many newer
144
+ * tool-suspends would never be reached at all.
145
+ *
146
+ * Exported alongside FENCE_RESUME_SCAN_PAGE for the same narrow reason
147
+ * MAX_FENCE_RESUMES_PER_PASS is: the test that proves a cohort past one wake's
148
+ * scan bound is still reached has to build a set that large, and a size
149
+ * hard-coded there would drift from these. Both stay off `./index.js` — they
150
+ * are tuning, not contract.
151
+ */
152
+ export const MAX_FENCE_RESUME_SCANS = 20;
153
+ /**
154
+ * How many `suspended` rows one pass READS to find that many.
155
+ *
156
+ * Larger than the resume budget on purpose. The fence marker lives in the
157
+ * suspend PAYLOAD, which no filter can express, so the pass has to read rows
158
+ * and sort them itself — and a page sized exactly to the resume budget would
159
+ * let a handful of tool-suspended tasks (awaiting a webhook, say) crowd the
160
+ * parked ones out of every pass and stall recovery indefinitely. Reading wider
161
+ * than it acts costs one query and buys headroom for that mix, while still
162
+ * bounding what a boot pulls out of D1.
163
+ */
164
+ export const FENCE_RESUME_SCAN_PAGE = 100;
165
+ /**
166
+ * A registration failure this host CHOSE, from wiring it can re-check without
167
+ * touching storage: the domains a host passed are the wrong ones.
168
+ *
169
+ * The distinction is what lets `boot()` memoize one kind of failure and retry
170
+ * the other. A configuration fault is deterministic — the next boot re-reads
171
+ * the same host wiring and fails identically — so caching it costs nothing and
172
+ * keeps the error stable. Everything else reaching #doRegister comes from a
173
+ * storage read (`getStorage()`, `getStore(...)`), and a transient D1 fault
174
+ * there must not lock this instance's read routes out until eviction.
175
+ *
176
+ * The split is deliberately conservative in one direction: a deterministic
177
+ * fault raised from INSIDE a storage read (a Mastra configured with no storage
178
+ * at all) is retried like a transient one, because from here the two are the
179
+ * same call. That costs one repeated read per boot and nothing else, whereas
180
+ * mistaking a transient fault for a permanent one costs the isolate's routes.
181
+ *
182
+ * Not exported: a caller cannot act on the difference, only this class can.
183
+ */
184
+ class BackgroundTasksConfigurationError extends Error {
185
+ constructor(message) {
186
+ super(message);
187
+ this.name = 'BackgroundTasksConfigurationError';
188
+ }
189
+ }
190
+ /**
191
+ * Raw-manager access for THIS PACKAGE'S TESTS, and nothing else.
192
+ *
193
+ * A side table rather than a property ON the host, because a property is
194
+ * reachable whatever it is keyed by: an own symbol key is enumerable through
195
+ * `Object.getOwnPropertySymbols(host)[0]`, so "unreachable from the published
196
+ * package" was true of the NAME and false of the manager. Nothing outside this
197
+ * module can produce this WeakMap, so the accessor below — absent from
198
+ * `./index.js`, the only export map entry this directory has — is the only way
199
+ * in, and the claim is now literally true.
200
+ *
201
+ * It exists because the host's lifecycle contract IS its interleaving with
202
+ * core's manager (init before shutdown before stopWorkers, the enqueue guard
203
+ * flipping before the first await), and there is no way to observe that
204
+ * ordering from outside without a handle on the manager those calls land on.
205
+ *
206
+ * Production code must not use it: everything a host legitimately does goes
207
+ * through `enqueue` (fence-gated) or the three reads on the host itself.
208
+ */
209
+ const hostManagers = new WeakMap();
210
+ /** @see hostManagers — tests only, and never re-exported. */
211
+ export function backgroundTaskManagerForTests(host) {
212
+ const manager = hostManagers.get(host);
213
+ if (!manager) {
214
+ throw new Error('background-tasks: host has no manager registered');
215
+ }
216
+ return manager;
217
+ }
83
218
  /**
84
219
  * A BackgroundTaskManager bound to a hosting DO's Mastra + pubsub, with the
85
220
  * boot/alarm lifecycle that makes DO eviction survivable. The hosting DO owns
86
221
  * alarm arming (it needs `ctx.storage.setAlarm`); this class owns the manager
87
- * wiring, the recovery-firing `boot()`, and the alarm `cleanup()` duty. The raw
88
- * manager is reachable as `.manager` for the read-only routes to wrap — never
89
- * expose it directly over HTTP.
222
+ * wiring, the recovery-firing `boot()`, and the alarm `cleanup()` duty.
223
+ *
224
+ * The manager itself is PRIVATE. It carries `enqueue`, `registerTaskContext`,
225
+ * `registerStaticExecutor`, `resume`, and `restart` — every one of which puts a
226
+ * task body on this deployment WITHOUT passing the fence, because the gate that
227
+ * stops a locked deployment executing is the `#gated` wrapper this host puts
228
+ * around an executor on the way in. A caller holding the manager could enqueue
229
+ * an unwrapped executor and defeat both. What this class forwards instead is
230
+ * the fence-gated `enqueue` and the three READS the host route adapter serves.
90
231
  */
91
232
  export class BackgroundTaskHost {
92
- manager;
233
+ #manager;
93
234
  #mastra;
94
235
  #pubsub;
95
236
  #executors;
96
237
  #execution;
238
+ #executionFence;
97
239
  #booted;
98
- #bootSettled = false;
240
+ /** Phase B (workers + init), memoized only once it has actually run. */
241
+ #dispatching;
242
+ /**
243
+ * The in-flight phase-B ATTEMPT, including the fence read that precedes
244
+ * admission — recorded synchronously by #ensureDispatching and cleared when
245
+ * it settles. `#dispatching` cannot serve this purpose: it is unset for the
246
+ * whole duration of the fence read, which is exactly the window two
247
+ * concurrent boots interleave in.
248
+ */
249
+ #dispatchAttempt;
250
+ /**
251
+ * The whole in-flight `boot()` — registration, the fence read, and phase B if
252
+ * the fence admitted it — recorded SYNCHRONOUSLY by `boot()`.
253
+ *
254
+ * Distinct from `#dispatching`, which is the memo of an ADMITTED phase and so
255
+ * is still unset while the fence read is in flight. Teardown waits on THIS:
256
+ * `shutdown()` called on a boot that has not reached admission yet would
257
+ * otherwise find nothing to wait for, return having stopped nothing, and
258
+ * leave behind the workers and the subscribed manager that boot went on to
259
+ * start.
260
+ */
261
+ #bootAttempt;
262
+ #bootAttemptSettled = false;
263
+ /**
264
+ * Where the NEXT sweep starts paging — the sweep's only state that outlives
265
+ * one invocation.
266
+ *
267
+ * Zero means "from the newest suspension", which is right whenever the last
268
+ * wake resumed something or reached the end of the set. It is non-zero only
269
+ * after a wake spent its whole scan budget finding no markers: that wake
270
+ * examined a prefix and proved it marker-free, so the next one continues
271
+ * past it instead of re-reading it. Instance state rather than storage
272
+ * because it is an optimisation, not a fact: an evicted DO simply starts
273
+ * from the top again, which is correct, only slower.
274
+ */
275
+ #sweepScanFloor = 0;
99
276
  #managerNeedsShutdown = false;
100
277
  #workersNeedStop = false;
101
278
  #shutdownRequested = false;
@@ -106,36 +283,69 @@ export class BackgroundTaskHost {
106
283
  this.#pubsub = options.pubsub;
107
284
  this.#executors = options.executors;
108
285
  this.#execution = options.execution ?? false;
109
- this.manager = new BackgroundTaskManager({
286
+ this.#executionFence = options.executionFence;
287
+ this.#manager = new BackgroundTaskManager({
110
288
  enabled: true,
111
289
  ...options.manager,
112
290
  });
291
+ hostManagers.set(this, this.#manager);
113
292
  // Must precede init(): the manager reads its Mastra for storage, the
114
293
  // internal background-task workflow registration, and id generation.
115
- this.manager.__registerMastra(options.mastra);
294
+ this.#manager.__registerMastra(options.mastra);
116
295
  }
117
296
  /**
118
- * Durable-Object boot wiring. Fail fast if the backgroundTasks storage domain is
119
- * missing, re-register the static executors, start execution-mode workflow
120
- * workers, THEN call `init(pubsub)` — whose internal `recoverStaleTasks()`
121
- * re-drives any task the evicted instance left mid-flight. Executors and the
122
- * workflow subscriber both go in BEFORE recovery publishes work. A failed
123
- * startup unwinds attempted components in reverse order. Memoized per
124
- * instance: `init` is itself idempotent (initPromise), and `boot()` from both
125
- * `fetch()` and `alarm()` must not double-register.
297
+ * Durable-Object boot wiring, in two phases with different lifetimes.
298
+ *
299
+ * REGISTRATION (memoized for the life of the instance): validate the storage
300
+ * domains and re-register the static executors. Nothing here subscribes,
301
+ * claims, or recovers, so it is safe in every fence state — and it must be,
302
+ * because every host boots before routing and the read routes hang off this
303
+ * memo.
304
+ *
305
+ * DISPATCHING (fence-gated, re-attempted on every boot until it is admitted):
306
+ * `startWorkers()` plus `manager.init(pubsub)`. Those two are what make this
307
+ * instance CLAIM work — see #ensureDispatching for why they cannot run behind
308
+ * a closed fence. A refused attempt is deliberately not memoized, so the next
309
+ * `boot()` from a request or an alarm starts dispatching once the fence
310
+ * reopens, with no operator action.
311
+ *
312
+ * A registration that FAILED is memoized only when it can only fail again:
313
+ * the same non-memoized-refusal reasoning #ensureDispatching applies to the
314
+ * fence. A transient storage fault on the first request into a fresh isolate
315
+ * would otherwise be the permanent answer for the life of that isolate — the
316
+ * read routes hang off this memo, so the host would keep 500ing a queue it
317
+ * can now reach, until an eviction nobody can schedule.
126
318
  */
127
319
  boot() {
128
320
  if (this.#shutdownRequested) {
129
321
  return Promise.reject(new Error('background-tasks: host is shutting down'));
130
322
  }
131
323
  if (!this.#booted) {
132
- this.#booted = this.#doBoot().finally(() => {
133
- this.#bootSettled = true;
324
+ const registration = this.#doRegister().catch((error) => {
325
+ // Identity-checked before clearing, the idiom `#ensureDispatching`
326
+ // and `shutdown()` use: a later registration must never be cleared
327
+ // by an earlier one's settlement.
328
+ if (!(error instanceof BackgroundTasksConfigurationError) &&
329
+ this.#booted === registration) {
330
+ this.#booted = undefined;
331
+ }
332
+ throw error;
134
333
  });
334
+ this.#booted = registration;
135
335
  }
136
- return this.#booted;
336
+ const registered = this.#booted;
337
+ // Recorded before this method returns, so a `shutdown()` on the very next
338
+ // statement already has the whole attempt to wait on.
339
+ this.#bootAttemptSettled = false;
340
+ const attempt = registered
341
+ .then(() => this.#ensureDispatching())
342
+ .finally(() => {
343
+ this.#bootAttemptSettled = true;
344
+ });
345
+ this.#bootAttempt = attempt;
346
+ return attempt;
137
347
  }
138
- async #doBoot() {
348
+ async #doRegister() {
139
349
  // Fail-fast with a clear message before any dispatch could surface core's
140
350
  // terser error deep in a lifecycle callback.
141
351
  const tasks = await backgroundTasksStore(this.#mastra);
@@ -144,32 +354,113 @@ export class BackgroundTaskHost {
144
354
  const workflows = await this.#mastra.getStorage()?.getStore('workflows');
145
355
  if (!workflows ||
146
356
  workflows[SERIALIZED_WORKFLOWS_D1] !== true) {
147
- throw new Error('background-tasks: execution requires DurableObjectWorkflowsStorageD1');
357
+ throw new BackgroundTasksConfigurationError('background-tasks: execution requires DurableObjectWorkflowsStorageD1');
148
358
  }
149
359
  const durableTasks = tasks;
150
360
  if (durableTasks[DURABLE_OBJECT_BACKGROUND_TASKS_D1] !== true) {
151
- throw new Error('background-tasks: execution requires DurableObjectBackgroundTasksStorageD1');
361
+ throw new BackgroundTasksConfigurationError('background-tasks: execution requires DurableObjectBackgroundTasksStorageD1');
152
362
  }
153
363
  }
154
364
  else {
155
365
  await this.#warnIfBodiesCannotExecute();
156
366
  }
157
367
  for (const [toolName, executor] of Object.entries(this.#executors)) {
158
- this.manager.registerStaticExecutor(toolName, executor);
368
+ this.#manager.registerStaticExecutor(toolName, this.#gated(executor));
159
369
  }
370
+ }
371
+ /**
372
+ * THE gate that matters: whether this instance becomes a DISPATCHER at all.
373
+ *
374
+ * `manager.init(pubsub)` is the only thing that subscribes `handleDispatch`,
375
+ * and `handleDispatch` is what writes `status: 'running'` — the CLAIM. It
376
+ * also runs `recoverStaleTasks()`, which on @mastra/core 1.53.0 does two
377
+ * destructive things behind a closed fence:
378
+ *
379
+ * 1. every stranded `running` row with `maxRetries === 0` (the DEFAULT) is
380
+ * marked `failed` outright, before any executor is consulted; and
381
+ * 2. every `pending` row is re-dispatched, i.e. claimed.
382
+ *
383
+ * Neither is reachable from inside an executor, which is why the gate lives
384
+ * here and not there. Skipping init leaves pending rows pending and stranded
385
+ * rows stranded — untouched, uncharged, and still visible to any nonterminal
386
+ * census — and the published dispatch event simply has no subscriber. One
387
+ * fence read per boot PASS, never memoized on refusal.
388
+ *
389
+ * `draining` still dispatches: the queue is exactly the work a drain exists
390
+ * to finish.
391
+ */
392
+ #ensureDispatching() {
393
+ if (this.#dispatching)
394
+ return this.#dispatching;
395
+ // DELIBERATELY NOT `async`, and the memo below is assigned before this
396
+ // method's first await can exist.
397
+ //
398
+ // `#dispatching` alone cannot collapse concurrent callers, because it is
399
+ // set only once the fence read RESUMES: two boots that both reach the
400
+ // guard above before either read completes would both go on to assign it,
401
+ // and both would run #startDispatching — `startWorkers()` twice and
402
+ // `manager.init(pubsub)` twice, which subscribes handleDispatch TWICE, so
403
+ // every dispatch is handled twice: double claim, double body execution.
404
+ // `#managerNeedsShutdown`/`#workersNeedStop` are booleans, so teardown
405
+ // would then stop one of the two. That is not hypothetical here: the
406
+ // request path and `onAlarm()` call `boot()` independently (a host's own
407
+ // memo collapses only the request path), so the two genuinely interleave.
408
+ //
409
+ // Recorded SYNCHRONOUSLY instead — the same shape `boot()` uses for
410
+ // `#bootAttempt`, for the same reason — and cleared when it settles, so a
411
+ // refusal still retries on the next boot.
412
+ const inFlight = this.#dispatchAttempt;
413
+ if (inFlight)
414
+ return inFlight;
415
+ const attempt = this.#attemptDispatching().finally(() => {
416
+ // Identity-checked before clearing, the idiom `shutdown()` uses below: a
417
+ // later attempt must never be cleared by an earlier one's settlement.
418
+ if (this.#dispatchAttempt === attempt)
419
+ this.#dispatchAttempt = undefined;
420
+ });
421
+ this.#dispatchAttempt = attempt;
422
+ return attempt;
423
+ }
424
+ async #attemptDispatching() {
425
+ const fence = await readExecutionFence(this.#executionFence);
426
+ // The fence read is an await, and `boot()`'s shutdown guard ran before it.
427
+ // A `shutdown()` that arrived in between has already decided this instance
428
+ // is going away; subscribing and claiming for the duration of an in-flight
429
+ // teardown would hand work to a manager that is about to stop — and
430
+ // `#doShutdown` waits on this very attempt, so it would wait for the claim
431
+ // it is trying to prevent.
432
+ if (this.#shutdownRequested)
433
+ return;
434
+ if (!admitsDrainableExecution(fence)) {
435
+ console.warn(JSON.stringify({
436
+ type: 'background-tasks.dispatch-fenced',
437
+ state: fence.state,
438
+ reason: 'workers and stale-task recovery are held back; queued tasks stay pending until the fence reopens',
439
+ }));
440
+ return;
441
+ }
442
+ this.#dispatching ??= this.#startDispatching().catch((error) => {
443
+ // Not memoized on failure, for the same reason a refusal is not: the
444
+ // next boot must be able to try again.
445
+ this.#dispatching = undefined;
446
+ throw error;
447
+ });
448
+ return this.#dispatching;
449
+ }
450
+ async #startDispatching() {
160
451
  try {
161
452
  if (this.#execution) {
162
453
  this.#workersNeedStop = true;
163
454
  await this.#mastra.startWorkers();
164
455
  }
165
456
  this.#managerNeedsShutdown = true;
166
- await this.manager.init(this.#pubsub);
457
+ await this.#manager.init(this.#pubsub);
167
458
  }
168
459
  catch (primary) {
169
460
  const cleanupErrors = [];
170
461
  if (this.#managerNeedsShutdown) {
171
462
  try {
172
- await this.manager.shutdown();
463
+ await this.#manager.shutdown();
173
464
  this.#managerNeedsShutdown = false;
174
465
  }
175
466
  catch (error) {
@@ -189,6 +480,216 @@ export class BackgroundTaskHost {
189
480
  throw primary;
190
481
  throw new AggregateError([primary, ...cleanupErrors], 'background-tasks: boot failed and cleanup also failed', { cause: primary });
191
482
  }
483
+ // AFTER init, because resume() publishes onto the topic init subscribes.
484
+ // The BOOT budget: enough to start moving, small enough that the request
485
+ // that triggered this boot does not wait for the whole parked queue.
486
+ // onAlarm() is where the rest drains.
487
+ await this.#resumeFenceSuspendedTasks(MAX_FENCE_RESUMES_PER_PASS);
488
+ }
489
+ /**
490
+ * Re-drive the tasks the executor backstop parked, once dispatching resumes.
491
+ *
492
+ * `recoverStaleTasks()` re-drives `running` and `pending` rows and knows
493
+ * nothing about `suspended` ones, so without this a task the backstop saved
494
+ * from destruction would be saved into a state nothing ever leaves. Scoped by
495
+ * the backstop's own marker: a task suspended by its TOOL (awaiting a
496
+ * webhook, say) is a different thing entirely and must stay suspended.
497
+ *
498
+ * BUDGETED, not one-shot. It runs on two lanes with two budgets: `boot()`
499
+ * spends MAX_FENCE_RESUMES_PER_PASS so the first request after a reopen is
500
+ * not stalled behind the whole parked queue, and `onAlarm()` spends
501
+ * MAX_FENCE_RESUMES_PER_ALARM on a lane nothing is waiting behind. The alarm
502
+ * lane is what makes this CONVERGE: one invocation keeps scanning until a
503
+ * scan resumes nothing, and the alarm recurs, so a queue larger than one
504
+ * alarm's budget still drains over the next few wakes with no eviction and no
505
+ * operator action. (An earlier shape swept only from #startDispatching, which
506
+ * runs once — every later boot returned the settled memo and never swept
507
+ * again, so anything past the first cap stayed parked indefinitely.)
508
+ *
509
+ * PAGES, because the scan order alone cannot reach a stale cohort. Newest
510
+ * suspensions first is right for the common case — the parked cohort is the
511
+ * one that just parked — but leftovers from an earlier lock carry an OLD
512
+ * `suspendedAt`, so after a lock/reopen/lock cycle plus a page-worth of newer
513
+ * tool-suspends, page 0 would never contain them again. So: a page that
514
+ * resumed nothing and came back FULL means the markers are deeper, and the
515
+ * sweep advances; a page that resumed something restarts at the top, because
516
+ * resuming removes rows from the set being paged and any fixed offset would
517
+ * then skip rows. `#resumedIds` makes that restart cheap and terminating —
518
+ * each pass strictly grows it.
519
+ *
520
+ * And the paging SURVIVES the wake, because within one wake it is bounded
521
+ * (MAX_FENCE_RESUME_SCANS). A cohort sitting behind more newer tool-suspends
522
+ * than one wake can page through would otherwise be stranded outright: every
523
+ * wake would re-read the same marker-free prefix and stop in the same place.
524
+ * So a wake that spends its whole scan budget finding nothing leaves
525
+ * `#sweepScanFloor` where it stopped and the next one resumes there, while
526
+ * any wake that resumes something — or reaches the end of the set — puts it
527
+ * back to zero, since both mean the prefix is worth re-reading. A floor left
528
+ * past the end of a shrunken set reads a short page and resets itself.
529
+ *
530
+ * The cost of that is bounded and the right way round: while the floor is
531
+ * deep, a cohort parked FRESH at the top waits the few wakes it takes to page
532
+ * to the end of the set (which resets the floor), instead of the old shape's
533
+ * "waits forever". Delaying the reachable cohort by a wake or two is the
534
+ * cheaper error than stranding the unreachable one permanently.
535
+ *
536
+ * `perPage`/`orderBy` are ADAPTER-DEPENDENT: honoured by
537
+ * @mastra/cloudflare-d1's SQL builder and by this package's D1 domain, but an
538
+ * adapter that ignores them returns the whole list — which is why the loop
539
+ * counts its own resumes rather than trusting the page size to bound them.
540
+ *
541
+ * Answers how many it resumed, so the caller can log a lane that is making
542
+ * progress distinctly from one that has drained.
543
+ */
544
+ async #resumeFenceSuspendedTasks(budget) {
545
+ // Resuming is asynchronous at the storage layer (resume() publishes; the
546
+ // handler is what writes 'running'), so a row can still read `suspended` on
547
+ // the next scan. Without this the sweep could re-resume the same rows —
548
+ // wasted publishes at best, and core throws outright once the row HAS
549
+ // moved, which would abort the whole invocation.
550
+ const resumedIds = new Set();
551
+ let page = this.#sweepScanFloor;
552
+ // The floor the NEXT wake starts from. Any wake that resumed something has
553
+ // changed the set it was paging, so its prefix is worth re-reading and the
554
+ // floor goes back to zero whatever this is called with.
555
+ const finish = (nextFloor) => {
556
+ this.#sweepScanFloor = resumedIds.size > 0 ? 0 : nextFloor;
557
+ return resumedIds.size;
558
+ };
559
+ for (let scan = 0; scan < MAX_FENCE_RESUME_SCANS; scan += 1) {
560
+ let tasks;
561
+ try {
562
+ ({ tasks } = await this.#manager.listTasks({
563
+ status: 'suspended',
564
+ orderBy: 'suspendedAt',
565
+ orderDirection: 'desc',
566
+ page,
567
+ perPage: FENCE_RESUME_SCAN_PAGE,
568
+ }));
569
+ }
570
+ catch (error) {
571
+ this.#logFenceResumeFailure(error);
572
+ // This page proved nothing, so the next wake retries it rather than
573
+ // stepping over rows it never read.
574
+ return finish(page);
575
+ }
576
+ let resumedThisScan = 0;
577
+ for (const task of tasks) {
578
+ if (resumedIds.size >= budget)
579
+ return finish(0);
580
+ if (resumedIds.has(task.id) || !isFenceParked(task))
581
+ continue;
582
+ try {
583
+ await this.#manager.resume(task.id);
584
+ }
585
+ catch (error) {
586
+ // Expected at capacity: core refuses a resume that would exceed the
587
+ // concurrency limit. Stopping is the honest response — the rows stay
588
+ // parked and the next wake retries once slots free — and it keeps a
589
+ // saturated deployment from burning the scan budget on refusals.
590
+ this.#logFenceResumeFailure(error);
591
+ return finish(page);
592
+ }
593
+ resumedIds.add(task.id);
594
+ resumedThisScan += 1;
595
+ }
596
+ if (resumedThisScan > 0) {
597
+ page = 0;
598
+ continue;
599
+ }
600
+ // Nothing here to resume. A SHORT page is the end of the set, so there is
601
+ // nothing deeper and this sweep has drained. A full one means the markers
602
+ // may simply be further down.
603
+ if (tasks.length < FENCE_RESUME_SCAN_PAGE)
604
+ return finish(0);
605
+ page += 1;
606
+ }
607
+ // Out of scans with nothing found: `page` is the first row range this wake
608
+ // never read, and the next one starts there.
609
+ return finish(page);
610
+ }
611
+ #logFenceResumeFailure(error) {
612
+ // Best effort: a failure here leaves the rows suspended and inspectable,
613
+ // which is where they already were. Never fails the boot that was about to
614
+ // start serving, nor the alarm duty that follows.
615
+ console.error(JSON.stringify({
616
+ type: 'background-tasks.fence-resume-error',
617
+ reason: error instanceof Error ? error.message : String(error),
618
+ }));
619
+ }
620
+ /**
621
+ * The fail-closed BACKSTOP, not the gate. #ensureDispatching stops this
622
+ * instance claiming work behind a closed fence; this only covers the narrow
623
+ * race where a subscriber started while the fence was open consumes a
624
+ * dispatch event published just before it closed. By then core has ALREADY
625
+ * written `status: 'running'`, so the claim cannot be undone from here — only
626
+ * exited well.
627
+ *
628
+ * SUSPEND, never throw. A thrown executor becomes `outcome: 'retry'`, and
629
+ * core retries only while `retryCount < maxRetries` — the default maxRetries
630
+ * is 0, so the very first throw settles the row `failed`: work destroyed, and
631
+ * silently absent from any nonterminal census. `suspend()` instead persists
632
+ * `status: 'suspended'` with a payload naming the fence, which is nonterminal,
633
+ * inspectable, and re-driven by #resumeFenceSuspendedTasks after reopen.
634
+ * Throwing survives only as the last resort for a core that supplied no
635
+ * `suspend` (it is optional on the interface): refusing loudly beats running
636
+ * a task body on a deployment whose state is being copied.
637
+ */
638
+ #gated(executor) {
639
+ return {
640
+ execute: async (args, executeOptions) => {
641
+ const fence = await readExecutionFence(this.#executionFence);
642
+ if (!admitsDrainableExecution(fence)) {
643
+ const suspend = executeOptions?.suspend;
644
+ if (!suspend) {
645
+ throw new ExecutionFencedError(fence.state, 'background task');
646
+ }
647
+ await suspend({
648
+ [EXECUTION_FENCE_SUSPEND_KEY]: { state: fence.state },
649
+ });
650
+ // Discarded on the suspend path — see core's ToolExecutor contract.
651
+ return undefined;
652
+ }
653
+ return executor.execute(args, executeOptions);
654
+ },
655
+ };
656
+ }
657
+ /**
658
+ * Enqueue a background task through the fence.
659
+ *
660
+ * A drain deliberately still ACCEPTS enqueues: the caller is an agent's tool
661
+ * call inside a run the drain is trying to finish, and refusing would fail
662
+ * exactly the runs that are draining. Locked and proof-only refuse, because
663
+ * a row written then is work the migration would have to carry.
664
+ *
665
+ * The per-task executor is wrapped with the same gate as the static ones, so
666
+ * a task enqueued while open cannot execute its body after a transition.
667
+ */
668
+ async enqueue(payload, context) {
669
+ const fence = await readExecutionFence(this.#executionFence);
670
+ if (!admitsDrainableExecution(fence)) {
671
+ throw new ExecutionFencedError(fence.state, 'background task enqueue');
672
+ }
673
+ return this.#manager.enqueue(payload, context
674
+ ? { ...context, executor: this.#gated(context.executor) }
675
+ : undefined);
676
+ }
677
+ // The read surface, and only the read surface. These three are what
678
+ // `createBackgroundTaskRoutes` serves and what a host inspecting its own
679
+ // queue needs; they claim nothing, so they stay open in every fence state
680
+ // (the semantics matrix keeps reads answering through a lock — an operator
681
+ // proving a deployment is drained has to be able to look).
682
+ /** One task by id, or null. */
683
+ getTask(taskId) {
684
+ return this.#manager.getTask(taskId);
685
+ }
686
+ /** Tasks matching a filter. The route adapter re-checks scope per row. */
687
+ listTasks(filter) {
688
+ return this.#manager.listTasks(filter);
689
+ }
690
+ /** Lifecycle-event stream, for the route adapter's SSE response. */
691
+ stream(options) {
692
+ return this.#manager.stream(options);
192
693
  }
193
694
  async #warnIfBodiesCannotExecute() {
194
695
  const workflows = await this.#mastra.getStorage()?.getStore('workflows');
@@ -210,7 +711,24 @@ export class BackgroundTaskHost {
210
711
  */
211
712
  async onAlarm() {
212
713
  await this.boot();
213
- await this.manager.cleanup();
714
+ // Teardown wins over the duty. A `shutdown()` that arrived while boot() was
715
+ // in flight got past its guard, so without this the alarm would sweep
716
+ // mid-teardown — publishing resumes onto a manager that is stopping — and
717
+ // then call cleanup() on a manager that has already shut down.
718
+ if (this.#shutdownRequested)
719
+ return;
720
+ // The convergence lane. boot() has resolved, so a set `#dispatching` means
721
+ // init actually landed and resume() has a subscriber to publish to. Nothing
722
+ // is waiting behind an alarm, so this lane carries the larger budget and is
723
+ // what drains a parked queue the boot budget only dented — including on the
724
+ // very wake that admitted dispatching, since the alarm recurs regardless.
725
+ //
726
+ // Convergence therefore rides the same alarm the host already arms for the
727
+ // cleanup below; a host that arms none gets neither duty.
728
+ if (this.#dispatching) {
729
+ await this.#resumeFenceSuspendedTasks(MAX_FENCE_RESUMES_PER_ALARM);
730
+ }
731
+ await this.#manager.cleanup();
214
732
  }
215
733
  /**
216
734
  * Graceful teardown. Stop the manager first: its shutdown flag rejects new
@@ -218,19 +736,30 @@ export class BackgroundTaskHost {
218
736
  * teardown is still attempted if manager teardown fails.
219
737
  */
220
738
  async #doShutdown() {
221
- if (this.#booted && !this.#bootSettled) {
739
+ // ONE wait, on the whole boot attempt: registration, the fence read, and
740
+ // phase B all hang off it, so nothing a racing boot is about to start can
741
+ // slip past this point and outlive the shutdown. Waiting on `#dispatching`
742
+ // instead would miss exactly the window the fence read opens — it is unset
743
+ // until admission, so a shutdown that arrived during the read would stop
744
+ // nothing and return.
745
+ //
746
+ // Awaited ONLY while still in flight: manager.shutdown() below flips its
747
+ // enqueue guard before its first await, and that guarantee survives only if
748
+ // nothing suspends this function before it is invoked.
749
+ if (this.#bootAttempt && !this.#bootAttemptSettled) {
222
750
  try {
223
- await this.#booted;
751
+ await this.#bootAttempt;
224
752
  }
225
753
  catch {
226
- // #doBoot already unwound every component it managed to stop. Any
227
- // component whose cleanup failed remains flagged for the retry below.
754
+ // #doRegister only validates and registers, and #startDispatching
755
+ // already unwound every component it managed to stop. Any component
756
+ // whose cleanup failed remains flagged for the retry below.
228
757
  }
229
758
  }
230
759
  const errors = [];
231
760
  if (this.#managerNeedsShutdown) {
232
761
  try {
233
- await this.manager.shutdown();
762
+ await this.#manager.shutdown();
234
763
  this.#managerNeedsShutdown = false;
235
764
  }
236
765
  catch (error) {