@noetic-tools/core 5.13.0 → 6.1.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.
- package/dist/builders/decide-builders.d.ts +2 -2
- package/dist/builders/dynamic-workflow.js +2 -0
- package/dist/builders/provide-builder.d.ts +2 -2
- package/dist/builders/spawn-builder.d.ts +2 -2
- package/dist/builders/step-builders.d.ts +5 -5
- package/dist/builders/workflow-hydrator.d.ts +1 -1
- package/dist/builders/workflow-hydrator.js +53 -3
- package/dist/expression/check.js +14 -0
- package/dist/expression/jsonata.d.ts +7 -0
- package/dist/expression/jsonata.js +11 -1
- package/dist/harness/agent-harness.d.ts +59 -5
- package/dist/harness/agent-harness.js +176 -25
- package/dist/harness/deps/runtime.d.ts +4 -0
- package/dist/harness/deps/runtime.js +2 -0
- package/dist/harness/model-call.js +69 -0
- package/dist/harness/model-rounds.d.ts +52 -0
- package/dist/harness/model-rounds.js +115 -0
- package/dist/harness/thread-record.d.ts +54 -0
- package/dist/harness/thread-record.js +159 -0
- package/dist/index.d.ts +2 -2
- package/dist/interpreter/emit-items.d.ts +19 -0
- package/dist/interpreter/emit-items.js +106 -0
- package/dist/interpreter/execute-action.js +3 -0
- package/dist/interpreter/execute-control.js +3 -0
- package/dist/interpreter/execute.js +66 -9
- package/dist/runtime/context-impl.d.ts +106 -4
- package/dist/runtime/context-impl.js +224 -14
- package/dist/runtime/durable/harness-checkpoints.d.ts +13 -3
- package/dist/runtime/durable/harness-checkpoints.js +66 -7
- package/dist/runtime/durable/session-store.d.ts +37 -0
- package/dist/runtime/durable/session-store.js +58 -0
- package/dist/runtime/durable/step-ledger.d.ts +77 -40
- package/dist/runtime/durable/step-ledger.js +193 -73
- package/dist/runtime/item-log-impl.d.ts +6 -0
- package/dist/runtime/item-log-impl.js +12 -0
- package/dist/runtime/session-runner.d.ts +25 -1
- package/dist/runtime/session-runner.js +83 -11
- package/dist/schemas/workflow.d.ts +1 -1
- package/dist/types/checkpoint.d.ts +21 -4
- package/dist/types/checkpoint.js +33 -3
- package/package.json +2 -2
- package/schema/noetic-workflow.schema.json +391 -0
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a session (`harness.execute()`) keeps in storage so a new harness can pick a
|
|
3
|
+
* thread up: the thread's history, what its turns spent, and the turn in flight.
|
|
4
|
+
*
|
|
5
|
+
* A turn's record is written before the turn runs and cleared when it finishes. A
|
|
6
|
+
* harness that finds one still set knows the turn was cut off. If the same messages
|
|
7
|
+
* arrive again — a host with at-least-once delivery re-sends what it never saw
|
|
8
|
+
* answered — the turn resumes on its recorded execution: finished steps replay and
|
|
9
|
+
* the turn continues from the step that was cut off.
|
|
10
|
+
*/
|
|
11
|
+
import { z } from 'zod';
|
|
12
|
+
//#region Schema
|
|
13
|
+
const SessionRecordSchema = z.object({
|
|
14
|
+
/** The thread's history after its last finished turn. */
|
|
15
|
+
items: z.array(z.unknown()),
|
|
16
|
+
/** What the thread's turns have spent, summed as each turn settles. */
|
|
17
|
+
usage: z
|
|
18
|
+
.object({
|
|
19
|
+
inputTokens: z.number(),
|
|
20
|
+
outputTokens: z.number(),
|
|
21
|
+
cachedTokens: z.number().optional(),
|
|
22
|
+
cost: z.number().optional(),
|
|
23
|
+
billedCost: z.number().optional(),
|
|
24
|
+
})
|
|
25
|
+
.optional(),
|
|
26
|
+
/** The turn in flight, if one was cut off. */
|
|
27
|
+
turn: z
|
|
28
|
+
.object({
|
|
29
|
+
executionId: z.string(),
|
|
30
|
+
/** The ids of the messages the turn delivers, in order. */
|
|
31
|
+
messageIds: z.array(z.string()),
|
|
32
|
+
})
|
|
33
|
+
.optional(),
|
|
34
|
+
});
|
|
35
|
+
/** @internal */
|
|
36
|
+
export function createSessionStore(storage) {
|
|
37
|
+
return {
|
|
38
|
+
load: async (threadId) => {
|
|
39
|
+
const raw = await storage.get(sessionKey(threadId));
|
|
40
|
+
if (raw === null) {
|
|
41
|
+
return undefined;
|
|
42
|
+
}
|
|
43
|
+
const parsed = SessionRecordSchema.safeParse(raw);
|
|
44
|
+
if (!parsed.success) {
|
|
45
|
+
console.warn(`SessionStore: discarding unreadable session "${threadId}": ${parsed.error.message}`);
|
|
46
|
+
return undefined;
|
|
47
|
+
}
|
|
48
|
+
return parsed.data;
|
|
49
|
+
},
|
|
50
|
+
save: async (threadId, record) => {
|
|
51
|
+
await storage.set(sessionKey(threadId), record);
|
|
52
|
+
},
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
function sessionKey(threadId) {
|
|
56
|
+
return `session:${threadId}`;
|
|
57
|
+
}
|
|
58
|
+
//#endregion
|
|
@@ -17,11 +17,19 @@
|
|
|
17
17
|
* `key:<replayKey>` instead: content-addressed, so it finds its output wherever it
|
|
18
18
|
* runs. A `durable: false` step has no key and is never recorded.
|
|
19
19
|
*
|
|
20
|
+
* An entry also carries what replay must put back: the items the step appended to its
|
|
21
|
+
* context's item log (a checkpoint holds the log as it stood when the run began, so the
|
|
22
|
+
* replayed steps rebuild the rest), and a hash of the step's input, so a step whose input
|
|
23
|
+
* changed since it was recorded runs again instead of replaying an answer to a
|
|
24
|
+
* different question.
|
|
25
|
+
*
|
|
20
26
|
* Sharding bounds the cost of one append but not the total, so retention is bounded on
|
|
21
27
|
* two axes (`StepLedgerRetention`): an oversized entry is dropped rather than written,
|
|
22
|
-
* and
|
|
23
|
-
*
|
|
24
|
-
*
|
|
28
|
+
* and once `maxEntries` are live nothing more is recorded. Entries beneath a parent that
|
|
29
|
+
* recorded are pruned, since a resumed run replays the parent without descending, so the
|
|
30
|
+
* live count tracks the open part of the run rather than its length. Both degradations
|
|
31
|
+
* are safe by construction — a missing entry re-runs its step, which costs work rather
|
|
32
|
+
* than correctness.
|
|
25
33
|
*/
|
|
26
34
|
import type { StorageAdapter } from '@noetic-tools/context';
|
|
27
35
|
import { z } from 'zod';
|
|
@@ -33,6 +41,9 @@ export declare const StepLedgerEntrySchema: z.ZodObject<{
|
|
|
33
41
|
stepId: z.ZodString;
|
|
34
42
|
kind: z.ZodString;
|
|
35
43
|
output: z.ZodUnknown;
|
|
44
|
+
inputHash: z.ZodOptional<z.ZodString>;
|
|
45
|
+
items: z.ZodOptional<z.ZodArray<z.ZodUnknown>>;
|
|
46
|
+
streamed: z.ZodOptional<z.ZodArray<z.ZodNumber>>;
|
|
36
47
|
completedAt: z.ZodString;
|
|
37
48
|
}, z.core.$strip>;
|
|
38
49
|
/** @public A completed step recorded for replay. */
|
|
@@ -46,8 +57,9 @@ export type StepLedgerEntry = z.infer<typeof StepLedgerEntrySchema>;
|
|
|
46
57
|
*/
|
|
47
58
|
export interface StepLedgerRetention {
|
|
48
59
|
/**
|
|
49
|
-
* Largest
|
|
50
|
-
*
|
|
60
|
+
* Largest entry that will be recorded, in UTF-8 bytes of the JSON encoding of the
|
|
61
|
+
* step's output plus the items it appended. A step whose entry exceeds this is not
|
|
62
|
+
* recorded at all and re-runs on resume. Keeps one
|
|
51
63
|
* entry inside the per-value limit real storage backends impose (128 KiB on several)
|
|
52
64
|
* instead of failing the write. Pass `Infinity` to record any size.
|
|
53
65
|
*
|
|
@@ -55,9 +67,10 @@ export interface StepLedgerRetention {
|
|
|
55
67
|
*/
|
|
56
68
|
maxEntryBytes?: number;
|
|
57
69
|
/**
|
|
58
|
-
* Most entries
|
|
59
|
-
*
|
|
60
|
-
*
|
|
70
|
+
* Most live entries for one execution. Once the cap is reached nothing more is
|
|
71
|
+
* recorded, so resume replays the head of the run and runs the rest again. Entries
|
|
72
|
+
* beneath a parent that recorded do not count — they are pruned. Pass `Infinity` to
|
|
73
|
+
* record without limit.
|
|
61
74
|
*
|
|
62
75
|
* Defaults to `DEFAULT_STEP_LEDGER_RETENTION.maxEntries` (1000).
|
|
63
76
|
*/
|
|
@@ -77,22 +90,30 @@ export declare const DEFAULT_STEP_LEDGER_RETENTION: {
|
|
|
77
90
|
* @throws NoeticConfigError `code: 'STEP_LEDGER_RETENTION_INVALID'`
|
|
78
91
|
*/
|
|
79
92
|
export declare function resolveStepLedgerRetention(retention?: StepLedgerRetention): Required<StepLedgerRetention>;
|
|
93
|
+
/**
|
|
94
|
+
* @internal
|
|
95
|
+
* A short, stable hash of a step input's JSON encoding, or undefined when the input
|
|
96
|
+
* cannot be encoded (a cycle, a `BigInt`). A replayed output becomes the next step's
|
|
97
|
+
* input after a JSON round trip, and `JSON.stringify` gives the same text for a value
|
|
98
|
+
* and its round-tripped copy, so a resumed run hashes the same inputs the first run did.
|
|
99
|
+
*/
|
|
100
|
+
export declare function hashStepInput(input: unknown): string | undefined;
|
|
80
101
|
/** Storage key prefix owning every ledger entry for one execution. */
|
|
81
102
|
export declare function stepLedgerPrefix(executionId: string): string;
|
|
82
103
|
/**
|
|
83
104
|
* @public
|
|
84
105
|
* Everything one execution's ledger recovered from storage: the entries available for
|
|
85
106
|
* replay plus the sequence bookkeeping a further append needs. `nextSeq` cannot be
|
|
86
|
-
* derived from `entries.size` —
|
|
87
|
-
*
|
|
107
|
+
* derived from `entries.size` — pruning leaves gaps, and reusing a live sequence number
|
|
108
|
+
* would overwrite an entry the resumed run still has to replay.
|
|
88
109
|
*/
|
|
89
110
|
export interface StepLedgerWindow {
|
|
90
111
|
/** Recovered entries, keyed by execution path. Corrupt rows are skipped. */
|
|
91
112
|
entries: Map<string, StepLedgerEntry>;
|
|
113
|
+
/** Sequence number holding each recovered path, so pruning can delete it. */
|
|
114
|
+
seqs: Map<string, number>;
|
|
92
115
|
/** Sequence number the next append takes: highest recorded, plus one. */
|
|
93
116
|
nextSeq: number;
|
|
94
|
-
/** Lowest sequence number still in storage — where eviction resumes. */
|
|
95
|
-
oldestSeq: number;
|
|
96
117
|
}
|
|
97
118
|
/**
|
|
98
119
|
* @public
|
|
@@ -124,8 +145,16 @@ export interface StepLedgerStats {
|
|
|
124
145
|
droppedOversize: number;
|
|
125
146
|
/** Entries not written because their output does not survive JSON encoding. */
|
|
126
147
|
droppedUnserialisable: number;
|
|
127
|
-
/** Entries
|
|
128
|
-
|
|
148
|
+
/** Entries not written because `maxEntries` were already live. */
|
|
149
|
+
droppedFull: number;
|
|
150
|
+
/** Entries deleted because a parent above them recorded. */
|
|
151
|
+
pruned: number;
|
|
152
|
+
}
|
|
153
|
+
/** What a recorded step leaves for replay: the step's identity and input hash. */
|
|
154
|
+
export interface StepLedgerMatch {
|
|
155
|
+
id: string;
|
|
156
|
+
kind: string;
|
|
157
|
+
inputHash: string | undefined;
|
|
129
158
|
}
|
|
130
159
|
/**
|
|
131
160
|
* @public
|
|
@@ -134,16 +163,16 @@ export interface StepLedgerStats {
|
|
|
134
163
|
*
|
|
135
164
|
* Shared by reference across inParallel/spawn children so one execution has one ledger —
|
|
136
165
|
* path keys are globally unique across the step tree, so a flat map is correct. That
|
|
137
|
-
* sharing is also why retention lives here rather than in the store: the
|
|
138
|
-
*
|
|
166
|
+
* sharing is also why retention lives here rather than in the store: the live set that
|
|
167
|
+
* the entry cap counts belongs to the execution, not to the harness.
|
|
139
168
|
*/
|
|
140
169
|
export declare class StepLedger {
|
|
141
|
-
/** Recovered entries, by path.
|
|
170
|
+
/** Recovered entries, by path. */
|
|
142
171
|
private readonly replayable;
|
|
172
|
+
/** Sequence number holding each live entry, recovered or recorded, by path. */
|
|
173
|
+
private readonly live;
|
|
143
174
|
/** Sequence number the next recorded entry takes. */
|
|
144
175
|
private seq;
|
|
145
|
-
/** Lowest sequence number still in storage — advances as eviction proceeds. */
|
|
146
|
-
private oldestSeq;
|
|
147
176
|
private readonly store?;
|
|
148
177
|
private readonly executionId;
|
|
149
178
|
private readonly retention;
|
|
@@ -155,38 +184,46 @@ export declare class StepLedger {
|
|
|
155
184
|
recovered?: StepLedgerWindow;
|
|
156
185
|
retention?: StepLedgerRetention;
|
|
157
186
|
});
|
|
187
|
+
/**
|
|
188
|
+
* Take what storage now holds for this execution in place of what this ledger has
|
|
189
|
+
* in memory — for a run retried in place, which replays what was stored.
|
|
190
|
+
*/
|
|
191
|
+
adopt(recovered: StepLedgerWindow): void;
|
|
158
192
|
/** True when this execution has nothing recovered to replay (the common, fresh case). */
|
|
159
193
|
get isEmpty(): boolean;
|
|
160
194
|
/** What retention has done so far. A snapshot — safe to hold. */
|
|
161
195
|
get stats(): StepLedgerStats;
|
|
162
196
|
/**
|
|
163
|
-
* The recorded
|
|
164
|
-
* A divergence
|
|
165
|
-
* runs fresh. At a positional path it also discards every entry
|
|
166
|
-
* the subtree's
|
|
167
|
-
* entry discards only itself:
|
|
168
|
-
*
|
|
197
|
+
* The recorded entry for `path`, when a previous run completed the same step there on
|
|
198
|
+
* the same input. A divergence — a different step id, kind, or input — returns
|
|
199
|
+
* undefined so the step runs fresh. At a positional path it also discards every entry
|
|
200
|
+
* recorded beneath it: the subtree's outputs belong to a run that no longer exists. A
|
|
201
|
+
* `key:` entry discards only itself: nothing is nested under a content key.
|
|
202
|
+
*
|
|
203
|
+
* An entry recorded without an input hash matches on identity alone.
|
|
204
|
+
*/
|
|
205
|
+
take(path: string, step: StepLedgerMatch): StepLedgerEntry | undefined;
|
|
206
|
+
/**
|
|
207
|
+
* Record a completed step, then prune what it makes dead: a resumed run replays this
|
|
208
|
+
* entry without descending, so nothing recorded beneath it will be read again.
|
|
209
|
+
* Best-effort: a failed write costs resumability, not the run.
|
|
169
210
|
*/
|
|
170
|
-
take(path: string, step: {
|
|
171
|
-
id: string;
|
|
172
|
-
kind: string;
|
|
173
|
-
}): StepLedgerEntry | undefined;
|
|
174
|
-
/** Drop `path` and everything recorded below it. */
|
|
175
|
-
private discardSubtree;
|
|
176
|
-
/** Record a completed step. Best-effort: a failed write costs resumability, not the run. */
|
|
177
211
|
record(entry: StepLedgerEntry): Promise<void>;
|
|
178
212
|
/**
|
|
179
|
-
*
|
|
180
|
-
*
|
|
181
|
-
*
|
|
213
|
+
* Drop every positional entry. A host calls this once a run has finished and the
|
|
214
|
+
* checkpoint holds its result: every later resume starts past them, so they are dead.
|
|
215
|
+
* `key:` entries stay — they are keyed by content, and a later run may ask the same.
|
|
182
216
|
*/
|
|
183
|
-
|
|
217
|
+
dropPaths(): Promise<void>;
|
|
218
|
+
private prune;
|
|
219
|
+
private deleteSeq;
|
|
184
220
|
/**
|
|
185
|
-
*
|
|
186
|
-
*
|
|
187
|
-
* correct without a `list()` per append.
|
|
221
|
+
* Whether this entry is small enough, encodable, and within the live cap. An entry
|
|
222
|
+
* that fails any test is not recorded, so its step re-runs on resume.
|
|
188
223
|
*/
|
|
189
|
-
private
|
|
224
|
+
private retainable;
|
|
225
|
+
/** Live entries once recording at `path` has pruned what lies beneath it. */
|
|
226
|
+
private liveAfter;
|
|
190
227
|
/** One warning per reason per execution — a long run would otherwise flood the log. */
|
|
191
228
|
private warnOnFirstDrop;
|
|
192
229
|
}
|
|
@@ -17,11 +17,19 @@
|
|
|
17
17
|
* `key:<replayKey>` instead: content-addressed, so it finds its output wherever it
|
|
18
18
|
* runs. A `durable: false` step has no key and is never recorded.
|
|
19
19
|
*
|
|
20
|
+
* An entry also carries what replay must put back: the items the step appended to its
|
|
21
|
+
* context's item log (a checkpoint holds the log as it stood when the run began, so the
|
|
22
|
+
* replayed steps rebuild the rest), and a hash of the step's input, so a step whose input
|
|
23
|
+
* changed since it was recorded runs again instead of replaying an answer to a
|
|
24
|
+
* different question.
|
|
25
|
+
*
|
|
20
26
|
* Sharding bounds the cost of one append but not the total, so retention is bounded on
|
|
21
27
|
* two axes (`StepLedgerRetention`): an oversized entry is dropped rather than written,
|
|
22
|
-
* and
|
|
23
|
-
*
|
|
24
|
-
*
|
|
28
|
+
* and once `maxEntries` are live nothing more is recorded. Entries beneath a parent that
|
|
29
|
+
* recorded are pruned, since a resumed run replays the parent without descending, so the
|
|
30
|
+
* live count tracks the open part of the run rather than its length. Both degradations
|
|
31
|
+
* are safe by construction — a missing entry re-runs its step, which costs work rather
|
|
32
|
+
* than correctness.
|
|
25
33
|
*/
|
|
26
34
|
import { storageGetMany } from '@noetic-tools/context';
|
|
27
35
|
import { NoeticConfigError } from '@noetic-tools/types';
|
|
@@ -40,6 +48,18 @@ export const StepLedgerEntrySchema = z.object({
|
|
|
40
48
|
kind: z.string(),
|
|
41
49
|
/** Replayed verbatim in place of re-running the step. */
|
|
42
50
|
output: z.unknown(),
|
|
51
|
+
/**
|
|
52
|
+
* Hash of the step's input when it ran (`hashStepInput`). Replay requires the new
|
|
53
|
+
* dispatch's input to hash the same. Absent when the input could not be encoded.
|
|
54
|
+
*/
|
|
55
|
+
inputHash: z.string().optional(),
|
|
56
|
+
/** Items the step appended to its context's item log, re-appended on replay. */
|
|
57
|
+
items: z.array(z.unknown()).optional(),
|
|
58
|
+
/**
|
|
59
|
+
* Indices into `items` of those `step.emitItems` emitted (spec 01 § Emitting items),
|
|
60
|
+
* streamed again on replay when the harness sets `emitItemsOnReplay`.
|
|
61
|
+
*/
|
|
62
|
+
streamed: z.array(z.number().int().nonnegative()).optional(),
|
|
43
63
|
completedAt: z.string(),
|
|
44
64
|
});
|
|
45
65
|
/** @public Retention applied when a harness does not configure `stepLedgerRetention`. */
|
|
@@ -90,6 +110,41 @@ function fitsByteCap(json, cap) {
|
|
|
90
110
|
return new TextEncoder().encode(json).length <= cap;
|
|
91
111
|
}
|
|
92
112
|
//#endregion
|
|
113
|
+
//#region Input hash
|
|
114
|
+
/**
|
|
115
|
+
* @internal
|
|
116
|
+
* A short, stable hash of a step input's JSON encoding, or undefined when the input
|
|
117
|
+
* cannot be encoded (a cycle, a `BigInt`). A replayed output becomes the next step's
|
|
118
|
+
* input after a JSON round trip, and `JSON.stringify` gives the same text for a value
|
|
119
|
+
* and its round-tripped copy, so a resumed run hashes the same inputs the first run did.
|
|
120
|
+
*/
|
|
121
|
+
export function hashStepInput(input) {
|
|
122
|
+
let json;
|
|
123
|
+
try {
|
|
124
|
+
json = JSON.stringify(input);
|
|
125
|
+
}
|
|
126
|
+
catch {
|
|
127
|
+
return undefined;
|
|
128
|
+
}
|
|
129
|
+
return cyrb53(json ?? 'undefined');
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* 53-bit string hash (cyrb53, public domain: https://github.com/bryc/code/blob/master/jshash/experimental/cyrb53.js).
|
|
133
|
+
* Not cryptographic — it tells "same input" from "changed input", nothing more.
|
|
134
|
+
*/
|
|
135
|
+
function cyrb53(text) {
|
|
136
|
+
let h1 = 0xdeadbeef;
|
|
137
|
+
let h2 = 0x41c6ce57;
|
|
138
|
+
for (let i = 0; i < text.length; i++) {
|
|
139
|
+
const ch = text.charCodeAt(i);
|
|
140
|
+
h1 = Math.imul(h1 ^ ch, 2654435761);
|
|
141
|
+
h2 = Math.imul(h2 ^ ch, 1597334677);
|
|
142
|
+
}
|
|
143
|
+
h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);
|
|
144
|
+
h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);
|
|
145
|
+
return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(36);
|
|
146
|
+
}
|
|
147
|
+
//#endregion
|
|
93
148
|
//#region Store
|
|
94
149
|
/** Storage key prefix owning every ledger entry for one execution. */
|
|
95
150
|
export function stepLedgerPrefix(executionId) {
|
|
@@ -123,20 +178,21 @@ export function createStepLedgerStore(opts) {
|
|
|
123
178
|
* moment a network-backed adapter can least afford an N+1. */
|
|
124
179
|
const raws = await storageGetMany(storage, keys);
|
|
125
180
|
const entries = new Map();
|
|
126
|
-
/*
|
|
127
|
-
* parse still occupies its key, so it must not be handed back out
|
|
181
|
+
/* The next sequence number comes from the KEYS, not the parsed rows: a row that
|
|
182
|
+
* fails to parse still occupies its key, so it must not be handed back out. */
|
|
128
183
|
let highestSeq = -1;
|
|
129
|
-
|
|
130
|
-
// Walk
|
|
131
|
-
//
|
|
132
|
-
for (const key of
|
|
184
|
+
const seqs = new Map();
|
|
185
|
+
// Walk the keys sorted: `seqKey`'s zero-padding makes key order dispatch order,
|
|
186
|
+
// and a later entry at a path must win over an earlier one.
|
|
187
|
+
for (const key of [
|
|
188
|
+
...keys,
|
|
189
|
+
].sort()) {
|
|
133
190
|
const seq = seqFromKey(executionId, key);
|
|
134
191
|
if (seq !== null) {
|
|
135
192
|
highestSeq = Math.max(highestSeq, seq);
|
|
136
|
-
oldestSeq = oldestSeq === -1 ? seq : Math.min(oldestSeq, seq);
|
|
137
193
|
}
|
|
138
194
|
const raw = raws.get(key);
|
|
139
|
-
if (raw === undefined) {
|
|
195
|
+
if (raw === undefined || seq === null) {
|
|
140
196
|
continue;
|
|
141
197
|
}
|
|
142
198
|
const parsed = StepLedgerEntrySchema.safeParse(raw);
|
|
@@ -147,11 +203,12 @@ export function createStepLedgerStore(opts) {
|
|
|
147
203
|
continue;
|
|
148
204
|
}
|
|
149
205
|
entries.set(parsed.data.path, parsed.data);
|
|
206
|
+
seqs.set(parsed.data.path, seq);
|
|
150
207
|
}
|
|
151
208
|
return {
|
|
152
209
|
entries,
|
|
210
|
+
seqs,
|
|
153
211
|
nextSeq: highestSeq + 1,
|
|
154
|
-
oldestSeq: oldestSeq === -1 ? 0 : oldestSeq,
|
|
155
212
|
};
|
|
156
213
|
},
|
|
157
214
|
clear: async (executionId) => {
|
|
@@ -169,16 +226,16 @@ export function createStepLedgerStore(opts) {
|
|
|
169
226
|
*
|
|
170
227
|
* Shared by reference across inParallel/spawn children so one execution has one ledger —
|
|
171
228
|
* path keys are globally unique across the step tree, so a flat map is correct. That
|
|
172
|
-
* sharing is also why retention lives here rather than in the store: the
|
|
173
|
-
*
|
|
229
|
+
* sharing is also why retention lives here rather than in the store: the live set that
|
|
230
|
+
* the entry cap counts belongs to the execution, not to the harness.
|
|
174
231
|
*/
|
|
175
232
|
export class StepLedger {
|
|
176
|
-
/** Recovered entries, by path.
|
|
177
|
-
replayable;
|
|
233
|
+
/** Recovered entries, by path. */
|
|
234
|
+
replayable = new Map();
|
|
235
|
+
/** Sequence number holding each live entry, recovered or recorded, by path. */
|
|
236
|
+
live;
|
|
178
237
|
/** Sequence number the next recorded entry takes. */
|
|
179
238
|
seq;
|
|
180
|
-
/** Lowest sequence number still in storage — advances as eviction proceeds. */
|
|
181
|
-
oldestSeq;
|
|
182
239
|
store;
|
|
183
240
|
executionId;
|
|
184
241
|
retention;
|
|
@@ -186,15 +243,33 @@ export class StepLedger {
|
|
|
186
243
|
recorded: 0,
|
|
187
244
|
droppedOversize: 0,
|
|
188
245
|
droppedUnserialisable: 0,
|
|
189
|
-
|
|
246
|
+
droppedFull: 0,
|
|
247
|
+
pruned: 0,
|
|
190
248
|
};
|
|
191
249
|
constructor(opts) {
|
|
192
250
|
this.executionId = opts.executionId;
|
|
193
251
|
this.store = opts.store;
|
|
194
252
|
this.retention = resolveStepLedgerRetention(opts.retention);
|
|
195
|
-
this.
|
|
196
|
-
this.seq =
|
|
197
|
-
|
|
253
|
+
this.live = new Map();
|
|
254
|
+
this.seq = 0;
|
|
255
|
+
if (opts.recovered) {
|
|
256
|
+
this.adopt(opts.recovered);
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
/**
|
|
260
|
+
* Take what storage now holds for this execution in place of what this ledger has
|
|
261
|
+
* in memory — for a run retried in place, which replays what was stored.
|
|
262
|
+
*/
|
|
263
|
+
adopt(recovered) {
|
|
264
|
+
this.replayable.clear();
|
|
265
|
+
for (const [path, entry] of recovered.entries) {
|
|
266
|
+
this.replayable.set(path, entry);
|
|
267
|
+
}
|
|
268
|
+
this.live.clear();
|
|
269
|
+
for (const [path, seq] of recovered.seqs) {
|
|
270
|
+
this.live.set(path, seq);
|
|
271
|
+
}
|
|
272
|
+
this.seq = Math.max(this.seq, recovered.nextSeq);
|
|
198
273
|
}
|
|
199
274
|
/** True when this execution has nothing recovered to replay (the common, fresh case). */
|
|
200
275
|
get isEmpty() {
|
|
@@ -207,39 +282,40 @@ export class StepLedger {
|
|
|
207
282
|
};
|
|
208
283
|
}
|
|
209
284
|
/**
|
|
210
|
-
* The recorded
|
|
211
|
-
* A divergence
|
|
212
|
-
* runs fresh. At a positional path it also discards every entry
|
|
213
|
-
* the subtree's
|
|
214
|
-
* entry discards only itself:
|
|
215
|
-
*
|
|
285
|
+
* The recorded entry for `path`, when a previous run completed the same step there on
|
|
286
|
+
* the same input. A divergence — a different step id, kind, or input — returns
|
|
287
|
+
* undefined so the step runs fresh. At a positional path it also discards every entry
|
|
288
|
+
* recorded beneath it: the subtree's outputs belong to a run that no longer exists. A
|
|
289
|
+
* `key:` entry discards only itself: nothing is nested under a content key.
|
|
290
|
+
*
|
|
291
|
+
* An entry recorded without an input hash matches on identity alone.
|
|
216
292
|
*/
|
|
217
293
|
take(path, step) {
|
|
218
294
|
const entry = this.replayable.get(path);
|
|
219
295
|
if (!entry) {
|
|
220
296
|
return undefined;
|
|
221
297
|
}
|
|
222
|
-
if (entry
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
this.discardSubtree(path);
|
|
298
|
+
if (matches(entry, step)) {
|
|
299
|
+
return entry;
|
|
300
|
+
}
|
|
301
|
+
if (path.startsWith(REPLAY_KEY_PREFIX)) {
|
|
302
|
+
this.replayable.delete(path);
|
|
228
303
|
return undefined;
|
|
229
304
|
}
|
|
230
|
-
return entry;
|
|
231
|
-
}
|
|
232
|
-
/** Drop `path` and everything recorded below it. */
|
|
233
|
-
discardSubtree(path) {
|
|
234
305
|
for (const key of [
|
|
235
306
|
...this.replayable.keys(),
|
|
236
307
|
]) {
|
|
237
|
-
if (key === path || key
|
|
308
|
+
if (key === path || isBeneath(key, path)) {
|
|
238
309
|
this.replayable.delete(key);
|
|
239
310
|
}
|
|
240
311
|
}
|
|
312
|
+
return undefined;
|
|
241
313
|
}
|
|
242
|
-
/**
|
|
314
|
+
/**
|
|
315
|
+
* Record a completed step, then prune what it makes dead: a resumed run replays this
|
|
316
|
+
* entry without descending, so nothing recorded beneath it will be read again.
|
|
317
|
+
* Best-effort: a failed write costs resumability, not the run.
|
|
318
|
+
*/
|
|
243
319
|
async record(entry) {
|
|
244
320
|
if (!this.store) {
|
|
245
321
|
return;
|
|
@@ -249,9 +325,7 @@ export class StepLedger {
|
|
|
249
325
|
}
|
|
250
326
|
/* Reserve the sequence number BEFORE awaiting: concurrent inParallel legs record through
|
|
251
327
|
* the one shared ledger, and two of them reading the same counter would write the
|
|
252
|
-
* same key, silently overwriting a sibling's entry.
|
|
253
|
-
* gap, which only makes the window below a slight over-estimate of the live count —
|
|
254
|
-
* eviction runs marginally early, never late. */
|
|
328
|
+
* same key, silently overwriting a sibling's entry. */
|
|
255
329
|
const seq = this.seq;
|
|
256
330
|
this.seq = seq + 1;
|
|
257
331
|
try {
|
|
@@ -261,56 +335,92 @@ export class StepLedger {
|
|
|
261
335
|
console.warn(`StepLedger: failed to record "${entry.path}":`, error instanceof Error ? error.message : String(error));
|
|
262
336
|
return;
|
|
263
337
|
}
|
|
338
|
+
const replaced = this.live.get(entry.path);
|
|
339
|
+
this.live.set(entry.path, seq);
|
|
264
340
|
this.counts.recorded += 1;
|
|
265
|
-
|
|
341
|
+
if (replaced !== undefined) {
|
|
342
|
+
await this.deleteSeq(replaced);
|
|
343
|
+
}
|
|
344
|
+
if (!entry.path.startsWith(REPLAY_KEY_PREFIX)) {
|
|
345
|
+
await this.prune((path) => isBeneath(path, entry.path));
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
/**
|
|
349
|
+
* Drop every positional entry. A host calls this once a run has finished and the
|
|
350
|
+
* checkpoint holds its result: every later resume starts past them, so they are dead.
|
|
351
|
+
* `key:` entries stay — they are keyed by content, and a later run may ask the same.
|
|
352
|
+
*/
|
|
353
|
+
async dropPaths() {
|
|
354
|
+
await this.prune((path) => !path.startsWith(REPLAY_KEY_PREFIX));
|
|
355
|
+
for (const path of [
|
|
356
|
+
...this.replayable.keys(),
|
|
357
|
+
]) {
|
|
358
|
+
if (!path.startsWith(REPLAY_KEY_PREFIX)) {
|
|
359
|
+
this.replayable.delete(path);
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
async prune(dead) {
|
|
364
|
+
for (const [path, seq] of [
|
|
365
|
+
...this.live,
|
|
366
|
+
]) {
|
|
367
|
+
if (!dead(path)) {
|
|
368
|
+
continue;
|
|
369
|
+
}
|
|
370
|
+
this.live.delete(path);
|
|
371
|
+
this.replayable.delete(path);
|
|
372
|
+
this.counts.pruned += 1;
|
|
373
|
+
await this.deleteSeq(seq);
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
async deleteSeq(seq) {
|
|
377
|
+
try {
|
|
378
|
+
await this.store?.delete(this.executionId, seq);
|
|
379
|
+
}
|
|
380
|
+
catch (error) {
|
|
381
|
+
console.warn(`StepLedger: failed to delete entry ${seq} of "${this.executionId}":`, error instanceof Error ? error.message : String(error));
|
|
382
|
+
}
|
|
266
383
|
}
|
|
267
384
|
/**
|
|
268
|
-
* Whether this entry is small enough
|
|
269
|
-
*
|
|
270
|
-
* not recorded, so the step re-runs.
|
|
385
|
+
* Whether this entry is small enough, encodable, and within the live cap. An entry
|
|
386
|
+
* that fails any test is not recorded, so its step re-runs on resume.
|
|
271
387
|
*/
|
|
272
388
|
retainable(entry) {
|
|
273
|
-
|
|
389
|
+
if (!this.live.has(entry.path) && this.liveAfter(entry.path) >= this.retention.maxEntries) {
|
|
390
|
+
this.counts.droppedFull += 1;
|
|
391
|
+
this.warnOnFirstDrop(this.counts.droppedFull, `StepLedger: not recording "${entry.path}" — ${this.retention.maxEntries} entries (maxEntries) are already live.`);
|
|
392
|
+
return false;
|
|
393
|
+
}
|
|
394
|
+
let bytes;
|
|
274
395
|
try {
|
|
275
|
-
|
|
396
|
+
// `undefined` stringifies to nothing; there is no size to bound.
|
|
397
|
+
bytes =
|
|
398
|
+
(JSON.stringify(entry.output) ?? '') + (entry.items ? JSON.stringify(entry.items) : '');
|
|
276
399
|
}
|
|
277
400
|
catch {
|
|
278
401
|
this.counts.droppedUnserialisable += 1;
|
|
279
402
|
this.warnOnFirstDrop(this.counts.droppedUnserialisable, `StepLedger: not recording "${entry.path}" — its output does not survive JSON encoding.`);
|
|
280
403
|
return false;
|
|
281
404
|
}
|
|
282
|
-
|
|
283
|
-
if (json !== undefined && !fitsByteCap(json, this.retention.maxEntryBytes)) {
|
|
405
|
+
if (!fitsByteCap(bytes, this.retention.maxEntryBytes)) {
|
|
284
406
|
this.counts.droppedOversize += 1;
|
|
285
|
-
this.warnOnFirstDrop(this.counts.droppedOversize, `StepLedger: not recording "${entry.path}" — output
|
|
407
|
+
this.warnOnFirstDrop(this.counts.droppedOversize, `StepLedger: not recording "${entry.path}" — output and items exceed maxEntryBytes (${this.retention.maxEntryBytes}).`);
|
|
286
408
|
return false;
|
|
287
409
|
}
|
|
288
410
|
return true;
|
|
289
411
|
}
|
|
290
|
-
/**
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
*/
|
|
295
|
-
async evictOverflow() {
|
|
296
|
-
const store = this.store;
|
|
297
|
-
if (!store) {
|
|
298
|
-
return;
|
|
412
|
+
/** Live entries once recording at `path` has pruned what lies beneath it. */
|
|
413
|
+
liveAfter(path) {
|
|
414
|
+
if (this.live.size < this.retention.maxEntries || path.startsWith(REPLAY_KEY_PREFIX)) {
|
|
415
|
+
return this.live.size;
|
|
299
416
|
}
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
417
|
+
let beneath = 0;
|
|
418
|
+
for (const key of this.live.keys()) {
|
|
419
|
+
if (isBeneath(key, path)) {
|
|
420
|
+
beneath += 1;
|
|
304
421
|
}
|
|
305
|
-
catch (error) {
|
|
306
|
-
/* Leave the cursor where it is and stop: the next append retries this victim
|
|
307
|
-
* rather than spinning on a store that is currently refusing deletes. */
|
|
308
|
-
console.warn(`StepLedger: failed to evict entry ${victim} of "${this.executionId}":`, error instanceof Error ? error.message : String(error));
|
|
309
|
-
return;
|
|
310
|
-
}
|
|
311
|
-
this.oldestSeq = victim + 1;
|
|
312
|
-
this.counts.evicted += 1;
|
|
313
422
|
}
|
|
423
|
+
return this.live.size - beneath;
|
|
314
424
|
}
|
|
315
425
|
/** One warning per reason per execution — a long run would otherwise flood the log. */
|
|
316
426
|
warnOnFirstDrop(count, message) {
|
|
@@ -320,4 +430,14 @@ export class StepLedger {
|
|
|
320
430
|
console.warn(`${message} The step will re-run on resume; further drops are silent.`);
|
|
321
431
|
}
|
|
322
432
|
}
|
|
433
|
+
function matches(entry, step) {
|
|
434
|
+
if (entry.stepId !== step.id || entry.kind !== step.kind) {
|
|
435
|
+
return false;
|
|
436
|
+
}
|
|
437
|
+
return entry.inputHash === undefined || entry.inputHash === step.inputHash;
|
|
438
|
+
}
|
|
439
|
+
/** Whether `path` lies in the subtree under `parent` — a lane below it or a child context's prefix. */
|
|
440
|
+
function isBeneath(path, parent) {
|
|
441
|
+
return path.startsWith(`${parent}/`) || path.startsWith(`${parent}[`);
|
|
442
|
+
}
|
|
323
443
|
//#endregion
|