@milaboratories/pl-middle-layer 2.3.0 → 2.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/dist/middle_layer/block_status_fold.cjs +51 -6
  2. package/dist/middle_layer/block_status_fold.cjs.map +1 -1
  3. package/dist/middle_layer/block_status_fold.js +50 -7
  4. package/dist/middle_layer/block_status_fold.js.map +1 -1
  5. package/dist/middle_layer/block_status_tree.cjs +39 -9
  6. package/dist/middle_layer/block_status_tree.cjs.map +1 -1
  7. package/dist/middle_layer/block_status_tree.js +39 -9
  8. package/dist/middle_layer/block_status_tree.js.map +1 -1
  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 +22 -2
  16. package/dist/middle_layer/project.cjs.map +1 -1
  17. package/dist/middle_layer/project.d.ts +13 -1
  18. package/dist/middle_layer/project.d.ts.map +1 -1
  19. package/dist/middle_layer/project.js +22 -2
  20. package/dist/middle_layer/project.js.map +1 -1
  21. package/package.json +8 -8
  22. package/src/middle_layer/block_status_bench.test.ts +139 -48
  23. package/src/middle_layer/block_status_fold.test.ts +2 -61
  24. package/src/middle_layer/block_status_fold.ts +68 -6
  25. package/src/middle_layer/block_status_test_utils.ts +62 -0
  26. package/src/middle_layer/block_status_tree.test.ts +23 -0
  27. package/src/middle_layer/block_status_tree.ts +62 -10
  28. package/src/middle_layer/block_status_tree_fold.test.ts +198 -0
  29. package/src/middle_layer/block_status_tree_fold.ts +150 -0
  30. package/src/middle_layer/project.ts +37 -4
@@ -2,56 +2,8 @@ import { describe, expect, it } from "vitest";
2
2
  import type { ActionContextNode } from "./block_status_fold";
3
3
  import { failureHeadline, foldBlockStatus } from "./block_status_fold";
4
4
  import type { BlockStatusJobs, BlockStatusState } from "@milaboratories/pl-model-middle-layer";
5
-
6
- // ── Fixtures ─────────────────────────────────────────────────────────────────
7
-
8
- /** One transition, written the way the reporters write it. */
9
- type TransitionFixture = {
10
- namespace: string;
11
- /** The resource that reported. Defaults to the context's own render. */
12
- reporter?: string;
13
- /** Milliseconds since the epoch; the key carries nanoseconds. */
14
- atMs: number;
15
- state: BlockStatusState | string;
16
- detail?: string;
17
- reason?: string;
18
- };
19
-
20
- type ContextFixture = {
21
- id: string;
22
- data?: Record<string, unknown>;
23
- transitions?: TransitionFixture[];
24
- children?: ContextFixture[];
25
- /** Extra KV entries: readings, and malformed input. */
26
- kv?: Record<string, string>;
27
- };
28
-
29
- /** Builds an {@link ActionContextNode} over a fixture, with the backend's key layout. */
30
- function context(fixture: ContextFixture): ActionContextNode {
31
- const kv = new Map<string, string>(Object.entries(fixture.kv ?? {}));
32
- for (const t of fixture.transitions ?? []) {
33
- const reporter = t.reporter ?? fixture.id;
34
- const ns = String(BigInt(t.atMs) * 1_000_000n);
35
- kv.set(
36
- `transition/${t.namespace}/${reporter}/${ns}`,
37
- JSON.stringify({ state: t.state, detail: t.detail ?? "", reason: t.reason ?? "" }),
38
- );
39
- }
40
-
41
- const children = (fixture.children ?? []).map(context);
42
- const childFields = new Map(children.map((c) => [`child/${c.id}`, c]));
43
-
44
- return {
45
- id: fixture.id,
46
- getData: () => fixture.data,
47
- listKeyValuesAsString: (prefix: string) =>
48
- [...kv.entries()]
49
- .filter(([key]) => key.startsWith(prefix))
50
- .map(([key, value]) => ({ key, value })),
51
- listFields: () => [...childFields.keys()],
52
- traverse: (field: string) => childFields.get(field),
53
- };
54
- }
5
+ import type { ContextFixture, TransitionFixture } from "./block_status_test_utils";
6
+ import { context, ms, renderCompleted } from "./block_status_test_utils";
55
7
 
56
8
  /** The jobs not ended, as `<namespace>/<state>: count`. */
