@milaboratories/pl-middle-layer 2.7.12 → 2.8.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.
@@ -1,4 +1,5 @@
1
1
  let _milaboratories_pl_model_middle_layer = require("@milaboratories/pl-model-middle-layer");
2
+ let zod = require("zod");
2
3
  // src/middle_layer/block_status_fold.ts
3
4
  /**
4
5
  * A key-value written as a JSON object, with its fields unchecked; undefined for anything else.
@@ -236,6 +237,63 @@ function mergeGroup(groups, key, group) {
236
237
  files: addFiles(previous.files, group.files)
237
238
  };
238
239
  }
240
+ /** The runner's reading with each command's telemetry record (`events.RunRecord` in pl). */
241
+ const TelemetryKey = "telemetry";
242
+ const EmptyUsage = {
243
+ jobs: 0,
244
+ cpu: {
245
+ used: 0,
246
+ granted: 0
247
+ },
248
+ ram: {
249
+ used: 0,
250
+ granted: 0
251
+ }
252
+ };
253
+ /** The part of a runner telemetry record (`events.RunRecord` in pl) the usage sums. */
254
+ const TelemetryRecord = zod.z.object({
255
+ cpu: zod.z.object({ peak: zod.z.number() }),
256
+ ram: zod.z.object({ peak: zod.z.number() }),
257
+ granted: zod.z.object({
258
+ cpu: zod.z.number(),
259
+ ram: zod.z.number()
260
+ })
261
+ });
262
+ function addUsage(a, b) {
263
+ return {
264
+ jobs: a.jobs + b.jobs,
265
+ cpu: {
266
+ used: a.cpu.used + b.cpu.used,
267
+ granted: a.cpu.granted + b.cpu.granted
268
+ },
269
+ ram: {
270
+ used: a.ram.used + b.ram.used,
271
+ granted: a.ram.granted + b.ram.granted
272
+ }
273
+ };
274
+ }
275
+ /** Each command's peak CPU and RAM and its grant, summed over the telemetry readings of a context. */
276
+ function ownUsage(readings) {
277
+ let usage = EmptyUsage;
278
+ for (const r of readings) {
279
+ if (r.namespace !== "exec" || r.key !== TelemetryKey) continue;
280
+ const parsed = TelemetryRecord.safeParse(parseJsonObject(r.value));
281
+ if (!parsed.success) continue;
282
+ const { cpu, ram, granted } = parsed.data;
283
+ usage = addUsage(usage, {
284
+ jobs: 1,
285
+ cpu: {
286
+ used: cpu.peak,
287
+ granted: granted.cpu * 1e3
288
+ },
289
+ ram: {
290
+ used: ram.peak,
291
+ granted: granted.ram
292
+ }
293
+ });
294
+ }
295
+ return usage;
296
+ }
239
297
  /** The job a context is, counted where it is now; empty when it is not one. */
