@milaboratories/pl-middle-layer 2.2.0 → 2.4.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/middle_layer/block_status_fold.cjs +427 -0
- package/dist/middle_layer/block_status_fold.cjs.map +1 -0
- package/dist/middle_layer/block_status_fold.js +416 -0
- package/dist/middle_layer/block_status_fold.js.map +1 -0
- package/dist/middle_layer/block_status_tree.cjs +317 -0
- package/dist/middle_layer/block_status_tree.cjs.map +1 -0
- package/dist/middle_layer/block_status_tree.js +313 -0
- package/dist/middle_layer/block_status_tree.js.map +1 -0
- package/dist/middle_layer/block_status_tree_fold.cjs +96 -0
- package/dist/middle_layer/block_status_tree_fold.cjs.map +1 -0
- package/dist/middle_layer/block_status_tree_fold.js +95 -0
- package/dist/middle_layer/block_status_tree_fold.js.map +1 -0
- package/dist/middle_layer/build_stamp.cjs +1 -1
- package/dist/middle_layer/build_stamp.js +1 -1
- package/dist/middle_layer/project.cjs +93 -2
- package/dist/middle_layer/project.cjs.map +1 -1
- package/dist/middle_layer/project.d.ts +34 -1
- package/dist/middle_layer/project.d.ts.map +1 -1
- package/dist/middle_layer/project.js +94 -3
- package/dist/middle_layer/project.js.map +1 -1
- package/dist/model/project_model.cjs +27 -0
- package/dist/model/project_model.cjs.map +1 -1
- package/dist/model/project_model.js +25 -1
- package/dist/model/project_model.js.map +1 -1
- package/dist/mutator/project.cjs +2 -1
- package/dist/mutator/project.cjs.map +1 -1
- package/dist/mutator/project.d.ts.map +1 -1
- package/dist/mutator/project.js +3 -2
- package/dist/mutator/project.js.map +1 -1
- package/dist/mutator/template/render_block.cjs +24 -0
- package/dist/mutator/template/render_block.cjs.map +1 -1
- package/dist/mutator/template/render_block.js +23 -2
- package/dist/mutator/template/render_block.js.map +1 -1
- package/package.json +15 -15
- package/src/middle_layer/block_status_bench.test.ts +288 -0
- package/src/middle_layer/block_status_fold.test.ts +635 -0
- package/src/middle_layer/block_status_fold.ts +625 -0
- package/src/middle_layer/block_status_test_utils.ts +62 -0
- package/src/middle_layer/block_status_tree.test.ts +276 -0
- package/src/middle_layer/block_status_tree.ts +443 -0
- package/src/middle_layer/block_status_tree_fold.test.ts +198 -0
- package/src/middle_layer/block_status_tree_fold.ts +150 -0
- package/src/middle_layer/project.ts +144 -2
- package/src/middle_layer/project_pruning.test.ts +59 -0
- package/src/model/project_model.ts +30 -0
- package/src/mutator/project.ts +7 -1
- package/src/mutator/project_action_context.test.ts +13 -3
- package/src/mutator/template/render_block.ts +32 -2
|
@@ -0,0 +1,625 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Folds a block's action-context tree into the {@link BlockStatusSummary} the Desktop App shows.
|
|
3
|
+
*
|
|
4
|
+
* The fold runs bottom up: {@link foldContext} reads one context on its own, and
|
|
5
|
+
* {@link mergeSubtree} merges it with the folds of its children. Over a synchronized tree each
|
|
6
|
+
* context gets its own computable (see `block_status_tree.ts`), so a report re-reads only the
|
|
7
|
+
* context it landed in and re-merges the contexts above it; the rest of the tree is not read
|
|
8
|
+
* again.
|
|
9
|
+
*
|
|
10
|
+
* The fold attaches no meaning to the states the reporters write, beyond the lifecycle the backend
|
|
11
|
+
* fixes: a context ends in `Completed` or `Terminated`, and a command's `Running` is work on a
|
|
12
|
+
* machine. Jobs are counted per state as reported, so a state added on the backend reaches the
|
|
13
|
+
* Desktop App without a middle layer release.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import type {
|
|
17
|
+
BlockStatusJobGroup,
|
|
18
|
+
BlockStatusJobs,
|
|
19
|
+
BlockStatusSummary,
|
|
20
|
+
} from "@milaboratories/pl-model-middle-layer";
|
|
21
|
+
import {
|
|
22
|
+
blockStatusStatesRecord,
|
|
23
|
+
isTerminalBlockStatusState,
|
|
24
|
+
} from "@milaboratories/pl-model-middle-layer";
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* A key-value written as a JSON object, with its fields unchecked; undefined for anything else.
|
|
28
|
+
* A reporter may write any JSON, so `null` or a bare number must not reach a field read.
|
|
29
|
+
*/
|
|
30
|
+
function parseJsonObject(value: string): Record<string, unknown> | undefined {
|
|
31
|
+
let parsed: unknown;
|
|
32
|
+
try {
|
|
33
|
+
parsed = JSON.parse(value);
|
|
34
|
+
} catch {
|
|
35
|
+
return undefined;
|
|
36
|
+
}
|
|
37
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return undefined;
|
|
38
|
+
return Object.fromEntries(Object.entries(parsed));
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** The part of an action context a fold reads. A tree node accessor satisfies it. */
|
|
42
|
+
export interface ActionContextNode {
|
|
43
|
+
/** Stable identity of the context, for deduplicating a walk. */
|
|
44
|
+
readonly id: string;
|
|
45
|
+
/** The context's baggage: `name`, `block-pack`, `block-id`, `run-id`. */
|
|
46
|
+
getData(): Record<string, unknown> | undefined;
|
|
47
|
+
/** KV entries under a prefix, values as text. */
|
|
48
|
+
listKeyValuesAsString(prefix: string): { key: string; value: string }[];
|
|
49
|
+
/** Field names, whatever their type: the children are `child/<render>`. */
|
|
50
|
+
listFields(): string[];
|
|
51
|
+
/** The context a field points at, or undefined while the field is unset. */
|
|
52
|
+
traverse(field: string): ActionContextNode | undefined;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* How deep the fold follows `child/<render>`.
|
|
57
|
+
*
|
|
58
|
+
* A stack guard, not a correctness device: a context already on the path is skipped, and the depth
|
|
59
|
+
* of a real tree is the nesting depth of the templates, far below this.
|
|
60
|
+
*/
|
|
61
|
+
export const MaxDepth = 256;
|
|
62
|
+
|
|
63
|
+
/** Prefix of the field names holding child contexts. */
|
|
64
|
+
const ChildFieldPrefix = "child/";
|
|
65
|
+
|
|
66
|
+
/** Prefix of the transition keys: `transition/<namespace>/<resource>/<ns>`. */
|
|
67
|
+
const TransitionPrefix = "transition/";
|
|
68
|
+
|
|
69
|
+
/** Prefix of the reading keys: `reading/<namespace>/<resource>/<key>`. */
|
|
70
|
+
const ReadingPrefix = "reading/";
|
|
71
|
+
|
|
72
|
+
/** The namespace the workflow controller reports a render's own lifecycle under. */
|
|
73
|
+
const RenderNamespace = "render";
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* The namespace the creator of a context reports under. The middle layer records `Terminated` here
|
|
77
|
+
* on the root when the user stops the run, see `recordBlockRunCancelled`.
|
|
78
|
+
*/
|
|
79
|
+
const CreatorNamespace = "core";
|
|
80
|
+
|
|
81
|
+
/** The namespace a command reports under; its `Running` means a job executing on a machine. */
|
|
82
|
+
export const ExecNamespace = "exec";
|
|
83
|
+
|
|
84
|
+
/** The namespace a job's work folder reports under. */
|
|
85
|
+
export const WorkdirNamespace = "workdir";
|
|
86
|
+
|
|
87
|
+
/** One transition, as stored under `transition/<namespace>/<resource>/<ns>`. */
|
|
88
|
+
export type Transition = {
|
|
89
|
+
namespace: string;
|
|
90
|
+
/** The resource that reported: the render itself, or a command or work dir it created. */
|
|
91
|
+
reporter: string;
|
|
92
|
+
/** The reporter's clock in nanoseconds, as the decimal string the key carries. */
|
|
93
|
+
ns: string;
|
|
94
|
+
/** As the reporter wrote it, whether or not this build knows the name. */
|
|
95
|
+
state: string;
|
|
96
|
+
detail: string;
|
|
97
|
+
reason: string;
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
/** What one context reported. */
|
|
101
|
+
export type ContextReports = {
|
|
102
|
+
/** Every transition whose key and value parse. */
|
|
103
|
+
all: Transition[];
|
|
104
|
+
/** The earliest and latest timestamp of any transition key, even one whose value does not
|
|
105
|
+
* parse: a report arriving is evidence the run moved whatever it says. */
|
|
106
|
+
firstNs?: string;
|
|
107
|
+
lastNs?: string;
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
/** A node of the tree, reduced to what the summary needs. */
|
|
111
|
+
export type FoldedNode = {
|
|
112
|
+
/** True when the render of this context has ended and nothing it started is still running. */
|
|
113
|
+
terminal: boolean;
|
|
114
|
+
/** The reason, set when the render itself ended in a termination rather than a completion. */
|
|
115
|
+
failure?: string;
|
|
116
|
+
/** The transition holding this node, undefined when it is terminal or has not reported. */
|
|
117
|
+
holding?: Transition;
|
|
118
|
+
/** True when {@link FoldedNode.holding} is `Running` reported by a command. */
|
|
119
|
+
onMachine: boolean;
|
|
120
|
+
};
|
|
121
|
+
|
|
122
|
+
/** Compares non-negative decimal integers given as strings, shorter is smaller. */
|
|
123
|
+
export function compareNs(a: string, b: string): number {
|
|
124
|
+
return a.length !== b.length ? a.length - b.length : a < b ? -1 : a > b ? 1 : 0;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** Nanoseconds since the epoch, as the key carries them, to milliseconds. */
|
|
128
|
+
export function nsToMs(ns: string): number {
|
|
129
|
+
return Number(BigInt(ns) / 1_000_000n);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function earlier(a: string | undefined, b: string | undefined): string | undefined {
|
|
133
|
+
return a === undefined || (b !== undefined && compareNs(b, a) < 0) ? b : a;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function later(a: string | undefined, b: string | undefined): string | undefined {
|
|
137
|
+
return a === undefined || (b !== undefined && compareNs(b, a) > 0) ? b : a;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* How strongly a report claims to be what holds a node.
|
|
142
|
+
*
|
|
143
|
+
* The render's own `Running` means only that template code is being evaluated, and the workflow
|
|
144
|
+
* controller records it again on every evaluation, so it routinely carries a newer timestamp than
|
|
145
|
+
* the wait that actually holds the node. Anything else outranks it however old it is, including a
|
|
146
|
+
* command's `Running`, which is real work. Recency decides only between equal ranks.
|
|
147
|
+
*/
|
|
148
|
+
function rank(t: Transition): number {
|
|
149
|
+
return t.state === blockStatusStatesRecord.Running && t.namespace === RenderNamespace ? 0 : 1;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* The transitions of one context.
|
|
154
|
+
*
|
|
155
|
+
* A value that is not the JSON the reporters write is left out: a report is diagnostic, and a
|
|
156
|
+
* malformed one must not break the surface. Its timestamp still counts.
|
|
157
|
+
*/
|
|
158
|
+
export function readTransitions(node: ActionContextNode): ContextReports {
|
|
159
|
+
const out: ContextReports = { all: [] };
|
|
160
|
+
|
|
161
|
+
for (const { key, value } of node.listKeyValuesAsString(TransitionPrefix)) {
|
|
162
|
+
const parts = key.split("/");
|
|
163
|
+
if (parts.length !== 4) continue;
|
|
164
|
+
const [, namespace, reporter, ns] = parts;
|
|
165
|
+
// Leading zeros would break the length-first comparison, and no reporter writes them.
|
|
166
|
+
if (!/^(0|[1-9]\d*)$/.test(ns)) continue;
|
|
167
|
+
|
|
168
|
+
out.firstNs = earlier(out.firstNs, ns);
|
|
169
|
+
out.lastNs = later(out.lastNs, ns);
|
|
170
|
+
|
|
171
|
+
const parsed = parseJsonObject(value);
|
|
172
|
+
if (parsed === undefined) continue;
|
|
173
|
+
const state = parsed.state;
|
|
174
|
+
if (typeof state !== "string") continue;
|
|
175
|
+
const detail = typeof parsed.detail === "string" ? parsed.detail : "";
|
|
176
|
+
const reason = typeof parsed.reason === "string" ? parsed.reason : "";
|
|
177
|
+
out.all.push({ namespace, reporter, ns, state, detail, reason });
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
return out;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* Reduces one context to {@link FoldedNode}.
|
|
185
|
+
*
|
|
186
|
+
* A context carries the reports of several reporters: the render reports under `render`, and the
|
|
187
|
+
* commands and work dirs it created report under `exec` and `workdir`. The latest transition of
|
|
188
|
+
* each reporter is that reporter's current state, and the state holding the node is the strongest
|
|
189
|
+
* of those a reporter has not left, see {@link rank}.
|
|
190
|
+
*
|
|
191
|
+
* The node has ended when the render has reported its own end (`Completed` once its outputs are
|
|
192
|
+
* set, `Terminated` with its error, or `Completed` with detail `deduplicated`) and every other
|
|
193
|
+
* reporter in the context has ended too: the render's outputs being set does not stop a command it
|
|
194
|
+
* started, and that command's report must stay visible.
|
|
195
|
+
*/
|
|
196
|
+
export function foldNode(transitions: readonly Transition[]): FoldedNode {
|
|
197
|
+
const latestPerReporter = new Map<string, Transition>();
|
|
198
|
+
for (const t of transitions) {
|
|
199
|
+
const reporterKey = `${t.namespace}/${t.reporter}`;
|
|
200
|
+
const previous = latestPerReporter.get(reporterKey);
|
|
201
|
+
if (previous === undefined || compareNs(t.ns, previous.ns) > 0)
|
|
202
|
+
latestPerReporter.set(reporterKey, t);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
let render: Transition | undefined;
|
|
206
|
+
let holding: Transition | undefined;
|
|
207
|
+
let everyReporterEnded = true;
|
|
208
|
+
for (const t of latestPerReporter.values()) {
|
|
209
|
+
if (t.namespace === RenderNamespace) render = t;
|
|
210
|
+
if (isTerminalBlockStatusState(t.state)) continue;
|
|
211
|
+
everyReporterEnded = false;
|
|
212
|
+
if (holding === undefined) {
|
|
213
|
+
holding = t;
|
|
214
|
+
continue;
|
|
215
|
+
}
|
|
216
|
+
const byRank = rank(t) - rank(holding);
|
|
217
|
+
if (byRank > 0 || (byRank === 0 && compareNs(t.ns, holding.ns) > 0)) holding = t;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
if (render !== undefined && isTerminalBlockStatusState(render.state) && everyReporterEnded)
|
|
221
|
+
return {
|
|
222
|
+
terminal: true,
|
|
223
|
+
onMachine: false,
|
|
224
|
+
failure: render.state === blockStatusStatesRecord.Terminated ? render.reason : undefined,
|
|
225
|
+
};
|
|
226
|
+
|
|
227
|
+
return {
|
|
228
|
+
terminal: false,
|
|
229
|
+
holding,
|
|
230
|
+
onMachine:
|
|
231
|
+
holding?.state === blockStatusStatesRecord.Running && holding.namespace === ExecNamespace,
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** The render's own latest transition in a context. */
|
|
236
|
+
export function latestRender(transitions: readonly Transition[]): Transition | undefined {
|
|
237
|
+
let latest: Transition | undefined;
|
|
238
|
+
for (const t of transitions)
|
|
239
|
+
if (t.namespace === RenderNamespace && (latest === undefined || compareNs(t.ns, latest.ns) > 0))
|
|
240
|
+
latest = t;
|
|
241
|
+
return latest;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/** One reading, as stored under `reading/<namespace>/<resource>/<key>`. */
|
|
245
|
+
export type Reading = { namespace: string; resource: string; key: string; value: string };
|
|
246
|
+
|
|
247
|
+
/** One context read on its own, before its children are merged in. */
|
|
248
|
+
export type ContextFold = {
|
|
249
|
+
readonly id: string;
|
|
250
|
+
/** The baggage: `name`, `block-pack`, `block-id`, `run-id`. */
|
|
251
|
+
readonly data: Record<string, unknown> | undefined;
|
|
252
|
+
readonly reports: ContextReports;
|
|
253
|
+
readonly readings: readonly Reading[];
|
|
254
|
+
readonly folded: FoldedNode;
|
|
255
|
+
/** True for a context a command or its work folder reports in: one job. */
|
|
256
|
+
readonly job: boolean;
|
|
257
|
+
/** The render's own latest transition, when it is a termination. */
|
|
258
|
+
readonly terminated?: { readonly reason: string; readonly ns: string };
|
|
259
|
+
/** Time its commands spent in `Running`, see {@link computeOf}. */
|
|
260
|
+
readonly compute: ContextCompute;
|
|
261
|
+
};
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* Time the commands of a context spent in `Running`: each Running up to the reporter's next
|
|
265
|
+
* transition, ns. A command whose latest transition is Running is still open; it is counted up to
|
|
266
|
+
* whatever moment the reader picks.
|
|
267
|
+
*/
|
|
268
|
+
export type ContextCompute = {
|
|
269
|
+
readonly closedNs: bigint;
|
|
270
|
+
/** When each command still running started, ns. */
|
|
271
|
+
readonly openSinceNs: readonly string[];
|
|
272
|
+
};
|
|
273
|
+
|
|
274
|
+
function computeOf(all: readonly Transition[]): ContextCompute {
|
|
275
|
+
const byReporter = new Map<string, Transition[]>();
|
|
276
|
+
for (const t of all) {
|
|
277
|
+
if (t.namespace !== ExecNamespace) continue;
|
|
278
|
+
const list = byReporter.get(t.reporter);
|
|
279
|
+
if (list === undefined) byReporter.set(t.reporter, [t]);
|
|
280
|
+
else list.push(t);
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
let closedNs = 0n;
|
|
284
|
+
const openSinceNs: string[] = [];
|
|
285
|
+
for (const list of byReporter.values()) {
|
|
286
|
+
list.sort((a, b) => compareNs(a.ns, b.ns));
|
|
287
|
+
for (let i = 0; i < list.length; i++) {
|
|
288
|
+
if (list[i].state !== blockStatusStatesRecord.Running) continue;
|
|
289
|
+
const next = list[i + 1];
|
|
290
|
+
if (next === undefined) openSinceNs.push(list[i].ns);
|
|
291
|
+
else closedNs += BigInt(next.ns) - BigInt(list[i].ns);
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
return { closedNs, openSinceNs };
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
function readReadings(node: ActionContextNode): Reading[] {
|
|
298
|
+
const out: Reading[] = [];
|
|
299
|
+
for (const { key, value } of node.listKeyValuesAsString(ReadingPrefix)) {
|
|
300
|
+
const parts = key.split("/");
|
|
301
|
+
if (parts.length !== 4) continue;
|
|
302
|
+
out.push({ namespace: parts[1], resource: parts[2], key: parts[3], value });
|
|
303
|
+
}
|
|
304
|
+
return out;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/** Reads one context: its transitions, its readings, and the state holding it. */
|
|
308
|
+
export function foldContext(node: ActionContextNode): ContextFold {
|
|
309
|
+
const reports = readTransitions(node);
|
|
310
|
+
const render = latestRender(reports.all);
|
|
311
|
+
return {
|
|
312
|
+
id: node.id,
|
|
313
|
+
data: node.getData(),
|
|
314
|
+
reports,
|
|
315
|
+
readings: readReadings(node),
|
|
316
|
+
folded: foldNode(reports.all),
|
|
317
|
+
job: reports.all.some((t) => t.namespace === ExecNamespace || t.namespace === WorkdirNamespace),
|
|
318
|
+
terminated:
|
|
319
|
+
render?.state === blockStatusStatesRecord.Terminated
|
|
320
|
+
? { reason: render.reason, ns: render.ns }
|
|
321
|
+
: undefined,
|
|
322
|
+
compute: computeOf(reports.all),
|
|
323
|
+
};
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/** {@link BlockStatusJobGroup} being accumulated, its timestamp still in nanoseconds. */
|
|
327
|
+
type JobGroupTally = {
|
|
328
|
+
readonly namespace: string;
|
|
329
|
+
readonly state: string;
|
|
330
|
+
readonly count: number;
|
|
331
|
+
readonly sinceNs?: string;
|
|
332
|
+
readonly files?: { readonly done: number; readonly total: number };
|
|
333
|
+
};
|
|
334
|
+
|
|
335
|
+
/**
|
|
336
|
+
* {@link BlockStatusJobs} being accumulated over a subtree. Plain data throughout, no `Map`: it is
|
|
337
|
+
* the value of a computable, which the computable types map over field by field.
|
|
338
|
+
*/
|
|
339
|
+
export type JobTally = {
|
|
340
|
+
readonly total: number;
|
|
341
|
+
readonly done: number;
|
|
342
|
+
readonly failed: number;
|
|
343
|
+
/** Jobs not ended, by `<namespace>/<state>` of the transition holding each. */
|
|
344
|
+
readonly groups: Readonly<Record<string, JobGroupTally>>;
|
|
345
|
+
};
|
|
346
|
+
|
|
347
|
+
const EmptyJobTally: JobTally = { total: 0, done: 0, failed: 0, groups: {} };
|
|
348
|
+
|
|
349
|
+
/** A context and everything under it, folded. */
|
|
350
|
+
export type SubtreeFold = {
|
|
351
|
+
readonly own: ContextFold;
|
|
352
|
+
readonly children: readonly SubtreeFold[];
|
|
353
|
+
/** This context and every context under it. */
|
|
354
|
+
readonly contexts: number;
|
|
355
|
+
/** Contexts in the subtree that have not ended. */
|
|
356
|
+
readonly activeContexts: number;
|
|
357
|
+
readonly firstNs?: string;
|
|
358
|
+
readonly lastNs?: string;
|
|
359
|
+
/**
|
|
360
|
+
* The earliest render in the subtree whose latest report is a termination, with the context ids
|
|
361
|
+
* from this context down to it.
|
|
362
|
+
*/
|
|
363
|
+
readonly failure?: {
|
|
364
|
+
readonly reason: string;
|
|
365
|
+
readonly ns: string;
|
|
366
|
+
readonly path: readonly string[];
|
|
367
|
+
};
|
|
368
|
+
readonly jobs: JobTally;
|
|
369
|
+
/**
|
|
370
|
+
* Time the subtree's commands spent in `Running`. Commands still running add their time up to a
|
|
371
|
+
* moment the reader picks: `open × now − openSinceSumNs`.
|
|
372
|
+
*/
|
|
373
|
+
readonly compute: {
|
|
374
|
+
readonly closedNs: bigint;
|
|
375
|
+
readonly open: number;
|
|
376
|
+
readonly openSinceSumNs: bigint;
|
|
377
|
+
};
|
|
378
|
+
};
|
|
379
|
+
|
|
380
|
+
/** Files done of all, summed over the work folders' progress readings of one context. */
|
|
381
|
+
function workdirProgress(readings: readonly Reading[]): JobGroupTally["files"] {
|
|
382
|
+
let progress: JobGroupTally["files"];
|
|
383
|
+
for (const r of readings) {
|
|
384
|
+
if (r.namespace !== WorkdirNamespace || r.key !== "progress") continue;
|
|
385
|
+
const parsed = parseJsonObject(r.value);
|
|
386
|
+
if (typeof parsed?.done !== "number" || typeof parsed.total !== "number") continue;
|
|
387
|
+
progress = addFiles(progress, { done: parsed.done, total: parsed.total });
|
|
388
|
+
}
|
|
389
|
+
return progress;
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
function addFiles(a: JobGroupTally["files"], b: JobGroupTally["files"]): JobGroupTally["files"] {
|
|
393
|
+
if (a === undefined) return b;
|
|
394
|
+
if (b === undefined) return a;
|
|
395
|
+
return { done: a.done + b.done, total: a.total + b.total };
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
function groupKey(group: Pick<JobGroupTally, "namespace" | "state">): string {
|
|
399
|
+
return `${group.namespace}/${group.state}`;
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
function mergeGroup(
|
|
403
|
+
groups: Record<string, JobGroupTally>,
|
|
404
|
+
key: string,
|
|
405
|
+
group: JobGroupTally,
|
|
406
|
+
): void {
|
|
407
|
+
const previous = groups[key];
|
|
408
|
+
groups[key] =
|
|
409
|
+
previous === undefined
|
|
410
|
+
? group
|
|
411
|
+
: {
|
|
412
|
+
namespace: group.namespace,
|
|
413
|
+
state: group.state,
|
|
414
|
+
count: previous.count + group.count,
|
|
415
|
+
sinceNs: earlier(previous.sinceNs, group.sinceNs),
|
|
416
|
+
files: addFiles(previous.files, group.files),
|
|
417
|
+
};
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
/** The job a context is, counted where it is now; empty when it is not one. */
|
|
421
|
+
function ownJobs(own: ContextFold): JobTally {
|
|
422
|
+
if (!own.job) return EmptyJobTally;
|
|
423
|
+
const { terminal, failure, holding } = own.folded;
|
|
424
|
+
if (terminal)
|
|
425
|
+
return failure === undefined
|
|
426
|
+
? { ...EmptyJobTally, total: 1, done: 1 }
|
|
427
|
+
: { ...EmptyJobTally, total: 1, failed: 1 };
|
|
428
|
+
if (holding === undefined) return { ...EmptyJobTally, total: 1 };
|
|
429
|
+
const group: JobGroupTally = {
|
|
430
|
+
namespace: holding.namespace,
|
|
431
|
+
state: holding.state,
|
|
432
|
+
count: 1,
|
|
433
|
+
sinceNs: holding.ns,
|
|
434
|
+
files: workdirProgress(own.readings),
|
|
435
|
+
};
|
|
436
|
+
return { ...EmptyJobTally, total: 1, groups: { [groupKey(group)]: group } };
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
/**
|
|
440
|
+
* Merges a context with the folds of its children. One pass over the direct children, so a report
|
|
441
|
+
* re-merges each context on its path to the root and nothing else.
|
|
442
|
+
*/
|
|
443
|
+
export function mergeSubtree(own: ContextFold, children: readonly SubtreeFold[]): SubtreeFold {
|
|
444
|
+
let contexts = 1;
|
|
445
|
+
let activeContexts = own.folded.terminal ? 0 : 1;
|
|
446
|
+
let firstNs = own.reports.firstNs;
|
|
447
|
+
let lastNs = own.reports.lastNs;
|
|
448
|
+
let failure: SubtreeFold["failure"] =
|
|
449
|
+
own.terminated === undefined ? undefined : { ...own.terminated, path: [own.id] };
|
|
450
|
+
let failedBelow = false;
|
|
451
|
+
let closedNs = own.compute.closedNs;
|
|
452
|
+
let open = own.compute.openSinceNs.length;
|
|
453
|
+
let openSinceSumNs = 0n;
|
|
454
|
+
for (const since of own.compute.openSinceNs) openSinceSumNs += BigInt(since);
|
|
455
|
+
|
|
456
|
+
const self = ownJobs(own);
|
|
457
|
+
let { total, done, failed } = self;
|
|
458
|
+
const groups: Record<string, JobGroupTally> = { ...self.groups };
|
|
459
|
+
|
|
460
|
+
for (const child of children) {
|
|
461
|
+
contexts += child.contexts;
|
|
462
|
+
activeContexts += child.activeContexts;
|
|
463
|
+
firstNs = earlier(firstNs, child.firstNs);
|
|
464
|
+
lastNs = later(lastNs, child.lastNs);
|
|
465
|
+
if (child.failure !== undefined) {
|
|
466
|
+
failedBelow = true;
|
|
467
|
+
if (failure === undefined || compareNs(child.failure.ns, failure.ns) < 0)
|
|
468
|
+
failure = { ...child.failure, path: [own.id, ...child.failure.path] };
|
|
469
|
+
}
|
|
470
|
+
closedNs += child.compute.closedNs;
|
|
471
|
+
open += child.compute.open;
|
|
472
|
+
openSinceSumNs += child.compute.openSinceSumNs;
|
|
473
|
+
total += child.jobs.total;
|
|
474
|
+
done += child.jobs.done;
|
|
475
|
+
failed += child.jobs.failed;
|
|
476
|
+
for (const [key, group] of Object.entries(child.jobs.groups)) mergeGroup(groups, key, group);
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
// A render that failed on its own, e.g. one whose command could not start, is a failed job too;
|
|
480
|
+
// one that only passes up the failure under it is not counted again.
|
|
481
|
+
if (own.terminated !== undefined && !failedBelow && !own.job) {
|
|
482
|
+
total++;
|
|
483
|
+
failed++;
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
return {
|
|
487
|
+
own,
|
|
488
|
+
children,
|
|
489
|
+
contexts,
|
|
490
|
+
activeContexts,
|
|
491
|
+
firstNs,
|
|
492
|
+
lastNs,
|
|
493
|
+
failure,
|
|
494
|
+
jobs: { total, done, failed, groups },
|
|
495
|
+
compute: { closedNs, open, openSinceSumNs },
|
|
496
|
+
};
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
/**
|
|
500
|
+
* The child contexts a fold follows: each once, and none already on the path from the root, so a
|
|
501
|
+
* context linked twice or a cycle cannot count a subtree again.
|
|
502
|
+
*/
|
|
503
|
+
export function childContexts<T extends { readonly id: unknown }>(
|
|
504
|
+
fields: readonly string[],
|
|
505
|
+
traverse: (field: string) => T | undefined,
|
|
506
|
+
path: ReadonlySet<string>,
|
|
507
|
+
): T[] {
|
|
508
|
+
if (path.size > MaxDepth) return [];
|
|
509
|
+
const out: T[] = [];
|
|
510
|
+
const seen = new Set<string>();
|
|
511
|
+
for (const field of fields) {
|
|
512
|
+
if (!field.startsWith(ChildFieldPrefix)) continue;
|
|
513
|
+
const child = traverse(field);
|
|
514
|
+
if (child === undefined) continue;
|
|
515
|
+
const id = String(child.id);
|
|
516
|
+
if (path.has(id) || seen.has(id)) continue;
|
|
517
|
+
seen.add(id);
|
|
518
|
+
out.push(child);
|
|
519
|
+
}
|
|
520
|
+
return out;
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
/**
|
|
524
|
+
* Folds a context and everything under it in one walk: what the per-context computables compute,
|
|
525
|
+
* for a tree that is read once.
|
|
526
|
+
*/
|
|
527
|
+
export function foldSubtree(
|
|
528
|
+
node: ActionContextNode,
|
|
529
|
+
path: ReadonlySet<string> = new Set(),
|
|
530
|
+
): SubtreeFold {
|
|
531
|
+
const below = new Set(path).add(node.id);
|
|
532
|
+
const children = childContexts(node.listFields(), (f) => node.traverse(f), below);
|
|
533
|
+
return mergeSubtree(
|
|
534
|
+
foldContext(node),
|
|
535
|
+
children.map((child) => foldSubtree(child, below)),
|
|
536
|
+
);
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
/** Where the backend nests the error of an input inside the error of what consumes it. */
|
|
540
|
+
const InputErrorMarker = "has input errors:";
|
|
541
|
+
|
|
542
|
+
/** Wrappers the workflow controller puts in front of a template's own error. */
|
|
543
|
+
const TemplateErrorPrefix = /^(cannot eval code: |cannot eval template: |tengo template error: )+/;
|
|
544
|
+
|
|
545
|
+
/** Longest headline, in characters. */
|
|
546
|
+
const MaxHeadlineLength = 200;
|
|
547
|
+
|
|
548
|
+
/**
|
|
549
|
+
* The innermost message of a termination reason, for a title: the backend wraps the error of each
|
|
550
|
+
* input in the error of its consumer, and tengo appends stack frames, so a reason can run to pages.
|
|
551
|
+
*/
|
|
552
|
+
export function failureHeadline(reason: string): string {
|
|
553
|
+
const marker = reason.lastIndexOf(InputErrorMarker);
|
|
554
|
+
const lines = reason
|
|
555
|
+
.slice(marker < 0 ? 0 : marker + InputErrorMarker.length)
|
|
556
|
+
.split("\n")
|
|
557
|
+
.map((line) => line.trim())
|
|
558
|
+
// Stack frames: `@platforma-sdk/workflow-tengo:tpl.base:595:5`.
|
|
559
|
+
.filter((line) => line !== "" && !/^@\S+:\d+:\d+$/.test(line));
|
|
560
|
+
|
|
561
|
+
const text = lines.join(" ");
|
|
562
|
+
// A command that failed: `Command ID: … Command name: "python" … Error: docker is not set`.
|
|
563
|
+
const command = /Command name: "([^"]*)".*\bError: (.+)$/.exec(text);
|
|
564
|
+
const headline =
|
|
565
|
+
command !== null
|
|
566
|
+
? `${command[1]} failed: ${command[2]}`
|
|
567
|
+
: text.replace(TemplateErrorPrefix, "");
|
|
568
|
+
return headline.length > MaxHeadlineLength
|
|
569
|
+
? `${headline.slice(0, MaxHeadlineLength - 1)}…`
|
|
570
|
+
: headline;
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
function finishJobs(jobs: JobTally): BlockStatusJobs {
|
|
574
|
+
const byState = Object.values(jobs.groups)
|
|
575
|
+
.map((g): BlockStatusJobGroup => ({
|
|
576
|
+
namespace: g.namespace,
|
|
577
|
+
state: g.state,
|
|
578
|
+
count: g.count,
|
|
579
|
+
since: g.sinceNs === undefined ? undefined : nsToMs(g.sinceNs),
|
|
580
|
+
files: g.files,
|
|
581
|
+
}))
|
|
582
|
+
.sort((a, b) => b.count - a.count || groupKey(a).localeCompare(groupKey(b)));
|
|
583
|
+
return { total: jobs.total, done: jobs.done, failed: jobs.failed, byState };
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
/** The summary of a block run, from the fold of its root action context. */
|
|
587
|
+
export function summarize(root: SubtreeFold): BlockStatusSummary {
|
|
588
|
+
const runId = root.own.data?.["run-id"];
|
|
589
|
+
const jobs = finishJobs(root.jobs);
|
|
590
|
+
const summary = {
|
|
591
|
+
availability: "read" as const,
|
|
592
|
+
runId: typeof runId === "string" ? runId : undefined,
|
|
593
|
+
activeContexts: root.activeContexts,
|
|
594
|
+
totalContexts: root.contexts,
|
|
595
|
+
jobs,
|
|
596
|
+
startedAt: root.firstNs === undefined ? undefined : nsToMs(root.firstNs),
|
|
597
|
+
};
|
|
598
|
+
|
|
599
|
+
// A stopped run: its render is gone and reports nothing more, so the tree is frozen where it
|
|
600
|
+
// stopped. The counters stay, to say where each node was; the run itself is over.
|
|
601
|
+
let cancelledNs: string | undefined;
|
|
602
|
+
for (const t of root.own.reports.all)
|
|
603
|
+
if (t.namespace === CreatorNamespace && t.state === blockStatusStatesRecord.Terminated)
|
|
604
|
+
cancelledNs = later(cancelledNs, t.ns);
|
|
605
|
+
if (cancelledNs !== undefined)
|
|
606
|
+
return { ...summary, lastChangeAt: nsToMs(cancelledNs), done: true, cancelled: true };
|
|
607
|
+
|
|
608
|
+
// A terminated render fails the run. Renders waiting on its outputs never report again, so once
|
|
609
|
+
// no job is held by its command or work folder the run is over, though they still look active.
|
|
610
|
+
const working = jobs.byState.some((g) => g.namespace !== RenderNamespace);
|
|
611
|
+
return {
|
|
612
|
+
...summary,
|
|
613
|
+
lastChangeAt: root.lastNs === undefined ? undefined : nsToMs(root.lastNs),
|
|
614
|
+
// The root's outputs can be set while work it started still runs, so done needs both.
|
|
615
|
+
done:
|
|
616
|
+
(root.own.folded.terminal && root.activeContexts === 0) ||
|
|
617
|
+
(root.failure !== undefined && !working),
|
|
618
|
+
failure: root.failure === undefined ? undefined : failureHeadline(root.failure.reason),
|
|
619
|
+
};
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
/** The summary of a block run, from the root action context of its render. */
|
|
623
|
+
export function foldBlockStatus(root: ActionContextNode): BlockStatusSummary {
|
|
624
|
+
return summarize(foldSubtree(root));
|
|
625
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/** Fixtures for the block status fold and tree tests: action contexts with the backend's key layout. */
|
|
2
|
+
import type { BlockStatusState } from "@milaboratories/pl-model-middle-layer";
|
|
3
|
+
import type { ActionContextNode } from "./block_status_fold";
|
|
4
|
+
|
|
5
|
+
/** One transition, written the way the reporters write it. */
|
|
6
|
+
export type TransitionFixture = {
|
|
7
|
+
namespace: string;
|
|
8
|
+
/** The resource that reported. Defaults to the context's own render. */
|
|
9
|
+
reporter?: string;
|
|
10
|
+
/** Milliseconds since the epoch; the key carries nanoseconds. */
|
|
11
|
+
atMs: number;
|
|
12
|
+
state: BlockStatusState | string;
|
|
13
|
+
detail?: string;
|
|
14
|
+
reason?: string;
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
export type ContextFixture = {
|
|
18
|
+
id: string;
|
|
19
|
+
data?: Record<string, unknown>;
|
|
20
|
+
transitions?: TransitionFixture[];
|
|
21
|
+
children?: ContextFixture[];
|
|
22
|
+
/** Extra KV entries: readings, and malformed input. */
|
|
23
|
+
kv?: Record<string, string>;
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
/** Builds an {@link ActionContextNode} over a fixture, with the backend's key layout. */
|
|
27
|
+
export function context(fixture: ContextFixture): ActionContextNode {
|
|
28
|
+
const kv = new Map<string, string>(Object.entries(fixture.kv ?? {}));
|
|
29
|
+
for (const t of fixture.transitions ?? []) {
|
|
30
|
+
const reporter = t.reporter ?? fixture.id;
|
|
31
|
+
const ns = String(BigInt(t.atMs) * 1_000_000n);
|
|
32
|
+
kv.set(
|
|
33
|
+
`transition/${t.namespace}/${reporter}/${ns}`,
|
|
34
|
+
JSON.stringify({ state: t.state, detail: t.detail ?? "", reason: t.reason ?? "" }),
|
|
35
|
+
);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const children = (fixture.children ?? []).map(context);
|
|
39
|
+
const childFields = new Map(children.map((c) => [`child/${c.id}`, c]));
|
|
40
|
+
|
|
41
|
+
return {
|
|
42
|
+
id: fixture.id,
|
|
43
|
+
getData: () => fixture.data,
|
|
44
|
+
listKeyValuesAsString: (prefix: string) =>
|
|
45
|
+
[...kv.entries()]
|
|
46
|
+
.filter(([key]) => key.startsWith(prefix))
|
|
47
|
+
.map(([key, value]) => ({ key, value })),
|
|
48
|
+
listFields: () => [...childFields.keys()],
|
|
49
|
+
traverse: (field: string) => childFields.get(field),
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export const t0 = Date.UTC(2026, 9, 27, 12, 0, 0);
|
|
54
|
+
export const ms = (offset: number) => t0 + offset;
|
|
55
|
+
|
|
56
|
+
/** The render's own end, as the workflow controller records it. */
|
|
57
|
+
export const renderCompleted = (atMs: number, detail?: string): TransitionFixture => ({
|
|
58
|
+
namespace: "render",
|
|
59
|
+
atMs,
|
|
60
|
+
state: "Completed",
|
|
61
|
+
detail,
|
|
62
|
+
});
|