spool-engine 0.0.0-stage → 0.2.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 (166) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +12 -2
  3. package/dist/config.js +130 -0
  4. package/dist/config.js.map +1 -0
  5. package/dist/domain/errors.js +108 -0
  6. package/dist/domain/errors.js.map +1 -0
  7. package/dist/domain/journal.js +21 -0
  8. package/dist/domain/journal.js.map +1 -0
  9. package/dist/domain/json.js +55 -0
  10. package/dist/domain/json.js.map +1 -0
  11. package/dist/domain/llm.js +22 -0
  12. package/dist/domain/llm.js.map +1 -0
  13. package/dist/domain/retry.js +21 -0
  14. package/dist/domain/retry.js.map +1 -0
  15. package/dist/domain/run-status.js +40 -0
  16. package/dist/domain/run-status.js.map +1 -0
  17. package/dist/domain/sleep.js +7 -0
  18. package/dist/domain/sleep.js.map +1 -0
  19. package/dist/engine.js +131 -0
  20. package/dist/engine.js.map +1 -0
  21. package/dist/loops/every.js +32 -0
  22. package/dist/loops/every.js.map +1 -0
  23. package/dist/loops/listener.js +58 -0
  24. package/dist/loops/listener.js.map +1 -0
  25. package/dist/loops/live-runs.js +30 -0
  26. package/dist/loops/live-runs.js.map +1 -0
  27. package/dist/loops/queue-depth.js +28 -0
  28. package/dist/loops/queue-depth.js.map +1 -0
  29. package/dist/loops/reaper.js +71 -0
  30. package/dist/loops/reaper.js.map +1 -0
  31. package/dist/loops/waker.js +42 -0
  32. package/dist/loops/waker.js.map +1 -0
  33. package/dist/main.js +48 -0
  34. package/dist/main.js.map +1 -0
  35. package/dist/observability/logger.js +9 -0
  36. package/dist/observability/logger.js.map +1 -0
  37. package/dist/observability/metrics.js +97 -0
  38. package/dist/observability/metrics.js.map +1 -0
  39. package/dist/observability/tracing.js +146 -0
  40. package/dist/observability/tracing.js.map +1 -0
  41. package/dist/proto/limits_pb.d.ts +212 -0
  42. package/dist/proto/limits_pb.js +76 -0
  43. package/dist/proto/runs_pb.d.ts +740 -0
  44. package/dist/proto/runs_pb.js +147 -0
  45. package/dist/proto/workers_pb.d.ts +900 -0
  46. package/dist/proto/workers_pb.js +168 -0
  47. package/dist/services/admission.js +47 -0
  48. package/dist/services/admission.js.map +1 -0
  49. package/dist/services/cancel-run.js +43 -0
  50. package/dist/services/cancel-run.js.map +1 -0
  51. package/dist/services/claim-tasks.js +59 -0
  52. package/dist/services/claim-tasks.js.map +1 -0
  53. package/dist/services/complete-task.js +45 -0
  54. package/dist/services/complete-task.js.map +1 -0
  55. package/dist/services/fail-step.js +102 -0
  56. package/dist/services/fail-step.js.map +1 -0
  57. package/dist/services/group-commit.js +83 -0
  58. package/dist/services/group-commit.js.map +1 -0
  59. package/dist/services/live-tokens.js +90 -0
  60. package/dist/services/live-tokens.js.map +1 -0
  61. package/dist/services/next-step.js +33 -0
  62. package/dist/services/next-step.js.map +1 -0
  63. package/dist/services/notifier.js +54 -0
  64. package/dist/services/notifier.js.map +1 -0
  65. package/dist/services/query-runs.js +14 -0
  66. package/dist/services/query-runs.js.map +1 -0
  67. package/dist/services/replay-run.js +63 -0
  68. package/dist/services/replay-run.js.map +1 -0
  69. package/dist/services/report-step.js +129 -0
  70. package/dist/services/report-step.js.map +1 -0
  71. package/dist/services/run-watches.js +46 -0
  72. package/dist/services/run-watches.js.map +1 -0
  73. package/dist/services/send-event.js +16 -0
  74. package/dist/services/send-event.js.map +1 -0
  75. package/dist/services/sleep-run.js +47 -0
  76. package/dist/services/sleep-run.js.map +1 -0
  77. package/dist/services/throttle-step.js +76 -0
  78. package/dist/services/throttle-step.js.map +1 -0
  79. package/dist/services/trigger-run.js +38 -0
  80. package/dist/services/trigger-run.js.map +1 -0
  81. package/dist/services/wait-for-event.js +73 -0
  82. package/dist/services/wait-for-event.js.map +1 -0
  83. package/dist/services/wakeups.js +70 -0
  84. package/dist/services/wakeups.js.map +1 -0
  85. package/dist/services/watch-run.js +36 -0
  86. package/dist/services/watch-run.js.map +1 -0
  87. package/dist/services/worker-session.js +198 -0
  88. package/dist/services/worker-session.js.map +1 -0
  89. package/dist/store/errors.js +42 -0
  90. package/dist/store/errors.js.map +1 -0
  91. package/dist/store/events.js +96 -0
  92. package/dist/store/events.js.map +1 -0
  93. package/dist/store/idempotency.js +29 -0
  94. package/dist/store/idempotency.js.map +1 -0
  95. package/dist/store/json.js +9 -0
  96. package/dist/store/json.js.map +1 -0
  97. package/dist/store/limits.js +60 -0
  98. package/dist/store/limits.js.map +1 -0
  99. package/dist/store/migrate.js +20 -0
  100. package/dist/store/migrate.js.map +1 -0
  101. package/dist/store/run-views.js +96 -0
  102. package/dist/store/run-views.js.map +1 -0
  103. package/dist/store/runs.js +104 -0
  104. package/dist/store/runs.js.map +1 -0
  105. package/dist/store/schema.js +191 -0
  106. package/dist/store/schema.js.map +1 -0
  107. package/dist/store/steps.js +114 -0
  108. package/dist/store/steps.js.map +1 -0
  109. package/dist/store/tasks.js +463 -0
  110. package/dist/store/tasks.js.map +1 -0
  111. package/dist/store/transaction.js +23 -0
  112. package/dist/store/transaction.js.map +1 -0
  113. package/dist/store/waits.js +75 -0
  114. package/dist/store/waits.js.map +1 -0
  115. package/dist/store/watches.js +31 -0
  116. package/dist/store/watches.js.map +1 -0
  117. package/dist/transport/auth.js +26 -0
  118. package/dist/transport/auth.js.map +1 -0
  119. package/dist/transport/channel.js +46 -0
  120. package/dist/transport/channel.js.map +1 -0
  121. package/dist/transport/errors.js +74 -0
  122. package/dist/transport/errors.js.map +1 -0
  123. package/dist/transport/limits-service.js +60 -0
  124. package/dist/transport/limits-service.js.map +1 -0
  125. package/dist/transport/protocol.js +14 -0
  126. package/dist/transport/protocol.js.map +1 -0
  127. package/dist/transport/run-events.js +133 -0
  128. package/dist/transport/run-events.js.map +1 -0
  129. package/dist/transport/run-messages.js +78 -0
  130. package/dist/transport/run-messages.js.map +1 -0
  131. package/dist/transport/run-service.js +147 -0
  132. package/dist/transport/run-service.js.map +1 -0
  133. package/dist/transport/server.js +227 -0
  134. package/dist/transport/server.js.map +1 -0
  135. package/dist/transport/validation.js +61 -0
  136. package/dist/transport/validation.js.map +1 -0
  137. package/dist/transport/worker-service.js +396 -0
  138. package/dist/transport/worker-service.js.map +1 -0
  139. package/drizzle/0000_init.sql +95 -0
  140. package/drizzle/0001_tasks_storage.sql +2 -0
  141. package/drizzle/0002_waits_route.sql +3 -0
  142. package/drizzle/0003_event_waits.sql +8 -0
  143. package/drizzle/0004_llm_steps.sql +2 -0
  144. package/drizzle/0005_tasks_notify.sql +19 -0
  145. package/drizzle/0006_drop_tasks_notify.sql +8 -0
  146. package/drizzle/0007_tasks_fair.sql +5 -0
  147. package/drizzle/0008_concurrency_limits.sql +8 -0
  148. package/drizzle/0009_rate_limits.sql +12 -0
  149. package/drizzle/0010_run_listings.sql +2 -0
  150. package/drizzle/0011_run_replays.sql +7 -0
  151. package/drizzle/0012_run_watches.sql +8 -0
  152. package/drizzle/meta/0000_snapshot.json +668 -0
  153. package/drizzle/meta/0001_snapshot.json +668 -0
  154. package/drizzle/meta/0002_snapshot.json +680 -0
  155. package/drizzle/meta/0003_snapshot.json +723 -0
  156. package/drizzle/meta/0004_snapshot.json +733 -0
  157. package/drizzle/meta/0005_snapshot.json +733 -0
  158. package/drizzle/meta/0006_snapshot.json +733 -0
  159. package/drizzle/meta/0007_snapshot.json +739 -0
  160. package/drizzle/meta/0008_snapshot.json +791 -0
  161. package/drizzle/meta/0009_snapshot.json +843 -0
  162. package/drizzle/meta/0010_snapshot.json +881 -0
  163. package/drizzle/meta/0011_snapshot.json +903 -0
  164. package/drizzle/meta/0012_snapshot.json +958 -0
  165. package/drizzle/meta/_journal.json +97 -0
  166. package/package.json +58 -3
