@milaboratories/pl-middle-layer 2.1.2 → 2.3.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 (47) hide show
  1. package/dist/middle_layer/block_status_fold.cjs +382 -0
  2. package/dist/middle_layer/block_status_fold.cjs.map +1 -0
  3. package/dist/middle_layer/block_status_fold.js +373 -0
  4. package/dist/middle_layer/block_status_fold.js.map +1 -0
  5. package/dist/middle_layer/block_status_tree.cjs +287 -0
  6. package/dist/middle_layer/block_status_tree.cjs.map +1 -0
  7. package/dist/middle_layer/block_status_tree.js +283 -0
  8. package/dist/middle_layer/block_status_tree.js.map +1 -0
  9. package/dist/middle_layer/build_stamp.cjs +1 -1
  10. package/dist/middle_layer/build_stamp.js +1 -1
  11. package/dist/middle_layer/instance_stats.cjs +2 -2
  12. package/dist/middle_layer/instance_stats.cjs.map +1 -1
  13. package/dist/middle_layer/instance_stats.js +2 -2
  14. package/dist/middle_layer/instance_stats.js.map +1 -1
  15. package/dist/middle_layer/project.cjs +73 -2
  16. package/dist/middle_layer/project.cjs.map +1 -1
  17. package/dist/middle_layer/project.d.ts +22 -1
  18. package/dist/middle_layer/project.d.ts.map +1 -1
  19. package/dist/middle_layer/project.js +74 -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 +14 -14
  35. package/src/middle_layer/block_status_bench.test.ts +197 -0
  36. package/src/middle_layer/block_status_fold.test.ts +694 -0
  37. package/src/middle_layer/block_status_fold.ts +563 -0
  38. package/src/middle_layer/block_status_tree.test.ts +253 -0
  39. package/src/middle_layer/block_status_tree.ts +391 -0
  40. package/src/middle_layer/instance_stats.test.ts +7 -9
  41. package/src/middle_layer/instance_stats.ts +2 -2
  42. package/src/middle_layer/project.ts +111 -2
  43. package/src/middle_layer/project_pruning.test.ts +59 -0
  44. package/src/model/project_model.ts +30 -0
  45. package/src/mutator/project.ts +7 -1
  46. package/src/mutator/project_action_context.test.ts +13 -3
  47. package/src/mutator/template/render_block.ts +32 -2
@@ -18,7 +18,7 @@ describe("parseInstanceStats", () => {
18
18
  kv("reading/instance/source", "scheduler"),
19
19
  ]),
20
20
  ).toEqual({
21
- availability: "read",
21
+ status: "ok",
22
22
  cpu: { total: 24000, current: 18500 },
23
23
  ram: { total: 64e9, current: 41e9 },
24
24
  jobs: { running: 12, queued: 14 },
@@ -51,7 +51,7 @@ describe("parseInstanceStats", () => {
51
51
  kv("reading/instance/jobs", { running: "many" }),
52
52
  kv("reading/other/cpu", { current: 1 }),
53
53
  ]);
54
- expect(stats).toEqual({ availability: "read" });
54
+ expect(stats).toEqual({ status: "ok" });
55
55
  });
56
56
  });
57
57
 
@@ -64,9 +64,7 @@ test("the watch reads a sample where the capability is advertised, and nothing e
64
64
  await new Promise((r) => setTimeout(r, 100));
65
65
  stats = await watch.stats.getValue();
66
66
  }
