effect-mq 0.5.0 → 0.6.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 (59) 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 +312 -10
  11. package/dist/JobStore.d.ts.map +1 -1
  12. package/dist/JobStore.js.map +1 -1
  13. package/dist/MemoryJobStore.d.ts.map +1 -1
  14. package/dist/MemoryJobStore.js +334 -7
  15. package/dist/MemoryJobStore.js.map +1 -1
  16. package/dist/Metrics.d.ts +31 -0
  17. package/dist/Metrics.d.ts.map +1 -1
  18. package/dist/Metrics.js +39 -0
  19. package/dist/Metrics.js.map +1 -1
  20. package/dist/Worker.d.ts +120 -11
  21. package/dist/Worker.d.ts.map +1 -1
  22. package/dist/Worker.js +452 -26
  23. package/dist/Worker.js.map +1 -1
  24. package/dist/drizzle-postgres/DrizzleJobStore.d.ts +19 -1
  25. package/dist/drizzle-postgres/DrizzleJobStore.d.ts.map +1 -1
  26. package/dist/drizzle-postgres/DrizzleJobStore.js +653 -77
  27. package/dist/drizzle-postgres/DrizzleJobStore.js.map +1 -1
  28. package/dist/drizzle-postgres/schema.d.ts +293 -3
  29. package/dist/drizzle-postgres/schema.d.ts.map +1 -1
  30. package/dist/drizzle-postgres/schema.js +66 -1
  31. package/dist/drizzle-postgres/schema.js.map +1 -1
  32. package/dist/index.d.ts +7 -0
  33. package/dist/index.d.ts.map +1 -1
  34. package/dist/index.js +7 -0
  35. package/dist/index.js.map +1 -1
  36. package/dist/redis/RedisJobStore.d.ts.map +1 -1
  37. package/dist/redis/RedisJobStore.js +219 -18
  38. package/dist/redis/RedisJobStore.js.map +1 -1
  39. package/dist/redis/scripts.d.ts +117 -10
  40. package/dist/redis/scripts.d.ts.map +1 -1
  41. package/dist/redis/scripts.js +492 -25
  42. package/dist/redis/scripts.js.map +1 -1
  43. package/dist/testing/conformance.d.ts +6 -0
  44. package/dist/testing/conformance.d.ts.map +1 -1
  45. package/dist/testing/conformance.js +728 -1
  46. package/dist/testing/conformance.js.map +1 -1
  47. package/package.json +1 -1
  48. package/src/Flow.ts +778 -0
  49. package/src/Job.ts +35 -11
  50. package/src/JobStore.ts +339 -9
  51. package/src/MemoryJobStore.ts +370 -7
  52. package/src/Metrics.ts +43 -0
  53. package/src/Worker.ts +726 -37
  54. package/src/drizzle-postgres/DrizzleJobStore.ts +817 -78
  55. package/src/drizzle-postgres/schema.ts +92 -0
  56. package/src/index.ts +8 -0
  57. package/src/redis/RedisJobStore.ts +289 -8
  58. package/src/redis/scripts.ts +524 -24
  59. package/src/testing/conformance.ts +945 -1
@@ -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.ts"
@@ -38,6 +44,7 @@ const baseRequest = (
38
44
  timeoutMs: undefined,
39
45
  dedupe: undefined,
40
46
  trace: undefined,
47
+ parent: undefined,
41
48
  delayMs: 0,
42
49
  ...overrides
43
50
  })
@@ -623,6 +630,7 @@ export const jobStoreConformance = (
623
630
  waiting: 1,
624
631
  delayed: 1,
625
632
  active: 1,
633
+ "waiting-children": 0,
626
634
  completed: 0,
627
635
  failed: 0,
628
636
  cancelled: 0
@@ -1108,7 +1116,14 @@ export const jobStoreConformance = (
1108
1116
  backoff: { _tag: "fixed", delayMs: 2_000 },
1109
1117
  keep: { completed: { count: 2, ageMs: undefined } },
1110
1118
  timeoutMs: 9_000,
1111
- trace: { traceId: "trace-1", spanId: "span-1", sampled: true, delayed: false }
1119
+ trace: { traceId: "trace-1", spanId: "span-1", sampled: true, delayed: false },
1120
+ parent: {
1121
+ flowName: "rich-flow",
1122
+ flowId: JobId("rich-parent"),
1123
+ childKey: "rich-child",
1124
+ parentStoreKey: "effect-mq/JobStore",
1125
+ depth: 1
1126
+ }
1112
1127
  })
1113
1128
  yield* store.enqueue(richRequest("rich-single"))
1114
1129
  expect(yield* store.enqueueMany([richRequest("rich-batch")]))
@@ -1136,6 +1151,8 @@ export const jobStoreConformance = (
1136
1151
  timeoutMs: job.timeoutMs,
1137
1152
  cancelRequested: job.cancelRequested,
1138
1153
  trace: job.trace,
1154
+ parent: job.parent,
1155
+ flow: job.flow,
1139
1156
  runAt: job.runAt,
1140
1157
  enqueuedAt: job.enqueuedAt
1141
1158
  })
@@ -1154,11 +1171,28 @@ export const jobStoreConformance = (
1154
1171
  delayed: false
1155
1172
  })
1156
1173
  expect(expected.payload).toEqual({ big: 1234567890123456, nested: { arr: [1, 2, 3] } })
1174
+ expect(expected.parent).toEqual({
1175
+ flowName: "rich-flow",
1176
+ flowId: "rich-parent",
1177
+ childKey: "rich-child",
1178
+ parentStoreKey: "effect-mq/JobStore",
1179
+ depth: 1
1180
+ })
1181
+ expect(expected.flow).toBeUndefined()
1157
1182
  for (const id of [JobId("rich-batch"), JobId("rich-tick")]) {
1158
1183
  const job = yield* store.getJob(id)
1159
1184
  assert(Option.isSome(job))
1160
1185
  expect(project(job.value)).toEqual(expected)
1161
1186
  }
1187
+
1188
+ // `list` must return the same complete records as `getJob` —
1189
+ // drivers with hand-written SELECT lists can silently drop fields
1190
+ // there while every getJob-path test stays green.
1191
+ const listed = yield* store.list({ name: "TestJob" })
1192
+ expect(listed.items).toHaveLength(3)
1193
+ for (const job of listed.items) {
1194
+ expect(project(job)).toEqual(expected)
1195
+ }
1162
1196
  })
1163
1197
  ))
1164
1198
 
@@ -1370,6 +1404,7 @@ export const jobStoreConformance = (
1370
1404
  waiting: 1,
1371
1405
  delayed: 0,
1372
1406
  active: 0,
1407
+ "waiting-children": 0,
1373
1408
  completed: 0,
1374
1409
  failed: 0,
1375
1410
  cancelled: 1
@@ -1701,5 +1736,914 @@ export const jobStoreConformance = (
1701
1736
  expect(job.value.state).toBe("waiting")
1702
1737
  })
