@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
@@ -33,6 +33,27 @@ function createBlockActionContext(tx, baggage) {
33
33
  "run-id": (0, node_crypto.randomUUID)()
34
34
  }));
35
35
  }
36
+ /** The namespace the creator of a context reports under, as the backend reserves it. */
37
+ const ActionContextCreatorNamespace = "core";
38
+ /** The reason recorded when the user stops a run. */
39
+ const BlockRunCancelledReason = "cancelled";
40
+ /**
41
+ * Marks a block run's root action context as cancelled by the user.
42
+ *
43
+ * Stopping a block destroys its render, and a destroyed render reports nothing, so without this
44
+ * every node of a stopped run would read as live forever. The middle layer created the context, so
45
+ * it reports under the creator's namespace, with the context itself as the reporting resource and
46
+ * this machine's clock, the same key layout the backend's reporters use.
47
+ */
48
+ function recordBlockRunCancelled(tx, context) {
49
+ const reporter = (0, _milaboratories_pl_client.isResourceId)(context) ? String((0, _milaboratories_pl_client.parseSignedResourceId)(context).globalId) : "0";
50
+ const ns = (BigInt(Date.now()) * 1000000n).toString();
51
+ tx.setKValue(context, `transition/${ActionContextCreatorNamespace}/${reporter}/${ns}`, JSON.stringify({
52
+ state: "Terminated",
53
+ detail: "",
54
+ reason: BlockRunCancelledReason
55
+ }));
56
+ }
36
57
  /**
37
58
  * Creates the heavy block render, and with `baggage` its root action context in the same
38
59
  * transaction. Returns `actionContext`: the render is garbage collected after its outputs resolve,
@@ -60,14 +81,17 @@ function createBContextFromUpstreams(tx, upstreamCtxs) {
60
81
  tx.lock(ctx);
61
82
  return ctx;
62
83
  }
84
+ exports.ActionContextCreatorNamespace = ActionContextCreatorNamespace;
63
85
  exports.ActionContextLinkCapability = ActionContextLinkCapability;
64
86
  exports.ActionContextType = ActionContextType;
65
87
  exports.BContext = BContext;
66
88
  exports.BContextEnd = BContextEnd;
67
89
  exports.BContextMultiParentPrefix = BContextMultiParentPrefix;
90
+ exports.BlockRunCancelledReason = BlockRunCancelledReason;
68
91
  exports.HeavyBlockOutputNames = HeavyBlockOutputNames;
69
92
  exports.createBContextEnd = createBContextEnd;
70
93
  exports.createBContextFromUpstreams = createBContextFromUpstreams;
71
94
  exports.createRenderHeavyBlock = createRenderHeavyBlock;
95
+ exports.recordBlockRunCancelled = recordBlockRunCancelled;
72
96
 
73
97
  //# sourceMappingURL=render_block.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"render_block.cjs","names":["randomUUID","createRenderTemplateWithResource","field","Pl"],"sources":["../../../src/mutator/template/render_block.ts"],"sourcesContent":["import type { AnyRef, PlTransaction, ResourceRef, ResourceType } from \"@milaboratories/pl-client\";\nimport { field, Pl } from \"@milaboratories/pl-client\";\nimport { randomUUID } from \"node:crypto\";\nimport { createRenderTemplateWithResource } from \"./render_template\";\n\nexport const BContextEnd: ResourceType = { name: \"BContextEnd\", version: \"1\" };\nexport const BContext: ResourceType = { name: \"BContext\", version: \"1\" };\nexport const BContextId = \"id\";\nexport const BContextParent = \"parent\";\nexport const BContextMultiParentPrefix = \"parent/\";\n\n// TODO: add implementation for dual context heavy block.\n// export type BlockType =\n// | 'LightBlock'\n// | 'HeavyBlock'\n// | 'DualContextHeavyBlock';\n// moved to project model ==>>>\n\nexport type HeavyBlockInputs = {\n args: AnyRef;\n blockId: AnyRef;\n isProduction: AnyRef;\n context: AnyRef;\n};\n\nexport type HeavyBlockOutputs = {\n context: AnyRef;\n result: AnyRef;\n};\n\nexport const HeavyBlockOutputNames: (keyof HeavyBlockOutputs)[] = [\"context\", \"result\"];\n\n/** Baggage of the root action context of a block render. See the block action context spec. */\nexport type BlockActionContextBaggage = {\n /** Display name of the block. */\n name: string;\n /** JSON of the block pack spec. */\n blockPack: string;\n blockId: string;\n};\n\n/** Resource type of a block action context. See ActionContextV1Type in the backend. */\nexport const ActionContextType: ResourceType = { name: \"ActionContext\", version: \"1\" };\n\n/** The capability under which the backend accepts the \"actionContext\" link on a render. */\nexport const ActionContextLinkCapability = \"optionalFieldsInSchemas:v1\";\n\n/**\n * Creates the root action context of a block render: an ActionContext resource carrying the\n * baggage, with a new random `run-id`, since each render is one run of the block and the contexts\n * the templates create copy it. Undefined without baggage, or on a backend that cannot take the link.\n */\nfunction createBlockActionContext(\n tx: PlTransaction,\n baggage: BlockActionContextBaggage | undefined,\n): ResourceRef | undefined {\n if (baggage === undefined || !tx.hasCapability(ActionContextLinkCapability)) return undefined;\n return tx.createEphemeral(\n ActionContextType,\n JSON.stringify({\n name: baggage.name,\n \"block-pack\": baggage.blockPack,\n \"block-id\": baggage.blockId,\n \"run-id\": randomUUID(),\n }),\n );\n}\n\n/**\n * Creates the heavy block render, and with `baggage` its root action context in the same\n * transaction. Returns `actionContext`: the render is garbage collected after its outputs resolve,\n * so the caller must hold the context to keep it.\n */\nexport function createRenderHeavyBlock(\n tx: PlTransaction,\n tpl: AnyRef,\n inputs: HeavyBlockInputs,\n baggage?: BlockActionContextBaggage,\n): HeavyBlockOutputs & { actionContext?: ResourceRef } {\n const actionContext = createBlockActionContext(tx, baggage);\n const { outputs } = createRenderTemplateWithResource(\n tx,\n tpl,\n true,\n inputs,\n HeavyBlockOutputNames,\n actionContext,\n );\n return actionContext === undefined ? outputs : { ...outputs, actionContext };\n}\n\nexport type LightBlockInputs = {\n args: AnyRef;\n blockId: AnyRef;\n stagingContext: AnyRef;\n productionContext: AnyRef;\n};\n\nexport type LightBlockOutput = {\n result: AnyRef;\n};\n\nexport const LightBlockOutputNames: (keyof LightBlockOutput)[] = [\"result\"];\n\n/**\n * Creates the light block render, with the same action context as a heavy one, so template code\n * of either kind knows its block and run.\n */\nexport function createRenderLightBlock(\n tx: PlTransaction,\n tpl: ResourceRef,\n inputs: LightBlockInputs,\n baggage?: BlockActionContextBaggage,\n): LightBlockOutput & { actionContext?: ResourceRef } {\n const actionContext = createBlockActionContext(tx, baggage);\n const { outputs } = createRenderTemplateWithResource(\n tx,\n tpl,\n true,\n inputs,\n LightBlockOutputNames,\n actionContext,\n );\n return actionContext === undefined ? outputs : { ...outputs, actionContext };\n}\n\nexport function createBContextEnd(tx: PlTransaction): ResourceRef {\n const ctx = tx.createEphemeral(BContextEnd);\n tx.lock(ctx);\n return ctx;\n}\n\nexport function createBContextFromUpstreams(tx: PlTransaction, upstreamCtxs: AnyRef[]): AnyRef {\n if (upstreamCtxs.length === 0) return createBContextEnd(tx);\n\n if (upstreamCtxs.length === 1) return upstreamCtxs[0];\n\n const ctx = tx.createEphemeral(BContext);\n\n // setting id\n tx.createField(field(ctx, BContextId), \"Input\", Pl.createPlString(tx, randomUUID()));\n\n // setting parents\n for (let i = 0; i < upstreamCtxs.length; i++)\n tx.createField(field(ctx, `${BContextMultiParentPrefix}${i}`), \"Input\", upstreamCtxs[i]);\n\n tx.lock(ctx);\n\n return ctx;\n}\n"],"mappings":";;;;AAKA,MAAa,cAA4B;CAAE,MAAM;CAAe,SAAS;AAAI;AAC7E,MAAa,WAAyB;CAAE,MAAM;CAAY,SAAS;AAAI;AAGvE,MAAa,4BAA4B;AAqBzC,MAAa,wBAAqD,CAAC,WAAW,QAAQ;;AAYtF,MAAa,oBAAkC;CAAE,MAAM;CAAiB,SAAS;AAAI;;AAGrF,MAAa,8BAA8B;;;;;;AAO3C,SAAS,yBACP,IACA,SACyB;CACzB,IAAI,YAAY,KAAA,KAAa,CAAC,GAAG,cAAA,4BAAyC,GAAG,OAAO,KAAA;CACpF,OAAO,GAAG,gBACR,mBACA,KAAK,UAAU;EACb,MAAM,QAAQ;EACd,cAAc,QAAQ;EACtB,YAAY,QAAQ;EACpB,WAAA,GAAUA,YAAAA,WAAAA,CAAW;CACvB,CAAC,CACH;AACF;;;;;;AAOA,SAAgB,uBACd,IACA,KACA,QACA,SACqD;CACrD,MAAM,gBAAgB,yBAAyB,IAAI,OAAO;CAC1D,MAAM,EAAE,YAAYC,wBAAAA,iCAClB,IACA,KACA,MACA,QACA,uBACA,aACF;CACA,OAAO,kBAAkB,KAAA,IAAY,UAAU;EAAE,GAAG;EAAS;CAAc;AAC7E;AAqCA,SAAgB,kBAAkB,IAAgC;CAChE,MAAM,MAAM,GAAG,gBAAgB,WAAW;CAC1C,GAAG,KAAK,GAAG;CACX,OAAO;AACT;AAEA,SAAgB,4BAA4B,IAAmB,cAAgC;CAC7F,IAAI,aAAa,WAAW,GAAG,OAAO,kBAAkB,EAAE;CAE1D,IAAI,aAAa,WAAW,GAAG,OAAO,aAAa;CAEnD,MAAM,MAAM,GAAG,gBAAgB,QAAQ;CAGvC,GAAG,aAAA,GAAYC,0BAAAA,MAAAA,CAAM,KAAA,IAAe,GAAG,SAASC,0BAAAA,GAAG,eAAe,KAAA,GAAIH,YAAAA,WAAAA,CAAW,CAAC,CAAC;CAGnF,KAAK,IAAI,IAAI,GAAG,IAAI,aAAa,QAAQ,KACvC,GAAG,aAAA,GAAYE,0BAAAA,MAAAA,CAAM,KAAK,GAAG,4BAA4B,GAAG,GAAG,SAAS,aAAa,EAAE;CAEzF,GAAG,KAAK,GAAG;CAEX,OAAO;AACT"}
