effect-mq 0.5.0 → 0.7.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 (61) hide show
  1. package/README.md +85 -17
  2. package/dist/Flow.d.ts +381 -0
  3. package/dist/Flow.d.ts.map +1 -0
  4. package/dist/Flow.js +340 -0
  5. package/dist/Flow.js.map +1 -0
  6. package/dist/Job.d.ts +31 -6
  7. package/dist/Job.d.ts.map +1 -1
  8. package/dist/Job.js +16 -2
  9. package/dist/Job.js.map +1 -1
  10. package/dist/JobStore.d.ts +353 -13
  11. package/dist/JobStore.d.ts.map +1 -1
  12. package/dist/JobStore.js +10 -0
  13. package/dist/JobStore.js.map +1 -1
  14. package/dist/MemoryJobStore.d.ts.map +1 -1
  15. package/dist/MemoryJobStore.js +361 -21
  16. package/dist/MemoryJobStore.js.map +1 -1
  17. package/dist/Metrics.d.ts +31 -0
  18. package/dist/Metrics.d.ts.map +1 -1
  19. package/dist/Metrics.js +39 -0
  20. package/dist/Metrics.js.map +1 -1
  21. package/dist/Worker.d.ts +120 -11
  22. package/dist/Worker.d.ts.map +1 -1
  23. package/dist/Worker.js +452 -26
  24. package/dist/Worker.js.map +1 -1
  25. package/dist/drizzle-postgres/DrizzleJobStore.d.ts +19 -1
  26. package/dist/drizzle-postgres/DrizzleJobStore.d.ts.map +1 -1
  27. package/dist/drizzle-postgres/DrizzleJobStore.js +678 -80
  28. package/dist/drizzle-postgres/DrizzleJobStore.js.map +1 -1
  29. package/dist/drizzle-postgres/schema.d.ts +293 -3
  30. package/dist/drizzle-postgres/schema.d.ts.map +1 -1
  31. package/dist/drizzle-postgres/schema.js +66 -1
  32. package/dist/drizzle-postgres/schema.js.map +1 -1
  33. package/dist/index.d.ts +7 -0
  34. package/dist/index.d.ts.map +1 -1
  35. package/dist/index.js +7 -0
  36. package/dist/index.js.map +1 -1
  37. package/dist/redis/RedisJobStore.d.ts +53 -0
  38. package/dist/redis/RedisJobStore.d.ts.map +1 -1
  39. package/dist/redis/RedisJobStore.js +402 -50
  40. package/dist/redis/RedisJobStore.js.map +1 -1
  41. package/dist/redis/scripts.d.ts +213 -35
  42. package/dist/redis/scripts.d.ts.map +1 -1
  43. package/dist/redis/scripts.js +689 -73
  44. package/dist/redis/scripts.js.map +1 -1
  45. package/dist/testing/conformance.d.ts +6 -0
  46. package/dist/testing/conformance.d.ts.map +1 -1
  47. package/dist/testing/conformance.js +855 -12
  48. package/dist/testing/conformance.js.map +1 -1
  49. package/package.json +1 -1
  50. package/src/Flow.ts +778 -0
  51. package/src/Job.ts +35 -11
  52. package/src/JobStore.ts +377 -12
  53. package/src/MemoryJobStore.ts +396 -25
  54. package/src/Metrics.ts +43 -0
  55. package/src/Worker.ts +726 -37
  56. package/src/drizzle-postgres/DrizzleJobStore.ts +844 -81
  57. package/src/drizzle-postgres/schema.ts +92 -0
  58. package/src/index.ts +8 -0
  59. package/src/redis/RedisJobStore.ts +540 -39
  60. package/src/redis/scripts.ts +751 -78
  61. package/src/testing/conformance.ts +1088 -12
@@ -14,6 +14,12 @@
14
14
  * Effect `Clock` (e.g. pass `now` into queries as a bind parameter) — never
15
15
  * from the database server's clock — so this works against real storage too.
16
16
  *
17
+ * Beyond the core queue contract, dedicated sections pin the flow contract:
18
+ * parent-side ownership (the FanOut ack, dependency rows, batched
19
+ * `recordChildResults`, every settle decision) and the child-side outbox
20
+ * (terminal transitions of envelope-carrying jobs staging reports for the
21
+ * relay to another store).
22
+ *
17
23
  * @since 0.1.0
18
24
  */
19
25
  import * as JobStore from "../JobStore.js";
@@ -34,6 +40,7 @@ const baseRequest = (overrides) => ({
34
40
  timeoutMs: undefined,
35
41
  dedupe: undefined,
36
42
  trace: undefined,
43
+ parent: undefined,
37
44
  delayMs: 0,
38
45
  ...overrides
39
46
  });
@@ -353,21 +360,137 @@ export const jobStoreConformance = (name, storeLayer) => {
353
360
  })));