@@ -0,0 +1,463 @@
1
+ import { statusesThatCanBecome } from "../domain/run-status.js";
2
+ import { withTransaction } from "./transaction.js";
3
+ /** One round trip claims at most this many tasks. */
4
+ export const MAX_CLAIM_BATCH = 1000;
5
+ /**
6
+ * Leases runnable tasks to `owner`, taking turns across tenants (F12), so one
7
+ * tenant's backlog of any depth cannot starve the others, and never past a concurrency
8
+ * limit (F10). Expiry uses the database clock, so engine clock skew cannot shorten
9
+ * or extend a lease.
10
+ *
11
+ * The claim visits up to `limit` tenants that have queued tasks, in tenant order starting
12
+ * after `after` and wrapping around, then takes up to ⌈limit / tenants⌉ tasks from each,
13
+ * highest priority then oldest first, and returns them in turns. Its cost follows the
14
+ * claim's size, not the depth of any backlog or the number of tenants.
15
+ *
16
+ * Tasks whose concurrency key has no limit are leased by that one statement. A key with a
17
+ * limit is counted there without locks, and a key already full is passed over, so a
18
+ * tenant held at its limit makes no claim wait. The rest are leased by leaseWithinLimits,
19
+ * which locks each key's limit and counts again.
20
+ *
21
+ * Plan: a recursive skip scan finds each next tenant with one Index Only Scan step on
22
+ * tasks_fair (queue, tenant_id, ...), fenced with OFFSET 0 so each probe runs once; each
23
+ * tenant's tasks come from an Index Scan on tasks_fair with run_after as an index
24
+ * condition, then LockRows; a key's running runs are an Index Only Scan on
25
+ * tasks_running_keys; the UPDATE finds the picked rows by primary key, because joining a
26
+ * CTE made the planner seq-scan the table. Concurrent claimers skip
27
+ * each other's locked rows instead of waiting.
28
+ */
29
+ export async function claimTasks(sql, request) {
30
+ const { queue, workflows, owner, limit, leaseMs } = request;
31
+ const after = request.after ?? "";
32
+ checkBatch(limit);
33
+ if (!Number.isInteger(leaseMs) || leaseMs < 1) {
34
+ throw new RangeError("leaseMs must be a positive integer");
35
+ }
36
+ if (workflows.length === 0)
37
+ throw new RangeError("workflows must not be empty");
38
+ if (owner.length === 0)
39
+ throw new RangeError("owner must not be empty");
40
+ // A probe that wraps past the end starts again at the first tenant, and the ring stops
41
+ // before it reaches a tenant it already visited (one after `after`). It looks one tenant
42
+ // further than it claims from, which tells whether it saw them all.
43
+ const [row] = await sql `
44
+ WITH RECURSIVE ring(tenant_id, wrapped, n) AS (
45
+ SELECT ${after}::text, false, 0
46
+ UNION ALL
47
+ SELECT next.tenant_id, next.wrapped, r.n + 1
48
+ FROM ring r
49
+ CROSS JOIN LATERAL (
50
+ SELECT coalesce(probe.tenant_id, CASE WHEN NOT r.wrapped THEN (
51
+ SELECT tenant_id FROM tasks
52
+ WHERE queue = ${queue} AND lease_owner IS NULL
53
+ ORDER BY tenant_id LIMIT 1) END) AS tenant_id,
54
+ r.wrapped OR probe.tenant_id IS NULL AS wrapped
55
+ FROM (
56
+ SELECT (SELECT tenant_id FROM tasks
57
+ WHERE queue = ${queue} AND lease_owner IS NULL AND tenant_id > r.tenant_id
58
+ ORDER BY tenant_id LIMIT 1) AS tenant_id
59
+ OFFSET 0
60
+ ) probe
61
+ OFFSET 0
62
+ ) next
63
+ WHERE r.n <= ${limit}
64
+ AND next.tenant_id IS NOT NULL
65
+ AND NOT (next.wrapped AND next.tenant_id > ${after}::text)
66
+ ),
67
+ picked AS (
68
+ SELECT p.id, p.concurrency_key, r.n, p.turn
69
+ FROM ring r
70
+ CROSS JOIN LATERAL (
71
+ SELECT id, concurrency_key, row_number() OVER () AS turn
72
+ FROM (
73
+ SELECT id, concurrency_key FROM tasks
74
+ WHERE queue = ${queue}
75
+ AND tenant_id = r.tenant_id
76
+ AND lease_owner IS NULL
77
+ AND run_after <= now()
78
+ AND workflow = ANY(${[...workflows]}::text[])
79
+ ORDER BY priority DESC, run_after
80
+ LIMIT (SELECT ceil(${limit}::numeric / count(*))::int
81
+ FROM ring WHERE n BETWEEN 1 AND ${limit})
82
+ FOR UPDATE SKIP LOCKED
83
+ ) mine
84
+ ) p
85
+ WHERE r.n BETWEEN 1 AND ${limit}
86
+ ),
87
+ chosen AS (
88
+ SELECT id, concurrency_key, row_number() OVER (ORDER BY turn, n) AS place
89
+ FROM (SELECT * FROM picked ORDER BY turn, n LIMIT ${limit}) first
90
+ ),
91
+ -- Room left under each limit among the chosen keys, as this statement sees it.
92
+ room AS (
93
+ SELECT s.key, s.max_running - (
94
+ SELECT count(*) FROM tasks l
95
+ WHERE l.concurrency_key = s.key AND l.lease_owner IS NOT NULL) AS room
96
+ FROM concurrency_slots s
97
+ WHERE s.key IN (SELECT concurrency_key FROM chosen)
98
+ ),
99
+ claimed AS (
100
+ UPDATE tasks t
101
+ SET lease_owner = ${owner},
102
+ lease_expires_at = now() + make_interval(secs => ${leaseMs / 1000}),
103
+ attempt = t.attempt + 1
104
+ WHERE t.id = ANY(ARRAY(
105
+ SELECT c.id FROM chosen c
106
+ WHERE c.concurrency_key IS NULL
107
+ OR NOT EXISTS (SELECT 1 FROM room WHERE room.key = c.concurrency_key)))
108
+ RETURNING t.id, t.run_id, t.tenant_id, t.workflow, t.attempt,
109
+ extract(epoch FROM now() - t.run_after)::float8 * 1000 AS waited_ms
110
+ )
111
+ SELECT
112
+ coalesce((
113
+ SELECT json_agg(json_build_object(
114
+ 'id', c.id::text, 'runId', c.run_id, 'tenantId', c.tenant_id,
115
+ 'workflow', c.workflow, 'attempt', c.attempt, 'waitedMs', c.waited_ms,
116
+ 'place', ch.place))
117
+ FROM claimed c JOIN chosen ch ON ch.id = c.id
118
+ ), '[]'::json) AS tasks,
119
+ coalesce((
120
+ SELECT json_agg(json_build_object('id', id::text, 'key', concurrency_key, 'place', place))
121
+ FROM (
122
+ SELECT c.id, c.concurrency_key, c.place, room.room,
123
+ row_number() OVER (PARTITION BY c.concurrency_key ORDER BY c.place) AS nth
124
+ FROM chosen c JOIN room ON room.key = c.concurrency_key
125
+ ) ranked
126
+ WHERE nth <= room
127
+ ), '[]'::json) AS limited,
128
+ (SELECT tenant_id FROM ring WHERE n <= ${limit} ORDER BY n DESC LIMIT 1) AS "lastTenant",
129
+ (SELECT count(*)::int FROM ring WHERE n > 0) AS visited`;
130
+ if (row === undefined)
131
+ throw new Error("the claim returned no row");
132
+ const placed = [...row.tasks];
133
+ if (row.limited.length > 0)
134
+ placed.push(...(await leaseWithinLimits(sql, row.limited, request)));
135
+ return {
136
+ tasks: placed
137
+ .toSorted((a, b) => a.place - b.place)
138
+ .map((task) => ({
139
+ id: task.id,
140
+ runId: task.runId,
141
+ tenantId: task.tenantId,
142
+ workflow: task.workflow,
143
+ attempt: task.attempt,
144
+ waitedMs: task.waitedMs,
145
+ })),
146
+ lastTenant: row.lastTenant,
147
+ // The ring found a tenant beyond the ones it claimed from only if one was left unseen.
148
+ sawEveryTenant: row.visited <= limit,
149
+ };
150
+ }
151
+ /**
152
+ * Leases the candidates whose key has a concurrency limit, never past it. Locks the
153
+ * keys' limits first, in key order, so claimers of one key take turns and no two lock each
154
+ * other's keys in a cycle; then counts the keys' running runs again in a statement of its
155
+ * own, whose snapshot begins after the locks are held and so sees every lease a claim that
156
+ * held them before committed. A candidate another claimer has taken since is skipped.
157
+ *
158
+ * Plan: primary-key lookups on concurrency_slots under LockRows; Index Only Scans on
159
+ * tasks_running_keys for the counts; primary-key lookups for the candidates and the UPDATE.
160
+ */
161
+ async function leaseWithinLimits(sql, candidates, request) {
162
+ const keys = [...new Set(candidates.map((c) => c.key))];
163
+ return withTransaction(sql, async (tx) => {
164
+ await tx `
165
+ SELECT 1 FROM concurrency_slots WHERE key = ANY(${keys}::text[])
166
+ ORDER BY key FOR UPDATE`;
167
+ return tx `
168
+ WITH candidate AS (
169
+ SELECT * FROM unnest(${candidates.map((c) => c.id)}::bigint[],
170
+ ${candidates.map((c) => c.key)}::text[],
171
+ ${candidates.map((c) => c.place)}::int[]) AS c(id, key, place)
172
+ ),
173
+ room AS (
174
+ SELECT s.key, s.max_running - (
175
+ SELECT count(*) FROM tasks l
176
+ WHERE l.concurrency_key = s.key AND l.lease_owner IS NOT NULL) AS room
177
+ FROM concurrency_slots s
178
+ WHERE s.key = ANY(${keys}::text[])
179
+ ),
180
+ free AS (
181
+ SELECT t.id FROM tasks t
182
+ WHERE t.id = ANY(${candidates.map((c) => c.id)}::bigint[])
183
+ AND t.lease_owner IS NULL AND t.run_after <= now()
184
+ FOR UPDATE SKIP LOCKED
185
+ ),
186
+ allowed AS (
187
+ SELECT id, place FROM (
188
+ SELECT c.id, c.place, room.room,
189
+ row_number() OVER (PARTITION BY c.key ORDER BY c.place) AS nth
190
+ FROM candidate c JOIN free f ON f.id = c.id JOIN room ON room.key = c.key
191
+ ) ranked
192
+ WHERE nth <= room
193
+ ),
194
+ claimed AS (
195
+ UPDATE tasks t
196
+ SET lease_owner = ${request.owner},
197
+ lease_expires_at = now() + make_interval(secs => ${request.leaseMs / 1000}),
198
+ attempt = t.attempt + 1
199
+ WHERE t.id = ANY(ARRAY(SELECT id FROM allowed))
200
+ RETURNING t.id, t.run_id, t.tenant_id, t.workflow, t.attempt,
201
+ extract(epoch FROM now() - t.run_after)::float8 * 1000 AS waited_ms
202
+ )
203
+ SELECT c.id::text AS id, c.run_id AS "runId", c.tenant_id AS "tenantId", c.workflow,
204
+ c.attempt, c.waited_ms AS "waitedMs", a.place::int AS place
205
+ FROM claimed c JOIN allowed a ON a.id = c.id`;
206
+ });
207
+ }
208
+ function checkBatch(limit) {
209
+ if (!Number.isInteger(limit) || limit < 1 || limit > MAX_CLAIM_BATCH) {
210
+ throw new RangeError(`limit must be an integer from 1 to ${String(MAX_CLAIM_BATCH)}`);
211
+ }
212
+ }
213
+ /**
214
+ * Returns tasks whose lease has expired to the queue and counts the expiry. Safe to run
215
+ * from every engine at once: SKIP LOCKED gives each expired row to one reaper, and the
216
+ * locking read re-checks the expiry, so a heartbeat that committed first wins.
217
+ *
218
+ * With `maxExpiries`, a task whose expiry would reach it is left for failExhaustedLeases;
219
+ * without it (tests of the release itself) every expired lease is released. The cap is
220
+ * compared against the bare column (`lease_expiries < cap - 1`, not `lease_expiries + 1 <
221
+ * cap`) so the planner can use its statistics: written the other way, it guessed, switched
222
+ * to a bitmap scan of every expired lease plus a sort, and took 2-6x longer.
223
+ *
224
+ * Plan: Index Scan on tasks_leases in expiry order, stopping at the limit, then
225
+ * primary-key lookups. Returns the released ids.
226
+ */
227
+ export async function releaseExpiredLeases(sql, limit, maxExpiries) {
228
+ checkBatch(limit);
229
+ const cap = maxExpiries ?? null;
230
+ const rows = await sql `
231
+ UPDATE tasks t
232
+ SET lease_owner = NULL, lease_expires_at = NULL, lease_expiries = t.lease_expiries + 1
233
+ WHERE t.id = ANY(ARRAY(
234
+ SELECT id FROM tasks
235
+ WHERE lease_owner IS NOT NULL AND lease_expires_at <= now()
236
+ AND (${cap}::int IS NULL OR lease_expiries < ${cap}::int - 1)
237
+ ORDER BY lease_expires_at
238
+ LIMIT ${limit}
239
+ FOR UPDATE SKIP LOCKED
240
+ ))
241
+ RETURNING t.id::text AS id`;
242
+ return rows.map((row) => row.id);
243
+ }
244
+ /**
245
+ * The lease-expiry cap: a task whose lease expires for the `maxExpiries`-th time in a
246
+ * row without a step recorded is not returned to the queue. Its run moves to failed, in the
247
+ * same statement, so a step that kills every worker that runs it cannot loop forever.
248
+ * Concurrency is as for releaseExpiredLeases. Returns the failed run ids.
249
+ *
250
+ * Plan: Bitmap Index Scan on tasks_leases with the cap as a filter (few rows match, so the
251
+ * planner reads every expired lease and sorts the matches), primary-key deletes, then a
252
+ * nested loop of primary-key updates on runs.
253
+ */
254
+ export async function failExhaustedLeases(sql, limit, maxExpiries) {
255
+ checkBatch(limit);
256
+ const rows = await sql `
257
+ WITH exhausted AS (
258
+ DELETE FROM tasks t
259
+ WHERE t.id = ANY(ARRAY(
260
+ SELECT id FROM tasks
261
+ WHERE lease_owner IS NOT NULL AND lease_expires_at <= now()
262
+ AND lease_expiries >= ${maxExpiries}::int - 1
263
+ ORDER BY lease_expires_at
264
+ LIMIT ${limit}
265
+ FOR UPDATE SKIP LOCKED
266
+ ))
267
+ RETURNING t.run_id, t.lease_expiries + 1 AS expiries
268
+ )
269
+ UPDATE runs r
270
+ SET status = 'failed',
271
+ error = jsonb_build_object(
272
+ 'reason', 'lease_expired',
273
+ 'leaseExpiries', e.expiries,
274
+ 'message', 'the lease expired ' || e.expiries || ' times in a row without a step being recorded: the workers running it keep dying or stalling'),
275
+ updated_at = now()
276
+ FROM exhausted e
277
+ WHERE r.id = e.run_id AND r.status = ANY(${statusesThatCanBecome("failed")}::text[])
278
+ RETURNING r.id`;
279
+ return rows.map((row) => row.id);
280
+ }
281
+ /** Makes a run claimable now. The unique run_id keeps it to one task per run. */
282
+ export async function insertTask(tx, task) {
283
+ await tx `
284
+ INSERT INTO tasks (run_id, queue, tenant_id, workflow, concurrency_key)
285
+ VALUES (${task.runId}, ${task.queue}, ${task.tenantId}, ${task.workflow},
286
+ ${task.concurrencyKey ?? null})`;
287
+ }
288
+ /**
289
+ * Tasks queued or leased per queue: the queue depth gauge, and admission's total. A full
290
+ * scan is fine because tasks holds only active runs, and the queue depth loop runs it about
291
+ * once a second, not per request.
292
+ *
293
+ * Plan: Seq Scan on tasks with a HashAggregate by queue.
294
+ */
295
+ export async function countTasksByQueue(sql) {
296
+ const rows = await sql `
297
+ SELECT queue, count(*)::int AS count FROM tasks GROUP BY queue`;
298
+ return new Map(rows.map((row) => [row.queue, row.count]));
299
+ }
300
+ /**
301
+ * Tasks queued or leased per tenant, for admission once the queue is full. A full
302
+ * scan like countTasksByQueue, run only while the queue is full.
303
+ *
304
+ * Plan: Seq Scan on tasks with a HashAggregate by tenant.
305
+ */
306
+ export async function countTasksByTenant(sql) {
307
+ const rows = await sql `
308
+ SELECT tenant_id AS "tenantId", count(*)::int AS count FROM tasks GROUP BY tenant_id`;
309
+ return new Map(rows.map((row) => [row.tenantId, row.count]));
310
+ }
311
+ /**
312
+ * Deletes a task only while `owner` still holds its lease for `attempt`, and returns its
313
+ * run, queue and concurrency key; undefined means the lease was lost and nothing changed. This is the fencing
314
+ * check: a worker whose lease expired is refused even before the reaper notices, and
315
+ * a worker replaced by a newer claim no longer matches the attempt.
316
+ *
317
+ * Concurrent writers are safe without an explicit lock: a DELETE that waits on a row
318
+ * another transaction changed re-checks the WHERE clause against the committed row, so a
319
+ * racing reaper, claim or duplicate completion leaves this one with zero rows.
320
+ *
321
+ * Plan: primary-key lookup on tasks_pkey.
322
+ */
323
+ export async function deleteLeasedTask(tx, lease) {
324
+ const [row] = await tx `
325
+ DELETE FROM tasks
326
+ WHERE id = ${lease.taskId}::bigint
327
+ AND lease_owner = ${lease.owner}
328
+ AND attempt = ${lease.attempt}
329
+ AND lease_expires_at > now()
330
+ RETURNING run_id AS "runId", tenant_id AS "tenantId", workflow, queue,
331
+ concurrency_key AS "concurrencyKey"`;
332
+ return row;
333
+ }
334
+ /**
335
+ * Locks a task only while `owner` still holds its lease for `attempt`; undefined means the
336
+ * lease was lost. The same fencing as deleteLeasedTask, for changes that keep the task.
337
+ * The row lock serialises every other report, completion, claim and reaper for this task
338
+ * until the transaction ends.
339
+ *
340
+ * Plan: primary-key lookup on tasks_pkey.
341
+ */
342
+ export async function lockLeasedTask(tx, lease) {
343
+ const [row] = await tx `
344
+ SELECT run_id AS "runId", tenant_id AS "tenantId", queue, workflow,
345
+ concurrency_key AS "concurrencyKey", step_failures AS "stepFailures"
346
+ FROM tasks
347
+ WHERE id = ${lease.taskId}::bigint
348
+ AND lease_owner = ${lease.owner}
349
+ AND attempt = ${lease.attempt}
350
+ AND lease_expires_at > now()
351
+ FOR UPDATE`;
352
+ return row;
353
+ }
354
+ /**
355
+ * A step was recorded: the run made progress, so the counts that bound retries start over
356
+ * (a step's failures, and leases lost in a row), and the lease is renewed. Callers have
357
+ * fenced the lease.
358
+ */
359
+ export async function recordProgress(tx, taskId, leaseMs) {
360
+ await tx `
361
+ UPDATE tasks
362
+ SET lease_expires_at = now() + make_interval(secs => ${leaseMs / 1000}),
363
+ step_failures = 0, lease_expiries = 0
364
+ WHERE id = ${taskId}::bigint`;
365
+ }
366
+ /**
367
+ * Gives a held task back to the queue to run again after `delayMs`, recording how often
368
+ * its next step has failed. Callers have fenced the lease.
369
+ */
370
+ export async function rescheduleTask(tx, taskId, stepFailures, delayMs) {
371
+ await tx `
372
+ UPDATE tasks
373
+ SET lease_owner = NULL, lease_expires_at = NULL, step_failures = ${stepFailures},
374
+ run_after = now() + make_interval(secs => ${delayMs / 1000})
375
+ WHERE id = ${taskId}::bigint`;
376
+ }
377
+ /** Removes a held task whose run has ended. Callers have fenced the lease. */
378
+ export async function deleteTask(tx, taskId) {
379
+ await tx `DELETE FROM tasks WHERE id = ${taskId}::bigint`;
380
+ }
381
+ /**
382
+ * Deletes a run's task, leased or not, and returns its queue and concurrency key; undefined
383
+ * when the run has none. Waits for a claim, report or completion holding the row.
384
+ *
385
+ * Plan: Index Scan on tasks_run_id_unique.
386
+ */
387
+ export async function deleteRunTask(tx, runId) {
388
+ const [row] = await tx `
389
+ DELETE FROM tasks WHERE run_id = ${runId}
390
+ RETURNING queue, concurrency_key AS "concurrencyKey"`;
391
+ return row;
392
+ }
393
+ /**
394
+ * Renews every listed lease that `owner` still holds, in one statement, and returns the
395
+ * ids it renewed. An expired lease is not revived: the reaper or another worker may
396
+ * already have it.
397
+ *
398
+ * The rows are locked in id order first, as step-report batches lock theirs
399
+ * (lockLeasedTasks): a heartbeat renewing a worker's leases in another order deadlocked
400
+ * with those batches under load, each aborted only after Postgres's one-second deadlock
401
+ * timeout (found by the soak).
402
+ *
403
+ * Plan: Nested Loop over the unnested pairs with a primary-key lookup each, then a sort
404
+ * and LockRows; the UPDATE finds the locked rows by primary key.
405
+ */
406
+ export async function renewLeases(tx, owner, leases, leaseMs) {
407
+ if (leases.length === 0)
408
+ return [];
409
+ const rows = await tx `
410
+ WITH held AS (
411
+ SELECT t.id FROM tasks t
412
+ JOIN unnest(${leases.map((l) => l.taskId)}::bigint[], ${leases.map((l) => l.attempt)}::int[])
413
+ AS listed(id, attempt)
414
+ ON t.id = listed.id AND t.attempt = listed.attempt
415
+ WHERE t.lease_owner = ${owner} AND t.lease_expires_at > now()
416
+ ORDER BY t.id
417
+ FOR UPDATE OF t
418
+ )
419
+ UPDATE tasks t
420
+ SET lease_expires_at = now() + make_interval(secs => ${leaseMs / 1000})
421
+ FROM held
422
+ WHERE t.id = held.id
423
+ RETURNING t.id::text AS id`;
424
+ return rows.map((row) => row.id);
425
+ }
426
+ /**
427
+ * The batch form of lockLeasedTask: locks every task in `leases` that its owner still
428
+ * holds for its attempt, in id order (so two batches never wait on each other in a cycle),
429
+ * and returns them by task id. A lease missing from the result was lost. One statement for
430
+ * the whole batch.
431
+ *
432
+ * Plan: Nested Loop over the unnested leases with a primary-key lookup each, then LockRows.
433
+ */
434
+ export async function lockLeasedTasks(tx, leases) {
435
+ if (leases.length === 0)
436
+ return new Map();
437
+ const rows = await tx `
438
+ SELECT t.id::text AS "taskId", t.run_id AS "runId", t.tenant_id AS "tenantId", t.queue,
439
+ t.workflow, t.concurrency_key AS "concurrencyKey", t.step_failures AS "stepFailures"
440
+ FROM tasks t
441
+ JOIN unnest(${leases.map((l) => l.taskId)}::bigint[], ${leases.map((l) => l.owner)}::text[],
442
+ ${leases.map((l) => l.attempt)}::int[]) AS held(id, owner, attempt)
443
+ ON t.id = held.id AND t.lease_owner = held.owner AND t.attempt = held.attempt
444
+ WHERE t.lease_expires_at > now()
445
+ ORDER BY t.id
446
+ FOR UPDATE OF t`;
447
+ return new Map(rows.map((row) => [row.taskId, row]));
448
+ }
449
+ /**
450
+ * After a batch of step reports: renews each listed lease, and for the
451
+ * tasks that recorded a step also starts their retry counts over. Callers hold the locks.
452
+ */
453
+ export async function renewAfterReports(tx, progressed, unchanged, leaseMs) {
454
+ if (progressed.length === 0 && unchanged.length === 0)
455
+ return;
456
+ await tx `
457
+ UPDATE tasks
458
+ SET lease_expires_at = now() + make_interval(secs => ${leaseMs / 1000}),
459
+ step_failures = CASE WHEN id = ANY(${[...progressed]}::bigint[]) THEN 0 ELSE step_failures END,
460
+ lease_expiries = CASE WHEN id = ANY(${[...progressed]}::bigint[]) THEN 0 ELSE lease_expiries END
461
+ WHERE id = ANY(${[...progressed, ...unchanged]}::bigint[])`;
462
+ }
463
+ //# sourceMappingURL=tasks.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tasks.js","sourceRoot":"","sources":["../../src/store/tasks.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,yBAAyB,CAAC;AAEhE,OAAO,EAAE,eAAe,EA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AAM,KAAK,CAAC;QAAE,OAAO;IAC9D,MAAM,EAAE,CAAA;;2DAEiD,OAAO,GAAG,IAAI;6CAC5B,CAAC,GAAG,UAAU,CAAC;8CACd,CAAC,GAAG,UAAU,CAAC;qBACxC,CAAC,GAAG,UAAU,EAAE,GAAG,SAAS,CAAC,aAAa,CAAC;AAChE,CAAC"}
@@ -0,0 +1,23 @@
1
+ import { DatabaseUnavailableError, TransactionConflictError } from "../domain/errors.js";
2
+ import { isDatabaseUnavailable, isTransactionConflict } from "./errors.js";
3
+ /**
4
+ * The one way to change state: everything inside commits together or not at all. A lost
5
+ * connection becomes DatabaseUnavailableError, so callers can tell an outage, which is
6
+ * worth retrying, from a bug; a deadlock or serialization failure becomes the retryable
7
+ * TransactionConflictError. The transaction may have committed before the connection
8
+ * dropped; callers that retry rely on idempotency keys to make that safe.
9
+ */
10
+ export async function withTransaction(sql, work) {
11
+ try {
12
+ return await sql.begin(work);
13
+ }
14
+ catch (error) {
15
+ if (isDatabaseUnavailable(error))
16
+ throw new DatabaseUnavailableError({ cause: error });
17
+ // Rolled back to resolve a conflict: retryable, unlike a bug or a constraint violation.
18
+ if (isTransactionConflict(error))
19
+ throw new TransactionConflictError({ cause: error });
20
+ throw error;
21
+ }
22
+ }
23
+ //# sourceMappingURL=transaction.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transaction.js","sourceRoot":"","sources":["../../src/store/transaction.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,wBAAwB,EAAE,wBAAwB,EAAE,MAAM,qBAAqB,CAAC;AACzF,OAAO,EAAE,qBAAqB,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AAK3E;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,eAAe,CACnC,GAAQ,EACR,IAAwC;IAExC,IAAI,CAAC;QACH,OAAO,MAAM,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IAC/B,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,qBAAqB,CAAC,KAAK,CAAC;YAAE,MAAM,IAAI,wBAAwB,CAAC,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;QACvF,wFAAwF;QACxF,IAAI,qBAAqB,CAAC,KAAK,CAAC;YAAE,MAAM,IAAI,wBAAwB,CAAC,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;QACvF,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC"}
@@ -0,0 +1,75 @@
1
+ import { statusesThatCanBecome } from "../domain/run-status.js";
2
+ import { jsonb } from "./json.js";
3
+ /**
4
+ * Parks a run until `durationMs` from now on the database clock (invariant 7), so engines
5
+ * with skewed clocks agree on when it wakes. The primary key keeps one wait per run.
6
+ */
7
+ export async function insertSleep(tx, sleep) {
8
+ await tx `
9
+ INSERT INTO waits (run_id, seq, tenant_id, queue, workflow, kind, wake_at)
10
+ VALUES (${sleep.runId}, ${sleep.seq}, ${sleep.tenantId}, ${sleep.queue}, ${sleep.workflow},
11
+ 'sleep', now() + make_interval(secs => ${sleep.durationMs / 1000}))`;
12
+ }
13
+ /** Parks a run until a matching event arrives or the timeout passes on the database clock. */
14
+ export async function insertEventWait(tx, wait) {
15
+ await tx `
16
+ INSERT INTO waits (run_id, seq, tenant_id, queue, workflow, step_name, kind, wake_at,
17
+ event_name, match)
18
+ VALUES (${wait.runId}, ${wait.seq}, ${wait.tenantId}, ${wait.queue}, ${wait.workflow},
19
+ ${wait.stepName}, 'event', now() + make_interval(secs => ${wait.timeoutMs / 1000}),
20
+ ${wait.eventName}, ${jsonb(wait.match)}::text::jsonb)`;
21
+ }
22
+ /**
23
+ * Wakes parked runs whose time has come, in one statement: removes the wait, moves the run
24
+ * back to queued and gives it a new task, so a run is never left awake without a task or
25
+ * queued twice. A sleep simply ends; an event wait that reaches its timeout is recorded as
26
+ * its step with a null output, which ctx.waitForEvent returns on replay. Safe to run from
27
+ * every engine at once: SKIP LOCKED gives each due wait to one waker, and an event that
28
+ * ends the same wait first leaves nothing to delete. A run that is no longer parked
29
+ * (cancelled, later) loses its wait and gets no task. Returns the woken run ids.
30
+ *
31
+ * Plan: Index Scan on waits_wake in wake order, stopping at the limit, then primary-key
32
+ * deletes on waits, primary-key updates on runs and a hash join of the batches
33
+ *.
34
+ */
35
+ export async function wakeDueWaits(sql, limit) {
36
+ if (!Number.isInteger(limit) || limit < 1) {
37
+ throw new RangeError("limit must be a positive integer");
38
+ }
39
+ const rows = await sql `
40
+ WITH due AS (
41
+ DELETE FROM waits w
42
+ WHERE w.run_id = ANY(ARRAY(
43
+ SELECT run_id FROM waits
44
+ WHERE wake_at <= now()
45
+ ORDER BY wake_at
46
+ LIMIT ${limit}
47
+ FOR UPDATE SKIP LOCKED
48
+ ))
49
+ RETURNING w.run_id, w.seq, w.kind, w.step_name, w.tenant_id, w.queue, w.workflow
50
+ ),
51
+ requeued AS (
52
+ UPDATE runs r
53
+ SET status = 'queued', updated_at = now()
54
+ FROM due
55
+ WHERE r.id = due.run_id AND r.status = ANY(${statusesThatCanBecome("queued")}::text[])
56
+ RETURNING r.id, r.concurrency_key
57
+ ),
58
+ timed_out AS (
59
+ INSERT INTO steps (run_id, seq, name, kind, status, output, attempts, started_at, finished_at)
60
+ SELECT due.run_id, due.seq, due.step_name, 'wait_event', 'succeeded', 'null'::jsonb, 1,
61
+ now(), now()
62
+ FROM due JOIN requeued ON requeued.id = due.run_id
63
+ WHERE due.kind = 'event'
64
+ )
65
+ INSERT INTO tasks (run_id, queue, tenant_id, workflow, concurrency_key)
66
+ SELECT due.run_id, due.queue, due.tenant_id, due.workflow, requeued.concurrency_key
67
+ FROM due JOIN requeued ON requeued.id = due.run_id
68
+ RETURNING run_id AS "runId"`;
69
+ return rows.map((row) => row.runId);
70
+ }
71
+ /** Deletes a run's sleep or event wait, if it has one. Plan: primary-key lookup on waits. */
72
+ export async function deleteRunWait(tx, runId) {
73
+ await tx `DELETE FROM waits WHERE run_id = ${runId}`;
74
+ }
75
+ //# sourceMappingURL=waits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CAAC;IAC/B,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;AACtC,CAAC;AAED,6FAA6F;AAC7F,MAAM,CAAC,KAAK,UAAU,aAAa,CAAC,EAAa,EAAE,KAAa;IAC9D,MAAM,EAAE,CAAA,oCAAoC,KAAK,EAAE,CAAC;AACtD,CAAC"}
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Marks runs as followed live through this engine until `ttlMs` from now (on the database
3
+ * clock), adding or renewing one row per run. Plan: primary-key upserts.
4
+ */
5
+ export async function renewWatches(sql, engineId, runIds, ttlMs) {
6
+ if (runIds.length === 0)
7
+ return;
8
+ await sql `
9
+ INSERT INTO run_watches (run_id, engine_id, expires_at)
10
+ SELECT id, ${engineId}, now() + make_interval(secs => ${ttlMs / 1000})
11
+ FROM unnest(${[...runIds]}::uuid[]) AS id
12
+ ON CONFLICT (run_id, engine_id) DO UPDATE SET expires_at = excluded.expires_at`;
13
+ }
14
+ /** This engine no longer follows the run. Plan: primary-key delete. */
15
+ export async function removeWatch(sql, engineId, runId) {
16
+ await sql `DELETE FROM run_watches WHERE run_id = ${runId} AND engine_id = ${engineId}`;
17
+ }
18
+ /**
19
+ * Runs any engine follows now. Plan: Index Scan on run_watches_expiry; the table holds a
20
+ * row per followed run per engine, a few thousand at most.
21
+ */
22
+ export async function watchedRuns(sql) {
23
+ const rows = await sql `
24
+ SELECT DISTINCT run_id AS "runId" FROM run_watches WHERE expires_at > now()`;
25
+ return rows.map((row) => row.runId);
26
+ }
27
+ /** Removes watches that expired a minute ago or more: engines that died or lost their way. */
28
+ export async function deleteExpiredWatches(sql) {
29
+ await sql `DELETE FROM run_watches WHERE expires_at < now() - interval '1 minute'`;
30
+ }
31
+ //# sourceMappingURL=watches.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"watches.js","sourceRoot":"","sources":["../../src/store/watches.ts"],"names":[],"mappings":"AAEA;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,YAAY,CAChC,GAAc,EACd,QAAgB,EAChB,MAAyB,EACzB,KAAa;IAEb,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO;IAChC,MAAM,GAAG,CAAA;;iBAEM,QAAQ,mCAAmC,KAAK,GAAG,IAAI;kBACtD,CAAC,GAAG,MAAM,CAAC;mFACsD,CAAC;AACpF,CAAC;AAED,uEAAuE;AACvE,MAAM,CAAC,KAAK,UAAU,WAAW,CAAC,GAAc,EAAE,QAAgB,EAAE,KAAa;IAC/E,MAAM,GAAG,CAAA,0CAA0C,KAAK,oBAAoB,QAAQ,EAAE,CAAC;AACzF,CAAC;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,WAAW,CAAC,GAAc;IAC9C,MAAM,IAAI,GAAG,MAAM,GAAG,CAAqB;gFACmC,CAAC;IAC/E,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;AACtC,CAAC;AAED,8FAA8F;AAC9F,MAAM,CAAC,KAAK,UAAU,oBAAoB,CAAC,GAAc;IACvD,MAAM,GAAG,CAAA,wEAAwE,CAAC;AACpF,CAAC"}
@@ -0,0 +1,26 @@
1
+ import { createHash, timingSafeEqual } from "node:crypto";
2
+ import { Code, ConnectError } from "@connectrpc/connect";
3
+ const digest = (text) => createHash("sha256").update(text).digest();
4
+ /**
5
+ * Requires `authorization: Bearer <key>` on every call. Comparing fixed-length digests in
6
+ * constant time reveals neither the key's content nor its length through timing.
7
+ */
8
+ export function requireApiKey(apiKey) {
9
+ const authorized = bearerCheck(apiKey);
10
+ return (next) => (request) => {
11
+ if (!authorized(request.header.get("authorization") ?? undefined)) {
12
+ throw new ConnectError("missing or invalid API key", Code.Unauthenticated);
13
+ }
14
+ return next(request);
15
+ };
16
+ }
17
+ /** Whether an `authorization` header carries the key, compared as above. */
18
+ export function bearerCheck(apiKey) {
19
+ const expected = digest(apiKey);
20
+ return (header) => {
21
+ const value = header ?? "";
22
+ const presented = value.startsWith("Bearer ") ? value.slice("Bearer ".length) : "";
23
+ return timingSafeEqual(digest(presented), expected);
24
+ };
25
+ }
26
+ //# sourceMappingURL=auth.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.js","sourceRoot":"","sources":["../../src/transport/auth.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAC1D,OAAO,EAAE,IAAI,EAAE,YAAY,EAAoB,MAAM,qBAAqB,CAAC;AAE3E,MAAM,MAAM,GAAG,CAAC,IAAY,EAAU,EAAE,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,MAAM,EAAE,CAAC;AAEpF;;;GAGG;AACH,MAAM,UAAU,aAAa,CAAC,MAAc;IAC1C,MAAM,UAAU,GAAG,WAAW,CAAC,MAAM,CAAC,CAAC;IACvC,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,OAAO,EAAE,EAAE;QAC3B,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,eAAe,CAAC,IAAI,SAAS,CAAC,EAAE,CAAC;YAClE,MAAM,IAAI,YAAY,CAAC,4BAA4B,EAAE,IAAI,CAAC,eAAe,CAAC,CAAC;QAC7E,CAAC;QACD,OAAO,IAAI,CAAC,OAAO,CAAC,CAAC;IACvB,CAAC,CAAC;AACJ,CAAC;AAED,4EAA4E;AAC5E,MAAM,UAAU,WAAW,CAAC,MAAc;IACxC,MAAM,QAAQ,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC;IAChC,OAAO,CAAC,MAAM,EAAE,EAAE;QAChB,MAAM,KAAK,GAAG,MAAM,IAAI,EAAE,CAAC;QAC3B,MAAM,SAAS,GAAG,KAAK,CAAC,UAAU,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,KAAK,CA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