@nagi-js/core 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/testing.js CHANGED
@@ -1,4 +1,4 @@
1
- import { Facts, stepStateOf, InMemoryQueue, stepStatusOf, NagiConcurrencyConflictError } from './chunk-VU2LG4VW.js';
1
+ import { Facts, isRunEnd, stepStateOf, InMemoryQueue, stepStatusOf, NagiConcurrencyConflictError } from './chunk-DPTPJZEG.js';
2
2
 
3
3
  // src/testing.ts
4
4
  function passthroughSchema() {
@@ -97,7 +97,7 @@ async function stepStatus(s, runId, stepId) {
97
97
  }
98
98
  async function endRun(s, runId, status, at = /* @__PURE__ */ new Date()) {
99
99
  const fact = status === "completed" ? Facts.flowCompleted(runId, null, at) : status === "failed" ? Facts.flowFailed(runId, { name: "E", message: "x" }, at) : Facts.flowCanceled(runId, { cause: "explicit", reason: "test" }, at);
100
- await s.appendFact(runId, fact);
100
+ await s.endRun(runId, fact);
101
101
  }
102
102
  async function stepView(s, runId, stepId) {
103
103
  const d = await s.describe(runId);
@@ -110,6 +110,53 @@ async function claimableAgain(s, runId, stepId, what) {
110
110
  `${what} must release the lease: claimStep at the same attempt still returns null`
111
111
  );
112
112
  }
113
+ var TRANSPORT_WAIT_MS = 5e3;
114
+ async function eventually(cond, msg) {
115
+ const deadline = Date.now() + TRANSPORT_WAIT_MS;
116
+ while (!cond()) {
117
+ ok(Date.now() < deadline, msg);
118
+ await sleep(10);
119
+ }
120
+ }
121
+ function recordRuns(s) {
122
+ if (s.events === void 0) return null;
123
+ const seen = [];
124
+ s.events.watchRuns((e) => seen.push(e));
125
+ return seen;
126
+ }
127
+ function typesFor(seen, runId) {
128
+ return seen.filter((e) => e.runId === runId).map((e) => e.type);
129
+ }
130
+ async function drain(stream, what) {
131
+ const out = [];
132
+ const iter = stream[Symbol.asyncIterator]();
133
+ for (; ; ) {
134
+ const next = await Promise.race([
135
+ iter.next(),
136
+ sleep(TRANSPORT_WAIT_MS).then(() => null)
137
+ ]);
138
+ if (next === null) {
139
+ await iter.return?.();
140
+ throw new StoreContractViolation(`${what}: the stream never closed`);
141
+ }
142
+ if (next.done === true) return out;
143
+ out.push(next.value);
144
+ }
145
+ }
146
+ function failingQueue() {
147
+ const fail = async () => {
148
+ throw new Error("queue unavailable");
149
+ };
150
+ const q = {
151
+ enqueue: fail,
152
+ dequeue: fail,
153
+ ack: fail,
154
+ nack: fail,
155
+ extend: fail,
156
+ withTx: () => q
157
+ };
158
+ return q;
159
+ }
113
160
  var storeContract = [
114
161
  {
115
162
  name: "tryStartRun: concurrent calls with the same runId produce exactly one flow.started",
@@ -245,17 +292,59 @@ var storeContract = [
245
292
  );
246
293
  }
247
294
  },
295
+ {
296
+ name: "endRun: a run ends once \u2014 of racing ends exactly one is admitted, and a later one (or one on a never-started run) is refused and writes nothing",
297
+ async run(h) {
298
+ const s = await h.makeStore({ leaseMs: LEASE_MS });
299
+ const runId = rid();
300
+ await startRun(s, runId);
301
+ const won = await Promise.all([
302
+ s.endRun(
303
+ runId,
304
+ Facts.flowFailed(runId, { name: "E", message: "x" }, /* @__PURE__ */ new Date())
305
+ ),
306
+ s.endRun(
307
+ runId,
308
+ Facts.flowCanceled(
309
+ runId,
310
+ { cause: "explicit", reason: "race" },
311
+ /* @__PURE__ */ new Date()
312
+ )
313
+ )
314
+ ]);
315
+ eq(won.filter(Boolean).length, 1, "exactly one racing end is admitted");
316
+ const winner = won[0] === true ? "failed" : "canceled";
317
+ ok(
318
+ !await s.endRun(runId, Facts.flowCompleted(runId, null, /* @__PURE__ */ new Date())),
319
+ "an end on an already-ended run must resolve false"
320
+ );
321
+ const state = await s.loadRunState(runId);
322
+ eq(
323
+ state.facts.filter(isRunEnd).length,
324
+ 1,
325
+ "a refused end is not persisted"
326
+ );
327
+ eq(state.phase.tag, winner, "the fold keeps the winner's end");
328
+ eq((await s.describe(runId))?.run.status, winner, "so does the row");
329
+ const ghost = rid();
330
+ ok(
331
+ !await s.endRun(ghost, Facts.flowCompleted(ghost, null, /* @__PURE__ */ new Date())),
332
+ "a run that never started cannot end"
333
+ );
334
+ eq((await s.loadRunState(ghost)).facts, [], "and nothing is written");
335
+ }
336
+ },
248
337
  {
249
338
  // NagiCanceledError is public: a handler can name any run as its canceler
250
339
  // and classifyFailure turns that claim into a concurrency-cause fact. The
251
340
  // fact is the record; the VIEW must not present an unresolvable claim as a
252
341
  // reference, or every consumer's audit finds nagi#29's orphan.
253
- name: "appendFact(flow.canceled): a canceler that never existed is not surfaced as a reference",
342
+ name: "endRun(flow.canceled): a canceler that never existed is not surfaced as a reference",
254
343
  async run(h) {
255
344
  const s = await h.makeStore({ leaseMs: LEASE_MS });
256
345
  const victim = rid();
257
346
  await startRun(s, victim);
258
- await s.appendFact(
347
+ await s.endRun(
259
348
  victim,
260
349
  Facts.flowCanceledByConcurrency({
261
350
  runId: victim,
@@ -359,7 +448,7 @@ var storeContract = [
359
448
  }
360
449
  },
361
450
  {
362
- name: "settleStep(step.completed): releases the lease \u2014 describe() drops lease.expiresAt and claimStep re-acquires",
451
+ name: "appendFact(step.completed): releases the lease \u2014 describe() drops lease.expiresAt and claimStep re-acquires",
363
452
  async run(h) {
364
453
  const s = await h.makeStore({ leaseMs: LEASE_MS });
365
454
  const runId = rid();
@@ -368,29 +457,27 @@ var storeContract = [
368
457
  ok(await s.claimStep(runId, "s", A1) !== null, "claim");
369
458
  const live = await stepView(s, runId, "s");
370
459
  ok(live?.lease?.expiresAt instanceof Date, "lease visible while held");
371
- await s.settleStep(
460
+ await s.appendFact(
372
461
  runId,
373
- "s",
374
462
  Facts.stepCompleted(runId, "s", A1, { ok: 1 }, /* @__PURE__ */ new Date())
375
463
  );
376
464
  const done = await stepView(s, runId, "s");
377
465
  eq(done?.status, "completed", "status");
378
466
  eq(done?.output, { ok: 1 }, "output");
379
467
  eq(done?.lease, void 0, "lease gone from describe()");
380
- await claimableAgain(s, runId, "s", "settleStep(step.completed)");
468
+ await claimableAgain(s, runId, "s", "appendFact(step.completed)");
381
469
  }
382
470
  },
383
471
  {
384
- name: "settleStep(step.failed): releases the lease",
472
+ name: "appendFact(step.failed): releases the lease",
385
473
  async run(h) {
386
474
  const s = await h.makeStore({ leaseMs: LEASE_MS });
387
475
  const runId = rid();
388
476
  await startRun(s, runId);
389
477
  await startStep(s, runId, "s");
390
478
  ok(await s.claimStep(runId, "s", A1) !== null, "claim");
391
- await s.settleStep(
479
+ await s.appendFact(
392
480
  runId,
393
- "s",
394
481
  Facts.stepFailed(
395
482
  runId,
396
483
  "s",
@@ -401,7 +488,7 @@ var storeContract = [
401
488
  );
402
489
  eq(await stepStatus(s, runId, "s"), "failed", "status");
403
490
  eq((await stepView(s, runId, "s"))?.lease, void 0, "lease");
404
- await claimableAgain(s, runId, "s", "settleStep(step.failed)");
491
+ await claimableAgain(s, runId, "s", "appendFact(step.failed)");
405
492
  }
406
493
  },
407
494
  {
@@ -568,9 +655,8 @@ var storeContract = [
568
655
  async run(h) {
569
656
  const s = await h.makeStore({ leaseMs: LEASE_MS });
570
657
  for (const status of ["completed", "failed"]) {
571
- const flowId = fid();
572
658
  const runId2 = rid();
573
- await startRun(s, runId2, { flowId });
659
+ await startRun(s, runId2);
574
660
  await startStep(s, runId2, "s");
575
661
  await endRun(s, runId2, status);
576
662
  await s.appendFact(
@@ -582,12 +668,9 @@ var storeContract = [
582
668
  "running",
583
669
  `fold after flow.${status}`
584
670
  );
585
- const { runs } = await s.queryRuns({
586
- where: { flowId, status: ["running"] }
587
- });
588
671
  eq(
589
- runs.map((r) => r.runId),
590
- [runId2],
672
+ (await s.describe(runId2))?.run.status,
673
+ "running",
591
674
  `read model after flow.${status}`
592
675
  );
593
676
  }
@@ -863,8 +946,8 @@ var storeContract = [
863
946
  eq(msg?.stepId, "s", "re-enqueued stepId");
864
947
  eq(msg?.attempt, A2, "re-enqueued attempt");
865
948
  eq(msg?.flowId, flowId, "re-enqueued flowId");
866
- await claimableAgain(s, runId, "s", "sweepLeases");
867
949
  eq(await s.sweepLeases({ now: /* @__PURE__ */ new Date(), queue }), [], "restart-safe");
950
+ await claimableAgain(s, runId, "s", "sweepLeases");
868
951
  }
869
952
  },
870
953
  {
@@ -881,9 +964,8 @@ var storeContract = [
881
964
  await startRun(s, settled);
882
965
  await startStep(s, settled, "s");
883
966
  ok(await s.claimStep(settled, "s", A1) !== null, "claim settled");
884
- await s.settleStep(
967
+ await s.appendFact(
885
968
  settled,
886
- "s",
887
969
  Facts.stepCompleted(settled, "s", A1, null, /* @__PURE__ */ new Date())
888
970
  );
889
971
  await sleep(PAST_LEASE_MS);
@@ -968,19 +1050,26 @@ var storeContract = [
968
1050
  }
969
1051
  },
970
1052
  {
971
- name: "recordOnce / getOnce: first write wins; null when absent",
1053
+ name: "recordOnce / getOnce: first write wins; miss when absent; a recorded null is a hit",
972
1054
  async run(h) {
973
1055
  const s = await h.makeStore({ leaseMs: LEASE_MS });
974
1056
  const runId = rid();
975
- eq(await s.getOnce(runId, "s", "scope"), null, "absent");
1057
+ eq(await s.getOnce(runId, "s", "scope"), { tag: "miss" }, "absent");
976
1058
  await s.recordOnce(runId, "s", "scope", { value: 1 });
977
1059
  await s.recordOnce(runId, "s", "scope", { value: 2 });
978
1060
  eq(
979
1061
  await s.getOnce(runId, "s", "scope"),
980
- { value: 1 },
1062
+ { tag: "hit", value: { value: 1 } },
981
1063
  "first write wins"
982
1064
  );
983
- eq(await s.getOnce(runId, "s", "other"), null, "scoped");
1065
+ eq(await s.getOnce(runId, "s", "other"), { tag: "miss" }, "scoped");
1066
+ await s.recordOnce(runId, "s", "nil", null);
1067
+ await s.recordOnce(runId, "s", "nil", { value: 3 });
1068
+ eq(
1069
+ await s.getOnce(runId, "s", "nil"),
1070
+ { tag: "hit", value: null },
1071
+ "recorded null"
1072
+ );
984
1073
  }
985
1074
  },
986
1075
  {
@@ -1035,9 +1124,8 @@ var storeContract = [
1035
1124
  const runId = rid();
1036
1125
  await startRun(s, runId, { flowId: "f", input: { a: 1 } });
1037
1126
  await startStep(s, runId, "s");
1038
- await s.settleStep(
1127
+ await s.appendFact(
1039
1128
  runId,
1040
- "s",
1041
1129
  Facts.stepCompleted(runId, "s", A1, 7, /* @__PURE__ */ new Date())
1042
1130
  );
1043
1131
  await endRun(s, runId, "completed");
@@ -1052,178 +1140,6 @@ var storeContract = [
1052
1140
  eq(state.phase.tag, "completed", "phase");
1053
1141
  }
1054
1142
  },
1055
- {
1056
- name: "queryRuns: orders by (startedAt DESC, runId DESC)",
1057
- async run(h) {
1058
- const s = await h.makeStore({ leaseMs: LEASE_MS });
1059
- const flowId = fid();
1060
- const t0 = /* @__PURE__ */ new Date(17e11);
1061
- const t1 = /* @__PURE__ */ new Date(1700000001e3);
1062
- const base = crypto.randomUUID();
1063
- const a = `run-${base}-a`;
1064
- const b = `run-${base}-b`;
1065
- const c = `run-${base}-c`;
1066
- const later = `run-${base}-0`;
1067
- for (const runId of [b, a, c])
1068
- await startRun(s, runId, { flowId, at: t0 });
1069
- await startRun(s, later, { flowId, at: t1 });
1070
- const r = await s.queryRuns({ where: { flowId } });
1071
- eq(
1072
- r.runs.map((x) => x.runId),
1073
- [later, c, b, a],
1074
- "order"
1075
- );
1076
- eq(r.cursor, null, "single page");
1077
- }
1078
- },
1079
- {
1080
- name: "queryRuns: input containment follows jsonb @> \u2014 subset, nested, arrays, empty object, type mismatch",
1081
- async run(h) {
1082
- const s = await h.makeStore({ leaseMs: LEASE_MS });
1083
- const flowId = fid();
1084
- await startRun(s, rid(), {
1085
- flowId,
1086
- input: { videoId: "abc", userId: 7 }
1087
- });
1088
- await startRun(s, rid(), {
1089
- flowId,
1090
- input: { customer: { id: 1, plan: { seats: 5 } } }
1091
- });
1092
- await startRun(s, rid(), { flowId, input: { tags: ["a", "b", "c"] } });
1093
- await startRun(s, rid(), { flowId, input: { x: "string" } });
1094
- const count = async (input) => (await s.queryRuns({ where: { flowId, input } })).runs.length;
1095
- eq(await count({ videoId: "abc" }), 1, "subset of keys");
1096
- eq(await count({ videoId: "abc", userId: 7 }), 1, "all keys");
1097
- eq(await count({ videoId: "abc", missing: 1 }), 0, "superset of keys");
1098
- eq(await count({ videoId: "MISS" }), 0, "value mismatch");
1099
- eq(await count({ customer: { plan: { seats: 5 } } }), 1, "nested");
1100
- eq(await count({ customer: {} }), 1, "empty object matches any object");
1101
- eq(await count({ tags: ["a", "b"] }), 1, "array subset");
1102
- eq(await count({ tags: ["b", "a"] }), 1, "array order-insensitive");
1103
- eq(await count({ tags: ["a", "z"] }), 0, "array with a missing element");
1104
- eq(await count({ x: 42 }), 0, "type mismatch");
1105
- eq(await count({}), 4, "empty filter matches all");
1106
- }
1107
- },
1108
- {
1109
- name: "queryRuns: filters by flowId and status",
1110
- async run(h) {
1111
- const s = await h.makeStore({ leaseMs: LEASE_MS });
1112
- const flowId = fid();
1113
- const running = rid();
1114
- const completed = rid();
1115
- const failed = rid();
1116
- await startRun(s, running, { flowId });
1117
- await startRun(s, completed, { flowId });
1118
- await endRun(s, completed, "completed");
1119
- await startRun(s, failed, { flowId });
1120
- await endRun(s, failed, "failed");
1121
- await startRun(s, rid(), { flowId: fid() });
1122
- eq((await s.queryRuns({ where: { flowId } })).runs.length, 3, "flowId");
1123
- const terminal = await s.queryRuns({
1124
- where: { flowId, status: ["completed", "failed"] }
1125
- });
1126
- eq(
1127
- terminal.runs.map((r) => r.runId).sort(),
1128
- [completed, failed].sort(),
1129
- "status array"
1130
- );
1131
- const one = await s.queryRuns({
1132
- where: { flowId, status: ["completed"] }
1133
- });
1134
- eq(
1135
- one.runs.map((r) => r.status),
1136
- ["completed"],
1137
- "single status"
1138
- );
1139
- ok(one.runs[0]?.completedAt instanceof Date, "completedAt populated");
1140
- }
1141
- },
1142
- {
1143
- name: "queryRuns: latest:true returns the single newest matching run and no cursor",
1144
- async run(h) {
1145
- const s = await h.makeStore({ leaseMs: LEASE_MS });
1146
- const flowId = fid();
1147
- await startRun(s, rid(), { flowId, at: /* @__PURE__ */ new Date(17e11) });
1148
- const newest = rid();
1149
- await startRun(s, newest, { flowId, at: /* @__PURE__ */ new Date(1700000005e3) });
1150
- await startRun(s, rid(), { flowId, at: /* @__PURE__ */ new Date(1700000002e3) });
1151
- const r = await s.queryRuns({ where: { flowId }, latest: true });
1152
- eq(
1153
- r.runs.map((x) => x.runId),
1154
- [newest],
1155
- "newest"
1156
- );
1157
- eq(r.cursor, null, "no cursor");
1158
- eq(
1159
- await s.queryRuns({ where: { flowId: fid() }, latest: true }),
1160
- { runs: [], cursor: null },
1161
- "no match"
1162
- );
1163
- }
1164
- },
1165
- {
1166
- name: "queryRuns: cursor pagination visits every row exactly once and ends with a null cursor",
1167
- async run(h) {
1168
- const s = await h.makeStore({ leaseMs: LEASE_MS });
1169
- const flowId = fid();
1170
- const seeded = [];
1171
- for (let i = 0; i < 5; i++) {
1172
- const runId = rid();
1173
- seeded.push(runId);
1174
- await startRun(s, runId, {
1175
- flowId,
1176
- at: new Date(17e11 + i * 1e3)
1177
- });
1178
- }
1179
- const seen = [];
1180
- let cursor = null;
1181
- let pages = 0;
1182
- do {
1183
- const page = await s.queryRuns({
1184
- where: { flowId },
1185
- limit: 2,
1186
- ...cursor !== null ? { cursor } : {}
1187
- });
1188
- ok(page.runs.length <= 2, "page size");
1189
- seen.push(...page.runs.map((r) => r.runId));
1190
- cursor = page.cursor;
1191
- pages++;
1192
- } while (cursor !== null && pages < 10);
1193
- eq(pages, 3, "three pages");
1194
- eq([...seen].sort(), [...seeded].sort(), "every row once");
1195
- }
1196
- },
1197
- {
1198
- name: "queryRuns: rejects a malformed cursor",
1199
- async run(h) {
1200
- const s = await h.makeStore({ leaseMs: LEASE_MS });
1201
- await rejects(s.queryRuns({ cursor: "not-a-cursor" }), "throws");
1202
- }
1203
- },
1204
- {
1205
- name: "queryRuns: a non-positive or non-integer limit falls back to the default",
1206
- async run(h) {
1207
- const s = await h.makeStore({ leaseMs: LEASE_MS });
1208
- const flowId = fid();
1209
- for (let i = 0; i < 3; i++) await startRun(s, rid(), { flowId });
1210
- eq(
1211
- (await s.queryRuns({ where: { flowId }, limit: 0 })).runs.length,
1212
- 3,
1213
- "0"
1214
- );
1215
- eq(
1216
- (await s.queryRuns({ where: { flowId }, limit: 1.5 })).runs.length,
1217
- 3,
1218
- "1.5"
1219
- );
1220
- eq(
1221
- (await s.queryRuns({ where: { flowId }, limit: 2 })).runs.length,
1222
- 2,
1223
- "2"
1224
- );
1225
- }
1226
- },
1227
1143
  {
1228
1144
  name: "describe: returns null for an unknown runId",
1229
1145
  async run(h) {
@@ -1248,9 +1164,8 @@ var storeContract = [
1248
1164
  parent: { runId: parent, stepId: "sub" }
1249
1165
  });
1250
1166
  await startStep(s, parent, "sub", { kind: "subflow" });
1251
- await s.settleStep(
1167
+ await s.appendFact(
1252
1168
  parent,
1253
- "sub",
1254
1169
  Facts.stepCompleted(
1255
1170
  parent,
1256
1171
  "sub",
@@ -1259,7 +1174,7 @@ var storeContract = [
1259
1174
  /* @__PURE__ */ new Date()
1260
1175
  )
1261
1176
  );
1262
- await s.appendFact(
1177
+ await s.endRun(
1263
1178
  parent,
1264
1179
  Facts.flowCompleted(parent, { done: true }, /* @__PURE__ */ new Date())
1265
1180
  );
@@ -1289,6 +1204,277 @@ var storeContract = [
1289
1204
  eq(await s.listChildren(child), [], "listChildren leaf");
1290
1205
  }
1291
1206
  },
1207
+ {
1208
+ name: "describe: a retried step is ONE view of its latest attempt, timestamped by its facts' `at`",
1209
+ async run(h) {
1210
+ const s = await h.makeStore({ leaseMs: LEASE_MS });
1211
+ const runId = rid();
1212
+ const t = (n) => new Date(17e11 + n * 1e3);
1213
+ const error = { name: "E", message: "boom" };
1214
+ await startRun(s, runId, { at: t(0) });
1215
+ await s.appendFact(
1216
+ runId,
1217
+ Facts.stepStarted(runId, "s", A1, "task", t(1))
1218
+ );
1219
+ await s.appendFact(
1220
+ runId,
1221
+ Facts.stepRetried(runId, "s", A1, t(3), error, t(2))
1222
+ );
1223
+ eq(
1224
+ (await s.describe(runId))?.steps,
1225
+ [
1226
+ {
1227
+ stepId: "s",
1228
+ attempt: A1,
1229
+ status: "running",
1230
+ startedAt: t(1),
1231
+ error
1232
+ }
1233
+ ],
1234
+ "backing off: the failed attempt, still running, with its error"
1235
+ );
1236
+ await s.appendFact(
1237
+ runId,
1238
+ Facts.stepStarted(runId, "s", A2, "task", t(3))
1239
+ );
1240
+ await s.appendFact(
1241
+ runId,
1242
+ Facts.stepStarted(runId, "s", A1, "task", t(4))
1243
+ );
1244
+ eq(
1245
+ (await s.describe(runId))?.steps,
1246
+ [{ stepId: "s", attempt: A2, status: "running", startedAt: t(3) }],
1247
+ "attempt 2 supersedes attempt 1; a stale attempt-1 start changes nothing"
1248
+ );
1249
+ eq(
1250
+ (await s.describe(runId))?.run.status,
1251
+ "running",
1252
+ "a retry leaves the run running"
1253
+ );
1254
+ await s.appendFact(
1255
+ runId,
1256
+ Facts.stepCompleted(runId, "s", A2, { v: 2 }, t(5))
1257
+ );
1258
+ await endRun(s, runId, "completed", t(6));
1259
+ const d = await s.describe(runId);
1260
+ eq(
1261
+ d?.steps,
1262
+ [
1263
+ {
1264
+ stepId: "s",
1265
+ attempt: A2,
1266
+ status: "completed",
1267
+ startedAt: t(3),
1268
+ completedAt: t(5),
1269
+ output: { v: 2 }
1270
+ }
1271
+ ],
1272
+ "one view per step"
1273
+ );
1274
+ eq(d?.run.startedAt, t(0), "run startedAt");
1275
+ eq(d?.run.completedAt, t(6), "run completedAt");
1276
+ }
1277
+ },
1278
+ {
1279
+ name: "step attempts only move forward, in loadRunState and describe alike: a newer start supersedes a live attempt; a duplicate start, and a retry or abort for an attempt not in flight, change nothing",
1280
+ async run(h) {
1281
+ const s = await h.makeStore({ leaseMs: LEASE_MS });
1282
+ const runId = rid();
1283
+ const t = (n) => new Date(17e11 + n * 1e3);
1284
+ const error = { name: "E", message: "boom" };
1285
+ const both = async (tag, attempt, at) => {
1286
+ eq(
1287
+ stepStateOf(await s.loadRunState(runId), "s"),
1288
+ { tag, attempt },
1289
+ `loadRunState after ${at.toISOString()}`
1290
+ );
1291
+ eq(
1292
+ await stepView(s, runId, "s"),
1293
+ { stepId: "s", attempt, status: "running", startedAt: at },
1294
+ `describe after ${at.toISOString()}`
1295
+ );
1296
+ };
1297
+ await startRun(s, runId, { at: t(0) });
1298
+ await s.appendFact(
1299
+ runId,
1300
+ Facts.stepStarted(runId, "s", A1, "task", t(1))
1301
+ );
1302
+ await s.appendFact(
1303
+ runId,
1304
+ Facts.stepStarted(runId, "s", A1, "task", t(2))
1305
+ );
1306
+ await both("running", A1, t(1));
1307
+ await s.appendFact(
1308
+ runId,
1309
+ Facts.stepStarted(runId, "s", A2, "task", t(3))
1310
+ );
1311
+ await both("running", A2, t(3));
1312
+ for (const attempt of [A1, 3]) {
1313
+ await s.appendFact(
1314
+ runId,
1315
+ Facts.stepRetried(runId, "s", attempt, t(9), error, t(4))
1316
+ );
1317
+ }
1318
+ await s.appendFact(
1319
+ runId,
1320
+ Facts.stepAbortRequested({
1321
+ runId,
1322
+ stepId: "s",
1323
+ attempt: A1,
1324
+ at: t(5)
1325
+ })
1326
+ );
1327
+ await both("running", A2, t(3));
1328
+ await s.appendFact(
1329
+ runId,
1330
+ Facts.stepAbortRequested({
1331
+ runId,
1332
+ stepId: "s",
1333
+ attempt: A2,
1334
+ at: t(6)
1335
+ })
1336
+ );
1337
+ eq(
1338
+ stepStateOf(await s.loadRunState(runId), "s"),
1339
+ { tag: "aborting", attempt: A2 },
1340
+ "an abort for the live attempt lands"
1341
+ );
1342
+ }
1343
+ },
1344
+ {
1345
+ name: "a settle needs its attempt to have started: after a reset, a pre-reset attempt's completion, failure or cancel changes nothing in loadRunState or describe",
1346
+ async run(h) {
1347
+ const s = await h.makeStore({ leaseMs: LEASE_MS });
1348
+ const runId = rid();
1349
+ const t = (n) => new Date(17e11 + n * 1e3);
1350
+ const error = { name: "E", message: "stale" };
1351
+ const stale = (at) => [
1352
+ Facts.stepCompleted(runId, "s", A2, { stale: true }, at),
1353
+ Facts.stepFailed(runId, "s", A2, error, at),
1354
+ Facts.stepCanceled(runId, "s", A2, at, error)
1355
+ ];
1356
+ await startRun(s, runId, { at: t(0) });
1357
+ await s.appendFact(
1358
+ runId,
1359
+ Facts.stepStarted(runId, "s", A1, "task", t(1))
1360
+ );
1361
+ await s.appendFact(
1362
+ runId,
1363
+ Facts.stepStarted(runId, "s", A2, "task", t(2))
1364
+ );
1365
+ await s.appendFact(
1366
+ runId,
1367
+ Facts.stepReset({ runId, stepId: "s", at: t(3) })
1368
+ );
1369
+ for (const fact of stale(t(4))) await s.appendFact(runId, fact);
1370
+ eq(
1371
+ stepStateOf(await s.loadRunState(runId), "s"),
1372
+ { tag: "pending" },
1373
+ "loadRunState: a reset step ignores a settle before it restarts"
1374
+ );
1375
+ eq(
1376
+ await stepView(s, runId, "s"),
1377
+ void 0,
1378
+ "describe: a reset step ignores a settle before it restarts"
1379
+ );
1380
+ await s.appendFact(
1381
+ runId,
1382
+ Facts.stepStarted(runId, "s", A1, "task", t(5))
1383
+ );
1384
+ for (const fact of stale(t(6))) await s.appendFact(runId, fact);
1385
+ eq(
1386
+ stepStateOf(await s.loadRunState(runId), "s"),
1387
+ { tag: "running", attempt: A1 },
1388
+ "loadRunState: a settle for an attempt that has not started is ignored"
1389
+ );
1390
+ eq(
1391
+ await stepView(s, runId, "s"),
1392
+ { stepId: "s", attempt: A1, status: "running", startedAt: t(5) },
1393
+ "describe: a settle for an attempt that has not started is ignored"
1394
+ );
1395
+ await s.appendFact(
1396
+ runId,
1397
+ Facts.stepCompleted(runId, "s", A1, { fresh: true }, t(7))
1398
+ );
1399
+ eq(
1400
+ stepStateOf(await s.loadRunState(runId), "s"),
1401
+ { tag: "completed", attempt: A1, output: { fresh: true } },
1402
+ "loadRunState: the restarted attempt settles"
1403
+ );
1404
+ eq(
1405
+ await stepView(s, runId, "s"),
1406
+ {
1407
+ stepId: "s",
1408
+ attempt: A1,
1409
+ status: "completed",
1410
+ startedAt: t(5),
1411
+ completedAt: t(7),
1412
+ output: { fresh: true }
1413
+ },
1414
+ "describe: the restarted attempt settles"
1415
+ );
1416
+ }
1417
+ },
1418
+ {
1419
+ name: "describe: a skipped step settles its view; a settled step changes only by reset",
1420
+ async run(h) {
1421
+ const s = await h.makeStore({ leaseMs: LEASE_MS });
1422
+ const runId = rid();
1423
+ const t = (n) => new Date(17e11 + n * 1e3);
1424
+ const skip = (stepId, at) => s.appendFact(
1425
+ runId,
1426
+ Facts.stepSkipped({ runId, stepId, reason: "when-false", at })
1427
+ );
1428
+ await startRun(s, runId, { at: t(0) });
1429
+ await skip("never", t(1));
1430
+ await s.appendFact(
1431
+ runId,
1432
+ Facts.stepStarted(runId, "inflight", A1, "task", t(2))
1433
+ );
1434
+ await skip("inflight", t(3));
1435
+ await s.appendFact(
1436
+ runId,
1437
+ Facts.stepCompleted(runId, "inflight", A1, { late: true }, t(4))
1438
+ );
1439
+ eq(
1440
+ (await s.describe(runId))?.steps,
1441
+ [
1442
+ {
1443
+ stepId: "inflight",
1444
+ attempt: A1,
1445
+ status: "skipped",
1446
+ startedAt: t(2),
1447
+ completedAt: t(3)
1448
+ },
1449
+ {
1450
+ stepId: "never",
1451
+ attempt: 0,
1452
+ status: "skipped",
1453
+ completedAt: t(1)
1454
+ }
1455
+ ],
1456
+ "skipped views; the late completion is ignored"
1457
+ );
1458
+ await s.appendFact(
1459
+ runId,
1460
+ Facts.stepReset({ runId, stepId: "inflight", at: t(5) })
1461
+ );
1462
+ eq(
1463
+ (await s.describe(runId))?.steps.map((st) => st.stepId),
1464
+ ["never"],
1465
+ "a reset step has no view until it restarts"
1466
+ );
1467
+ await s.appendFact(
1468
+ runId,
1469
+ Facts.stepStarted(runId, "inflight", A1, "task", t(6))
1470
+ );
1471
+ eq(
1472
+ await stepView(s, runId, "inflight"),
1473
+ { stepId: "inflight", attempt: A1, status: "running", startedAt: t(6) },
1474
+ "restarted"
1475
+ );
1476
+ }
1477
+ },
1292
1478
  {
1293
1479
  name: "pruneFacts: never prunes non-terminal runs; respects olderThan and statuses",
1294
1480
  async run(h) {
@@ -1358,7 +1544,7 @@ var storeContract = [
1358
1544
  }
1359
1545
  },
1360
1546
  {
1361
- name: "pruneFacts keepSummary:true: the run stays queryable and describable with no steps, and its runId stays reserved",
1547
+ name: "pruneFacts keepSummary:true: the run stays describable with no steps, and its runId stays reserved",
1362
1548
  async run(h) {
1363
1549
  const s = await h.makeStore({ leaseMs: LEASE_MS });
1364
1550
  const flowId = fid();
@@ -1366,11 +1552,7 @@ var storeContract = [
1366
1552
  const old = /* @__PURE__ */ new Date(17e11);
1367
1553
  await startRun(s, runId, { flowId, input: { keep: 1 }, at: old });
1368
1554
  await startStep(s, runId, "s");
1369
- await s.settleStep(
1370
- runId,
1371
- "s",
1372
- Facts.stepCompleted(runId, "s", A1, null, old)
1373
- );
1555
+ await s.appendFact(runId, Facts.stepCompleted(runId, "s", A1, null, old));
1374
1556
  await endRun(s, runId, "completed", old);
1375
1557
  await s.pruneFacts({
1376
1558
  olderThan: /* @__PURE__ */ new Date(17000001e5),
@@ -1378,12 +1560,9 @@ var storeContract = [
1378
1560
  batchSize: 100,
1379
1561
  keepSummary: true
1380
1562
  });
1381
- const q = await s.queryRuns({ where: { flowId } });
1382
- eq(q.runs.length, 1, "still listed");
1383
- eq(q.runs[0]?.runId, runId, "runId");
1384
- eq(q.runs[0]?.status, "completed", "status");
1385
- eq(q.runs[0]?.input, { keep: 1 }, "input");
1386
1563
  const d = await s.describe(runId);
1564
+ eq(d?.run.runId, runId, "describe runId");
1565
+ eq(d?.run.flowId, flowId, "describe flowId");
1387
1566
  eq(d?.run.status, "completed", "describe status");
1388
1567
  eq(d?.run.input, { keep: 1 }, "describe input");
1389
1568
  eq(d?.steps, [], "no steps");
@@ -1410,7 +1589,6 @@ var storeContract = [
1410
1589
  batchSize: 100,
1411
1590
  keepSummary: false
1412
1591
  });
1413
- eq((await s.queryRuns({ where: { flowId } })).runs, [], "not listed");
1414
1592
  eq(await s.describe(runId), null, "not describable");
1415
1593
  eq(
1416
1594
  (await startRun(s, runId, { flowId })).started,
@@ -1437,10 +1615,253 @@ var storeContract = [
1437
1615
  batchSize: 100,
1438
1616
  keepSummary: false
1439
1617
  });
1440
- eq(await s.getOnce(runId, "gate", "scope"), null, "once gone");
1618
+ eq(await s.getOnce(runId, "gate", "scope"), { tag: "miss" }, "once gone");
1441
1619
  await claimableAgain(s, runId, "gate", "pruneFacts");
1442
1620
  eq(await s.sweepSignalTimeouts({ now: /* @__PURE__ */ new Date() }), [], "timer gone");
1443
1621
  }
1622
+ },
1623
+ {
1624
+ name: "tryStartRunOnTx: starts the run on the caller's tx; a second call for the same runId is a no-op",
1625
+ async run(h) {
1626
+ const s = await h.makeStore({ leaseMs: LEASE_MS });
1627
+ const runId = rid();
1628
+ const fact = Facts.flowStarted({
1629
+ runId,
1630
+ flowId: fid(),
1631
+ input: { x: 1 },
1632
+ at: /* @__PURE__ */ new Date()
1633
+ });
1634
+ const first = await h.withTx(
1635
+ s,
1636
+ (tx) => s.tryStartRunOnTx(tx, runId, fact)
1637
+ );
1638
+ eq(first, { started: true, canceled: [] }, "first start");
1639
+ const again = await h.withTx(
1640
+ s,
1641
+ (tx) => s.tryStartRunOnTx(tx, runId, { ...fact, input: { x: 2 } })
1642
+ );
1643
+ eq(again, { started: false, canceled: [] }, "second start");
1644
+ const state = await s.loadRunState(runId);
1645
+ eq(state.phase.tag, "running", "running after commit");
1646
+ eq(state.input, { x: 1 }, "input unchanged");
1647
+ eq((await s.describe(runId))?.run.status, "running", "read model");
1648
+ }
1649
+ },
1650
+ {
1651
+ name: "tryStartRunOnTx: with concurrency, cancels the prior active run on the same (flowId, key) and returns its fact",
1652
+ async run(h) {
1653
+ const s = await h.makeStore({ leaseMs: LEASE_MS });
1654
+ const flowId = fid();
1655
+ const a = rid();
1656
+ const b = rid();
1657
+ await startRun(s, a, { flowId, concurrencyKey: "k" });
1658
+ const res = await h.withTx(
1659
+ s,
1660
+ (tx) => s.tryStartRunOnTx(
1661
+ tx,
1662
+ b,
1663
+ Facts.flowStarted({ runId: b, flowId, input: {}, at: /* @__PURE__ */ new Date() }),
1664
+ { key: "k", mode: "cancel-in-progress" }
1665
+ )
1666
+ );
1667
+ ok(res.started, "b started");
1668
+ eq(
1669
+ res.canceled.map((c) => [c.runId, c.fact.canceledByRunId]),
1670
+ [[a, b]],
1671
+ "a canceled by b"
1672
+ );
1673
+ eq((await s.loadRunState(a)).phase.tag, "canceled", "a folds canceled");
1674
+ eq((await s.describe(a))?.run.canceledByRunId, b, "describe(a)");
1675
+ }
1676
+ },
1677
+ {
1678
+ name: "events: watchRuns sees flow.started from both tryStartRun and tryStartRunOnTx",
1679
+ async run(h) {
1680
+ const s = await h.makeStore({ leaseMs: LEASE_MS });
1681
+ const seen = recordRuns(s);
1682
+ if (seen === null) return;
1683
+ const own = rid();
1684
+ const onTx = rid();
1685
+ await startRun(s, own);
1686
+ await h.withTx(
1687
+ s,
1688
+ (tx) => s.tryStartRunOnTx(
1689
+ tx,
1690
+ onTx,
1691
+ Facts.flowStarted({
1692
+ runId: onTx,
1693
+ flowId: "f",
1694
+ input: {},
1695
+ at: /* @__PURE__ */ new Date()
1696
+ })
1697
+ )
1698
+ );
1699
+ await eventually(
1700
+ () => typesFor(seen, own).includes("flow.started"),
1701
+ "tryStartRun must announce flow.started"
1702
+ );
1703
+ await eventually(
1704
+ () => typesFor(seen, onTx).includes("flow.started"),
1705
+ "tryStartRunOnTx must announce flow.started once its tx commits"
1706
+ );
1707
+ }
1708
+ },
1709
+ {
1710
+ name: "events: watchRun sees step events in order and ends on the terminal event",
1711
+ async run(h) {
1712
+ const s = await h.makeStore({ leaseMs: LEASE_MS });
1713
+ if (s.events === void 0) return;
1714
+ const runId = rid();
1715
+ const seen = [];
1716
+ s.events.watchRun(runId, (e) => seen.push(e));
1717
+ await startRun(s, runId);
1718
+ await startStep(s, runId, "s");
1719
+ await s.appendFact(
1720
+ runId,
1721
+ Facts.stepCompleted(runId, "s", A1, { ok: 1 }, /* @__PURE__ */ new Date())
1722
+ );
1723
+ await s.appendFact(
1724
+ runId,
1725
+ Facts.stepAbortRequested({
1726
+ runId,
1727
+ stepId: "s",
1728
+ attempt: A1,
1729
+ at: /* @__PURE__ */ new Date()
1730
+ })
1731
+ );
1732
+ await endRun(s, runId, "completed");
1733
+ const want = [
1734
+ "flow.started",
1735
+ "step.started",
1736
+ "step.completed",
1737
+ "flow.completed"
1738
+ ];
1739
+ await eventually(() => seen.length >= want.length, "all four events");
1740
+ eq(
1741
+ seen.map((e) => e.type),
1742
+ want,
1743
+ "bookkeeping facts are not events"
1744
+ );
1745
+ }
1746
+ },
1747
+ {
1748
+ name: "events: a superseded run announces flow.canceled naming its superseder",
1749
+ async run(h) {
1750
+ const s = await h.makeStore({ leaseMs: LEASE_MS });
1751
+ const seen = recordRuns(s);
1752
+ if (seen === null) return;
1753
+ const flowId = fid();
1754
+ const a = rid();
1755
+ const b = rid();
1756
+ await startRun(s, a, { flowId, concurrencyKey: "k" });
1757
+ await startRun(s, b, { flowId, concurrencyKey: "k" });
1758
+ await eventually(
1759
+ () => seen.some((e) => e.runId === a && e.type === "flow.canceled"),
1760
+ "a's cancellation is announced"
1761
+ );
1762
+ eq(
1763
+ seen.find((e) => e.runId === a && e.type === "flow.canceled"),
1764
+ {
1765
+ type: "flow.canceled",
1766
+ cause: "concurrency",
1767
+ canceledByRunId: b,
1768
+ runId: a
1769
+ },
1770
+ "cancel event"
1771
+ );
1772
+ }
1773
+ },
1774
+ {
1775
+ name: "stream: a subscriber receives published chunks, then closes on step.completed",
1776
+ async run(h) {
1777
+ const s = await h.makeStore({ leaseMs: LEASE_MS });
1778
+ if (s.stream === void 0) return;
1779
+ const runId = rid();
1780
+ await startRun(s, runId);
1781
+ await startStep(s, runId, "s", { kind: "streaming" });
1782
+ const events = drain(s.stream.subscribeStream(runId, "s"), "completed");
1783
+ s.stream.publishChunk(runId, "s", "a");
1784
+ s.stream.publishChunk(runId, "s", "b");
1785
+ await s.appendFact(
1786
+ runId,
1787
+ Facts.stepCompleted(runId, "s", A1, null, /* @__PURE__ */ new Date())
1788
+ );
1789
+ eq(
1790
+ await events,
1791
+ [
1792
+ { kind: "chunk", chunk: "a" },
1793
+ { kind: "chunk", chunk: "b" }
1794
+ ],
1795
+ "chunks in order, then closed"
1796
+ );
1797
+ }
1798
+ },
1799
+ {
1800
+ name: "stream: step.failed closes with the error; a run end closes a step that never emitted",
1801
+ async run(h) {
1802
+ const s = await h.makeStore({ leaseMs: LEASE_MS });
1803
+ if (s.stream === void 0) return;
1804
+ const runId = rid();
1805
+ await startRun(s, runId);
1806
+ await startStep(s, runId, "bad", { kind: "streaming" });
1807
+ await startStep(s, runId, "quiet", { kind: "streaming" });
1808
+ const bad = drain(s.stream.subscribeStream(runId, "bad"), "failed");
1809
+ const quiet = drain(s.stream.subscribeStream(runId, "quiet"), "run end");
1810
+ const error = { name: "E", message: "x" };
1811
+ await s.appendFact(
1812
+ runId,
1813
+ Facts.stepFailed(runId, "bad", A1, error, /* @__PURE__ */ new Date())
1814
+ );
1815
+ eq(await bad, [{ kind: "error", error }], "error event, then closed");
1816
+ await endRun(s, runId, "canceled");
1817
+ eq(await quiet, [], "closed by the run end");
1818
+ }
1819
+ },
1820
+ {
1821
+ name: "stream: subscribing to an already-settled step closes instead of hanging",
1822
+ async run(h) {
1823
+ const s = await h.makeStore({ leaseMs: LEASE_MS });
1824
+ if (s.stream === void 0) return;
1825
+ const runId = rid();
1826
+ await startRun(s, runId);
1827
+ await startStep(s, runId, "s", { kind: "streaming" });
1828
+ await s.appendFact(
1829
+ runId,
1830
+ Facts.stepCompleted(runId, "s", A1, null, /* @__PURE__ */ new Date())
1831
+ );
1832
+ eq(
1833
+ await drain(s.stream.subscribeStream(runId, "s"), "settled step"),
1834
+ [],
1835
+ "empty and closed"
1836
+ );
1837
+ }
1838
+ },
1839
+ {
1840
+ name: "sweepLeases: a failing enqueue leaves nothing half-reaped \u2014 the lease stays reapable and no lease.reaped is written",
1841
+ async run(h) {
1842
+ const s = await h.makeStore({ leaseMs: SHORT_LEASE_MS });
1843
+ const runId = rid();
1844
+ await startRun(s, runId);
1845
+ await startStep(s, runId, "s");
1846
+ ok(await s.claimStep(runId, "s", A1) !== null, "claim");
1847
+ await sleep(PAST_LEASE_MS);
1848
+ await rejects(
1849
+ s.sweepLeases({ now: /* @__PURE__ */ new Date(), queue: failingQueue() }),
1850
+ "the enqueue failure surfaces"
1851
+ );
1852
+ eq(
1853
+ (await s.loadRunState(runId)).facts.filter(
1854
+ (f) => f.kind === "lease.reaped"
1855
+ ).length,
1856
+ 0,
1857
+ "no lease.reaped"
1858
+ );
1859
+ eq(
1860
+ (await s.sweepLeases({ now: /* @__PURE__ */ new Date(), queue: new InMemoryQueue() })).map((r) => r.runId),
1861
+ [runId],
1862
+ "the next sweep still reaps it"
1863
+ );
1864
+ }
1444
1865
  }
1445
1866
  ];
1446
1867