354
361
  it.effect("list pagination is lossless when enqueue timestamps tie", () => withStore((store) => Effect.gen(function* () {
355
362
  // No clock adjustment: every record shares one enqueuedAt, so
356
- // ordering and the cursor fall back entirely to the id tie-break.
363
+ // ordering and the cursor fall back entirely to the id tie-break
364
+ // in both directions.
357
365
  for (let i = 0; i < 7; i++) {
358
366
  yield* store.enqueue(baseRequest({ payload: { n: i } }));
359
367
  }
360
- const seen = new Set();
361
- let cursor;
362
- do {
363
- const page = yield* store.list({ limit: 3, cursor });
364
- for (const item of page.items) {
365
- expect(seen.has(item.id)).toBe(false);
366
- seen.add(item.id);
368
+ for (const order of ["desc", "asc"]) {
369
+ const seen = [];
370
+ let cursor;
371
+ do {
372
+ const page = yield* store.list({ limit: 3, order, cursor });
373
+ for (const item of page.items) {
374
+ expect(seen.includes(item.id)).toBe(false);
375
+ seen.push(item.id);
376
+ }
377
+ cursor = page.cursor;
378
+ } while (cursor !== undefined);
379
+ expect(seen.length).toBe(7);
380
+ // Opposite directions walk exact mirror orders.
381
+ if (order === "asc") {
382
+ const descAll = yield* store.list({ limit: 7, order: "desc" });
383
+ expect(seen).toEqual(descAll.items.map((item) => item.id).toReversed());
367
384
  }
368
- cursor = page.cursor;
369
- } while (cursor !== undefined);
370
- expect(seen.size).toBe(7);
385
+ }
386
+ })));
387
+ it.effect("list orders by enqueuedAt ascending on request, cursor included", () => withStore((store) => Effect.gen(function* () {
388
+ const ids = [];
389
+ for (let i = 0; i < 3; i++) {
390
+ const { id } = yield* store.enqueue(baseRequest({ payload: { n: i } }));
391
+ ids.push(id);
392
+ yield* TestClock.adjust(1_000);
393
+ }
394
+ const first = yield* store.list({ orderBy: "enqueuedAt", order: "asc", limit: 2 });
395
+ expect(first.items.map((job) => job.id)).toEqual([ids[0], ids[1]]);
396
+ assert(first.cursor !== undefined);
397
+ const second = yield* store.list({
398
+ orderBy: "enqueuedAt",
399
+ order: "asc",
400
+ limit: 2,
401
+ cursor: first.cursor
402
+ });
403
+ expect(second.items.map((job) => job.id)).toEqual([ids[2]]);
404
+ expect(second.cursor).toBeUndefined();
405
+ })));
406
+ it.effect("list orders delayed jobs by runAt within a queue", () => withStore((store) => Effect.gen(function* () {
407
+ const late = yield* store.enqueue(baseRequest({ payload: { n: 1 }, delayMs: 30_000 }));
408
+ const soon = yield* store.enqueue(baseRequest({ payload: { n: 2 }, delayMs: 5_000 }));
409
+ const middle = yield* store.enqueue(baseRequest({ payload: { n: 3 }, delayMs: 10_000 }));
410
+ // An immediate job in the same queue must not appear.
411
+ yield* store.enqueue(baseRequest({ payload: { n: 4 } }));
412
+ const upcoming = yield* store.list({
413
+ queue: QueueName("default"),
414
+ states: ["delayed"],
415
+ orderBy: "runAt",
416
+ order: "asc",
417
+ limit: 2
418
+ });
419
+ expect(upcoming.items.map((job) => job.id)).toEqual([soon.id, middle.id]);
420
+ assert(upcoming.cursor !== undefined);
421
+ const rest = yield* store.list({
422
+ queue: QueueName("default"),
423
+ states: ["delayed"],
424
+ orderBy: "runAt",
425
+ order: "asc",
426
+ limit: 2,
427
+ cursor: upcoming.cursor
428
+ });
429
+ expect(rest.items.map((job) => job.id)).toEqual([late.id]);
430
+ expect(rest.cursor).toBeUndefined();
431
+ })));
432
+ it.effect("list orders terminal jobs by finishedAt, with and without a name", () => withStore((store) => Effect.gen(function* () {
433
+ // Enqueue in one order, finish in the REVERSE order, so finishedAt
434
+ // ordering and enqueuedAt ordering disagree — a driver that quietly
435
+ // ignores orderBy fails here instead of passing by coincidence.
436
+ const enqueueAs = (name, queue) => {
437
+ const request = queue === undefined
438
+ ? baseRequest({ name })
439
+ : baseRequest({ name, queue: QueueName(queue) });
440
+ return Effect.map(store.enqueue(request), (result) => result.id);
441
+ };
442
+ const first = yield* enqueueAs("TestJob");
443
+ const second = yield* enqueueAs("OtherJob");
444
+ const third = yield* enqueueAs("TestJob");
445
+ const elsewhere = yield* enqueueAs("TestJob", "other");
446
+ const claims = new Map();
447
+ for (const token of ["t-1", "t-2", "t-3"]) {
448
+ const claim = yield* store.claim(claimOptions({
449
+ names: ["TestJob", "OtherJob"],
450
+ token
451
+ }));
452
+ assert(claim._tag === "Claimed");
453
+ claims.set(claim.job.id, token);
454
+ }
455
+ const otherClaim = yield* store.claim(claimOptions({
456
+ queue: QueueName("other"),
457
+ token: "t-4"
458
+ }));
459
+ assert(otherClaim._tag === "Claimed");
460
+ claims.set(elsewhere, "t-4");
461
+ for (const id of [elsewhere, third, second, first]) {
462
+ const token = claims.get(id);
463
+ assert(token !== undefined);
464
+ yield* store.ack(id, token, {
465
+ _tag: id === second ? "Fail" : "Complete",
466
+ exit: undefined
467
+ });
468
+ yield* TestClock.adjust(1_000);
469
+ }
470
+ // Across terminal states, newest FINISHED first: the reverse of
471
+ // enqueue order.
472
+ const recent = yield* store.list({
473
+ states: ["completed", "failed"],
474
+ orderBy: "finishedAt",
475
+ order: "desc"
476
+ });
477
+ expect(recent.items.map((job) => job.id)).toEqual([first, second, third, elsewhere]);
478
+ // Scoped to one name and state.
479
+ const byName = yield* store.list({
480
+ name: "TestJob",
481
+ states: ["completed"],
482
+ orderBy: "finishedAt",
483
+ order: "desc"
484
+ });
485
+ expect(byName.items.map((job) => job.id)).toEqual([first, third, elsewhere]);
486
+ // The queue filter applies on top of the finishedAt route.
487
+ const byQueue = yield* store.list({
488
+ queue: QueueName("other"),
489
+ states: ["completed"],
490
+ orderBy: "finishedAt",
491
+ order: "desc"
492
+ });
493
+ expect(byQueue.items.map((job) => job.id)).toEqual([elsewhere]);
371
494
  })));
372
495
  it.effect("keep count ties on finishedAt keep the most recently acked records", () => withStore((store) => Effect.gen(function* () {
373
496
  // Two jobs acked at the SAME TestClock instant: the tie must break
@@ -429,6 +552,7 @@ export const jobStoreConformance = (name, storeLayer) => {
429
552
  waiting: 1,
430
553
  delayed: 1,
431
554
  active: 1,
555
+ "waiting-children": 0,
432
556
  completed: 0,
433
557
  failed: 0,
434
558
  cancelled: 0
@@ -792,7 +916,14 @@ export const jobStoreConformance = (name, storeLayer) => {
792
916
  backoff: { _tag: "fixed", delayMs: 2_000 },
793
917
  keep: { completed: { count: 2, ageMs: undefined } },
794
918
  timeoutMs: 9_000,
795
- trace: { traceId: "trace-1", spanId: "span-1", sampled: true, delayed: false }
919
+ trace: { traceId: "trace-1", spanId: "span-1", sampled: true, delayed: false },
920
+ parent: {
921
+ flowName: "rich-flow",
922
+ flowId: JobId("rich-parent"),
923
+ childKey: "rich-child",
924
+ parentStoreKey: "effect-mq/JobStore",
925
+ depth: 1
926
+ }
796
927
  });
797
928
  yield* store.enqueue(richRequest("rich-single"));
798
929
  expect(yield* store.enqueueMany([richRequest("rich-batch")]))
@@ -819,6 +950,8 @@ export const jobStoreConformance = (name, storeLayer) => {
819
950
  timeoutMs: job.timeoutMs,
820
951
  cancelRequested: job.cancelRequested,
821
952
  trace: job.trace,
953
+ parent: job.parent,
954
+ flow: job.flow,
822
955
  runAt: job.runAt,
823
956
  enqueuedAt: job.enqueuedAt
824
957
  });
@@ -837,11 +970,27 @@ export const jobStoreConformance = (name, storeLayer) => {
837
970
  delayed: false
838
971
  });
839
972
  expect(expected.payload).toEqual({ big: 1234567890123456, nested: { arr: [1, 2, 3] } });
973
+ expect(expected.parent).toEqual({
974
+ flowName: "rich-flow",
975
+ flowId: "rich-parent",
976
+ childKey: "rich-child",
977
+ parentStoreKey: "effect-mq/JobStore",
978
+ depth: 1
979
+ });
980
+ expect(expected.flow).toBeUndefined();
840
981
  for (const id of [JobId("rich-batch"), JobId("rich-tick")]) {
841
982
  const job = yield* store.getJob(id);
842
983
  assert(Option.isSome(job));
843
984
  expect(project(job.value)).toEqual(expected);
844
985
  }
986
+ // `list` must return the same complete records as `getJob` —
987
+ // drivers with hand-written SELECT lists can silently drop fields
988
+ // there while every getJob-path test stays green.
989
+ const listed = yield* store.list({ name: "TestJob" });
990
+ expect(listed.items).toHaveLength(3);
991
+ for (const job of listed.items) {
992
+ expect(project(job)).toEqual(expected);
993
+ }
845
994
  })));
