@protobase/workflows 0.72.2 → 0.73.1

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.
@@ -75,10 +75,13 @@ export type LoadedRun = {
75
75
  status: RunStatus;
76
76
  startedAt: Date;
77
77
  /**
78
- * The run this one replays: its steps that write are not called but give what that run's steps gave; null when that
79
- * run is gone, so they give nothing. Absent: no replay.
78
+ * The run this one replays, with the definition it ran: its steps that write are not called but give what that
79
+ * run's steps gave; null when that run is gone, so they give nothing. Absent: no replay.
80
80
  */
81
- replayOf?: string | null;
81
+ replayOf?: {
82
+ id: string;
83
+ definition: Definition;
84
+ } | null;
82
85
  };
83
86
  export type RunStatus = 'queued' | 'running' | 'waiting' | 'succeeded' | 'failed';
84
87
  /** What changes on a run as a segment ends. */
@@ -0,0 +1,84 @@
1
+ //#region src/run/replay-match.ts
2
+ /** A Map item's scope segment, as `innerScope` writes it: the Map's name, its step's number and the item's index. */
3
+ const segmentPattern = /^(.*)\.(\d+)\[(\d+)\]$/;
4
+ /**
5
+ * Which visit of `state` in its scope the step at `seq` belongs to, from 0: the visits that began before it, less
6
+ * its own when it is a retry, whose step comes right after the try that failed.
7
+ */
8
+ const visitAt = (rows, state, seq) => {
9
+ const begun = rows.filter((row) => row.state === state && row.attempt === 1 && row.seq < seq).length;
10
+ return rows.some((row) => row.seq === seq - 1 && row.state === state && row.status === "retrying") ? begun - 1 : begun;
11
+ };
12
+ /**
13
+ * A scope named by each Map's visit rather than its step's number, so states added or removed before a Map do not
14
+ * change the names of its items' scopes; a scope with no steps yet, such as the run's own while the Map that starts it
15
+ * runs, has no earlier visits.
16
+ */
17
+ const logicalScope = (scope, visit) => {
18
+ if (scope === "") return "";
19
+ let parent = "";
20
+ const names = [];
21
+ for (const segment of scope.split("/")) {
22
+ const [, name, seq, index] = segmentPattern.exec(segment) ?? [];
23
+ if (name === void 0) return;
24
+ names.push(`${name}#${visit(parent, decodeURIComponent(name), Number(seq))}[${index}]`);
25
+ parent = parent ? `${parent}/${segment}` : segment;
26
+ }
27
+ return names.join("/");
28
+ };
29
+ const keyOf = (logical, state, visit) => `${logical}|${encodeURIComponent(state)}|${visit}`;
30
+ /** What a step is matched by between a run and its replay: its scope by visits, its state, and its visit of that state. */
31
+ const matchKey = (rows, scope, state, seq) => {
32
+ const visit = (at, name, from) => visitAt(rows.get(at) ?? [], name, from);
33
+ const logical = logicalScope(scope, visit);
34
+ if (logical === void 0) return;
35
+ return keyOf(logical, state, visit(scope, state, seq));
36
+ };
37
+ /**
38
+ * The visit of each step of a run, by its scope and seq, counted in one pass over the steps in seq order: what
39
+ * `visitAt` gives each of them, without scanning its scope again for every step.
40
+ */
41
+ const stepVisits = (sorted) => {
42
+ const begun = /* @__PURE__ */ new Map();
43
+ const last = /* @__PURE__ */ new Map();
44
+ const visits = /* @__PURE__ */ new Map();
45
+ for (const step of sorted) {
46
+ const counted = `${step.scope}|${encodeURIComponent(step.state)}`;
47
+ const before = begun.get(counted) ?? 0;
48
+ const previous = last.get(step.scope);
49
+ const retry = previous?.seq === step.seq - 1 && previous.state === step.state && previous.status === "retrying";
50
+ visits.set(`${step.scope}|${step.seq}`, retry ? before - 1 : before);
51
+ if (step.attempt === 1) begun.set(counted, before + 1);
52
+ last.set(step.scope, step);
53
+ }
54
+ return visits;
55
+ };
56
+ /** A run's steps by scope. */
57
+ const rowsByScope = (steps) => {
58
+ const rows = /* @__PURE__ */ new Map();
59
+ for (const step of steps) {
60
+ const scopeRows = rows.get(step.scope);
61
+ if (scopeRows) scopeRows.push(step);
62
+ else rows.set(step.scope, [step]);
63
+ }
64
+ return rows;
65
+ };
66
+ /** The last try of each visit of each state of a run, by its match key, from one pass over its steps. */
67
+ const visitOutcomes = (steps) => {
68
+ const sorted = [...steps].sort((a, b) => a.seq - b.seq);
69
+ const rows = rowsByScope(sorted);
70
+ const visits = stepVisits(sorted);
71
+ const visit = (scope, state, seq) => visits.get(`${scope}|${seq}`) ?? visitAt(rows.get(scope) ?? [], state, seq);
72
+ const scopes = /* @__PURE__ */ new Map();
73
+ const outcomes = /* @__PURE__ */ new Map();
74
+ for (const step of sorted) {
75
+ if (!scopes.has(step.scope)) scopes.set(step.scope, logicalScope(step.scope, visit));
76
+ const logical = scopes.get(step.scope);
77
+ if (logical !== void 0) outcomes.set(keyOf(logical, step.state, visits.get(`${step.scope}|${step.seq}`)), step);
78
+ }
79
+ return outcomes;
80
+ };
81
+ /** The Map names a scope runs inside, outermost first. */
82
+ const mapNames = (scope) => scope === "" ? [] : scope.split("/").map((segment) => decodeURIComponent(segmentPattern.exec(segment)?.[1] ?? ""));
83
+ //#endregion
84
+ export { mapNames, matchKey, rowsByScope, visitOutcomes };
@@ -0,0 +1,9 @@
1
+ import { Definition } from "../definition/types.js";
2
+ import { SavedStep } from "./port.js";
3
+ //#region src/run/replay-of.d.ts
4
+ /** The run a replay replays: the definition it ran and its steps. */
5
+ export type Replayed = {
6
+ definition: Definition;
7
+ steps: readonly SavedStep[];
8
+ };
9
+ //#endregion
@@ -0,0 +1,21 @@
1
+ import { rowsByScope, visitOutcomes } from "./replay-match.js";
2
+ //#region src/run/replay-of.ts
3
+ /**
4
+ * What a replay matches its held-back steps by: the replayed run's last try of each visit, the definition it ran,
5
+ * and the replay's own steps so far, by scope, which `seen` adds to as the replay saves them.
6
+ */
7
+ const replayOf = (replayed, saved) => {
8
+ const seen = rowsByScope(saved);
9
+ return {
10
+ outcomes: visitOutcomes(replayed.steps),
11
+ machine: replayed.definition.stateMachine,
12
+ seen,
13
+ add: (step) => {
14
+ const rows = seen.get(step.scope);
15
+ if (rows) rows.push(step);
16
+ else seen.set(step.scope, [step]);
17
+ }
18
+ };
19
+ };
20
+ //#endregion
21
+ export { replayOf };
@@ -1,39 +1,43 @@
1
+ import { mapNames, matchKey } from "./replay-match.js";
1
2
  //#region src/run/replay.ts
