@milaboratories/pl-middle-layer 2.2.0 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/dist/middle_layer/block_status_fold.cjs +427 -0
  2. package/dist/middle_layer/block_status_fold.cjs.map +1 -0
  3. package/dist/middle_layer/block_status_fold.js +416 -0
  4. package/dist/middle_layer/block_status_fold.js.map +1 -0
  5. package/dist/middle_layer/block_status_tree.cjs +317 -0
  6. package/dist/middle_layer/block_status_tree.cjs.map +1 -0
  7. package/dist/middle_layer/block_status_tree.js +313 -0
  8. package/dist/middle_layer/block_status_tree.js.map +1 -0
  9. package/dist/middle_layer/block_status_tree_fold.cjs +96 -0
  10. package/dist/middle_layer/block_status_tree_fold.cjs.map +1 -0
  11. package/dist/middle_layer/block_status_tree_fold.js +95 -0
  12. package/dist/middle_layer/block_status_tree_fold.js.map +1 -0
  13. package/dist/middle_layer/build_stamp.cjs +1 -1
  14. package/dist/middle_layer/build_stamp.js +1 -1
  15. package/dist/middle_layer/project.cjs +93 -2
  16. package/dist/middle_layer/project.cjs.map +1 -1
  17. package/dist/middle_layer/project.d.ts +34 -1
  18. package/dist/middle_layer/project.d.ts.map +1 -1
  19. package/dist/middle_layer/project.js +94 -3
  20. package/dist/middle_layer/project.js.map +1 -1
  21. package/dist/model/project_model.cjs +27 -0
  22. package/dist/model/project_model.cjs.map +1 -1
  23. package/dist/model/project_model.js +25 -1
  24. package/dist/model/project_model.js.map +1 -1
  25. package/dist/mutator/project.cjs +2 -1
  26. package/dist/mutator/project.cjs.map +1 -1
  27. package/dist/mutator/project.d.ts.map +1 -1
  28. package/dist/mutator/project.js +3 -2
  29. package/dist/mutator/project.js.map +1 -1
  30. package/dist/mutator/template/render_block.cjs +24 -0
  31. package/dist/mutator/template/render_block.cjs.map +1 -1
  32. package/dist/mutator/template/render_block.js +23 -2
  33. package/dist/mutator/template/render_block.js.map +1 -1
  34. package/package.json +15 -15
  35. package/src/middle_layer/block_status_bench.test.ts +288 -0
  36. package/src/middle_layer/block_status_fold.test.ts +635 -0
  37. package/src/middle_layer/block_status_fold.ts +625 -0
  38. package/src/middle_layer/block_status_test_utils.ts +62 -0
  39. package/src/middle_layer/block_status_tree.test.ts +276 -0
  40. package/src/middle_layer/block_status_tree.ts +443 -0
  41. package/src/middle_layer/block_status_tree_fold.test.ts +198 -0
  42. package/src/middle_layer/block_status_tree_fold.ts +150 -0
  43. package/src/middle_layer/project.ts +144 -2
  44. package/src/middle_layer/project_pruning.test.ts +59 -0
  45. package/src/model/project_model.ts +30 -0
  46. package/src/mutator/project.ts +7 -1
  47. package/src/mutator/project_action_context.test.ts +13 -3
  48. package/src/mutator/template/render_block.ts +32 -2