846
995
  it.effect("enqueueMany wakes parked takers", () => withStore((store) => Effect.gen(function* () {
847
996
  const empty = yield* store.claim(claimOptions());
@@ -1008,6 +1157,7 @@ export const jobStoreConformance = (name, storeLayer) => {
1008
1157
  waiting: 1,
1009
1158
  delayed: 0,
1010
1159
  active: 0,
1160
+ "waiting-children": 0,
1011
1161
  completed: 0,
1012
1162
  failed: 0,
1013
1163
  cancelled: 1
@@ -1243,6 +1393,699 @@ export const jobStoreConformance = (name, storeLayer) => {
1243
1393
  assert(Option.isSome(job));
1244
1394
  expect(job.value.state).toBe("waiting");
1245
1395
  })));
1396
+ // ----------------------------------------------------------------------
1397
+ // Flows (parent-child). The parent store owns the flow: the FanOut ack,
1398
+ // dependency rows, pending counter, and every settle decision are pinned
1399
+ // here. `storeKey` strings are opaque to the store.
1400
+ // ----------------------------------------------------------------------
1401
+ const parentEnvelope = (flowId, key) => ({
1402
+ flowName: "test-flow",
1403
+ flowId,
1404
+ childKey: key,
1405
+ parentStoreKey: "main",
1406
+ depth: 1
1407
+ });
1408
+ const childSpec = (flowId, key, overrides) => ({
1409
+ childKey: key,
1410
+ storeKey: "effect-mq/JobStore/children",
1411
+ request: baseRequest({
1412
+ id: JobId(`flow/main/${flowId}/${key}`),
1413
+ name: "ChildJob",
1414
+ parent: parentEnvelope(flowId, key),
1415
+ ...overrides
1416
+ })
1417
+ });
1418
+ const fanOutParent = (store, options) => Effect.gen(function* () {
1419
+ const { id } = yield* store.enqueue(baseRequest({ payload: { parent: true } }));
1420
+ const claim = yield* store.claim(claimOptions({ token: "t-parent" }));
1421
+ assert(claim._tag === "Claimed");
1422
+ expect(claim.job.id).toBe(id);
1423
+ const keys = options?.children ?? ["a", "b"];
1424
+ yield* store.ack(id, "t-parent", {
1425
+ _tag: "FanOut",
1426
+ failFast: options?.failFast ?? false,
1427
+ children: keys.map((key) => childSpec(id, key))
1428
+ });
1429
+ return id;
1430
+ });
1431
+ const report = (flowId, key, outcome, overrides) => ({
1432
+ flowId,
1433
+ childKey: key,
1434
+ outcome,
1435
+ exit: { ok: outcome === "completed" },
1436
+ failedReason: undefined,
1437
+ ...overrides
1438
+ });
1439
+ // Batch-of-one sugar for the single-report pins below; the batch
1440
+ // semantics get their own section.
1441
+ const recordOne = (store, value) => Effect.map(store.recordChildResults([value]), (results) => results[0] ?? { applied: false, parentSettled: false });
1442
+ const flowCounts = (overrides) => ({
1443
+ failFast: false,
1444
+ pending: 0,
1445
+ completed: 0,
1446
+ failed: 0,
1447
+ cancelled: 0,
1448
+ ...overrides
1449
+ });
1450
+ it.effect("FanOut parks the parent with its manifest, rows, and ledger entry", () => withStore((store) => Effect.gen(function* () {
1451
+ const flowId = yield* fanOutParent(store);
1452
+ const parent = yield* store.getJob(flowId);
1453
+ assert(Option.isSome(parent));
1454
+ expect(parent.value.state).toBe("waiting-children");
1455
+ expect(parent.value.flow).toEqual(flowCounts({ pending: 2 }));
1456
+ // A fan-out is a phase transition, not a completed run.
1457
+ expect(parent.value.attemptsMade).toBe(0);
1458
+ const attempts = yield* store.getAttempts(flowId);
1459
+ expect(attempts.map((attempt) => attempt.outcome)).toEqual(["fanned-out"]);
1460
+ const rows = yield* store.listChildResults(flowId);
1461
+ expect(rows.cursor).toBeUndefined();
1462
+ expect(rows.items.map((row) => ({
1463
+ childKey: row.childKey,
1464
+ name: row.name,
1465
+ storeKey: row.storeKey,
1466
+ childJobId: row.childJobId,
1467
+ status: row.status,
1468
+ cascaded: row.cascaded
1469
+ }))).toEqual([
1470
+ {
1471
+ childKey: "a",
1472
+ name: "ChildJob",
1473
+ storeKey: "effect-mq/JobStore/children",
1474
+ childJobId: `flow/main/${flowId}/a`,
1475
+ status: "pending",
1476
+ cascaded: false
1477
+ },
1478
+ {
1479
+ childKey: "b",
1480
+ name: "ChildJob",
1481
+ storeKey: "effect-mq/JobStore/children",
1482
+ childJobId: `flow/main/${flowId}/b`,
1483
+ status: "pending",
1484
+ cascaded: false
1485
+ }
1486
+ ]);
1487
+ // Parked parents are never claimable and show in counts.
1488
+ const claim = yield* store.claim(claimOptions({ token: "t-again" }));
1489
+ expect(claim._tag).toBe("Empty");
1490
+ expect((yield* store.counts())["waiting-children"]).toBe(1);
1491
+ })));
1492
+ it.effect("FanOut is lock-token-guarded and validates child ids", () => withStore((store) => Effect.gen(function* () {
1493
+ const { id } = yield* store.enqueue(baseRequest());
1494
+ const claim = yield* store.claim(claimOptions({ token: "t-owner" }));
1495
+ assert(claim._tag === "Claimed");
1496
+ const stale = yield* Effect.exit(store.ack(id, "t-wrong", {
1497
+ _tag: "FanOut",
1498
+ failFast: false,
1499
+ children: [childSpec(id, "a")]
1500
+ }));
1501
+ assert(Exit.isFailure(stale));
1502
+ // A spec without an explicit id fails loudly and leaves the job
1503
+ // active (the ack can be retried with a fixed spec).
1504
+ const bad = yield* Effect.exit(store.ack(id, "t-owner", {
1505
+ _tag: "FanOut",
1506
+ failFast: false,
1507
+ children: [{ ...childSpec(id, "a"), request: baseRequest({ id: undefined }) }]
1508
+ }));
1509
+ assert(Exit.isFailure(bad));
1510
+ const job = yield* store.getJob(id);
1511
+ assert(Option.isSome(job));
1512
+ expect(job.value.state).toBe("active");
1513
+ yield* store.ack(id, "t-owner", {
1514
+ _tag: "FanOut",
1515
+ failFast: false,
1516
+ children: [childSpec(id, "a")]
1517
+ });
1518
+ })));
1519
+ it.effect("an empty FanOut settles straight to runnable collect", () => withStore((store) => Effect.gen(function* () {
1520
+ const flowId = yield* fanOutParent(store, { children: [] });
1521
+ const parent = yield* store.getJob(flowId);
1522
+ assert(Option.isSome(parent));
1523
+ expect(parent.value.state).toBe("waiting");
1524
+ expect(parent.value.flow).toEqual(flowCounts());
1525
+ const claim = yield* store.claim(claimOptions({ token: "t-resume" }));
1526
+ assert(claim._tag === "Claimed");
1527
+ expect(claim.job.id).toBe(flowId);
1528
+ expect(claim.job.flow).toEqual(flowCounts());
1529
+ })));
1530
+ it.effect("recordChildResults applies once, decrements, and settles on the last report", () => withStore((store) => Effect.gen(function* () {
1531
+ const flowId = yield* fanOutParent(store);
1532
+ const first = yield* recordOne(store, report(flowId, "a", "completed"));
1533
+ expect(first).toEqual({ applied: true, parentSettled: false });
1534
+ const midway = yield* store.getJob(flowId);
1535
+ assert(Option.isSome(midway));
1536
+ expect(midway.value.state).toBe("waiting-children");
1537
+ expect(midway.value.flow?.pending).toBe(1);
1538
+ // Duplicates and unknowns drop on the dependency row.
1539
+ expect(yield* recordOne(store, report(flowId, "a", "failed")))
1540
+ .toEqual({ applied: false, parentSettled: false });
1541
+ expect(yield* recordOne(store, report(flowId, "ghost", "completed")))
1542
+ .toEqual({ applied: false, parentSettled: false });
1543
+ expect(yield* recordOne(store, report(JobId("no-such-flow"), "a", "completed")))
1544
+ .toEqual({ applied: false, parentSettled: false });
1545
+ const last = yield* recordOne(store, report(flowId, "b", "failed", {
1546
+ exit: { boom: true }
1547
+ }));
1548
+ expect(last).toEqual({ applied: true, parentSettled: true });
1549
+ // Settled: runnable now, phase collect, results recorded exactly.
1550
+ const parent = yield* store.getJob(flowId);
1551
+ assert(Option.isSome(parent));
1552
+ expect(parent.value.state).toBe("waiting");
1553
+ // The counters mirror the recorded outcomes exactly — via getJob,
1554
+ // via the claimed record (what `collect` reads its counts from),
1555
+ // and via list (what dashboards read). A driver whose claim/list
1556
+ // projections drop the counter columns fails here, not in prod.
1557
+ expect(parent.value.flow).toEqual(flowCounts({ completed: 1, failed: 1 }));
1558
+ const claim = yield* store.claim(claimOptions({ token: "t-resume" }));
1559
+ assert(claim._tag === "Claimed");
1560
+ expect(claim.job.id).toBe(flowId);
1561
+ expect(claim.job.flow).toEqual(flowCounts({ completed: 1, failed: 1 }));
1562
+ const listed = yield* store.list({ name: "TestJob" });
1563
+ expect(listed.items.find((job) => job.id === flowId)?.flow)
1564
+ .toEqual(flowCounts({ completed: 1, failed: 1 }));
1565
+ const rows = yield* store.listChildResults(flowId);
1566
+ const byKey = new Map(rows.items.map((row) => [row.childKey, row]));
1567
+ expect(byKey.get("a")?.status).toBe("completed");
1568
+ expect(byKey.get("a")?.exit).toEqual({ ok: true });
1569
+ // A recorded outcome came FROM the child's store: nothing to cascade.
1570
+ expect(byKey.get("a")?.cascaded).toBe(true);
1571
+ expect(byKey.get("b")?.status).toBe("failed");
1572
+ expect(byKey.get("b")?.exit).toEqual({ boom: true });
1573
+ })));
1574
+ it.effect("recordChildResults wakes a taker parked on the parent's queue", () => withStore((store) => Effect.gen(function* () {
1575
+ const flowId = yield* fanOutParent(store, { children: ["only"] });
1576
+ const empty = yield* store.claim(claimOptions({ token: "t-idle" }));
1577
+ assert(empty._tag === "Empty");
1578
+ const waiter = yield* Effect.forkChild(store.awaitWake([QueueName("default")], empty.wakeToken));
1579
+ yield* TestClock.adjust(1);
1580
+ yield* recordOne(store, report(flowId, "only", "completed"));
1581
+ yield* TestClock.adjust(1);
1582
+ expect(yield* Fiber.join(waiter)).toBeUndefined();
1583
+ })));
1584
+ it.effect("concurrent last reports settle the parent exactly once", () => withStore((store) => Effect.gen(function* () {
1585
+ const flowId = yield* fanOutParent(store);
1586
+ const results = yield* Effect.all([
1587
+ recordOne(store, report(flowId, "a", "completed")),
1588
+ recordOne(store, report(flowId, "b", "completed")),
1589
+ recordOne(store, report(flowId, "a", "completed")),
1590
+ recordOne(store, report(flowId, "b", "completed"))
1591
+ ], { concurrency: 4 });
1592
+ expect(results.filter((result) => result.applied).length).toBe(2);
1593
+ expect(results.filter((result) => result.parentSettled).length).toBe(1);
1594
+ })));
1595
+ it.effect("fail-fast settles the parent terminally and marks remaining rows", () => withStore((store) => Effect.gen(function* () {
1596
+ const flowId = yield* fanOutParent(store, { children: ["a", "b", "c"], failFast: true });
1597
+ yield* recordOne(store, report(flowId, "a", "completed"));
1598
+ const settle = yield* recordOne(store, report(flowId, "b", "failed"));
1599
+ expect(settle).toEqual({ applied: true, parentSettled: true });
1600
+ const parent = yield* store.getJob(flowId);
1601
+ assert(Option.isSome(parent));
1602
+ expect(parent.value.state).toBe("failed");
1603
+ expect(parent.value.failedReason).toContain("b");
1604
+ expect(parent.value.exit).toBeUndefined();
1605
+ const rows = yield* store.listChildResults(flowId);
1606
+ const remaining = rows.items.find((row) => row.childKey === "c");
1607
+ expect(remaining?.status).toBe("cancelled");
1608
+ // Marked by the settle — the sweeper still owes a real cancel.
1609
+ expect(remaining?.cascaded).toBe(false);
1610
+ // Settle-time marking lands in the counters too.
1611
+ expect(parent.value.flow).toEqual(flowCounts({ failFast: true, completed: 1, failed: 1, cancelled: 1 }));
1612
+ // A late completion finds its row terminal and drops.
1613
+ expect(yield* recordOne(store, report(flowId, "c", "completed")))
1614
+ .toEqual({ applied: false, parentSettled: false });
1615
+ })));
1616
+ it.effect("cancelling a waiting-children parent settles and marks its pending rows", () => withStore((store) => Effect.gen(function* () {
1617
+ const flowId = yield* fanOutParent(store);
1618
+ yield* recordOne(store, report(flowId, "a", "completed"));
1619
+ yield* store.cancel(flowId);
1620
+ const parent = yield* store.getJob(flowId);
1621
+ assert(Option.isSome(parent));
1622
+ expect(parent.value.state).toBe("cancelled");
1623
+ // The settle marking moves the counters too.
1624
+ expect(parent.value.flow).toEqual(flowCounts({ completed: 1, cancelled: 1 }));
1625
+ const rows = yield* store.listChildResults(flowId);
1626
+ const byKey = new Map(rows.items.map((row) => [row.childKey, row]));
1627
+ expect(byKey.get("a")?.status).toBe("completed");
1628
+ expect(byKey.get("b")?.status).toBe("cancelled");
1629
+ expect(byKey.get("b")?.cascaded).toBe(false);
1630
+ expect(yield* recordOne(store, report(flowId, "b", "completed")))
1631
+ .toEqual({ applied: false, parentSettled: false });
1632
+ })));
1633
+ it.effect("a cancel that races the fan-out wins and marks the rows", () => withStore((store) => Effect.gen(function* () {
1634
+ const { id } = yield* store.enqueue(baseRequest());
1635
+ const claim = yield* store.claim(claimOptions({ token: "t-parent" }));
1636
+ assert(claim._tag === "Claimed");
1637
+ // Cancel the ACTIVE parent (sets cancelRequested), then the worker
1638
+ // acks its fan-out: cancellation wins over parking.
1639
+ yield* store.cancel(id);
1640
+ yield* store.ack(id, "t-parent", {
1641
+ _tag: "FanOut",
1642
+ failFast: false,
1643
+ children: [childSpec(id, "a"), childSpec(id, "b")]
1644
+ });
1645
+ const parent = yield* store.getJob(id);
1646
+ assert(Option.isSome(parent));
1647
+ expect(parent.value.state).toBe("cancelled");
1648
+ expect(parent.value.flow).toEqual(flowCounts({ cancelled: 2 }));
1649
+ // The manifest landed and every row was marked for cascade, so
1650
+ // the sweeper delivers (mostly no-op) cancels to the child store.
1651
+ const rows = yield* store.listChildResults(id);
1652
+ expect(rows.items.map((row) => row.status)).toEqual(["cancelled", "cancelled"]);
1653
+ expect(rows.items.every((row) => !row.cascaded)).toBe(true);
1654
+ const work = yield* store.flowSweepWork({ pendingAgeMs: 0 });
1655
+ expect(work.cascade[0]?.children.map((child) => child.childKey)).toEqual(["a", "b"]);
1656
+ })));
1657
+ it.effect("promote and retry reject a waiting-children parent", () => withStore((store) => Effect.gen(function* () {
1658
+ const flowId = yield* fanOutParent(store);
1659
+ const promoted = yield* Effect.exit(store.promote(flowId));
1660
+ assert(Exit.isFailure(promoted));
1661
+ const retried = yield* Effect.exit(store.retry(flowId));
1662
+ assert(Exit.isFailure(retried));
1663
+ })));
1664
+ it.effect("retrying a fail-fast-failed parent re-enters collect with its manifest", () => withStore((store) => Effect.gen(function* () {
1665
+ const flowId = yield* fanOutParent(store, { children: ["a", "b"], failFast: true });
1666
+ yield* recordOne(store, report(flowId, "a", "failed"));
1667
+ yield* store.retry(flowId);
1668
+ const parent = yield* store.getJob(flowId);
1669
+ assert(Option.isSome(parent));
1670
+ expect(parent.value.state).toBe("waiting");
1671
+ // The manifest survives: a re-claimed parent dispatches collect,
1672
+ // never a second fan-out.
1673
+ expect(parent.value.flow).toBeDefined();
1674
+ expect((yield* store.listChildResults(flowId)).items.length).toBe(2);
1675
+ })));
1676
+ it.effect("a second FanOut converges on the persisted manifest", () => withStore((store) => Effect.gen(function* () {
1677
+ const flowId = yield* fanOutParent(store, { children: ["a"] });
1678
+ yield* recordOne(store, report(flowId, "a", "completed"));
1679
+ // Parent settled to waiting; claim and (bug-path) fan out again
1680
+ // with DIFFERENT children.
1681
+ const claim = yield* store.claim(claimOptions({ token: "t-double" }));
1682
+ assert(claim._tag === "Claimed");
1683
+ yield* store.ack(flowId, "t-double", {
1684
+ _tag: "FanOut",
1685
+ failFast: false,
1686
+ children: [childSpec(flowId, "x"), childSpec(flowId, "y")]
1687
+ });
1688
+ // The original manifest is untouched; state follows its pending
1689
+ // count (0 → runnable collect again).
1690
+ const rows = yield* store.listChildResults(flowId);
1691
+ expect(rows.items.map((row) => row.childKey)).toEqual(["a"]);
1692
+ const parent = yield* store.getJob(flowId);
1693
+ assert(Option.isSome(parent));
1694
+ expect(parent.value.state).toBe("waiting");
1695
+ })));
1696
+ it.effect("flowSweepWork scopes reconcile by parent state and pending age", () => withStore((store) => Effect.gen(function* () {
1697
+ const flowId = yield* fanOutParent(store);
1698
+ // Fresh rows are the push path's business.
1699
+ const fresh = yield* store.flowSweepWork({ pendingAgeMs: 30_000 });
1700
+ expect(fresh.reconcile).toEqual([]);
1701
+ expect(fresh.cascade).toEqual([]);
1702
+ yield* TestClock.adjust(30_000);
1703
+ const due = yield* store.flowSweepWork({ pendingAgeMs: 30_000 });
1704
+ expect(due.reconcile.length).toBe(1);
1705
+ expect(due.reconcile[0]?.flowId).toBe(flowId);
1706
+ expect(due.reconcile[0]?.children.map((child) => child.childKey)).toEqual(["a", "b"]);
1707
+ // The stored spec is the complete original request.
1708
+ expect(due.reconcile[0]?.children[0]?.request).toEqual(childSpec(flowId, "a").request);
1709
+ // Returned rows are re-armed: they leave the page for another full
1710
+ // age, so a sweep page rotates instead of pinning its head.
1711
+ const rearmed = yield* store.flowSweepWork({ pendingAgeMs: 30_000 });
1712
+ expect(rearmed.reconcile).toEqual([]);
1713
+ // A recorded row leaves the reconcile set for good; a settled
1714
+ // parent leaves it entirely.
1715
+ yield* recordOne(store, report(flowId, "a", "completed"));
1716
+ yield* TestClock.adjust(30_000);
1717
+ const partial = yield* store.flowSweepWork({ pendingAgeMs: 30_000 });
1718
+ expect(partial.reconcile[0]?.children.map((child) => child.childKey)).toEqual(["b"]);
1719
+ yield* recordOne(store, report(flowId, "b", "completed"));
1720
+ yield* TestClock.adjust(30_000);
1721
+ const settled = yield* store.flowSweepWork({ pendingAgeMs: 30_000 });
1722
+ expect(settled.reconcile).toEqual([]);
1723
+ })));
1724
+ it.effect("a fail-fast report that is also the last pending row settles as failed", () => withStore((store) => Effect.gen(function* () {
1725
+ const flowId = yield* fanOutParent(store, { children: ["a", "b"], failFast: true });
1726
+ yield* recordOne(store, report(flowId, "a", "completed"));
1727
+ // This report triggers BOTH settle rules: pending hits zero AND it
1728
+ // is the first failure under fail-fast. Fail-fast wins: terminal
1729
+ // `failed`, never a resume into collect.
1730
+ const last = yield* recordOne(store, report(flowId, "b", "failed"));
1731
+ expect(last).toEqual({ applied: true, parentSettled: true });
1732
+ const parent = yield* store.getJob(flowId);
1733
+ assert(Option.isSome(parent));
1734
+ expect(parent.value.state).toBe("failed");
1735
+ expect(parent.value.failedReason).toContain("b");
1736
+ })));
1737
+ it.effect("an empty FanOut wakes takers parked on the parent's queue", () => withStore((store) => Effect.gen(function* () {
1738
+ const { id } = yield* store.enqueue(baseRequest());
1739
+ const claim = yield* store.claim(claimOptions({ token: "t-parent" }));
1740
+ assert(claim._tag === "Claimed");
1741
+ const empty = yield* store.claim(claimOptions({ token: "t-idle" }));
1742
+ assert(empty._tag === "Empty");
1743
+ const waiter = yield* Effect.forkChild(store.awaitWake([QueueName("default")], empty.wakeToken));
1744
+ yield* TestClock.adjust(1);
1745
+ yield* store.ack(id, "t-parent", { _tag: "FanOut", failFast: false, children: [] });
1746
+ yield* TestClock.adjust(1);
1747
+ expect(yield* Fiber.join(waiter)).toBeUndefined();
1748
+ })));
1749
+ it.effect("automatic retention spares a settled parent that still owes cascades", () => withStore((store) => Effect.gen(function* () {
1750
+ // A fail-fast settle marks rows for cascade in the same op that
1751
+ // makes the parent prunable — retention must not race the sweeper
1752
+ // out of its only record that cancels are still owed.
1753
+ const keep = { failed: { count: 1, ageMs: undefined } };
1754
+ const { id: flowId } = yield* store.enqueue(baseRequest({ keep }));
1755
+ const claim = yield* store.claim(claimOptions({ token: "t-parent" }));
1756
+ assert(claim._tag === "Claimed");
1757
+ yield* store.ack(flowId, "t-parent", {
1758
+ _tag: "FanOut",
1759
+ failFast: true,
1760
+ children: [childSpec(flowId, "a"), childSpec(flowId, "b")]
1761
+ });
1762
+ yield* recordOne(store, report(flowId, "a", "failed"));
1763
+ // A newer failed peer would evict the flow parent under count: 1 —
1764
+ // but its "b" row is cancelled and not yet cascaded.
1765
+ const { id: peer1 } = yield* store.enqueue(baseRequest({ keep }));
1766
+ const claim1 = yield* store.claim(claimOptions({ token: "t-p1" }));
1767
+ assert(claim1._tag === "Claimed");
1768
+ yield* store.ack(peer1, "t-p1", { _tag: "Fail", exit: undefined });
1769
+ const spared = yield* store.getJob(flowId);
1770
+ assert(Option.isSome(spared));
1771
+ expect(spared.value.state).toBe("failed");
1772
+ expect((yield* store.listChildResults(flowId)).items.length).toBe(2);
1773
+ // Once the cascade is delivered, retention applies normally.
1774
+ yield* store.markChildrenCascaded(flowId, ["b"]);
1775
+ const { id: peer2 } = yield* store.enqueue(baseRequest({ keep }));
1776
+ const claim2 = yield* store.claim(claimOptions({ token: "t-p2" }));
1777
+ assert(claim2._tag === "Claimed");
1778
+ yield* store.ack(peer2, "t-p2", { _tag: "Fail", exit: undefined });
1779
+ expect(Option.isNone(yield* store.getJob(flowId))).toBe(true);
1780
+ expect((yield* store.listChildResults(flowId)).items).toEqual([]);
1781
+ })));
1782
+ it.effect("flowSweepWork yields cascade work until rows are marked cascaded", () => withStore((store) => Effect.gen(function* () {
1783
+ const flowId = yield* fanOutParent(store, { children: ["a", "b"], failFast: true });
1784
+ yield* recordOne(store, report(flowId, "a", "failed"));
1785
+ const work = yield* store.flowSweepWork({ pendingAgeMs: 30_000 });
1786
+ // Settled flow: nothing to reconcile, but "b" owes a cascade.
1787
+ expect(work.reconcile).toEqual([]);
1788
+ expect(work.cascade.length).toBe(1);
1789
+ expect(work.cascade[0]?.children).toEqual([{
1790
+ childKey: "b",
1791
+ storeKey: "effect-mq/JobStore/children",
1792
+ childJobId: `flow/main/${flowId}/b`
1793
+ }]);
1794
+ yield* store.markChildrenCascaded(flowId, ["b"]);
1795
+ const after = yield* store.flowSweepWork({ pendingAgeMs: 30_000 });
1796
+ expect(after.cascade).toEqual([]);
1797
+ // Idempotent (unknown keys included).
1798
+ yield* store.markChildrenCascaded(flowId, ["b", "ghost"]);
1799
+ })));
1800
+ it.effect("listChildResults paginates in child-key order", () => withStore((store) => Effect.gen(function* () {
1801
+ const flowId = yield* fanOutParent(store, { children: ["c", "a", "b"] });
1802
+ const first = yield* store.listChildResults(flowId, { limit: 2 });
1803
+ expect(first.items.map((row) => row.childKey)).toEqual(["a", "b"]);
1804
+ expect(first.cursor).toBeDefined();
1805
+ const second = yield* store.listChildResults(flowId, {
1806
+ cursor: first.cursor,
1807
+ limit: 2
1808
+ });
1809
+ expect(second.items.map((row) => row.childKey)).toEqual(["c"]);
1810
+ expect(second.cursor).toBeUndefined();
1811
+ })));
1812
+ it.effect("remove refuses a waiting-children parent and deletes rows with a settled one", () => withStore((store) => Effect.gen(function* () {
1813
+ const flowId = yield* fanOutParent(store, { children: ["a"] });
1814
+ expect(yield* store.remove(flowId)).toBe(false);
1815
+ yield* recordOne(store, report(flowId, "a", "failed", { exit: undefined }));
1816
+ // continue-policy: the parent settled to waiting; cancel it so it
1817
+ // is removable, then remove it — the dependency rows go with it.
1818
+ yield* store.cancel(flowId);
1819
+ expect(yield* store.remove(flowId)).toBe(true);
1820
+ expect((yield* store.listChildResults(flowId)).items).toEqual([]);
1821
+ })));
1822
+ it.effect("store-side child failures carry failedReason on the row", () => withStore((store) => Effect.gen(function* () {
1823
+ const flowId = yield* fanOutParent(store, { children: ["a"] });
1824
+ yield* recordOne(store, report(flowId, "a", "failed", {
1825
+ exit: undefined,
1826
+ failedReason: "job stalled more than allowable limit"
1827
+ }));
1828
+ const rows = yield* store.listChildResults(flowId);
1829
+ expect(rows.items[0]?.exit).toBeUndefined();
1830
+ expect(rows.items[0]?.failedReason).toBe("job stalled more than allowable limit");
1831
+ })));
1832
+ // ----------------------------------------------------------------------
1833
+ // Batched reports + the child-side outbox. The outbox is how a CHILD
1834
+ // store reports terminal transitions to a parent living in another
1835
+ // store: append on the transition, peek/delete from the relay.
1836
+ // ----------------------------------------------------------------------
1837
+ it.effect("recordChildResults applies a batch positionally and keeps counters exact", () => withStore((store) => Effect.gen(function* () {
1838
+ const flowId = yield* fanOutParent(store, { children: ["a", "b", "c"] });
1839
+ const results = yield* store.recordChildResults([
1840
+ report(flowId, "a", "completed"),
1841
+ report(flowId, "a", "completed"), // duplicate inside the batch
1842
+ report(flowId, "ghost", "completed"),
1843
+ report(flowId, "b", "failed")
1844
+ ]);
1845
+ expect(results).toEqual([
1846
+ { applied: true, parentSettled: false },
1847
+ { applied: false, parentSettled: false },
1848
+ { applied: false, parentSettled: false },
1849
+ { applied: true, parentSettled: false }
1850
+ ]);
1851
+ const parent = yield* store.getJob(flowId);
1852
+ assert(Option.isSome(parent));
1853
+ expect(parent.value.state).toBe("waiting-children");
1854
+ expect(parent.value.flow).toEqual(flowCounts({ pending: 1, completed: 1, failed: 1 }));
1855
+ })));
1856
+ it.effect("a batch that empties pending settles once, on its last applied report", () => withStore((store) => Effect.gen(function* () {
1857
+ const flowId = yield* fanOutParent(store);
1858
+ const results = yield* store.recordChildResults([
1859
+ report(flowId, "a", "completed"),
1860
+ report(flowId, "b", "completed")
1861
+ ]);
1862
+ expect(results).toEqual([
1863
+ { applied: true, parentSettled: false },
1864
+ { applied: true, parentSettled: true }
1865
+ ]);
1866
+ const parent = yield* store.getJob(flowId);
1867
+ assert(Option.isSome(parent));
1868
+ expect(parent.value.state).toBe("waiting");
1869
+ })));
1870
+ it.effect("fail-fast wins inside a batch, after every batch-mate applied", () => withStore((store) => Effect.gen(function* () {
1871
+ const flowId = yield* fanOutParent(store, { children: ["a", "b", "c"], failFast: true });
1872
+ const results = yield* store.recordChildResults([
1873
+ report(flowId, "b", "failed"),
1874
+ report(flowId, "c", "completed")
1875
+ ]);
1876
+ // Row updates apply BEFORE the settle decision: "c" keeps its real
1877
+ // completed outcome even though "b" settles the flow.
1878
+ expect(results).toEqual([
1879
+ { applied: true, parentSettled: true },
1880
+ { applied: true, parentSettled: false }
1881
+ ]);
1882
+ const parent = yield* store.getJob(flowId);
1883
+ assert(Option.isSome(parent));
1884
+ expect(parent.value.state).toBe("failed");
1885
+ expect(parent.value.failedReason).toContain("b");
1886
+ expect(parent.value.flow).toEqual(flowCounts({ failFast: true, completed: 1, failed: 1, cancelled: 1 }));
1887
+ const rows = yield* store.listChildResults(flowId);
1888
+ const byKey = new Map(rows.items.map((row) => [row.childKey, row.status]));
1889
+ expect(byKey.get("c")).toBe("completed");
1890
+ expect(byKey.get("a")).toBe("cancelled");
1891
+ })));
1892
+ it.effect("a batch may span flows and settles each independently", () => withStore((store) => Effect.gen(function* () {
1893
+ const first = yield* fanOutParent(store, { children: ["a"] });
1894
+ const second = yield* fanOutParent(store, { children: ["b"] });
1895
+ const results = yield* store.recordChildResults([
1896
+ report(first, "a", "completed"),
1897
+ report(second, "b", "completed")
1898
+ ]);
1899
+ expect(results).toEqual([
1900
+ { applied: true, parentSettled: true },
1901
+ { applied: true, parentSettled: true }
1902
+ ]);
1903
+ })));
1904
+ it.effect("a cancelled child report moves the cancelled counter", () => withStore((store) => Effect.gen(function* () {
1905
+ const flowId = yield* fanOutParent(store);
1906
+ yield* recordOne(store, report(flowId, "a", "cancelled", { exit: undefined }));
1907
+ const parent = yield* store.getJob(flowId);
1908
+ assert(Option.isSome(parent));
1909
+ expect(parent.value.flow).toEqual(flowCounts({ pending: 1, cancelled: 1 }));
1910
+ })));
1911
+ it.effect("peekOutbox pages past prior entries with `after`, even deleted ones", () => withStore((store) => Effect.gen(function* () {
1912
+ const enqueueChild = (key) => Effect.gen(function* () {
1913
+ const { id } = yield* store.enqueue(baseRequest({
1914
+ parent: parentEnvelope(JobId("remote-flow-3"), key)
1915
+ }));
1916
+ const claim = yield* store.claim(claimOptions({ token: `t-${key}` }));
1917
+ assert(claim._tag === "Claimed");
1918
+ yield* store.ack(id, `t-${key}`, { _tag: "Complete", exit: { key } });
1919
+ });
1920
+ yield* enqueueChild("one");
1921
+ yield* enqueueChild("two");
1922
+ yield* enqueueChild("three");
1923
+ const first = yield* store.peekOutbox({ limit: 2 });
1924
+ expect(first.map((entry) => entry.report.childKey)).toEqual(["one", "two"]);
1925
+ const cursor = first[first.length - 1]?.id;
1926
+ assert(cursor !== undefined);
1927
+ const rest = yield* store.peekOutbox({ limit: 2, after: cursor });
1928
+ expect(rest.map((entry) => entry.report.childKey)).toEqual(["three"]);
1929
+ // The cursor keeps working when the entry it names is gone.
1930
+ yield* store.deleteOutbox([cursor]);
1931
+ const restAgain = yield* store.peekOutbox({ limit: 2, after: cursor });
1932
+ expect(restAgain.map((entry) => entry.report.childKey)).toEqual(["three"]);
1933
+ })));
1934
+ it.effect("cancels honoured by retry acks, the stall sweep, and on a parked parent land in the outbox", () => withStore((store) => Effect.gen(function* () {
1935
+ const envelope = (key) => parentEnvelope(JobId("remote-flow-4"), key);
1936
+ // A cancel honoured when a RETRY ack finds the flag set.
1937
+ const retried = yield* store.enqueue(baseRequest({ parent: envelope("retry-cancel") }));
1938
+ const claimA = yield* store.claim(claimOptions({ token: "t-a" }));
1939
+ assert(claimA._tag === "Claimed");
1940
+ yield* store.cancel(retried.id);
1941
+ yield* store.ack(retried.id, "t-a", { _tag: "Retry", delayMs: 0, exit: undefined });
1942
+ // A cancel honoured when the stall sweep recovers a dead worker.
1943
+ const stalled = yield* store.enqueue(baseRequest({ parent: envelope("stall-cancel") }));
1944
+ const claimB = yield* store.claim(claimOptions({ token: "t-b", lockDurationMs: 1_000 }));
1945
+ assert(claimB._tag === "Claimed");
1946
+ yield* store.cancel(stalled.id);
1947
+ yield* TestClock.adjust(2_000);
1948
+ yield* store.recoverStalled({ maxStalledCount: 5 });
1949
+ // A direct cancel of a PARKED nested parent (waiting-children).
1950
+ const parked = yield* store.enqueue(baseRequest({ parent: envelope("parked-cancel") }));
1951
+ const claimC = yield* store.claim(claimOptions({ token: "t-c" }));
1952
+ assert(claimC._tag === "Claimed");
1953
+ yield* store.ack(parked.id, "t-c", {
1954
+ _tag: "FanOut",
1955
+ failFast: false,
1956
+ children: [childSpec(parked.id, "a")]
1957
+ });
1958
+ yield* store.cancel(parked.id);
1959
+ const entries = yield* store.peekOutbox({ limit: 10 });
1960
+ expect(entries.map((entry) => [entry.report.childKey, entry.report.outcome])).toEqual([
1961
+ ["retry-cancel", "cancelled"],
1962
+ ["stall-cancel", "cancelled"],
1963
+ ["parked-cancel", "cancelled"]
1964
+ ]);
1965
+ })));
1966
+ it.effect("terminal transitions of envelope-carrying jobs land in the outbox", () => withStore((store) => Effect.gen(function* () {
1967
+ const envelope = (key) => parentEnvelope(JobId("remote-flow-1"), key);
1968
+ // A plain job's terminal ack appends nothing.
1969
+ const plain = yield* store.enqueue(baseRequest());
1970
+ const plainClaim = yield* store.claim(claimOptions({ token: "t-plain" }));
1971
+ assert(plainClaim._tag === "Claimed");
1972
+ yield* store.ack(plain.id, "t-plain", { _tag: "Complete", exit: { ok: true } });
1973
+ expect(yield* store.peekOutbox({ limit: 10 })).toEqual([]);
1974
+ // Ack Complete → outbox entry with the exit.
1975
+ const acked = yield* store.enqueue(baseRequest({ parent: envelope("acked") }));
1976
+ const claim = yield* store.claim(claimOptions({ token: "t-child" }));
1977
+ assert(claim._tag === "Claimed");
1978
+ expect(claim.job.id).toBe(acked.id);
1979
+ yield* store.ack(acked.id, "t-child", { _tag: "Complete", exit: { sent: 1 } });
1980
+ // Direct cancel of a delayed child → outbox entry.
1981
+ const cancelled = yield* store.enqueue(baseRequest({ parent: envelope("cancelled"), delayMs: 60_000 }));
1982
+ yield* store.cancel(cancelled.id);
1983
+ // Stall exhaustion → outbox entry carrying the failedReason.
1984
+ yield* store.enqueue(baseRequest({ parent: envelope("stalled") }));
1985
+ const stalledClaim = yield* store.claim(claimOptions({ token: "t-stall", lockDurationMs: 1_000 }));
1986
+ assert(stalledClaim._tag === "Claimed");
1987
+ yield* TestClock.adjust(2_000);
1988
+ const recovered = yield* store.recoverStalled({ maxStalledCount: 0 });
1989
+ expect(recovered).toEqual([{ id: stalledClaim.job.id, failed: true }]);
1990
+ // Oldest first, `limit` respected, full entry shape.
1991
+ const firstPage = yield* store.peekOutbox({ limit: 2 });
1992
+ expect(firstPage.map((entry) => entry.report.childKey)).toEqual(["acked", "cancelled"]);
1993
+ const head = firstPage[0];
1994
+ assert(head !== undefined);
1995
+ expect(head.flowName).toBe("test-flow");
1996
+ expect(head.parentStoreKey).toBe("main");
1997
+ expect(head.report.flowId).toBe("remote-flow-1");
1998
+ expect(head.report.outcome).toBe("completed");
1999
+ expect(head.report.exit).toEqual({ sent: 1 });
2000
+ const all = yield* store.peekOutbox({ limit: 10 });
2001
+ expect(all.map((entry) => entry.report.outcome)).toEqual([
2002
+ "completed",
2003
+ "cancelled",
2004
+ "failed"
2005
+ ]);
2006
+ expect(all[2]?.report.exit).toBeUndefined();
2007
+ expect(all[2]?.report.failedReason).toBe("job stalled more than allowable limit");
2008
+ // Peek does not consume; delete does, idempotently.
2009
+ yield* store.deleteOutbox([head.id, "ghost-id"]);
2010
+ const rest = yield* store.peekOutbox({ limit: 10 });
2011
+ expect(rest.map((entry) => entry.report.childKey)).toEqual(["cancelled", "stalled"]);
2012
+ yield* store.deleteOutbox([head.id]);
2013
+ expect((yield* store.peekOutbox({ limit: 10 })).length).toBe(2);
2014
+ })));
2015
+ it.effect("cancels honoured off the ack path still land in the outbox", () => withStore((store) => Effect.gen(function* () {
2016
+ // A cancel that arrives while the child runs, honoured when the
2017
+ // worker RELEASES the job (shutdown) instead of acking it.
2018
+ const { id } = yield* store.enqueue(baseRequest({
2019
+ parent: parentEnvelope(JobId("remote-flow-2"), "released")
2020
+ }));
2021
+ const claim = yield* store.claim(claimOptions({ token: "t-run" }));
2022
+ assert(claim._tag === "Claimed");
2023
+ yield* store.cancel(id);
2024
+ yield* store.release(id, "t-run");
2025
+ const job = yield* store.getJob(id);
2026
+ assert(Option.isSome(job));
2027
+ expect(job.value.state).toBe("cancelled");
2028
+ const entries = yield* store.peekOutbox({ limit: 10 });
2029
+ expect(entries.map((entry) => entry.report.outcome)).toEqual(["cancelled"]);
2030
+ expect(entries[0]?.report.childKey).toBe("released");
2031
+ })));
2032
+ it.effect("a cancel that races a nested parent's fan-out reports upward through the outbox", () => withStore((store) => Effect.gen(function* () {
2033
+ // The parent being fanned out is itself a flow child; the raced
2034
+ // cancel settles it terminally inside the FanOut ack.
2035
+ const inner = yield* store.enqueue(baseRequest({
2036
+ parent: {
2037
+ flowName: "outer-flow",
2038
+ flowId: JobId("outer-2"),
2039
+ childKey: "inner-raced",
2040
+ parentStoreKey: "outer-store",
2041
+ depth: 1
2042
+ }
2043
+ }));
2044
+ const claim = yield* store.claim(claimOptions({ token: "t-race" }));
2045
+ assert(claim._tag === "Claimed");
2046
+ yield* store.cancel(inner.id);
2047
+ yield* store.ack(inner.id, "t-race", {
2048
+ _tag: "FanOut",
2049
+ failFast: false,
2050
+ children: [childSpec(inner.id, "a")]
2051
+ });
2052
+ const parent = yield* store.getJob(inner.id);
2053
+ assert(Option.isSome(parent));
2054
+ expect(parent.value.state).toBe("cancelled");
2055
+ const entries = yield* store.peekOutbox({ limit: 10 });
2056
+ expect(entries.map((entry) => entry.report.outcome)).toEqual(["cancelled"]);
2057
+ expect(entries[0]?.report.childKey).toBe("inner-raced");
2058
+ expect(entries[0]?.flowName).toBe("outer-flow");
2059
+ })));
2060
+ it.effect("a fail-fast settle of a nested parent reports upward through the outbox", () => withStore((store) => Effect.gen(function* () {
2061
+ // The inner parent is itself a flow child; its terminal transition
2062
+ // happens store-side (the settle), with no worker ack to hook.
2063
+ const inner = yield* store.enqueue(baseRequest({
2064
+ parent: {
2065
+ flowName: "outer-flow",
2066
+ flowId: JobId("outer-1"),
2067
+ childKey: "inner",
2068
+ parentStoreKey: "outer-store",
2069
+ depth: 1
2070
+ }
2071
+ }));
2072
+ const claim = yield* store.claim(claimOptions({ token: "t-inner" }));
2073
+ assert(claim._tag === "Claimed");
2074
+ yield* store.ack(inner.id, "t-inner", {
2075
+ _tag: "FanOut",
2076
+ failFast: true,
2077
+ children: [childSpec(inner.id, "a")]
2078
+ });
2079
+ // Parking is not terminal: nothing in the outbox yet.
2080
+ expect(yield* store.peekOutbox({ limit: 10 })).toEqual([]);
2081
+ yield* recordOne(store, report(inner.id, "a", "failed"));
2082
+ const entries = yield* store.peekOutbox({ limit: 10 });
2083
+ expect(entries.length).toBe(1);
2084
+ expect(entries[0]?.flowName).toBe("outer-flow");
2085
+ expect(entries[0]?.report.childKey).toBe("inner");
2086
+ expect(entries[0]?.report.outcome).toBe("failed");
2087
+ expect(entries[0]?.report.failedReason).toContain('"a" failed');
2088
+ })));
1246
2089
  });
1247
2090
  };
1248
2091
  //# sourceMappingURL=conformance.js.map