@jive-sh/workflow-platform 1.4.2 → 1.4.4

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.
@@ -739,9 +739,17 @@ const syncList = function* (input: { readonly workflow: WorkflowRow; readonly ev
739
739
  }
740
740
 
741
741
  /**
742
- * Records the failure and puts the task back at the front of the queue it was taken from, to be taken again: at once,
743
- * or after the step's `retries.delayMs`. At the step's `retries.limit` of failed runs in a row it leaves through
744
- * `retries.giveUp` instead.
742
+ * How long a task waits after its step failed, when the step names no `retries`: a minute after its first failure in a
743
+ * row, doubling with each one after, up to half an hour. A failure puts the task back at the front of its queue, so
744
+ * without a wait a step failing every time is taken again at once, as often as a worker can take it: Verification
745
+ * sources' inputs gate failed 125 times in 17 minutes on 2026-11-29. Pure.
746
+ */
747
+ export const failureDelayMs = (failuresInARow: number): number => Math.min(60_000 * 2 ** Math.max(0, failuresInARow - 1), 30 * 60_000)
748
+
749
+ /**
750
+ * Records the failure and puts the task back at the front of the queue it was taken from, to be taken again: after
751
+ * the step's `retries.delayMs`, or, with no `retries`, after `failureDelayMs`. At the step's `retries.limit` of failed
752
+ * runs in a row it leaves through `retries.giveUp` instead.
745
753
  */
746
754
  export const fail = function* (input: { readonly run: Id<"stepRuns">; readonly error: string; readonly measurements: Option.Option<StepMeasurements> }): Run<void> {
747
755
  const store = yield* WorkflowStore
@@ -750,14 +758,14 @@ export const fail = function* (input: { readonly run: Id<"stepRuns">; readonly e
750
758
  const workflow = yield* workflowNamed(run.workflow)
751
759
  const step = yield* stepNamed({ workflow, step: run.step })
752
760
  const retries = step.retries
753
- if (retries === undefined) {
754
- yield* store.moveFlow({ flow: run.flow, place: run.takenFrom.place, enteredAt: run.takenFrom.enteredAt })
755
- return yield* advance(run.workflow)
756
- }
757
761
  // The failed runs in a row of this flow in this step, this one included.
758
762
  const runs = (yield* store.stepRunsOfTask(run.task)).filter((candidate) => candidate.flow === run.flow && candidate.step === run.step)
759
763
  const inARow = [...runs].sort((a, b) => b.startedAt - a.startedAt || b._creationTime - a._creationTime).findIndex((candidate) => candidate.status !== "failed")
760
764
  const failures = inARow === -1 ? runs.length : inARow
765
+ if (retries === undefined) {
766
+ yield* store.moveFlow({ flow: run.flow, place: run.takenFrom.place, enteredAt: run.takenFrom.enteredAt, notBefore: store.now + failureDelayMs(failures) })
767
+ return yield* advance(run.workflow)
768
+ }
761
769
  if (failures >= retries.limit) {
762
770
  yield* store.insertTaskNote({ task: run.task, note: `${step.id} gave up after ${failures} failed runs in a row; the last: ${input.error.slice(0, 500)}` })
763
771
  yield* leaveStep({ workflow, flow: yield* flowWithId(run.flow), step, endState: retries.giveUp, measurements: Option.none(), note: Option.none() })
@@ -0,0 +1,21 @@
1
+ import { expect, test } from "bun:test"
2
+ import { failureDelayMs } from "./engine"
3
+
4
+ test("a step with no retries waits a minute after its first failure, doubling with each one in a row", () => {
5
+ expect([1, 2, 3, 4, 5].map(failureDelayMs)).toEqual([60_000, 120_000, 240_000, 480_000, 960_000])
6
+ })
7
+
8
+ test("the wait stops growing at half an hour", () => {
9
+ expect(failureDelayMs(6)).toBe(30 * 60_000)
10
+ expect(failureDelayMs(125)).toBe(30 * 60_000)
11
+ })
12
+
13
+ test("a gate failing every time, as Verification sources' did, is taken 5 times in its first 17 minutes, not 125", () => {
14
+ let at = 0
15
+ let takes = 0
16
+ for (let failures = 1; at < 17 * 60_000; failures++) {
17
+ takes += 1
18
+ at += failureDelayMs(failures)
19
+ }
20
+ expect(takes).toBe(5)
21
+ })
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jive-sh/workflow-platform",
3
- "version": "1.4.2",
3
+ "version": "1.4.4",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "description": "Durable workflows in Convex: one workflow primitive with a task schema, queues on every line, workflow budgets, named end states, events and sub-workflows; worker processes run the steps.",
@@ -0,0 +1,20 @@
1
+ /**
2
+ * A test's stand-in for a Convex deployment, in a thread of its own so it answers while the test's own thread is held:
3
+ * every mutation succeeds, and each one's arrival time and path are kept. Messages in: `times`, answered with them.
4
+ */
5
+ declare const self: { onmessage: ((event: { readonly data: "times" }) => void) | null; postMessage: (message: unknown) => void }
6
+
7
+ const arrived: Array<{ readonly path: string; readonly at: number }> = []
8
+
9
+ const server = Bun.serve({
10
+ port: 0,
11
+ hostname: "127.0.0.1",
12
+ fetch: async (request) => {
13
+ const body = (await request.json()) as { readonly path: string }
14
+ arrived.push({ path: body.path, at: Date.now() })
15
+ return Response.json({ status: "success", value: null, logLines: [] })
16
+ },
17
+ })
18
+
19
+ self.onmessage = () => self.postMessage({ kind: "times", arrived })
20
+ self.postMessage({ kind: "ready", url: `http://127.0.0.1:${server.port}` })
@@ -0,0 +1,78 @@
1
+ /**
2
+ * THE HEARTBEATS OF A WORKER'S RUNS, in a thread of their own (`HeartbeatThread`, `heartbeats.ts`). A step may hold the
3
+ * worker's own thread for minutes (a synchronous database scan, a long compile it waits on in-process), and a heartbeat
4
+ * timer on that thread fires only once the step lets go: on 2026-11-29 a conversion's run went 6 minutes without one
5
+ * and lost its lease while it was working. Here each run's heartbeat has its own timer and its own client, whatever the
6
+ * worker's thread is doing.
7
+ *
8
+ * Messages in: `start` (a run to keep alive) and `stop`. Messages out: `beat` (each heartbeat that got through, with how
9
+ * long it took) and `lost` (heartbeats that failed every try for longer than the lease still covered).
10
+ */
11
+ import { ConvexHttpClient } from "convex/browser"
12
+ import { makeFunctionReference } from "convex/server"
13
+
14
+ export interface StartHeartbeats {
15
+ readonly kind: "start"
16
+ readonly url: string
17
+ readonly heartbeat: string
18
+ readonly workflow: string
19
+ readonly run: string
20
+ readonly leaseMs: number
21
+ }
22
+ export interface StopHeartbeats {
23
+ readonly kind: "stop"
24
+ readonly run: string
25
+ }
26
+ export type ToHeartbeatThread = StartHeartbeats | StopHeartbeats
27
+ export type FromHeartbeatThread =
28
+ | { readonly kind: "ready" }
29
+ | { readonly kind: "beat"; readonly run: string; readonly at: number; readonly ms: number }
30
+ | { readonly kind: "lost"; readonly run: string; readonly error: string }
31
+
32
+ declare const self: { onmessage: ((event: { readonly data: ToHeartbeatThread }) => void) | null; postMessage: (message: FromHeartbeatThread) => void }
33
+
34
+ const clients = new Map<string, ConvexHttpClient>()
35
+ const running = new Map<string, { stopped: boolean }>()
36
+
37
+ /** One run's heartbeats: one every third of the lease, each tried again until the lease it extended would run out. */
38
+ const keepAlive = async (start: StartHeartbeats, state: { stopped: boolean }) => {
39
+ const client = clients.get(start.url) ?? new ConvexHttpClient(start.url)
40
+ clients.set(start.url, client)
41
+ const reference = makeFunctionReference<"mutation">(start.heartbeat)
42
+ const every = Math.max(1, Math.floor(start.leaseMs / 3))
43
+ let covered = Date.now() + start.leaseMs
44
+ while (!state.stopped) {
45
+ await Bun.sleep(every)
46
+ for (let wait = 250; !state.stopped; wait = Math.min(wait * 2, every)) {
47
+ const sent = Date.now()
48
+ try {
49
+ await client.mutation(reference, { workflow: start.workflow, run: start.run, leaseMs: start.leaseMs })
50
+ covered = Date.now() + start.leaseMs
51
+ self.postMessage({ kind: "beat", run: start.run, at: sent, ms: Date.now() - sent })
52
+ break
53
+ } catch (cause) {
54
+ if (Date.now() + wait >= covered) {
55
+ self.postMessage({ kind: "lost", run: start.run, error: `heartbeat failed until the lease ran out: ${String(cause)}` })
56
+ return
57
+ }
58
+ await Bun.sleep(wait)
59
+ }
60
+ }
61
+ }
62
+ }
63
+
64
+ self.onmessage = (event) => {
65
+ const message = event.data
66
+ if (message.kind === "start") {
67
+ const state = { stopped: false }
68
+ running.set(message.run, state)
69
+ void keepAlive(message, state)
70
+ } else {
71
+ const state = running.get(message.run)
72
+ if (state !== undefined) state.stopped = true
73
+ running.delete(message.run)
74
+ }
75
+ }
76
+
77
+ // Loaded: the worker waits for this before it starts a run's heartbeats.
78
+ self.postMessage({ kind: "ready" })
@@ -0,0 +1,76 @@
1
+ import { Effect } from "effect"
2
+ import type { FromHeartbeatThread, ToHeartbeatThread } from "./heartbeat-thread"
3
+ import { PlatformCallFailed } from "./platform-client"
4
+
5
+ /**
6
+ * The worker process's one heartbeat thread (`heartbeat-thread.ts`), started on the first run that needs it. Each run's
7
+ * heartbeats go on there, apart from the step's own work, until the run ends.
8
+ */
9
+ const thread = (() => {
10
+ let started: { readonly worker: Worker; readonly ready: Promise<void> } | undefined
11
+ const lost = new Map<string, (error: string) => void>()
12
+ const gaps = new Map<string, { last: number; longestMs: number }>()
13
+ const get = () => {
14
+ if (started !== undefined) return started
15
+ const worker = new Worker(new URL("./heartbeat-thread.ts", import.meta.url).href)
16
+ let markReady = () => {}
17
+ const ready = new Promise<void>((resolve) => (markReady = resolve))
18
+ worker.onmessage = (event: MessageEvent<FromHeartbeatThread>) => {
19
+ const message = event.data
20
+ if (message.kind === "ready") markReady()
21
+ else if (message.kind === "lost") lost.get(message.run)?.(message.error)
22
+ else {
23
+ const gap = gaps.get(message.run)
24
+ if (gap !== undefined) {
25
+ gap.longestMs = Math.max(gap.longestMs, message.at + message.ms - gap.last)
26
+ gap.last = message.at + message.ms
27
+ }
28
+ }
29
+ }
30
+ // The thread is the process's helper, never a reason to keep it running.
31
+ worker.unref()
32
+ started = { worker, ready }
33
+ return started
34
+ }
35
+ return {
36
+ ready: () => get().ready,
37
+ start: (input: Omit<Extract<ToHeartbeatThread, { kind: "start" }>, "kind">, onLost: (error: string) => void) => {
38
+ lost.set(input.run, onLost)
39
+ gaps.set(input.run, { last: Date.now(), longestMs: 0 })
40
+ get().worker.postMessage({ kind: "start", ...input } satisfies ToHeartbeatThread)
41
+ },
42
+ stop: (run: string): number => {
43
+ lost.delete(run)
44
+ const longestMs = gaps.get(run)?.longestMs ?? 0
45
+ gaps.delete(run)
46
+ started?.worker.postMessage({ kind: "stop", run } satisfies ToHeartbeatThread)
47
+ return longestMs
48
+ },
49
+ }
50
+ })()
51
+
52
+ /** A run's heartbeats running in the heartbeat thread: what fails if they are lost, and what stops them. */
53
+ export interface RunHeartbeats {
54
+ /** Never succeeds; fails once the heartbeats failed every try until the lease ran out. */
55
+ readonly lost: Effect.Effect<never, PlatformCallFailed>
56
+ /** Stops them when the run ends, warning when two came more than half the lease apart. */
57
+ readonly stop: Effect.Effect<void>
58
+ }
59
+
60
+ /**
61
+ * Starts a run's heartbeats in the heartbeat thread, once the thread is up, before the step runs: a step that holds this
62
+ * thread from its first moment must not hold back the thread's start or the first heartbeat.
63
+ */
64
+ export const startThreadedHeartbeats = (input: { readonly url: string; readonly heartbeat: string; readonly workflow: string; readonly run: string; readonly leaseMs: number }) =>
65
+ Effect.promise(async (): Promise<RunHeartbeats> => {
66
+ await thread.ready()
67
+ let markLost = (_error: string) => {}
68
+ const lostWith = new Promise<string>((resolve) => (markLost = resolve))
69
+ thread.start(input, markLost)
70
+ return {
71
+ lost: Effect.flatMap(Effect.promise(() => lostWith), (error) => Effect.fail(new PlatformCallFailed({ call: "heartbeat", cause: error }))),
72
+ stop: Effect.flatMap(Effect.sync(() => thread.stop(input.run)), (longestMs) =>
73
+ longestMs > input.leaseMs / 2 ? Effect.logWarning(`run ${input.run}'s heartbeats came ${longestMs} ms apart at most, past half its ${input.leaseMs} ms lease`) : Effect.void,
74
+ ),
75
+ }
76
+ })
@@ -1,5 +1,5 @@
1
1
  import type { ConvexHttpClient } from "convex/browser"
2
- import type { FunctionReference } from "convex/server"
2
+ import { type FunctionReference, getFunctionName } from "convex/server"
3
3
  import { Context, Data, Effect, Option, Schema } from "effect"
4
4
  import type { FoundTask, TasksAt } from "../src/definition/tasks"
5
5
  import type { StepMeasurements, TaskFile } from "../src/graph"
@@ -86,6 +86,12 @@ export interface IWorkflowPlatformClient {
86
86
  complete(input: CompleteInput): Effect.fn.Return<void, PlatformCallFailed>
87
87
  fail(input: { readonly workflow: string; readonly run: string; readonly error: string; readonly measurements: StepMeasurements }): Effect.fn.Return<void, PlatformCallFailed>
88
88
  heartbeat(input: { readonly workflow: string; readonly run: string; readonly leaseMs: number }): Effect.fn.Return<void, PlatformCallFailed>
89
+ /**
90
+ * Where a thread of its own can send this client's heartbeats (`heartbeat-thread.ts`): the deployment's URL and the
91
+ * heartbeat function's name. A step can hold the worker's thread for minutes, and a heartbeat behind it lost a working
92
+ * run's lease (2026-11-29). None for a client with no deployment behind it (a test's fake): its heartbeats run inline.
93
+ */
94
+ heartbeatTarget?(): Option.Option<{ readonly url: string; readonly heartbeat: string }>
89
95
  /** Tasks of `in` that the run `run` of `workflow` asks for; Convex refuses a workflow its step may not read. */
90
96
  findTasks(input: {
91
97
  readonly workflow: string
@@ -151,6 +157,10 @@ export class ConvexWorkflowPlatformClient implements IWorkflowPlatformClient {
151
157
  yield* this.call("fail", input)
152
158
  }
153
159
 
160
+ heartbeatTarget() {
161
+ return Option.some({ url: this.client.url, heartbeat: getFunctionName(this.functions.heartbeat) })
162
+ }
163
+
154
164
  *heartbeat(input: { readonly workflow: string; readonly run: string; readonly leaseMs: number }) {
155
165
  yield* this.call("heartbeat", input)
156
166
  }
@@ -37,6 +37,9 @@ class FakePlatform implements IWorkflowPlatformClient {
37
37
  readonly calls: Array<string> = []
38
38
  readonly failures: Array<string> = []
39
39
  readonly takes: Array<ReadonlyArray<{ readonly workflow: string; readonly step: string }>> = []
40
+ /** How many heartbeats time out first, as a loaded backend's did (2026-11-29). */
41
+ heartbeatsFailing = 0
42
+ heartbeats = 0
40
43
  constructor(
41
44
  private readonly answers: { readonly complete: boolean; readonly fail: boolean },
42
45
  private readonly budgetsRead: Option.Option<WorkflowBudgets> | "fails" = Option.none(),
@@ -58,7 +61,10 @@ class FakePlatform implements IWorkflowPlatformClient {
58
61
  this.failures.push(input.error)
59
62
  if (!this.answers.fail) return yield* Effect.fail(timedOut("fail"))
60
63
  }
61
- *heartbeat() {}
64
+ *heartbeat() {
65
+ this.heartbeats += 1
66
+ if (this.heartbeats <= this.heartbeatsFailing) return yield* Effect.fail(timedOut("heartbeat"))
67
+ }
62
68
  *findTasks() {
63
69
  return []
64
70
  }
@@ -236,3 +242,100 @@ describe("timer turns", () => {
236
242
  expect(problemsOf(withoutDefaults.graph).join("\n")).toContain("timer event tick cannot start a turn: its task schema cannot make a task from {}, so some field has no default")
237
243
  })
238
244
  })
245
+
246
+ describe("a heartbeat the platform fails once", () => {
247
+ const slow = Workflow.make({
248
+ name: "counted",
249
+ task: TaskSchema.make({ fields: Schema.Struct({ n: Schema.Number }) }),
250
+ endStates: ["done"],
251
+ budgets: { agents: 0, cpu: 1 },
252
+ events: { arrive: { kind: "task" } },
253
+ steps: (step) => ({
254
+ count: step.code({
255
+ endStates: ["done"],
256
+ run: function* () {
257
+ yield* Effect.sleep("1200 millis")
258
+ return { endState: "done" as const }
259
+ },
260
+ }),
261
+ }),
262
+ lines: [
263
+ { from: { event: "arrive" }, to: { step: "count" } },
264
+ { from: { step: "count", endState: "done" }, to: { end: "done" } },
265
+ ],
266
+ })
267
+
268
+
269
+ test("is tried again, and the run goes on to complete", async () => {
270
+ const platform = new FakePlatform({ complete: true, fail: true })
271
+ platform.heartbeatsFailing = 2
272
+ const result = await Effect.runPromise(
273
+ pipe(
274
+ Effect.gen(() => workOnce({ worker: "w", workflows: [slow], leaseMs: 300 })),
275
+ Effect.provideService(WorkflowPlatformClient, platform),
276
+ Effect.provideService(FileStore, new UnusedFileStore()),
277
+ ),
278
+ )
279
+ expect(result).toEqual({ _tag: "Ran", taken, outcome: "completed" })
280
+ expect(platform.calls).toEqual(["complete"])
281
+ expect(platform.heartbeats).toBeGreaterThan(2)
282
+ })
283
+ })
284
+
285
+ describe("heartbeats in their own thread", () => {
286
+ const holding = Workflow.make({
287
+ name: "counted",
288
+ task: TaskSchema.make({ fields: Schema.Struct({ n: Schema.Number }) }),
289
+ endStates: ["done"],
290
+ budgets: { agents: 0, cpu: 1 },
291
+ events: { arrive: { kind: "task" } },
292
+ steps: (step) => ({
293
+ count: step.code({
294
+ endStates: ["done"],
295
+ // Holds the worker's thread for four leases, as decomp's synchronous database scans held it (2026-11-29).
296
+ run: function* () {
297
+ const until = Date.now() + 1_200
298
+ while (Date.now() < until) {}
299
+ return { endState: "done" as const }
300
+ },
301
+ }),
302
+ }),
303
+ lines: [
304
+ { from: { event: "arrive" }, to: { step: "count" } },
305
+ { from: { step: "count", endState: "done" }, to: { end: "done" } },
306
+ ],
307
+ })
308
+
309
+ /** A fake platform whose heartbeats go to a deployment, so the worker sends them from the heartbeat thread. */
310
+ class Deployed extends FakePlatform {
311
+ constructor(private readonly url: string) {
312
+ super({ complete: true, fail: true })
313
+ }
314
+ heartbeatTarget() {
315
+ return Option.some({ url: this.url, heartbeat: "workforce:heartbeat" })
316
+ }
317
+ }
318
+
319
+ test("a step holding the worker's thread past its lease keeps the lease: heartbeats arrive meanwhile", async () => {
320
+ const deployment = new Worker(new URL("./fake-deployment-thread.ts", import.meta.url).href)
321
+ const message = <A>() => new Promise<A>((resolve) => (deployment.onmessage = (event) => resolve(event.data as A)))
322
+ const { url } = await message<{ readonly url: string }>()
323
+ const result = await Effect.runPromise(
324
+ pipe(
325
+ Effect.gen(() => workOnce({ worker: "w", workflows: [holding], leaseMs: 300 })),
326
+ Effect.provideService(WorkflowPlatformClient, new Deployed(url)),
327
+ Effect.provideService(FileStore, new UnusedFileStore()),
328
+ ),
329
+ )
330
+ const times = message<{ readonly arrived: ReadonlyArray<{ readonly path: string; readonly at: number }> }>()
331
+ deployment.postMessage("times")
332
+ const beats = (await times).arrived.filter((a) => a.path === "workforce:heartbeat").map((a) => a.at)
333
+ deployment.terminate()
334
+ expect(result).toEqual({ _tag: "Ran", taken, outcome: "completed" })
335
+ // While the step held the thread for 1.2 s, a heartbeat came every third of the 300 ms lease: never a gap the lease
336
+ // didn't cover.
337
+ expect(beats.length).toBeGreaterThanOrEqual(8)
338
+ const gaps = beats.slice(1).map((at, i) => at - beats[i]!)
339
+ expect(Math.max(...gaps)).toBeLessThan(300)
340
+ })
341
+ })
package/worker/worker.ts CHANGED
@@ -6,6 +6,7 @@ import { Tasks } from "../src/definition/tasks"
6
6
  import type { WorkflowDefinition } from "../src/definition/workflow"
7
7
  import { budgetOfStepKind, nothingUsed, noSpend, type StepMeasurements, type TaskFile } from "../src/graph"
8
8
  import { type PlatformCallFailed, type ReportedOtherWrite, type TakenStep, type WorkflowBudgets, WorkflowPlatformClient } from "./platform-client"
9
+ import { type RunHeartbeats, startThreadedHeartbeats } from "./heartbeats"
9
10
  import { StepMeter } from "./step-meter"
10
11
  import { RunTasks } from "./worker-tasks"
11
12
 
@@ -130,11 +131,19 @@ const runOnce = function* <Services>(input: {
130
131
 
131
132
  // The lease taken with the task covers the first interval, so the first heartbeat waits a third of it.
132
133
  const heartbeatEvery = Duration.millis(Math.max(1, Math.floor(options.leaseMs / 3)))
133
- const heartbeats = pipe(
134
- Effect.sleep(heartbeatEvery),
135
- Effect.andThen(Effect.gen(() => client.heartbeat({ workflow: taken.workflow, run: taken.run, leaseMs: options.leaseMs }))),
136
- Effect.repeat(Schedule.spaced(heartbeatEvery)),
134
+ // A heartbeat the backend fails once (a mutation over its time limit on a loaded machine) is tried again before the
135
+ // run is given up: giving it up ends the step, and the task is taken again, so one slow answer cost a whole run
136
+ // (2026-11-29, Convert for browser). Its tries stay well inside the interval the lease still covers.
137
+ const heartbeat = pipe(
138
+ Effect.gen(() => client.heartbeat({ workflow: taken.workflow, run: taken.run, leaseMs: options.leaseMs })),
139
+ Effect.retry({ schedule: Schedule.jittered(Schedule.exponential(Duration.millis(250))), times: 5 }),
137
140
  )
141
+ // In the heartbeat thread when the client has a deployment behind it, so a step holding this thread can't delay them.
142
+ const heartbeats: RunHeartbeats = yield* Option.match(Option.flatten(Option.fromUndefinedOr(client.heartbeatTarget?.())), {
143
+ onNone: () =>
144
+ Effect.succeed({ lost: Effect.andThen(pipe(Effect.sleep(heartbeatEvery), Effect.andThen(heartbeat), Effect.repeat(Schedule.spaced(heartbeatEvery))), Effect.never), stop: Effect.void }),
145
+ onSome: (target) => startThreadedHeartbeats({ ...target, workflow: taken.workflow, run: taken.run, leaseMs: options.leaseMs }),
146
+ })
138
147
  const exit = yield* pipe(
139
148
  Effect.gen(function* () {
140
149
  const fields = yield* Schema.decodeUnknownEffect(workflow.task.fields)(taken.task.fields)
@@ -180,7 +189,8 @@ const runOnce = function* <Services>(input: {
180
189
  })
181
190
  return { endState: outcome.endState, encodedFields, files, measurements, note: outcome.note, listed, others }
182
191
  }),
183
- Effect.raceFirst(Effect.andThen(heartbeats, Effect.never)),
192
+ Effect.raceFirst(heartbeats.lost),
193
+ Effect.ensuring(heartbeats.stop),
184
194
  Effect.exit,
185
195
  )
186
196
  if (Exit.isFailure(exit)) {