240
298
  function ownJobs(own) {
241
299
  if (!own.job) return EmptyJobTally;
@@ -287,6 +345,7 @@ function mergeSubtree(own, children) {
287
345
  const self = ownJobs(own);
288
346
  let { total, done, failed } = self;
289
347
  const groups = { ...self.groups };
348
+ let usage = ownUsage(own.readings);
290
349
  for (const child of children) {
291
350
  contexts += child.contexts;
292
351
  activeContexts += child.activeContexts;
@@ -306,6 +365,7 @@ function mergeSubtree(own, children) {
306
365
  done += child.jobs.done;
307
366
  failed += child.jobs.failed;
308
367
  for (const [key, group] of Object.entries(child.jobs.groups)) mergeGroup(groups, key, group);
368
+ usage = addUsage(usage, child.usage);
309
369
  }
310
370
  if (own.terminated !== void 0 && !failedBelow && !own.job) {
311
371
  total++;
@@ -325,6 +385,7 @@ function mergeSubtree(own, children) {
325
385
  failed,
326
386
  groups
327
387
  },
388
+ usage,
328
389
  compute: {
329
390
  closedNs,
330
391
  open,
@@ -393,6 +454,7 @@ function summarize(root) {
393
454
  activeContexts: root.activeContexts,
394
455
  totalContexts: root.contexts,
395
456
  jobs,
457
+ usage: root.usage.jobs === 0 ? void 0 : root.usage,
396
458
  startedAt: root.firstNs === void 0 ? void 0 : nsToMs(root.firstNs)
397
459
  };
398
460
  let cancelledNs;
@@ -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. */\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,M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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","z"],"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 BlockStatusUsage,\n} from \"@milaboratories/pl-model-middle-layer\";\nimport {\n blockStatusStatesRecord,\n isTerminalBlockStatusState,\n} from \"@milaboratories/pl-model-middle-layer\";\nimport { z } from \"zod\";\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 /** CPU and RAM of the subtree's commands that report telemetry. */\n readonly usage: BlockStatusUsage;\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 runner's reading with each command's telemetry record (`events.RunRecord` in pl). */\nconst TelemetryKey = \"telemetry\";\n\nconst EmptyUsage: BlockStatusUsage = {\n jobs: 0,\n cpu: { used: 0, granted: 0 },\n ram: { used: 0, granted: 0 },\n};\n\n/** The part of a runner telemetry record (`events.RunRecord` in pl) the usage sums. */\nconst TelemetryRecord = z.object({\n cpu: z.object({ peak: z.number() }),\n ram: z.object({ peak: z.number() }),\n granted: z.object({ cpu: z.number(), ram: z.number() }),\n});\n\nfunction addUsage(a: BlockStatusUsage, b: BlockStatusUsage): BlockStatusUsage {\n return {\n jobs: a.jobs + b.jobs,\n cpu: { used: a.cpu.used + b.cpu.used, granted: a.cpu.granted + b.cpu.granted },\n ram: { used: a.ram.used + b.ram.used, granted: a.ram.granted + b.ram.granted },\n };\n}\n\n/** Each command's peak CPU and RAM and its grant, summed over the telemetry readings of a context. */\nfunction ownUsage(readings: readonly Reading[]): BlockStatusUsage {\n let usage = EmptyUsage;\n for (const r of readings) {\n if (r.namespace !== ExecNamespace || r.key !== TelemetryKey) continue;\n const parsed = TelemetryRecord.safeParse(parseJsonObject(r.value));\n if (!parsed.success) continue;\n const { cpu, ram, granted } = parsed.data;\n usage = addUsage(usage, {\n jobs: 1,\n // Usage is in millicores, the grant in whole cores.\n cpu: { used: cpu.peak, granted: granted.cpu * 1000 },\n ram: { used: ram.peak, granted: granted.ram },\n });\n }\n return usage;\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 let usage = ownUsage(own.readings);\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 usage = addUsage(usage, child.usage);\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 usage,\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 usage: root.usage.jobs === 0 ? undefined : root.usage,\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":";;;;;;;AA+BA,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,SAA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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,4 +1,5 @@
1
1
  import { blockStatusStatesRecord, isTerminalBlockStatusState } from "@milaboratories/pl-model-middle-layer";
2
+ import { z } from "zod";
2
3
  // src/middle_layer/block_status_fold.ts
3
4
  /**
4
5
  * A key-value written as a JSON object, with its fields unchecked; undefined for anything else.
@@ -236,6 +237,63 @@ function mergeGroup(groups, key, group) {
236
237
  files: addFiles(previous.files, group.files)
237
238
  };
238
239
  }
240
+ /** The runner's reading with each command's telemetry record (`events.RunRecord` in pl). */
241
+ const TelemetryKey = "telemetry";
242
+ const EmptyUsage = {
243
+ jobs: 0,
244
+ cpu: {
245
+ used: 0,
246
+ granted: 0
247
+ },
248
+ ram: {
249
+ used: 0,
250
+ granted: 0
251
+ }
252
+ };
253
+ /** The part of a runner telemetry record (`events.RunRecord` in pl) the usage sums. */
254
+ const TelemetryRecord = z.object({
255
+ cpu: z.object({ peak: z.number() }),
256
+ ram: z.object({ peak: z.number() }),
257
+ granted: z.object({
258
+ cpu: z.number(),
259
+ ram: z.number()
260
+ })
261
+ });
262
+ function addUsage(a, b) {
263
+ return {
264
+ jobs: a.jobs + b.jobs,
265
+ cpu: {
266
+ used: a.cpu.used + b.cpu.used,
267
+ granted: a.cpu.granted + b.cpu.granted
268
+ },
269
+ ram: {
270
+ used: a.ram.used + b.ram.used,
271
+ granted: a.ram.granted + b.ram.granted
272
+ }
273
+ };
274
+ }
275
+ /** Each command's peak CPU and RAM and its grant, summed over the telemetry readings of a context. */
276
+ function ownUsage(readings) {
277
+ let usage = EmptyUsage;
278
+ for (const r of readings) {
279
+ if (r.namespace !== "exec" || r.key !== TelemetryKey) continue;
280
+ const parsed = TelemetryRecord.safeParse(parseJsonObject(r.value));
281
+ if (!parsed.success) continue;
282
+ const { cpu, ram, granted } = parsed.data;
283
+ usage = addUsage(usage, {
284
+ jobs: 1,
285
+ cpu: {
286
+ used: cpu.peak,
287
+ granted: granted.cpu * 1e3
288
+ },
289
+ ram: {
290
+ used: ram.peak,
291
+ granted: granted.ram
292
+ }
293
+ });
294
+ }
295
+ return usage;
296
+ }
239
297
  /** The job a context is, counted where it is now; empty when it is not one. */
240
298
  function ownJobs(own) {
241
299
  if (!own.job) return EmptyJobTally;
@@ -287,6 +345,7 @@ function mergeSubtree(own, children) {
287
345
  const self = ownJobs(own);
288
346
  let { total, done, failed } = self;
289
347
  const groups = { ...self.groups };
348
+ let usage = ownUsage(own.readings);
290
349
  for (const child of children) {
291
350
  contexts += child.contexts;
292
351
  activeContexts += child.activeContexts;
@@ -306,6 +365,7 @@ function mergeSubtree(own, children) {
306
365
  done += child.jobs.done;
307
366
  failed += child.jobs.failed;
308
367
  for (const [key, group] of Object.entries(child.jobs.groups)) mergeGroup(groups, key, group);
368
+ usage = addUsage(usage, child.usage);
309
369
  }
310
370
  if (own.terminated !== void 0 && !failedBelow && !own.job) {
311
371
  total++;
@@ -325,6 +385,7 @@ function mergeSubtree(own, children) {
325
385
  failed,
326
386
  groups
327
387
  },
388
+ usage,
328
389
  compute: {
329
390
  closedNs,
330
391
  open,
@@ -393,6 +454,7 @@ function summarize(root) {
393
454
  activeContexts: root.activeContexts,
394
455
  totalContexts: root.contexts,
395
456
  jobs,
457
+ usage: root.usage.jobs === 0 ? void 0 : root.usage,
396
458
  startedAt: root.firstNs === void 0 ? void 0 : nsToMs(root.firstNs)
397
459
  };
398
460
  let cancelledNs;
@@ -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. */\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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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 BlockStatusUsage,\n} from \"@milaboratories/pl-model-middle-layer\";\nimport {\n blockStatusStatesRecord,\n isTerminalBlockStatusState,\n} from \"@milaboratories/pl-model-middle-layer\";\nimport { z } from \"zod\";\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 /** CPU and RAM of the subtree's commands that report telemetry. */\n readonly usage: BlockStatusUsage;\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 runner's reading with each command's telemetry record (`events.RunRecord` in pl). */\nconst TelemetryKey = \"telemetry\";\n\nconst EmptyUsage: BlockStatusUsage = {\n jobs: 0,\n cpu: { used: 0, granted: 0 },\n ram: { used: 0, granted: 0 },\n};\n\n/** The part of a runner telemetry record (`events.RunRecord` in pl) the usage sums. */\nconst TelemetryRecord = z.object({\n cpu: z.object({ peak: z.number() }),\n ram: z.object({ peak: z.number() }),\n granted: z.object({ cpu: z.number(), ram: z.number() }),\n});\n\nfunction addUsage(a: BlockStatusUsage, b: BlockStatusUsage): BlockStatusUsage {\n return {\n jobs: a.jobs + b.jobs,\n cpu: { used: a.cpu.used + b.cpu.used, granted: a.cpu.granted + b.cpu.granted },\n ram: { used: a.ram.used + b.ram.used, granted: a.ram.granted + b.ram.granted },\n };\n}\n\n/** Each command's peak CPU and RAM and its grant, summed over the telemetry readings of a context. */\nfunction ownUsage(readings: readonly Reading[]): BlockStatusUsage {\n let usage = EmptyUsage;\n for (const r of readings) {\n if (r.namespace !== ExecNamespace || r.key !== TelemetryKey) continue;\n const parsed = TelemetryRecord.safeParse(parseJsonObject(r.value));\n if (!parsed.success) continue;\n const { cpu, ram, granted } = parsed.data;\n usage = addUsage(usage, {\n jobs: 1,\n // Usage is in millicores, the grant in whole cores.\n cpu: { used: cpu.peak, granted: granted.cpu * 1000 },\n ram: { used: ram.peak, granted: granted.ram },\n });\n }\n return usage;\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 let usage = ownUsage(own.readings);\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 usage = addUsage(usage, child.usage);\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 usage,\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 usage: root.usage.jobs === 0 ? undefined : root.usage,\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":";;;;;;;AA+BA,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;;AAs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zC,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,7 +1,7 @@
1
1
  // src/middle_layer/build_stamp.ts
2
2
  function injectedStamp() {
3
3
  try {
4
- return "35fc8eeee6a7-dirty-1795431145665";
4
+ return "c1f78bc96ab4-dirty-1795511420536";
5
5
  } catch {
6
6
  return;
7
7
  }
@@ -1,7 +1,7 @@
1
1
  // src/middle_layer/build_stamp.ts
2
2
  function injectedStamp() {
3
3
  try {
4
- return "35fc8eeee6a7-dirty-1795431145644";
4
+ return "c1f78bc96ab4-dirty-1795511420509";
5
5
  } catch {
6
6
  return;
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@milaboratories/pl-middle-layer",
3
- "version": "2.7.12",
3
+ "version": "2.8.0",
4
4
  "description": "Pl Middle Layer",
5
5
  "keywords": [],
6
6
  "license": "UNLICENSED",
@@ -22,8 +22,8 @@
22
22
  "@milaboratories/columns-collection-driver": "0.3.0",
23
23
  "@milaboratories/computable": "2.9.10",
24
24
  "@milaboratories/helpers": "1.14.7",
25
- "@milaboratories/pf-driver": "1.9.19",
26
- "@milaboratories/pf-spec-driver": "1.6.1",
25
+ "@milaboratories/pf-driver": "1.9.20",
26
+ "@milaboratories/pf-spec-driver": "1.6.2",
27
27
  "@milaboratories/pframes-rs-node": "1.3.1",
28
28
  "@milaboratories/pl-client": "3.27.0",
29
29
  "@milaboratories/pl-crash-recorder": "0.3.12",
@@ -32,12 +32,12 @@
32
32
  "@milaboratories/pl-http": "1.2.7",
33
33
  "@milaboratories/pl-model-backend": "1.4.53",
34
34
  "@milaboratories/pl-model-common": "1.56.0",
35
- "@milaboratories/pl-model-middle-layer": "1.40.0",
35
+ "@milaboratories/pl-model-middle-layer": "1.41.0",
36
36
  "@milaboratories/pl-tree": "1.18.7",
37
37
  "@milaboratories/resolve-helper": "1.1.3",
38
38
  "@milaboratories/ts-helpers": "1.9.1",
39
- "@platforma-sdk/block-tools": "2.20.5",
40
- "@platforma-sdk/model": "1.90.2",
39
+ "@platforma-sdk/block-tools": "2.20.6",
40
+ "@platforma-sdk/model": "1.90.20",
41
41
  "@platforma-sdk/workflow-tengo": "6.24.3",
42
42
  "canonicalize": "~2.1.0",
43
43
  "denque": "^2.1.0",
@@ -17,11 +17,13 @@ import type {
17
17
  BlockStatusJobGroup,
18
18
  BlockStatusJobs,
19
19
  BlockStatusSummary,
20
+ BlockStatusUsage,
20
21
  } from "@milaboratories/pl-model-middle-layer";
21
22
  import {
22
23
  blockStatusStatesRecord,
23
24
  isTerminalBlockStatusState,
24
25
  } from "@milaboratories/pl-model-middle-layer";
26
+ import { z } from "zod";
25
27
 
26
28
  /**
27
29
  * A key-value written as a JSON object, with its fields unchecked; undefined for anything else.
@@ -366,6 +368,8 @@ export type SubtreeFold = {
366
368
  readonly path: readonly string[];
367
369
  };
368
370
  readonly jobs: JobTally;
371
+ /** CPU and RAM of the subtree's commands that report telemetry. */
372
+ readonly usage: BlockStatusUsage;
369
373
  /**
370
374
  * Time the subtree's commands spent in `Running`. Commands still running add their time up to a
371
375
  * moment the reader picks: `open × now − openSinceSumNs`.
@@ -417,6 +421,48 @@ function mergeGroup(
417
421
  };
418
422
  }
419
423
 
424
+ /** The runner's reading with each command's telemetry record (`events.RunRecord` in pl). */
425
+ const TelemetryKey = "telemetry";
426
+
427
+ const EmptyUsage: BlockStatusUsage = {
428
+ jobs: 0,
429
+ cpu: { used: 0, granted: 0 },
430
+ ram: { used: 0, granted: 0 },
431
+ };
432
+
433
+ /** The part of a runner telemetry record (`events.RunRecord` in pl) the usage sums. */
434
+ const TelemetryRecord = z.object({
435
+ cpu: z.object({ peak: z.number() }),
436
+ ram: z.object({ peak: z.number() }),
437
+ granted: z.object({ cpu: z.number(), ram: z.number() }),
438
+ });
439
+
440
+ function addUsage(a: BlockStatusUsage, b: BlockStatusUsage): BlockStatusUsage {
441
+ return {
442
+ jobs: a.jobs + b.jobs,
443
+ cpu: { used: a.cpu.used + b.cpu.used, granted: a.cpu.granted + b.cpu.granted },
444
+ ram: { used: a.ram.used + b.ram.used, granted: a.ram.granted + b.ram.granted },
445
+ };
446
+ }
447
+
448
+ /** Each command's peak CPU and RAM and its grant, summed over the telemetry readings of a context. */
449
+ function ownUsage(readings: readonly Reading[]): BlockStatusUsage {
450
+ let usage = EmptyUsage;
451
+ for (const r of readings) {
452
+ if (r.namespace !== ExecNamespace || r.key !== TelemetryKey) continue;
453
+ const parsed = TelemetryRecord.safeParse(parseJsonObject(r.value));
454
+ if (!parsed.success) continue;
455
+ const { cpu, ram, granted } = parsed.data;
456
+ usage = addUsage(usage, {
457
+ jobs: 1,
458
+ // Usage is in millicores, the grant in whole cores.
459
+ cpu: { used: cpu.peak, granted: granted.cpu * 1000 },
460
+ ram: { used: ram.peak, granted: granted.ram },
461
+ });
462
+ }
463
+ return usage;
464
+ }
465
+
420
466
  /** The job a context is, counted where it is now; empty when it is not one. */
421
467
  function ownJobs(own: ContextFold): JobTally {
422
468
  if (!own.job) return EmptyJobTally;
@@ -456,6 +502,7 @@ export function mergeSubtree(own: ContextFold, children: readonly SubtreeFold[])
456
502
  const self = ownJobs(own);
457
503
  let { total, done, failed } = self;
458
504
  const groups: Record<string, JobGroupTally> = { ...self.groups };
505
+ let usage = ownUsage(own.readings);
459
506
 
460
507
  for (const child of children) {
461
508
  contexts += child.contexts;
@@ -474,6 +521,7 @@ export function mergeSubtree(own: ContextFold, children: readonly SubtreeFold[])
474
521
  done += child.jobs.done;
475
522
  failed += child.jobs.failed;
476
523
  for (const [key, group] of Object.entries(child.jobs.groups)) mergeGroup(groups, key, group);
524
+ usage = addUsage(usage, child.usage);
477
525
  }
478
526
 
479
527
  // A render that failed on its own, e.g. one whose command could not start, is a failed job too;
@@ -492,6 +540,7 @@ export function mergeSubtree(own: ContextFold, children: readonly SubtreeFold[])
492
540
  lastNs,
493
541
  failure,
494
542
  jobs: { total, done, failed, groups },
543
+ usage,
495
544
  compute: { closedNs, open, openSinceSumNs },
496
545
  };
497
546
  }
@@ -593,6 +642,7 @@ export function summarize(root: SubtreeFold): BlockStatusSummary {
593
642
  activeContexts: root.activeContexts,
594
643
  totalContexts: root.contexts,
595
644
  jobs,
645
+ usage: root.usage.jobs === 0 ? undefined : root.usage,
596
646
  startedAt: root.firstNs === undefined ? undefined : nsToMs(root.firstNs),
597
647
  };
598
648