2
3
  /** The log line of a step a replay held back, which the run's page marks it by. */
3
4
  const heldBackLog = "Not sent: replay";
4
- const keyOf = (scope, seq) => `${scope}#${seq}`;
5
- const replayedSteps = (steps) => new Map(steps.map((step) => [keyOf(step.scope, step.seq), step]));
6
5
  /** Whether a replay holds back this call: anything but its type saying `false`, it writes. */
7
6
  const heldBack = (context, handler, args) => Boolean(context.replay) && handler?.writes?.(args) !== false;
7
+ /** The replayed run's state of this name in the scope of these Map names. */
8
+ const stateIn = (machine, maps, name) => {
9
+ let inner = machine;
10
+ for (const map of maps) {
11
+ const state = inner?.States[map];
12
+ inner = state?.Type === "Map" ? state.ItemProcessor : void 0;
13
+ }
14
+ return inner?.States[name];
15
+ };
8
16
  /**
9
- * A Task a replay holds back: it ends as the replayed run's step of the same scope, number and state ended, with its
10
- * output and variables, or with a null output and on to its next state when that run has no such step.
17
+ * What a held-back step takes from the replayed run's step of the same state and visit of it in the same scope: its
18
+ * error, or its result, which only a Task that did not shape it with `Output` saved as it was. Undefined when that
19
+ * run has no such step, its step was still retrying, or saved its result shaped.
11
20
  */