1
+ {"version":3,"file":"render_block.cjs","names":["randomUUID","isResourceId","parseSignedResourceId","createRenderTemplateWithResource","field","Pl"],"sources":["../../../src/mutator/template/render_block.ts"],"sourcesContent":["import type {\n AnyRef,\n AnyResourceRef,\n PlTransaction,\n ResourceRef,\n ResourceType,\n} from \"@milaboratories/pl-client\";\nimport { field, isResourceId, parseSignedResourceId, Pl } from \"@milaboratories/pl-client\";\nimport { randomUUID } from \"node:crypto\";\nimport { createRenderTemplateWithResource } from \"./render_template\";\n\nexport const BContextEnd: ResourceType = { name: \"BContextEnd\", version: \"1\" };\nexport const BContext: ResourceType = { name: \"BContext\", version: \"1\" };\nexport const BContextId = \"id\";\nexport const BContextParent = \"parent\";\nexport const BContextMultiParentPrefix = \"parent/\";\n\n// TODO: add implementation for dual context heavy block.\n// export type BlockType =\n// | 'LightBlock'\n// | 'HeavyBlock'\n// | 'DualContextHeavyBlock';\n// moved to project model ==>>>\n\nexport type HeavyBlockInputs = {\n args: AnyRef;\n blockId: AnyRef;\n isProduction: AnyRef;\n context: AnyRef;\n};\n\nexport type HeavyBlockOutputs = {\n context: AnyRef;\n result: AnyRef;\n};\n\nexport const HeavyBlockOutputNames: (keyof HeavyBlockOutputs)[] = [\"context\", \"result\"];\n\n/** Baggage of the root action context of a block render. See the block action context spec. */\nexport type BlockActionContextBaggage = {\n /** Display name of the block. */\n name: string;\n /** JSON of the block pack spec. */\n blockPack: string;\n blockId: string;\n};\n\n/** Resource type of a block action context. See ActionContextV1Type in the backend. */\nexport const ActionContextType: ResourceType = { name: \"ActionContext\", version: \"1\" };\n\n/** The capability under which the backend accepts the \"actionContext\" link on a render. */\nexport const ActionContextLinkCapability = \"optionalFieldsInSchemas:v1\";\n\n/**\n * Creates the root action context of a block render: an ActionContext resource carrying the\n * baggage, with a new random `run-id`, since each render is one run of the block and the contexts\n * the templates create copy it. Undefined without baggage, or on a backend that cannot take the link.\n */\nfunction createBlockActionContext(\n tx: PlTransaction,\n baggage: BlockActionContextBaggage | undefined,\n): ResourceRef | undefined {\n if (baggage === undefined || !tx.hasCapability(ActionContextLinkCapability)) return undefined;\n return tx.createEphemeral(\n ActionContextType,\n JSON.stringify({\n name: baggage.name,\n \"block-pack\": baggage.blockPack,\n \"block-id\": baggage.blockId,\n \"run-id\": randomUUID(),\n }),\n );\n}\n\n/** The namespace the creator of a context reports under, as the backend reserves it. */\nexport const ActionContextCreatorNamespace = \"core\";\n\n/** The reason recorded when the user stops a run. */\nexport const BlockRunCancelledReason = \"cancelled\";\n\n/**\n * Marks a block run's root action context as cancelled by the user.\n *\n * Stopping a block destroys its render, and a destroyed render reports nothing, so without this\n * every node of a stopped run would read as live forever. The middle layer created the context, so\n * it reports under the creator's namespace, with the context itself as the reporting resource and\n * this machine's clock, the same key layout the backend's reporters use.\n */\nexport function recordBlockRunCancelled(tx: PlTransaction, context: AnyResourceRef): void {\n const reporter = isResourceId(context) ? String(parseSignedResourceId(context).globalId) : \"0\";\n const ns = (BigInt(Date.now()) * 1_000_000n).toString();\n tx.setKValue(\n context,\n `transition/${ActionContextCreatorNamespace}/${reporter}/${ns}`,\n JSON.stringify({ state: \"Terminated\", detail: \"\", reason: BlockRunCancelledReason }),\n );\n}\n\n/**\n * Creates the heavy block render, and with `baggage` its root action context in the same\n * transaction. Returns `actionContext`: the render is garbage collected after its outputs resolve,\n * so the caller must hold the context to keep it.\n */\nexport function createRenderHeavyBlock(\n tx: PlTransaction,\n tpl: AnyRef,\n inputs: HeavyBlockInputs,\n baggage?: BlockActionContextBaggage,\n): HeavyBlockOutputs & { actionContext?: ResourceRef } {\n const actionContext = createBlockActionContext(tx, baggage);\n const { outputs } = createRenderTemplateWithResource(\n tx,\n tpl,\n true,\n inputs,\n HeavyBlockOutputNames,\n actionContext,\n );\n return actionContext === undefined ? outputs : { ...outputs, actionContext };\n}\n\nexport type LightBlockInputs = {\n args: AnyRef;\n blockId: AnyRef;\n stagingContext: AnyRef;\n productionContext: AnyRef;\n};\n\nexport type LightBlockOutput = {\n result: AnyRef;\n};\n\nexport const LightBlockOutputNames: (keyof LightBlockOutput)[] = [\"result\"];\n\n/**\n * Creates the light block render, with the same action context as a heavy one, so template code\n * of either kind knows its block and run.\n */\nexport function createRenderLightBlock(\n tx: PlTransaction,\n tpl: ResourceRef,\n inputs: LightBlockInputs,\n baggage?: BlockActionContextBaggage,\n): LightBlockOutput & { actionContext?: ResourceRef } {\n const actionContext = createBlockActionContext(tx, baggage);\n const { outputs } = createRenderTemplateWithResource(\n tx,\n tpl,\n true,\n inputs,\n LightBlockOutputNames,\n actionContext,\n );\n return actionContext === undefined ? outputs : { ...outputs, actionContext };\n}\n\nexport function createBContextEnd(tx: PlTransaction): ResourceRef {\n const ctx = tx.createEphemeral(BContextEnd);\n tx.lock(ctx);\n return ctx;\n}\n\nexport function createBContextFromUpstreams(tx: PlTransaction, upstreamCtxs: AnyRef[]): AnyRef {\n if (upstreamCtxs.length === 0) return createBContextEnd(tx);\n\n if (upstreamCtxs.length === 1) return upstreamCtxs[0];\n\n const ctx = tx.createEphemeral(BContext);\n\n // setting id\n tx.createField(field(ctx, BContextId), \"Input\", Pl.createPlString(tx, randomUUID()));\n\n // setting parents\n for (let i = 0; i < upstreamCtxs.length; i++)\n tx.createField(field(ctx, `${BContextMultiParentPrefix}${i}`), \"Input\", upstreamCtxs[i]);\n\n tx.lock(ctx);\n\n return ctx;\n}\n"],"mappings":";;;;AAWA,MAAa,cAA4B;CAAE,MAAM;CAAe,SAAS;AAAI;AAC7E,MAAa,WAAyB;CAAE,MAAM;CAAY,SAAS;AAAI;AAGvE,MAAa,4BAA4B;AAqBzC,MAAa,wBAAqD,CAAC,WAAW,QAAQ;;AAYtF,MAAa,oBAAkC;CAAE,MAAM;CAAiB,SAAS;AAAI;;AAGrF,MAAa,8BAA8B;;;;;;AAO3C,SAAS,yBACP,IACA,SACyB;CACzB,IAAI,YAAY,KAAA,KAAa,CAAC,GAAG,cAAA,4BAAyC,GAAG,OAAO,KAAA;CACpF,OAAO,GAAG,gBACR,mBACA,KAAK,UAAU;EACb,MAAM,QAAQ;EACd,cAAc,QAAQ;EACtB,YAAY,QAAQ;EACpB,WAAA,GAAUA,YAAAA,WAAAA,CAAW;CACvB,CAAC,CACH;AACF;;AAGA,MAAa,gCAAgC;;AAG7C,MAAa,0BAA0B;;;;;;;;;AAUvC,SAAgB,wBAAwB,IAAmB,SAA+B;CACxF,MAAM,YAAA,GAAWC,0BAAAA,aAAAA,CAAa,OAAO,IAAI,QAAA,GAAOC,0BAAAA,sBAAAA,CAAsB,OAAO,CAAC,CAAC,QAAQ,IAAI;CAC3F,MAAM,MAAM,OAAO,KAAK,IAAI,CAAC,IAAI,SAAA,CAAY,SAAS;CACtD,GAAG,UACD,SACA,cAAc,8BAA8B,GAAG,SAAS,GAAG,MAC3D,KAAK,UAAU;EAAE,OAAO;EAAc,QAAQ;EAAI,QAAQ;CAAwB,CAAC,CACrF;AACF;;;;;;AAOA,SAAgB,uBACd,IACA,KACA,QACA,SACqD;CACrD,MAAM,gBAAgB,yBAAyB,IAAI,OAAO;CAC1D,MAAM,EAAE,YAAYC,wBAAAA,iCAClB,IACA,KACA,MACA,QACA,uBACA,aACF;CACA,OAAO,kBAAkB,KAAA,IAAY,UAAU;EAAE,GAAG;EAAS;CAAc;AAC7E;AAqCA,SAAgB,kBAAkB,IAAgC;CAChE,MAAM,MAAM,GAAG,gBAAgB,WAAW;CAC1C,GAAG,KAAK,GAAG;CACX,OAAO;AACT;AAEA,SAAgB,4BAA4B,IAAmB,cAAgC;CAC7F,IAAI,aAAa,WAAW,GAAG,OAAO,kBAAkB,EAAE;CAE1D,IAAI,aAAa,WAAW,GAAG,OAAO,aAAa;CAEnD,MAAM,MAAM,GAAG,gBAAgB,QAAQ;CAGvC,GAAG,aAAA,GAAYC,0BAAAA,MAAAA,CAAM,KAAA,IAAe,GAAG,SAASC,0BAAAA,GAAG,eAAe,KAAA,GAAIL,YAAAA,WAAAA,CAAW,CAAC,CAAC;CAGnF,KAAK,IAAI,IAAI,GAAG,IAAI,aAAa,QAAQ,KACvC,GAAG,aAAA,GAAYI,0BAAAA,MAAAA,CAAM,KAAK,GAAG,4BAA4B,GAAG,GAAG,SAAS,aAAa,EAAE;CAEzF,GAAG,KAAK,GAAG;CAEX,OAAO;AACT"}
@@ -1,5 +1,5 @@
1
1
  import { createRenderTemplateWithResource } from "./render_template.js";