@@ -0,0 +1,150 @@
1
+ /**
2
+ * Builds the {@link BlockStatusTree} of a block run from the {@link SubtreeFold} of its root.
3
+ *
4
+ * Every counter it shows (contexts, active contexts, compute time, the first failure) is already
5
+ * merged into the fold bottom up, so building the tree touches only the root, its top-level
6
+ * contexts and the children of the expanded contexts. It reads nothing from the action-context
7
+ * tree itself.
8
+ *
9
+ * Source: docs/text/work/projects/sdk/block-status/README_teo.md, "Developer debug panel".
10
+ */
11
+
12
+ import type {
13
+ BlockStatusSummary,
14
+ BlockStatusTree,
15
+ BlockStatusTreeBranch,
16
+ BlockStatusTreeNode,
17
+ BlockStatusTreeReading,
18
+ BlockStatusTreeTransition,
19
+ } from "@milaboratories/pl-model-middle-layer";
20
+ import { BlockStatusTreeHeaviestCount } from "@milaboratories/pl-model-middle-layer";
21
+ import type { ActionContextNode, ContextFold, SubtreeFold } from "./block_status_fold";
22
+ import {
23
+ compareNs,
24
+ ExecNamespace,
25
+ foldSubtree,
26
+ nsToMs,
27
+ summarize,
28
+ WorkdirNamespace,
29
+ } from "./block_status_fold";
30
+
31
+ /** A tree with no context under it. */
32
+ export function emptyBlockStatusTree(summary: BlockStatusSummary): BlockStatusTree {
33
+ return { summary, heaviest: { byCompute: [], byContexts: [] } };
34
+ }
35
+
36
+ /**
37
+ * The tree of a block run.
38
+ *
39
+ * @param expanded context ids whose children the reader has opened. The root's children are
40
+ * always present.
41
+ */
42
+ export function blockStatusTree(
43
+ root: SubtreeFold,
44
+ summary: BlockStatusSummary,
45
+ expanded: ReadonlySet<string>,
46
+ ): BlockStatusTree {
47
+ // A command still running is counted up to the run's latest report, not to now: the fold has no
48
+ // clock, and the Desktop App extrapolates the same way for the run's own time.
49
+ const computeMs = (fold: SubtreeFold): number => {
50
+ const { closedNs, open, openSinceSumNs } = fold.compute;
51
+ const lastNs = root.lastNs === undefined ? 0n : BigInt(root.lastNs);
52
+ return Number((closedNs + BigInt(open) * lastNs - openSinceSumNs) / 1_000_000n);
53
+ };
54
+
55
+ const node = (fold: SubtreeFold, isRoot: boolean): BlockStatusTreeNode => {
56
+ const { own } = fold;
57
+ const { holding } = own.folded;
58
+ return {
59
+ contextId: own.id,
60
+ name: nameOf(own),
61
+ kind: kindOf(own),
62
+ baggage: baggageOf(own),
63
+ state: holding?.state,
64
+ onMachine: own.folded.onMachine,
65
+ enteredAt: holding === undefined ? undefined : nsToMs(holding.ns),
66
+ ended: own.folded.terminal,
67
+ failure: own.folded.failure || undefined,
68
+ transitions: transitionsOf(own),
69
+ readings: readingsOf(own),
70
+ childCount: fold.children.length,
71
+ subtreeContexts: fold.contexts,
72
+ subtreeActiveContexts: fold.activeContexts,
73
+ subtreeComputeMs: computeMs(fold),
74
+ children:
75
+ isRoot || expanded.has(own.id)
76
+ ? fold.children.map((child) => node(child, false))
77
+ : undefined,
78
+ };
79
+ };
80
+
81
+ /** The root's top-level contexts, ranked by one measure. One with nothing to rank is left out. */
82
+ const rank = (value: (fold: SubtreeFold) => number): BlockStatusTreeBranch[] =>
83
+ root.children
84
+ .map((child) => ({ contextId: child.own.id, name: nameOf(child.own), value: value(child) }))
85
+ .filter((b) => b.value > 0)
86
+ .sort((a, b) => b.value - a.value || a.contextId.localeCompare(b.contextId))
87
+ .slice(0, BlockStatusTreeHeaviestCount);
88
+
89
+ return {
90
+ summary,
91
+ heaviest: {
92
+ byCompute: rank(computeMs),
93
+ byContexts: rank((fold) => fold.contexts),
94
+ // No reporter writes file sizes yet.
95
+ byFileSize: undefined,
96
+ },
97
+ root: node(root, true),
98
+ firstFailurePath: root.failure?.path,
99
+ };
100
+ }
101
+
102
+ /** {@link blockStatusTree} over a tree that is read once. */
103
+ export function foldBlockStatusTree(
104
+ root: ActionContextNode,
105
+ expanded: ReadonlySet<string>,
106
+ ): BlockStatusTree {
107
+ const fold = foldSubtree(root);
108
+ return blockStatusTree(fold, summarize(fold), expanded);
109
+ }
110
+
111
+ function nameOf(own: ContextFold): string {
112
+ const name = own.data?.name;
113
+ return typeof name === "string" && name !== "" ? name : own.id;
114
+ }
115
+
116
+ function kindOf(own: ContextFold): BlockStatusTreeNode["kind"] {
117
+ const all = own.reports.all;
118
+ if (all.some((t) => t.namespace === ExecNamespace)) return "command";
119
+ if (all.length > 0 && all.every((t) => t.namespace === WorkdirNamespace)) return "workdir";
120
+ return "render";
121
+ }
122
+
123
+ function baggageOf(own: ContextFold): Record<string, string> {
124
+ const out: Record<string, string> = {};
125
+ for (const [key, value] of Object.entries(own.data ?? {}))
126
+ if (key !== "name") out[key] = typeof value === "string" ? value : JSON.stringify(value);
127
+ return out;
128
+ }
129
+
130
+ function transitionsOf(own: ContextFold): BlockStatusTreeTransition[] {
131
+ return [...own.reports.all]
132
+ .sort((a, b) => compareNs(a.ns, b.ns))
133
+ .map((t) => ({
134
+ namespace: t.namespace,
135
+ reporter: t.reporter,
136
+ state: t.state,
137
+ detail: t.detail || undefined,
138
+ reason: t.reason || undefined,
139
+ at: nsToMs(t.ns),
140
+ }));
141
+ }
142
+
143
+ function readingsOf(own: ContextFold): BlockStatusTreeReading[] {
144
+ return [...own.readings].sort(
145
+ (a, b) =>
146
+ a.namespace.localeCompare(b.namespace) ||
147
+ a.resource.localeCompare(b.resource) ||
148
+ a.key.localeCompare(b.key),
149
+ );
150
+ }
@@ -46,9 +46,15 @@ import { getBlockParameters, blockOutputs } from "./block";
46
46
  import type { BlockActionContextMode, BlockActionContextNode } from "./block_action_context";