12
- const replayedTask = (context, state, at, input, logs) => {
13
- logs.push({
14
- at: context.now().toISOString(),
15
- message: heldBackLog
16
- });
17
- const step = context.replay?.steps.get(keyOf(at.scope, at.seq));
18
- if (!step || step.state !== at.name) return {
19
- kind: "step",
20
- status: "succeeded",
21
- next: state.Next ?? null,
22
- input,
23
- output: null,
24
- logs
25
- };
26
- return {
27
- kind: "step",
28
- status: step.status,
29
- next: step.next,
30
- input,
31
- output: step.output ?? null,
32
- ...step.assigned && { assigned: step.assigned },
33
- ...step.error != null && { error: step.error },
34
- ...step.cause != null && { cause: step.cause },
35
- logs
36
- };
21
+ const replayedOutcome = (replay, at) => {
22
+ const key = matchKey(replay.seen, at.scope, at.name, at.seq);
23
+ const step = key === void 0 ? void 0 : replay.outcomes.get(key);
24
+ if (!step || step.status === "retrying") return;
25
+ if (step.status !== "succeeded") return { failure: {
26
+ Error: step.error ?? "States.Runtime",
27
+ Cause: step.cause ?? ""
28
+ } };
29
+ const state = stateIn(replay.machine, mapNames(at.scope), at.name);
30
+ if (state?.Type !== "Task" || state.Output !== void 0) return;
31
+ return { result: step.output ?? null };
37
32
  };
33
+ /** A held-back step the replayed run gave nothing for: a null output, on to its next state. */
34
+ const emptyTask = (state, input, logs) => ({
35
+ kind: "step",
36
+ status: "succeeded",
37
+ next: state.Next ?? null,
38
+ input,
39
+ output: null,
40
+ logs
41
+ });
38
42
  //#endregion
39
- export { heldBack, heldBackLog, replayedSteps, replayedTask };
43
+ export { emptyTask, heldBack, heldBackLog, replayedOutcome };
@@ -1,7 +1,7 @@
1
1
  import { limits } from "../limits.js";
2
2
  import { StepError, errorOutput } from "./errors.js";
3
3
  import { redacted } from "./redact.js";
4
- import { heldBack, replayedTask } from "./replay.js";
4
+ import { emptyTask, heldBack, heldBackLog, replayedOutcome } from "./replay.js";
5
5
  import { jsonBytes } from "./json-bytes.js";
6
6
  import { evaluateAssign, evaluateKept, evaluateTemplate, recordedArguments } from "./evaluate.js";
7
7
  import { fanOut } from "./fan-out.js";
@@ -76,21 +76,36 @@ const attempt = async (state, call) => {
76
76
  };
77
77
  }
78
78
  };
79
+ const withReplayed = async (state, call) => {
80
+ const ran = await attempt(state, call);
81
+ if ("kind" in ran || !("held" in ran)) return ran;
82
+ call.logs.push({
83
+ at: call.context.now().toISOString(),
84
+ message: heldBackLog
85
+ });
86
+ const outcome = replayedOutcome(call.context.replay, {
87
+ scope: call.scope,
88
+ seq: call.position.seq,
89
+ name: call.name
90
+ });
91
+ if (!outcome) return emptyTask(state, ran.input, call.logs);
92
+ return {
93
+ held: true,
94
+ input: ran.input,
95
+ ...outcome
96
+ };
97
+ };
79
98
  /**
80
99
  * A Task or a Map: its result shaped by `Output` and `Assign`, which read it as `$states.result`; a failure,
81
100
  * its own or an item's, goes to its retriers and catchers.
82
101
  */