2
- import { Pl, field } from "@milaboratories/pl-client";
2
+ import { Pl, field, isResourceId, parseSignedResourceId } from "@milaboratories/pl-client";
3
3
  import { randomUUID } from "node:crypto";
4
4
  // src/mutator/template/render_block.ts
5
5
  const BContextEnd = {
@@ -33,6 +33,27 @@ function createBlockActionContext(tx, baggage) {
33
33
  "run-id": randomUUID()
34
34
  }));
35
35
  }
36
+ /** The namespace the creator of a context reports under, as the backend reserves it. */
37
+ const ActionContextCreatorNamespace = "core";
38
+ /** The reason recorded when the user stops a run. */
39
+ const BlockRunCancelledReason = "cancelled";
40
+ /**
41
+ * Marks a block run's root action context as cancelled by the user.
42
+ *
43
+ * Stopping a block destroys its render, and a destroyed render reports nothing, so without this
44
+ * every node of a stopped run would read as live forever. The middle layer created the context, so
45
+ * it reports under the creator's namespace, with the context itself as the reporting resource and
46
+ * this machine's clock, the same key layout the backend's reporters use.
47
+ */
48
+ function recordBlockRunCancelled(tx, context) {
49
+ const reporter = isResourceId(context) ? String(parseSignedResourceId(context).globalId) : "0";
50
+ const ns = (BigInt(Date.now()) * 1000000n).toString();
51
+ tx.setKValue(context, `transition/${ActionContextCreatorNamespace}/${reporter}/${ns}`, JSON.stringify({
52
+ state: "Terminated",
53
+ detail: "",
54
+ reason: BlockRunCancelledReason
55
+ }));
56
+ }
36
57
  /**
37
58
  * Creates the heavy block render, and with `baggage` its root action context in the same
38
59
  * transaction. Returns `actionContext`: the render is garbage collected after its outputs resolve,
@@ -60,6 +81,6 @@ function createBContextFromUpstreams(tx, upstreamCtxs) {
60
81
  tx.lock(ctx);
61
82
  return ctx;
62
83
  }
63
- export { ActionContextLinkCapability, ActionContextType, BContext, BContextEnd, BContextMultiParentPrefix, HeavyBlockOutputNames, createBContextEnd, createBContextFromUpstreams, createRenderHeavyBlock };
84
+ export { ActionContextCreatorNamespace, ActionContextLinkCapability, ActionContextType, BContext, BContextEnd, BContextMultiParentPrefix, BlockRunCancelledReason, HeavyBlockOutputNames, createBContextEnd, createBContextFromUpstreams, createRenderHeavyBlock, recordBlockRunCancelled };
64
85
 
65
86
  //# sourceMappingURL=render_block.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"render_block.js","names":[],"sources":["../../../src/mutator/template/render_block.ts"],"sourcesContent":["import type { AnyRef, PlTransaction, ResourceRef, ResourceType } from \"@milaboratories/pl-client\";\nimport { field, Pl } from \"@milaboratories/pl-client\";\nimport { randomUUID } from \"node:crypto\";\nimport { createRenderTemplateWithResource } from \"./render_template\";\n\nexport const BContextEnd: ResourceType = { name: \"BContextEnd\", version: \"1\" };\nexport const BContext: ResourceType = { name: \"BContext\", version: \"1\" };\nexport const BContextId = \"id\";\nexport const BContextParent = \"parent\";\nexport const BContextMultiParentPrefix = \"parent/\";\n\n// TODO: add implementation for dual context heavy block.\n// export type BlockType =\n// | 'LightBlock'\n// | 'HeavyBlock'\n// | 'DualContextHeavyBlock';\n// moved to project model ==>>>\n\nexport type HeavyBlockInputs = {\n args: AnyRef;\n blockId: AnyRef;\n isProduction: AnyRef;\n context: AnyRef;\n};\n\nexport type HeavyBlockOutputs = {\n context: AnyRef;\n result: AnyRef;\n};\n\nexport const HeavyBlockOutputNames: (keyof HeavyBlockOutputs)[] = [\"context\", \"result\"];\n\n/** Baggage of the root action context of a block render. See the block action context spec. */\nexport type BlockActionContextBaggage = {\n /** Display name of the block. */\n name: string;\n /** JSON of the block pack spec. */\n blockPack: string;\n blockId: string;\n};\n\n/** Resource type of a block action context. See ActionContextV1Type in the backend. */\nexport const ActionContextType: ResourceType = { name: \"ActionContext\", version: \"1\" };\n\n/** The capability under which the backend accepts the \"actionContext\" link on a render. */\nexport const ActionContextLinkCapability = \"optionalFieldsInSchemas:v1\";\n\n/**\n * Creates the root action context of a block render: an ActionContext resource carrying the\n * baggage, with a new random `run-id`, since each render is one run of the block and the contexts\n * the templates create copy it. Undefined without baggage, or on a backend that cannot take the link.\n */\nfunction createBlockActionContext(\n tx: PlTransaction,\n baggage: BlockActionContextBaggage | undefined,\n): ResourceRef | undefined {\n if (baggage === undefined || !tx.hasCapability(ActionContextLinkCapability)) return undefined;\n return tx.createEphemeral(\n ActionContextType,\n JSON.stringify({\n name: baggage.name,\n \"block-pack\": baggage.blockPack,\n \"block-id\": baggage.blockId,\n \"run-id\": randomUUID(),\n }),\n );\n}\n\n/**\n * Creates the heavy block render, and with `baggage` its root action context in the same\n * transaction. Returns `actionContext`: the render is garbage collected after its outputs resolve,\n * so the caller must hold the context to keep it.\n */\nexport function createRenderHeavyBlock(\n tx: PlTransaction,\n tpl: AnyRef,\n inputs: HeavyBlockInputs,\n baggage?: BlockActionContextBaggage,\n): HeavyBlockOutputs & { actionContext?: ResourceRef } {\n const actionContext = createBlockActionContext(tx, baggage);\n const { outputs } = createRenderTemplateWithResource(\n tx,\n tpl,\n true,\n inputs,\n HeavyBlockOutputNames,\n actionContext,\n );\n return actionContext === undefined ? outputs : { ...outputs, actionContext };\n}\n\nexport type LightBlockInputs = {\n args: AnyRef;\n blockId: AnyRef;\n stagingContext: AnyRef;\n productionContext: AnyRef;\n};\n\nexport type LightBlockOutput = {\n result: AnyRef;\n};\n\nexport const LightBlockOutputNames: (keyof LightBlockOutput)[] = [\"result\"];\n\n/**\n * Creates the light block render, with the same action context as a heavy one, so template code\n * of either kind knows its block and run.\n */\nexport function createRenderLightBlock(\n tx: PlTransaction,\n tpl: ResourceRef,\n inputs: LightBlockInputs,\n baggage?: BlockActionContextBaggage,\n): LightBlockOutput & { actionContext?: ResourceRef } {\n const actionContext = createBlockActionContext(tx, baggage);\n const { outputs } = createRenderTemplateWithResource(\n tx,\n tpl,\n true,\n inputs,\n LightBlockOutputNames,\n actionContext,\n );\n return actionContext === undefined ? outputs : { ...outputs, actionContext };\n}\n\nexport function createBContextEnd(tx: PlTransaction): ResourceRef {\n const ctx = tx.createEphemeral(BContextEnd);\n tx.lock(ctx);\n return ctx;\n}\n\nexport function createBContextFromUpstreams(tx: PlTransaction, upstreamCtxs: AnyRef[]): AnyRef {\n if (upstreamCtxs.length === 0) return createBContextEnd(tx);\n\n if (upstreamCtxs.length === 1) return upstreamCtxs[0];\n\n const ctx = tx.createEphemeral(BContext);\n\n // setting id\n tx.createField(field(ctx, BContextId), \"Input\", Pl.createPlString(tx, randomUUID()));\n\n // setting parents\n for (let i = 0; i < upstreamCtxs.length; i++)\n tx.createField(field(ctx, `${BContextMultiParentPrefix}${i}`), \"Input\", upstreamCtxs[i]);\n\n tx.lock(ctx);\n\n return ctx;\n}\n"],"mappings":";;;;AAKA,MAAa,cAA4B;CAAE,MAAM;CAAe,SAAS;AAAI;AAC7E,MAAa,WAAyB;CAAE,MAAM;CAAY,SAAS;AAAI;AAGvE,MAAa,4BAA4B;AAqBzC,MAAa,wBAAqD,CAAC,WAAW,QAAQ;;AAYtF,MAAa,oBAAkC;CAAE,MAAM;CAAiB,SAAS;AAAI;;AAGrF,MAAa,8BAA8B;;;;;;AAO3C,SAAS,yBACP,IACA,SACyB;CACzB,IAAI,YAAY,KAAA,KAAa,CAAC,GAAG,cAAA,4BAAyC,GAAG,OAAO,KAAA;CACpF,OAAO,GAAG,gBACR,mBACA,KAAK,UAAU;EACb,MAAM,QAAQ;EACd,cAAc,QAAQ;EACtB,YAAY,QAAQ;EACpB,UAAU,WAAW;CACvB,CAAC,CACH;AACF;;;;;;AAOA,SAAgB,uBACd,IACA,KACA,QACA,SACqD;CACrD,MAAM,gBAAgB,yBAAyB,IAAI,OAAO;CAC1D,MAAM,EAAE,YAAY,iCAClB,IACA,KACA,MACA,QACA,uBACA,aACF;CACA,OAAO,kBAAkB,KAAA,IAAY,UAAU;EAAE,GAAG;EAAS;CAAc;AAC7E;AAqCA,SAAgB,kBAAkB,IAAgC;CAChE,MAAM,MAAM,GAAG,gBAAgB,WAAW;CAC1C,GAAG,KAAK,GAAG;CACX,OAAO;AACT;AAEA,SAAgB,4BAA4B,IAAmB,cAAgC;CAC7F,IAAI,aAAa,WAAW,GAAG,OAAO,kBAAkB,EAAE;CAE1D,IAAI,aAAa,WAAW,GAAG,OAAO,aAAa;CAEnD,MAAM,MAAM,GAAG,gBAAgB,QAAQ;CAGvC,GAAG,YAAY,MAAM,KAAA,IAAe,GAAG,SAAS,GAAG,eAAe,IAAI,WAAW,CAAC,CAAC;CAGnF,KAAK,IAAI,IAAI,GAAG,IAAI,aAAa,QAAQ,KACvC,GAAG,YAAY,MAAM,KAAK,GAAG,4BAA4B,GAAG,GAAG,SAAS,aAAa,EAAE;CAEzF,GAAG,KAAK,GAAG;CAEX,OAAO;AACT"}