57
9
  function counts(jobs: BlockStatusJobs): Record<string, number> {
@@ -63,17 +15,6 @@ function group(jobs: BlockStatusJobs, key: string) {
63
15
  return jobs.byState.find((g) => `${g.namespace}/${g.state}` === key);
64
16
  }
65
17
 
66
- const t0 = Date.UTC(2026, 9, 27, 12, 0, 0);
67
- const ms = (offset: number) => t0 + offset;
68
-
69
- /** The render's own end, as the workflow controller records it. */
70
- const renderCompleted = (atMs: number, detail?: string): TransitionFixture => ({
71
- namespace: "render",
72
- atMs,
73
- state: "Completed",
74
- detail,
75
- });
76
-
77
18
  // ── The shape of the summary ─────────────────────────────────────────────────
78
19
 
79
20
  describe("foldBlockStatus", () => {
@@ -79,10 +79,10 @@ const RenderNamespace = "render";
79
79
  const CreatorNamespace = "core";
80
80
 
81
81
  /** The namespace a command reports under; its `Running` means a job executing on a machine. */
82
- const ExecNamespace = "exec";
82
+ export const ExecNamespace = "exec";
83
83
 
84
84
  /** The namespace a job's work folder reports under. */
85
- const WorkdirNamespace = "workdir";
85
+ export const WorkdirNamespace = "workdir";
86
86
 
87
87
  /** One transition, as stored under `transition/<namespace>/<resource>/<ns>`. */
88
88
  export type Transition = {
@@ -256,8 +256,44 @@ export type ContextFold = {
256
256
  readonly job: boolean;
257
257
  /** The render's own latest transition, when it is a termination. */
258
258
  readonly terminated?: { readonly reason: string; readonly ns: string };
259
+ /** Time its commands spent in `Running`, see {@link computeOf}. */
260
+ readonly compute: ContextCompute;
259
261
  };
260
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
+
261
297
  function readReadings(node: ActionContextNode): Reading[] {
262
298
  const out: Reading[] = [];
263
299
  for (const { key, value } of node.listKeyValuesAsString(ReadingPrefix)) {
@@ -283,6 +319,7 @@ export function foldContext(node: ActionContextNode): ContextFold {
283
319
  render?.state === blockStatusStatesRecord.Terminated
284
320
  ? { reason: render.reason, ns: render.ns }
285
321
  : undefined,
322
+ compute: computeOf(reports.all),
286
323
  };
287
324
  }
288
325
 
@@ -319,9 +356,25 @@ export type SubtreeFold = {
319
356
  readonly activeContexts: number;
320
357
  readonly firstNs?: string;
321
358
  readonly lastNs?: string;
322
- /** The earliest render in the subtree whose latest report is a termination. */
323
- readonly failure?: { readonly reason: string; readonly ns: 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
+ };
324
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
+ };
325
378
  };
326
379
 
327
380
  /** Files done of all, summed over the work folders' progress readings of one context. */
@@ -392,8 +445,13 @@ export function mergeSubtree(own: ContextFold, children: readonly SubtreeFold[])
392
445
  let activeContexts = own.folded.terminal ? 0 : 1;
393
446
  let firstNs = own.reports.firstNs;
394
447
  let lastNs = own.reports.lastNs;
395
- let failure = own.terminated;
448
+ let failure: SubtreeFold["failure"] =
449
+ own.terminated === undefined ? undefined : { ...own.terminated, path: [own.id] };
396
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);
397
455
 
398
456
  const self = ownJobs(own);
399
457
  let { total, done, failed } = self;
@@ -407,8 +465,11 @@ export function mergeSubtree(own: ContextFold, children: readonly SubtreeFold[])
407
465
  if (child.failure !== undefined) {
408
466
  failedBelow = true;
409
467
  if (failure === undefined || compareNs(child.failure.ns, failure.ns) < 0)
410
- failure = child.failure;
468
+ failure = { ...child.failure, path: [own.id, ...child.failure.path] };
411
469
  }
470
+ closedNs += child.compute.closedNs;
471
+ open += child.compute.open;
472
+ openSinceSumNs += child.compute.openSinceSumNs;
412
473
  total += child.jobs.total;
413
474
  done += child.jobs.done;
414
475
  failed += child.jobs.failed;
@@ -431,6 +492,7 @@ export function mergeSubtree(own: ContextFold, children: readonly SubtreeFold[])
431
492
  lastNs,
432
493
  failure,
433
494
  jobs: { total, done, failed, groups },
495
+ compute: { closedNs, open, openSinceSumNs },
434
496
  };
435
497
  }
436
498
 
@@ -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
+ });
@@ -251,3 +251,26 @@ test("closing the project terminates its watches and refuses new ones", async ()
251
251
  await expect(prj.watchBlockStatus(blockId)).rejects.toThrow(/project is closed/);
252
252
  });
253
253
  }, 120_000);