83
102
  const runResultState = async (state, call) => {
84
- const ran = await attempt(state, call);
103
+ const ran = await withReplayed(state, call);
85
104
  if ("kind" in ran) return ran;
86
- if ("held" in ran) return replayedTask(call.context, state, {
87
- scope: call.scope,
88
- seq: call.position.seq,
89
- name: call.name
90
- }, ran.input, call.logs);
91
105
  const now = call.context.now();
106
+ const recoverable = "held" in ran ? { ...state.Catch && { Catch: state.Catch } } : state;
92
107
  if ("failure" in ran) return {
93
- ...await recover(state, call.position, ran.failure, call.bindings, now, call.logs),
108
+ ...await recover(recoverable, call.position, ran.failure, call.bindings, now, call.logs),
94
109
  ...ran.input !== void 0 && { input: ran.input }
95
110
  };
96
111
  const after = {
@@ -109,7 +124,7 @@ const runResultState = async (state, call) => {
109
124
  return { failure: errorOutput(error) };
110
125
  });
111
126
  if ("failure" in done) return {
112
- ...await recover(state, call.position, done.failure, call.bindings, now, call.logs),
127
+ ...await recover(recoverable, call.position, done.failure, call.bindings, now, call.logs),
113
128
  input: ran.input
114
129
  };
115
130
  return {
@@ -34,7 +34,13 @@ const createRunner = ({ store, queue, tasks, cache, secrets = {}, now = () => /*
34
34
  budgetMs,
35
35
  maxSteps
36
36
  };
37
- const replayed = run.replayOf === void 0 ? void 0 : run.replayOf === null ? [] : await store.steps(db, run.replayOf);
37
+ const replayed = run.replayOf === void 0 ? void 0 : run.replayOf === null ? {
38
+ definition: run.definition,
39
+ steps: []
40
+ } : {
41
+ definition: run.replayOf.definition,
42
+ steps: await store.steps(db, run.replayOf.id)
43
+ };
38
44
  const outcome = await runSegment({
39
45
  ...segment,
40
46
  ...replayed && { replayed },
@@ -2,6 +2,7 @@ import { Definition } from "../definition/types.js";
2
2
  import { Redactor } from "./redact.js";
3
3
  import { StepCacheStore } from "./cache/cache-port.js";
4
4
  import { SavedStep, StepRecord, TaskHandlers } from "./port.js";
5
+ import { Replayed } from "./replay-of.js";
5
6
  import { ScopeOutcome } from "./context.js";
6
7
  //#region src/run/segment.d.ts
7
8
  export type SegmentInput = {
@@ -21,8 +22,8 @@ export type SegmentInput = {
21
22
  tasks: TaskHandlers;
22
23
  /** Where step types that cache keep their results; none keeps nothing. */
23
24
  cache?: StepCacheStore;
24
- /** In a replay, the steps of the run it replays. */
25
- replayed?: readonly SavedStep[];
25
+ /** In a replay, the run it replays. */
26
+ replayed?: Replayed;
26
27
  signal: AbortSignal;
27
28
  now?: () => Date;
28
29
  /** How long the segment takes new steps. Default `limits.segmentMs`. */
@@ -1,7 +1,7 @@
1
1
  import { limits } from "../limits.js";
2
2
  import { SupersededError } from "./errors.js";
3
- import { replayedSteps } from "./replay.js";
4
3
  import { secretNamer } from "./cache/secret-names.js";
4
+ import { replayOf } from "./replay-of.js";
5
5
  import { runScope } from "./scope.js";
6
6
  //#region src/run/segment.ts
7
7
  /**
@@ -16,6 +16,7 @@ const runSegment = async ({ runId, definition, input, startedAt, secrets, redact
16
16
  else byScope.set(step.scope, [step]);
17
17
  }
18
18
  let superseded = false;
19
+ const replay = replayed && replayOf(replayed, saved);
19
20
  let kept = [];
20
21
  const write = async () => {
21
22
  const steps = kept;
@@ -39,13 +40,14 @@ const runSegment = async ({ runId, definition, input, startedAt, secrets, redact
39
40
  store: cache,
40
41
  nameSecrets: secretNamer(secrets)
41
42
  } },
42
- ...replayed && { replay: { steps: replayedSteps(replayed) } },
43
+ ...replay && { replay },
43
44
  signal,
44
45
  now,
45
46
  deadline: Date.now() + budgetMs,
46
47
  saved: byScope,
47
48
  save: async (step, checkpoint) => {
48
49
  kept.push(step);
50
+ replay?.add(step);
49
51
  if (checkpoint) await write();
50
52
  },
51
53
  superseded: () => superseded,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@protobase/workflows",
3
- "version": "0.72.2",
3
+ "version": "0.73.1",
4
4
  "description": "Workflows as state machines with JSONata expressions: their check, a runner that saves every step, and the plugin interface for trigger and step types.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {