@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.
Files changed (48) hide show
  1. package/dist/middle_layer/block_status_fold.cjs +427 -0
  2. package/dist/middle_layer/block_status_fold.cjs.map +1 -0
  3. package/dist/middle_layer/block_status_fold.js +416 -0
  4. package/dist/middle_layer/block_status_fold.js.map +1 -0
  5. package/dist/middle_layer/block_status_tree.cjs +317 -0
  6. package/dist/middle_layer/block_status_tree.cjs.map +1 -0
  7. package/dist/middle_layer/block_status_tree.js +313 -0
  8. package/dist/middle_layer/block_status_tree.js.map +1 -0
  9. package/dist/middle_layer/block_status_tree_fold.cjs +96 -0
  10. package/dist/middle_layer/block_status_tree_fold.cjs.map +1 -0
  11. package/dist/middle_layer/block_status_tree_fold.js +95 -0
  12. package/dist/middle_layer/block_status_tree_fold.js.map +1 -0
  13. package/dist/middle_layer/build_stamp.cjs +1 -1
  14. package/dist/middle_layer/build_stamp.js +1 -1
  15. package/dist/middle_layer/project.cjs +93 -2
  16. package/dist/middle_layer/project.cjs.map +1 -1
  17. package/dist/middle_layer/project.d.ts +34 -1
  18. package/dist/middle_layer/project.d.ts.map +1 -1
  19. package/dist/middle_layer/project.js +94 -3
  20. package/dist/middle_layer/project.js.map +1 -1
  21. package/dist/model/project_model.cjs +27 -0
  22. package/dist/model/project_model.cjs.map +1 -1
  23. package/dist/model/project_model.js +25 -1
  24. package/dist/model/project_model.js.map +1 -1
  25. package/dist/mutator/project.cjs +2 -1
  26. package/dist/mutator/project.cjs.map +1 -1
  27. package/dist/mutator/project.d.ts.map +1 -1
  28. package/dist/mutator/project.js +3 -2
  29. package/dist/mutator/project.js.map +1 -1
  30. package/dist/mutator/template/render_block.cjs +24 -0
  31. package/dist/mutator/template/render_block.cjs.map +1 -1
  32. package/dist/mutator/template/render_block.js +23 -2
  33. package/dist/mutator/template/render_block.js.map +1 -1
  34. package/package.json +15 -15
  35. package/src/middle_layer/block_status_bench.test.ts +288 -0
  36. package/src/middle_layer/block_status_fold.test.ts +635 -0
  37. package/src/middle_layer/block_status_fold.ts +625 -0
  38. package/src/middle_layer/block_status_test_utils.ts +62 -0
  39. package/src/middle_layer/block_status_tree.test.ts +276 -0
  40. package/src/middle_layer/block_status_tree.ts +443 -0
  41. package/src/middle_layer/block_status_tree_fold.test.ts +198 -0
  42. package/src/middle_layer/block_status_tree_fold.ts +150 -0
  43. package/src/middle_layer/project.ts +144 -2
  44. package/src/middle_layer/project_pruning.test.ts +59 -0
  45. package/src/model/project_model.ts +30 -0
  46. package/src/mutator/project.ts +7 -1
  47. package/src/mutator/project_action_context.test.ts +13 -3
  48. package/src/mutator/template/render_block.ts +32 -2