67
- expect(stats?.availability).toEqual(
68
- pl.hasCapability(InstanceStatsCapability) ? "read" : "unsupported",
69
- );
67
+ expect(stats?.status).toEqual(pl.hasCapability(InstanceStatsCapability) ? "ok" : "unsupported");
70
68
  } finally {
71
69
  await watch.terminate();
72
70
  await pl.close();
@@ -113,13 +111,13 @@ async function firstSample(client: InstanceStatsClient) {
113
111
  describe("InstanceStatsWatch", () => {
114
112
  it("does nothing on a backend that does not advertise the capability", async () => {
115
113
  const client = fakeClient({ capabilities: [] });
116
- expect(await firstSample(client)).toEqual({ availability: "unsupported" });
114
+ expect(await firstSample(client)).toEqual({ status: "unsupported" });
117
115
  expect(client.listed).toBe(0);
118
116
  });
119
117
 
120
118
  it("reports unsupported when the capability is advertised but the context is missing", async () => {
121
119
  const client = fakeClient({ capabilities: [InstanceStatsCapability] });
122
- expect(await firstSample(client)).toEqual({ availability: "unsupported" });
120
+ expect(await firstSample(client)).toEqual({ status: "unsupported" });
123
121
  expect(client.listed).toBe(1);
124
122
  });
125
123
 
@@ -127,9 +125,9 @@ describe("InstanceStatsWatch", () => {
127
125
  const sample = [kv("reading/instance/jobs", { running: 1, queued: 2 })];
128
126
  expect(
129
127
  await firstSample(fakeClient({ capabilities: [InstanceStatsCapability], context: sample })),
130
- ).toEqual({ availability: "read", jobs: { running: 1, queued: 2 } });
128
+ ).toEqual({ status: "ok", jobs: { running: 1, queued: 2 } });
131
129
  expect(
132
130
  await firstSample(fakeClient({ capabilities: [InstanceStatsCapability], context: [] })),
133
- ).toEqual({ availability: "read" });
131
+ ).toEqual({ status: "ok" });
134
132
  });
135
133
  });