1
+ {"version":3,"file":"render_block.js","names":[],"sources":["../../../src/mutator/template/render_block.ts"],"sourcesContent":["import type {\n AnyRef,\n AnyResourceRef,\n PlTransaction,\n ResourceRef,\n ResourceType,\n} from \"@milaboratories/pl-client\";\nimport { field, isResourceId, parseSignedResourceId, Pl } from \"@milaboratories/pl-client\";\nimport { randomUUID } from \"node:crypto\";\nimport { createRenderTemplateWithResource } from \"./render_template\";\n\nexport const BContextEnd: ResourceType = { name: \"BContextEnd\", version: \"1\" };\nexport const BContext: ResourceType = { name: \"BContext\", version: \"1\" };\nexport const BContextId = \"id\";\nexport const BContextParent = \"parent\";\nexport const BContextMultiParentPrefix = \"parent/\";\n\n// TODO: add implementation for dual context heavy block.\n// export type BlockType =\n// | 'LightBlock'\n// | 'HeavyBlock'\n// | 'DualContextHeavyBlock';\n// moved to project model ==>>>\n\nexport type HeavyBlockInputs = {\n args: AnyRef;\n blockId: AnyRef;\n isProduction: AnyRef;\n context: AnyRef;\n};\n\nexport type HeavyBlockOutputs = {\n context: AnyRef;\n result: AnyRef;\n};\n\nexport const HeavyBlockOutputNames: (keyof HeavyBlockOutputs)[] = [\"context\", \"result\"];\n\n/** Baggage of the root action context of a block render. See the block action context spec. */\nexport type BlockActionContextBaggage = {\n /** Display name of the block. */\n name: string;\n /** JSON of the block pack spec. */\n blockPack: string;\n blockId: string;\n};\n\n/** Resource type of a block action context. See ActionContextV1Type in the backend. */\nexport const ActionContextType: ResourceType = { name: \"ActionContext\", version: \"1\" };\n\n/** The capability under which the backend accepts the \"actionContext\" link on a render. */\nexport const ActionContextLinkCapability = \"optionalFieldsInSchemas:v1\";\n\n/**\n * Creates the root action context of a block render: an ActionContext resource carrying the\n * baggage, with a new random `run-id`, since each render is one run of the block and the contexts\n * the templates create copy it. Undefined without baggage, or on a backend that cannot take the link.\n */\nfunction createBlockActionContext(\n tx: PlTransaction,\n baggage: BlockActionContextBaggage | undefined,\n): ResourceRef | undefined {\n if (baggage === undefined || !tx.hasCapability(ActionContextLinkCapability)) return undefined;\n return tx.createEphemeral(\n ActionContextType,\n JSON.stringify({\n name: baggage.name,\n \"block-pack\": baggage.blockPack,\n \"block-id\": baggage.blockId,\n \"run-id\": randomUUID(),\n }),\n );\n}\n\n/** The namespace the creator of a context reports under, as the backend reserves it. */\nexport const ActionContextCreatorNamespace = \"core\";\n\n/** The reason recorded when the user stops a run. */\nexport const BlockRunCancelledReason = \"cancelled\";\n\n/**\n * Marks a block run's root action context as cancelled by the user.\n *\n * Stopping a block destroys its render, and a destroyed render reports nothing, so without this\n * every node of a stopped run would read as live forever. The middle layer created the context, so\n * it reports under the creator's namespace, with the context itself as the reporting resource and\n * this machine's clock, the same key layout the backend's reporters use.\n */\nexport function recordBlockRunCancelled(tx: PlTransaction, context: AnyResourceRef): void {\n const reporter = isResourceId(context) ? String(parseSignedResourceId(context).globalId) : \"0\";\n const ns = (BigInt(Date.now()) * 1_000_000n).toString();\n tx.setKValue(\n context,\n `transition/${ActionContextCreatorNamespace}/${reporter}/${ns}`,\n JSON.stringify({ state: \"Terminated\", detail: \"\", reason: BlockRunCancelledReason }),\n );\n}\n\n/**\n * Creates the heavy block render, and with `baggage` its root action context in the same\n * transaction. Returns `actionContext`: the render is garbage collected after its outputs resolve,\n * so the caller must hold the context to keep it.\n */\nexport function createRenderHeavyBlock(\n tx: PlTransaction,\n tpl: AnyRef,\n inputs: HeavyBlockInputs,\n baggage?: BlockActionContextBaggage,\n): HeavyBlockOutputs & { actionContext?: ResourceRef } {\n const actionContext = createBlockActionContext(tx, baggage);\n const { outputs } = createRenderTemplateWithResource(\n tx,\n tpl,\n true,\n inputs,\n HeavyBlockOutputNames,\n actionContext,\n );\n return actionContext === undefined ? outputs : { ...outputs, actionContext };\n}\n\nexport type LightBlockInputs = {\n args: AnyRef;\n blockId: AnyRef;\n stagingContext: AnyRef;\n productionContext: AnyRef;\n};\n\nexport type LightBlockOutput = {\n result: AnyRef;\n};\n\nexport const LightBlockOutputNames: (keyof LightBlockOutput)[] = [\"result\"];\n\n/**\n * Creates the light block render, with the same action context as a heavy one, so template code\n * of either kind knows its block and run.\n */\nexport function createRenderLightBlock(\n tx: PlTransaction,\n tpl: ResourceRef,\n inputs: LightBlockInputs,\n baggage?: BlockActionContextBaggage,\n): LightBlockOutput & { actionContext?: ResourceRef } {\n const actionContext = createBlockActionContext(tx, baggage);\n const { outputs } = createRenderTemplateWithResource(\n tx,\n tpl,\n true,\n inputs,\n LightBlockOutputNames,\n actionContext,\n );\n return actionContext === undefined ? outputs : { ...outputs, actionContext };\n}\n\nexport function createBContextEnd(tx: PlTransaction): ResourceRef {\n const ctx = tx.createEphemeral(BContextEnd);\n tx.lock(ctx);\n return ctx;\n}\n\nexport function createBContextFromUpstreams(tx: PlTransaction, upstreamCtxs: AnyRef[]): AnyRef {\n if (upstreamCtxs.length === 0) return createBContextEnd(tx);\n\n if (upstreamCtxs.length === 1) return upstreamCtxs[0];\n\n const ctx = tx.createEphemeral(BContext);\n\n // setting id\n tx.createField(field(ctx, BContextId), \"Input\", Pl.createPlString(tx, randomUUID()));\n\n // setting parents\n for (let i = 0; i < upstreamCtxs.length; i++)\n tx.createField(field(ctx, `${BContextMultiParentPrefix}${i}`), \"Input\", upstreamCtxs[i]);\n\n tx.lock(ctx);\n\n return ctx;\n}\n"],"mappings":";;;;AAWA,MAAa,cAA4B;CAAE,MAAM;CAAe,SAAS;AAAI;AAC7E,MAAa,WAAyB;CAAE,MAAM;CAAY,SAAS;AAAI;AAGvE,MAAa,4BAA4B;AAqBzC,MAAa,wBAAqD,CAAC,WAAW,QAAQ;;AAYtF,MAAa,oBAAkC;CAAE,MAAM;CAAiB,SAAS;AAAI;;AAGrF,MAAa,8BAA8B;;;;;;AAO3C,SAAS,yBACP,IACA,SACyB;CACzB,IAAI,YAAY,KAAA,KAAa,CAAC,GAAG,cAAA,4BAAyC,GAAG,OAAO,KAAA;CACpF,OAAO,GAAG,gBACR,mBACA,KAAK,UAAU;EACb,MAAM,QAAQ;EACd,cAAc,QAAQ;EACtB,YAAY,QAAQ;EACpB,UAAU,WAAW;CACvB,CAAC,CACH;AACF;;AAGA,MAAa,gCAAgC;;AAG7C,MAAa,0BAA0B;;;;;;;;;AAUvC,SAAgB,wBAAwB,IAAmB,SAA+B;CACxF,MAAM,WAAW,aAAa,OAAO,IAAI,OAAO,sBAAsB,OAAO,CAAC,CAAC,QAAQ,IAAI;CAC3F,MAAM,MAAM,OAAO,KAAK,IAAI,CAAC,IAAI,SAAA,CAAY,SAAS;CACtD,GAAG,UACD,SACA,cAAc,8BAA8B,GAAG,SAAS,GAAG,MAC3D,KAAK,UAAU;EAAE,OAAO;EAAc,QAAQ;EAAI,QAAQ;CAAwB,CAAC,CACrF;AACF;;;;;;AAOA,SAAgB,uBACd,IACA,KACA,QACA,SACqD;CACrD,MAAM,gBAAgB,yBAAyB,IAAI,OAAO;CAC1D,MAAM,EAAE,YAAY,iCAClB,IACA,KACA,MACA,QACA,uBACA,aACF;CACA,OAAO,kBAAkB,KAAA,IAAY,UAAU;EAAE,GAAG;EAAS;CAAc;AAC7E;AAqCA,SAAgB,kBAAkB,IAAgC;CAChE,MAAM,MAAM,GAAG,gBAAgB,WAAW;CAC1C,GAAG,KAAK,GAAG;CACX,OAAO;AACT;AAEA,SAAgB,4BAA4B,IAAmB,cAAgC;CAC7F,IAAI,aAAa,WAAW,GAAG,OAAO,kBAAkB,EAAE;CAE1D,IAAI,aAAa,WAAW,GAAG,OAAO,aAAa;CAEnD,MAAM,MAAM,GAAG,gBAAgB,QAAQ;CAGvC,GAAG,YAAY,MAAM,KAAA,IAAe,GAAG,SAAS,GAAG,eAAe,IAAI,WAAW,CAAC,CAAC;CAGnF,KAAK,IAAI,IAAI,GAAG,IAAI,aAAa,QAAQ,KACvC,GAAG,YAAY,MAAM,KAAK,GAAG,4BAA4B,GAAG,GAAG,SAAS,aAAa,EAAE;CAEzF,GAAG,KAAK,GAAG;CAEX,OAAO;AACT"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@milaboratories/pl-middle-layer",
3
- "version": "2.1.2",
3
+ "version": "2.3.0",
4
4
  "description": "Pl Middle Layer",
5
5
  "keywords": [],
6
6
  "license": "UNLICENSED",
@@ -19,25 +19,25 @@
19
19
  }