@@ -0,0 +1,443 @@
1
+ /**
2
+ * The live action-context tree of one block render, and the computables that fold it.
3
+ *
4
+ * A status tree is its own {@link SynchronizedTreeState}, seeded at the root action context of the
5
+ * render rather than at the project. It has to be separate: the project tree prunes the context
6
+ * fields (see `ProjectStatusFieldPattern`), because a context holds the whole subtree of its render
7
+ * and every report into it is a KV write.
8
+ *
9
+ * One tree per watched block, held while anyone watches, terminated when the last holder lets go.
10
+ */
11
+
12
+ import type { PlClient, SignedResourceId } from "@milaboratories/pl-client";
13
+ import { isNullSignedResourceId, ResourceTypeName, treeFilter } from "@milaboratories/pl-client";
14
+ import { Computable, WatchableValue } from "@milaboratories/computable";
15
+ import type { PlTreeEntry, PlTreeNodeAccessor } from "@milaboratories/pl-tree";
16
+ import { SynchronizedTreeState } from "@milaboratories/pl-tree";
17
+ import type { BlockStatusSummary, BlockStatusTree } from "@milaboratories/pl-model-middle-layer";
18
+ import {
19
+ EmptyBlockStatusSummary,
20
+ UnreadableBlockStatusSummary,
21
+ UnsupportedBlockStatusSummary,
22
+ } from "@milaboratories/pl-model-middle-layer";
23
+ import { setTimeout } from "node:timers/promises";
24
+ import type { ActionContextNode, SubtreeFold } from "./block_status_fold";
25
+ import { childContexts, foldContext, mergeSubtree, summarize } from "./block_status_fold";
26
+ import { blockStatusTree, emptyBlockStatusTree } from "./block_status_tree_fold";
27
+ import type { BlockActionContextMode } from "./block_action_context";
28
+ import { ActionContextLinkCapability } from "../mutator/template/render_block";
29
+ import { projectFieldName } from "../model/project_model";
30
+ import type { MiddleLayerEnvironment } from "./middle_layer";
31
+
32
+ /**
33
+ * How long the refetch loop waits between looks at the project's change generation.
34
+ *
35
+ * The tick itself reads an in-memory counter. It opens a read transaction only when the project
36
+ * has changed since the last look, which while a block runs is most ticks: one read transaction
37
+ * per second per watched block, which is the cost of noticing a re-run promptly.
38
+ */
39
+ const RefetchDebounceMs = 1_000;
40
+
41
+ /** The poll floor of a status tree, as the spec sets it. */
42
+ const StatusTreePollingIntervalMs = 5_000;
43
+
44
+ /**
45
+ * Deadline for the first load of a status tree.
46
+ *
47
+ * Deliberately NOT the project tree's, which disables the timeout outright: a status tree is
48
+ * opened and closed while the app runs, and {@link BlockStatusWatch.terminate} awaits the loop, so
49
+ * an init that never returns would hang a project close and with it the app's shutdown.
50
+ */
51
+ const StatusTreeInitialLoadTimeoutMs = 30_000;
52
+
53
+ /** The status tree walks action contexts and nothing else. */
54
+ const statusTreeFieldFilter = treeFilter.resourceTypeEq(ResourceTypeName.ActionContext);
55
+
56
+ /**
57
+ * The root action context of a block render, read once from the project.
58
+ *
59
+ * Undefined when the block has no context: it was never rendered, or it ran against a backend or a
60
+ * middle layer that did not create one.
61
+ */
62
+ export async function readBlockActionContextRoot(
63
+ pl: PlClient,
64
+ projectRid: SignedResourceId,
65
+ blockId: string,
66
+ mode: BlockActionContextMode,
67
+ ): Promise<SignedResourceId | undefined> {
68
+ return await pl.withReadTx("readBlockActionContextRoot", async (tx) => {
69
+ const project = await tx.getResourceData(projectRid, true);
70
+ const fieldName = projectFieldName(
71
+ blockId,
72
+ mode === "prod" ? "prodActionContext" : "stagingActionContext",
73
+ );
74
+ const statusField = project.fields.find((f) => f.name === fieldName);
75
+ if (statusField === undefined || isNullSignedResourceId(statusField.value)) return undefined;
76
+ return statusField.value;
77
+ });
78
+ }
79
+
80
+ /** Adapts a tree node accessor to what the fold reads. */
81
+ export function actionContextNode(acc: PlTreeNodeAccessor): ActionContextNode {
82
+ return {
83
+ id: String(acc.id),
84
+ getData: () => acc.getDataAsJson<Record<string, unknown>>(),
85
+ listKeyValuesAsString: (prefix: string) => acc.listKeyValuesAsString(prefix),
86
+ listFields: () => acc.listFields(),
87
+ traverse: (field: string) => {
88
+ // A child that carries an error is skipped rather than thrown: the status surface is
89
+ // diagnostic, and one broken branch must not take the whole line down with it.
90
+ const child = acc.traverse({ field, ignoreError: true });
91
+ return child === undefined ? undefined : actionContextNode(child);
92
+ },
93
+ };
94
+ }
95
+
96
+ /**
97
+ * The fold of the context an entry points at and everything under it, one computable per context.
98
+ *
99
+ * A report is a KV write into one context, and only that context's computable reads its KV, so a
100
+ * report re-reads that one context. Each computable above it re-merges its direct children, which
101
+ * are cached, and nothing else in the tree is read again.
102
+ *
103
+ * Undefined when the context cannot be read. A context that is gone is the ordinary case, not a
104
+ * fault: an ephemeral context is dropped as soon as the project stops holding it, which happens the
105
+ * moment the block is run again, and the watch is briefly pointed at it until the next look for a
106
+ * new render. A child that cannot be read is left out rather than breaking the whole run's status.
107
+ * The cause is logged, so a genuine fault is not silent.
108
+ */
109
+ export function subtreeFold(
110
+ entry: PlTreeEntry,
111
+ path: ReadonlySet<string>,
112
+ onError: (err: unknown) => void,
113
+ ): Computable<SubtreeFold | undefined> {
114
+ return Computable.make(
115
+ (ctx) => {
116
+ try {
117
+ const acc = ctx.accessor(entry).node({ ignoreError: true });
118
+ if (acc === undefined) return undefined;
119
+ const node = actionContextNode(acc);
120
+ const below = new Set(path).add(node.id);
121
+ const children = childContexts(
122
+ acc.listFields(),
123
+ // A child that carries an error is skipped rather than thrown, as in actionContextNode.
124
+ (field) => acc.traverse({ field, ignoreError: true }),
125
+ below,
126
+ ).map((child) => subtreeFold(child.persist(), below, onError));
127
+ return { own: foldContext(node), children };
128
+ } catch (err: unknown) {
129
+ onError(err);
130
+ return undefined;
131
+ }
132
+ },
133
+ {
134
+ key: `block-status-context/${entry.id}`,
135
+ postprocessValue: (value) => {
136
+ if (value === undefined) return undefined;
137
+ const children: SubtreeFold[] = [];
138
+ for (const child of value.children) if (child !== undefined) children.push(child);
139
+ return mergeSubtree(value.own, children);
140
+ },
141
+ },
142
+ );
143
+ }
144
+
145
+ /** The summary of the run whose root context an entry points at. */
146
+ export function entrySummary(
147
+ entry: PlTreeEntry,
148
+ reportsSupported: boolean,
149
+ onError: (err: unknown) => void,
150
+ ): Computable<BlockStatusSummary> {
151
+ return Computable.make(() => ({ fold: subtreeFold(entry, new Set(), onError) }), {
152
+ key: `block-status-summary/${entry.id}`,
153
+ postprocessValue: ({ fold }) => summaryOfFold(fold, reportsSupported),
154
+ });
155
+ }
156
+
157
+ /** The summary of a fold, or of a root context that could not be read. */
158
+ function summaryOfFold(
159
+ fold: SubtreeFold | undefined,
160
+ reportsSupported: boolean,
161
+ ): BlockStatusSummary {
162
+ // The counters of a context that could not be read are unknown, not zero.
163
+ if (fold === undefined) return UnreadableBlockStatusSummary;
164
+ const summary = summarize(fold);
165
+ if (reportsSupported || summary.totalContexts === 0) return summary;
166
+ // The context exists and carries its data, but no transition can ever arrive.
167
+ return { ...summary, availability: "unsupported" };
168
+ }
169
+
170
+ /** What {@link BlockStatusWatch.start} watches. */
171
+ export type BlockStatusWatchParams = {
172
+ readonly env: MiddleLayerEnvironment;
173
+ readonly projectRid: SignedResourceId;
174
+ readonly blockId: string;
175
+ readonly mode: BlockActionContextMode;
176
+ /** The project tree's change generation, the trigger for looking for a new render. */
177
+ readonly projectGeneration: () => number;
178
+ };
179
+
180
+ /**
181
+ * The live status of one block render.
182
+ *
183
+ * The summary is stable across runs of the block: clicking Run creates a new render with a new
184
+ * status context, and the watch re-seeds itself onto it rather than handing the caller a new
185
+ * computable. The watch is shared between callers and reference counted; the tree lives until the
186
+ * last holder releases it.
187
+ */
188
+ export class BlockStatusWatch {
189
+ /** The entry of the tree currently seeded, swapped when the block is run again. */
190
+ private readonly source = new WatchableValue<PlTreeEntry | undefined>(undefined);
191
+ private current?: { readonly root: SignedResourceId; readonly tree: SynchronizedTreeState };
192
+ private readonly abortController = new AbortController();
193
+ private loop?: Promise<void>;
194
+
195
+ /**
196
+ * Orders the seeds. A reseed that started before the one that last installed a root is stale by
197
+ * the time it finishes, however long its tree took to open, and must not displace it.
198
+ */
199
+ private seedSequence = 0;
200
+ private installedSeed = -1;
201
+
202
+ /** How many callers hold this watch. The tree is terminated when it reaches zero. */
203
+ private holders = 0;
204
+
205
+ public readonly summary: Computable<BlockStatusSummary>;
206
+
207
+ /**
208
+ * The contexts whose children {@link tree} shows. Shared by every holder: two windows on one
209
+ * block see one expansion.
210
+ */
211
+ private readonly expanded = new WatchableValue<ReadonlySet<string>>(new Set());
212
+
213
+ /**
214
+ * The run's tree, context by context, over the same synchronized tree as {@link summary}. It
215
+ * keeps its own per-context computables, so watching it doubles the cost of a report.
216
+ */
217
+ public readonly tree: Computable<BlockStatusTree>;
218
+
219
+ private readonly env: MiddleLayerEnvironment;
220
+ private readonly projectRid: SignedResourceId;
221
+ private readonly blockId: string;
222
+ private readonly mode: BlockActionContextMode;
223
+ private readonly projectGeneration: () => number;
224
+
225
+ private constructor({
226
+ env,
227
+ projectRid,
228
+ blockId,
229
+ mode,
230
+ projectGeneration,
231
+ }: BlockStatusWatchParams) {
232
+ this.env = env;
233
+ this.projectRid = projectRid;
234
+ this.blockId = blockId;
235
+ this.mode = mode;
236
+ this.projectGeneration = projectGeneration;
237
+ // Without the `actionContext` link a block has no context and nothing is ever reported.
238
+ const reportsSupported = env.pl.hasCapability(ActionContextLinkCapability);
239
+ // One computable for the life of the watch, reading whichever tree is seeded now, so a caller
240
+ // keeps its handle across a re-run of the block.
241
+ this.summary = Computable.make((ctx) => {
242
+ const entry = this.source.getValue(ctx);
243
+ if (entry === undefined)
244
+ return reportsSupported ? EmptyBlockStatusSummary : UnsupportedBlockStatusSummary;
245
+ return entrySummary(entry, reportsSupported, (err) =>
246
+ this.env.logger.warn(new Error("block status fold failed", { cause: err })),
247
+ );
248
+ });
249
+ // The expansion is read in the body, so expanding re-runs it; the per-context computables
250
+ // under it keep their keys and so their cached folds.
251
+ this.tree = Computable.make(
252
+ (ctx) => {
253
+ const entry = this.source.getValue(ctx);
254
+ return {
255
+ seeded: entry !== undefined,
256
+ expanded: [...this.expanded.getValue(ctx)],
257
+ fold:
258
+ entry === undefined
259
+ ? undefined
260
+ : subtreeFold(entry, new Set(), (err) =>
261
+ this.env.logger.warn(new Error("block status tree fold failed", { cause: err })),
262
+ ),
263
+ };
264
+ },
265
+ {
266
+ postprocessValue: ({ seeded, expanded, fold }) => {
267
+ if (!seeded)
268
+ return emptyBlockStatusTree(
269
+ reportsSupported ? EmptyBlockStatusSummary : UnsupportedBlockStatusSummary,
270
+ );
271
+ if (fold === undefined) return emptyBlockStatusTree(UnreadableBlockStatusSummary);
272
+ return blockStatusTree(fold, summaryOfFold(fold, reportsSupported), new Set(expanded));
273
+ },
274
+ },
275
+ );
276
+ }
277
+
278
+ /** Replaces the set of contexts whose children {@link tree} shows. */
279
+ public setExpanded(contextIds: readonly string[]): void {
280
+ this.expanded.setValue(new Set(contextIds), "block status tree expansion changed");
281
+ }
282
+
283
+ /**
284
+ * Starts watching the status of a block render.
285
+ *
286
+ * The first seed is awaited, so the caller gets a handle that already reports whatever the
287
+ * current render has reported. A block with no status context yet still gets a handle: it
288
+ * reports an empty summary and seeds itself when a render that has one appears.
289
+ *
290
+ * The refetch loop is started only once that first seed has settled. Starting it in the
291
+ * constructor would leave it running with nobody holding a reference to stop it if this throws.
292
+ */
293
+ public static async start(params: BlockStatusWatchParams): Promise<BlockStatusWatch> {
294
+ const watch = new BlockStatusWatch(params);
295
+ try {
296
+ await watch.reseed();
297
+ } catch (err: unknown) {
298
+ await watch.terminateNow();
299
+ throw err;
300
+ }
301
+ watch.begin();
302
+ return watch;
303
+ }
304
+
305
+ /** Takes the first holder and starts looking for new renders, once the first seed settled. */
306
+ private begin(): void {
307
+ this.holders = 1;
308
+ // The loop handles its own errors; this catch is only a backstop, so the promise kept here
309
+ // never rejects and can be awaited as is.
310
+ this.loop = this.refetchLoop().catch((err: unknown) => {
311
+ this.env.logger.warn(new Error("block status refetch loop failed", { cause: err }));
312
+ });
313
+ }
314
+
315
+ /** Records one more caller holding this watch. */
316
+ public retain(): void {
317
+ this.holders++;
318
+ }
319
+
320
+ /**
321
+ * Releases one caller's hold. The tree is terminated, and the watch is finished, only when the
322
+ * last holder lets go; returns true when that happened.
323
+ */
324
+ public async release(): Promise<boolean> {
325
+ if (this.holders > 0) this.holders--;
326
+ if (this.holders > 0) return false;
327
+ await this.terminateNow();
328
+ return true;
329
+ }
330
+
331
+ /**
332
+ * Stops the watch whatever the holder count, for a project being torn down. An ordinary caller
333
+ * uses {@link release}.
334
+ */
335
+ public async terminate(): Promise<void> {
336
+ this.holders = 0;
337
+ await this.terminateNow();
338
+ }
339
+
340
+ /** Stops the loop, terminates the tree and releases the computable's holders. */
341
+ private async terminateNow(): Promise<void> {
342
+ this.abortController.abort();
343
+ await this.loop;
344
+ const held = this.current;
345
+ this.current = undefined;
346
+ this.source.setValue(undefined, "block status watch terminated");
347
+ this.summary.resetState();
348
+ this.tree.resetState();
349
+ await this.terminateTree(held?.tree);
350
+ }
351
+
352
+ /**
353
+ * Looks for a new render while the caller watches.
354
+ *
355
+ * The project field holding the root context is pruned from the project tree, so the re-point is
356
+ * not visible there; what is visible is that the project changed at all. A tick that finds the
357
+ * same root installs nothing.
358
+ */
359
+ private async refetchLoop(): Promise<void> {
360
+ let seen = this.projectGeneration();
361
+ while (!this.abortController.signal.aborted) {
362
+ try {
363
+ await setTimeout(RefetchDebounceMs, undefined, { signal: this.abortController.signal });
364
+ } catch {
365
+ return; // aborted
366
+ }
367
+
368
+ const generation = this.projectGeneration();
369
+ if (generation === seen) continue;
370
+
371
+ try {
372
+ await this.reseed();
373
+ // Only once the look succeeded, so a failed one is retried on the next tick rather than
374
+ // waiting for the project to change again.
375
+ seen = generation;
376
+ } catch (err: unknown) {
377
+ if (this.abortController.signal.aborted) return;
378
+ // The current tree stays in place: the surface keeps showing what it has rather than
379
+ // going blank, and the next tick tries again.
380
+ this.env.logger.warn(new Error("block status reseed failed", { cause: err }));
381
+ }
382
+ }
383
+ }
384
+
385
+ /** Points the summary at the current render's context, replacing any earlier one. */
386
+ private async reseed(): Promise<void> {
387
+ const seed = ++this.seedSequence;
388
+
389
+ const root = await readBlockActionContextRoot(
390
+ this.env.pl,
391
+ this.projectRid,
392
+ this.blockId,
393
+ this.mode,
394
+ );
395
+ if (this.abortController.signal.aborted) return;
396
+ if (seed < this.installedSeed) return;
397
+ if (root === this.current?.root) return;
398
+
399
+ const tree =
400
+ root === undefined
401
+ ? undefined
402
+ : await SynchronizedTreeState.init(
403
+ this.env.pl,
404
+ root,
405
+ {
406
+ ...this.env.ops.defaultTreeOptions,
407
+ pollingInterval: StatusTreePollingIntervalMs,
408
+ initialTreeLoadingTimeout: StatusTreeInitialLoadTimeoutMs,
409
+ fieldFilter: statusTreeFieldFilter,
410
+ // A context never becomes final: the backend keeps reporting into it for as long as
411
+ // its render lives, so every poll has to seed it again.
412
+ rootsNeverFinal: true,
413
+ },
414
+ this.env.logger,
415
+ );
416
+
417
+ // Opening the tree took time, and a later reseed may have installed a newer root meanwhile.
418
+ // Terminating the tree just opened is the whole cost of losing that race.
419
+ if (this.abortController.signal.aborted || seed < this.installedSeed) {
420
+ await this.terminateTree(tree);
421
+ return;
422
+ }
423
+
424
+ const previous = this.current;
425
+ this.installedSeed = seed;
426
+ this.current = root !== undefined && tree !== undefined ? { root, tree } : undefined;
427
+
428
+ // Swapped before the old tree is terminated. A computable body runs to completion
429
+ // synchronously, so after this returns no reader is inside the old tree.
430
+ this.source.setValue(tree?.entry(), "block status root changed");
431
+ await this.terminateTree(previous?.tree);
432
+ }
433
+
434
+ private async terminateTree(tree: SynchronizedTreeState | undefined): Promise<void> {
435
+ if (tree === undefined) return;
436
+ try {
437
+ await tree.terminate();
438
+ } catch (err: unknown) {
439
+ // terminate() can throw when the sync loop had already failed; nothing is left to clean up.
440
+ this.env.logger.warn(new Error("block status tree termination failed", { cause: err }));
441
+ }
442
+ }
443
+ }
@@ -0,0 +1,198 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { foldBlockStatusTree } from "./block_status_tree_fold";
3
+ import type { ContextFixture } from "./block_status_test_utils";
4
+ import { context, ms, renderCompleted } from "./block_status_test_utils";
5
+
6
+ const none = new Set<string>();
7
+
8
+ /** A sample render whose command ran on a machine from `from` to `to`, or is still running. */
9
+ function sample(id: string, from: number, to?: number): ContextFixture {
10
+ return {
11
+ id,
12
+ data: { name: `sample ${id}` },
13
+ transitions: [
14
+ { namespace: "render", atMs: ms(from - 1_000), state: "Running" },
15
+ { namespace: "exec", reporter: `cmd-${id}`, atMs: ms(from), state: "Running" },
16
+ ...(to === undefined
17
+ ? []
18
+ : [
19
+ { namespace: "exec", reporter: `cmd-${id}`, atMs: ms(to), state: "Completed" },
20
+ renderCompleted(ms(to)),
21
+ ]),
22
+ ],
23
+ };
24
+ }
25
+
26
+ describe("foldBlockStatusTree", () => {
27
+ it("opens the root to its top-level nodes and leaves their subtrees collapsed", () => {
28
+ const tree = foldBlockStatusTree(
29
+ context({
30
+ id: "root",
31
+ data: { name: "my block", "run-id": "run-1" },
32
+ children: [{ id: "a", children: [{ id: "a1" }] }, { id: "b" }],
33
+ }),
34
+ none,
35
+ );
36
+
37
+ expect(tree.root?.name).toBe("my block");
38
+ expect(tree.root?.baggage).toEqual({ "run-id": "run-1" });
39
+ expect(tree.root?.children?.map((c) => c.contextId)).toEqual(["a", "b"]);
40
+ expect(tree.root?.children?.[0]).toMatchObject({ childCount: 1, subtreeContexts: 2 });
41
+ expect(tree.root?.children?.[0].children).toBeUndefined();
42
+ });
43
+
44
+ it("shows the children of an expanded node in place", () => {
45
+ const tree = foldBlockStatusTree(
46
+ context({
47
+ id: "root",
48
+ children: [{ id: "a", children: [{ id: "a1", data: { name: "deep" } }] }],
49
+ }),
50
+ new Set(["a"]),
51
+ );
52
+
53
+ expect(tree.root?.children?.[0].children?.map((c) => c.name)).toEqual(["deep"]);
54
+ });
55
+
56
+ it("describes a node: kind, the state holding it as its reporter wrote it, and every transition", () => {
57
+ const tree = foldBlockStatusTree(
58
+ context({
59
+ id: "root",
60
+ children: [
61
+ {
62
+ id: "c",
63
+ transitions: [
64
+ { namespace: "exec", reporter: "cmd", atMs: ms(0), state: "WaitingForMachine" },
65
+ {
66
+ namespace: "exec",
67
+ reporter: "cmd",
68
+ atMs: ms(5),
69
+ state: "SomeFutureState",
70
+ detail: "x",
71
+ },
72
+ ],
73
+ },
74
+ ],
75
+ }),
76
+ none,
77
+ );
78
+
79
+ expect(tree.root?.children?.[0]).toMatchObject({
80
+ kind: "command",
81
+ state: "SomeFutureState",
82
+ enteredAt: ms(5),
83
+ transitions: [
84
+ { namespace: "exec", reporter: "cmd", state: "WaitingForMachine", at: ms(0) },
85
+ { namespace: "exec", reporter: "cmd", state: "SomeFutureState", detail: "x", at: ms(5) },
86
+ ],
87
+ });
88
+ });
89
+
90
+ it("lists readings, grouped by namespace and then by the resource that wrote them", () => {
91
+ const tree = foldBlockStatusTree(
92
+ context({
93
+ id: "root",
94
+ kv: {
95
+ "reading/workdir/wd-2/progress": '{"done":1,"total":2}',
96
+ "reading/exec/cmd-1/peak-ram": "512Mi",
97
+ "reading/workdir/wd-1/progress": '{"done":3,"total":3}',
98
+ "reading/malformed": "dropped",
99
+ },
100
+ }),
101
+ none,
102
+ );
103
+
104
+ expect(tree.root?.readings.map((a) => `${a.namespace}/${a.resource}/${a.key}`)).toEqual([
105
+ "exec/cmd-1/peak-ram",
106
+ "workdir/wd-1/progress",
107
+ "workdir/wd-2/progress",
108
+ ]);
109
+ });
110
+
111
+ it("reports the termination reason of a failed render", () => {
112
+ const tree = foldBlockStatusTree(
113
+ context({
114
+ id: "root",
115
+ transitions: [
116
+ { namespace: "render", atMs: ms(0), state: "Terminated", reason: "OOM killed" },
117
+ ],
118
+ }),
119
+ none,
120
+ );
121
+
122
+ expect(tree.root).toMatchObject({ ended: true, failure: "OOM killed" });
123
+ });
124
+
125
+ it("counts compute per subtree, a running command up to the run's latest report", () => {
126
+ const tree = foldBlockStatusTree(
127
+ context({
128
+ id: "root",
129
+ children: [sample("done", 0, 60_000), sample("running", 30_000)],
130
+ // The latest report anywhere in the run.
131
+ transitions: [{ namespace: "render", atMs: ms(90_000), state: "Running" }],
132
+ }),
133
+ none,
134
+ );
135
+
136
+ const [done, running] = tree.root!.children!;
137
+ expect(done.subtreeComputeMs).toBe(60_000);
138
+ expect(running.subtreeComputeMs).toBe(60_000);
139
+ expect(tree.root?.subtreeComputeMs).toBe(120_000);
140
+ expect(tree.root).toMatchObject({ subtreeContexts: 3, subtreeActiveContexts: 2 });
141
+ });
142
+
143
+ it("ranks the top-level branches by compute and by context count, largest first", () => {
144
+ const tree = foldBlockStatusTree(
145
+ context({
146
+ id: "root",
147
+ children: [
148
+ sample("small", 0, 1_000),
149
+ { ...sample("big", 0, 50_000), children: [{ id: "x" }, { id: "y" }] },
150
+ sample("mid", 0, 10_000),
151
+ ],
152
+ }),
153
+ none,
154
+ );
155
+
156
+ expect(tree.heaviest.byCompute.map((b) => [b.name, b.value])).toEqual([
157
+ ["sample big", 50_000],
158
+ ["sample mid", 10_000],
159
+ ["sample small", 1_000],
160
+ ]);
161
+ expect(tree.heaviest.byContexts[0]).toMatchObject({ contextId: "big", value: 3 });
162
+ expect(tree.heaviest.byFileSize).toBeUndefined();
163
+ });
164
+
165
+ it("carries the run's summary", () => {
166
+ const tree = foldBlockStatusTree(context({ id: "root", children: [sample("a", 0)] }), none);
167
+
168
+ expect(tree.summary.jobs).toMatchObject({
169
+ total: 1,
170
+ byState: [{ namespace: "exec", state: "Running", count: 1 }],
171
+ });
172
+ });
173
+ });
174
+
175
+ describe("firstFailurePath", () => {
176
+ it("leads from the root to the render that terminated first", () => {
177
+ const failed = (id: string, atMs: number): ContextFixture => ({
178
+ id,
179
+ transitions: [{ namespace: "render", atMs, state: "Terminated", reason: "boom" }],
180
+ });
181
+ const tree = foldBlockStatusTree(
182
+ context({
183
+ id: "root",
184
+ children: [
185
+ { id: "a", children: [failed("late", ms(900))] },
186
+ { id: "b", children: [{ id: "b1", children: [failed("early", ms(100))] }] },
187
+ ],
188
+ }),
189
+ none,
190
+ );
191
+
192
+ expect(tree.firstFailurePath).toEqual(["root", "b", "b1", "early"]);
193
+ });
194
+
195
+ it("is undefined while nothing has terminated", () => {
196
+ expect(foldBlockStatusTree(context({ id: "root" }), none).firstFailurePath).toBeUndefined();
197
+ });
198
+ });