@@ -66,7 +66,7 @@ export function parseInstanceStats(kvs: readonly { key: string; value: string }[
66
66
 
67
67
  const source = readings.get("source");
68
68
  return {
69
- availability: "read",
69
+ status: "ok",
70
70
  cpu: asCapacity(readings.get("cpu")),
71
71
  ram: asCapacity(readings.get("ram")),
72
72
  gpu: asCapacity(readings.get("gpu")),
@@ -160,7 +160,7 @@ export class InstanceStatsWatch {
160
160
  // Retried on the next tick, with the context looked up again in case it was replaced.
161
161
  this.logger.warn(new Error("instance stats read failed", { cause: err }));
162
162
  context = undefined;
163
- this.publish({ availability: "unreadable" });
163
+ this.publish({ status: "unreadable" });
164
164
  }
165
165
 
166
166
  try {
@@ -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 } 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,90 @@ 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
+ if (this.destroyed)
864
+ throw new Error(`cannot watch the status of ${blockId}: the project is closed`);
865
+
866
+ const key = blockStatusKey(blockId, mode);
867
+ const existing = this.blockStatusWatches.get(key);
868
+ if (existing !== undefined) {
869
+ const watch = await existing;
870
+ watch.retain();
871
+ return watch.summary;
872
+ }
873
+
874
+ const started = BlockStatusWatch.start({
875
+ env: this.env,
876
+ projectRid: this.rid,
877
+ blockId,
878
+ mode,
879
+ projectGeneration: () => (this.destroyed ? -1 : this.projectTree.changeGeneration),
880
+ });
881
+ this.blockStatusWatches.set(key, started);
882
+ // A failed start must not leave a rejected promise in the map for every later caller. Only
883
+ // this start's own entry is dropped: by the time a late rejection lands, the key may already
884
+ // hold a newer, live watch.
885
+ started.catch(() => {
886
+ if (this.blockStatusWatches.get(key) === started) this.blockStatusWatches.delete(key);
887
+ });
888
+ return (await started).summary;
889
+ }
890
+
891
+ /**
892
+ * Releases one hold taken by {@link watchBlockStatus}. The tree is terminated when the last
893
+ * holder lets go, so two callers watching one block do not cut each other off.
894
+ */
895
+ public async unwatchBlockStatus(
896
+ blockId: string,
897
+ mode: BlockActionContextMode = "prod",
898
+ ): Promise<void> {
899
+ const key = blockStatusKey(blockId, mode);
900
+ const pending = this.blockStatusWatches.get(key);
901
+ if (pending === undefined) return;
902
+
903
+ let watch: BlockStatusWatch;
904
+ try {
905
+ watch = await pending;
906
+ } catch {
907
+ // The start failed; its own catch handler drops the entry. Nothing to release, and a
908
+ // panel-close handler must not see that failure again.
909
+ return;
910
+ }
911
+
912
+ if (await watch.release()) {
913
+ if (this.blockStatusWatches.get(key) === pending) this.blockStatusWatches.delete(key);
914
+ }
915
+ }
916
+
917
+ private async terminateBlockStatusWatches(): Promise<void> {
918
+ const watches = [...this.blockStatusWatches.values()];
919
+ this.blockStatusWatches.clear();
920
+ await Promise.all(
921
+ watches.map(async (watch) => {
922
+ try {
923
+ await (await watch).terminate();
924
+ } catch (e: unknown) {
925
+ // A watch whose start rejected has nothing to terminate; anything else is logged.
926
+ this.env.logger.warn(new Error("block status watch termination failed", { cause: e }));
927
+ }
928
+ }),
929
+ );
930
+ }
931
+
838
932
  public getBlockState(blockId: string): Computable<BlockStateInternalV3> {
839
933
  return this.getBlockComputables(blockId).fullState;
840
934
  }
@@ -870,6 +964,9 @@ export class Project {
870
964
  );
871
965
  }
872
966
 
967
+ // terminating the status trees before the project tree: they are seeded from it
968
+ await this.terminateBlockStatusWatches();
969
+
873
970
  // terminating the synchronized project tree
874
971
  try {
875
972
  await this.projectTree.terminate();
@@ -1015,6 +1112,11 @@ export function isSnapshotFailsafeError(e: unknown): boolean {
1015
1112
  return false;
1016
1113
  }
1017
1114
 
1115
+ /** Key of a status watch in {@link Project.blockStatusWatches}. */
1116
+ function blockStatusKey(blockId: string, mode: BlockActionContextMode): string {
1117
+ return `${mode}:${blockId}`;
1118
+ }
1119
+
1018
1120
  export function projectTreePruning(logger: MiLogger): PruningFunction {
1019
1121
  return (r: ExtendedResourceData): FieldData[] => {
1020
1122
  if (r.fields.length > 1000)
@@ -1030,7 +1132,9 @@ export function projectTreePruning(logger: MiLogger): PruningFunction {
1030
1132
  case "BlockPackCustom":
1031
1133
  return r.fields.filter((f) => f.name !== "template");
1032
1134
  case "UserProject":
1033
- return r.fields.filter((f) => !f.name.startsWith("__serviceTemplate"));
1135
+ return r.fields.filter(
1136
+ (f) => !f.name.startsWith("__serviceTemplate") && !projectStatusFieldRegex.test(f.name),
1137
+ );
1034
1138
  case "Blob":
1035
1139
  return [];
1036
1140
  default:
@@ -1055,6 +1159,11 @@ export function projectTreeFieldFilter(): Filter {
1055
1159
  treeFilter.resourceTypeEq("UserProject"),
1056
1160
  treeFilter.fieldNameMatch("^__serviceTemplate"),
1057
1161
  ),
1162
+ // UserProject: drop the status-context fields, see ProjectStatusFieldPattern
1163
+ treeFilter.and(
1164
+ treeFilter.resourceTypeEq("UserProject"),
1165
+ treeFilter.fieldNameMatch(ProjectStatusFieldPattern),
1166
+ ),
1058
1167
  // Blob — pruned entirely
1059
1168
  treeFilter.resourceTypeEq("Blob"),
1060
1169
  ),
@@ -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,