@milaboratories/pl-middle-layer 2.3.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 (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 +7 -7
  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
@@ -130,7 +130,7 @@ function foldNode(transitions) {
130
130
  return {
131
131
  terminal: false,
132
132
  holding,
133
- onMachine: holding?.state === _milaboratories_pl_model_middle_layer.blockStatusStatesRecord.Running && holding.namespace === ExecNamespace
133
+ onMachine: holding?.state === _milaboratories_pl_model_middle_layer.blockStatusStatesRecord.Running && holding.namespace === "exec"
134
134
  };
135
135
  }
136
136
  /** The render's own latest transition in a context. */
@@ -139,6 +139,30 @@ function latestRender(transitions) {
139
139
  for (const t of transitions) if (t.namespace === RenderNamespace && (latest === void 0 || compareNs(t.ns, latest.ns) > 0)) latest = t;
140
140
  return latest;
141
141
  }
142
+ function computeOf(all) {
143
+ const byReporter = /* @__PURE__ */ new Map();
144
+ for (const t of all) {
145
+ if (t.namespace !== "exec") continue;
146
+ const list = byReporter.get(t.reporter);
147
+ if (list === void 0) byReporter.set(t.reporter, [t]);
148
+ else list.push(t);
149
+ }
150
+ let closedNs = 0n;
151
+ const openSinceNs = [];
152
+ for (const list of byReporter.values()) {
153
+ list.sort((a, b) => compareNs(a.ns, b.ns));
154
+ for (let i = 0; i < list.length; i++) {
155
+ if (list[i].state !== _milaboratories_pl_model_middle_layer.blockStatusStatesRecord.Running) continue;
156
+ const next = list[i + 1];
157
+ if (next === void 0) openSinceNs.push(list[i].ns);
158
+ else closedNs += BigInt(next.ns) - BigInt(list[i].ns);
159
+ }
160
+ }
161
+ return {
162
+ closedNs,
163
+ openSinceNs
164
+ };
165
+ }
142
166
  function readReadings(node) {
143
167
  const out = [];
144
168
  for (const { key, value } of node.listKeyValuesAsString(ReadingPrefix)) {
@@ -163,11 +187,12 @@ function foldContext(node) {
163
187
  reports,
164
188
  readings: readReadings(node),
165
189
  folded: foldNode(reports.all),
166
- job: reports.all.some((t) => t.namespace === ExecNamespace || t.namespace === WorkdirNamespace),
190
+ job: reports.all.some((t) => t.namespace === "exec" || t.namespace === "workdir"),
167
191
  terminated: render?.state === _milaboratories_pl_model_middle_layer.blockStatusStatesRecord.Terminated ? {
168
192
  reason: render.reason,
169
193
  ns: render.ns
170
- } : void 0
194
+ } : void 0,
195
+ compute: computeOf(reports.all)
171
196
  };
172
197
  }
173
198
  const EmptyJobTally = {
@@ -180,7 +205,7 @@ const EmptyJobTally = {
180
205
  function workdirProgress(readings) {
181
206
  let progress;
182
207
  for (const r of readings) {
183
- if (r.namespace !== WorkdirNamespace || r.key !== "progress") continue;
208
+ if (r.namespace !== "workdir" || r.key !== "progress") continue;
184
209
  const parsed = parseJsonObject(r.value);
185
210
  if (typeof parsed?.done !== "number" || typeof parsed.total !== "number") continue;
186
211
  progress = addFiles(progress, {
@@ -250,8 +275,15 @@ function mergeSubtree(own, children) {
250
275
  let activeContexts = own.folded.terminal ? 0 : 1;
251
276
  let firstNs = own.reports.firstNs;
252
277
  let lastNs = own.reports.lastNs;
253
- let failure = own.terminated;
278
+ let failure = own.terminated === void 0 ? void 0 : {
279
+ ...own.terminated,
280
+ path: [own.id]
281
+ };
254
282
  let failedBelow = false;
283
+ let closedNs = own.compute.closedNs;
284
+ let open = own.compute.openSinceNs.length;
285
+ let openSinceSumNs = 0n;
286
+ for (const since of own.compute.openSinceNs) openSinceSumNs += BigInt(since);
255
287
  const self = ownJobs(own);
256
288
  let { total, done, failed } = self;
257
289
  const groups = { ...self.groups };
@@ -262,8 +294,14 @@ function mergeSubtree(own, children) {
262
294
  lastNs = later(lastNs, child.lastNs);
263
295
  if (child.failure !== void 0) {
264
296
  failedBelow = true;
265
- if (failure === void 0 || compareNs(child.failure.ns, failure.ns) < 0) failure = child.failure;
297
+ if (failure === void 0 || compareNs(child.failure.ns, failure.ns) < 0) failure = {
298
+ ...child.failure,
299
+ path: [own.id, ...child.failure.path]
300
+ };
266
301
  }
302
+ closedNs += child.compute.closedNs;
303
+ open += child.compute.open;
304
+ openSinceSumNs += child.compute.openSinceSumNs;
267
305
  total += child.jobs.total;
268
306
  done += child.jobs.done;
269
307
  failed += child.jobs.failed;
@@ -286,6 +324,11 @@ function mergeSubtree(own, children) {
286
324
  done,
287
325
  failed,
288
326
  groups
327
+ },
328
+ compute: {
329
+ closedNs,
330
+ open,
331
+ openSinceSumNs
289
332
  }
290
333
  };
291
334
  }
@@ -368,6 +411,8 @@ function summarize(root) {
368
411
  failure: root.failure === void 0 ? void 0 : failureHeadline(root.failure.reason)
369
412
  };
370
413
  }
414
+ exports.ExecNamespace = ExecNamespace;
415
+ exports.WorkdirNamespace = WorkdirNamespace;
371
416
  exports.childContexts = childContexts;
372
417
  exports.compareNs = compareNs;
373
418
  exports.failureHeadline = failureHeadline;
@@ -1 +1 @@
1
- {"version":3,"file":"block_status_fold.cjs","names":["blockStatusStatesRecord","isTerminalBlockStatusState"],"sources":["../../src/middle_layer/block_status_fold.ts"],"sourcesContent":["/**\n * Folds a block's action-context tree into the {@link BlockStatusSummary} the Desktop App shows.\n *\n * The fold runs bottom up: {@link foldContext} reads one context on its own, and\n * {@link mergeSubtree} merges it with the folds of its children. Over a synchronized tree each\n * context gets its own computable (see `block_status_tree.ts`), so a report re-reads only the\n * context it landed in and re-merges the contexts above it; the rest of the tree is not read\n * again.\n *\n * The fold attaches no meaning to the states the reporters write, beyond the lifecycle the backend\n * fixes: a context ends in `Completed` or `Terminated`, and a command's `Running` is work on a\n * machine. Jobs are counted per state as reported, so a state added on the backend reaches the\n * Desktop App without a middle layer release.\n */\n\nimport type {\n BlockStatusJobGroup,\n BlockStatusJobs,\n BlockStatusSummary,\n} from \"@milaboratories/pl-model-middle-layer\";\nimport {\n blockStatusStatesRecord,\n isTerminalBlockStatusState,\n} from \"@milaboratories/pl-model-middle-layer\";\n\n/**\n * A key-value written as a JSON object, with its fields unchecked; undefined for anything else.\n * A reporter may write any JSON, so `null` or a bare number must not reach a field read.\n */\nfunction parseJsonObject(value: string): Record<string, unknown> | undefined {\n let parsed: unknown;\n try {\n parsed = JSON.parse(value);\n } catch {\n return undefined;\n }\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) return undefined;\n return Object.fromEntries(Object.entries(parsed));\n}\n\n/** The part of an action context a fold reads. A tree node accessor satisfies it. */\nexport interface ActionContextNode {\n /** Stable identity of the context, for deduplicating a walk. */\n readonly id: string;\n /** The context's baggage: `name`, `block-pack`, `block-id`, `run-id`. */\n getData(): Record<string, unknown> | undefined;\n /** KV entries under a prefix, values as text. */\n listKeyValuesAsString(prefix: string): { key: string; value: string }[];\n /** Field names, whatever their type: the children are `child/<render>`. */\n listFields(): string[];\n /** The context a field points at, or undefined while the field is unset. */\n traverse(field: string): ActionContextNode | undefined;\n}\n\n/**\n * How deep the fold follows `child/<render>`.\n *\n * A stack guard, not a correctness device: a context already on the path is skipped, and the depth\n * of a real tree is the nesting depth of the templates, far below this.\n */\nexport const MaxDepth = 256;\n\n/** Prefix of the field names holding child contexts. */\nconst ChildFieldPrefix = \"child/\";\n\n/** Prefix of the transition keys: `transition/<namespace>/<resource>/<ns>`. */\nconst TransitionPrefix = \"transition/\";\n\n/** Prefix of the reading keys: `reading/<namespace>/<resource>/<key>`. */\nconst ReadingPrefix = \"reading/\";\n\n/** The namespace the workflow controller reports a render's own lifecycle under. */\nconst RenderNamespace = \"render\";\n\n/**\n * The namespace the creator of a context reports under. The middle layer records `Terminated` here\n * on the root when the user stops the run, see `recordBlockRunCancelled`.\n */\nconst CreatorNamespace = \"core\";\n\n/** The namespace a command reports under; its `Running` means a job executing on a machine. */\nconst ExecNamespace = \"exec\";\n\n/** The namespace a job's work folder reports under. */\nconst WorkdirNamespace = \"workdir\";\n\n/** One transition, as stored under `transition/<namespace>/<resource>/<ns>`. */\nexport type Transition = {\n namespace: string;\n /** The resource that reported: the render itself, or a command or work dir it created. */\n reporter: string;\n /** The reporter's clock in nanoseconds, as the decimal string the key carries. */\n ns: string;\n /** As the reporter wrote it, whether or not this build knows the name. */\n state: string;\n detail: string;\n reason: string;\n};\n\n/** What one context reported. */\nexport type ContextReports = {\n /** Every transition whose key and value parse. */\n all: Transition[];\n /** The earliest and latest timestamp of any transition key, even one whose value does not\n * parse: a report arriving is evidence the run moved whatever it says. */\n firstNs?: string;\n lastNs?: string;\n};\n\n/** A node of the tree, reduced to what the summary needs. */\nexport type FoldedNode = {\n /** True when the render of this context has ended and nothing it started is still running. */\n terminal: boolean;\n /** The reason, set when the render itself ended in a termination rather than a completion. */\n failure?: string;\n /** The transition holding this node, undefined when it is terminal or has not reported. */\n holding?: Transition;\n /** True when {@link FoldedNode.holding} is `Running` reported by a command. */\n onMachine: boolean;\n};\n\n/** Compares non-negative decimal integers given as strings, shorter is smaller. */\nexport function compareNs(a: string, b: string): number {\n return a.length !== b.length ? a.length - b.length : a < b ? -1 : a > b ? 1 : 0;\n}\n\n/** Nanoseconds since the epoch, as the key carries them, to milliseconds. */\nexport function nsToMs(ns: string): number {\n return Number(BigInt(ns) / 1_000_000n);\n}\n\nfunction earlier(a: string | undefined, b: string | undefined): string | undefined {\n return a === undefined || (b !== undefined && compareNs(b, a) < 0) ? b : a;\n}\n\nfunction later(a: string | undefined, b: string | undefined): string | undefined {\n return a === undefined || (b !== undefined && compareNs(b, a) > 0) ? b : a;\n}\n\n/**\n * How strongly a report claims to be what holds a node.\n *\n * The render's own `Running` means only that template code is being evaluated, and the workflow\n * controller records it again on every evaluation, so it routinely carries a newer timestamp than\n * the wait that actually holds the node. Anything else outranks it however old it is, including a\n * command's `Running`, which is real work. Recency decides only between equal ranks.\n */\nfunction rank(t: Transition): number {\n return t.state === blockStatusStatesRecord.Running && t.namespace === RenderNamespace ? 0 : 1;\n}\n\n/**\n * The transitions of one context.\n *\n * A value that is not the JSON the reporters write is left out: a report is diagnostic, and a\n * malformed one must not break the surface. Its timestamp still counts.\n */\nexport function readTransitions(node: ActionContextNode): ContextReports {\n const out: ContextReports = { all: [] };\n\n for (const { key, value } of node.listKeyValuesAsString(TransitionPrefix)) {\n const parts = key.split(\"/\");\n if (parts.length !== 4) continue;\n const [, namespace, reporter, ns] = parts;\n // Leading zeros would break the length-first comparison, and no reporter writes them.\n if (!/^(0|[1-9]\\d*)$/.test(ns)) continue;\n\n out.firstNs = earlier(out.firstNs, ns);\n out.lastNs = later(out.lastNs, ns);\n\n const parsed = parseJsonObject(value);\n if (parsed === undefined) continue;\n const state = parsed.state;\n if (typeof state !== \"string\") continue;\n const detail = typeof parsed.detail === \"string\" ? parsed.detail : \"\";\n const reason = typeof parsed.reason === \"string\" ? parsed.reason : \"\";\n out.all.push({ namespace, reporter, ns, state, detail, reason });\n }\n\n return out;\n}\n\n/**\n * Reduces one context to {@link FoldedNode}.\n *\n * A context carries the reports of several reporters: the render reports under `render`, and the\n * commands and work dirs it created report under `exec` and `workdir`. The latest transition of\n * each reporter is that reporter's current state, and the state holding the node is the strongest\n * of those a reporter has not left, see {@link rank}.\n *\n * The node has ended when the render has reported its own end (`Completed` once its outputs are\n * set, `Terminated` with its error, or `Completed` with detail `deduplicated`) and every other\n * reporter in the context has ended too: the render's outputs being set does not stop a command it\n * started, and that command's report must stay visible.\n */\nexport function foldNode(transitions: readonly Transition[]): FoldedNode {\n const latestPerReporter = new Map<string, Transition>();\n for (const t of transitions) {\n const reporterKey = `${t.namespace}/${t.reporter}`;\n const previous = latestPerReporter.get(reporterKey);\n if (previous === undefined || compareNs(t.ns, previous.ns) > 0)\n latestPerReporter.set(reporterKey, t);\n }\n\n let render: Transition | undefined;\n let holding: Transition | undefined;\n let everyReporterEnded = true;\n for (const t of latestPerReporter.values()) {\n if (t.namespace === RenderNamespace) render = t;\n if (isTerminalBlockStatusState(t.state)) continue;\n everyReporterEnded = false;\n if (holding === undefined) {\n holding = t;\n continue;\n }\n const byRank = rank(t) - rank(holding);\n if (byRank > 0 || (byRank === 0 && compareNs(t.ns, holding.ns) > 0)) holding = t;\n }\n\n if (render !== undefined && isTerminalBlockStatusState(render.state) && everyReporterEnded)\n return {\n terminal: true,\n onMachine: false,\n failure: render.state === blockStatusStatesRecord.Terminated ? render.reason : undefined,\n };\n\n return {\n terminal: false,\n holding,\n onMachine:\n holding?.state === blockStatusStatesRecord.Running && holding.namespace === ExecNamespace,\n };\n}\n\n/** The render's own latest transition in a context. */\nexport function latestRender(transitions: readonly Transition[]): Transition | undefined {\n let latest: Transition | undefined;\n for (const t of transitions)\n if (t.namespace === RenderNamespace && (latest === undefined || compareNs(t.ns, latest.ns) > 0))\n latest = t;\n return latest;\n}\n\n/** One reading, as stored under `reading/<namespace>/<resource>/<key>`. */\nexport type Reading = { namespace: string; resource: string; key: string; value: string };\n\n/** One context read on its own, before its children are merged in. */\nexport type ContextFold = {\n readonly id: string;\n /** The baggage: `name`, `block-pack`, `block-id`, `run-id`. */\n readonly data: Record<string, unknown> | undefined;\n readonly reports: ContextReports;\n readonly readings: readonly Reading[];\n readonly folded: FoldedNode;\n /** True for a context a command or its work folder reports in: one job. */\n readonly job: boolean;\n /** The render's own latest transition, when it is a termination. */\n readonly terminated?: { readonly reason: string; readonly ns: string };\n};\n\nfunction readReadings(node: ActionContextNode): Reading[] {\n const out: Reading[] = [];\n for (const { key, value } of node.listKeyValuesAsString(ReadingPrefix)) {\n const parts = key.split(\"/\");\n if (parts.length !== 4) continue;\n out.push({ namespace: parts[1], resource: parts[2], key: parts[3], value });\n }\n return out;\n}\n\n/** Reads one context: its transitions, its readings, and the state holding it. */\nexport function foldContext(node: ActionContextNode): ContextFold {\n const reports = readTransitions(node);\n const render = latestRender(reports.all);\n return {\n id: node.id,\n data: node.getData(),\n reports,\n readings: readReadings(node),\n folded: foldNode(reports.all),\n job: reports.all.some((t) => t.namespace === ExecNamespace || t.namespace === WorkdirNamespace),\n terminated:\n render?.state === blockStatusStatesRecord.Terminated\n ? { reason: render.reason, ns: render.ns }\n : undefined,\n };\n}\n\n/** {@link BlockStatusJobGroup} being accumulated, its timestamp still in nanoseconds. */\ntype JobGroupTally = {\n readonly namespace: string;\n readonly state: string;\n readonly count: number;\n readonly sinceNs?: string;\n readonly files?: { readonly done: number; readonly total: number };\n};\n\n/**\n * {@link BlockStatusJobs} being accumulated over a subtree. Plain data throughout, no `Map`: it is\n * the value of a computable, which the computable types map over field by field.\n */\nexport type JobTally = {\n readonly total: number;\n readonly done: number;\n readonly failed: number;\n /** Jobs not ended, by `<namespace>/<state>` of the transition holding each. */\n readonly groups: Readonly<Record<string, JobGroupTally>>;\n};\n\nconst EmptyJobTally: JobTally = { total: 0, done: 0, failed: 0, groups: {} };\n\n/** A context and everything under it, folded. */\nexport type SubtreeFold = {\n readonly own: ContextFold;\n readonly children: readonly SubtreeFold[];\n /** This context and every context under it. */\n readonly contexts: number;\n /** Contexts in the subtree that have not ended. */\n readonly activeContexts: number;\n readonly firstNs?: string;\n readonly lastNs?: string;\n /** The earliest render in the subtree whose latest report is a termination. */\n readonly failure?: { readonly reason: string; readonly ns: string };\n readonly jobs: JobTally;\n};\n\n/** Files done of all, summed over the work folders' progress readings of one context. */\nfunction workdirProgress(readings: readonly Reading[]): JobGroupTally[\"files\"] {\n let progress: JobGroupTally[\"files\"];\n for (const r of readings) {\n if (r.namespace !== WorkdirNamespace || r.key !== \"progress\") continue;\n const parsed = parseJsonObject(r.value);\n if (typeof parsed?.done !== \"number\" || typeof parsed.total !== \"number\") continue;\n progress = addFiles(progress, { done: parsed.done, total: parsed.total });\n }\n return progress;\n}\n\nfunction addFiles(a: JobGroupTally[\"files\"], b: JobGroupTally[\"files\"]): JobGroupTally[\"files\"] {\n if (a === undefined) return b;\n if (b === undefined) return a;\n return { done: a.done + b.done, total: a.total + b.total };\n}\n\nfunction groupKey(group: Pick<JobGroupTally, \"namespace\" | \"state\">): string {\n return `${group.namespace}/${group.state}`;\n}\n\nfunction mergeGroup(\n groups: Record<string, JobGroupTally>,\n key: string,\n group: JobGroupTally,\n): void {\n const previous = groups[key];\n groups[key] =\n previous === undefined\n ? group\n : {\n namespace: group.namespace,\n state: group.state,\n count: previous.count + group.count,\n sinceNs: earlier(previous.sinceNs, group.sinceNs),\n files: addFiles(previous.files, group.files),\n };\n}\n\n/** The job a context is, counted where it is now; empty when it is not one. */\nfunction ownJobs(own: ContextFold): JobTally {\n if (!own.job) return EmptyJobTally;\n const { terminal, failure, holding } = own.folded;\n if (terminal)\n return failure === undefined\n ? { ...EmptyJobTally, total: 1, done: 1 }\n : { ...EmptyJobTally, total: 1, failed: 1 };\n if (holding === undefined) return { ...EmptyJobTally, total: 1 };\n const group: JobGroupTally = {\n namespace: holding.namespace,\n state: holding.state,\n count: 1,\n sinceNs: holding.ns,\n files: workdirProgress(own.readings),\n };\n return { ...EmptyJobTally, total: 1, groups: { [groupKey(group)]: group } };\n}\n\n/**\n * Merges a context with the folds of its children. One pass over the direct children, so a report\n * re-merges each context on its path to the root and nothing else.\n */\nexport function mergeSubtree(own: ContextFold, children: readonly SubtreeFold[]): SubtreeFold {\n let contexts = 1;\n let activeContexts = own.folded.terminal ? 0 : 1;\n let firstNs = own.reports.firstNs;\n let lastNs = own.reports.lastNs;\n let failure = own.terminated;\n let failedBelow = false;\n\n const self = ownJobs(own);\n let { total, done, failed } = self;\n const groups: Record<string, JobGroupTally> = { ...self.groups };\n\n for (const child of children) {\n contexts += child.contexts;\n activeContexts += child.activeContexts;\n firstNs = earlier(firstNs, child.firstNs);\n lastNs = later(lastNs, child.lastNs);\n if (child.failure !== undefined) {\n failedBelow = true;\n if (failure === undefined || compareNs(child.failure.ns, failure.ns) < 0)\n failure = child.failure;\n }\n total += child.jobs.total;\n done += child.jobs.done;\n failed += child.jobs.failed;\n for (const [key, group] of Object.entries(child.jobs.groups)) mergeGroup(groups, key, group);\n }\n\n // A render that failed on its own, e.g. one whose command could not start, is a failed job too;\n // one that only passes up the failure under it is not counted again.\n if (own.terminated !== undefined && !failedBelow && !own.job) {\n total++;\n failed++;\n }\n\n return {\n own,\n children,\n contexts,\n activeContexts,\n firstNs,\n lastNs,\n failure,\n jobs: { total, done, failed, groups },\n };\n}\n\n/**\n * The child contexts a fold follows: each once, and none already on the path from the root, so a\n * context linked twice or a cycle cannot count a subtree again.\n */\nexport function childContexts<T extends { readonly id: unknown }>(\n fields: readonly string[],\n traverse: (field: string) => T | undefined,\n path: ReadonlySet<string>,\n): T[] {\n if (path.size > MaxDepth) return [];\n const out: T[] = [];\n const seen = new Set<string>();\n for (const field of fields) {\n if (!field.startsWith(ChildFieldPrefix)) continue;\n const child = traverse(field);\n if (child === undefined) continue;\n const id = String(child.id);\n if (path.has(id) || seen.has(id)) continue;\n seen.add(id);\n out.push(child);\n }\n return out;\n}\n\n/**\n * Folds a context and everything under it in one walk: what the per-context computables compute,\n * for a tree that is read once.\n */\nexport function foldSubtree(\n node: ActionContextNode,\n path: ReadonlySet<string> = new Set(),\n): SubtreeFold {\n const below = new Set(path).add(node.id);\n const children = childContexts(node.listFields(), (f) => node.traverse(f), below);\n return mergeSubtree(\n foldContext(node),\n children.map((child) => foldSubtree(child, below)),\n );\n}\n\n/** Where the backend nests the error of an input inside the error of what consumes it. */\nconst InputErrorMarker = \"has input errors:\";\n\n/** Wrappers the workflow controller puts in front of a template's own error. */\nconst TemplateErrorPrefix = /^(cannot eval code: |cannot eval template: |tengo template error: )+/;\n\n/** Longest headline, in characters. */\nconst MaxHeadlineLength = 200;\n\n/**\n * The innermost message of a termination reason, for a title: the backend wraps the error of each\n * input in the error of its consumer, and tengo appends stack frames, so a reason can run to pages.\n */\nexport function failureHeadline(reason: string): string {\n const marker = reason.lastIndexOf(InputErrorMarker);\n const lines = reason\n .slice(marker < 0 ? 0 : marker + InputErrorMarker.length)\n .split(\"\\n\")\n .map((line) => line.trim())\n // Stack frames: `@platforma-sdk/workflow-tengo:tpl.base:595:5`.\n .filter((line) => line !== \"\" && !/^@\\S+:\\d+:\\d+$/.test(line));\n\n const text = lines.join(\" \");\n // A command that failed: `Command ID: … Command name: \"python\" … Error: docker is not set`.\n const command = /Command name: \"([^\"]*)\".*\\bError: (.+)$/.exec(text);\n const headline =\n command !== null\n ? `${command[1]} failed: ${command[2]}`\n : text.replace(TemplateErrorPrefix, \"\");\n return headline.length > MaxHeadlineLength\n ? `${headline.slice(0, MaxHeadlineLength - 1)}…`\n : headline;\n}\n\nfunction finishJobs(jobs: JobTally): BlockStatusJobs {\n const byState = Object.values(jobs.groups)\n .map((g): BlockStatusJobGroup => ({\n namespace: g.namespace,\n state: g.state,\n count: g.count,\n since: g.sinceNs === undefined ? undefined : nsToMs(g.sinceNs),\n files: g.files,\n }))\n .sort((a, b) => b.count - a.count || groupKey(a).localeCompare(groupKey(b)));\n return { total: jobs.total, done: jobs.done, failed: jobs.failed, byState };\n}\n\n/** The summary of a block run, from the fold of its root action context. */\nexport function summarize(root: SubtreeFold): BlockStatusSummary {\n const runId = root.own.data?.[\"run-id\"];\n const jobs = finishJobs(root.jobs);\n const summary = {\n availability: \"read\" as const,\n runId: typeof runId === \"string\" ? runId : undefined,\n activeContexts: root.activeContexts,\n totalContexts: root.contexts,\n jobs,\n startedAt: root.firstNs === undefined ? undefined : nsToMs(root.firstNs),\n };\n\n // A stopped run: its render is gone and reports nothing more, so the tree is frozen where it\n // stopped. The counters stay, to say where each node was; the run itself is over.\n let cancelledNs: string | undefined;\n for (const t of root.own.reports.all)\n if (t.namespace === CreatorNamespace && t.state === blockStatusStatesRecord.Terminated)\n cancelledNs = later(cancelledNs, t.ns);\n if (cancelledNs !== undefined)\n return { ...summary, lastChangeAt: nsToMs(cancelledNs), done: true, cancelled: true };\n\n // A terminated render fails the run. Renders waiting on its outputs never report again, so once\n // no job is held by its command or work folder the run is over, though they still look active.\n const working = jobs.byState.some((g) => g.namespace !== RenderNamespace);\n return {\n ...summary,\n lastChangeAt: root.lastNs === undefined ? undefined : nsToMs(root.lastNs),\n // The root's outputs can be set while work it started still runs, so done needs both.\n done:\n (root.own.folded.terminal && root.activeContexts === 0) ||\n (root.failure !== undefined && !working),\n failure: root.failure === undefined ? undefined : failureHeadline(root.failure.reason),\n };\n}\n\n/** The summary of a block run, from the root action context of its render. */\nexport function foldBlockStatus(root: ActionContextNode): BlockStatusSummary {\n return summarize(foldSubtree(root));\n}\n"],"mappings":";;;;;;AA6BA,SAAS,gBAAgB,OAAoD;CAC3E,IAAI;CACJ,IAAI;EACF,SAAS,KAAK,MAAM,KAAK;CAC3B,QAAQ;EACN;CACF;CACA,IAAI,OAAO,WAAW,YAAY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AM,OAAO,WAAW,KAAK,IAAI;CACjC,MAAM,UAAU;EACd,cAAc;EACd,OAAO,OAAO,UAAU,WAAW,QAAQ,KAAA;EAC3C,gBAAgB,KAAK;EACrB,eAAe,KAAK;EACpB;EACA,WAAW,KAAK,YAAY,KAAA,IAAY,KAAA,IAAY,OAAO,KAAK,OAAO;CACzE;CAIA,IAAI;CACJ,KAAK,MAAM,KAAK,KAAK,IAAI,QAAQ,KAC/B,IAAI,EAAE,cAAc,oBAAoB,EAAE,UAAUA,sCAAAA,wBAAwB,YAC1E,cAAc,MAAM,aAAa,EAAE,EAAE;CACzC,IAAI,gBAAgB,KAAA,GAClB,OAAO;EAAE,GAAG;EAAS,cAAc,OAAO,WAAW;EAAG,MAAM;EAAM,WAAW;CAAK;CAItF,MAAM,UAAU,KAAK,QAAQ,MAAM,MAAM,EAAE,cAAc,eAAe;CACxE,OAAO;EACL,GAAG;EACH,cAAc,KAAK,WAAW,KAAA,IAAY,KAAA,IAAY,OAAO,KAAK,MAAM;EAExE,MACG,KAAK,IAAI,OAAO,YAAY,KAAK,mBAAmB,KACpD,KAAK,YAAY,KAAA,KAAa,CAAC;EAClC,SAAS,KAAK,YAAY,KAAA,IAAY,KAAA,IAAY,gBAAgB,KAAK,QAAQ,MAAM;CACvF;AACF"}
1
+ {"version":3,"file":"block_status_fold.cjs","names":["blockStatusStatesRecord","isTerminalBlockStatusState"],"sources":["../../src/middle_layer/block_status_fold.ts"],"sourcesContent":["/**\n * Folds a block's action-context tree into the {@link BlockStatusSummary} the Desktop App shows.\n *\n * The fold runs bottom up: {@link foldContext} reads one context on its own, and\n * {@link mergeSubtree} merges it with the folds of its children. Over a synchronized tree each\n * context gets its own computable (see `block_status_tree.ts`), so a report re-reads only the\n * context it landed in and re-merges the contexts above it; the rest of the tree is not read\n * again.\n *\n * The fold attaches no meaning to the states the reporters write, beyond the lifecycle the backend\n * fixes: a context ends in `Completed` or `Terminated`, and a command's `Running` is work on a\n * machine. Jobs are counted per state as reported, so a state added on the backend reaches the\n * Desktop App without a middle layer release.\n */\n\nimport type {\n BlockStatusJobGroup,\n BlockStatusJobs,\n BlockStatusSummary,\n} from \"@milaboratories/pl-model-middle-layer\";\nimport {\n blockStatusStatesRecord,\n isTerminalBlockStatusState,\n} from \"@milaboratories/pl-model-middle-layer\";\n\n/**\n * A key-value written as a JSON object, with its fields unchecked; undefined for anything else.\n * A reporter may write any JSON, so `null` or a bare number must not reach a field read.\n */\nfunction parseJsonObject(value: string): Record<string, unknown> | undefined {\n let parsed: unknown;\n try {\n parsed = JSON.parse(value);\n } catch {\n return undefined;\n }\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) return undefined;\n return Object.fromEntries(Object.entries(parsed));\n}\n\n/** The part of an action context a fold reads. A tree node accessor satisfies it. */\nexport interface ActionContextNode {\n /** Stable identity of the context, for deduplicating a walk. */\n readonly id: string;\n /** The context's baggage: `name`, `block-pack`, `block-id`, `run-id`. */\n getData(): Record<string, unknown> | undefined;\n /** KV entries under a prefix, values as text. */\n listKeyValuesAsString(prefix: string): { key: string; value: string }[];\n /** Field names, whatever their type: the children are `child/<render>`. */\n listFields(): string[];\n /** The context a field points at, or undefined while the field is unset. */\n traverse(field: string): ActionContextNode | undefined;\n}\n\n/**\n * How deep the fold follows `child/<render>`.\n *\n * A stack guard, not a correctness device: a context already on the path is skipped, and the depth\n * of a real tree is the nesting depth of the templates, far below this.\n */\nexport const MaxDepth = 256;\n\n/** Prefix of the field names holding child contexts. */\nconst ChildFieldPrefix = \"child/\";\n\n/** Prefix of the transition keys: `transition/<namespace>/<resource>/<ns>`. */\nconst TransitionPrefix = \"transition/\";\n\n/** Prefix of the reading keys: `reading/<namespace>/<resource>/<key>`. */\nconst ReadingPrefix = \"reading/\";\n\n/** The namespace the workflow controller reports a render's own lifecycle under. */\nconst RenderNamespace = \"render\";\n\n/**\n * The namespace the creator of a context reports under. The middle layer records `Terminated` here\n * on the root when the user stops the run, see `recordBlockRunCancelled`.\n */\nconst CreatorNamespace = \"core\";\n\n/** The namespace a command reports under; its `Running` means a job executing on a machine. */\nexport const ExecNamespace = \"exec\";\n\n/** The namespace a job's work folder reports under. */\nexport const WorkdirNamespace = \"workdir\";\n\n/** One transition, as stored under `transition/<namespace>/<resource>/<ns>`. */\nexport type Transition = {\n namespace: string;\n /** The resource that reported: the render itself, or a command or work dir it created. */\n reporter: string;\n /** The reporter's clock in nanoseconds, as the decimal string the key carries. */\n ns: string;\n /** As the reporter wrote it, whether or not this build knows the name. */\n state: string;\n detail: string;\n reason: string;\n};\n\n/** What one context reported. */\nexport type ContextReports = {\n /** Every transition whose key and value parse. */\n all: Transition[];\n /** The earliest and latest timestamp of any transition key, even one whose value does not\n * parse: a report arriving is evidence the run moved whatever it says. */\n firstNs?: string;\n lastNs?: string;\n};\n\n/** A node of the tree, reduced to what the summary needs. */\nexport type FoldedNode = {\n /** True when the render of this context has ended and nothing it started is still running. */\n terminal: boolean;\n /** The reason, set when the render itself ended in a termination rather than a completion. */\n failure?: string;\n /** The transition holding this node, undefined when it is terminal or has not reported. */\n holding?: Transition;\n /** True when {@link FoldedNode.holding} is `Running` reported by a command. */\n onMachine: boolean;\n};\n\n/** Compares non-negative decimal integers given as strings, shorter is smaller. */\nexport function compareNs(a: string, b: string): number {\n return a.length !== b.length ? a.length - b.length : a < b ? -1 : a > b ? 1 : 0;\n}\n\n/** Nanoseconds since the epoch, as the key carries them, to milliseconds. */\nexport function nsToMs(ns: string): number {\n return Number(BigInt(ns) / 1_000_000n);\n}\n\nfunction earlier(a: string | undefined, b: string | undefined): string | undefined {\n return a === undefined || (b !== undefined && compareNs(b, a) < 0) ? b : a;\n}\n\nfunction later(a: string | undefined, b: string | undefined): string | undefined {\n return a === undefined || (b !== undefined && compareNs(b, a) > 0) ? b : a;\n}\n\n/**\n * How strongly a report claims to be what holds a node.\n *\n * The render's own `Running` means only that template code is being evaluated, and the workflow\n * controller records it again on every evaluation, so it routinely carries a newer timestamp than\n * the wait that actually holds the node. Anything else outranks it however old it is, including a\n * command's `Running`, which is real work. Recency decides only between equal ranks.\n */\nfunction rank(t: Transition): number {\n return t.state === blockStatusStatesRecord.Running && t.namespace === RenderNamespace ? 0 : 1;\n}\n\n/**\n * The transitions of one context.\n *\n * A value that is not the JSON the reporters write is left out: a report is diagnostic, and a\n * malformed one must not break the surface. Its timestamp still counts.\n */\nexport function readTransitions(node: ActionContextNode): ContextReports {\n const out: ContextReports = { all: [] };\n\n for (const { key, value } of node.listKeyValuesAsString(TransitionPrefix)) {\n const parts = key.split(\"/\");\n if (parts.length !== 4) continue;\n const [, namespace, reporter, ns] = parts;\n // Leading zeros would break the length-first comparison, and no reporter writes them.\n if (!/^(0|[1-9]\\d*)$/.test(ns)) continue;\n\n out.firstNs = earlier(out.firstNs, ns);\n out.lastNs = later(out.lastNs, ns);\n\n const parsed = parseJsonObject(value);\n if (parsed === undefined) continue;\n const state = parsed.state;\n if (typeof state !== \"string\") continue;\n const detail = typeof parsed.detail === \"string\" ? parsed.detail : \"\";\n const reason = typeof parsed.reason === \"string\" ? parsed.reason : \"\";\n out.all.push({ namespace, reporter, ns, state, detail, reason });\n }\n\n return out;\n}\n\n/**\n * Reduces one context to {@link FoldedNode}.\n *\n * A context carries the reports of several reporters: the render reports under `render`, and the\n * commands and work dirs it created report under `exec` and `workdir`. The latest transition of\n * each reporter is that reporter's current state, and the state holding the node is the strongest\n * of those a reporter has not left, see {@link rank}.\n *\n * The node has ended when the render has reported its own end (`Completed` once its outputs are\n * set, `Terminated` with its error, or `Completed` with detail `deduplicated`) and every other\n * reporter in the context has ended too: the render's outputs being set does not stop a command it\n * started, and that command's report must stay visible.\n */\nexport function foldNode(transitions: readonly Transition[]): FoldedNode {\n const latestPerReporter = new Map<string, Transition>();\n for (const t of transitions) {\n const reporterKey = `${t.namespace}/${t.reporter}`;\n const previous = latestPerReporter.get(reporterKey);\n if (previous === undefined || compareNs(t.ns, previous.ns) > 0)\n latestPerReporter.set(reporterKey, t);\n }\n\n let render: Transition | undefined;\n let holding: Transition | undefined;\n let everyReporterEnded = true;\n for (const t of latestPerReporter.values()) {\n if (t.namespace === RenderNamespace) render = t;\n if (isTerminalBlockStatusState(t.state)) continue;\n everyReporterEnded = false;\n if (holding === undefined) {\n holding = t;\n continue;\n }\n const byRank = rank(t) - rank(holding);\n if (byRank > 0 || (byRank === 0 && compareNs(t.ns, holding.ns) > 0)) holding = t;\n }\n\n if (render !== undefined && isTerminalBlockStatusState(render.state) && everyReporterEnded)\n return {\n terminal: true,\n onMachine: false,\n failure: render.state === blockStatusStatesRecord.Terminated ? render.reason : undefined,\n };\n\n return {\n terminal: false,\n holding,\n onMachine:\n holding?.state === blockStatusStatesRecord.Running && holding.namespace === ExecNamespace,\n };\n}\n\n/** The render's own latest transition in a context. */\nexport function latestRender(transitions: readonly Transition[]): Transition | undefined {\n let latest: Transition | undefined;\n for (const t of transitions)\n if (t.namespace === RenderNamespace && (latest === undefined || compareNs(t.ns, latest.ns) > 0))\n latest = t;\n return latest;\n}\n\n/** One reading, as stored under `reading/<namespace>/<resource>/<key>`. */\nexport type Reading = { namespace: string; resource: string; key: string; value: string };\n\n/** One context read on its own, before its children are merged in. */\nexport type ContextFold = {\n readonly id: string;\n /** The baggage: `name`, `block-pack`, `block-id`, `run-id`. */\n readonly data: Record<string, unknown> | undefined;\n readonly reports: ContextReports;\n readonly readings: readonly Reading[];\n readonly folded: FoldedNode;\n /** True for a context a command or its work folder reports in: one job. */\n readonly job: boolean;\n /** The render's own latest transition, when it is a termination. */\n readonly terminated?: { readonly reason: string; readonly ns: string };\n /** Time its commands spent in `Running`, see {@link computeOf}. */\n readonly compute: ContextCompute;\n};\n\n/**\n * Time the commands of a context spent in `Running`: each Running up to the reporter's next\n * transition, ns. A command whose latest transition is Running is still open; it is counted up to\n * whatever moment the reader picks.\n */\nexport type ContextCompute = {\n readonly closedNs: bigint;\n /** When each command still running started, ns. */\n readonly openSinceNs: readonly string[];\n};\n\nfunction computeOf(all: readonly Transition[]): ContextCompute {\n const byReporter = new Map<string, Transition[]>();\n for (const t of all) {\n if (t.namespace !== ExecNamespace) continue;\n const list = byReporter.get(t.reporter);\n if (list === undefined) byReporter.set(t.reporter, [t]);\n else list.push(t);\n }\n\n let closedNs = 0n;\n const openSinceNs: string[] = [];\n for (const list of byReporter.values()) {\n list.sort((a, b) => compareNs(a.ns, b.ns));\n for (let i = 0; i < list.length; i++) {\n if (list[i].state !== blockStatusStatesRecord.Running) continue;\n const next = list[i + 1];\n if (next === undefined) openSinceNs.push(list[i].ns);\n else closedNs += BigInt(next.ns) - BigInt(list[i].ns);\n }\n }\n return { closedNs, openSinceNs };\n}\n\nfunction readReadings(node: ActionContextNode): Reading[] {\n const out: Reading[] = [];\n for (const { key, value } of node.listKeyValuesAsString(ReadingPrefix)) {\n const parts = key.split(\"/\");\n if (parts.length !== 4) continue;\n out.push({ namespace: parts[1], resource: parts[2], key: parts[3], value });\n }\n return out;\n}\n\n/** Reads one context: its transitions, its readings, and the state holding it. */\nexport function foldContext(node: ActionContextNode): ContextFold {\n const reports = readTransitions(node);\n const render = latestRender(reports.all);\n return {\n id: node.id,\n data: node.getData(),\n reports,\n readings: readReadings(node),\n folded: foldNode(reports.all),\n job: reports.all.some((t) => t.namespace === ExecNamespace || t.namespace === WorkdirNamespace),\n terminated:\n render?.state === blockStatusStatesRecord.Terminated\n ? { reason: render.reason, ns: render.ns }\n : undefined,\n compute: computeOf(reports.all),\n };\n}\n\n/** {@link BlockStatusJobGroup} being accumulated, its timestamp still in nanoseconds. */\ntype JobGroupTally = {\n readonly namespace: string;\n readonly state: string;\n readonly count: number;\n readonly sinceNs?: string;\n readonly files?: { readonly done: number; readonly total: number };\n};\n\n/**\n * {@link BlockStatusJobs} being accumulated over a subtree. Plain data throughout, no `Map`: it is\n * the value of a computable, which the computable types map over field by field.\n */\nexport type JobTally = {\n readonly total: number;\n readonly done: number;\n readonly failed: number;\n /** Jobs not ended, by `<namespace>/<state>` of the transition holding each. */\n readonly groups: Readonly<Record<string, JobGroupTally>>;\n};\n\nconst EmptyJobTally: JobTally = { total: 0, done: 0, failed: 0, groups: {} };\n\n/** A context and everything under it, folded. */\nexport type SubtreeFold = {\n readonly own: ContextFold;\n readonly children: readonly SubtreeFold[];\n /** This context and every context under it. */\n readonly contexts: number;\n /** Contexts in the subtree that have not ended. */\n readonly activeContexts: number;\n readonly firstNs?: string;\n readonly lastNs?: string;\n /**\n * The earliest render in the subtree whose latest report is a termination, with the context ids\n * from this context down to it.\n */\n readonly failure?: {\n readonly reason: string;\n readonly ns: string;\n readonly path: readonly string[];\n };\n readonly jobs: JobTally;\n /**\n * Time the subtree's commands spent in `Running`. Commands still running add their time up to a\n * moment the reader picks: `open × now − openSinceSumNs`.\n */\n readonly compute: {\n readonly closedNs: bigint;\n readonly open: number;\n readonly openSinceSumNs: bigint;\n };\n};\n\n/** Files done of all, summed over the work folders' progress readings of one context. */\nfunction workdirProgress(readings: readonly Reading[]): JobGroupTally[\"files\"] {\n let progress: JobGroupTally[\"files\"];\n for (const r of readings) {\n if (r.namespace !== WorkdirNamespace || r.key !== \"progress\") continue;\n const parsed = parseJsonObject(r.value);\n if (typeof parsed?.done !== \"number\" || typeof parsed.total !== \"number\") continue;\n progress = addFiles(progress, { done: parsed.done, total: parsed.total });\n }\n return progress;\n}\n\nfunction addFiles(a: JobGroupTally[\"files\"], b: JobGroupTally[\"files\"]): JobGroupTally[\"files\"] {\n if (a === undefined) return b;\n if (b === undefined) return a;\n return { done: a.done + b.done, total: a.total + b.total };\n}\n\nfunction groupKey(group: Pick<JobGroupTally, \"namespace\" | \"state\">): string {\n return `${group.namespace}/${group.state}`;\n}\n\nfunction mergeGroup(\n groups: Record<string, JobGroupTally>,\n key: string,\n group: JobGroupTally,\n): void {\n const previous = groups[key];\n groups[key] =\n previous === undefined\n ? group\n : {\n namespace: group.namespace,\n state: group.state,\n count: previous.count + group.count,\n sinceNs: earlier(previous.sinceNs, group.sinceNs),\n files: addFiles(previous.files, group.files),\n };\n}\n\n/** The job a context is, counted where it is now; empty when it is not one. */\nfunction ownJobs(own: ContextFold): JobTally {\n if (!own.job) return EmptyJobTally;\n const { terminal, failure, holding } = own.folded;\n if (terminal)\n return failure === undefined\n ? { ...EmptyJobTally, total: 1, done: 1 }\n : { ...EmptyJobTally, total: 1, failed: 1 };\n if (holding === undefined) return { ...EmptyJobTally, total: 1 };\n const group: JobGroupTally = {\n namespace: holding.namespace,\n state: holding.state,\n count: 1,\n sinceNs: holding.ns,\n files: workdirProgress(own.readings),\n };\n return { ...EmptyJobTally, total: 1, groups: { [groupKey(group)]: group } };\n}\n\n/**\n * Merges a context with the folds of its children. One pass over the direct children, so a report\n * re-merges each context on its path to the root and nothing else.\n */\nexport function mergeSubtree(own: ContextFold, children: readonly SubtreeFold[]): SubtreeFold {\n let contexts = 1;\n let activeContexts = own.folded.terminal ? 0 : 1;\n let firstNs = own.reports.firstNs;\n let lastNs = own.reports.lastNs;\n let failure: SubtreeFold[\"failure\"] =\n own.terminated === undefined ? undefined : { ...own.terminated, path: [own.id] };\n let failedBelow = false;\n let closedNs = own.compute.closedNs;\n let open = own.compute.openSinceNs.length;\n let openSinceSumNs = 0n;\n for (const since of own.compute.openSinceNs) openSinceSumNs += BigInt(since);\n\n const self = ownJobs(own);\n let { total, done, failed } = self;\n const groups: Record<string, JobGroupTally> = { ...self.groups };\n\n for (const child of children) {\n contexts += child.contexts;\n activeContexts += child.activeContexts;\n firstNs = earlier(firstNs, child.firstNs);\n lastNs = later(lastNs, child.lastNs);\n if (child.failure !== undefined) {\n failedBelow = true;\n if (failure === undefined || compareNs(child.failure.ns, failure.ns) < 0)\n failure = { ...child.failure, path: [own.id, ...child.failure.path] };\n }\n closedNs += child.compute.closedNs;\n open += child.compute.open;\n openSinceSumNs += child.compute.openSinceSumNs;\n total += child.jobs.total;\n done += child.jobs.done;\n failed += child.jobs.failed;\n for (const [key, group] of Object.entries(child.jobs.groups)) mergeGroup(groups, key, group);\n }\n\n // A render that failed on its own, e.g. one whose command could not start, is a failed job too;\n // one that only passes up the failure under it is not counted again.\n if (own.terminated !== undefined && !failedBelow && !own.job) {\n total++;\n failed++;\n }\n\n return {\n own,\n children,\n contexts,\n activeContexts,\n firstNs,\n lastNs,\n failure,\n jobs: { total, done, failed, groups },\n compute: { closedNs, open, openSinceSumNs },\n };\n}\n\n/**\n * The child contexts a fold follows: each once, and none already on the path from the root, so a\n * context linked twice or a cycle cannot count a subtree again.\n */\nexport function childContexts<T extends { readonly id: unknown }>(\n fields: readonly string[],\n traverse: (field: string) => T | undefined,\n path: ReadonlySet<string>,\n): T[] {\n if (path.size > MaxDepth) return [];\n const out: T[] = [];\n const seen = new Set<string>();\n for (const field of fields) {\n if (!field.startsWith(ChildFieldPrefix)) continue;\n const child = traverse(field);\n if (child === undefined) continue;\n const id = String(child.id);\n if (path.has(id) || seen.has(id)) continue;\n seen.add(id);\n out.push(child);\n }\n return out;\n}\n\n/**\n * Folds a context and everything under it in one walk: what the per-context computables compute,\n * for a tree that is read once.\n */\nexport function foldSubtree(\n node: ActionContextNode,\n path: ReadonlySet<string> = new Set(),\n): SubtreeFold {\n const below = new Set(path).add(node.id);\n const children = childContexts(node.listFields(), (f) => node.traverse(f), below);\n return mergeSubtree(\n foldContext(node),\n children.map((child) => foldSubtree(child, below)),\n );\n}\n\n/** Where the backend nests the error of an input inside the error of what consumes it. */\nconst InputErrorMarker = \"has input errors:\";\n\n/** Wrappers the workflow controller puts in front of a template's own error. */\nconst TemplateErrorPrefix = /^(cannot eval code: |cannot eval template: |tengo template error: )+/;\n\n/** Longest headline, in characters. */\nconst MaxHeadlineLength = 200;\n\n/**\n * The innermost message of a termination reason, for a title: the backend wraps the error of each\n * input in the error of its consumer, and tengo appends stack frames, so a reason can run to pages.\n */\nexport function failureHeadline(reason: string): string {\n const marker = reason.lastIndexOf(InputErrorMarker);\n const lines = reason\n .slice(marker < 0 ? 0 : marker + InputErrorMarker.length)\n .split(\"\\n\")\n .map((line) => line.trim())\n // Stack frames: `@platforma-sdk/workflow-tengo:tpl.base:595:5`.\n .filter((line) => line !== \"\" && !/^@\\S+:\\d+:\\d+$/.test(line));\n\n const text = lines.join(\" \");\n // A command that failed: `Command ID: … Command name: \"python\" … Error: docker is not set`.\n const command = /Command name: \"([^\"]*)\".*\\bError: (.+)$/.exec(text);\n const headline =\n command !== null\n ? `${command[1]} failed: ${command[2]}`\n : text.replace(TemplateErrorPrefix, \"\");\n return headline.length > MaxHeadlineLength\n ? `${headline.slice(0, MaxHeadlineLength - 1)}…`\n : headline;\n}\n\nfunction finishJobs(jobs: JobTally): BlockStatusJobs {\n const byState = Object.values(jobs.groups)\n .map((g): BlockStatusJobGroup => ({\n namespace: g.namespace,\n state: g.state,\n count: g.count,\n since: g.sinceNs === undefined ? undefined : nsToMs(g.sinceNs),\n files: g.files,\n }))\n .sort((a, b) => b.count - a.count || groupKey(a).localeCompare(groupKey(b)));\n return { total: jobs.total, done: jobs.done, failed: jobs.failed, byState };\n}\n\n/** The summary of a block run, from the fold of its root action context. */\nexport function summarize(root: SubtreeFold): BlockStatusSummary {\n const runId = root.own.data?.[\"run-id\"];\n const jobs = finishJobs(root.jobs);\n const summary = {\n availability: \"read\" as const,\n runId: typeof runId === \"string\" ? runId : undefined,\n activeContexts: root.activeContexts,\n totalContexts: root.contexts,\n jobs,\n startedAt: root.firstNs === undefined ? undefined : nsToMs(root.firstNs),\n };\n\n // A stopped run: its render is gone and reports nothing more, so the tree is frozen where it\n // stopped. The counters stay, to say where each node was; the run itself is over.\n let cancelledNs: string | undefined;\n for (const t of root.own.reports.all)\n if (t.namespace === CreatorNamespace && t.state === blockStatusStatesRecord.Terminated)\n cancelledNs = later(cancelledNs, t.ns);\n if (cancelledNs !== undefined)\n return { ...summary, lastChangeAt: nsToMs(cancelledNs), done: true, cancelled: true };\n\n // A terminated render fails the run. Renders waiting on its outputs never report again, so once\n // no job is held by its command or work folder the run is over, though they still look active.\n const working = jobs.byState.some((g) => g.namespace !== RenderNamespace);\n return {\n ...summary,\n lastChangeAt: root.lastNs === undefined ? undefined : nsToMs(root.lastNs),\n // The root's outputs can be set while work it started still runs, so done needs both.\n done:\n (root.own.folded.terminal && root.activeContexts === 0) ||\n (root.failure !== undefined && !working),\n failure: root.failure === undefined ? undefined : failureHeadline(root.failure.reason),\n };\n}\n\n/** The summary of a block run, from the root action context of its render. */\nexport function foldBlockStatus(root: ActionContextNode): BlockStatusSummary {\n return summarize(foldSubtree(root));\n}\n"],"mappings":";;;;;;AA6BA,SAAS,gBAAgB,OAAoD;CAC3E,IAAI;CACJ,IAAI;EACF,SAAS,KAAK,MAAM,KAAK;CAC3B,QAAQ;EACN;CACF;CACA,IAAI,OAAO,WAAW,YAAY,WAAW,QAAQ,MAAM,QAAQ,MAAM,GAAG,OAAO,KAAA;CACnF,OAAO,OAAO,YAAY,OAAO,QAAQ,MAAM,CAAC;AAClD;;AAyBA,MAAM,mBAAmB;;AAGzB,MAAM,mBAAmB;;AAGzB,MAAM,gBAAgB;;AAGtB,MAAM,kBAAkB;;;;;AAMxB,MAAM,mBAAmB;;AAGzB,MAAa,gBAAgB;;AAG7B,MAAa,mBAAmB;;AAsChC,SAAgB,UAAU,GAAW,GAAmB;CACtD,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,SAAS,EAAE,SAAS,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI;AAChF;;AAGA,SAAgB,OAAO,IAAoB;CACzC,OAAO,OAAO,OAAO,EAAE,IAAI,QAAU;AACvC;AAEA,SAAS,QAAQ,GAAuB,GAA2C;CACjF,OAAO,MAAM,KAAA,KAAc,MAAM,KAAA,KAAa,UAAU,GAAG,CAAC,IAAI,IAAK,IAAI;AAC3E;AAEA,SAAS,MAAM,GAAuB,GAA2C;CAC/E,OAAO,MAAM,KAAA,KAAc,MAAM,KAAA,KAAa,UAAU,GAAG,CAAC,IAAI,IAAK,IAAI;AAC3E;;;;;;;;;AAUA,SAAS,KAAK,GAAuB;CACnC,OAAO,EAAE,UAAUA,sCAAAA,wBAAwB,W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
131
  terminal: false,
132
132
  holding,
133
- onMachine: holding?.state === blockStatusStatesRecord.Running && holding.namespace === ExecNamespace
133
+ onMachine: holding?.state === blockStatusStatesRecord.Running && holding.namespace === "exec"
134
134
  };
135
135
  }
136
136
  /** The render's own latest transition in a context. */
@@ -139,6 +139,30 @@ function latestRender(transitions) {
139
139
  for (const t of transitions) if (t.namespace === RenderNamespace && (latest === void 0 || compareNs(t.ns, latest.ns) > 0)) latest = t;
140
140
  return latest;
141
141
  }
142
+ function computeOf(all) {
143
+ const byReporter = /* @__PURE__ */ new Map();
144
+ for (const t of all) {
145
+ if (t.namespace !== "exec") continue;
146
+ const list = byReporter.get(t.reporter);
147
+ if (list === void 0) byReporter.set(t.reporter, [t]);
148
+ else list.push(t);
149
+ }
150
+ let closedNs = 0n;
151
+ const openSinceNs = [];
152
+ for (const list of byReporter.values()) {
153
+ list.sort((a, b) => compareNs(a.ns, b.ns));
154
+ for (let i = 0; i < list.length; i++) {
155
+ if (list[i].state !== blockStatusStatesRecord.Running) continue;
156
+ const next = list[i + 1];
157
+ if (next === void 0) openSinceNs.push(list[i].ns);
158
+ else closedNs += BigInt(next.ns) - BigInt(list[i].ns);
159
+ }
160
+ }
161
+ return {
162
+ closedNs,
163
+ openSinceNs
164
+ };
165
+ }
142
166
  function readReadings(node) {
143
167
  const out = [];
144
168
  for (const { key, value } of node.listKeyValuesAsString(ReadingPrefix)) {
@@ -163,11 +187,12 @@ function foldContext(node) {
163
187
  reports,
164
188
  readings: readReadings(node),
165
189
  folded: foldNode(reports.all),
166
- job: reports.all.some((t) => t.namespace === ExecNamespace || t.namespace === WorkdirNamespace),
190
+ job: reports.all.some((t) => t.namespace === "exec" || t.namespace === "workdir"),
167
191
  terminated: render?.state === blockStatusStatesRecord.Terminated ? {
168
192
  reason: render.reason,
169
193
  ns: render.ns
170
- } : void 0
194
+ } : void 0,
195
+ compute: computeOf(reports.all)
171
196
  };
172
197
  }
173
198
  const EmptyJobTally = {
@@ -180,7 +205,7 @@ const EmptyJobTally = {
180
205
  function workdirProgress(readings) {
181
206
  let progress;
182
207
  for (const r of readings) {
183
- if (r.namespace !== WorkdirNamespace || r.key !== "progress") continue;
208
+ if (r.namespace !== "workdir" || r.key !== "progress") continue;
184
209
  const parsed = parseJsonObject(r.value);
185
210
  if (typeof parsed?.done !== "number" || typeof parsed.total !== "number") continue;
186
211
  progress = addFiles(progress, {
@@ -250,8 +275,15 @@ function mergeSubtree(own, children) {
250
275
  let activeContexts = own.folded.terminal ? 0 : 1;
251
276
  let firstNs = own.reports.firstNs;
252
277
  let lastNs = own.reports.lastNs;
253
- let failure = own.terminated;
278
+ let failure = own.terminated === void 0 ? void 0 : {
279
+ ...own.terminated,
280
+ path: [own.id]
281
+ };
254
282
  let failedBelow = false;
283
+ let closedNs = own.compute.closedNs;
284
+ let open = own.compute.openSinceNs.length;
285
+ let openSinceSumNs = 0n;
286
+ for (const since of own.compute.openSinceNs) openSinceSumNs += BigInt(since);
255
287
  const self = ownJobs(own);
256
288
  let { total, done, failed } = self;
257
289
  const groups = { ...self.groups };
@@ -262,8 +294,14 @@ function mergeSubtree(own, children) {
262
294
  lastNs = later(lastNs, child.lastNs);
263
295
  if (child.failure !== void 0) {
264
296
  failedBelow = true;
265
- if (failure === void 0 || compareNs(child.failure.ns, failure.ns) < 0) failure = child.failure;
297
+ if (failure === void 0 || compareNs(child.failure.ns, failure.ns) < 0) failure = {
298
+ ...child.failure,
299
+ path: [own.id, ...child.failure.path]
300
+ };
266
301
  }
302
+ closedNs += child.compute.closedNs;
303
+ open += child.compute.open;
304
+ openSinceSumNs += child.compute.openSinceSumNs;
267
305
  total += child.jobs.total;
268
306
  done += child.jobs.done;
269
307
  failed += child.jobs.failed;
@@ -286,6 +324,11 @@ function mergeSubtree(own, children) {
286
324
  done,
287
325
  failed,
288
326
  groups
327
+ },
328
+ compute: {
329
+ closedNs,
330
+ open,
331
+ openSinceSumNs
289
332
  }
290
333
  };
291
334
  }
@@ -368,6 +411,6 @@ function summarize(root) {
368
411
  failure: root.failure === void 0 ? void 0 : failureHeadline(root.failure.reason)
369
412
  };
370
413
  }
371
- export { childContexts, compareNs, failureHeadline, foldContext, foldNode, latestRender, mergeSubtree, nsToMs, readTransitions, summarize };
414
+ export { ExecNamespace, WorkdirNamespace, childContexts, compareNs, failureHeadline, foldContext, foldNode, latestRender, mergeSubtree, nsToMs, readTransitions, summarize };
372
415
 
373
416
  //# sourceMappingURL=block_status_fold.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"block_status_fold.js","names":[],"sources":["../../src/middle_layer/block_status_fold.ts"],"sourcesContent":["/**\n * Folds a block's action-context tree into the {@link BlockStatusSummary} the Desktop App shows.\n *\n * The fold runs bottom up: {@link foldContext} reads one context on its own, and\n * {@link mergeSubtree} merges it with the folds of its children. Over a synchronized tree each\n * context gets its own computable (see `block_status_tree.ts`), so a report re-reads only the\n * context it landed in and re-merges the contexts above it; the rest of the tree is not read\n * again.\n *\n * The fold attaches no meaning to the states the reporters write, beyond the lifecycle the backend\n * fixes: a context ends in `Completed` or `Terminated`, and a command's `Running` is work on a\n * machine. Jobs are counted per state as reported, so a state added on the backend reaches the\n * Desktop App without a middle layer release.\n */\n\nimport type {\n BlockStatusJobGroup,\n BlockStatusJobs,\n BlockStatusSummary,\n} from \"@milaboratories/pl-model-middle-layer\";\nimport {\n blockStatusStatesRecord,\n isTerminalBlockStatusState,\n} from \"@milaboratories/pl-model-middle-layer\";\n\n/**\n * A key-value written as a JSON object, with its fields unchecked; undefined for anything else.\n * A reporter may write any JSON, so `null` or a bare number must not reach a field read.\n */\nfunction parseJsonObject(value: string): Record<string, unknown> | undefined {\n let parsed: unknown;\n try {\n parsed = JSON.parse(value);\n } catch {\n return undefined;\n }\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) return undefined;\n return Object.fromEntries(Object.entries(parsed));\n}\n\n/** The part of an action context a fold reads. A tree node accessor satisfies it. */\nexport interface ActionContextNode {\n /** Stable identity of the context, for deduplicating a walk. */\n readonly id: string;\n /** The context's baggage: `name`, `block-pack`, `block-id`, `run-id`. */\n getData(): Record<string, unknown> | undefined;\n /** KV entries under a prefix, values as text. */\n listKeyValuesAsString(prefix: string): { key: string; value: string }[];\n /** Field names, whatever their type: the children are `child/<render>`. */\n listFields(): string[];\n /** The context a field points at, or undefined while the field is unset. */\n traverse(field: string): ActionContextNode | undefined;\n}\n\n/**\n * How deep the fold follows `child/<render>`.\n *\n * A stack guard, not a correctness device: a context already on the path is skipped, and the depth\n * of a real tree is the nesting depth of the templates, far below this.\n */\nexport const MaxDepth = 256;\n\n/** Prefix of the field names holding child contexts. */\nconst ChildFieldPrefix = \"child/\";\n\n/** Prefix of the transition keys: `transition/<namespace>/<resource>/<ns>`. */\nconst TransitionPrefix = \"transition/\";\n\n/** Prefix of the reading keys: `reading/<namespace>/<resource>/<key>`. */\nconst ReadingPrefix = \"reading/\";\n\n/** The namespace the workflow controller reports a render's own lifecycle under. */\nconst RenderNamespace = \"render\";\n\n/**\n * The namespace the creator of a context reports under. The middle layer records `Terminated` here\n * on the root when the user stops the run, see `recordBlockRunCancelled`.\n */\nconst CreatorNamespace = \"core\";\n\n/** The namespace a command reports under; its `Running` means a job executing on a machine. */\nconst ExecNamespace = \"exec\";\n\n/** The namespace a job's work folder reports under. */\nconst WorkdirNamespace = \"workdir\";\n\n/** One transition, as stored under `transition/<namespace>/<resource>/<ns>`. */\nexport type Transition = {\n namespace: string;\n /** The resource that reported: the render itself, or a command or work dir it created. */\n reporter: string;\n /** The reporter's clock in nanoseconds, as the decimal string the key carries. */\n ns: string;\n /** As the reporter wrote it, whether or not this build knows the name. */\n state: string;\n detail: string;\n reason: string;\n};\n\n/** What one context reported. */\nexport type ContextReports = {\n /** Every transition whose key and value parse. */\n all: Transition[];\n /** The earliest and latest timestamp of any transition key, even one whose value does not\n * parse: a report arriving is evidence the run moved whatever it says. */\n firstNs?: string;\n lastNs?: string;\n};\n\n/** A node of the tree, reduced to what the summary needs. */\nexport type FoldedNode = {\n /** True when the render of this context has ended and nothing it started is still running. */\n terminal: boolean;\n /** The reason, set when the render itself ended in a termination rather than a completion. */\n failure?: string;\n /** The transition holding this node, undefined when it is terminal or has not reported. */\n holding?: Transition;\n /** True when {@link FoldedNode.holding} is `Running` reported by a command. */\n onMachine: boolean;\n};\n\n/** Compares non-negative decimal integers given as strings, shorter is smaller. */\nexport function compareNs(a: string, b: string): number {\n return a.length !== b.length ? a.length - b.length : a < b ? -1 : a > b ? 1 : 0;\n}\n\n/** Nanoseconds since the epoch, as the key carries them, to milliseconds. */\nexport function nsToMs(ns: string): number {\n return Number(BigInt(ns) / 1_000_000n);\n}\n\nfunction earlier(a: string | undefined, b: string | undefined): string | undefined {\n return a === undefined || (b !== undefined && compareNs(b, a) < 0) ? b : a;\n}\n\nfunction later(a: string | undefined, b: string | undefined): string | undefined {\n return a === undefined || (b !== undefined && compareNs(b, a) > 0) ? b : a;\n}\n\n/**\n * How strongly a report claims to be what holds a node.\n *\n * The render's own `Running` means only that template code is being evaluated, and the workflow\n * controller records it again on every evaluation, so it routinely carries a newer timestamp than\n * the wait that actually holds the node. Anything else outranks it however old it is, including a\n * command's `Running`, which is real work. Recency decides only between equal ranks.\n */\nfunction rank(t: Transition): number {\n return t.state === blockStatusStatesRecord.Running && t.namespace === RenderNamespace ? 0 : 1;\n}\n\n/**\n * The transitions of one context.\n *\n * A value that is not the JSON the reporters write is left out: a report is diagnostic, and a\n * malformed one must not break the surface. Its timestamp still counts.\n */\nexport function readTransitions(node: ActionContextNode): ContextReports {\n const out: ContextReports = { all: [] };\n\n for (const { key, value } of node.listKeyValuesAsString(TransitionPrefix)) {\n const parts = key.split(\"/\");\n if (parts.length !== 4) continue;\n const [, namespace, reporter, ns] = parts;\n // Leading zeros would break the length-first comparison, and no reporter writes them.\n if (!/^(0|[1-9]\\d*)$/.test(ns)) continue;\n\n out.firstNs = earlier(out.firstNs, ns);\n out.lastNs = later(out.lastNs, ns);\n\n const parsed = parseJsonObject(value);\n if (parsed === undefined) continue;\n const state = parsed.state;\n if (typeof state !== \"string\") continue;\n const detail = typeof parsed.detail === \"string\" ? parsed.detail : \"\";\n const reason = typeof parsed.reason === \"string\" ? parsed.reason : \"\";\n out.all.push({ namespace, reporter, ns, state, detail, reason });\n }\n\n return out;\n}\n\n/**\n * Reduces one context to {@link FoldedNode}.\n *\n * A context carries the reports of several reporters: the render reports under `render`, and the\n * commands and work dirs it created report under `exec` and `workdir`. The latest transition of\n * each reporter is that reporter's current state, and the state holding the node is the strongest\n * of those a reporter has not left, see {@link rank}.\n *\n * The node has ended when the render has reported its own end (`Completed` once its outputs are\n * set, `Terminated` with its error, or `Completed` with detail `deduplicated`) and every other\n * reporter in the context has ended too: the render's outputs being set does not stop a command it\n * started, and that command's report must stay visible.\n */\nexport function foldNode(transitions: readonly Transition[]): FoldedNode {\n const latestPerReporter = new Map<string, Transition>();\n for (const t of transitions) {\n const reporterKey = `${t.namespace}/${t.reporter}`;\n const previous = latestPerReporter.get(reporterKey);\n if (previous === undefined || compareNs(t.ns, previous.ns) > 0)\n latestPerReporter.set(reporterKey, t);\n }\n\n let render: Transition | undefined;\n let holding: Transition | undefined;\n let everyReporterEnded = true;\n for (const t of latestPerReporter.values()) {\n if (t.namespace === RenderNamespace) render = t;\n if (isTerminalBlockStatusState(t.state)) continue;\n everyReporterEnded = false;\n if (holding === undefined) {\n holding = t;\n continue;\n }\n const byRank = rank(t) - rank(holding);\n if (byRank > 0 || (byRank === 0 && compareNs(t.ns, holding.ns) > 0)) holding = t;\n }\n\n if (render !== undefined && isTerminalBlockStatusState(render.state) && everyReporterEnded)\n return {\n terminal: true,\n onMachine: false,\n failure: render.state === blockStatusStatesRecord.Terminated ? render.reason : undefined,\n };\n\n return {\n terminal: false,\n holding,\n onMachine:\n holding?.state === blockStatusStatesRecord.Running && holding.namespace === ExecNamespace,\n };\n}\n\n/** The render's own latest transition in a context. */\nexport function latestRender(transitions: readonly Transition[]): Transition | undefined {\n let latest: Transition | undefined;\n for (const t of transitions)\n if (t.namespace === RenderNamespace && (latest === undefined || compareNs(t.ns, latest.ns) > 0))\n latest = t;\n return latest;\n}\n\n/** One reading, as stored under `reading/<namespace>/<resource>/<key>`. */\nexport type Reading = { namespace: string; resource: string; key: string; value: string };\n\n/** One context read on its own, before its children are merged in. */\nexport type ContextFold = {\n readonly id: string;\n /** The baggage: `name`, `block-pack`, `block-id`, `run-id`. */\n readonly data: Record<string, unknown> | undefined;\n readonly reports: ContextReports;\n readonly readings: readonly Reading[];\n readonly folded: FoldedNode;\n /** True for a context a command or its work folder reports in: one job. */\n readonly job: boolean;\n /** The render's own latest transition, when it is a termination. */\n readonly terminated?: { readonly reason: string; readonly ns: string };\n};\n\nfunction readReadings(node: ActionContextNode): Reading[] {\n const out: Reading[] = [];\n for (const { key, value } of node.listKeyValuesAsString(ReadingPrefix)) {\n const parts = key.split(\"/\");\n if (parts.length !== 4) continue;\n out.push({ namespace: parts[1], resource: parts[2], key: parts[3], value });\n }\n return out;\n}\n\n/** Reads one context: its transitions, its readings, and the state holding it. */\nexport function foldContext(node: ActionContextNode): ContextFold {\n const reports = readTransitions(node);\n const render = latestRender(reports.all);\n return {\n id: node.id,\n data: node.getData(),\n reports,\n readings: readReadings(node),\n folded: foldNode(reports.all),\n job: reports.all.some((t) => t.namespace === ExecNamespace || t.namespace === WorkdirNamespace),\n terminated:\n render?.state === blockStatusStatesRecord.Terminated\n ? { reason: render.reason, ns: render.ns }\n : undefined,\n };\n}\n\n/** {@link BlockStatusJobGroup} being accumulated, its timestamp still in nanoseconds. */\ntype JobGroupTally = {\n readonly namespace: string;\n readonly state: string;\n readonly count: number;\n readonly sinceNs?: string;\n readonly files?: { readonly done: number; readonly total: number };\n};\n\n/**\n * {@link BlockStatusJobs} being accumulated over a subtree. Plain data throughout, no `Map`: it is\n * the value of a computable, which the computable types map over field by field.\n */\nexport type JobTally = {\n readonly total: number;\n readonly done: number;\n readonly failed: number;\n /** Jobs not ended, by `<namespace>/<state>` of the transition holding each. */\n readonly groups: Readonly<Record<string, JobGroupTally>>;\n};\n\nconst EmptyJobTally: JobTally = { total: 0, done: 0, failed: 0, groups: {} };\n\n/** A context and everything under it, folded. */\nexport type SubtreeFold = {\n readonly own: ContextFold;\n readonly children: readonly SubtreeFold[];\n /** This context and every context under it. */\n readonly contexts: number;\n /** Contexts in the subtree that have not ended. */\n readonly activeContexts: number;\n readonly firstNs?: string;\n readonly lastNs?: string;\n /** The earliest render in the subtree whose latest report is a termination. */\n readonly failure?: { readonly reason: string; readonly ns: string };\n readonly jobs: JobTally;\n};\n\n/** Files done of all, summed over the work folders' progress readings of one context. */\nfunction workdirProgress(readings: readonly Reading[]): JobGroupTally[\"files\"] {\n let progress: JobGroupTally[\"files\"];\n for (const r of readings) {\n if (r.namespace !== WorkdirNamespace || r.key !== \"progress\") continue;\n const parsed = parseJsonObject(r.value);\n if (typeof parsed?.done !== \"number\" || typeof parsed.total !== \"number\") continue;\n progress = addFiles(progress, { done: parsed.done, total: parsed.total });\n }\n return progress;\n}\n\nfunction addFiles(a: JobGroupTally[\"files\"], b: JobGroupTally[\"files\"]): JobGroupTally[\"files\"] {\n if (a === undefined) return b;\n if (b === undefined) return a;\n return { done: a.done + b.done, total: a.total + b.total };\n}\n\nfunction groupKey(group: Pick<JobGroupTally, \"namespace\" | \"state\">): string {\n return `${group.namespace}/${group.state}`;\n}\n\nfunction mergeGroup(\n groups: Record<string, JobGroupTally>,\n key: string,\n group: JobGroupTally,\n): void {\n const previous = groups[key];\n groups[key] =\n previous === undefined\n ? group\n : {\n namespace: group.namespace,\n state: group.state,\n count: previous.count + group.count,\n sinceNs: earlier(previous.sinceNs, group.sinceNs),\n files: addFiles(previous.files, group.files),\n };\n}\n\n/** The job a context is, counted where it is now; empty when it is not one. */\nfunction ownJobs(own: ContextFold): JobTally {\n if (!own.job) return EmptyJobTally;\n const { terminal, failure, holding } = own.folded;\n if (terminal)\n return failure === undefined\n ? { ...EmptyJobTally, total: 1, done: 1 }\n : { ...EmptyJobTally, total: 1, failed: 1 };\n if (holding === undefined) return { ...EmptyJobTally, total: 1 };\n const group: JobGroupTally = {\n namespace: holding.namespace,\n state: holding.state,\n count: 1,\n sinceNs: holding.ns,\n files: workdirProgress(own.readings),\n };\n return { ...EmptyJobTally, total: 1, groups: { [groupKey(group)]: group } };\n}\n\n/**\n * Merges a context with the folds of its children. One pass over the direct children, so a report\n * re-merges each context on its path to the root and nothing else.\n */\nexport function mergeSubtree(own: ContextFold, children: readonly SubtreeFold[]): SubtreeFold {\n let contexts = 1;\n let activeContexts = own.folded.terminal ? 0 : 1;\n let firstNs = own.reports.firstNs;\n let lastNs = own.reports.lastNs;\n let failure = own.terminated;\n let failedBelow = false;\n\n const self = ownJobs(own);\n let { total, done, failed } = self;\n const groups: Record<string, JobGroupTally> = { ...self.groups };\n\n for (const child of children) {\n contexts += child.contexts;\n activeContexts += child.activeContexts;\n firstNs = earlier(firstNs, child.firstNs);\n lastNs = later(lastNs, child.lastNs);\n if (child.failure !== undefined) {\n failedBelow = true;\n if (failure === undefined || compareNs(child.failure.ns, failure.ns) < 0)\n failure = child.failure;\n }\n total += child.jobs.total;\n done += child.jobs.done;\n failed += child.jobs.failed;\n for (const [key, group] of Object.entries(child.jobs.groups)) mergeGroup(groups, key, group);\n }\n\n // A render that failed on its own, e.g. one whose command could not start, is a failed job too;\n // one that only passes up the failure under it is not counted again.\n if (own.terminated !== undefined && !failedBelow && !own.job) {\n total++;\n failed++;\n }\n\n return {\n own,\n children,\n contexts,\n activeContexts,\n firstNs,\n lastNs,\n failure,\n jobs: { total, done, failed, groups },\n };\n}\n\n/**\n * The child contexts a fold follows: each once, and none already on the path from the root, so a\n * context linked twice or a cycle cannot count a subtree again.\n */\nexport function childContexts<T extends { readonly id: unknown }>(\n fields: readonly string[],\n traverse: (field: string) => T | undefined,\n path: ReadonlySet<string>,\n): T[] {\n if (path.size > MaxDepth) return [];\n const out: T[] = [];\n const seen = new Set<string>();\n for (const field of fields) {\n if (!field.startsWith(ChildFieldPrefix)) continue;\n const child = traverse(field);\n if (child === undefined) continue;\n const id = String(child.id);\n if (path.has(id) || seen.has(id)) continue;\n seen.add(id);\n out.push(child);\n }\n return out;\n}\n\n/**\n * Folds a context and everything under it in one walk: what the per-context computables compute,\n * for a tree that is read once.\n */\nexport function foldSubtree(\n node: ActionContextNode,\n path: ReadonlySet<string> = new Set(),\n): SubtreeFold {\n const below = new Set(path).add(node.id);\n const children = childContexts(node.listFields(), (f) => node.traverse(f), below);\n return mergeSubtree(\n foldContext(node),\n children.map((child) => foldSubtree(child, below)),\n );\n}\n\n/** Where the backend nests the error of an input inside the error of what consumes it. */\nconst InputErrorMarker = \"has input errors:\";\n\n/** Wrappers the workflow controller puts in front of a template's own error. */\nconst TemplateErrorPrefix = /^(cannot eval code: |cannot eval template: |tengo template error: )+/;\n\n/** Longest headline, in characters. */\nconst MaxHeadlineLength = 200;\n\n/**\n * The innermost message of a termination reason, for a title: the backend wraps the error of each\n * input in the error of its consumer, and tengo appends stack frames, so a reason can run to pages.\n */\nexport function failureHeadline(reason: string): string {\n const marker = reason.lastIndexOf(InputErrorMarker);\n const lines = reason\n .slice(marker < 0 ? 0 : marker + InputErrorMarker.length)\n .split(\"\\n\")\n .map((line) => line.trim())\n // Stack frames: `@platforma-sdk/workflow-tengo:tpl.base:595:5`.\n .filter((line) => line !== \"\" && !/^@\\S+:\\d+:\\d+$/.test(line));\n\n const text = lines.join(\" \");\n // A command that failed: `Command ID: … Command name: \"python\" … Error: docker is not set`.\n const command = /Command name: \"([^\"]*)\".*\\bError: (.+)$/.exec(text);\n const headline =\n command !== null\n ? `${command[1]} failed: ${command[2]}`\n : text.replace(TemplateErrorPrefix, \"\");\n return headline.length > MaxHeadlineLength\n ? `${headline.slice(0, MaxHeadlineLength - 1)}…`\n : headline;\n}\n\nfunction finishJobs(jobs: JobTally): BlockStatusJobs {\n const byState = Object.values(jobs.groups)\n .map((g): BlockStatusJobGroup => ({\n namespace: g.namespace,\n state: g.state,\n count: g.count,\n since: g.sinceNs === undefined ? undefined : nsToMs(g.sinceNs),\n files: g.files,\n }))\n .sort((a, b) => b.count - a.count || groupKey(a).localeCompare(groupKey(b)));\n return { total: jobs.total, done: jobs.done, failed: jobs.failed, byState };\n}\n\n/** The summary of a block run, from the fold of its root action context. */\nexport function summarize(root: SubtreeFold): BlockStatusSummary {\n const runId = root.own.data?.[\"run-id\"];\n const jobs = finishJobs(root.jobs);\n const summary = {\n availability: \"read\" as const,\n runId: typeof runId === \"string\" ? runId : undefined,\n activeContexts: root.activeContexts,\n totalContexts: root.contexts,\n jobs,\n startedAt: root.firstNs === undefined ? undefined : nsToMs(root.firstNs),\n };\n\n // A stopped run: its render is gone and reports nothing more, so the tree is frozen where it\n // stopped. The counters stay, to say where each node was; the run itself is over.\n let cancelledNs: string | undefined;\n for (const t of root.own.reports.all)\n if (t.namespace === CreatorNamespace && t.state === blockStatusStatesRecord.Terminated)\n cancelledNs = later(cancelledNs, t.ns);\n if (cancelledNs !== undefined)\n return { ...summary, lastChangeAt: nsToMs(cancelledNs), done: true, cancelled: true };\n\n // A terminated render fails the run. Renders waiting on its outputs never report again, so once\n // no job is held by its command or work folder the run is over, though they still look active.\n const working = jobs.byState.some((g) => g.namespace !== RenderNamespace);\n return {\n ...summary,\n lastChangeAt: root.lastNs === undefined ? undefined : nsToMs(root.lastNs),\n // The root's outputs can be set while work it started still runs, so done needs both.\n done:\n (root.own.folded.terminal && root.activeContexts === 0) ||\n (root.failure !== undefined && !working),\n failure: root.failure === undefined ? undefined : failureHeadline(root.failure.reason),\n };\n}\n\n/** The summary of a block run, from the root action context of its render. */\nexport function foldBlockStatus(root: ActionContextNode): BlockStatusSummary {\n return summarize(foldSubtree(root));\n}\n"],"mappings":";;;;;;AA6BA,SAAS,gBAAgB,OAAoD;CAC3E,IAAI;CACJ,IAAI;EACF,SAAS,KAAK,MAAM,KAAK;CAC3B,QAAQ;EACN;CACF;CACA,IAAI,OAAO,WAAW,YAAY,WAAW,QAAQ,MAAM,Q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gBAAgB,KAAK;EACrB,eAAe,KAAK;EACpB;EACA,WAAW,KAAK,YAAY,KAAA,IAAY,KAAA,IAAY,OAAO,KAAK,OAAO;CACzE;CAIA,IAAI;CACJ,KAAK,MAAM,KAAK,KAAK,IAAI,QAAQ,KAC/B,IAAI,EAAE,cAAc,oBAAoB,EAAE,UAAU,wBAAwB,YAC1E,cAAc,MAAM,aAAa,EAAE,EAAE;CACzC,IAAI,gBAAgB,KAAA,GAClB,OAAO;EAAE,GAAG;EAAS,cAAc,OAAO,WAAW;EAAG,MAAM;EAAM,WAAW;CAAK;CAItF,MAAM,UAAU,KAAK,QAAQ,MAAM,MAAM,EAAE,cAAc,eAAe;CACxE,OAAO;EACL,GAAG;EACH,cAAc,KAAK,WAAW,KAAA,IAAY,KAAA,IAAY,OAAO,KAAK,MAAM;EAExE,MACG,KAAK,IAAI,OAAO,YAAY,KAAK,mBAAmB,KACpD,KAAK,YAAY,KAAA,KAAa,CAAC;EAClC,SAAS,KAAK,YAAY,KAAA,IAAY,KAAA,IAAY,gBAAgB,KAAK,QAAQ,MAAM;CACvF;AACF"}
1
+ {"version":3,"file":"block_status_fold.js","names":[],"sources":["../../src/middle_layer/block_status_fold.ts"],"sourcesContent":["/**\n * Folds a block's action-context tree into the {@link BlockStatusSummary} the Desktop App shows.\n *\n * The fold runs bottom up: {@link foldContext} reads one context on its own, and\n * {@link mergeSubtree} merges it with the folds of its children. Over a synchronized tree each\n * context gets its own computable (see `block_status_tree.ts`), so a report re-reads only the\n * context it landed in and re-merges the contexts above it; the rest of the tree is not read\n * again.\n *\n * The fold attaches no meaning to the states the reporters write, beyond the lifecycle the backend\n * fixes: a context ends in `Completed` or `Terminated`, and a command's `Running` is work on a\n * machine. Jobs are counted per state as reported, so a state added on the backend reaches the\n * Desktop App without a middle layer release.\n */\n\nimport type {\n BlockStatusJobGroup,\n BlockStatusJobs,\n BlockStatusSummary,\n} from \"@milaboratories/pl-model-middle-layer\";\nimport {\n blockStatusStatesRecord,\n isTerminalBlockStatusState,\n} from \"@milaboratories/pl-model-middle-layer\";\n\n/**\n * A key-value written as a JSON object, with its fields unchecked; undefined for anything else.\n * A reporter may write any JSON, so `null` or a bare number must not reach a field read.\n */\nfunction parseJsonObject(value: string): Record<string, unknown> | undefined {\n let parsed: unknown;\n try {\n parsed = JSON.parse(value);\n } catch {\n return undefined;\n }\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) return undefined;\n return Object.fromEntries(Object.entries(parsed));\n}\n\n/** The part of an action context a fold reads. A tree node accessor satisfies it. */\nexport interface ActionContextNode {\n /** Stable identity of the context, for deduplicating a walk. */\n readonly id: string;\n /** The context's baggage: `name`, `block-pack`, `block-id`, `run-id`. */\n getData(): Record<string, unknown> | undefined;\n /** KV entries under a prefix, values as text. */\n listKeyValuesAsString(prefix: string): { key: string; value: string }[];\n /** Field names, whatever their type: the children are `child/<render>`. */\n listFields(): string[];\n /** The context a field points at, or undefined while the field is unset. */\n traverse(field: string): ActionContextNode | undefined;\n}\n\n/**\n * How deep the fold follows `child/<render>`.\n *\n * A stack guard, not a correctness device: a context already on the path is skipped, and the depth\n * of a real tree is the nesting depth of the templates, far below this.\n */\nexport const MaxDepth = 256;\n\n/** Prefix of the field names holding child contexts. */\nconst ChildFieldPrefix = \"child/\";\n\n/** Prefix of the transition keys: `transition/<namespace>/<resource>/<ns>`. */\nconst TransitionPrefix = \"transition/\";\n\n/** Prefix of the reading keys: `reading/<namespace>/<resource>/<key>`. */\nconst ReadingPrefix = \"reading/\";\n\n/** The namespace the workflow controller reports a render's own lifecycle under. */\nconst RenderNamespace = \"render\";\n\n/**\n * The namespace the creator of a context reports under. The middle layer records `Terminated` here\n * on the root when the user stops the run, see `recordBlockRunCancelled`.\n */\nconst CreatorNamespace = \"core\";\n\n/** The namespace a command reports under; its `Running` means a job executing on a machine. */\nexport const ExecNamespace = \"exec\";\n\n/** The namespace a job's work folder reports under. */\nexport const WorkdirNamespace = \"workdir\";\n\n/** One transition, as stored under `transition/<namespace>/<resource>/<ns>`. */\nexport type Transition = {\n namespace: string;\n /** The resource that reported: the render itself, or a command or work dir it created. */\n reporter: string;\n /** The reporter's clock in nanoseconds, as the decimal string the key carries. */\n ns: string;\n /** As the reporter wrote it, whether or not this build knows the name. */\n state: string;\n detail: string;\n reason: string;\n};\n\n/** What one context reported. */\nexport type ContextReports = {\n /** Every transition whose key and value parse. */\n all: Transition[];\n /** The earliest and latest timestamp of any transition key, even one whose value does not\n * parse: a report arriving is evidence the run moved whatever it says. */\n firstNs?: string;\n lastNs?: string;\n};\n\n/** A node of the tree, reduced to what the summary needs. */\nexport type FoldedNode = {\n /** True when the render of this context has ended and nothing it started is still running. */\n terminal: boolean;\n /** The reason, set when the render itself ended in a termination rather than a completion. */\n failure?: string;\n /** The transition holding this node, undefined when it is terminal or has not reported. */\n holding?: Transition;\n /** True when {@link FoldedNode.holding} is `Running` reported by a command. */\n onMachine: boolean;\n};\n\n/** Compares non-negative decimal integers given as strings, shorter is smaller. */\nexport function compareNs(a: string, b: string): number {\n return a.length !== b.length ? a.length - b.length : a < b ? -1 : a > b ? 1 : 0;\n}\n\n/** Nanoseconds since the epoch, as the key carries them, to milliseconds. */\nexport function nsToMs(ns: string): number {\n return Number(BigInt(ns) / 1_000_000n);\n}\n\nfunction earlier(a: string | undefined, b: string | undefined): string | undefined {\n return a === undefined || (b !== undefined && compareNs(b, a) < 0) ? b : a;\n}\n\nfunction later(a: string | undefined, b: string | undefined): string | undefined {\n return a === undefined || (b !== undefined && compareNs(b, a) > 0) ? b : a;\n}\n\n/**\n * How strongly a report claims to be what holds a node.\n *\n * The render's own `Running` means only that template code is being evaluated, and the workflow\n * controller records it again on every evaluation, so it routinely carries a newer timestamp than\n * the wait that actually holds the node. Anything else outranks it however old it is, including a\n * command's `Running`, which is real work. Recency decides only between equal ranks.\n */\nfunction rank(t: Transition): number {\n return t.state === blockStatusStatesRecord.Running && t.namespace === RenderNamespace ? 0 : 1;\n}\n\n/**\n * The transitions of one context.\n *\n * A value that is not the JSON the reporters write is left out: a report is diagnostic, and a\n * malformed one must not break the surface. Its timestamp still counts.\n */\nexport function readTransitions(node: ActionContextNode): ContextReports {\n const out: ContextReports = { all: [] };\n\n for (const { key, value } of node.listKeyValuesAsString(TransitionPrefix)) {\n const parts = key.split(\"/\");\n if (parts.length !== 4) continue;\n const [, namespace, reporter, ns] = parts;\n // Leading zeros would break the length-first comparison, and no reporter writes them.\n if (!/^(0|[1-9]\\d*)$/.test(ns)) continue;\n\n out.firstNs = earlier(out.firstNs, ns);\n out.lastNs = later(out.lastNs, ns);\n\n const parsed = parseJsonObject(value);\n if (parsed === undefined) continue;\n const state = parsed.state;\n if (typeof state !== \"string\") continue;\n const detail = typeof parsed.detail === \"string\" ? parsed.detail : \"\";\n const reason = typeof parsed.reason === \"string\" ? parsed.reason : \"\";\n out.all.push({ namespace, reporter, ns, state, detail, reason });\n }\n\n return out;\n}\n\n/**\n * Reduces one context to {@link FoldedNode}.\n *\n * A context carries the reports of several reporters: the render reports under `render`, and the\n * commands and work dirs it created report under `exec` and `workdir`. The latest transition of\n * each reporter is that reporter's current state, and the state holding the node is the strongest\n * of those a reporter has not left, see {@link rank}.\n *\n * The node has ended when the render has reported its own end (`Completed` once its outputs are\n * set, `Terminated` with its error, or `Completed` with detail `deduplicated`) and every other\n * reporter in the context has ended too: the render's outputs being set does not stop a command it\n * started, and that command's report must stay visible.\n */\nexport function foldNode(transitions: readonly Transition[]): FoldedNode {\n const latestPerReporter = new Map<string, Transition>();\n for (const t of transitions) {\n const reporterKey = `${t.namespace}/${t.reporter}`;\n const previous = latestPerReporter.get(reporterKey);\n if (previous === undefined || compareNs(t.ns, previous.ns) > 0)\n latestPerReporter.set(reporterKey, t);\n }\n\n let render: Transition | undefined;\n let holding: Transition | undefined;\n let everyReporterEnded = true;\n for (const t of latestPerReporter.values()) {\n if (t.namespace === RenderNamespace) render = t;\n if (isTerminalBlockStatusState(t.state)) continue;\n everyReporterEnded = false;\n if (holding === undefined) {\n holding = t;\n continue;\n }\n const byRank = rank(t) - rank(holding);\n if (byRank > 0 || (byRank === 0 && compareNs(t.ns, holding.ns) > 0)) holding = t;\n }\n\n if (render !== undefined && isTerminalBlockStatusState(render.state) && everyReporterEnded)\n return {\n terminal: true,\n onMachine: false,\n failure: render.state === blockStatusStatesRecord.Terminated ? render.reason : undefined,\n };\n\n return {\n terminal: false,\n holding,\n onMachine:\n holding?.state === blockStatusStatesRecord.Running && holding.namespace === ExecNamespace,\n };\n}\n\n/** The render's own latest transition in a context. */\nexport function latestRender(transitions: readonly Transition[]): Transition | undefined {\n let latest: Transition | undefined;\n for (const t of transitions)\n if (t.namespace === RenderNamespace && (latest === undefined || compareNs(t.ns, latest.ns) > 0))\n latest = t;\n return latest;\n}\n\n/** One reading, as stored under `reading/<namespace>/<resource>/<key>`. */\nexport type Reading = { namespace: string; resource: string; key: string; value: string };\n\n/** One context read on its own, before its children are merged in. */\nexport type ContextFold = {\n readonly id: string;\n /** The baggage: `name`, `block-pack`, `block-id`, `run-id`. */\n readonly data: Record<string, unknown> | undefined;\n readonly reports: ContextReports;\n readonly readings: readonly Reading[];\n readonly folded: FoldedNode;\n /** True for a context a command or its work folder reports in: one job. */\n readonly job: boolean;\n /** The render's own latest transition, when it is a termination. */\n readonly terminated?: { readonly reason: string; readonly ns: string };\n /** Time its commands spent in `Running`, see {@link computeOf}. */\n readonly compute: ContextCompute;\n};\n\n/**\n * Time the commands of a context spent in `Running`: each Running up to the reporter's next\n * transition, ns. A command whose latest transition is Running is still open; it is counted up to\n * whatever moment the reader picks.\n */\nexport type ContextCompute = {\n readonly closedNs: bigint;\n /** When each command still running started, ns. */\n readonly openSinceNs: readonly string[];\n};\n\nfunction computeOf(all: readonly Transition[]): ContextCompute {\n const byReporter = new Map<string, Transition[]>();\n for (const t of all) {\n if (t.namespace !== ExecNamespace) continue;\n const list = byReporter.get(t.reporter);\n if (list === undefined) byReporter.set(t.reporter, [t]);\n else list.push(t);\n }\n\n let closedNs = 0n;\n const openSinceNs: string[] = [];\n for (const list of byReporter.values()) {\n list.sort((a, b) => compareNs(a.ns, b.ns));\n for (let i = 0; i < list.length; i++) {\n if (list[i].state !== blockStatusStatesRecord.Running) continue;\n const next = list[i + 1];\n if (next === undefined) openSinceNs.push(list[i].ns);\n else closedNs += BigInt(next.ns) - BigInt(list[i].ns);\n }\n }\n return { closedNs, openSinceNs };\n}\n\nfunction readReadings(node: ActionContextNode): Reading[] {\n const out: Reading[] = [];\n for (const { key, value } of node.listKeyValuesAsString(ReadingPrefix)) {\n const parts = key.split(\"/\");\n if (parts.length !== 4) continue;\n out.push({ namespace: parts[1], resource: parts[2], key: parts[3], value });\n }\n return out;\n}\n\n/** Reads one context: its transitions, its readings, and the state holding it. */\nexport function foldContext(node: ActionContextNode): ContextFold {\n const reports = readTransitions(node);\n const render = latestRender(reports.all);\n return {\n id: node.id,\n data: node.getData(),\n reports,\n readings: readReadings(node),\n folded: foldNode(reports.all),\n job: reports.all.some((t) => t.namespace === ExecNamespace || t.namespace === WorkdirNamespace),\n terminated:\n render?.state === blockStatusStatesRecord.Terminated\n ? { reason: render.reason, ns: render.ns }\n : undefined,\n compute: computeOf(reports.all),\n };\n}\n\n/** {@link BlockStatusJobGroup} being accumulated, its timestamp still in nanoseconds. */\ntype JobGroupTally = {\n readonly namespace: string;\n readonly state: string;\n readonly count: number;\n readonly sinceNs?: string;\n readonly files?: { readonly done: number; readonly total: number };\n};\n\n/**\n * {@link BlockStatusJobs} being accumulated over a subtree. Plain data throughout, no `Map`: it is\n * the value of a computable, which the computable types map over field by field.\n */\nexport type JobTally = {\n readonly total: number;\n readonly done: number;\n readonly failed: number;\n /** Jobs not ended, by `<namespace>/<state>` of the transition holding each. */\n readonly groups: Readonly<Record<string, JobGroupTally>>;\n};\n\nconst EmptyJobTally: JobTally = { total: 0, done: 0, failed: 0, groups: {} };\n\n/** A context and everything under it, folded. */\nexport type SubtreeFold = {\n readonly own: ContextFold;\n readonly children: readonly SubtreeFold[];\n /** This context and every context under it. */\n readonly contexts: number;\n /** Contexts in the subtree that have not ended. */\n readonly activeContexts: number;\n readonly firstNs?: string;\n readonly lastNs?: string;\n /**\n * The earliest render in the subtree whose latest report is a termination, with the context ids\n * from this context down to it.\n */\n readonly failure?: {\n readonly reason: string;\n readonly ns: string;\n readonly path: readonly string[];\n };\n readonly jobs: JobTally;\n /**\n * Time the subtree's commands spent in `Running`. Commands still running add their time up to a\n * moment the reader picks: `open × now − openSinceSumNs`.\n */\n readonly compute: {\n readonly closedNs: bigint;\n readonly open: number;\n readonly openSinceSumNs: bigint;\n };\n};\n\n/** Files done of all, summed over the work folders' progress readings of one context. */\nfunction workdirProgress(readings: readonly Reading[]): JobGroupTally[\"files\"] {\n let progress: JobGroupTally[\"files\"];\n for (const r of readings) {\n if (r.namespace !== WorkdirNamespace || r.key !== \"progress\") continue;\n const parsed = parseJsonObject(r.value);\n if (typeof parsed?.done !== \"number\" || typeof parsed.total !== \"number\") continue;\n progress = addFiles(progress, { done: parsed.done, total: parsed.total });\n }\n return progress;\n}\n\nfunction addFiles(a: JobGroupTally[\"files\"], b: JobGroupTally[\"files\"]): JobGroupTally[\"files\"] {\n if (a === undefined) return b;\n if (b === undefined) return a;\n return { done: a.done + b.done, total: a.total + b.total };\n}\n\nfunction groupKey(group: Pick<JobGroupTally, \"namespace\" | \"state\">): string {\n return `${group.namespace}/${group.state}`;\n}\n\nfunction mergeGroup(\n groups: Record<string, JobGroupTally>,\n key: string,\n group: JobGroupTally,\n): void {\n const previous = groups[key];\n groups[key] =\n previous === undefined\n ? group\n : {\n namespace: group.namespace,\n state: group.state,\n count: previous.count + group.count,\n sinceNs: earlier(previous.sinceNs, group.sinceNs),\n files: addFiles(previous.files, group.files),\n };\n}\n\n/** The job a context is, counted where it is now; empty when it is not one. */\nfunction ownJobs(own: ContextFold): JobTally {\n if (!own.job) return EmptyJobTally;\n const { terminal, failure, holding } = own.folded;\n if (terminal)\n return failure === undefined\n ? { ...EmptyJobTally, total: 1, done: 1 }\n : { ...EmptyJobTally, total: 1, failed: 1 };\n if (holding === undefined) return { ...EmptyJobTally, total: 1 };\n const group: JobGroupTally = {\n namespace: holding.namespace,\n state: holding.state,\n count: 1,\n sinceNs: holding.ns,\n files: workdirProgress(own.readings),\n };\n return { ...EmptyJobTally, total: 1, groups: { [groupKey(group)]: group } };\n}\n\n/**\n * Merges a context with the folds of its children. One pass over the direct children, so a report\n * re-merges each context on its path to the root and nothing else.\n */\nexport function mergeSubtree(own: ContextFold, children: readonly SubtreeFold[]): SubtreeFold {\n let contexts = 1;\n let activeContexts = own.folded.terminal ? 0 : 1;\n let firstNs = own.reports.firstNs;\n let lastNs = own.reports.lastNs;\n let failure: SubtreeFold[\"failure\"] =\n own.terminated === undefined ? undefined : { ...own.terminated, path: [own.id] };\n let failedBelow = false;\n let closedNs = own.compute.closedNs;\n let open = own.compute.openSinceNs.length;\n let openSinceSumNs = 0n;\n for (const since of own.compute.openSinceNs) openSinceSumNs += BigInt(since);\n\n const self = ownJobs(own);\n let { total, done, failed } = self;\n const groups: Record<string, JobGroupTally> = { ...self.groups };\n\n for (const child of children) {\n contexts += child.contexts;\n activeContexts += child.activeContexts;\n firstNs = earlier(firstNs, child.firstNs);\n lastNs = later(lastNs, child.lastNs);\n if (child.failure !== undefined) {\n failedBelow = true;\n if (failure === undefined || compareNs(child.failure.ns, failure.ns) < 0)\n failure = { ...child.failure, path: [own.id, ...child.failure.path] };\n }\n closedNs += child.compute.closedNs;\n open += child.compute.open;\n openSinceSumNs += child.compute.openSinceSumNs;\n total += child.jobs.total;\n done += child.jobs.done;\n failed += child.jobs.failed;\n for (const [key, group] of Object.entries(child.jobs.groups)) mergeGroup(groups, key, group);\n }\n\n // A render that failed on its own, e.g. one whose command could not start, is a failed job too;\n // one that only passes up the failure under it is not counted again.\n if (own.terminated !== undefined && !failedBelow && !own.job) {\n total++;\n failed++;\n }\n\n return {\n own,\n children,\n contexts,\n activeContexts,\n firstNs,\n lastNs,\n failure,\n jobs: { total, done, failed, groups },\n compute: { closedNs, open, openSinceSumNs },\n };\n}\n\n/**\n * The child contexts a fold follows: each once, and none already on the path from the root, so a\n * context linked twice or a cycle cannot count a subtree again.\n */\nexport function childContexts<T extends { readonly id: unknown }>(\n fields: readonly string[],\n traverse: (field: string) => T | undefined,\n path: ReadonlySet<string>,\n): T[] {\n if (path.size > MaxDepth) return [];\n const out: T[] = [];\n const seen = new Set<string>();\n for (const field of fields) {\n if (!field.startsWith(ChildFieldPrefix)) continue;\n const child = traverse(field);\n if (child === undefined) continue;\n const id = String(child.id);\n if (path.has(id) || seen.has(id)) continue;\n seen.add(id);\n out.push(child);\n }\n return out;\n}\n\n/**\n * Folds a context and everything under it in one walk: what the per-context computables compute,\n * for a tree that is read once.\n */\nexport function foldSubtree(\n node: ActionContextNode,\n path: ReadonlySet<string> = new Set(),\n): SubtreeFold {\n const below = new Set(path).add(node.id);\n const children = childContexts(node.listFields(), (f) => node.traverse(f), below);\n return mergeSubtree(\n foldContext(node),\n children.map((child) => foldSubtree(child, below)),\n );\n}\n\n/** Where the backend nests the error of an input inside the error of what consumes it. */\nconst InputErrorMarker = \"has input errors:\";\n\n/** Wrappers the workflow controller puts in front of a template's own error. */\nconst TemplateErrorPrefix = /^(cannot eval code: |cannot eval template: |tengo template error: )+/;\n\n/** Longest headline, in characters. */\nconst MaxHeadlineLength = 200;\n\n/**\n * The innermost message of a termination reason, for a title: the backend wraps the error of each\n * input in the error of its consumer, and tengo appends stack frames, so a reason can run to pages.\n */\nexport function failureHeadline(reason: string): string {\n const marker = reason.lastIndexOf(InputErrorMarker);\n const lines = reason\n .slice(marker < 0 ? 0 : marker + InputErrorMarker.length)\n .split(\"\\n\")\n .map((line) => line.trim())\n // Stack frames: `@platforma-sdk/workflow-tengo:tpl.base:595:5`.\n .filter((line) => line !== \"\" && !/^@\\S+:\\d+:\\d+$/.test(line));\n\n const text = lines.join(\" \");\n // A command that failed: `Command ID: … Command name: \"python\" … Error: docker is not set`.\n const command = /Command name: \"([^\"]*)\".*\\bError: (.+)$/.exec(text);\n const headline =\n command !== null\n ? `${command[1]} failed: ${command[2]}`\n : text.replace(TemplateErrorPrefix, \"\");\n return headline.length > MaxHeadlineLength\n ? `${headline.slice(0, MaxHeadlineLength - 1)}…`\n : headline;\n}\n\nfunction finishJobs(jobs: JobTally): BlockStatusJobs {\n const byState = Object.values(jobs.groups)\n .map((g): BlockStatusJobGroup => ({\n namespace: g.namespace,\n state: g.state,\n count: g.count,\n since: g.sinceNs === undefined ? undefined : nsToMs(g.sinceNs),\n files: g.files,\n }))\n .sort((a, b) => b.count - a.count || groupKey(a).localeCompare(groupKey(b)));\n return { total: jobs.total, done: jobs.done, failed: jobs.failed, byState };\n}\n\n/** The summary of a block run, from the fold of its root action context. */\nexport function summarize(root: SubtreeFold): BlockStatusSummary {\n const runId = root.own.data?.[\"run-id\"];\n const jobs = finishJobs(root.jobs);\n const summary = {\n availability: \"read\" as const,\n runId: typeof runId === \"string\" ? runId : undefined,\n activeContexts: root.activeContexts,\n totalContexts: root.contexts,\n jobs,\n startedAt: root.firstNs === undefined ? undefined : nsToMs(root.firstNs),\n };\n\n // A stopped run: its render is gone and reports nothing more, so the tree is frozen where it\n // stopped. The counters stay, to say where each node was; the run itself is over.\n let cancelledNs: string | undefined;\n for (const t of root.own.reports.all)\n if (t.namespace === CreatorNamespace && t.state === blockStatusStatesRecord.Terminated)\n cancelledNs = later(cancelledNs, t.ns);\n if (cancelledNs !== undefined)\n return { ...summary, lastChangeAt: nsToMs(cancelledNs), done: true, cancelled: true };\n\n // A terminated render fails the run. Renders waiting on its outputs never report again, so once\n // no job is held by its command or work folder the run is over, though they still look active.\n const working = jobs.byState.some((g) => g.namespace !== RenderNamespace);\n return {\n ...summary,\n lastChangeAt: root.lastNs === undefined ? undefined : nsToMs(root.lastNs),\n // The root's outputs can be set while work it started still runs, so done needs both.\n done:\n (root.own.folded.terminal && root.activeContexts === 0) ||\n (root.failure !== undefined && !working),\n failure: root.failure === undefined ? undefined : failureHeadline(root.failure.reason),\n };\n}\n\n/** The summary of a block run, from the root action context of its render. */\nexport function foldBlockStatus(root: ActionContextNode): BlockStatusSummary {\n return summarize(foldSubtree(root));\n}\n"],"mappings":";;;;;;AA6BA,SAAS,gBAAgB,OAAoD;CAC3E,IAAI;CACJ,IAAI;EACF,SAAS,KAAK,MAAM,KAAK;CAC3B,QAAQ;EACN;CACF;CACA,IAAI,OAAO,WAAW,YAAY,WAAW,QAAQ,MAAM,QAAQ,MAAM,GAAG,OAAO,KAAA;CACnF,OAAO,OAAO,YAAY,OAAO,QAAQ,MAAM,CAAC;AAClD;;AAyBA,MAAM,mBAAmB;;AAGzB,MAAM,mBAAmB;;AAGzB,MAAM,gBAAgB;;AAGtB,MAAM,kBAAkB;;;;;AAMxB,MAAM,mBAAmB;;AAGzB,MAAa,gBAAgB;;AAG7B,MAAa,mBAAmB;;AAsChC,SAAgB,UAAU,GAAW,GAAmB;CACtD,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,SAAS,EAAE,SAAS,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI;AAChF;;AAGA,SAAgB,OAAO,IAAoB;CACzC,OAAO,OAAO,OAAO,EAAE,IAAI,QAAU;AACvC;AAEA,SAAS,QAAQ,GAAuB,GAA2C;CACjF,OAAO,MAAM,KAAA,KAAc,MAAM,KAAA,KAAa,UAAU,GAAG,CAAC,IAAI,IAAK,IAAI;AAC3E;AAEA,SAAS,MAAM,GAAuB,GAA2C;CAC/E,OAAO,MAAM,KAAA,KAAc,MAAM,KAAA,KAAa,UAAU,GAAG,CAAC,IAAI,IAAK,IAAI;AAC3E;;;;;;;;;AAUA,SAAS,KAAK,GAAuB;CACnC,OAAO,EAAE,UAAU,wBAAwB,WAAW,EAAE,cAAc,kBAAkB,IAAI;AAC9F;;;;;;;AAQA,SAAgB,gBAAgB,MAAyC;CACvE,MAAM,MAAsB,EAAE,KAAK,CAAC,EAAE;CAEtC,KAAK,MAAM,EAAE,KAAK,WAAW,KA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AAO,KAAK;EAAO,MAAM,KAAK;EAAM,QAAQ,KAAK;EAAQ;CAAQ;AAC5E;;AAGA,SAAgB,UAAU,MAAuC;CAC/D,MAAM,QAAQ,KAAK,IAAI,OAAO;CAC9B,MAAM,OAAO,WAAW,KAAK,IAAI;CACjC,MAAM,UAAU;EACd,cAAc;EACd,OAAO,OAAO,UAAU,WAAW,QAAQ,KAAA;EAC3C,gBAAgB,KAAK;EACrB,eAAe,KAAK;EACpB;EACA,WAAW,KAAK,YAAY,KAAA,IAAY,KAAA,IAAY,OAAO,KAAK,OAAO;CACzE;CAIA,IAAI;CACJ,KAAK,MAAM,KAAK,KAAK,IAAI,QAAQ,KAC/B,IAAI,EAAE,cAAc,oBAAoB,EAAE,UAAU,wBAAwB,YAC1E,cAAc,MAAM,aAAa,EAAE,EAAE;CACzC,IAAI,gBAAgB,KAAA,GAClB,OAAO;EAAE,GAAG;EAAS,cAAc,OAAO,WAAW;EAAG,MAAM;EAAM,WAAW;CAAK;CAItF,MAAM,UAAU,KAAK,QAAQ,MAAM,MAAM,EAAE,cAAc,eAAe;CACxE,OAAO;EACL,GAAG;EACH,cAAc,KAAK,WAAW,KAAA,IAAY,KAAA,IAAY,OAAO,KAAK,MAAM;EAExE,MACG,KAAK,IAAI,OAAO,YAAY,KAAK,mBAAmB,KACpD,KAAK,YAAY,KAAA,KAAa,CAAC;EAClC,SAAS,KAAK,YAAY,KAAA,IAAY,KAAA,IAAY,gBAAgB,KAAK,QAAQ,MAAM;CACvF;AACF"}
@@ -1,6 +1,7 @@
1
1
  const require_project_model = require("../model/project_model.cjs");
2
2
  const require_render_block = require("../mutator/template/render_block.cjs");
3
3
  const require_block_status_fold = require("./block_status_fold.cjs");
4
+ const require_block_status_tree_fold = require("./block_status_tree_fold.cjs");
4
5
  let _milaboratories_pl_model_middle_layer = require("@milaboratories/pl-model-middle-layer");
5
6
  let _milaboratories_computable = require("@milaboratories/computable");
6
7
  let node_timers_promises = require("node:timers/promises");
@@ -104,17 +105,19 @@ function subtreeFold(entry, path, onError) {
104
105
  function entrySummary(entry, reportsSupported, onError) {
105
106
  return _milaboratories_computable.Computable.make(() => ({ fold: subtreeFold(entry, /* @__PURE__ */ new Set(), onError) }), {
106
107
  key: `block-status-summary/${entry.id}`,
107
- postprocessValue: ({ fold }) => {
108
- if (fold === void 0) return _milaboratories_pl_model_middle_layer.UnreadableBlockStatusSummary;
109
- const summary = require_block_status_fold.summarize(fold);
110
- if (reportsSupported || summary.totalContexts === 0) return summary;
111
- return {
112
- ...summary,
113
- availability: "unsupported"
114
- };
115
- }
108
+ postprocessValue: ({ fold }) => summaryOfFold(fold, reportsSupported)
116
109
  });
117
110
  }
111
+ /** The summary of a fold, or of a root context that could not be read. */
112
+ function summaryOfFold(fold, reportsSupported) {
113
+ if (fold === void 0) return _milaboratories_pl_model_middle_layer.UnreadableBlockStatusSummary;
114
+ const summary = require_block_status_fold.summarize(fold);
115
+ if (reportsSupported || summary.totalContexts === 0) return summary;
116
+ return {
117
+ ...summary,
118
+ availability: "unsupported"
119
+ };
120
+ }
118
121
  /**
119
122
  * The live status of one block render.
120
123
  *
@@ -138,6 +141,16 @@ var BlockStatusWatch = class BlockStatusWatch {
138
141
  /** How many callers hold this watch. The tree is terminated when it reaches zero. */
139
142
  holders = 0;
140
143
  summary;
144
+ /**
145
+ * The contexts whose children {@link tree} shows. Shared by every holder: two windows on one
146
+ * block see one expansion.
147
+ */
148
+ expanded = new _milaboratories_computable.WatchableValue(/* @__PURE__ */ new Set());
149
+ /**
150
+ * The run's tree, context by context, over the same synchronized tree as {@link summary}. It
151
+ * keeps its own per-context computables, so watching it doubles the cost of a report.
152
+ */
153
+ tree;
141
154
  env;
142
155
  projectRid;
143
156
  blockId;
@@ -155,6 +168,22 @@ var BlockStatusWatch = class BlockStatusWatch {
155
168
  if (entry === void 0) return reportsSupported ? _milaboratories_pl_model_middle_layer.EmptyBlockStatusSummary : _milaboratories_pl_model_middle_layer.UnsupportedBlockStatusSummary;
156
169
  return entrySummary(entry, reportsSupported, (err) => this.env.logger.warn(new Error("block status fold failed", { cause: err })));
157
170
  });
171
+ this.tree = _milaboratories_computable.Computable.make((ctx) => {
172
+ const entry = this.source.getValue(ctx);
173
+ return {
174
+ seeded: entry !== void 0,
175
+ expanded: [...this.expanded.getValue(ctx)],
176
+ fold: entry === void 0 ? void 0 : subtreeFold(entry, /* @__PURE__ */ new Set(), (err) => this.env.logger.warn(new Error("block status tree fold failed", { cause: err })))
177
+ };
178
+ }, { postprocessValue: ({ seeded, expanded, fold }) => {
179
+ if (!seeded) return require_block_status_tree_fold.emptyBlockStatusTree(reportsSupported ? _milaboratories_pl_model_middle_layer.EmptyBlockStatusSummary : _milaboratories_pl_model_middle_layer.UnsupportedBlockStatusSummary);
180
+ if (fold === void 0) return require_block_status_tree_fold.emptyBlockStatusTree(_milaboratories_pl_model_middle_layer.UnreadableBlockStatusSummary);
181
+ return require_block_status_tree_fold.blockStatusTree(fold, summaryOfFold(fold, reportsSupported), new Set(expanded));
182
+ } });
183
+ }
184
+ /** Replaces the set of contexts whose children {@link tree} shows. */
185
+ setExpanded(contextIds) {
186
+ this.expanded.setValue(new Set(contextIds), "block status tree expansion changed");
158
187
  }
159
188
  /**
160
189
  * Starts watching the status of a block render.
@@ -214,6 +243,7 @@ var BlockStatusWatch = class BlockStatusWatch {
214
243
  this.current = void 0;
215
244
  this.source.setValue(void 0, "block status watch terminated");
216
245
  this.summary.resetState();
246
+ this.tree.resetState();
217
247
  await this.terminateTree(held?.tree);
218
248
  }
219
249
  /**