47
47
  import { readBlockActionContextTree } from "./block_action_context";
48
48
  import { getBlockPackInfo } from "./util";
49
+ import { BlockStatusWatch } from "./block_status_tree";
50
+ import type { BlockStatusSummary, BlockStatusTree } from "@milaboratories/pl-model-middle-layer";
49
51
  import type { FrontendData } from "../model/frontend";
50
52
  import type { ProjectId, ProjectStructure } from "../model/project_model";
51
- import { projectFieldName } from "../model/project_model";
53
+ import {
54
+ projectFieldName,
55
+ ProjectStatusFieldPattern,
56
+ projectStatusFieldRegex,
57
+ } from "../model/project_model";
52
58
  import {
53
59
  cachedDeserialize,
54
60
  notEmpty,
@@ -124,6 +130,10 @@ export class Project {
124
130
  private readonly blockComputables = new Map<string, BlockStateComputables | null>();
125
131
 
126
132
  private readonly blockFrontends = new Map<string, ComputableStableDefined<FrontendData>>();
133
+
134
+ /** Live status watches, keyed by {@link blockStatusKey}. One per block whose status is shown;
135
+ * each owns a synchronized tree, so they are started and terminated explicitly. */
136
+ private readonly blockStatusWatches = new Map<string, Promise<BlockStatusWatch>>();
127
137
  private readonly activeConfigs: Computable<unknown[]>;
128
138
  private readonly refreshLoopResult: Promise<void>;
129
139
 
@@ -835,6 +845,123 @@ export class Project {
835
845
  return await readBlockActionContextTree(this.env.pl, this.rid, blockId, mode);
836
846
  }
837
847
 
848
+ /**
849
+ * Starts watching the live status of a block render, and returns the folded summary.
850
+ *
851
+ * One watch per block and mode: calling it again while a watch is open returns the same
852
+ * computable. The watch owns a synchronized tree, so the caller must call
853
+ * {@link unwatchBlockStatus} once it stops showing the status; {@link destroy} terminates
854
+ * whatever is left.
855
+ *
856
+ * The summary survives a re-run of the block: a new render gets a new status context, and the
857
+ * watch re-seeds itself onto it.
858
+ */
859
+ public async watchBlockStatus(
860
+ blockId: string,
861
+ mode: BlockActionContextMode = "prod",
862
+ ): Promise<Computable<BlockStatusSummary>> {
863
+ return (await this.retainBlockStatusWatch(blockId, mode)).summary;
864
+ }
865
+
866
+ /**
867
+ * Starts watching the action-context tree of a block render, context by context. Takes the same
868
+ * hold as {@link watchBlockStatus}, released by {@link unwatchBlockStatus}, and shares its
869
+ * synchronized tree.
870
+ */
871
+ public async watchBlockStatusTree(
872
+ blockId: string,
873
+ mode: BlockActionContextMode = "prod",
874
+ ): Promise<Computable<BlockStatusTree>> {
875
+ return (await this.retainBlockStatusWatch(blockId, mode)).tree;
876
+ }
877
+
878
+ /**
879
+ * Sets which contexts of {@link watchBlockStatusTree} show their children. A no-op while nobody
880
+ * watches the block: the expansion lives with the watch.
881
+ */
882
+ public async setBlockStatusTreeExpanded(
883
+ blockId: string,
884
+ contextIds: readonly string[],
885
+ mode: BlockActionContextMode = "prod",
886
+ ): Promise<void> {
887
+ const pending = this.blockStatusWatches.get(blockStatusKey(blockId, mode));
888
+ if (pending === undefined) return;
889
+ (await pending).setExpanded(contextIds);
890
+ }
891
+
892
+ private async retainBlockStatusWatch(
893
+ blockId: string,
894
+ mode: BlockActionContextMode,
895
+ ): Promise<BlockStatusWatch> {
896
+ if (this.destroyed)
897
+ throw new Error(`cannot watch the status of ${blockId}: the project is closed`);
898
+
899
+ const key = blockStatusKey(blockId, mode);
900
+ const existing = this.blockStatusWatches.get(key);
901
+ if (existing !== undefined) {
902
+ const watch = await existing;
903
+ watch.retain();
904
+ return watch;
905
+ }
906
+
907
+ const started = BlockStatusWatch.start({
908
+ env: this.env,
909
+ projectRid: this.rid,
910
+ blockId,
911
+ mode,
912
+ projectGeneration: () => (this.destroyed ? -1 : this.projectTree.changeGeneration),
913
+ });
914
+ this.blockStatusWatches.set(key, started);
915
+ // A failed start must not leave a rejected promise in the map for every later caller. Only
916
+ // this start's own entry is dropped: by the time a late rejection lands, the key may already
917
+ // hold a newer, live watch.
918
+ started.catch(() => {
919
+ if (this.blockStatusWatches.get(key) === started) this.blockStatusWatches.delete(key);
920
+ });
921
+ return await started;
922
+ }
923
+
924
+ /**
925
+ * Releases one hold taken by {@link watchBlockStatus}. The tree is terminated when the last
926
+ * holder lets go, so two callers watching one block do not cut each other off.
927
+ */
928
+ public async unwatchBlockStatus(
929
+ blockId: string,
930
+ mode: BlockActionContextMode = "prod",
931
+ ): Promise<void> {
932
+ const key = blockStatusKey(blockId, mode);
933
+ const pending = this.blockStatusWatches.get(key);
934
+ if (pending === undefined) return;
935
+
936
+ let watch: BlockStatusWatch;
937
+ try {
938
+ watch = await pending;
939
+ } catch {
940
+ // The start failed; its own catch handler drops the entry. Nothing to release, and a
941
+ // caller letting go must not see that failure again.
942
+ return;
943
+ }
944
+
945
+ if (await watch.release()) {
946
+ if (this.blockStatusWatches.get(key) === pending) this.blockStatusWatches.delete(key);
947
+ }
948
+ }
949
+
950
+ private async terminateBlockStatusWatches(): Promise<void> {
951
+ const watches = [...this.blockStatusWatches.values()];
952
+ this.blockStatusWatches.clear();
953
+ await Promise.all(
954
+ watches.map(async (watch) => {
955
+ try {
956
+ await (await watch).terminate();
957
+ } catch (e: unknown) {
958
+ // A watch whose start rejected has nothing to terminate; anything else is logged.
959
+ this.env.logger.warn(new Error("block status watch termination failed", { cause: e }));
960
+ }
961
+ }),
962
+ );
963
+ }
964
+
838
965
  public getBlockState(blockId: string): Computable<BlockStateInternalV3> {
839
966
  return this.getBlockComputables(blockId).fullState;
840
967
  }
@@ -870,6 +997,9 @@ export class Project {
870
997
  );
871
998
  }
872
999
 
1000
+ // terminating the status trees before the project tree: they are seeded from it
1001
+ await this.terminateBlockStatusWatches();
1002
+
873
1003
  // terminating the synchronized project tree
874
1004
  try {
875
1005
  await this.projectTree.terminate();
@@ -1015,6 +1145,11 @@ export function isSnapshotFailsafeError(e: unknown): boolean {
1015
1145
  return false;
1016
1146
  }
1017
1147
 
1148
+ /** Key of a status watch in {@link Project.blockStatusWatches}. */
1149
+ function blockStatusKey(blockId: string, mode: BlockActionContextMode): string {
1150
+ return `${mode}:${blockId}`;
1151
+ }
1152
+
1018
1153
  export function projectTreePruning(logger: MiLogger): PruningFunction {
1019
1154
  return (r: ExtendedResourceData): FieldData[] => {
1020
1155
  if (r.fields.length > 1000)
@@ -1030,7 +1165,9 @@ export function projectTreePruning(logger: MiLogger): PruningFunction {
1030
1165
  case "BlockPackCustom":
1031
1166
  return r.fields.filter((f) => f.name !== "template");
1032
1167
  case "UserProject":
1033
- return r.fields.filter((f) => !f.name.startsWith("__serviceTemplate"));
1168
+ return r.fields.filter(
1169
+ (f) => !f.name.startsWith("__serviceTemplate") && !projectStatusFieldRegex.test(f.name),
1170
+ );
1034
1171
  case "Blob":
1035
1172
  return [];
1036
1173
  default:
@@ -1055,6 +1192,11 @@ export function projectTreeFieldFilter(): Filter {
1055
1192
  treeFilter.resourceTypeEq("UserProject"),
1056
1193
  treeFilter.fieldNameMatch("^__serviceTemplate"),
1057
1194
  ),
1195
+ // UserProject: drop the status-context fields, see ProjectStatusFieldPattern
1196
+ treeFilter.and(
1197
+ treeFilter.resourceTypeEq("UserProject"),
1198
+ treeFilter.fieldNameMatch(ProjectStatusFieldPattern),
1199
+ ),
1058
1200
  // Blob — pruned entirely
1059
1201
  treeFilter.resourceTypeEq("Blob"),
1060
1202
  ),
@@ -15,6 +15,7 @@ import {
15
15
  projectTreeTraverseStopRules,
16
16
  } from "./project";
17
17
  import { projectsListFieldFilter, ProjectsListTreePruningFunction } from "./project_list";
18
+ import { ProjectStatusFieldNames, ProjectStatusFieldPattern } from "../model/project_model";
18
19
  import type { Filter } from "@milaboratories/pl-client";
19
20
  import {
20
21
  DefaultFinalResourceDataPredicate,
@@ -205,6 +206,47 @@ const projectPruningCases: Array<{
205
206
  fields: ["__serviceTemplateA", "__serviceTemplateB", "x"],
206
207
  expected: ["x"],
207
208
  },
209
+ {
210
+ name: "UserProject — status context fields dropped, others kept",
211
+ typeName: "UserProject",
212
+ fields: [
213
+ "block1-prodActionContext",
214
+ "block1-stagingActionContext",
215
+ "block1-prodOutput",
216
+ "block1-blockPack",
217
+ ],
218
+ expected: ["block1-prodOutput", "block1-blockPack"],
219
+ },
220
+ {
221
+ name: "UserProject — a block id containing a dash is still matched by suffix",
222
+ typeName: "UserProject",
223
+ fields: ["my-block-prodActionContext", "my-block-prodOutput"],
224
+ expected: ["my-block-prodOutput"],
225
+ },
226
+ {
227
+ name: "UserProject — a block id that is itself a status name is matched by suffix only",
228
+ typeName: "UserProject",
229
+ fields: ["prodActionContext-prodActionContext", "prodActionContext-blockPack"],
230
+ expected: ["prodActionContext-blockPack"],
231
+ },
232
+ {
233
+ name: "UserProject — a bare status name with no block id is kept, the dash is required",
234
+ typeName: "UserProject",
235
+ fields: ["prodActionContext", "stagingActionContext"],
236
+ expected: ["prodActionContext", "stagingActionContext"],
237
+ },
238
+ {
239
+ name: "UserProject — an empty block id still produces a status field",
240
+ typeName: "UserProject",
241
+ fields: ["-prodActionContext", "-prodOutput"],
242
+ expected: ["-prodOutput"],
243
+ },
244
+ {
245
+ name: "another type — a status-looking field is kept, the rule is UserProject's",
246
+ typeName: "SomeStructure",
247
+ fields: ["block1-prodActionContext"],
248
+ expected: ["block1-prodActionContext"],
249
+ },
208
250
  {
209
251
  name: "Blob — all fields dropped",
210
252
  typeName: "Blob",
@@ -219,6 +261,22 @@ const projectPruningCases: Array<{
219
261
  },
220
262
  ];
221
263
 
264
+ describe("the status field pattern stays portable", () => {
265
+ // projectTreeFieldFilter's pattern is evaluated by the BACKEND (Go RE2 via expr-lang), while
266
+ // projectTreePruning evaluates the JS copy. A construct only one engine knows would pass every
267
+ // parity case above and then fail compileFieldFilter server-side, which stops the project tree
268
+ // opening at all. Keep the pattern inside the subset both engines share.
269
+ it("uses no construct RE2 lacks", () => {
270
+ expect(ProjectStatusFieldPattern).not.toMatch(/\(\?/); // lookaround, named groups
271
+ expect(ProjectStatusFieldPattern).not.toMatch(/\\[1-9]/); // backreferences
272
+ });
273
+
274
+ it("is derived from the field names, so the two cannot drift", () => {
275
+ for (const name of ProjectStatusFieldNames)
276
+ expect(new RegExp(ProjectStatusFieldPattern).test(`block1-${name}`)).toBe(true);
277
+ });
278
+ });
279
+
222
280
  describe("§4.1 project tree pruning parity", () => {
223
281
  const pruner = projectTreePruning(noopLogger);
224
282
  const filter = projectTreeFieldFilter();
@@ -645,6 +703,7 @@ describe("§4.3 final-predicate parity: DefaultFinalResourceDataPredicate ⇄ pr
645
703
  { typeName: "Projects", label: "declared never" },
646
704
  { typeName: "ClientRoot", label: "declared never" },
647
705
  { typeName: "SomeUnknownType", label: "unmatched type" },
706
+ { typeName: "StatusContext", label: "declared never" },
648
707
  ];
649
708
 
650
709
  for (const { typeName, label } of neverFinalCases) {
@@ -149,6 +149,36 @@ export function projectFieldName(blockId: string, fieldName: ProjectField["field
149
149
  const projectFieldPattern =
150
150
  /^(?<blockId>.*)-(?<fieldName>blockPack|blockSettings|blockStorage|inputsValid|prodArgs|currentArgs|currentPrerunArgs|prodChainCtx|prodCtx|prodUiCtx|prodOutput|prodCtxPrevious|prodUiCtxPrevious|prodOutputPrevious|stagingCtx|stagingUiCtx|stagingOutput|stagingCtxPrevious|stagingUiCtxPrevious|stagingOutputPrevious|prodActionContext|stagingActionContext)$/;
151
151
 
152
+ /**
153
+ * The field names holding the root action context of a render.
154
+ *
155
+ * One list, from which both the backend pattern and the local predicate below are derived, so the
156
+ * two cannot drift and a misspelling is a type error.
157
+ */
158
+ export const ProjectStatusFieldNames = [
159
+ "prodActionContext",
160
+ "stagingActionContext",
161
+ ] as const satisfies readonly ProjectField["fieldName"][];
162
+
163
+ /**
164
+ * {@link ProjectStatusFieldNames} as a regular expression over a field name, for the backend's
165
+ * tree filter.
166
+ *
167
+ * The project tree prunes these. A status context holds the whole status subtree of its render,
168
+ * which fans out with the samples of the run, and every status report into it is a KV write; left
169
+ * in, the project tree would mirror thousands of resources and its change generation would move on
170
+ * every report, which is what drives the snapshot writer and the project's own generation waits.
171
+ * (It would not by itself recompute the project overview: that reads named fields and specific KV
172
+ * keys, and pl-tree notifies per read.) The status tree reads them instead, seeded at the context.
173
+ *
174
+ * Kept inside the subset RE2 and JavaScript agree on, because the backend evaluates this one and
175
+ * `projectTreePruning` evaluates the local copy. See the parity test.
176
+ */
177
+ export const ProjectStatusFieldPattern = `-(${ProjectStatusFieldNames.join("|")})$`;
178
+
179
+ /** {@link ProjectStatusFieldPattern} as a compiled expression, for readers outside the backend. */
180
+ export const projectStatusFieldRegex = new RegExp(ProjectStatusFieldPattern);
181
+
152
182
  export function parseProjectField(name: string): ProjectField | undefined {
153
183
  const match = name.match(projectFieldPattern);
154
184
  if (match === null) return undefined;
@@ -25,6 +25,7 @@ import {
25
25
  type BlockActionContextBaggage,
26
26
  createBContextFromUpstreams,
27
27
  createBContextEnd,
28
+ recordBlockRunCancelled,
28
29
  } from "./template/render_block";
29
30
  import type {
30
31
  Block,
@@ -1827,11 +1828,16 @@ export class ProjectMutator {
1827
1828
  // skipping finished blocks
1828
1829
  continue;
1829
1830
 
1830
- this.deleteBlockFields(blockId, "prodActionContext");
1831
1831
  if (this.deleteBlockFields(blockId, "prodOutput", "prodCtx", "prodUiCtx", "prodArgs")) {
1832
1832
  // was actually stopped
1833
1833
  stopped.push(blockId);
1834
1834
 
1835
+ // The run's status tree stays, so the user can see where it stopped; the next run replaces
1836
+ // it. It is marked cancelled, because a destroyed render reports nothing of its own.
1837
+ const actionContext = fields.prodActionContext?.ref;
1838
+ if (actionContext !== undefined && isResource(actionContext))
1839
+ recordBlockRunCancelled(this.tx, actionContext);
1840
+
1835
1841
  // will try to stop all its downstreams
1836
1842
  for (const downstream of activeProdGraph.traverseIdsExcludingRoots("downstream", blockId)) {
1837
1843
  if (queued.has(downstream)) continue;
@@ -70,7 +70,8 @@ test("block action context outlives its renderer and is replaced on re-render",
70
70
  // 4. The context has the Running transition of the render. Wait until the render is garbage
71
71
  // collected; the context must stay readable.
72
72
  // 5. Re-render production: prodActionContext must point at a new context with a new run-id.
73
- // 6. Render and stop production in one transaction: prodActionContext must be removed.
73
+ // 6. Render and stop production in one transaction: the stopped run keeps its context, marked
74
+ // cancelled.
74
75
  //
75
76
 
76
77
  const quickJs = await getQuickJS();
@@ -162,7 +163,8 @@ test("block action context outlives its renderer and is replaced on re-render",
162
163
  expect(second.baggage["run-id"]).not.toEqual(first.baggage["run-id"]);
163
164
  expect(await contextRender(pl, second.contextRef)).not.toEqual(firstRender);
164
165
 
165
- // 6. Render and stop production in one transaction: prodActionContext must be removed.
166
+ // 6. Render and stop production in one transaction: the stopped run keeps its new context, so
167
+ // its status tree stays readable, and the context is marked cancelled by its creator.
166
168
  await pl.withWriteTx("RenderAndStop", async (tx) => {
167
169
  const mut = await ProjectMutator.load(new ProjectHelper(quickJs), tx, prj);
168
170
  mut.setStates([
@@ -173,6 +175,14 @@ test("block action context outlives its renderer and is replaced on re-render",
173
175
  mut.save();
174
176
  await tx.commit();
175
177
  });
176
- expect(await readActionContext(pl, prj, "block1")).toBeUndefined();
178
+ const stopped = (await readActionContext(pl, prj, "block1"))!;
179
+ expect(stopped).toBeDefined();
180
+ expect(stopped.contextId).not.toEqual(second.contextId);
181
+ const cancelled = await poll(pl, async ({ tx }) =>
182
+ (await tx.listKeyValuesString(stopped.contextRef))
183
+ .filter((e) => e.key.startsWith("transition/core/"))
184
+ .map((e) => JSON.parse(e.value)),
185
+ );
186
+ expect(cancelled).toEqual([{ state: "Terminated", detail: "", reason: "cancelled" }]);
177
187
  });
178
188
  });
@@ -1,5 +1,11 @@
1
- import type { AnyRef, PlTransaction, ResourceRef, ResourceType } from "@milaboratories/pl-client";
2
- import { field, Pl } from "@milaboratories/pl-client";
1
+ import type {
2
+ AnyRef,
3
+ AnyResourceRef,
4
+ PlTransaction,
5
+ ResourceRef,
6
+ ResourceType,
7
+ } from "@milaboratories/pl-client";
8
+ import { field, isResourceId, parseSignedResourceId, Pl } from "@milaboratories/pl-client";
3
9
  import { randomUUID } from "node:crypto";
4
10
  import { createRenderTemplateWithResource } from "./render_template";
5
11
 
@@ -66,6 +72,30 @@ function createBlockActionContext(
66
72
  );
67
73
  }
68
74
 
75
+ /** The namespace the creator of a context reports under, as the backend reserves it. */
76
+ export const ActionContextCreatorNamespace = "core";
77
+
78
+ /** The reason recorded when the user stops a run. */
79
+ export const BlockRunCancelledReason = "cancelled";
80
+
81
+ /**
82
+ * Marks a block run's root action context as cancelled by the user.
83
+ *
84
+ * Stopping a block destroys its render, and a destroyed render reports nothing, so without this
85
+ * every node of a stopped run would read as live forever. The middle layer created the context, so
86
+ * it reports under the creator's namespace, with the context itself as the reporting resource and
87
+ * this machine's clock, the same key layout the backend's reporters use.
88
+ */
89
+ export function recordBlockRunCancelled(tx: PlTransaction, context: AnyResourceRef): void {
90
+ const reporter = isResourceId(context) ? String(parseSignedResourceId(context).globalId) : "0";
91
+ const ns = (BigInt(Date.now()) * 1_000_000n).toString();
92
+ tx.setKValue(
93
+ context,
94
+ `transition/${ActionContextCreatorNamespace}/${reporter}/${ns}`,
95
+ JSON.stringify({ state: "Terminated", detail: "", reason: BlockRunCancelledReason }),
96
+ );
97
+ }
98
+
69
99
  /**
70
100
  * Creates the heavy block render, and with `baggage` its root action context in the same
71
101
  * transaction. Returns `actionContext`: the render is garbage collected after its outputs resolve,