@nagi-js/postgres 0.1.1-rc.21 → 0.1.1-rc.23

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.
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { sql } from 'kysely';
2
- import { NagiConcurrencyConflictError, projectRunState, decideSignal, DEFAULT_SWEEP_LIMIT, decideExpiredLeaseAction, decideTimeout, rowDeltaOf, factEffects, clampQueryLimit, decodeRunCursor, encodeRunCursor } from '@nagi-js/core';
2
+ import { InMemoryRunEventHub, InMemoryStreamHub, isStreamOver, NagiConcurrencyConflictError, supersede, projectRunState, decideSignal, DEFAULT_SWEEP_LIMIT, decideExpiredLeaseAction, decideTimeout, isRunEnd, admitsRunEnd, factConsequences } from '@nagi-js/core';
3
3
 
4
4
  // src/migrations.ts
5
5
  var migrations = [
@@ -168,38 +168,97 @@ var migrations = [
168
168
  WHERE completed_at IS NOT NULL
169
169
  AND status IN ('completed','failed','canceled');
170
170
  `
171
+ },
172
+ {
173
+ id: "0008_canceled_by_run_id_fk",
174
+ sql: (schema) => `
175
+ UPDATE ${schema}.workflow_run w
176
+ SET canceled_by_run_id = NULL
177
+ WHERE w.canceled_by_run_id IS NOT NULL
178
+ AND NOT EXISTS (
179
+ SELECT 1 FROM ${schema}.workflow_run s
180
+ WHERE s.run_id = w.canceled_by_run_id
181
+ );
182
+
183
+ CREATE INDEX IF NOT EXISTS workflow_run_canceled_by_idx
184
+ ON ${schema}.workflow_run (canceled_by_run_id)
185
+ WHERE canceled_by_run_id IS NOT NULL;
186
+
187
+ ALTER TABLE ${schema}.workflow_run
188
+ DROP CONSTRAINT IF EXISTS workflow_run_canceled_by_fk;
189
+ ALTER TABLE ${schema}.workflow_run
190
+ ADD CONSTRAINT workflow_run_canceled_by_fk
191
+ FOREIGN KEY (canceled_by_run_id)
192
+ REFERENCES ${schema}.workflow_run(run_id)
193
+ ON DELETE SET NULL;
194
+ `
195
+ },
196
+ {
197
+ // step_run becomes one row per step (its latest attempt), updated in place.
198
+ // Of the per-attempt rows, a settled one wins, then the highest attempt —
199
+ // what the fold would have made of the same facts.
200
+ id: "0009_step_run_per_step",
201
+ sql: (schema) => `
202
+ DELETE FROM ${schema}.step_run s
203
+ USING (
204
+ SELECT run_id, step_id, attempt,
205
+ row_number() OVER (
206
+ PARTITION BY run_id, step_id
207
+ ORDER BY (status IN ('completed','failed','canceled','skipped')) DESC,
208
+ attempt DESC
209
+ ) AS rn
210
+ FROM ${schema}.step_run
211
+ ) ranked
212
+ WHERE s.run_id = ranked.run_id
213
+ AND s.step_id = ranked.step_id
214
+ AND s.attempt = ranked.attempt
215
+ AND ranked.rn > 1;
216
+
217
+ ALTER TABLE ${schema}.step_run DROP CONSTRAINT IF EXISTS step_run_pkey;
218
+ ALTER TABLE ${schema}.step_run ADD CONSTRAINT step_run_pkey
219
+ PRIMARY KEY (run_id, step_id);
220
+ DROP INDEX IF EXISTS ${schema}.step_run_lookup_idx;
221
+ `
171
222
  }
172
223
  ];
173
224
  async function migrate(db, opts = {}) {
174
225
  const schema = opts.schema ?? "nagi";
175
226
  assertValidSchema(schema);
176
- const applied = [];
177
- const skipped = [];
178
- await sql.raw(
179
- `CREATE SCHEMA IF NOT EXISTS ${schema};
180
- CREATE TABLE IF NOT EXISTS ${schema}.schema_migrations (
181
- id text PRIMARY KEY,
182
- applied_at timestamptz NOT NULL DEFAULT now()
183
- );`
184
- ).execute(db);
185
- for (const m of migrations) {
186
- await db.transaction().execute(async (tx) => {
187
- const existing = await sql`
188
- SELECT id FROM ${sql.raw(`${schema}.schema_migrations`)}
189
- WHERE id = ${m.id}
190
- `.execute(tx);
191
- if (existing.rows.length > 0) {
192
- skipped.push(m.id);
193
- return;
227
+ return db.connection().execute(async (conn) => {
228
+ const key = `nagi:migrate:${schema}`;
229
+ await sql`SELECT pg_advisory_lock(hashtext(${key}))`.execute(conn);
230
+ try {
231
+ const applied = [];
232
+ const skipped = [];
233
+ await sql.raw(
234
+ `CREATE SCHEMA IF NOT EXISTS ${schema};
235
+ CREATE TABLE IF NOT EXISTS ${schema}.schema_migrations (
236
+ id text PRIMARY KEY,
237
+ applied_at timestamptz NOT NULL DEFAULT now()
238
+ );`
239
+ ).execute(conn);
240
+ for (const m of migrations) {
241
+ await conn.transaction().execute(async (tx) => {
242
+ const existing = await sql`
243
+ SELECT id FROM ${sql.raw(`${schema}.schema_migrations`)}
244
+ WHERE id = ${m.id}
245
+ `.execute(tx);
246
+ if (existing.rows.length > 0) {
247
+ skipped.push(m.id);
248
+ return;
249
+ }
250
+ await sql.raw(m.sql(schema)).execute(tx);
251
+ await sql`
252
+ INSERT INTO ${sql.raw(`${schema}.schema_migrations`)} (id) VALUES (${m.id})
253
+ `.execute(tx);
254
+ applied.push(m.id);
255
+ });
194
256
  }
195
- await sql.raw(m.sql(schema)).execute(tx);
196
- await sql`
197
- INSERT INTO ${sql.raw(`${schema}.schema_migrations`)} (id) VALUES (${m.id})
198
- `.execute(tx);
199
- applied.push(m.id);
200
- });
201
- }
202
- return { applied, skipped };
257
+ return { applied, skipped };
258
+ } finally {
259
+ await sql`SELECT pg_advisory_unlock(hashtext(${key}))`.execute(conn);
260
+ }
261
+ });
203
262
  }
204
263
  function assertValidSchema(schema) {
205
264
  if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(schema)) {
@@ -209,6 +268,40 @@ function assertValidSchema(schema) {
209
268
  }
210
269
  }
211
270
 
271
+ // src/stream.ts
272
+ var MAX_CHUNK_BYTES = 7e3;
273
+ function encodeFrame(frame) {
274
+ return JSON.stringify(frame);
275
+ }
276
+ function decodeFrame(payload) {
277
+ try {
278
+ const parsed = JSON.parse(payload);
279
+ if (parsed === null || typeof parsed !== "object") return null;
280
+ return typeof parsed.k === "string" ? parsed : null;
281
+ } catch {
282
+ return null;
283
+ }
284
+ }
285
+ function applyFrame(hub, frame) {
286
+ switch (frame.k) {
287
+ case "chunk":
288
+ hub.publishChunk(frame.r, frame.s, frame.c);
289
+ return;
290
+ case "retry":
291
+ hub.signalRetry(frame.r, frame.s, frame.a);
292
+ return;
293
+ case "ok":
294
+ hub.closeOk(frame.r, frame.s);
295
+ return;
296
+ case "err":
297
+ hub.closeError(frame.r, frame.s, frame.e);
298
+ return;
299
+ case "run":
300
+ hub.closeRun(frame.r);
301
+ return;
302
+ }
303
+ }
304
+
212
305
  // src/uuidv7.ts
213
306
  var HEX = "0123456789abcdef";
214
307
  function toHex(bytes) {
@@ -220,9 +313,24 @@ function toHex(bytes) {
220
313
  }
221
314
  return out;
222
315
  }
316
+ var COUNTER_MAX = 4095;
317
+ var COUNTER_SEED_MAX = 2048;
318
+ var lastMs = -1;
319
+ var counter = 0;
320
+ function seedCounter() {
321
+ const b = new Uint8Array(2);
322
+ crypto.getRandomValues(b);
323
+ return (b[0] << 8 | b[1]) % COUNTER_SEED_MAX;
324
+ }
223
325
  function uuidv7(now = Date.now()) {
224
326
  const bytes = new Uint8Array(16);
225
327
  const ts = Math.floor(now);
328
+ if (ts === lastMs) {
329
+ if (counter < COUNTER_MAX) counter += 1;
330
+ } else {
331
+ lastMs = ts;
332
+ counter = seedCounter();
333
+ }
226
334
  const hi = Math.floor(ts / 4294967296);
227
335
  const lo = ts >>> 0;
228
336
  bytes[0] = hi >>> 8 & 255;
@@ -231,12 +339,13 @@ function uuidv7(now = Date.now()) {
231
339
  bytes[3] = lo >>> 16 & 255;
232
340
  bytes[4] = lo >>> 8 & 255;
233
341
  bytes[5] = lo & 255;
234
- const rand = new Uint8Array(10);
342
+ const rand = new Uint8Array(8);
235
343
  crypto.getRandomValues(rand);
236
- for (let i = 0; i < 10; i++) {
237
- bytes[6 + i] = rand[i];
344
+ for (let i = 0; i < 8; i++) {
345
+ bytes[8 + i] = rand[i];
238
346
  }
239
- bytes[6] = bytes[6] & 15 | 112;
347
+ bytes[6] = 112 | counter >>> 8 & 15;
348
+ bytes[7] = counter & 255;
240
349
  bytes[8] = bytes[8] & 63 | 128;
241
350
  const hex = toHex(bytes);
242
351
  return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
@@ -245,6 +354,7 @@ function uuidv7(now = Date.now()) {
245
354
  // src/store.ts
246
355
  var DEFAULT_LEASE_MS = 6e4;
247
356
  var SCHEMA_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
357
+ var NOT_STARTED = { started: false, canceled: [] };
248
358
  function postgresStore(opts) {
249
359
  return new PostgresStore(opts);
250
360
  }
@@ -253,6 +363,19 @@ var PostgresStore = class {
253
363
  schema;
254
364
  leaseMs;
255
365
  notifyChannel;
366
+ streamChannel;
367
+ eventChannel;
368
+ eventHub;
369
+ // Both channels ride one LISTEN connection. Until it is live NOTIFY delivers
370
+ // nothing here — it never queues for a connection that is not yet listening —
371
+ // so chunks and events published before then are gone, not delayed. Total
372
+ // rather than optional: with no listener there is simply nothing to wait for.
373
+ listening;
374
+ // Left UNASSIGNED when no listener is supplied: under
375
+ // exactOptionalPropertyTypes an absent property and one set to undefined are
376
+ // different things, and Store declares `stream?`.
377
+ stream;
378
+ events;
256
379
  constructor(opts) {
257
380
  if (!SCHEMA_RE.test(opts.schema ?? "nagi")) {
258
381
  throw new Error(
@@ -263,166 +386,221 @@ var PostgresStore = class {
263
386
  this.schema = opts.schema ?? "nagi";
264
387
  this.leaseMs = opts.leaseMs ?? DEFAULT_LEASE_MS;
265
388
  this.notifyChannel = opts.notifyChannel;
389
+ this.streamChannel = `${this.schema}_stream`;
390
+ this.eventChannel = `${this.schema}_events`;
391
+ let listening = Promise.resolve();
392
+ if (opts.listener !== void 0) {
393
+ const eventHub = new InMemoryRunEventHub();
394
+ this.eventHub = eventHub;
395
+ this.events = {
396
+ watchRun: (runId, handler) => eventHub.watchRun(runId, handler),
397
+ watchRuns: (handler) => eventHub.watchRuns(handler)
398
+ };
399
+ const eventsListening = opts.listener.listen(
400
+ this.eventChannel,
401
+ (payload) => {
402
+ const envelope = decodeEnvelope(payload);
403
+ if (envelope !== null) eventHub.publish(envelope);
404
+ }
405
+ );
406
+ const hub = new InMemoryStreamHub();
407
+ const streamListening = opts.listener.listen(
408
+ this.streamChannel,
409
+ (payload) => {
410
+ const frame = decodeFrame(payload);
411
+ if (frame !== null) applyFrame(hub, frame);
412
+ }
413
+ );
414
+ this.stream = this.makeStreamTransport(hub);
415
+ listening = Promise.all([eventsListening, streamListening]).then(
416
+ () => void 0
417
+ );
418
+ }
419
+ this.listening = listening;
420
+ void this.listening.catch(() => void 0);
421
+ }
422
+ // Resolves once this process is actually receiving NOTIFY on both channels.
423
+ ready() {
424
+ return this.listening;
425
+ }
426
+ makeStreamTransport(hub) {
427
+ return {
428
+ subscribeStream: (runId, stepId, opts) => {
429
+ const live = hub.subscribeStream(runId, stepId, opts);
430
+ void (async () => {
431
+ try {
432
+ await this.listening;
433
+ if (isStreamOver(await this.loadRunState(runId), stepId)) {
434
+ hub.closeOk(runId, stepId);
435
+ }
436
+ } catch {
437
+ }
438
+ })();
439
+ return live;
440
+ },
441
+ publishChunk: (runId, stepId, chunk) => {
442
+ const frame = encodeFrame({
443
+ k: "chunk",
444
+ r: runId,
445
+ s: stepId,
446
+ c: chunk
447
+ });
448
+ const size = byteLength(frame);
449
+ if (size > MAX_CHUNK_BYTES) {
450
+ throw new Error(
451
+ `@nagi-js/postgres: streaming chunk for step "${stepId}" is ${size} bytes, over the ${MAX_CHUNK_BYTES}-byte NOTIFY limit. Emit smaller chunks, or carry the payload elsewhere and emit a reference.`
452
+ );
453
+ }
454
+ this.notifyStream(`${runId}::${stepId}`, frame);
455
+ }
456
+ };
457
+ }
458
+ // Chunk order is the whole point of a token stream, and `db` is a POOL: two
459
+ // un-awaited pg_notify calls can take different connections and arrive
460
+ // reversed. So publishes for one step are chained — each waits for the
461
+ // previous — while different steps stay independent. The chain is still
462
+ // fire-and-forget to the caller, per the StreamTransport contract.
463
+ publishTails = /* @__PURE__ */ new Map();
464
+ // Waits for in-flight chunk publishes: one step's chain, or every chain of a
465
+ // run when the whole run is closing.
466
+ async drainPublishes(runId, stepId) {
467
+ if (stepId !== void 0) {
468
+ await this.publishTails.get(`${runId}::${stepId}`);
469
+ return;
470
+ }
471
+ const prefix = `${runId}::`;
472
+ await Promise.all(
473
+ [...this.publishTails.entries()].filter(([k]) => k.startsWith(prefix)).map(([, tail]) => tail)
474
+ );
475
+ }
476
+ notifyStream(key, frame) {
477
+ const prev = this.publishTails.get(key) ?? Promise.resolve();
478
+ const next = prev.then(async () => {
479
+ await sql`SELECT pg_notify(${this.streamChannel}, ${frame})`.execute(
480
+ this.db
481
+ );
482
+ }).catch(() => {
483
+ }).finally(() => {
484
+ if (this.publishTails.get(key) === next) this.publishTails.delete(key);
485
+ });
486
+ this.publishTails.set(key, next);
266
487
  }
267
488
  t(table) {
268
489
  return `${this.schema}.${table}`;
269
490
  }
270
491
  async appendFact(runId, fact) {
271
492
  await this.db.transaction().execute(async (trx) => {
272
- await this.persistFact(trx, runId, fact);
273
- await this.applyFactEffects(trx, runId, fact);
493
+ await this.writeFact(trx, runId, fact);
274
494
  });
275
- await this.maybeNotify(runId);
495
+ }
496
+ async endRun(runId, fact) {
497
+ return this.db.transaction().execute((trx) => this.writeFact(trx, runId, fact));
276
498
  }
277
499
  async tryStartRun(runId, fact, concurrency) {
278
- if (concurrency === void 0) {
279
- const started = await this.db.transaction().execute(async (trx) => {
280
- const insert = await sql`
281
- INSERT INTO ${sql.raw(this.t("workflow_run"))}
282
- (run_id, flow_id, status, input, started_at, flow_hash, code_version, parent_run_id, parent_step_id)
283
- VALUES
284
- (${runId}, ${fact.flowId}, 'running', ${jsonb(fact.input)}, ${fact.at}, ${fact.flowHash ?? null}, ${fact.codeVersion ?? null}, ${fact.parent?.runId ?? null}, ${fact.parent?.stepId ?? null})
285
- ON CONFLICT (run_id) DO NOTHING
286
- RETURNING run_id
287
- `.execute(trx);
288
- if (insert.rows.length === 0) {
289
- return false;
290
- }
291
- await this.insertFact(trx, runId, fact);
292
- return true;
293
- });
294
- if (started) {
295
- await this.maybeNotify(runId);
296
- }
297
- return { started, canceled: [] };
298
- }
299
- const result = await this.db.transaction().execute(async (trx) => {
300
- const lockText = `nagi:concurrency:${fact.flowId}:${concurrency.key}`;
301
- await sql`SELECT pg_advisory_xact_lock(hashtext(${lockText}))`.execute(
302
- trx
303
- );
304
- const existing = await sql`
305
- SELECT run_id FROM ${sql.raw(this.t("workflow_run"))}
306
- WHERE run_id = ${runId}
307
- LIMIT 1
308
- `.execute(trx);
309
- if (existing.rows.length > 0) {
310
- return {
311
- started: false,
312
- canceled: []
313
- };
314
- }
315
- const others = await sql`
316
- SELECT run_id FROM ${sql.raw(this.t("workflow_run"))}
317
- WHERE flow_id = ${fact.flowId}
318
- AND concurrency_key = ${concurrency.key}
319
- AND status IN ('pending', 'running')
320
- FOR UPDATE
321
- `.execute(trx);
322
- const canceled = [];
323
- for (const row of others.rows) {
324
- const priorRunId = row.run_id;
325
- const cancelFact = {
326
- kind: "flow.canceled",
327
- cause: "concurrency",
328
- runId: priorRunId,
329
- at: fact.at,
330
- canceledByRunId: runId,
331
- concurrencyKey: concurrency.key
332
- };
333
- await this.persistFact(trx, priorRunId, cancelFact);
334
- canceled.push({ runId: priorRunId, fact: cancelFact });
500
+ return this.db.transaction().execute(async (trx) => {
501
+ if (concurrency !== void 0) {
502
+ const lockText = `nagi:concurrency:${fact.flowId}:${concurrency.key}`;
503
+ await sql`SELECT pg_advisory_xact_lock(hashtext(${lockText}))`.execute(
504
+ trx
505
+ );
335
506
  }
336
- await sql`
337
- INSERT INTO ${sql.raw(this.t("workflow_run"))}
338
- (run_id, flow_id, status, input, started_at, flow_hash, code_version, concurrency_key, parent_run_id, parent_step_id)
339
- VALUES
340
- (${runId}, ${fact.flowId}, 'running', ${jsonb(fact.input)}, ${fact.at}, ${fact.flowHash ?? null}, ${fact.codeVersion ?? null}, ${concurrency.key}, ${fact.parent?.runId ?? null}, ${fact.parent?.stepId ?? null})
341
- `.execute(trx);
342
- await this.insertFact(trx, runId, fact);
343
- return { started: true, canceled };
507
+ return this.startRetrying(trx, runId, fact, concurrency);
344
508
  });
345
- if (result.started) {
346
- await this.maybeNotify(runId);
347
- for (const c of result.canceled) {
348
- await this.maybeNotify(c.runId);
349
- }
350
- }
351
- return result;
352
509
  }
510
+ // D6=A: no advisory lock under shared tx — the partial unique index on
511
+ // (flow_id, concurrency_key) WHERE status IN ('pending','running') is the
512
+ // load-bearing invariant.
353
513
  async tryStartRunOnTx(tx, runId, fact, concurrency) {
354
- const trx = tx;
514
+ return this.startRetrying(
515
+ tx,
516
+ runId,
517
+ fact,
518
+ concurrency
519
+ );
520
+ }
521
+ // A start racing one that holds no advisory lock (the OnTx path) can lose to
522
+ // the partial unique index; it is retried once, and a second loss surfaces
523
+ // NagiConcurrencyConflictError. A failed statement aborts the whole tx, so
524
+ // each attempt runs under a savepoint the failure rolls back to: the retry
525
+ // runs, and a caller's tx stays usable, with no half-applied cancels.
526
+ async startRetrying(trx, runId, fact, concurrency) {
355
527
  if (concurrency === void 0) {
356
- const insert = await sql`
357
- INSERT INTO ${sql.raw(this.t("workflow_run"))}
358
- (run_id, flow_id, status, input, started_at, flow_hash, code_version, parent_run_id, parent_step_id)
359
- VALUES
360
- (${runId}, ${fact.flowId}, 'running', ${jsonb(fact.input)}, ${fact.at}, ${fact.flowHash ?? null}, ${fact.codeVersion ?? null}, ${fact.parent?.runId ?? null}, ${fact.parent?.stepId ?? null})
361
- ON CONFLICT (run_id) DO NOTHING
362
- RETURNING run_id
363
- `.execute(trx);
364
- if (insert.rows.length === 0) {
365
- return { started: false, canceled: [] };
366
- }
367
- await this.insertFact(trx, runId, fact);
368
- return { started: true, canceled: [] };
528
+ return this.startIn(trx, runId, fact, void 0);
369
529
  }
370
- let attemptedRetry = false;
371
- for (; ; ) {
372
- const existing = await sql`
373
- SELECT run_id FROM ${sql.raw(this.t("workflow_run"))}
374
- WHERE run_id = ${runId}
375
- LIMIT 1
376
- `.execute(trx);
377
- if (existing.rows.length > 0) {
378
- return { started: false, canceled: [] };
379
- }
380
- const others = await sql`
381
- SELECT run_id FROM ${sql.raw(this.t("workflow_run"))}
382
- WHERE flow_id = ${fact.flowId}
383
- AND concurrency_key = ${concurrency.key}
384
- AND status IN ('pending', 'running')
385
- FOR UPDATE
386
- `.execute(trx);
387
- const canceled = [];
388
- for (const row of others.rows) {
389
- const priorRunId = row.run_id;
390
- const cancelFact = {
391
- kind: "flow.canceled",
392
- cause: "concurrency",
393
- runId: priorRunId,
394
- at: fact.at,
395
- canceledByRunId: runId,
396
- concurrencyKey: concurrency.key
397
- };
398
- await this.persistFact(trx, priorRunId, cancelFact);
399
- canceled.push({ runId: priorRunId, fact: cancelFact });
400
- }
530
+ for (let retried = false; ; retried = true) {
531
+ await sql`SAVEPOINT nagi_start_run`.execute(trx);
401
532
  try {
402
- await sql`
403
- INSERT INTO ${sql.raw(this.t("workflow_run"))}
404
- (run_id, flow_id, status, input, started_at, flow_hash, code_version, concurrency_key, parent_run_id, parent_step_id)
405
- VALUES
406
- (${runId}, ${fact.flowId}, 'running', ${jsonb(fact.input)}, ${fact.at}, ${fact.flowHash ?? null}, ${fact.codeVersion ?? null}, ${concurrency.key}, ${fact.parent?.runId ?? null}, ${fact.parent?.stepId ?? null})
407
- `.execute(trx);
533
+ const started = await this.startIn(trx, runId, fact, concurrency);
534
+ await sql`RELEASE SAVEPOINT nagi_start_run`.execute(trx);
535
+ return started;
408
536
  } catch (err) {
409
- if (isUniqueViolation(err) && !attemptedRetry) {
410
- attemptedRetry = true;
411
- continue;
412
- }
413
- if (isUniqueViolation(err)) {
537
+ await sql`ROLLBACK TO SAVEPOINT nagi_start_run`.execute(trx);
538
+ if (!isUniqueViolation(err)) throw err;
539
+ if (retried) {
414
540
  throw new NagiConcurrencyConflictError({
415
541
  runId,
416
542
  flowId: fact.flowId,
417
543
  concurrencyKey: concurrency.key
418
544
  });
419
545
  }
420
- throw err;
421
546
  }
422
- await this.insertFact(trx, runId, fact);
423
- return { started: true, canceled };
424
547
  }
425
548
  }
549
+ async startIn(trx, runId, fact, concurrency) {
550
+ if (concurrency === void 0) {
551
+ if (!await this.insertRun(trx, runId, fact, null)) return NOT_STARTED;
552
+ await this.writeFact(trx, runId, fact);
553
+ return { started: true, canceled: [] };
554
+ }
555
+ const existing = await sql`
556
+ SELECT run_id FROM ${sql.raw(this.t("workflow_run"))}
557
+ WHERE run_id = ${runId}
558
+ LIMIT 1
559
+ `.execute(trx);
560
+ if (existing.rows.length > 0) return NOT_STARTED;
561
+ const priors = await sql`
562
+ SELECT run_id FROM ${sql.raw(this.t("workflow_run"))}
563
+ WHERE flow_id = ${fact.flowId}
564
+ AND concurrency_key = ${concurrency.key}
565
+ AND status IN ('pending', 'running')
566
+ FOR UPDATE
567
+ `.execute(trx);
568
+ const canceled = [];
569
+ for (const c of supersede({
570
+ start: fact,
571
+ concurrency,
572
+ priors: priors.rows.map((r) => r.run_id)
573
+ })) {
574
+ if (await this.writeFact(trx, c.runId, c.fact)) canceled.push(c);
575
+ }
576
+ if (!await this.insertRun(trx, runId, fact, concurrency.key)) {
577
+ throw new NagiConcurrencyConflictError({
578
+ runId,
579
+ flowId: fact.flowId,
580
+ concurrencyKey: concurrency.key
581
+ });
582
+ }
583
+ await this.writeFact(trx, runId, fact);
584
+ await this.linkSuperseder(
585
+ trx,
586
+ runId,
587
+ canceled.map((c) => c.runId)
588
+ );
589
+ return { started: true, canceled };
590
+ }
591
+ // The only workflow_run INSERT: the start paths claim the runId here, before
592
+ // the flow.started fact whose row delta this already is.
593
+ async insertRun(trx, runId, fact, concurrencyKey) {
594
+ const insert = await sql`
595
+ INSERT INTO ${sql.raw(this.t("workflow_run"))}
596
+ (run_id, flow_id, status, input, started_at, flow_hash, code_version, concurrency_key, parent_run_id, parent_step_id)
597
+ VALUES
598
+ (${runId}, ${fact.flowId}, 'running', ${jsonb(fact.input)}, ${fact.at}, ${fact.flowHash ?? null}, ${fact.codeVersion ?? null}, ${concurrencyKey}, ${fact.parent?.runId ?? null}, ${fact.parent?.stepId ?? null})
599
+ ON CONFLICT (run_id) DO NOTHING
600
+ RETURNING run_id
601
+ `.execute(trx);
602
+ return insert.rows.length > 0;
603
+ }
426
604
  async loadRunState(runId) {
427
605
  return this.loadRunStateWith(this.db, runId);
428
606
  }
@@ -440,7 +618,7 @@ var PostgresStore = class {
440
618
  }
441
619
  async settleSignal(args) {
442
620
  const { runId, stepId, at, incoming } = args;
443
- const result = await this.db.transaction().execute(async (trx) => {
621
+ return this.db.transaction().execute(async (trx) => {
444
622
  const lockText = `nagi:signal:${runId}`;
445
623
  await sql`SELECT pg_advisory_xact_lock(hashtext(${lockText}))`.execute(
446
624
  trx
@@ -452,17 +630,14 @@ var PostgresStore = class {
452
630
  return decision.result;
453
631
  case "buffer":
454
632
  if (decision.fact !== null)
455
- await this.insertFact(trx, runId, decision.fact);
633
+ await this.writeFact(trx, runId, decision.fact);
456
634
  return decision.result;
457
635
  case "deliver":
458
- await this.persistFact(trx, runId, decision.received);
459
- await this.persistFact(trx, runId, decision.completed);
460
- await this.applyFactEffects(trx, runId, decision.completed);
636
+ await this.writeFact(trx, runId, decision.received);
637
+ await this.writeFact(trx, runId, decision.completed);
461
638
  return decision.result;
462
639
  }
463
640
  });
464
- await this.maybeNotify(runId);
465
- return result;
466
641
  }
467
642
  async claimStep(runId, stepId, attempt) {
468
643
  const token = `lease-${crypto.randomUUID()}`;
@@ -500,7 +675,6 @@ var PostgresStore = class {
500
675
  LEFT JOIN ${sql.raw(this.t("step_run"))} s
501
676
  ON s.run_id = l.run_id
502
677
  AND s.step_id = l.step_id
503
- AND s.attempt = l.attempt
504
678
  LEFT JOIN ${sql.raw(this.t("workflow_run"))} r
505
679
  ON r.run_id = l.run_id
506
680
  WHERE l.expires_at < ${now}
@@ -522,20 +696,7 @@ var PostgresStore = class {
522
696
  now
523
697
  });
524
698
  if (decision.tag === "skip") continue;
525
- await sql`
526
- DELETE FROM ${sql.raw(this.t("lease"))}
527
- WHERE run_id = ${runId} AND step_id = ${stepId} AND attempt = ${attempt}
528
- `.execute(trx);
529
- const fact = {
530
- kind: "lease.reaped",
531
- runId,
532
- stepId,
533
- attempt,
534
- at: now,
535
- reapedAt: now,
536
- reason: "expired"
537
- };
538
- await this.insertFact(trx, runId, fact);
699
+ await this.writeFact(trx, runId, decision.fact);
539
700
  await txQueue.enqueue(runId, stepId, {
540
701
  attempt: decision.nextAttempt,
541
702
  delayMs: decision.backoffMs,
@@ -580,8 +741,7 @@ var PostgresStore = class {
580
741
  const decision = decideTimeout({ runState, stepId, fireAt, at: now });
581
742
  await this.deleteTimer(trx, runId, stepId);
582
743
  if (decision.kind === "noop") return false;
583
- await this.persistFact(trx, runId, decision.fact);
584
- await this.applyFactEffects(trx, runId, decision.fact);
744
+ await this.writeFact(trx, runId, decision.fact);
585
745
  return decision.attempt;
586
746
  });
587
747
  if (failed !== false) {
@@ -590,13 +750,6 @@ var PostgresStore = class {
590
750
  }
591
751
  return timedOut;
592
752
  }
593
- async settleStep(runId, _stepId, fact) {
594
- await this.db.transaction().execute(async (trx) => {
595
- await this.persistFact(trx, runId, fact);
596
- await this.applyFactEffects(trx, runId, fact);
597
- });
598
- await this.maybeNotify(runId);
599
- }
600
753
  async recordOnce(runId, stepId, scope, value) {
601
754
  await sql`
602
755
  INSERT INTO ${sql.raw(this.t("dedupe"))} (run_id, step_id, scope, value)
@@ -610,28 +763,69 @@ var PostgresStore = class {
610
763
  FROM ${sql.raw(this.t("dedupe"))}
611
764
  WHERE run_id = ${runId} AND step_id = ${stepId} AND scope = ${scope}
612
765
  `.execute(this.db);
613
- return r.rows[0]?.value ?? null;
766
+ const row = r.rows[0];
767
+ return row === void 0 ? { tag: "miss" } : { tag: "hit", value: row.value };
614
768
  }
615
769
  async runStep(runId, _stepId, _attempt, body) {
616
- const output = await this.db.transaction().execute(async (trx) => {
770
+ return this.db.transaction().execute(async (trx) => {
617
771
  const result = await body(trx);
618
- await this.persistFact(trx, runId, result.fact);
619
- await this.applyFactEffects(trx, runId, result.fact);
772
+ await this.writeFact(trx, runId, result.fact);
620
773
  return result.output;
621
774
  });
622
- await this.maybeNotify(runId);
623
- return output;
624
775
  }
625
- async insertFact(trx, runId, fact) {
776
+ // The one fact-write path: every consequence core declares for the fact
777
+ // lands on `trx` with it. NOTIFYs ride the same tx, and PostgreSQL holds them
778
+ // until commit, so an observer hears only about durable facts and a
779
+ // rolled-back write — including one on a caller's tx — announces nothing.
780
+ async writeFact(trx, runId, fact) {
781
+ if (isRunEnd(fact)) {
782
+ const run = await sql`
783
+ SELECT status FROM ${sql.raw(this.t("workflow_run"))}
784
+ WHERE run_id = ${runId}
785
+ FOR UPDATE
786
+ `.execute(trx);
787
+ if (!admitsRunEnd(run.rows[0]?.status)) return false;
788
+ }
626
789
  await sql`
627
790
  INSERT INTO ${sql.raw(this.t("fact"))} (run_id, fact_id, kind, at, payload)
628
791
  VALUES (${runId}, ${uuidv7()}, ${fact.kind}, ${fact.at}, ${jsonb(serializeFactPayload(fact))})
629
792
  `.execute(trx);
793
+ const { rows, release, stream, event } = factConsequences(fact);
794
+ if (rows !== null) await this.applyRowDelta(trx, runId, rows);
795
+ if (release !== null) await this.applyRelease(trx, runId, release);
796
+ if (stream !== null) await this.notifyStreamEffect(trx, runId, stream);
797
+ if (event !== null && this.eventHub !== void 0) {
798
+ const payload = JSON.stringify({ ...event, runId });
799
+ await sql`SELECT pg_notify(${this.eventChannel}, ${payload})`.execute(
800
+ trx
801
+ );
802
+ }
803
+ if (this.notifyChannel !== void 0) {
804
+ await sql`SELECT pg_notify(${this.notifyChannel}, ${runId})`.execute(trx);
805
+ }
806
+ return true;
630
807
  }
631
- async persistFact(trx, runId, fact) {
632
- await this.insertFact(trx, runId, fact);
633
- const delta = rowDeltaOf(fact);
634
- if (delta !== null) await this.applyRowDelta(trx, runId, delta);
808
+ // Victims are canceled BEFORE the superseder row exists: the partial unique
809
+ // index on (flow_id, concurrency_key) only frees the slot once they leave
810
+ // 'pending'/'running'. Their reference is therefore resolved here, after the
811
+ // insert, rather than by the cancel write that cannot yet name it.
812
+ async linkSuperseder(trx, runId, priors) {
813
+ if (priors.length === 0) return;
814
+ await sql`
815
+ UPDATE ${sql.raw(this.t("workflow_run"))}
816
+ SET canceled_by_run_id = ${runId}
817
+ WHERE run_id = ANY(${priors}::text[])
818
+ `.execute(trx);
819
+ }
820
+ async notifyStreamEffect(trx, runId, effect) {
821
+ if (this.stream === void 0) return;
822
+ await this.drainPublishes(
823
+ runId,
824
+ effect.tag === "close-run" ? void 0 : effect.stepId
825
+ );
826
+ await sql`SELECT pg_notify(${this.streamChannel}, ${encodeFrame(frameOf(runId, effect))})`.execute(
827
+ trx
828
+ );
635
829
  }
636
830
  applyRowDelta(trx, runId, delta) {
637
831
  switch (delta.row) {
@@ -639,90 +833,93 @@ var PostgresStore = class {
639
833
  return this.applyRunDelta(trx, runId, delta);
640
834
  case "step":
641
835
  return this.applyStepDelta(trx, runId, delta);
642
- case "once":
643
- return this.insertOnce(trx, runId, delta);
644
836
  }
645
837
  }
646
838
  async applyRunDelta(trx, runId, delta) {
647
839
  switch (delta.status) {
648
840
  case "running":
649
- await sql`
650
- INSERT INTO ${sql.raw(this.t("workflow_run"))}
651
- (run_id, flow_id, status, input, started_at, flow_hash, code_version, parent_run_id, parent_step_id)
652
- VALUES
653
- (${runId}, ${delta.flowId}, 'running', ${jsonb(delta.input)}, ${delta.startedAt}, ${delta.flowHash}, ${delta.codeVersion}, ${delta.parent?.runId ?? null}, ${delta.parent?.stepId ?? null})
654
- ON CONFLICT (run_id) DO NOTHING
655
- `.execute(trx);
656
841
  return;
657
842
  case "completed":
658
843
  await sql`
659
844
  UPDATE ${sql.raw(this.t("workflow_run"))}
660
- SET status = 'completed', output = ${jsonb(delta.output)}, completed_at = ${delta.completedAt}
845
+ SET status = 'completed', output = ${jsonb(delta.output)}, error = NULL, completed_at = ${delta.completedAt}
661
846
  WHERE run_id = ${runId}
662
847
  `.execute(trx);
663
848
  return;
664
849
  case "failed":
665
850
  await sql`
666
851
  UPDATE ${sql.raw(this.t("workflow_run"))}
667
- SET status = 'failed', error = ${jsonb(delta.error)}, completed_at = ${delta.completedAt}
852
+ SET status = 'failed', output = NULL, error = ${jsonb(delta.error)}, completed_at = ${delta.completedAt}
668
853
  WHERE run_id = ${runId}
669
854
  `.execute(trx);
670
855
  return;
671
856
  case "canceled":
672
857
  await sql`
673
858
  UPDATE ${sql.raw(this.t("workflow_run"))}
674
- SET status = 'canceled',
675
- canceled_by_run_id = ${delta.canceledByRunId},
859
+ SET status = 'canceled', output = NULL, error = NULL,
860
+ canceled_by_run_id = (
861
+ SELECT s.run_id FROM ${sql.raw(this.t("workflow_run"))} s
862
+ WHERE s.run_id = ${delta.canceledByRunId}
863
+ ),
676
864
  completed_at = ${delta.completedAt}
677
865
  WHERE run_id = ${runId}
678
866
  `.execute(trx);
679
867
  return;
680
868
  }
681
869
  }
870
+ // Mirrors nextStepRow (@nagi-js/core read-model): one row per step, a
871
+ // settled row changes only by reset, a start applies only for a newer
872
+ // attempt, and a retry only to the attempt in flight.
682
873
  async applyStepDelta(trx, runId, delta) {
683
874
  switch (delta.status) {
684
875
  case "running":
685
876
  await sql`
686
- INSERT INTO ${sql.raw(this.t("step_run"))} (run_id, step_id, attempt, status, started_at)
877
+ INSERT INTO ${sql.raw(this.t("step_run"))} AS s (run_id, step_id, attempt, status, started_at)
687
878
  VALUES (${runId}, ${delta.stepId}, ${delta.attempt}, 'running', ${delta.startedAt})
688
- ON CONFLICT (run_id, step_id, attempt) DO UPDATE
689
- SET status = 'running', started_at = EXCLUDED.started_at
879
+ ON CONFLICT (run_id, step_id) DO UPDATE
880
+ SET attempt = EXCLUDED.attempt, status = 'running', started_at = EXCLUDED.started_at,
881
+ completed_at = NULL, output = NULL, error = NULL
882
+ WHERE s.status NOT IN ${SETTLED_STEP} AND s.attempt < EXCLUDED.attempt
883
+ `.execute(trx);
884
+ return;
885
+ case "backoff":
886
+ await sql`
887
+ UPDATE ${sql.raw(this.t("step_run"))}
888
+ SET error = ${jsonb(delta.error)}
889
+ WHERE run_id = ${runId} AND step_id = ${delta.stepId}
890
+ AND status NOT IN ${SETTLED_STEP} AND error IS NULL
891
+ AND attempt = ${delta.attempt}
690
892
  `.execute(trx);
691
893
  return;
692
894
  case "completed":
693
- await this.upsertStepCompleted(
895
+ return this.settleStepRow(
694
896
  trx,
695
897
  runId,
696
- delta.stepId,
898
+ delta,
697
899
  delta.attempt,
698
- delta.output
900
+ delta.output,
901
+ null
699
902
  );
700
- return;
701
903
  case "failed":
702
- await this.upsertStepFailed(
904
+ return this.settleStepRow(
703
905
  trx,
704
906
  runId,
705
- delta.stepId,
907
+ delta,
706
908
  delta.attempt,
909
+ null,
707
910
  delta.error
708
911
  );
709
- return;
710
912
  case "canceled":
711
- await this.upsertStepCanceled(
913
+ return this.settleStepRow(
712
914
  trx,
713
915
  runId,
714
- delta.stepId,
916
+ delta,
715
917
  delta.attempt,
716
- delta.error ?? void 0
918
+ null,
919
+ delta.error
717
920
  );
718
- return;
719
921
  case "skipped":
720
- await sql`
721
- INSERT INTO ${sql.raw(this.t("step_run"))} (run_id, step_id, attempt, status)
722
- VALUES (${runId}, ${delta.stepId}, 0, 'skipped')
723
- ON CONFLICT (run_id, step_id, attempt) DO UPDATE SET status = 'skipped'
724
- `.execute(trx);
725
- return;
922
+ return this.settleStepRow(trx, runId, delta, null, null, null);
726
923
  case "reset": {
727
924
  const row = await sql`
728
925
  SELECT flow_id, concurrency_key FROM ${sql.raw(this.t("workflow_run"))}
@@ -750,48 +947,20 @@ var PostgresStore = class {
750
947
  }
751
948
  }
752
949
  }
753
- async insertOnce(trx, runId, delta) {
754
- await sql`
755
- INSERT INTO ${sql.raw(this.t("dedupe"))} (run_id, step_id, scope, value)
756
- VALUES (${runId}, ${delta.stepId}, ${delta.scope}, ${jsonb(delta.value)})
757
- ON CONFLICT (run_id, step_id, scope) DO NOTHING
758
- `.execute(trx);
759
- }
760
- async upsertStepCompleted(trx, runId, stepId, attempt, output) {
950
+ // `attempt` null keeps the row's attempt (0 when there is none): a skip
951
+ // records no attempt of its own.
952
+ async settleStepRow(trx, runId, delta, attempt, output, error) {
953
+ const outputJson = output === null ? null : jsonb(output);
954
+ const errorJson = error === null ? null : jsonb(error);
761
955
  await sql`
762
- INSERT INTO ${sql.raw(this.t("step_run"))}
763
- (run_id, step_id, attempt, status, output, started_at, completed_at)
956
+ INSERT INTO ${sql.raw(this.t("step_run"))} AS s
957
+ (run_id, step_id, attempt, status, output, error, completed_at)
764
958
  VALUES
765
- (${runId}, ${stepId}, ${attempt}, 'completed', ${jsonb(output)}, now(), now())
766
- ON CONFLICT (run_id, step_id, attempt) DO UPDATE
767
- SET status = 'completed', output = EXCLUDED.output, completed_at = now()
768
- `.execute(trx);
769
- }
770
- async upsertStepFailed(trx, runId, stepId, attempt, error) {
771
- await sql`
772
- INSERT INTO ${sql.raw(this.t("step_run"))}
773
- (run_id, step_id, attempt, status, error, started_at, completed_at)
774
- VALUES
775
- (${runId}, ${stepId}, ${attempt}, 'failed', ${jsonb(error)}, now(), now())
776
- ON CONFLICT (run_id, step_id, attempt) DO UPDATE
777
- SET status = 'failed', error = EXCLUDED.error, completed_at = now()
778
- `.execute(trx);
779
- }
780
- async upsertStepCanceled(trx, runId, stepId, attempt, error) {
781
- const errorJson = error === void 0 ? null : jsonb(error);
782
- await sql`
783
- INSERT INTO ${sql.raw(this.t("step_run"))}
784
- (run_id, step_id, attempt, status, error, started_at, completed_at)
785
- VALUES
786
- (${runId}, ${stepId}, ${attempt}, 'canceled', ${errorJson}, now(), now())
787
- ON CONFLICT (run_id, step_id, attempt) DO UPDATE
788
- SET status = 'canceled', error = EXCLUDED.error, completed_at = now()
789
- `.execute(trx);
790
- }
791
- async deleteLease(trx, runId, stepId) {
792
- await sql`
793
- DELETE FROM ${sql.raw(this.t("lease"))}
794
- WHERE run_id = ${runId} AND step_id = ${stepId}
959
+ (${runId}, ${delta.stepId}, COALESCE(${attempt}::int, 0), ${delta.status}, ${outputJson}, ${errorJson}, ${delta.completedAt})
960
+ ON CONFLICT (run_id, step_id) DO UPDATE
961
+ SET attempt = COALESCE(${attempt}::int, s.attempt), status = EXCLUDED.status,
962
+ output = EXCLUDED.output, error = EXCLUDED.error, completed_at = EXCLUDED.completed_at
963
+ WHERE s.status NOT IN ${SETTLED_STEP}
795
964
  `.execute(trx);
796
965
  }
797
966
  async deleteTimer(trx, runId, stepId) {
@@ -800,20 +969,24 @@ var PostgresStore = class {
800
969
  WHERE run_id = ${runId} AND step_id = ${stepId}
801
970
  `.execute(trx);
802
971
  }
803
- // The adapter's whole share of the release table: lease / timer rows. The
804
- // concurrency slot needs no write — the partial unique index keys on status,
805
- // which the materializer already set.
806
- async applyFactEffects(trx, runId, fact) {
807
- const effects = factEffects(fact);
808
- if (effects.tag !== "release-step") return;
809
- await this.deleteLease(trx, runId, effects.stepId);
810
- if (effects.timer) await this.deleteTimer(trx, runId, effects.stepId);
811
- }
812
- async maybeNotify(runId) {
813
- if (!this.notifyChannel) return;
814
- await sql`SELECT pg_notify(${this.notifyChannel}, ${runId})`.execute(
815
- this.db
816
- );
972
+ async applyRelease(trx, runId, release) {
973
+ switch (release.tag) {
974
+ case "release-step":
975
+ await sql`
976
+ DELETE FROM ${sql.raw(this.t("lease"))}
977
+ WHERE run_id = ${runId} AND step_id = ${release.stepId}
978
+ `.execute(trx);
979
+ if (release.timer) await this.deleteTimer(trx, runId, release.stepId);
980
+ return;
981
+ case "release-lease":
982
+ await sql`
983
+ DELETE FROM ${sql.raw(this.t("lease"))}
984
+ WHERE run_id = ${runId} AND step_id = ${release.stepId} AND attempt = ${release.attempt}
985
+ `.execute(trx);
986
+ return;
987
+ case "release-run":
988
+ return;
989
+ }
817
990
  }
818
991
  async upsertSnapshot(args) {
819
992
  await sql`
@@ -853,46 +1026,6 @@ var PostgresStore = class {
853
1026
  VALUES (${uuidv7()}, ${fact.kind}, ${fact.at}, ${jsonb(serializeGlobalFactPayload(fact))})
854
1027
  `.execute(this.db);
855
1028
  }
856
- async queryRuns(opts) {
857
- const where = opts.where ?? {};
858
- const flowId = where.flowId;
859
- const statuses = where.status ? Array.from(where.status) : void 0;
860
- const inputJson = where.input === void 0 ? null : JSON.stringify(where.input);
861
- const isLatest = opts.latest === true;
862
- const limit = isLatest ? 1 : clampQueryLimit(opts.limit);
863
- const cursor = !isLatest && opts.cursor !== void 0 ? decodeRunCursor(opts.cursor) : null;
864
- const fetchLimit = isLatest ? 1 : limit + 1;
865
- const rows = await sql`
866
- SELECT run_id, flow_id, status, input, started_at, completed_at
867
- FROM ${sql.raw(this.t("workflow_run"))}
868
- WHERE (${flowId ?? null}::text IS NULL OR flow_id = ${flowId ?? null})
869
- AND (${statuses === void 0 ? null : statuses}::text[] IS NULL
870
- OR status = ANY(${statuses === void 0 ? null : statuses}::text[]))
871
- AND (${inputJson}::jsonb IS NULL OR input @> ${inputJson}::jsonb)
872
- AND (${cursor === null ? null : cursor.startedAt}::timestamptz IS NULL
873
- OR (started_at, run_id) <
874
- (${cursor === null ? null : cursor.startedAt}::timestamptz,
875
- ${cursor === null ? null : cursor.runId}::text))
876
- ORDER BY started_at DESC, run_id DESC
877
- LIMIT ${fetchLimit}
878
- `.execute(this.db);
879
- const summaries = rows.rows.map((r) => ({
880
- runId: r.run_id,
881
- flowId: r.flow_id,
882
- status: r.status,
883
- startedAt: r.started_at instanceof Date ? r.started_at : new Date(r.started_at),
884
- completedAt: r.completed_at === null ? null : r.completed_at instanceof Date ? r.completed_at : new Date(r.completed_at),
885
- input: r.input
886
- }));
887
- if (isLatest) {
888
- return { runs: summaries.slice(0, 1), cursor: null };
889
- }
890
- const hasMore = summaries.length > limit;
891
- const page = hasMore ? summaries.slice(0, limit) : summaries;
892
- const last = page[page.length - 1];
893
- const nextCursor = hasMore && last !== void 0 ? encodeRunCursor({ startedAt: last.startedAt, runId: last.runId }) : null;
894
- return { runs: page, cursor: nextCursor };
895
- }
896
1029
  async describe(runId) {
897
1030
  return this.db.transaction().execute(async (trx) => {
898
1031
  const runRows = await sql`
@@ -1050,6 +1183,7 @@ function reviveFact(kind, at, payload) {
1050
1183
  ...body
1051
1184
  };
1052
1185
  }
1186
+ var SETTLED_STEP = sql.raw("('completed', 'failed', 'canceled', 'skipped')");
1053
1187
  function jsonb(value) {
1054
1188
  return sql`${JSON.stringify(value)}::jsonb`;
1055
1189
  }
@@ -1064,7 +1198,31 @@ function isUniqueViolation(err) {
1064
1198
  }
1065
1199
  return false;
1066
1200
  }
1201
+ function frameOf(runId, effect) {
1202
+ switch (effect.tag) {
1203
+ case "close-ok":
1204
+ return { k: "ok", r: runId, s: effect.stepId };
1205
+ case "close-error":
1206
+ return { k: "err", r: runId, s: effect.stepId, e: effect.error };
1207
+ case "retry":
1208
+ return { k: "retry", r: runId, s: effect.stepId, a: effect.nextAttempt };
1209
+ case "close-run":
1210
+ return { k: "run", r: runId };
1211
+ }
1212
+ }
1213
+ function byteLength(s) {
1214
+ return new TextEncoder().encode(s).length;
1215
+ }
1216
+ function decodeEnvelope(payload) {
1217
+ try {
1218
+ const parsed = JSON.parse(payload);
1219
+ if (parsed === null || typeof parsed !== "object") return null;
1220
+ return typeof parsed.type === "string" && typeof parsed.runId === "string" ? parsed : null;
1221
+ } catch {
1222
+ return null;
1223
+ }
1224
+ }
1067
1225
 
1068
- export { migrate, migrations, postgresStore, uuidv7 };
1226
+ export { MAX_CHUNK_BYTES, migrate, migrations, postgresStore, uuidv7 };
1069
1227
  //# sourceMappingURL=index.js.map
1070
1228
  //# sourceMappingURL=index.js.map