@nagi-js/postgres 0.1.1-rc.22 → 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 { InMemoryRunEventHub, InMemoryStreamHub, stepStatusOf, stepStateOf, isTerminalRun, NagiConcurrencyConflictError, projectRunState, decideSignal, DEFAULT_SWEEP_LIMIT, decideExpiredLeaseAction, decideTimeout, rowDeltaOf, runEventOf, 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 = [
@@ -192,38 +192,73 @@ var migrations = [
192
192
  REFERENCES ${schema}.workflow_run(run_id)
193
193
  ON DELETE SET NULL;
194
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
+ `
195
222
  }
196
223
  ];
197
224
  async function migrate(db, opts = {}) {
198
225
  const schema = opts.schema ?? "nagi";
199
226
  assertValidSchema(schema);
200
- const applied = [];
201
- const skipped = [];
202
- await sql.raw(
203
- `CREATE SCHEMA IF NOT EXISTS ${schema};
204
- CREATE TABLE IF NOT EXISTS ${schema}.schema_migrations (
205
- id text PRIMARY KEY,
206
- applied_at timestamptz NOT NULL DEFAULT now()
207
- );`
208
- ).execute(db);
209
- for (const m of migrations) {
210
- await db.transaction().execute(async (tx) => {
211
- const existing = await sql`
212
- SELECT id FROM ${sql.raw(`${schema}.schema_migrations`)}
213
- WHERE id = ${m.id}
214
- `.execute(tx);
215
- if (existing.rows.length > 0) {
216
- skipped.push(m.id);
217
- 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
+ });
218
256
  }
219
- await sql.raw(m.sql(schema)).execute(tx);
220
- await sql`
221
- INSERT INTO ${sql.raw(`${schema}.schema_migrations`)} (id) VALUES (${m.id})
222
- `.execute(tx);
223
- applied.push(m.id);
224
- });
225
- }
226
- return { applied, skipped };
257
+ return { applied, skipped };
258
+ } finally {
259
+ await sql`SELECT pg_advisory_unlock(hashtext(${key}))`.execute(conn);
260
+ }
261
+ });
227
262
  }
228
263
  function assertValidSchema(schema) {
229
264
  if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(schema)) {
@@ -319,6 +354,7 @@ function uuidv7(now = Date.now()) {
319
354
  // src/store.ts
320
355
  var DEFAULT_LEASE_MS = 6e4;
321
356
  var SCHEMA_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
357
+ var NOT_STARTED = { started: false, canceled: [] };
322
358
  function postgresStore(opts) {
323
359
  return new PostgresStore(opts);
324
360
  }
@@ -394,9 +430,7 @@ var PostgresStore = class {
394
430
  void (async () => {
395
431
  try {
396
432
  await this.listening;
397
- const state = await this.loadRunState(runId);
398
- const status = stepStatusOf(stepStateOf(state, stepId));
399
- if (isTerminalRun(state) || status === "completed" || status === "failed" || status === "canceled" || status === "skipped") {
433
+ if (isStreamOver(await this.loadRunState(runId), stepId)) {
400
434
  hub.closeOk(runId, stepId);
401
435
  }
402
436
  } catch {
@@ -456,171 +490,116 @@ var PostgresStore = class {
456
490
  }
457
491
  async appendFact(runId, fact) {
458
492
  await this.db.transaction().execute(async (trx) => {
459
- await this.persistFact(trx, runId, fact);
460
- await this.applyFactEffects(trx, runId, fact);
493
+ await this.writeFact(trx, runId, fact);
461
494
  });
462
- await this.maybeNotify(runId);
495
+ }
496
+ async endRun(runId, fact) {
497
+ return this.db.transaction().execute((trx) => this.writeFact(trx, runId, fact));
463
498
  }
464
499
  async tryStartRun(runId, fact, concurrency) {
465
- if (concurrency === void 0) {
466
- const started = await this.db.transaction().execute(async (trx) => {
467
- const insert = await sql`
468
- INSERT INTO ${sql.raw(this.t("workflow_run"))}
469
- (run_id, flow_id, status, input, started_at, flow_hash, code_version, parent_run_id, parent_step_id)
470
- VALUES
471
- (${runId}, ${fact.flowId}, 'running', ${jsonb(fact.input)}, ${fact.at}, ${fact.flowHash ?? null}, ${fact.codeVersion ?? null}, ${fact.parent?.runId ?? null}, ${fact.parent?.stepId ?? null})
472
- ON CONFLICT (run_id) DO NOTHING
473
- RETURNING run_id
474
- `.execute(trx);
475
- if (insert.rows.length === 0) {
476
- return false;
477
- }
478
- await this.insertFact(trx, runId, fact);
479
- await this.notifyRunEvent(trx, runId, fact);
480
- return true;
481
- });
482
- if (started) {
483
- await this.maybeNotify(runId);
484
- }
485
- return { started, canceled: [] };
486
- }
487
- const result = await this.db.transaction().execute(async (trx) => {
488
- const lockText = `nagi:concurrency:${fact.flowId}:${concurrency.key}`;
489
- await sql`SELECT pg_advisory_xact_lock(hashtext(${lockText}))`.execute(
490
- trx
491
- );
492
- const existing = await sql`
493
- SELECT run_id FROM ${sql.raw(this.t("workflow_run"))}
494
- WHERE run_id = ${runId}
495
- LIMIT 1
496
- `.execute(trx);
497
- if (existing.rows.length > 0) {
498
- return {
499
- started: false,
500
- canceled: []
501
- };
502
- }
503
- const others = await sql`
504
- SELECT run_id FROM ${sql.raw(this.t("workflow_run"))}
505
- WHERE flow_id = ${fact.flowId}
506
- AND concurrency_key = ${concurrency.key}
507
- AND status IN ('pending', 'running')
508
- FOR UPDATE
509
- `.execute(trx);
510
- const canceled = [];
511
- for (const row of others.rows) {
512
- const priorRunId = row.run_id;
513
- const cancelFact = {
514
- kind: "flow.canceled",
515
- cause: "concurrency",
516
- runId: priorRunId,
517
- at: fact.at,
518
- canceledByRunId: runId,
519
- concurrencyKey: concurrency.key
520
- };
521
- await this.persistFact(trx, priorRunId, cancelFact);
522
- 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
+ );
523
506
  }
524
- await sql`
525
- INSERT INTO ${sql.raw(this.t("workflow_run"))}
526
- (run_id, flow_id, status, input, started_at, flow_hash, code_version, concurrency_key, parent_run_id, parent_step_id)
527
- VALUES
528
- (${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})
529
- `.execute(trx);
530
- await this.insertFact(trx, runId, fact);
531
- await this.notifyRunEvent(trx, runId, fact);
532
- await this.linkSuperseder(
533
- trx,
534
- runId,
535
- canceled.map((c) => c.runId)
536
- );
537
- return { started: true, canceled };
507
+ return this.startRetrying(trx, runId, fact, concurrency);
538
508
  });
539
- if (result.started) {
540
- await this.maybeNotify(runId);
541
- for (const c of result.canceled) {
542
- await this.maybeNotify(c.runId);
543
- }
544
- }
545
- return result;
546
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.
547
513
  async tryStartRunOnTx(tx, runId, fact, concurrency) {
548
- 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) {
549
527
  if (concurrency === void 0) {
550
- const insert = await sql`
551
- INSERT INTO ${sql.raw(this.t("workflow_run"))}
552
- (run_id, flow_id, status, input, started_at, flow_hash, code_version, parent_run_id, parent_step_id)
553
- VALUES
554
- (${runId}, ${fact.flowId}, 'running', ${jsonb(fact.input)}, ${fact.at}, ${fact.flowHash ?? null}, ${fact.codeVersion ?? null}, ${fact.parent?.runId ?? null}, ${fact.parent?.stepId ?? null})
555
- ON CONFLICT (run_id) DO NOTHING
556
- RETURNING run_id
557
- `.execute(trx);
558
- if (insert.rows.length === 0) {
559
- return { started: false, canceled: [] };
560
- }
561
- await this.insertFact(trx, runId, fact);
562
- return { started: true, canceled: [] };
528
+ return this.startIn(trx, runId, fact, void 0);
563
529
  }
564
- let attemptedRetry = false;
565
- for (; ; ) {
566
- const existing = await sql`
567
- SELECT run_id FROM ${sql.raw(this.t("workflow_run"))}
568
- WHERE run_id = ${runId}
569
- LIMIT 1
570
- `.execute(trx);
571
- if (existing.rows.length > 0) {
572
- return { started: false, canceled: [] };
573
- }
574
- const others = await sql`
575
- SELECT run_id FROM ${sql.raw(this.t("workflow_run"))}
576
- WHERE flow_id = ${fact.flowId}
577
- AND concurrency_key = ${concurrency.key}
578
- AND status IN ('pending', 'running')
579
- FOR UPDATE
580
- `.execute(trx);
581
- const canceled = [];
582
- for (const row of others.rows) {
583
- const priorRunId = row.run_id;
584
- const cancelFact = {
585
- kind: "flow.canceled",
586
- cause: "concurrency",
587
- runId: priorRunId,
588
- at: fact.at,
589
- canceledByRunId: runId,
590
- concurrencyKey: concurrency.key
591
- };
592
- await this.persistFact(trx, priorRunId, cancelFact);
593
- canceled.push({ runId: priorRunId, fact: cancelFact });
594
- }
530
+ for (let retried = false; ; retried = true) {
531
+ await sql`SAVEPOINT nagi_start_run`.execute(trx);
595
532
  try {
596
- await sql`
597
- INSERT INTO ${sql.raw(this.t("workflow_run"))}
598
- (run_id, flow_id, status, input, started_at, flow_hash, code_version, concurrency_key, parent_run_id, parent_step_id)
599
- VALUES
600
- (${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})
601
- `.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;
602
536
  } catch (err) {
603
- if (isUniqueViolation(err) && !attemptedRetry) {
604
- attemptedRetry = true;
605
- continue;
606
- }
607
- if (isUniqueViolation(err)) {
537
+ await sql`ROLLBACK TO SAVEPOINT nagi_start_run`.execute(trx);
538
+ if (!isUniqueViolation(err)) throw err;
539
+ if (retried) {
608
540
  throw new NagiConcurrencyConflictError({
609
541
  runId,
610
542
  flowId: fact.flowId,
611
543
  concurrencyKey: concurrency.key
612
544
  });
613
545
  }
614
- throw err;
615
546
  }
616
- await this.insertFact(trx, runId, fact);
617
- await this.linkSuperseder(
618
- trx,
547
+ }
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({
619
578
  runId,
620
- canceled.map((c) => c.runId)
621
- );
622
- return { started: true, canceled };
579
+ flowId: fact.flowId,
580
+ concurrencyKey: concurrency.key
581
+ });
623
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;
624
603
  }
625
604
  async loadRunState(runId) {
626
605
  return this.loadRunStateWith(this.db, runId);
@@ -639,7 +618,7 @@ var PostgresStore = class {
639
618
  }
640
619
  async settleSignal(args) {
641
620
  const { runId, stepId, at, incoming } = args;
642
- const result = await this.db.transaction().execute(async (trx) => {
621
+ return this.db.transaction().execute(async (trx) => {
643
622
  const lockText = `nagi:signal:${runId}`;
644
623
  await sql`SELECT pg_advisory_xact_lock(hashtext(${lockText}))`.execute(
645
624
  trx
@@ -651,17 +630,14 @@ var PostgresStore = class {
651
630
  return decision.result;
652
631
  case "buffer":
653
632
  if (decision.fact !== null)
654
- await this.insertFact(trx, runId, decision.fact);
633
+ await this.writeFact(trx, runId, decision.fact);
655
634
  return decision.result;
656
635
  case "deliver":
657
- await this.persistFact(trx, runId, decision.received);
658
- await this.persistFact(trx, runId, decision.completed);
659
- await this.applyFactEffects(trx, runId, decision.completed);
636
+ await this.writeFact(trx, runId, decision.received);
637
+ await this.writeFact(trx, runId, decision.completed);
660
638
  return decision.result;
661
639
  }
662
640
  });
663
- await this.maybeNotify(runId);
664
- return result;
665
641
  }
666
642
  async claimStep(runId, stepId, attempt) {
667
643
  const token = `lease-${crypto.randomUUID()}`;
@@ -699,7 +675,6 @@ var PostgresStore = class {
699
675
  LEFT JOIN ${sql.raw(this.t("step_run"))} s
700
676
  ON s.run_id = l.run_id
701
677
  AND s.step_id = l.step_id
702
- AND s.attempt = l.attempt
703
678
  LEFT JOIN ${sql.raw(this.t("workflow_run"))} r
704
679
  ON r.run_id = l.run_id
705
680
  WHERE l.expires_at < ${now}
@@ -721,20 +696,7 @@ var PostgresStore = class {
721
696
  now
722
697
  });
723
698
  if (decision.tag === "skip") continue;
724
- await sql`
725
- DELETE FROM ${sql.raw(this.t("lease"))}
726
- WHERE run_id = ${runId} AND step_id = ${stepId} AND attempt = ${attempt}
727
- `.execute(trx);
728
- const fact = {
729
- kind: "lease.reaped",
730
- runId,
731
- stepId,
732
- attempt,
733
- at: now,
734
- reapedAt: now,
735
- reason: "expired"
736
- };
737
- await this.insertFact(trx, runId, fact);
699
+ await this.writeFact(trx, runId, decision.fact);
738
700
  await txQueue.enqueue(runId, stepId, {
739
701
  attempt: decision.nextAttempt,
740
702
  delayMs: decision.backoffMs,
@@ -779,8 +741,7 @@ var PostgresStore = class {
779
741
  const decision = decideTimeout({ runState, stepId, fireAt, at: now });
780
742
  await this.deleteTimer(trx, runId, stepId);
781
743
  if (decision.kind === "noop") return false;
782
- await this.persistFact(trx, runId, decision.fact);
783
- await this.applyFactEffects(trx, runId, decision.fact);
744
+ await this.writeFact(trx, runId, decision.fact);
784
745
  return decision.attempt;
785
746
  });
786
747
  if (failed !== false) {
@@ -789,13 +750,6 @@ var PostgresStore = class {
789
750
  }
790
751
  return timedOut;
791
752
  }
792
- async settleStep(runId, _stepId, fact) {
793
- await this.db.transaction().execute(async (trx) => {
794
- await this.persistFact(trx, runId, fact);
795
- await this.applyFactEffects(trx, runId, fact);
796
- });
797
- await this.maybeNotify(runId);
798
- }
799
753
  async recordOnce(runId, stepId, scope, value) {
800
754
  await sql`
801
755
  INSERT INTO ${sql.raw(this.t("dedupe"))} (run_id, step_id, scope, value)
@@ -809,23 +763,47 @@ var PostgresStore = class {
809
763
  FROM ${sql.raw(this.t("dedupe"))}
810
764
  WHERE run_id = ${runId} AND step_id = ${stepId} AND scope = ${scope}
811
765
  `.execute(this.db);
812
- return r.rows[0]?.value ?? null;
766
+ const row = r.rows[0];
767
+ return row === void 0 ? { tag: "miss" } : { tag: "hit", value: row.value };
813
768
  }
814
769
  async runStep(runId, _stepId, _attempt, body) {
815
- const output = await this.db.transaction().execute(async (trx) => {
770
+ return this.db.transaction().execute(async (trx) => {
816
771
  const result = await body(trx);
817
- await this.persistFact(trx, runId, result.fact);
818
- await this.applyFactEffects(trx, runId, result.fact);
772
+ await this.writeFact(trx, runId, result.fact);
819
773
  return result.output;
820
774
  });
821
- await this.maybeNotify(runId);
822
- return output;
823
775
  }
824
- 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
+ }
825
789
  await sql`
826
790
  INSERT INTO ${sql.raw(this.t("fact"))} (run_id, fact_id, kind, at, payload)
827
791
  VALUES (${runId}, ${uuidv7()}, ${fact.kind}, ${fact.at}, ${jsonb(serializeFactPayload(fact))})
828
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;
829
807
  }
830
808
  // Victims are canceled BEFORE the superseder row exists: the partial unique
831
809
  // index on (flow_id, concurrency_key) only frees the slot once they leave
@@ -839,35 +817,13 @@ var PostgresStore = class {
839
817
  WHERE run_id = ANY(${priors}::text[])
840
818
  `.execute(trx);
841
819
  }
842
- async persistFact(trx, runId, fact) {
843
- await this.insertFact(trx, runId, fact);
844
- const delta = rowDeltaOf(fact);
845
- if (delta !== null) await this.applyRowDelta(trx, runId, delta);
846
- await this.notifyStreamClose(trx, runId, fact);
847
- await this.notifyRunEvent(trx, runId, fact);
848
- }
849
- // Lifecycle events ride the fact's transaction: PostgreSQL holds a NOTIFY
850
- // until commit, so an observer is told about a fact only once it is durable,
851
- // and a rolled-back attempt announces nothing. This is also why the transport
852
- // lives here rather than in core — flow.canceled(concurrency) and
853
- // lease.reaped are minted inside this adapter and never reach core.
854
- async notifyRunEvent(trx, runId, fact) {
855
- if (this.eventHub === void 0) return;
856
- const event = runEventOf(fact);
857
- if (event === null) return;
858
- const payload = JSON.stringify({ ...event, runId });
859
- await sql`SELECT pg_notify(${this.eventChannel}, ${payload})`.execute(trx);
860
- }
861
- // Stream close/retry events ride the SAME transaction as the fact that caused
862
- // them. That is the opposite of publishChunk on purpose: PostgreSQL holds a
863
- // NOTIFY until commit, so a subscriber is told the step is finished only once
864
- // the fact is durable, and a rolled-back attempt never announces anything.
865
- async notifyStreamClose(trx, runId, fact) {
820
+ async notifyStreamEffect(trx, runId, effect) {
866
821
  if (this.stream === void 0) return;
867
- const frame = closeFrameOf(runId, fact);
868
- if (frame === null) return;
869
- await this.drainPublishes(runId, frame.k === "run" ? void 0 : frame.s);
870
- await sql`SELECT pg_notify(${this.streamChannel}, ${encodeFrame(frame)})`.execute(
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(
871
827
  trx
872
828
  );
873
829
  }
@@ -877,39 +833,30 @@ var PostgresStore = class {
877
833
  return this.applyRunDelta(trx, runId, delta);
878
834
  case "step":
879
835
  return this.applyStepDelta(trx, runId, delta);
880
- case "once":
881
- return this.insertOnce(trx, runId, delta);
882
836
  }
883
837
  }
884
838
  async applyRunDelta(trx, runId, delta) {
885
839
  switch (delta.status) {
886
840
  case "running":
887
- await sql`
888
- INSERT INTO ${sql.raw(this.t("workflow_run"))}
889
- (run_id, flow_id, status, input, started_at, flow_hash, code_version, parent_run_id, parent_step_id)
890
- VALUES
891
- (${runId}, ${delta.flowId}, 'running', ${jsonb(delta.input)}, ${delta.startedAt}, ${delta.flowHash}, ${delta.codeVersion}, ${delta.parent?.runId ?? null}, ${delta.parent?.stepId ?? null})
892
- ON CONFLICT (run_id) DO NOTHING
893
- `.execute(trx);
894
841
  return;
895
842
  case "completed":
896
843
  await sql`
897
844
  UPDATE ${sql.raw(this.t("workflow_run"))}
898
- 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}
899
846
  WHERE run_id = ${runId}
900
847
  `.execute(trx);
901
848
  return;
902
849
  case "failed":
903
850
  await sql`
904
851
  UPDATE ${sql.raw(this.t("workflow_run"))}
905
- 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}
906
853
  WHERE run_id = ${runId}
907
854
  `.execute(trx);
908
855
  return;
909
856
  case "canceled":
910
857
  await sql`
911
858
  UPDATE ${sql.raw(this.t("workflow_run"))}
912
- SET status = 'canceled',
859
+ SET status = 'canceled', output = NULL, error = NULL,
913
860
  canceled_by_run_id = (
914
861
  SELECT s.run_id FROM ${sql.raw(this.t("workflow_run"))} s
915
862
  WHERE s.run_id = ${delta.canceledByRunId}
@@ -920,50 +867,59 @@ var PostgresStore = class {
920
867
  return;
921
868
  }
922
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.
923
873
  async applyStepDelta(trx, runId, delta) {
924
874
  switch (delta.status) {
925
875
  case "running":
926
876
  await sql`
927
- 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)
928
878
  VALUES (${runId}, ${delta.stepId}, ${delta.attempt}, 'running', ${delta.startedAt})
929
- ON CONFLICT (run_id, step_id, attempt) DO UPDATE
930
- 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}
931
892
  `.execute(trx);
932
893
  return;
933
894
  case "completed":
934
- await this.upsertStepCompleted(
895
+ return this.settleStepRow(
935
896
  trx,
936
897
  runId,
937
- delta.stepId,
898
+ delta,
938
899
  delta.attempt,
939
- delta.output
900
+ delta.output,
901
+ null
940
902
  );
941
- return;
942
903
  case "failed":
943
- await this.upsertStepFailed(
904
+ return this.settleStepRow(
944
905
  trx,
945
906
  runId,
946
- delta.stepId,
907
+ delta,
947
908
  delta.attempt,
909
+ null,
948
910
  delta.error
949
911
  );
950
- return;
951
912
  case "canceled":
952
- await this.upsertStepCanceled(
913
+ return this.settleStepRow(
953
914
  trx,
954
915
  runId,
955
- delta.stepId,
916
+ delta,
956
917
  delta.attempt,
957
- delta.error ?? void 0
918
+ null,
919
+ delta.error
958
920
  );
959
- return;
960
921
  case "skipped":
961
- await sql`
962
- INSERT INTO ${sql.raw(this.t("step_run"))} (run_id, step_id, attempt, status)
963
- VALUES (${runId}, ${delta.stepId}, 0, 'skipped')
964
- ON CONFLICT (run_id, step_id, attempt) DO UPDATE SET status = 'skipped'
965
- `.execute(trx);
966
- return;
922
+ return this.settleStepRow(trx, runId, delta, null, null, null);
967
923
  case "reset": {
968
924
  const row = await sql`
969
925
  SELECT flow_id, concurrency_key FROM ${sql.raw(this.t("workflow_run"))}
@@ -991,48 +947,20 @@ var PostgresStore = class {
991
947
  }
992
948
  }
993
949
  }
994
- async insertOnce(trx, runId, delta) {
995
- await sql`
996
- INSERT INTO ${sql.raw(this.t("dedupe"))} (run_id, step_id, scope, value)
997
- VALUES (${runId}, ${delta.stepId}, ${delta.scope}, ${jsonb(delta.value)})
998
- ON CONFLICT (run_id, step_id, scope) DO NOTHING
999
- `.execute(trx);
1000
- }
1001
- async upsertStepCompleted(trx, runId, stepId, attempt, output) {
1002
- await sql`
1003
- INSERT INTO ${sql.raw(this.t("step_run"))}
1004
- (run_id, step_id, attempt, status, output, started_at, completed_at)
1005
- VALUES
1006
- (${runId}, ${stepId}, ${attempt}, 'completed', ${jsonb(output)}, now(), now())
1007
- ON CONFLICT (run_id, step_id, attempt) DO UPDATE
1008
- SET status = 'completed', output = EXCLUDED.output, completed_at = now()
1009
- `.execute(trx);
1010
- }
1011
- async upsertStepFailed(trx, runId, stepId, attempt, error) {
1012
- await sql`
1013
- INSERT INTO ${sql.raw(this.t("step_run"))}
1014
- (run_id, step_id, attempt, status, error, started_at, completed_at)
1015
- VALUES
1016
- (${runId}, ${stepId}, ${attempt}, 'failed', ${jsonb(error)}, now(), now())
1017
- ON CONFLICT (run_id, step_id, attempt) DO UPDATE
1018
- SET status = 'failed', error = EXCLUDED.error, completed_at = now()
1019
- `.execute(trx);
1020
- }
1021
- async upsertStepCanceled(trx, runId, stepId, attempt, error) {
1022
- const errorJson = error === void 0 ? null : jsonb(error);
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);
1023
955
  await sql`
1024
- INSERT INTO ${sql.raw(this.t("step_run"))}
1025
- (run_id, step_id, attempt, status, error, 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)
1026
958
  VALUES
1027
- (${runId}, ${stepId}, ${attempt}, 'canceled', ${errorJson}, now(), now())
1028
- ON CONFLICT (run_id, step_id, attempt) DO UPDATE
1029
- SET status = 'canceled', error = EXCLUDED.error, completed_at = now()
1030
- `.execute(trx);
1031
- }
1032
- async deleteLease(trx, runId, stepId) {
1033
- await sql`
1034
- DELETE FROM ${sql.raw(this.t("lease"))}
1035
- 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}
1036
964
  `.execute(trx);
1037
965
  }
1038
966
  async deleteTimer(trx, runId, stepId) {
@@ -1041,20 +969,24 @@ var PostgresStore = class {
1041
969
  WHERE run_id = ${runId} AND step_id = ${stepId}
1042
970
  `.execute(trx);
1043
971
  }
1044
- // The adapter's whole share of the release table: lease / timer rows. The
1045
- // concurrency slot needs no write — the partial unique index keys on status,
1046
- // which the materializer already set.
1047
- async applyFactEffects(trx, runId, fact) {
1048
- const effects = factEffects(fact);
1049
- if (effects.tag !== "release-step") return;
1050
- await this.deleteLease(trx, runId, effects.stepId);
1051
- if (effects.timer) await this.deleteTimer(trx, runId, effects.stepId);
1052
- }
1053
- async maybeNotify(runId) {
1054
- if (!this.notifyChannel) return;
1055
- await sql`SELECT pg_notify(${this.notifyChannel}, ${runId})`.execute(
1056
- this.db
1057
- );
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
+ }
1058
990
  }
1059
991
  async upsertSnapshot(args) {
1060
992
  await sql`
@@ -1094,46 +1026,6 @@ var PostgresStore = class {
1094
1026
  VALUES (${uuidv7()}, ${fact.kind}, ${fact.at}, ${jsonb(serializeGlobalFactPayload(fact))})
1095
1027
  `.execute(this.db);
1096
1028
  }
1097
- async queryRuns(opts) {
1098
- const where = opts.where ?? {};
1099
- const flowId = where.flowId;
1100
- const statuses = where.status ? Array.from(where.status) : void 0;
1101
- const inputJson = where.input === void 0 ? null : JSON.stringify(where.input);
1102
- const isLatest = opts.latest === true;
1103
- const limit = isLatest ? 1 : clampQueryLimit(opts.limit);
1104
- const cursor = !isLatest && opts.cursor !== void 0 ? decodeRunCursor(opts.cursor) : null;
1105
- const fetchLimit = isLatest ? 1 : limit + 1;
1106
- const rows = await sql`
1107
- SELECT run_id, flow_id, status, input, started_at, completed_at
1108
- FROM ${sql.raw(this.t("workflow_run"))}
1109
- WHERE (${flowId ?? null}::text IS NULL OR flow_id = ${flowId ?? null})
1110
- AND (${statuses === void 0 ? null : statuses}::text[] IS NULL
1111
- OR status = ANY(${statuses === void 0 ? null : statuses}::text[]))
1112
- AND (${inputJson}::jsonb IS NULL OR input @> ${inputJson}::jsonb)
1113
- AND (${cursor === null ? null : cursor.startedAt}::timestamptz IS NULL
1114
- OR (started_at, run_id) <
1115
- (${cursor === null ? null : cursor.startedAt}::timestamptz,
1116
- ${cursor === null ? null : cursor.runId}::text))
1117
- ORDER BY started_at DESC, run_id DESC
1118
- LIMIT ${fetchLimit}
1119
- `.execute(this.db);
1120
- const summaries = rows.rows.map((r) => ({
1121
- runId: r.run_id,
1122
- flowId: r.flow_id,
1123
- status: r.status,
1124
- startedAt: r.started_at instanceof Date ? r.started_at : new Date(r.started_at),
1125
- completedAt: r.completed_at === null ? null : r.completed_at instanceof Date ? r.completed_at : new Date(r.completed_at),
1126
- input: r.input
1127
- }));
1128
- if (isLatest) {
1129
- return { runs: summaries.slice(0, 1), cursor: null };
1130
- }
1131
- const hasMore = summaries.length > limit;
1132
- const page = hasMore ? summaries.slice(0, limit) : summaries;
1133
- const last = page[page.length - 1];
1134
- const nextCursor = hasMore && last !== void 0 ? encodeRunCursor({ startedAt: last.startedAt, runId: last.runId }) : null;
1135
- return { runs: page, cursor: nextCursor };
1136
- }
1137
1029
  async describe(runId) {
1138
1030
  return this.db.transaction().execute(async (trx) => {
1139
1031
  const runRows = await sql`
@@ -1291,6 +1183,7 @@ function reviveFact(kind, at, payload) {
1291
1183
  ...body
1292
1184
  };
1293
1185
  }
1186
+ var SETTLED_STEP = sql.raw("('completed', 'failed', 'canceled', 'skipped')");
1294
1187
  function jsonb(value) {
1295
1188
  return sql`${JSON.stringify(value)}::jsonb`;
1296
1189
  }
@@ -1305,20 +1198,16 @@ function isUniqueViolation(err) {
1305
1198
  }
1306
1199
  return false;
1307
1200
  }
1308
- function closeFrameOf(runId, fact) {
1309
- switch (fact.kind) {
1310
- case "step.completed":
1311
- return { k: "ok", r: runId, s: fact.stepId };
1312
- case "step.failed":
1313
- return { k: "err", r: runId, s: fact.stepId, e: fact.error };
1314
- case "step.retried":
1315
- return { k: "retry", r: runId, s: fact.stepId, a: fact.attempt + 1 };
1316
- case "flow.completed":
1317
- case "flow.failed":
1318
- case "flow.canceled":
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":
1319
1210
  return { k: "run", r: runId };
1320
- default:
1321
- return null;
1322
1211
  }
1323
1212
  }
1324
1213
  function byteLength(s) {