@protobase/workflows 0.76.3 → 0.77.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,19 +1,21 @@
1
1
  import { Machine } from "../definition/types.js";
2
- import { SavedStep } from "./port.js";
2
+ import { Checkpoint } from "./port.js";
3
3
  //#region src/run/rerun.d.ts
4
- /** What a re-run reads of a failed run's step to know whether to keep it. */
5
- export type EarlierStep = Pick<SavedStep, 'scope' | 'seq' | 'state' | 'status' | 'next'>;
4
+ /** What a re-run reads of a failed run's checkpoint to know where its scope goes on. */
5
+ export type EarlierCheckpoint = Pick<Checkpoint, 'scope' | 'next'>;
6
6
  /**
7
- * The steps of a failed run that a re-run of it keeps, to run on from where they leave it with `machine`, the workflow's
8
- * version now: every step but, in each scope, the try that failed it and that state's retried tries before it, so the
9
- * failed state runs again from its first try. A finished Map's items are kept as they ran; the items of a Map that runs
10
- * again are kept where they stand, each without its own failed try, and those of a Map's earlier tries are not.
11
- * Returns the problem instead when a scope would go on at a state the version does not have.
7
+ * The problem with re-running a failed run whose scopes stand at `checkpoints` on `machine`, the workflow's version
8
+ * now: a scope that would go on at a state, or in a Map, the version does not have; undefined when there is none.
9
+ * Scopes that ended stay as they ran.
10
+ * A re-run goes on from each scope's last checkpoint, as a run does after a crash: the steps since run again, the
11
+ * recorded ones before it never.
12
12
  */