254
+
255
+ test("the tree shares the watch and follows the expansion", async () => {
256
+ await withMl(async (ml) => {
257
+ const { prj, blockId } = await projectWithBlock(ml);
258
+ const run = await plantRoot(ml.pl, prj, blockId);
259
+
260
+ const summary = await prj.watchBlockStatus(blockId);
261
+ const tree = await prj.watchBlockStatusTree(blockId);
262
+ const first = await tree.getValue();
263
+ expect(first.summary.runId).toBe(run);
264
+ expect(first.root?.children).toEqual([]);
265
+
266
+ // The expansion is the tree's own input: setting it recomputes the tree.
267
+ await prj.setBlockStatusTreeExpanded(blockId, [first.root!.contextId]);
268
+ await tree.getValue();
269
+
270
+ // The tree holds the watch on its own once the summary lets go.
271
+ await prj.unwatchBlockStatus(blockId);
272
+ expect((await summary.getValue()).runId).toBe(run);
273
+ await prj.unwatchBlockStatus(blockId);
274
+ expect((await tree.getValue()).summary.runId).toBeUndefined();
275
+ });
276
+ }, 120_000);
@@ -1,5 +1,5 @@
1
1
  /**
2
- * The live action-context tree of one block render, and the computable that folds it.
2
+ * The live action-context tree of one block render, and the computables that fold it.
3
3
  *
4
4
  * A status tree is its own {@link SynchronizedTreeState}, seeded at the root action context of the
5
5
  * render rather than at the project. It has to be separate: the project tree prunes the context
@@ -14,7 +14,7 @@ import { isNullSignedResourceId, ResourceTypeName, treeFilter } from "@milaborat
14
14
  import { Computable, WatchableValue } from "@milaboratories/computable";
15
15
  import type { PlTreeEntry, PlTreeNodeAccessor } from "@milaboratories/pl-tree";
16
16
  import { SynchronizedTreeState } from "@milaboratories/pl-tree";
17
- import type { BlockStatusSummary } from "@milaboratories/pl-model-middle-layer";
17
+ import type { BlockStatusSummary, BlockStatusTree } from "@milaboratories/pl-model-middle-layer";
18
18
  import {
19
19
  EmptyBlockStatusSummary,
20
20
  UnreadableBlockStatusSummary,
@@ -23,6 +23,7 @@ import {
23
23
  import { setTimeout } from "node:timers/promises";
24
24
  import type { ActionContextNode, SubtreeFold } from "./block_status_fold";
25
25
  import { childContexts, foldContext, mergeSubtree, summarize } from "./block_status_fold";
26
+ import { blockStatusTree, emptyBlockStatusTree } from "./block_status_tree_fold";
26
27
  import type { BlockActionContextMode } from "./block_action_context";
27
28
  import { ActionContextLinkCapability } from "../mutator/template/render_block";
28
29
  import { projectFieldName } from "../model/project_model";
@@ -149,17 +150,23 @@ export function entrySummary(
149
150
  ): Computable<BlockStatusSummary> {
150
151
  return Computable.make(() => ({ fold: subtreeFold(entry, new Set(), onError) }), {
151
152
  key: `block-status-summary/${entry.id}`,
152
- postprocessValue: ({ fold }) => {
153
- // The counters of a context that could not be read are unknown, not zero.
154
- if (fold === undefined) return UnreadableBlockStatusSummary;
155
- const summary = summarize(fold);
156
- if (reportsSupported || summary.totalContexts === 0) return summary;
157
- // The context exists and carries its data, but no transition can ever arrive.
158
- return { ...summary, availability: "unsupported" as const };
159
- },
153
+ postprocessValue: ({ fold }) => summaryOfFold(fold, reportsSupported),
160
154
  });
161
155
  }
162
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
+
163
170
  /** What {@link BlockStatusWatch.start} watches. */
164
171
  export type BlockStatusWatchParams = {
165
172
  readonly env: MiddleLayerEnvironment;
@@ -197,6 +204,18 @@ export class BlockStatusWatch {
197
204
 
198
205
  public readonly summary: Computable<BlockStatusSummary>;
199
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
+
200
219
  private readonly env: MiddleLayerEnvironment;
201
220
  private readonly projectRid: SignedResourceId;
202
221
  private readonly blockId: string;
@@ -227,6 +246,38 @@ export class BlockStatusWatch {
227
246
  this.env.logger.warn(new Error("block status fold failed", { cause: err })),
228
247
  );
229
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");
230
281
  }
231
282
 
232
283
  /**
@@ -294,6 +345,7 @@ export class BlockStatusWatch {
294
345
  this.current = undefined;
295
346
  this.source.setValue(undefined, "block status watch terminated");
296
347
  this.summary.resetState();
348
+ this.tree.resetState();
297
349
  await this.terminateTree(held?.tree);
298
350
  }
299
351
 
@@ -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
+ });