1703
1738
  ))
1739
+
1740
+ // ----------------------------------------------------------------------
1741
+ // Flows (parent-child). The parent store owns the flow: the FanOut ack,
1742
+ // dependency rows, pending counter, and every settle decision are pinned
1743
+ // here. `storeKey` strings are opaque to the store.
1744
+ // ----------------------------------------------------------------------
1745
+
1746
+ const parentEnvelope = (
1747
+ flowId: JobStore.JobId,
1748
+ key: string
1749
+ ): JobStore.ParentEnvelope => ({
1750
+ flowName: "test-flow",
1751
+ flowId,
1752
+ childKey: key,
1753
+ parentStoreKey: "main",
1754
+ depth: 1
1755
+ })
1756
+
1757
+ const childSpec = (
1758
+ flowId: JobStore.JobId,
1759
+ key: string,
1760
+ overrides?: Partial<JobStore.EnqueueRequest>
1761
+ ): JobStore.FlowChildSpec => ({
1762
+ childKey: key,
1763
+ storeKey: "effect-mq/JobStore/children",
1764
+ request: baseRequest({
1765
+ id: JobId(`flow/main/${flowId}/${key}`),
1766
+ name: "ChildJob",
1767
+ parent: parentEnvelope(flowId, key),
1768
+ ...overrides
1769
+ })
1770
+ })
1771
+
1772
+ const fanOutParent = (
1773
+ store: JobStore.Service,
1774
+ options?: {
1775
+ readonly children?: ReadonlyArray<string> | undefined
1776
+ readonly failFast?: boolean | undefined
1777
+ }
1778
+ ) =>
1779
+ Effect.gen(function*() {
1780
+ const { id } = yield* store.enqueue(baseRequest({ payload: { parent: true } }))
1781
+ const claim = yield* store.claim(claimOptions({ token: "t-parent" }))
1782
+ assert(claim._tag === "Claimed")
1783
+ expect(claim.job.id).toBe(id)
1784
+ const keys = options?.children ?? ["a", "b"]
1785
+ yield* store.ack(id, "t-parent", {
1786
+ _tag: "FanOut",
1787
+ failFast: options?.failFast ?? false,
1788
+ children: keys.map((key) => childSpec(id, key))
1789
+ })
1790
+ return id
1791
+ })
1792
+
1793
+ const report = (
1794
+ flowId: JobStore.JobId,
1795
+ key: string,
1796
+ outcome: JobStore.FlowChildReport["outcome"],
1797
+ overrides?: Partial<JobStore.FlowChildReport>
1798
+ ): JobStore.FlowChildReport => ({
1799
+ flowId,
1800
+ childKey: key,
1801
+ outcome,
1802
+ exit: { ok: outcome === "completed" },
1803
+ failedReason: undefined,
1804
+ ...overrides
1805
+ })
1806
+
1807
+ // Batch-of-one sugar for the single-report pins below; the batch
1808
+ // semantics get their own section.
1809
+ const recordOne = (store: JobStore.Service, value: JobStore.FlowChildReport) =>
1810
+ Effect.map(
1811
+ store.recordChildResults([value]),
1812
+ (results) => results[0] ?? { applied: false, parentSettled: false }
1813
+ )
1814
+
1815
+ const flowCounts = (
1816
+ overrides?: Partial<Omit<JobStore.FlowState, "failFast">> & { readonly failFast?: boolean }
1817
+ ): JobStore.FlowState => ({
1818
+ failFast: false,
1819
+ pending: 0,
1820
+ completed: 0,
1821
+ failed: 0,
1822
+ cancelled: 0,
1823
+ ...overrides
1824
+ })
1825
+
1826
+ it.effect("FanOut parks the parent with its manifest, rows, and ledger entry", () =>
1827
+ withStore((store) =>
1828
+ Effect.gen(function*() {
1829
+ const flowId = yield* fanOutParent(store)
1830
+
1831
+ const parent = yield* store.getJob(flowId)
1832
+ assert(Option.isSome(parent))
1833
+ expect(parent.value.state).toBe("waiting-children")
1834
+ expect(parent.value.flow).toEqual(flowCounts({ pending: 2 }))
1835
+ // A fan-out is a phase transition, not a completed run.
1836
+ expect(parent.value.attemptsMade).toBe(0)
1837
+ const attempts = yield* store.getAttempts(flowId)
1838
+ expect(attempts.map((attempt) => attempt.outcome)).toEqual(["fanned-out"])
1839
+
1840
+ const rows = yield* store.listChildResults(flowId)
1841
+ expect(rows.cursor).toBeUndefined()
1842
+ expect(rows.items.map((row) => ({
1843
+ childKey: row.childKey,
1844
+ name: row.name,
1845
+ storeKey: row.storeKey,
1846
+ childJobId: row.childJobId,
1847
+ status: row.status,
1848
+ cascaded: row.cascaded
1849
+ }))).toEqual([
1850
+ {
1851
+ childKey: "a",
1852
+ name: "ChildJob",
1853
+ storeKey: "effect-mq/JobStore/children",
1854
+ childJobId: `flow/main/${flowId}/a`,
1855
+ status: "pending",
1856
+ cascaded: false
1857
+ },
1858
+ {
1859
+ childKey: "b",
1860
+ name: "ChildJob",
1861
+ storeKey: "effect-mq/JobStore/children",
1862
+ childJobId: `flow/main/${flowId}/b`,
1863
+ status: "pending",
1864
+ cascaded: false
1865
+ }
1866
+ ])
1867
+
1868
+ // Parked parents are never claimable and show in counts.
1869
+ const claim = yield* store.claim(claimOptions({ token: "t-again" }))
1870
+ expect(claim._tag).toBe("Empty")
1871
+ expect((yield* store.counts())["waiting-children"]).toBe(1)
1872
+ })
1873
+ ))
1874
+
1875
+ it.effect("FanOut is lock-token-guarded and validates child ids", () =>
1876
+ withStore((store) =>
1877
+ Effect.gen(function*() {
1878
+ const { id } = yield* store.enqueue(baseRequest())
1879
+ const claim = yield* store.claim(claimOptions({ token: "t-owner" }))
1880
+ assert(claim._tag === "Claimed")
1881
+
1882
+ const stale = yield* Effect.exit(store.ack(id, "t-wrong", {
1883
+ _tag: "FanOut",
1884
+ failFast: false,
1885
+ children: [childSpec(id, "a")]
1886
+ }))
1887
+ assert(Exit.isFailure(stale))
1888
+
1889
+ // A spec without an explicit id fails loudly and leaves the job
1890
+ // active (the ack can be retried with a fixed spec).
1891
+ const bad = yield* Effect.exit(store.ack(id, "t-owner", {
1892
+ _tag: "FanOut",
1893
+ failFast: false,
1894
+ children: [{ ...childSpec(id, "a"), request: baseRequest({ id: undefined }) }]
1895
+ }))
1896
+ assert(Exit.isFailure(bad))
1897
+ const job = yield* store.getJob(id)
1898
+ assert(Option.isSome(job))
1899
+ expect(job.value.state).toBe("active")
1900
+
1901
+ yield* store.ack(id, "t-owner", {
1902
+ _tag: "FanOut",
1903
+ failFast: false,
1904
+ children: [childSpec(id, "a")]
1905
+ })
1906
+ })
1907
+ ))
1908
+
1909
+ it.effect("an empty FanOut settles straight to runnable collect", () =>
1910
+ withStore((store) =>
1911
+ Effect.gen(function*() {
1912
+ const flowId = yield* fanOutParent(store, { children: [] })
1913
+ const parent = yield* store.getJob(flowId)
1914
+ assert(Option.isSome(parent))
1915
+ expect(parent.value.state).toBe("waiting")
1916
+ expect(parent.value.flow).toEqual(flowCounts())
1917
+
1918
+ const claim = yield* store.claim(claimOptions({ token: "t-resume" }))
1919
+ assert(claim._tag === "Claimed")
1920
+ expect(claim.job.id).toBe(flowId)
1921
+ expect(claim.job.flow).toEqual(flowCounts())
1922
+ })
1923
+ ))
1924
+
1925
+ it.effect("recordChildResults applies once, decrements, and settles on the last report", () =>
1926
+ withStore((store) =>
1927
+ Effect.gen(function*() {
1928
+ const flowId = yield* fanOutParent(store)
1929
+
1930
+ const first = yield* recordOne(store, report(flowId, "a", "completed"))
1931
+ expect(first).toEqual({ applied: true, parentSettled: false })
1932
+ const midway = yield* store.getJob(flowId)
1933
+ assert(Option.isSome(midway))
1934
+ expect(midway.value.state).toBe("waiting-children")
1935
+ expect(midway.value.flow?.pending).toBe(1)
1936
+
1937
+ // Duplicates and unknowns drop on the dependency row.
1938
+ expect(yield* recordOne(store, report(flowId, "a", "failed")))
1939
+ .toEqual({ applied: false, parentSettled: false })
1940
+ expect(yield* recordOne(store, report(flowId, "ghost", "completed")))
1941
+ .toEqual({ applied: false, parentSettled: false })
1942
+ expect(yield* recordOne(store, report(JobId("no-such-flow"), "a", "completed")))
1943
+ .toEqual({ applied: false, parentSettled: false })
1944
+
1945
+ const last = yield* recordOne(store, report(flowId, "b", "failed", {
1946
+ exit: { boom: true }
1947
+ }))
1948
+ expect(last).toEqual({ applied: true, parentSettled: true })
1949
+
1950
+ // Settled: runnable now, phase collect, results recorded exactly.
1951
+ const parent = yield* store.getJob(flowId)
1952
+ assert(Option.isSome(parent))
1953
+ expect(parent.value.state).toBe("waiting")
1954
+ // The counters mirror the recorded outcomes exactly — via getJob,
1955
+ // via the claimed record (what `collect` reads its counts from),
1956
+ // and via list (what dashboards read). A driver whose claim/list
1957
+ // projections drop the counter columns fails here, not in prod.
1958
+ expect(parent.value.flow).toEqual(flowCounts({ completed: 1, failed: 1 }))
1959
+ const claim = yield* store.claim(claimOptions({ token: "t-resume" }))
1960
+ assert(claim._tag === "Claimed")
1961
+ expect(claim.job.id).toBe(flowId)
1962
+ expect(claim.job.flow).toEqual(flowCounts({ completed: 1, failed: 1 }))
1963
+ const listed = yield* store.list({ name: "TestJob" })
1964
+ expect(listed.items.find((job) => job.id === flowId)?.flow)
1965
+ .toEqual(flowCounts({ completed: 1, failed: 1 }))
1966
+
1967
+ const rows = yield* store.listChildResults(flowId)
1968
+ const byKey = new Map(rows.items.map((row) => [row.childKey, row]))
1969
+ expect(byKey.get("a")?.status).toBe("completed")
1970
+ expect(byKey.get("a")?.exit).toEqual({ ok: true })
1971
+ // A recorded outcome came FROM the child's store: nothing to cascade.
1972
+ expect(byKey.get("a")?.cascaded).toBe(true)
1973
+ expect(byKey.get("b")?.status).toBe("failed")
1974
+ expect(byKey.get("b")?.exit).toEqual({ boom: true })
1975
+ })
1976
+ ))
1977
+
1978
+ it.effect("recordChildResults wakes a taker parked on the parent's queue", () =>
1979
+ withStore((store) =>
1980
+ Effect.gen(function*() {
1981
+ const flowId = yield* fanOutParent(store, { children: ["only"] })
1982
+ const empty = yield* store.claim(claimOptions({ token: "t-idle" }))
1983
+ assert(empty._tag === "Empty")
1984
+ const waiter = yield* Effect.forkChild(
1985
+ store.awaitWake([QueueName("default")], empty.wakeToken)
1986
+ )
1987
+ yield* TestClock.adjust(1)
1988
+ yield* recordOne(store, report(flowId, "only", "completed"))
1989
+ yield* TestClock.adjust(1)
1990
+ expect(yield* Fiber.join(waiter)).toBeUndefined()
1991
+ })
1992
+ ))
1993
+
1994
+ it.effect("concurrent last reports settle the parent exactly once", () =>
1995
+ withStore((store) =>
1996
+ Effect.gen(function*() {
1997
+ const flowId = yield* fanOutParent(store)
1998
+ const results = yield* Effect.all([
1999
+ recordOne(store, report(flowId, "a", "completed")),
2000
+ recordOne(store, report(flowId, "b", "completed")),
2001
+ recordOne(store, report(flowId, "a", "completed")),
2002
+ recordOne(store, report(flowId, "b", "completed"))
2003
+ ], { concurrency: 4 })
2004
+ expect(results.filter((result) => result.applied).length).toBe(2)
2005
+ expect(results.filter((result) => result.parentSettled).length).toBe(1)
2006
+ })
2007
+ ))
2008
+
2009
+ it.effect("fail-fast settles the parent terminally and marks remaining rows", () =>
2010
+ withStore((store) =>
2011
+ Effect.gen(function*() {
2012
+ const flowId = yield* fanOutParent(store, { children: ["a", "b", "c"], failFast: true })
2013
+ yield* recordOne(store, report(flowId, "a", "completed"))
2014
+ const settle = yield* recordOne(store, report(flowId, "b", "failed"))
2015
+ expect(settle).toEqual({ applied: true, parentSettled: true })
2016
+
2017
+ const parent = yield* store.getJob(flowId)
2018
+ assert(Option.isSome(parent))
2019
+ expect(parent.value.state).toBe("failed")
2020
+ expect(parent.value.failedReason).toContain("b")
2021
+ expect(parent.value.exit).toBeUndefined()
2022
+
2023
+ const rows = yield* store.listChildResults(flowId)
2024
+ const remaining = rows.items.find((row) => row.childKey === "c")
2025
+ expect(remaining?.status).toBe("cancelled")
2026
+ // Marked by the settle — the sweeper still owes a real cancel.
2027
+ expect(remaining?.cascaded).toBe(false)
2028
+ // Settle-time marking lands in the counters too.
2029
+ expect(parent.value.flow).toEqual(
2030
+ flowCounts({ failFast: true, completed: 1, failed: 1, cancelled: 1 })
2031
+ )
2032
+
2033
+ // A late completion finds its row terminal and drops.
2034
+ expect(yield* recordOne(store, report(flowId, "c", "completed")))
2035
+ .toEqual({ applied: false, parentSettled: false })
2036
+ })
2037
+ ))
2038
+
2039
+ it.effect("cancelling a waiting-children parent settles and marks its pending rows", () =>
2040
+ withStore((store) =>
2041
+ Effect.gen(function*() {
2042
+ const flowId = yield* fanOutParent(store)
2043
+ yield* recordOne(store, report(flowId, "a", "completed"))
2044
+ yield* store.cancel(flowId)
2045
+
2046
+ const parent = yield* store.getJob(flowId)
2047
+ assert(Option.isSome(parent))
2048
+ expect(parent.value.state).toBe("cancelled")
2049
+ // The settle marking moves the counters too.
2050
+ expect(parent.value.flow).toEqual(flowCounts({ completed: 1, cancelled: 1 }))
2051
+
2052
+ const rows = yield* store.listChildResults(flowId)
2053
+ const byKey = new Map(rows.items.map((row) => [row.childKey, row]))
2054
+ expect(byKey.get("a")?.status).toBe("completed")
2055
+ expect(byKey.get("b")?.status).toBe("cancelled")
2056
+ expect(byKey.get("b")?.cascaded).toBe(false)
2057
+
2058
+ expect(yield* recordOne(store, report(flowId, "b", "completed")))
2059
+ .toEqual({ applied: false, parentSettled: false })
2060
+ })
2061
+ ))
2062
+
2063
+ it.effect("a cancel that races the fan-out wins and marks the rows", () =>
2064
+ withStore((store) =>
2065
+ Effect.gen(function*() {
2066
+ const { id } = yield* store.enqueue(baseRequest())
2067
+ const claim = yield* store.claim(claimOptions({ token: "t-parent" }))
2068
+ assert(claim._tag === "Claimed")
2069
+ // Cancel the ACTIVE parent (sets cancelRequested), then the worker
2070
+ // acks its fan-out: cancellation wins over parking.
2071
+ yield* store.cancel(id)
2072
+ yield* store.ack(id, "t-parent", {
2073
+ _tag: "FanOut",
2074
+ failFast: false,
2075
+ children: [childSpec(id, "a"), childSpec(id, "b")]
2076
+ })
2077
+
2078
+ const parent = yield* store.getJob(id)
2079
+ assert(Option.isSome(parent))
2080
+ expect(parent.value.state).toBe("cancelled")
2081
+ expect(parent.value.flow).toEqual(flowCounts({ cancelled: 2 }))
2082
+
2083
+ // The manifest landed and every row was marked for cascade, so
2084
+ // the sweeper delivers (mostly no-op) cancels to the child store.
2085
+ const rows = yield* store.listChildResults(id)
2086
+ expect(rows.items.map((row) => row.status)).toEqual(["cancelled", "cancelled"])
2087
+ expect(rows.items.every((row) => !row.cascaded)).toBe(true)
2088
+ const work = yield* store.flowSweepWork({ pendingAgeMs: 0 })
2089
+ expect(work.cascade[0]?.children.map((child) => child.childKey)).toEqual(["a", "b"])
2090
+ })
2091
+ ))
2092
+
2093
+ it.effect("promote and retry reject a waiting-children parent", () =>
2094
+ withStore((store) =>
2095
+ Effect.gen(function*() {
2096
+ const flowId = yield* fanOutParent(store)
2097
+ const promoted = yield* Effect.exit(store.promote(flowId))
2098
+ assert(Exit.isFailure(promoted))
2099
+ const retried = yield* Effect.exit(store.retry(flowId))
2100
+ assert(Exit.isFailure(retried))
2101
+ })
2102
+ ))
2103
+
2104
+ it.effect("retrying a fail-fast-failed parent re-enters collect with its manifest", () =>
2105
+ withStore((store) =>
2106
+ Effect.gen(function*() {
2107
+ const flowId = yield* fanOutParent(store, { children: ["a", "b"], failFast: true })
2108
+ yield* recordOne(store, report(flowId, "a", "failed"))
2109
+ yield* store.retry(flowId)
2110
+
2111
+ const parent = yield* store.getJob(flowId)
2112
+ assert(Option.isSome(parent))
2113
+ expect(parent.value.state).toBe("waiting")
2114
+ // The manifest survives: a re-claimed parent dispatches collect,
2115
+ // never a second fan-out.
2116
+ expect(parent.value.flow).toBeDefined()
2117
+ expect((yield* store.listChildResults(flowId)).items.length).toBe(2)
2118
+ })
2119
+ ))
2120
+
2121
+ it.effect("a second FanOut converges on the persisted manifest", () =>
2122
+ withStore((store) =>
2123
+ Effect.gen(function*() {
2124
+ const flowId = yield* fanOutParent(store, { children: ["a"] })
2125
+ yield* recordOne(store, report(flowId, "a", "completed"))
2126
+ // Parent settled to waiting; claim and (bug-path) fan out again
2127
+ // with DIFFERENT children.
2128
+ const claim = yield* store.claim(claimOptions({ token: "t-double" }))
2129
+ assert(claim._tag === "Claimed")
2130
+ yield* store.ack(flowId, "t-double", {
2131
+ _tag: "FanOut",
2132
+ failFast: false,
2133
+ children: [childSpec(flowId, "x"), childSpec(flowId, "y")]
2134
+ })
2135
+
2136
+ // The original manifest is untouched; state follows its pending
2137
+ // count (0 → runnable collect again).
2138
+ const rows = yield* store.listChildResults(flowId)
2139
+ expect(rows.items.map((row) => row.childKey)).toEqual(["a"])
2140
+ const parent = yield* store.getJob(flowId)
2141
+ assert(Option.isSome(parent))
2142
+ expect(parent.value.state).toBe("waiting")
2143
+ })
2144
+ ))
2145
+
2146
+ it.effect("flowSweepWork scopes reconcile by parent state and pending age", () =>
2147
+ withStore((store) =>
2148
+ Effect.gen(function*() {
2149
+ const flowId = yield* fanOutParent(store)
2150
+
2151
+ // Fresh rows are the push path's business.
2152
+ const fresh = yield* store.flowSweepWork({ pendingAgeMs: 30_000 })
2153
+ expect(fresh.reconcile).toEqual([])
2154
+ expect(fresh.cascade).toEqual([])
2155
+
2156
+ yield* TestClock.adjust(30_000)
2157
+ const due = yield* store.flowSweepWork({ pendingAgeMs: 30_000 })
2158
+ expect(due.reconcile.length).toBe(1)
2159
+ expect(due.reconcile[0]?.flowId).toBe(flowId)
2160
+ expect(due.reconcile[0]?.children.map((child) => child.childKey)).toEqual(["a", "b"])
2161
+ // The stored spec is the complete original request.
2162
+ expect(due.reconcile[0]?.children[0]?.request).toEqual(
2163
+ childSpec(flowId, "a").request
2164
+ )
2165
+
2166
+ // Returned rows are re-armed: they leave the page for another full
2167
+ // age, so a sweep page rotates instead of pinning its head.
2168
+ const rearmed = yield* store.flowSweepWork({ pendingAgeMs: 30_000 })
2169
+ expect(rearmed.reconcile).toEqual([])
2170
+
2171
+ // A recorded row leaves the reconcile set for good; a settled
2172
+ // parent leaves it entirely.
2173
+ yield* recordOne(store, report(flowId, "a", "completed"))
2174
+ yield* TestClock.adjust(30_000)
2175
+ const partial = yield* store.flowSweepWork({ pendingAgeMs: 30_000 })
2176
+ expect(partial.reconcile[0]?.children.map((child) => child.childKey)).toEqual(["b"])
2177
+ yield* recordOne(store, report(flowId, "b", "completed"))
2178
+ yield* TestClock.adjust(30_000)
2179
+ const settled = yield* store.flowSweepWork({ pendingAgeMs: 30_000 })
2180
+ expect(settled.reconcile).toEqual([])
2181
+ })
2182
+ ))
2183
+
2184
+ it.effect("a fail-fast report that is also the last pending row settles as failed", () =>
2185
+ withStore((store) =>
2186
+ Effect.gen(function*() {
2187
+ const flowId = yield* fanOutParent(store, { children: ["a", "b"], failFast: true })
2188
+ yield* recordOne(store, report(flowId, "a", "completed"))
2189
+ // This report triggers BOTH settle rules: pending hits zero AND it
2190
+ // is the first failure under fail-fast. Fail-fast wins: terminal
2191
+ // `failed`, never a resume into collect.
2192
+ const last = yield* recordOne(store, report(flowId, "b", "failed"))
2193
+ expect(last).toEqual({ applied: true, parentSettled: true })
2194
+ const parent = yield* store.getJob(flowId)
2195
+ assert(Option.isSome(parent))
2196
+ expect(parent.value.state).toBe("failed")
2197
+ expect(parent.value.failedReason).toContain("b")
2198
+ })
2199
+ ))
2200
+
2201
+ it.effect("an empty FanOut wakes takers parked on the parent's queue", () =>
2202
+ withStore((store) =>
2203
+ Effect.gen(function*() {
2204
+ const { id } = yield* store.enqueue(baseRequest())
2205
+ const claim = yield* store.claim(claimOptions({ token: "t-parent" }))
2206
+ assert(claim._tag === "Claimed")
2207
+ const empty = yield* store.claim(claimOptions({ token: "t-idle" }))
2208
+ assert(empty._tag === "Empty")
2209
+ const waiter = yield* Effect.forkChild(
2210
+ store.awaitWake([QueueName("default")], empty.wakeToken)
2211
+ )
2212
+ yield* TestClock.adjust(1)
2213
+ yield* store.ack(id, "t-parent", { _tag: "FanOut", failFast: false, children: [] })
2214
+ yield* TestClock.adjust(1)
2215
+ expect(yield* Fiber.join(waiter)).toBeUndefined()
2216
+ })
2217
+ ))
2218
+
2219
+ it.effect("automatic retention spares a settled parent that still owes cascades", () =>
2220
+ withStore((store) =>
2221
+ Effect.gen(function*() {
2222
+ // A fail-fast settle marks rows for cascade in the same op that
2223
+ // makes the parent prunable — retention must not race the sweeper
2224
+ // out of its only record that cancels are still owed.
2225
+ const keep = { failed: { count: 1, ageMs: undefined } }
2226
+ const { id: flowId } = yield* store.enqueue(baseRequest({ keep }))
2227
+ const claim = yield* store.claim(claimOptions({ token: "t-parent" }))
2228
+ assert(claim._tag === "Claimed")
2229
+ yield* store.ack(flowId, "t-parent", {
2230
+ _tag: "FanOut",
2231
+ failFast: true,
2232
+ children: [childSpec(flowId, "a"), childSpec(flowId, "b")]
2233
+ })
2234
+ yield* recordOne(store, report(flowId, "a", "failed"))
2235
+
2236
+ // A newer failed peer would evict the flow parent under count: 1 —
2237
+ // but its "b" row is cancelled and not yet cascaded.
2238
+ const { id: peer1 } = yield* store.enqueue(baseRequest({ keep }))
2239
+ const claim1 = yield* store.claim(claimOptions({ token: "t-p1" }))
2240
+ assert(claim1._tag === "Claimed")
2241
+ yield* store.ack(peer1, "t-p1", { _tag: "Fail", exit: undefined })
2242
+ const spared = yield* store.getJob(flowId)
2243
+ assert(Option.isSome(spared))
2244
+ expect(spared.value.state).toBe("failed")
2245
+ expect((yield* store.listChildResults(flowId)).items.length).toBe(2)
2246
+
2247
+ // Once the cascade is delivered, retention applies normally.
2248
+ yield* store.markChildrenCascaded(flowId, ["b"])
2249
+ const { id: peer2 } = yield* store.enqueue(baseRequest({ keep }))
2250
+ const claim2 = yield* store.claim(claimOptions({ token: "t-p2" }))
2251
+ assert(claim2._tag === "Claimed")
2252
+ yield* store.ack(peer2, "t-p2", { _tag: "Fail", exit: undefined })
2253
+ expect(Option.isNone(yield* store.getJob(flowId))).toBe(true)
2254
+ expect((yield* store.listChildResults(flowId)).items).toEqual([])
2255
+ })
2256
+ ))
2257
+
2258
+ it.effect("flowSweepWork yields cascade work until rows are marked cascaded", () =>
2259
+ withStore((store) =>
2260
+ Effect.gen(function*() {
2261
+ const flowId = yield* fanOutParent(store, { children: ["a", "b"], failFast: true })
2262
+ yield* recordOne(store, report(flowId, "a", "failed"))
2263
+
2264
+ const work = yield* store.flowSweepWork({ pendingAgeMs: 30_000 })
2265
+ // Settled flow: nothing to reconcile, but "b" owes a cascade.
2266
+ expect(work.reconcile).toEqual([])
2267
+ expect(work.cascade.length).toBe(1)
2268
+ expect(work.cascade[0]?.children).toEqual([{
2269
+ childKey: "b",
2270
+ storeKey: "effect-mq/JobStore/children",
2271
+ childJobId: `flow/main/${flowId}/b`
2272
+ }])
2273
+
2274
+ yield* store.markChildrenCascaded(flowId, ["b"])
2275
+ const after = yield* store.flowSweepWork({ pendingAgeMs: 30_000 })
2276
+ expect(after.cascade).toEqual([])
2277
+ // Idempotent (unknown keys included).
2278
+ yield* store.markChildrenCascaded(flowId, ["b", "ghost"])
2279
+ })
2280
+ ))
2281
+
2282
+ it.effect("listChildResults paginates in child-key order", () =>
2283
+ withStore((store) =>
2284
+ Effect.gen(function*() {
2285
+ const flowId = yield* fanOutParent(store, { children: ["c", "a", "b"] })
2286
+ const first = yield* store.listChildResults(flowId, { limit: 2 })
2287
+ expect(first.items.map((row) => row.childKey)).toEqual(["a", "b"])
2288
+ expect(first.cursor).toBeDefined()
2289
+ const second = yield* store.listChildResults(flowId, {
2290
+ cursor: first.cursor,
2291
+ limit: 2
2292
+ })
2293
+ expect(second.items.map((row) => row.childKey)).toEqual(["c"])
2294
+ expect(second.cursor).toBeUndefined()
2295
+ })
2296
+ ))
2297
+
2298
+ it.effect("remove refuses a waiting-children parent and deletes rows with a settled one", () =>
2299
+ withStore((store) =>
2300
+ Effect.gen(function*() {
2301
+ const flowId = yield* fanOutParent(store, { children: ["a"] })
2302
+ expect(yield* store.remove(flowId)).toBe(false)
2303
+
2304
+ yield* recordOne(store, report(flowId, "a", "failed", { exit: undefined }))
2305
+ // continue-policy: the parent settled to waiting; cancel it so it
2306
+ // is removable, then remove it — the dependency rows go with it.
2307
+ yield* store.cancel(flowId)
2308
+ expect(yield* store.remove(flowId)).toBe(true)
2309
+ expect((yield* store.listChildResults(flowId)).items).toEqual([])
2310
+ })
2311
+ ))
2312
+
2313
+ it.effect("store-side child failures carry failedReason on the row", () =>
2314
+ withStore((store) =>
2315
+ Effect.gen(function*() {
2316
+ const flowId = yield* fanOutParent(store, { children: ["a"] })
2317
+ yield* recordOne(store, report(flowId, "a", "failed", {
2318
+ exit: undefined,
2319
+ failedReason: "job stalled more than allowable limit"
2320
+ }))
2321
+ const rows = yield* store.listChildResults(flowId)
2322
+ expect(rows.items[0]?.exit).toBeUndefined()
2323
+ expect(rows.items[0]?.failedReason).toBe("job stalled more than allowable limit")
2324
+ })
2325
+ ))
2326
+
2327
+ // ----------------------------------------------------------------------
2328
+ // Batched reports + the child-side outbox. The outbox is how a CHILD
2329
+ // store reports terminal transitions to a parent living in another
2330
+ // store: append on the transition, peek/delete from the relay.
2331
+ // ----------------------------------------------------------------------
2332
+
2333
+ it.effect("recordChildResults applies a batch positionally and keeps counters exact", () =>
2334
+ withStore((store) =>
2335
+ Effect.gen(function*() {
2336
+ const flowId = yield* fanOutParent(store, { children: ["a", "b", "c"] })
2337
+ const results = yield* store.recordChildResults([
2338
+ report(flowId, "a", "completed"),
2339
+ report(flowId, "a", "completed"), // duplicate inside the batch
2340
+ report(flowId, "ghost", "completed"),
2341
+ report(flowId, "b", "failed")
2342
+ ])
2343
+ expect(results).toEqual([
2344
+ { applied: true, parentSettled: false },
2345
+ { applied: false, parentSettled: false },
2346
+ { applied: false, parentSettled: false },
2347
+ { applied: true, parentSettled: false }
2348
+ ])
2349
+ const parent = yield* store.getJob(flowId)
2350
+ assert(Option.isSome(parent))
2351
+ expect(parent.value.state).toBe("waiting-children")
2352
+ expect(parent.value.flow).toEqual(flowCounts({ pending: 1, completed: 1, failed: 1 }))
2353
+ })
2354
+ ))
2355
+
2356
+ it.effect("a batch that empties pending settles once, on its last applied report", () =>
2357
+ withStore((store) =>
2358
+ Effect.gen(function*() {
2359
+ const flowId = yield* fanOutParent(store)
2360
+ const results = yield* store.recordChildResults([
2361
+ report(flowId, "a", "completed"),
2362
+ report(flowId, "b", "completed")
2363
+ ])
2364
+ expect(results).toEqual([
2365
+ { applied: true, parentSettled: false },
2366
+ { applied: true, parentSettled: true }
2367
+ ])
2368
+ const parent = yield* store.getJob(flowId)
2369
+ assert(Option.isSome(parent))
2370
+ expect(parent.value.state).toBe("waiting")
2371
+ })
2372
+ ))
2373
+
2374
+ it.effect("fail-fast wins inside a batch, after every batch-mate applied", () =>
2375
+ withStore((store) =>
2376
+ Effect.gen(function*() {
2377
+ const flowId = yield* fanOutParent(store, { children: ["a", "b", "c"], failFast: true })
2378
+ const results = yield* store.recordChildResults([
2379
+ report(flowId, "b", "failed"),
2380
+ report(flowId, "c", "completed")
2381
+ ])
2382
+ // Row updates apply BEFORE the settle decision: "c" keeps its real
2383
+ // completed outcome even though "b" settles the flow.
2384
+ expect(results).toEqual([
2385
+ { applied: true, parentSettled: true },
2386
+ { applied: true, parentSettled: false }
2387
+ ])
2388
+ const parent = yield* store.getJob(flowId)
2389
+ assert(Option.isSome(parent))
2390
+ expect(parent.value.state).toBe("failed")
2391
+ expect(parent.value.failedReason).toContain("b")
2392
+ expect(parent.value.flow).toEqual(
2393
+ flowCounts({ failFast: true, completed: 1, failed: 1, cancelled: 1 })
2394
+ )
2395
+ const rows = yield* store.listChildResults(flowId)
2396
+ const byKey = new Map(rows.items.map((row) => [row.childKey, row.status]))
2397
+ expect(byKey.get("c")).toBe("completed")
2398
+ expect(byKey.get("a")).toBe("cancelled")
2399
+ })
2400
+ ))
2401
+
2402
+ it.effect("a batch may span flows and settles each independently", () =>
2403
+ withStore((store) =>
2404
+ Effect.gen(function*() {
2405
+ const first = yield* fanOutParent(store, { children: ["a"] })
2406
+ const second = yield* fanOutParent(store, { children: ["b"] })
2407
+ const results = yield* store.recordChildResults([
2408
+ report(first, "a", "completed"),
2409
+ report(second, "b", "completed")
2410
+ ])
2411
+ expect(results).toEqual([
2412
+ { applied: true, parentSettled: true },
2413
+ { applied: true, parentSettled: true }
2414
+ ])
2415
+ })
2416
+ ))
2417
+
2418
+ it.effect("a cancelled child report moves the cancelled counter", () =>
2419
+ withStore((store) =>
2420
+ Effect.gen(function*() {
2421
+ const flowId = yield* fanOutParent(store)
2422
+ yield* recordOne(store, report(flowId, "a", "cancelled", { exit: undefined }))
2423
+ const parent = yield* store.getJob(flowId)
2424
+ assert(Option.isSome(parent))
2425
+ expect(parent.value.flow).toEqual(flowCounts({ pending: 1, cancelled: 1 }))
2426
+ })
2427
+ ))
2428
+
2429
+ it.effect("peekOutbox pages past prior entries with `after`, even deleted ones", () =>
2430
+ withStore((store) =>
2431
+ Effect.gen(function*() {
2432
+ const enqueueChild = (key: string) =>
2433
+ Effect.gen(function*() {
2434
+ const { id } = yield* store.enqueue(baseRequest({
2435
+ parent: parentEnvelope(JobId("remote-flow-3"), key)
2436
+ }))
2437
+ const claim = yield* store.claim(claimOptions({ token: `t-${key}` }))
2438
+ assert(claim._tag === "Claimed")
2439
+ yield* store.ack(id, `t-${key}`, { _tag: "Complete", exit: { key } })
2440
+ })
2441
+ yield* enqueueChild("one")
2442
+ yield* enqueueChild("two")
2443
+ yield* enqueueChild("three")
2444
+
2445
+ const first = yield* store.peekOutbox({ limit: 2 })
2446
+ expect(first.map((entry) => entry.report.childKey)).toEqual(["one", "two"])
2447
+ const cursor = first[first.length - 1]?.id
2448
+ assert(cursor !== undefined)
2449
+ const rest = yield* store.peekOutbox({ limit: 2, after: cursor })
2450
+ expect(rest.map((entry) => entry.report.childKey)).toEqual(["three"])
2451
+
2452
+ // The cursor keeps working when the entry it names is gone.
2453
+ yield* store.deleteOutbox([cursor])
2454
+ const restAgain = yield* store.peekOutbox({ limit: 2, after: cursor })
2455
+ expect(restAgain.map((entry) => entry.report.childKey)).toEqual(["three"])
2456
+ })
2457
+ ))
2458
+
2459
+ it.effect("cancels honoured by retry acks, the stall sweep, and on a parked parent land in the outbox", () =>
2460
+ withStore((store) =>
2461
+ Effect.gen(function*() {
2462
+ const envelope = (key: string) => parentEnvelope(JobId("remote-flow-4"), key)
2463
+ // A cancel honoured when a RETRY ack finds the flag set.
2464
+ const retried = yield* store.enqueue(baseRequest({ parent: envelope("retry-cancel") }))
2465
+ const claimA = yield* store.claim(claimOptions({ token: "t-a" }))
2466
+ assert(claimA._tag === "Claimed")
2467
+ yield* store.cancel(retried.id)
2468
+ yield* store.ack(retried.id, "t-a", { _tag: "Retry", delayMs: 0, exit: undefined })
2469
+
2470
+ // A cancel honoured when the stall sweep recovers a dead worker.
2471
+ const stalled = yield* store.enqueue(baseRequest({ parent: envelope("stall-cancel") }))
2472
+ const claimB = yield* store.claim(claimOptions({ token: "t-b", lockDurationMs: 1_000 }))
2473
+ assert(claimB._tag === "Claimed")
2474
+ yield* store.cancel(stalled.id)
2475
+ yield* TestClock.adjust(2_000)
2476
+ yield* store.recoverStalled({ maxStalledCount: 5 })
2477
+
2478
+ // A direct cancel of a PARKED nested parent (waiting-children).
2479
+ const parked = yield* store.enqueue(baseRequest({ parent: envelope("parked-cancel") }))
2480
+ const claimC = yield* store.claim(claimOptions({ token: "t-c" }))
2481
+ assert(claimC._tag === "Claimed")
2482
+ yield* store.ack(parked.id, "t-c", {
2483
+ _tag: "FanOut",
2484
+ failFast: false,
2485
+ children: [childSpec(parked.id, "a")]
2486
+ })
2487
+ yield* store.cancel(parked.id)
2488
+
2489
+ const entries = yield* store.peekOutbox({ limit: 10 })
2490
+ expect(entries.map((entry) => [entry.report.childKey, entry.report.outcome])).toEqual([
2491
+ ["retry-cancel", "cancelled"],
2492
+ ["stall-cancel", "cancelled"],
2493
+ ["parked-cancel", "cancelled"]
2494
+ ])
2495
+ })
2496
+ ))
2497
+
2498
+ it.effect("terminal transitions of envelope-carrying jobs land in the outbox", () =>
2499
+ withStore((store) =>
2500
+ Effect.gen(function*() {
2501
+ const envelope = (key: string) => parentEnvelope(JobId("remote-flow-1"), key)
2502
+ // A plain job's terminal ack appends nothing.
2503
+ const plain = yield* store.enqueue(baseRequest())
2504
+ const plainClaim = yield* store.claim(claimOptions({ token: "t-plain" }))
2505
+ assert(plainClaim._tag === "Claimed")
2506
+ yield* store.ack(plain.id, "t-plain", { _tag: "Complete", exit: { ok: true } })
2507
+ expect(yield* store.peekOutbox({ limit: 10 })).toEqual([])
2508
+
2509
+ // Ack Complete → outbox entry with the exit.
2510
+ const acked = yield* store.enqueue(baseRequest({ parent: envelope("acked") }))
2511
+ const claim = yield* store.claim(claimOptions({ token: "t-child" }))
2512
+ assert(claim._tag === "Claimed")
2513
+ expect(claim.job.id).toBe(acked.id)
2514
+ yield* store.ack(acked.id, "t-child", { _tag: "Complete", exit: { sent: 1 } })
2515
+
2516
+ // Direct cancel of a delayed child → outbox entry.
2517
+ const cancelled = yield* store.enqueue(
2518
+ baseRequest({ parent: envelope("cancelled"), delayMs: 60_000 })
2519
+ )
2520
+ yield* store.cancel(cancelled.id)
2521
+
2522
+ // Stall exhaustion → outbox entry carrying the failedReason.
2523
+ yield* store.enqueue(baseRequest({ parent: envelope("stalled") }))
2524
+ const stalledClaim = yield* store.claim(
2525
+ claimOptions({ token: "t-stall", lockDurationMs: 1_000 })
2526
+ )
2527
+ assert(stalledClaim._tag === "Claimed")
2528
+ yield* TestClock.adjust(2_000)
2529
+ const recovered = yield* store.recoverStalled({ maxStalledCount: 0 })
2530
+ expect(recovered).toEqual([{ id: stalledClaim.job.id, failed: true }])
2531
+
2532
+ // Oldest first, `limit` respected, full entry shape.
2533
+ const firstPage = yield* store.peekOutbox({ limit: 2 })
2534
+ expect(firstPage.map((entry) => entry.report.childKey)).toEqual(["acked", "cancelled"])
2535
+ const head = firstPage[0]
2536
+ assert(head !== undefined)
2537
+ expect(head.flowName).toBe("test-flow")
2538
+ expect(head.parentStoreKey).toBe("main")
2539
+ expect(head.report.flowId).toBe("remote-flow-1")
2540
+ expect(head.report.outcome).toBe("completed")
2541
+ expect(head.report.exit).toEqual({ sent: 1 })
2542
+ const all = yield* store.peekOutbox({ limit: 10 })
2543
+ expect(all.map((entry) => entry.report.outcome)).toEqual([
2544
+ "completed",
2545
+ "cancelled",
2546
+ "failed"
2547
+ ])
2548
+ expect(all[2]?.report.exit).toBeUndefined()
2549
+ expect(all[2]?.report.failedReason).toBe("job stalled more than allowable limit")
2550
+
2551
+ // Peek does not consume; delete does, idempotently.
2552
+ yield* store.deleteOutbox([head.id, "ghost-id"])
2553
+ const rest = yield* store.peekOutbox({ limit: 10 })
2554
+ expect(rest.map((entry) => entry.report.childKey)).toEqual(["cancelled", "stalled"])
2555
+ yield* store.deleteOutbox([head.id])
2556
+ expect((yield* store.peekOutbox({ limit: 10 })).length).toBe(2)
2557
+ })
2558
+ ))
2559
+
2560
+ it.effect("cancels honoured off the ack path still land in the outbox", () =>
2561
+ withStore((store) =>
2562
+ Effect.gen(function*() {
2563
+ // A cancel that arrives while the child runs, honoured when the
2564
+ // worker RELEASES the job (shutdown) instead of acking it.
2565
+ const { id } = yield* store.enqueue(baseRequest({
2566
+ parent: parentEnvelope(JobId("remote-flow-2"), "released")
2567
+ }))
2568
+ const claim = yield* store.claim(claimOptions({ token: "t-run" }))
2569
+ assert(claim._tag === "Claimed")
2570
+ yield* store.cancel(id)
2571
+ yield* store.release(id, "t-run")
2572
+
2573
+ const job = yield* store.getJob(id)
2574
+ assert(Option.isSome(job))
2575
+ expect(job.value.state).toBe("cancelled")
2576
+ const entries = yield* store.peekOutbox({ limit: 10 })
2577
+ expect(entries.map((entry) => entry.report.outcome)).toEqual(["cancelled"])
2578
+ expect(entries[0]?.report.childKey).toBe("released")
2579
+ })
2580
+ ))
2581
+
2582
+ it.effect("a cancel that races a nested parent's fan-out reports upward through the outbox", () =>
2583
+ withStore((store) =>
2584
+ Effect.gen(function*() {
2585
+ // The parent being fanned out is itself a flow child; the raced
2586
+ // cancel settles it terminally inside the FanOut ack.
2587
+ const inner = yield* store.enqueue(baseRequest({
2588
+ parent: {
2589
+ flowName: "outer-flow",
2590
+ flowId: JobId("outer-2"),
2591
+ childKey: "inner-raced",
2592
+ parentStoreKey: "outer-store",
2593
+ depth: 1
2594
+ }
2595
+ }))
2596
+ const claim = yield* store.claim(claimOptions({ token: "t-race" }))
2597
+ assert(claim._tag === "Claimed")
2598
+ yield* store.cancel(inner.id)
2599
+ yield* store.ack(inner.id, "t-race", {
2600
+ _tag: "FanOut",
2601
+ failFast: false,
2602
+ children: [childSpec(inner.id, "a")]
2603
+ })
2604
+
2605
+ const parent = yield* store.getJob(inner.id)
2606
+ assert(Option.isSome(parent))
2607
+ expect(parent.value.state).toBe("cancelled")
2608
+ const entries = yield* store.peekOutbox({ limit: 10 })
2609
+ expect(entries.map((entry) => entry.report.outcome)).toEqual(["cancelled"])
2610
+ expect(entries[0]?.report.childKey).toBe("inner-raced")
2611
+ expect(entries[0]?.flowName).toBe("outer-flow")
2612
+ })
2613
+ ))
2614
+
2615
+ it.effect("a fail-fast settle of a nested parent reports upward through the outbox", () =>
2616
+ withStore((store) =>
2617
+ Effect.gen(function*() {
2618
+ // The inner parent is itself a flow child; its terminal transition
2619
+ // happens store-side (the settle), with no worker ack to hook.
2620
+ const inner = yield* store.enqueue(baseRequest({
2621
+ parent: {
2622
+ flowName: "outer-flow",
2623
+ flowId: JobId("outer-1"),
2624
+ childKey: "inner",
2625
+ parentStoreKey: "outer-store",
2626
+ depth: 1
2627
+ }
2628
+ }))
2629
+ const claim = yield* store.claim(claimOptions({ token: "t-inner" }))
2630
+ assert(claim._tag === "Claimed")
2631
+ yield* store.ack(inner.id, "t-inner", {
2632
+ _tag: "FanOut",
2633
+ failFast: true,
2634
+ children: [childSpec(inner.id, "a")]
2635
+ })
2636
+ // Parking is not terminal: nothing in the outbox yet.
2637
+ expect(yield* store.peekOutbox({ limit: 10 })).toEqual([])
2638
+
2639
+ yield* recordOne(store, report(inner.id, "a", "failed"))
2640
+ const entries = yield* store.peekOutbox({ limit: 10 })
2641
+ expect(entries.length).toBe(1)
2642
+ expect(entries[0]?.flowName).toBe("outer-flow")
2643
+ expect(entries[0]?.report.childKey).toBe("inner")
2644
+ expect(entries[0]?.report.outcome).toBe("failed")
2645
+ expect(entries[0]?.report.failedReason).toContain('"a" failed')
2646
+ })
2647
+ ))
1704
2648
  })
1705
2649
  }