20
20
  },
21
21
  "dependencies": {
22
- "@milaboratories/columns-collection-driver": "0.2.14",
22
+ "@milaboratories/columns-collection-driver": "0.2.15",
23
23
  "@milaboratories/computable": "2.9.10",
24
24
  "@milaboratories/helpers": "1.14.7",
25
- "@milaboratories/pf-driver": "1.9.14",
26
- "@milaboratories/pf-spec-driver": "1.5.14",
25
+ "@milaboratories/pf-driver": "1.9.16",
26
+ "@milaboratories/pf-spec-driver": "1.5.16",
27
27
  "@milaboratories/pframes-rs-node": "1.2.0",
28
- "@milaboratories/pl-client": "3.22.0",
29
- "@milaboratories/pl-crash-recorder": "0.3.10",
30
- "@milaboratories/pl-drivers": "2.0.0",
31
- "@milaboratories/pl-errors": "1.4.60",
28
+ "@milaboratories/pl-client": "3.22.1",
29
+ "@milaboratories/pl-crash-recorder": "0.3.11",
30
+ "@milaboratories/pl-drivers": "2.0.1",
31
+ "@milaboratories/pl-errors": "1.4.61",
32
32
  "@milaboratories/pl-http": "1.2.6",
33
- "@milaboratories/pl-model-backend": "1.4.45",
34
- "@milaboratories/pl-model-common": "1.55.1",
35
- "@milaboratories/pl-model-middle-layer": "1.36.0",
36
- "@milaboratories/pl-tree": "1.17.2",
33
+ "@milaboratories/pl-model-backend": "1.4.46",
34
+ "@milaboratories/pl-model-common": "1.55.2",
35
+ "@milaboratories/pl-model-middle-layer": "1.38.0",
36
+ "@milaboratories/pl-tree": "1.18.0",
37
37
  "@milaboratories/resolve-helper": "1.1.3",
38
38
  "@milaboratories/ts-helpers": "1.9.1",
39
- "@platforma-sdk/block-tools": "2.18.0",
40
- "@platforma-sdk/model": "1.88.10",
39
+ "@platforma-sdk/block-tools": "2.18.2",
40
+ "@platforma-sdk/model": "1.88.14",
41
41
  "@platforma-sdk/workflow-tengo": "6.22.1",
42
42
  "canonicalize": "~2.1.0",
43
43
  "denque": "^2.1.0",
@@ -0,0 +1,197 @@
1
+ /**
2
+ * How the block status fold scales with the size of a run, through the real read path: an in-memory
3
+ * pl-tree holding the action contexts, its accessors, and the computable over them. No backend.
4
+ *
5
+ * A run is a root with one branch per 1 000 jobs and the jobs under the branches. Each job carries
6
+ * the transitions a real one writes. A report is one new transition on one job, as a command
7
+ * reports its next state.
8
+ *
9
+ * Off by default; run with `BLOCK_STATUS_BENCH=1 npx vitest run src/middle_layer/block_status_bench`.
10
+ */
11
+
12
+ import { Computable } from "@milaboratories/computable";
13
+ import type { SignedResourceId } from "@milaboratories/pl-client";
14
+ import {
15
+ createSignedResourceId,
16
+ DefaultFinalResourceDataPredicate,
17
+ NullSignedResourceId,
18
+ } from "@milaboratories/pl-client";
19
+ import type { ExtendedResourceData, PlTreeEntry } from "@milaboratories/pl-tree";
20
+ import { PlTreeState } from "@milaboratories/pl-tree";
21
+ import type { BlockStatusSummary } from "@milaboratories/pl-model-middle-layer";
22
+ import { expect, test } from "vitest";
23
+ import { ActionContextType } from "../mutator/template/render_block";
24
+ import { entrySummary } from "./block_status_tree";
25
+
26
+ const JobsPerBranch = 1_000;
27
+ const Sizes = [1_000, 10_000, 100_000];
28
+ const Reports = 20;
29
+
30
+ /** The computable under test: the summary of the run rooted at `entry`. */
31
+ function summaryOf(entry: PlTreeEntry): Computable<BlockStatusSummary> {
32
+ return entrySummary(entry, true, (err) => console.error(err));
33
+ }
34
+
35
+ const t0 = 1_800_000_000_000_000_000n;
36
+
37
+ function transition(namespace: string, reporter: number, atNs: bigint, state: string) {
38
+ return {
39
+ key: `transition/${namespace}/${reporter}/${atNs}`,
40
+ value: Buffer.from(JSON.stringify({ state, detail: "", reason: "" })),
41
+ };
42
+ }
43
+
44
+ /** A job somewhere in its life: done, running, queued or copying its input. */
45
+ function jobKv(id: number): ExtendedResourceData["kv"] {
46
+ const at = t0 + BigInt(id) * 1_000_000n;
47
+ const kv = [transition("render", id, at, "Running")];
48
+ switch (id % 10) {
49
+ case 0:
50
+ kv.push(transition("workdir", id + 1, at + 1n, "PopulatingWorkdir"));
51
+ kv.push({
52
+ key: `reading/workdir/${id + 1}/progress`,
53
+ value: Buffer.from('{"done":3,"total":8}'),
54
+ });
55
+ return kv;
56
+ case 1:
57
+ kv.push(transition("exec", id + 2, at + 2n, "WaitingSubmissionGate"));
58
+ return kv;
59
+ case 2:
60
+ case 3:
61
+ kv.push(transition("exec", id + 2, at + 2n, "Running"));
62
+ return kv;
63
+ default:
64
+ kv.push(transition("exec", id + 2, at + 2n, "Running"));
65
+ kv.push(transition("exec", id + 2, at + 3n, "Completed"));
66
+ kv.push(transition("render", id, at + 4n, "Completed"));
67
+ return kv;
68
+ }
69
+ }
70
+
71
+ function contextData(
72
+ rid: SignedResourceId,
73
+ name: string,
74
+ children: SignedResourceId[],
75
+ kv: ExtendedResourceData["kv"],
76
+ ): ExtendedResourceData {
77
+ return {
78
+ id: rid,
79
+ originalResourceId: NullSignedResourceId,
80
+ canonicalId: new Uint8Array(0),
81
+ kind: "Structural",
82
+ type: ActionContextType,
83
+ data: Buffer.from(JSON.stringify({ name })),
84
+ error: NullSignedResourceId,
85
+ inputsLocked: false,
86
+ outputsLocked: false,
87
+ resourceReady: false,
88
+ final: false,
89
+ fields: children.map((child) => ({
90
+ name: `child/${String(child)}`,
91
+ type: "Dynamic",
92
+ value: child,
93
+ error: NullSignedResourceId,
94
+ status: "Resolved",
95
+ valueIsFinal: false,
96
+ })),
97
+ kv,
98
+ };
99
+ }
100
+
101
+ /** A run of `size` contexts, and the jobs a report can land on. */
102
+ function buildRun(size: number) {
103
+ let next = 1;
104
+ /** The number behind each id, which the reporters' keys use. */
105
+ const numbers = new Map<SignedResourceId, number>();
106
+ const rid = () => {
107
+ const n = next++;
108
+ const id = createSignedResourceId(BigInt(n));
109
+ numbers.set(id, n);
110
+ return id;
111
+ };
112
+ const num = (id: SignedResourceId) => numbers.get(id)!;
113
+ const root = rid();
114
+ const resources = new Map<SignedResourceId, ExtendedResourceData>();
115
+ const jobs: SignedResourceId[] = [];
116
+
117
+ const branches: SignedResourceId[] = [];
118
+ for (let made = 1; made < size;) {
119
+ const branch = rid();
120
+ branches.push(branch);
121
+ made++;
122
+ const children: SignedResourceId[] = [];
123
+ for (let j = 0; j < JobsPerBranch && made < size; j++, made++) {
124
+ const job = rid();
125
+ children.push(job);
126
+ jobs.push(job);
127
+ resources.set(job, contextData(job, `job ${j}`, [], jobKv(num(job))));
128
+ }
129
+ resources.set(
130
+ branch,
131
+ contextData(branch, `branch ${branches.length}`, children, [
132
+ transition("render", num(branch), t0, "Running"),
133
+ ]),
134
+ );
135
+ }
136
+ resources.set(
137
+ root,
138
+ contextData(root, "root", branches, [transition("render", num(root), t0, "Running")]),
139
+ );
140
+
141
+ const tree = new PlTreeState(root, DefaultFinalResourceDataPredicate);
142
+ tree.updateFromResourceData([...resources.values()]);
143
+ return { tree, resources, jobs, num };
144
+ }
145
+
146
+ async function timed<T>(fn: () => Promise<T>): Promise<{ ms: number; value: T }> {
147
+ const start = performance.now();
148
+ const value = await fn();
149
+ return { ms: performance.now() - start, value };
150
+ }
151
+
152
+ const fmt = (ms: number) => (ms < 10 ? ms.toFixed(2) : ms.toFixed(0));
153
+
154
+ test.skipIf(process.env.BLOCK_STATUS_BENCH === undefined)(
155
+ "block status fold: first read and one report, by run size",
156
+ { timeout: 600_000 },
157
+ async () => {
158
+ const rows: string[] = [];
159
+ for (const size of Sizes) {
160
+ const { tree, resources, jobs, num } = buildRun(size);
161
+ const summary = summaryOf(tree.entry());
162
+
163
+ const first = await timed(() => summary.getValue());
164
+ expect(first.value.totalContexts).toBe(size);
165
+
166
+ const perReport: number[] = [];
167
+ for (let i = 0; i < Reports; i++) {
168
+ const job = jobs[(i * 7919) % jobs.length];
169
+ const data = resources.get(job)!;
170
+ const updated = {
171
+ ...data,
172
+ kv: [
173
+ ...data.kv,
174
+ transition("exec", num(job) + 2, t0 + 10_000_000_000n + BigInt(i), "Completed"),
175
+ ],
176
+ };
177
+ resources.set(job, updated);
178
+ tree.updateFromResourceData([updated]);
179
+ perReport.push((await timed(() => summary.getValue())).ms);
180
+ }
181
+ perReport.sort((a, b) => a - b);
182
+ const median = perReport[Math.floor(perReport.length / 2)];
183
+ const worst = perReport[perReport.length - 1];
184
+ rows.push(
185
+ `| ${size.toLocaleString("en")} | ${fmt(first.ms)} | ${fmt(median)} | ${fmt(worst)} |`,
186
+ );
187
+ }
188
+
189
+ console.log(
190
+ [
191
+ "| Contexts | First read, ms | One report, median ms | One report, worst ms |",
192
+ "|---:|---:|---:|---:|",
193
+ ...rows,
194
+ ].join("\n"),
195
+ );
196
+ },
197
+ );