13
- export declare const rerunSteps: <S extends EarlierStep>(machine: Machine, steps: readonly S[]) => {
14
- steps: S[];
15
- } | {
16
- problem: string;
13
+ export declare const rerunProblem: (machine: Machine, checkpoints: readonly EarlierCheckpoint[]) => string | undefined;
14
+ /** A failed run's checkpoint as its re-run, started at `clock`, takes it up: the state it goes on at from its first try, now. */
15
+ export declare const rerunCheckpoint: <C extends Checkpoint>({ resumeAt: _, ...checkpoint }: C, clock: Date) => Omit<C, "resumeAt"> & {
16
+ attempt: number;
17
+ failures: never[];
18
+ clock: Date;
17
19
  };
18
20
  /** How a state keeps its whole result in a variable. */
19
21
  export declare const resultRead = "{% $states.result %}";
@@ -33,15 +35,4 @@ export declare const keptAssigned: (machine: Machine, ran: Machine, step: {
33
35
  }) => {
34
36
  [x: string]: unknown;
35
37
  } | undefined;
36
- /**
37
- * The steps of an ended run that a re-run from `state`, a state of the workflow itself and not of a Map, keeps: those
38
- * before its first visit, with the items of the Maps among them as they ran, so the run goes on at `state` with `machine`,
39
- * the workflow's version now, and everything from there runs again. Returns the problem instead when the run never
40
- * reached it, or the version does not have it or starts elsewhere.
41
- */
42
- export declare const rerunFromSteps: <S extends EarlierStep>(machine: Machine, steps: readonly S[], state: string) => {
43
- steps: S[];
44
- } | {
45
- problem: string;
46
- };
47
38
  //#endregion
package/dist/run/rerun.js CHANGED
@@ -1,64 +1,40 @@
1
1
  import { expressionSource } from "../definition/expressions.js";
2
2
  //#region src/run/rerun.ts
3
- const itemOf = (scope) => {
4
- const slash = scope.lastIndexOf("/");
5
- const match = /^(.*)\.(\d+)\[\d+\]$/.exec(scope.slice(slash + 1));
6
- if (!match) throw new Error(`"${scope}" is not the scope of a Map item`);
7
- return {
8
- parent: slash < 0 ? "" : scope.slice(0, slash),
9
- map: decodeURIComponent(match[1]),
10
- seq: Number(match[2])
11
- };
12
- };
13
- const withoutFailure = (steps) => {
14
- if (steps.at(-1)?.status !== "failed") return [...steps];
15
- const failed = steps.at(-1);
16
- let end = steps.length - 1;
17
- while (end > 0 && steps[end - 1].status === "retrying" && steps[end - 1].state === failed.state) end--;
18
- return steps.slice(0, end);
3
+ const machineOf = (machine, scope) => {
4
+ if (scope === "") return machine;
5
+ let inner = machine;
6
+ for (const part of scope.split("/")) {
7
+ const match = /^(.*)\.\d+\[\d+\]$/.exec(part);
8
+ if (!match) throw new Error(`"${scope}" is not the scope of a Map item`);
9
+ const name = decodeURIComponent(match[1]);
10
+ const state = inner.States[name];
11
+ if (state?.Type !== "Map") return `The run goes on in the Map "${name}"${scope.includes("/") ? ` of ${scope}` : ""}, which the workflow no longer has`;
12
+ inner = state.ItemProcessor;
13
+ }
14
+ return inner;
19
15
  };
20
16
  /**
21
- * The steps of a failed run that a re-run of it keeps, to run on from where they leave it with `machine`, the workflow's
22
- * version now: every step but, in each scope, the try that failed it and that state's retried tries before it, so the
23
- * failed state runs again from its first try. A finished Map's items are kept as they ran; the items of a Map that runs
24
- * again are kept where they stand, each without its own failed try, and those of a Map's earlier tries are not.
25
- * Returns the problem instead when a scope would go on at a state the version does not have.
17
+ * The problem with re-running a failed run whose scopes stand at `checkpoints` on `machine`, the workflow's version
18
+ * now: a scope that would go on at a state, or in a Map, the version does not have; undefined when there is none.
19
+ * Scopes that ended stay as they ran.
20
+ * A re-run goes on from each scope's last checkpoint, as a run does after a crash: the steps since run again, the
21
+ * recorded ones before it never.
26
22
  */
27
- const rerunSteps = (machine, steps) => {
28
- const byScope = /* @__PURE__ */ new Map();
29
- for (const step of [...steps].sort((a, b) => a.seq - b.seq)) byScope.set(step.scope, [...byScope.get(step.scope) ?? [], step]);
30
- const children = /* @__PURE__ */ new Map();
31
- for (const scope of byScope.keys()) {
32
- if (scope === "") continue;
33
- const { parent } = itemOf(scope);
34
- children.set(parent, [...children.get(parent) ?? [], scope]);
23
+ const rerunProblem = (machine, checkpoints) => {
24
+ for (const { scope, next } of checkpoints) {
25
+ if (next === null) continue;
26
+ const inner = machineOf(machine, scope);
27
+ if (typeof inner === "string") return inner;
28
+ if (!Object.hasOwn(inner.States, next)) return `The run goes on at state "${next}"${scope ? ` in ${scope}` : ""}, which the workflow no longer has`;
35
29
  }
36
- const kept = [];
37
- const keepAll = (scope) => {
38
- kept.push(...byScope.get(scope) ?? []);
39
- for (const child of children.get(scope) ?? []) keepAll(child);
40
- };
41
- const keepFrom = (scope, inner) => {
42
- const own = withoutFailure(byScope.get(scope) ?? []);
43
- kept.push(...own);
44
- const last = own.at(-1);
45
- const at = last === void 0 ? inner.StartAt : last.status === "retrying" ? last.state : last.next;
46
- if (at !== null && !Object.hasOwn(inner.States, at)) return `The run goes on at state "${at}"${scope ? ` in ${scope}` : ""}, which the workflow no longer has`;
47
- const state = at === null ? void 0 : inner.States[at];
48
- const ran = new Set(own.map((step) => step.seq));
49
- const next = last === void 0 ? 0 : last.seq + 1;
50
- for (const child of children.get(scope) ?? []) {
51
- const item = itemOf(child);
52
- if (ran.has(item.seq)) keepAll(child);
53
- else if (item.seq === next && item.map === at && state?.Type === "Map") {
54
- const problem = keepFrom(child, state.ItemProcessor);
55
- if (problem) return problem;
56
- }
57
- }
58
- };
59
- const problem = keepFrom("", machine);
60
- return problem ? { problem } : { steps: kept };
61
30
  };
31
+ /** A failed run's checkpoint as its re-run, started at `clock`, takes it up: the state it goes on at from its first try, now. */
32
+ const rerunCheckpoint = ({ resumeAt: _, ...checkpoint }, clock) => ({
33
+ ...checkpoint,
34
+ attempt: 1,
35
+ failures: [],
36
+ clock
37
+ });
62
38
  /** How a state keeps its whole result in a variable. */
63
39
  const resultRead = "{% $states.result %}";
64
40
  /**
@@ -80,22 +56,5 @@ const keptAssigned = (machine, ran, step) => {
80
56
  ...Object.fromEntries(whole.map((name) => [name, step.output]))
81
57
  };
82
58
  };
83
- /**
84
- * The steps of an ended run that a re-run from `state`, a state of the workflow itself and not of a Map, keeps: those
85
- * before its first visit, with the items of the Maps among them as they ran, so the run goes on at `state` with `machine`,
86
- * the workflow's version now, and everything from there runs again. Returns the problem instead when the run never
87
- * reached it, or the version does not have it or starts elsewhere.
88
- */
89
- const rerunFromSteps = (machine, steps, state) => {
90
- const own = steps.filter((step) => step.scope === "").sort((a, b) => a.seq - b.seq);
91
- const from = own.findIndex((step) => step.state === state);
92
- if (from === -1) return { problem: `The run never reached state "${state}"` };
93
- if (!Object.hasOwn(machine.States, state)) return { problem: `The workflow no longer has state "${state}"` };
94
- if (from === 0 && machine.StartAt !== state) return { problem: `The workflow no longer starts at state "${state}"` };
95
- const kept = own.slice(0, from);
96
- const seqs = new Set(kept.map((step) => step.seq));
97
- const inner = steps.filter((step) => step.scope !== "" && seqs.has(itemOf(step.scope.split("/")[0]).seq));
98
- return { steps: [...kept, ...inner] };
99
- };
100
59
  //#endregion
101
- export { keptAssigned, rerunFromSteps, rerunSteps, resultRead };
60
+ export { keptAssigned, rerunCheckpoint, rerunProblem, resultRead };
@@ -6,25 +6,30 @@ import { jsonBytes } from "./json-bytes.js";
6
6
  import { evaluateAssign, evaluateKept, evaluateTemplate, recordedArguments } from "./evaluate.js";
7
7
  import { fanOut } from "./fan-out.js";
8
8
  import { recover } from "./recovery.js";
9
- import { innerScope, visibleVariables } from "./step-input.js";
9
+ import { stepFunctions } from "./step-functions.js";
10
+ import { visibleVariables } from "./step-input.js";
10
11
  import { runTask } from "./task.js";
11
12
  //#region src/run/result-states.ts
12
13
  const task = async (state, call) => {
13
14
  const args = await evaluateTemplate(state.Arguments ?? {}, call.bindings, "Arguments");
14
15
  const key = `${call.context.runId}/${call.scope}/${call.position.seq - call.position.attempt + 1}`;
15
16
  const input = redacted(recordedArguments(state.Arguments ?? {}, args));
16
- if (heldBack(call.context, call.context.tasks[state.Resource], args)) return {
17
+ const handler = call.context.tasks[state.Resource];
18
+ if (heldBack(call.context, handler, args)) return {
17
19
  held: true,
18
20
  input
19
21
  };
22
+ const recorded = handler?.writes?.(args) !== false;
20
23
  return runTask(call.context, state, args, key, call.logs).then((result) => ({
21
24
  result,
22
- input
25
+ input,
26
+ recorded
23
27
  }), (error) => {
24
28
  if (!(error instanceof StepError)) throw error;
25
29
  return {
26
30
  failure: errorOutput(error),
27
- input
31
+ input,
32
+ recorded
28
33
  };
29
34
  });
30
35
  };
@@ -35,14 +40,14 @@ const map = async (state, call) => {
35
40
  const outer = visibleVariables(call.bindings);
36
41
  let kept = 0;
37
42
  const scopes = items.map((item, index) => async () => {
38
- const outcome = await call.runScope(state.ItemProcessor, innerScope(call.scope, call.name, call.position.seq, index), item, outer);
43
+ const outcome = await call.runScope(state.ItemProcessor, index, item, outer);
39
44
  if (outcome.kind !== "ended") return outcome;
40
45
  kept += jsonBytes(outcome.output);
41
46
  if (kept <= limits.valueBytes) return outcome;
42
47
  return {
43
48
  kind: "failed",
44
49
  error: "States.DataLimitExceeded",
45
- cause: `The items' outputs are larger than ${limits.valueBytes / 1024 / 1024} MiB together`
50
+ cause: `The items' outputs come to ${kept} bytes as JSON so far, over the ${limits.valueBytes / 1024} KiB a value is kept up to`
46
51
  };
47
52
  });
48
53
  const outcome = await fanOut(scopes, state.MaxConcurrency || limits.mapConcurrency);
@@ -85,7 +90,8 @@ const withReplayed = async (state, call) => {
85
90
  });
86
91
  const outcome = replayedOutcome(call.context.replay, {
87
92
  scope: call.scope,
88
- seq: call.position.seq,
93
+ logical: call.logical,
94
+ visit: call.visit,
89
95
  name: call.name
90
96
  });
91
97
  if (!outcome) return emptyTask(state, ran.input, call.logs);
@@ -97,19 +103,28 @@ const withReplayed = async (state, call) => {
97
103
  };
98
104
  /**
99
105
  * A Task or a Map: its result shaped by `Output` and `Assign`, which read it as `$states.result`; a failure,
100
- * its own or an item's, goes to its retriers and catchers.
106
+ * its own or an item's, goes to its retriers and catchers. In a recorded Task's `Output` and `Assign`, `$now` is when
107
+ * its result was fetched, which the checkpoint keeps as the scope's clock.
101
108
  */
102
109
  const runResultState = async (state, call) => {
103
110
  const ran = await withReplayed(state, call);
104
111
  if ("kind" in ran) return ran;
105
112
  const now = call.context.now();
113
+ const recorded = { ...ran.recorded && {
114
+ recorded: true,
115
+ fetchedAt: now
116
+ } };
106
117
  const recoverable = "held" in ran ? { ...state.Catch && { Catch: state.Catch } } : state;
107
118
  if ("failure" in ran) return {
108
119
  ...await recover(recoverable, call.position, ran.failure, call.bindings, now, call.logs),
109
- ...ran.input !== void 0 && { input: ran.input }
120
+ ...ran.input !== void 0 && { input: ran.input },
121
+ ...recorded
110
122
  };
123
+ const { now: fetched, millis } = stepFunctions(ran.recorded ? now : call.position.clock, "");
111
124
  const after = {
112
125
  ...call.bindings,
126
+ now: fetched,
127
+ millis,
113
128
  states: {
114
129
  ...call.bindings.states,
115
130
  result: ran.result
@@ -125,7 +140,8 @@ const runResultState = async (state, call) => {
125
140
  });
126
141
  if ("failure" in done) return {
127
142
  ...await recover(recoverable, call.position, done.failure, call.bindings, now, call.logs),
128
- input: ran.input
143
+ input: ran.input,
144
+ ...recorded
129
145
  };
130
146
  return {
131
147
  kind: "step",
@@ -133,7 +149,8 @@ const runResultState = async (state, call) => {
133
149
  next: state.Next ?? null,
134
150
  input: ran.input,
135
151
  ...done,
136
- logs: call.logs
152
+ logs: call.logs,
153
+ ...recorded
137
154
  };
138
155
  };
139
156
  //#endregion
@@ -1,9 +1,10 @@
1
1
  import { StepCacheStore } from "./cache/cache-port.js";
2
- import { RunStore, SegmentQueue, TaskHandlers } from "./port.js";
2
+ import { LoadedRun, RunStore, SegmentQueue, StepRecord, TaskHandlers, TraceMode, TraceSink } from "./port.js";
3
3
  //#region src/run/runner.d.ts
4
4
  /**
5
- * The runner's port: where runs are kept, the queue that runs their segments, the step types, and the secrets
6
- * expressions may read by name, which the runner blanks out of all a run records.
5
+ * The runner's port: where runs are kept, the queue that runs their segments, the step types, the secrets expressions
6
+ * may read by name, which the runner blanks out of all a run records, and where traces go, with the trace a run keeps
7
+ * when neither it nor its definition says (default `all`).
7
8
  */
8
9
  export type RunnerPort<Db> = {
9
10
  store: RunStore<Db>;
@@ -12,6 +13,8 @@ export type RunnerPort<Db> = {
12
13
  /** Where step types that cache keep their results. */
13
14
  cache?: StepCacheStore;
14
15
  secrets?: Readonly<Record<string, string>>;
16
+ trace?: TraceSink;
17
+ traceMode?: TraceMode;
15
18
  now?: () => Date;
16
19
  budgetMs?: number;
17
20
  maxSteps?: number;
@@ -20,11 +23,16 @@ export type RunnerPort<Db> = {
20
23
  * The workflow runner over a port. `start` queues a run's first segment in `db`, which may be the caller's
21
24
  * transaction, so the run starts when it commits; `segment` is what the queue's job runs.
22
25
  */
23
- export declare const createRunner: <Db>({ store, queue, tasks, cache, secrets, now, budgetMs, maxSteps }: RunnerPort<Db>) => {
26
+ export declare const createRunner: <Db>({ store, queue, tasks, cache, secrets, trace, traceMode, now, budgetMs, maxSteps }: RunnerPort<Db>) => {
24
27
  start: (db: Db, runId: string) => Promise<void>;
28
+ /** The steps an ended run's trace holds, which a re-run from one of them starts from: undefined when it kept none. */
29
+ readTrace: (runId: string) => Promise<readonly StepRecord[] | undefined>;
30
+ /** Puts the steps a re-run from a step keeps of an earlier run at the start of `run`'s trace, as the run keeps one. */
31
+ keepSteps: (run: Pick<LoadedRun, "id" | "definition" | "trace">, steps: readonly StepRecord[]) => Promise<void> | undefined;
25
32
  /**
26
- * Runs the run from where it stands to its next wait, then queues the next segment or ends the run. Run again after
27
- * a crash, it takes up from the last saved step: only the step that was in progress runs again.
33
+ * Runs the run from where it stands to its next wait, then queues the next segment or ends the run, and hands the
34
+ * steps it ran to the trace. Run again after a crash, it takes up from each scope's last checkpoint: the steps since
35
+ * run again, recorded calls never.
28
36
  */
29
37
  segment: (db: Db, runId: string, signal: AbortSignal) => Promise<void>;
30
38
  };
@@ -7,13 +7,18 @@ const ended = /* @__PURE__ */ new Set(["succeeded", "failed"]);
7
7
  * The workflow runner over a port. `start` queues a run's first segment in `db`, which may be the caller's
8
8
  * transaction, so the run starts when it commits; `segment` is what the queue's job runs.
9
9
  */
10
- const createRunner = ({ store, queue, tasks, cache, secrets = {}, now = () => /* @__PURE__ */ new Date(), budgetMs = limits.segmentMs, maxSteps = limits.runSteps }) => {
10
+ const createRunner = ({ store, queue, tasks, cache, secrets = {}, trace, traceMode = "all", now = () => /* @__PURE__ */ new Date(), budgetMs = limits.segmentMs, maxSteps = limits.runSteps }) => {
11
11
  secretRedactor(Object.values(secrets));
12
12
  return {
13
13
  start: (db, runId) => queue.schedule(db, runId),
14
+ /** The steps an ended run's trace holds, which a re-run from one of them starts from: undefined when it kept none. */
15
+ readTrace: async (runId) => await trace?.read(runId) ?? void 0,
16
+ /** Puts the steps a re-run from a step keeps of an earlier run at the start of `run`'s trace, as the run keeps one. */
17
+ keepSteps: (run, steps) => trace?.write(run.id, steps, { mode: run.trace ?? run.definition.trace ?? traceMode }),
14
18
  /**
15
- * Runs the run from where it stands to its next wait, then queues the next segment or ends the run. Run again after
16
- * a crash, it takes up from the last saved step: only the step that was in progress runs again.
19
+ * Runs the run from where it stands to its next wait, then queues the next segment or ends the run, and hands the
20
+ * steps it ran to the trace. Run again after a crash, it takes up from each scope's last checkpoint: the steps since
21
+ * run again, recorded calls never.
17
22
  */
18
23
  segment: async (db, runId, signal) => {
19
24
  const run = await store.load(db, runId);
@@ -34,29 +39,45 @@ const createRunner = ({ store, queue, tasks, cache, secrets = {}, now = () => /*
34
39
  budgetMs,
35
40
  maxSteps
36
41
  };
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)
42
+ const replayed = run.replayOf === void 0 ? void 0 : {
43
+ definition: run.replayOf?.definition ?? run.definition,
44
+ steps: run.replayOf ? await trace?.read(run.replayOf.id) ?? [] : []
43
45
  };
46
+ const mode = run.trace ?? run.definition.trace ?? traceMode;
47
+ const keep = async (steps) => void await trace?.write(runId, steps, { mode });
44
48
  const outcome = await runSegment({
45
49
  ...segment,
46
50
  ...replayed && { replayed },
47
- saved: await store.steps(db, runId),
48
- save: (steps) => store.save(db, runId, steps)
49
- });
50
- if (outcome.kind === "superseded") return;
51
- if (outcome.kind === "ended") return store.update(db, runId, {
52
- status: "succeeded",
53
- output: redactor.value(outcome.output)
54
- });
55
- if (outcome.kind === "failed") return store.update(db, runId, {
56
- status: "failed",
57
- error: redactor.text(outcome.error),
58
- cause: redactor.text(outcome.cause)
51
+ saved: await store.checkpoints(db, runId),
52
+ save: (checkpoints) => store.save(db, runId, checkpoints),
53
+ keep
59
54
  });
55
+ const traced = async (end) => {
56
+ if (!end && outcome.steps.length === 0) return;
57
+ await trace?.write(runId, outcome.steps, {
58
+ mode,
59
+ ...end && { ended: end }
60
+ });
61
+ };
62
+ if (outcome.kind === "superseded") return traced();
63
+ if (outcome.kind === "ended") {
64
+ await traced("succeeded");
65
+ await store.update(db, runId, {
66
+ status: "succeeded",
67
+ output: redactor.value(outcome.output)
68
+ });
69
+ return;
70
+ }
71
+ if (outcome.kind === "failed") {
72
+ await traced("failed");
73
+ await store.update(db, runId, {
74
+ status: "failed",
75
+ error: redactor.text(outcome.error),
76
+ cause: redactor.text(outcome.cause)
77
+ });
78
+ return;
79
+ }
80
+ await traced();
60
81
  if (outcome.kind === "yielded") return queue.schedule(db, runId);
61
82
  await store.update(db, runId, {
62
83
  status: "waiting",
package/dist/run/scope.js CHANGED
@@ -1,8 +1,9 @@
1
1
  import { limits } from "../limits.js";
2
2
  import { StepError, SupersededError } from "./errors.js";
3
+ import { advance, checkpointOf, positionOf, startPosition, visitOf } from "./position.js";
4
+ import { itemScope } from "./replay-match.js";
3
5
  import { jsonBytes } from "./json-bytes.js";
4
- import { advance, foldPosition } from "./position.js";
5
- import { bindingsOf } from "./step-input.js";
6
+ import { bindingsOf, innerScope } from "./step-input.js";
6
7
  import { runResultState } from "./result-states.js";
7
8
  import { runChoice, runFail, runPass, runWait } from "./simple-states.js";
8
9
  //#region src/run/scope.ts
@@ -45,28 +46,36 @@ const keptLogs = (logs, redact) => {
45
46
  }];
46
47
  };
47
48
  const withinLimits = (record) => {
48
- const field = [
49
+ const sized = [
49
50
  "input",
50
51
  "output",
51
52
  "assigned"
52
- ].find((name) => jsonBytes(record[name]) > limits.valueBytes);
53
- if (!field) return record;
53
+ ].map((field) => ({
54
+ field,
55
+ bytes: jsonBytes(record[field])
56
+ })).find(({ bytes }) => bytes > limits.valueBytes);
57
+ if (!sized) return record;
54
58
  const { output: _, assigned: __, input: ___, ...rest } = record;
59
+ const cause = `The step's ${sized.field} is ${sized.bytes} bytes as JSON, over the ${limits.valueBytes / 1024} KiB a value is kept up to; keep it in a store and pass a reference`;
55
60
  return {
56
61
  ...rest,
57
62
  status: "failed",
58
63
  next: null,
59
64
  resumeAt: null,
60
65
  error: "States.DataLimitExceeded",
61
- cause: `The step's ${field} is larger than ${limits.valueBytes / 1024 / 1024} MiB`
66
+ cause
62
67
  };
63
68
  };
64
69
  /**
65
- * Runs one scope (the run or a Map item) from where its saved steps leave it, saving each step as
66
- * the segment's checkpoints come, until the scope ends or fails, waits for a time, or the segment's time is up.
70
+ * Runs one scope (the run or a Map item) from its latest checkpoint, or from its start at `clock`, until it ends or
71
+ * fails, waits for a time, or the segment's time is up. A recorded Task's step and a step with a time to go on at
72
+ * save the scope's checkpoint before it goes on, with every other scope's kept since the last; any other step only
73
+ * keeps it, as running it again gives the same.
67
74
  */
68
- const runScope = async (context, machine, scope, input, outer) => {
69
- let position = foldPosition(machine, input, context.saved.get(scope) ?? []);
75
+ const runScope = async (context, machine, where, input, outer, clock) => {
76
+ const { scope, logical } = where;
77
+ const saved = context.saved.get(scope);
78
+ let position = saved ? positionOf(saved) : startPosition(machine, input, clock);
70
79
  for (;;) {
71
80
  if (position.kind === "failed") return {
72
81
  kind: "failed",
@@ -97,14 +106,23 @@ const runScope = async (context, machine, scope, input, outer) => {
97
106
  const name = position.state;
98
107
  const state = machine.States[name];
99
108
  const startedAt = context.now();
109
+ const from = position;
110
+ const visit = visitOf(position);
111
+ const item = (index) => ({
112
+ scope: innerScope(scope, name, from.seq, index),
113
+ logical: itemScope(logical, name, visit, index)
114
+ });
115
+ const runItem = (inner, index, value, seen) => runScope(context, inner, item(index), value, seen, from.clock);
100
116
  const call = {
101
117
  context,
102
118
  name,
103
119
  scope,
120
+ logical,
104
121
  position,
105
- bindings: bindingsOf(context, outer, position),
122
+ visit,
123
+ bindings: bindingsOf(context, outer, scope, position),
106
124
  logs: [],
107
- runScope: (inner, key, value, seen) => runScope(context, inner, key, value, seen)
125
+ runScope: runItem
108
126
  };
109
127
  context.steps.count++;
110
128
  const result = await ranOrFailed(state, call);
@@ -112,7 +130,7 @@ const runScope = async (context, machine, scope, input, outer) => {
112
130
  context.steps.count--;
113
131
  return result;
114
132
  }
115
- const { kind: _, logs, ...step } = result;
133
+ const { kind: _, logs, recorded = false, fetchedAt, ...step } = result;
116
134
  const shaped = {
117
135
  ...step,
118
136
  logs: keptLogs(logs, context.redactor.text),
@@ -122,11 +140,15 @@ const runScope = async (context, machine, scope, input, outer) => {
122
140
  type: state.Type,
123
141
  attempt: position.attempt,
124
142
  startedAt,
125
- finishedAt: context.now()
143
+ finishedAt: fetchedAt ?? context.now(),
144
+ recorded
126
145
  };
127
146
  const record = withinLimits(context.redactor.value(shaped));
128
- await context.save(record, state.Type === "Task" || Boolean(record.resumeAt));
147
+ context.trace(record);
148
+ const before = position;
129
149
  position = advance(position, record);
150
+ if (position.kind === "failed") continue;
151
+ await context.checkpoint(checkpointOf(position, record, before.clock), record.recorded || Boolean(record.resumeAt));
130
152
  }
131
153
  };
132
154
  //#endregion
@@ -0,0 +1,49 @@
1
+ //#region src/run/seeded-random.ts
2
+ const seedsOf = (text) => {
3
+ let [h1, h2, h3, h4] = [
4
+ 1779033703,
5
+ 3144134277,
6
+ 1013904242,
7
+ 2773480762
8
+ ];
9
+ for (let index = 0; index < text.length; index++) {
10
+ const code = text.charCodeAt(index);
11
+ h1 = h2 ^ Math.imul(h1 ^ code, 597399067);
12
+ h2 = h3 ^ Math.imul(h2 ^ code, 2869860233);
13
+ h3 = h4 ^ Math.imul(h3 ^ code, 951274213);
14
+ h4 = h1 ^ Math.imul(h4 ^ code, 2716044179);
15
+ }
16
+ h1 = Math.imul(h3 ^ h1 >>> 18, 597399067);
17
+ h2 = Math.imul(h4 ^ h2 >>> 22, 2869860233);
18
+ h3 = Math.imul(h1 ^ h3 >>> 17, 951274213);
19
+ h4 = Math.imul(h2 ^ h4 >>> 19, 2716044179);
20
+ return [
21
+ (h1 ^ h2 ^ h3 ^ h4) >>> 0,
22
+ (h2 ^ h1) >>> 0,
23
+ (h3 ^ h1) >>> 0,
24
+ (h4 ^ h1) >>> 0
25
+ ];
26
+ };
27
+ /**
28
+ * A generator of numbers from 0 up to 1, as `Math.random` gives, that gives the same numbers for the same seed (sfc32,
29
+ * seeded by a hash of the text). Not for secrets.
30
+ */
31
+ const seededRandom = (seed) => {
32
+ let [a, b, c, d] = seedsOf(seed);
33
+ return () => {
34
+ a >>>= 0;
35
+ b >>>= 0;
36
+ c >>>= 0;
37
+ d >>>= 0;
38
+ let t = a + b | 0;
39
+ a = b ^ b >>> 9;
40
+ b = c + (c << 3) | 0;
41
+ c = c << 21 | c >>> 11;
42
+ d = d + 1 | 0;
43
+ t = t + d | 0;
44
+ c = c + t | 0;
45
+ return (t >>> 0) / 4294967296;
46
+ };
47
+ };
48
+ //#endregion
49
+ export { seededRandom };
@@ -1,7 +1,7 @@
1
1
  import { Definition } from "../definition/types.js";
2
2
  import { Redactor } from "./redact.js";
3
3
  import { StepCacheStore } from "./cache/cache-port.js";
4
- import { SavedStep, StepRecord, TaskHandlers } from "./port.js";
4
+ import { Checkpoint, StepRecord, TaskHandlers } from "./port.js";
5
5
  import { Replayed } from "./replay-of.js";
6
6
  import { ScopeOutcome } from "./context.js";
7
7
  //#region src/run/segment.d.ts
@@ -15,14 +15,16 @@ export type SegmentInput = {
15
15
  secrets: Readonly<Record<string, string>>;
16
16
  /** Blanks the secrets out of what the run records. */
17
17
  redactor: Redactor;
18
- /** The steps the run saved so far. */
19
- saved: readonly SavedStep[];
20
- /** Saves steps in one guarded statement: false when any of their scopes and seqs is taken. */
21
- save: (steps: readonly StepRecord[]) => Promise<boolean>;
18
+ /** The latest checkpoint of each scope the run saved so far. */
19
+ saved: readonly Checkpoint[];
20
+ /** Saves checkpoints in one guarded statement: false when a scope has one newer than the one it follows. */
21
+ save: (checkpoints: readonly Checkpoint[]) => Promise<boolean>;
22
+ /** Hands the steps run since the last time to the trace, before a checkpoint after them is saved. */
23
+ keep: (steps: readonly StepRecord[]) => Promise<void>;
22
24
  tasks: TaskHandlers;
23
25
  /** Where step types that cache keep their results; none keeps nothing. */
24
26
  cache?: StepCacheStore;
25
- /** In a replay, the run it replays. */
27
+ /** In a replay, the run it replays, with its steps from its trace. */
26
28
  replayed?: Replayed;
27
29
  signal: AbortSignal;
28
30
  now?: () => Date;
@@ -31,11 +33,16 @@ export type SegmentInput = {
31
33
  /** The most steps the run takes. Default `limits.runSteps`. */
32
34
  maxSteps?: number;
33
35
  };
36
+ /** How a segment ended, with the steps it ran since it last handed them to `keep`, for the run's trace. */
37
+ export type SegmentOutcome = (ScopeOutcome | {
38
+ kind: 'superseded';
39
+ }) & {
40
+ steps: StepRecord[];
41
+ };
34
42
  /**
35
- * Runs a run's steps from where its saved steps leave it to its next wait: it ends or fails, waits until a time
36
- * (a Wait, a retry's delay), or yields once its time is up. `superseded` when another segment saved a step first.
43
+ * Runs a run's steps from where its checkpoints leave it to its next wait: it ends or fails, waits until a time
44
+ * (a Wait, a retry's delay), or yields once its time is up, saving its checkpoints on the way and as it pauses.
45
+ * `superseded` when another segment saved a newer checkpoint first.
37
46
  */
38
- export declare const runSegment: ({ runId, definition, input, startedAt, secrets, redactor, saved, save, tasks, cache, replayed, signal, now, budgetMs, maxSteps }: SegmentInput) => Promise<ScopeOutcome | {
39
- kind: "superseded";
40
- }>;
47
+ export declare const runSegment: ({ runId, definition, input, startedAt, secrets, redactor, saved, save, keep, tasks, cache, replayed, signal, now, budgetMs, maxSteps }: SegmentInput) => Promise<SegmentOutcome>;
41
48
  //#endregion