From 7590b7cec8d952f4865823966e0e9e03e44da350 Mon Sep 17 00:00:00 2001 From: lex00 <121451605+lex00@users.noreply.github.com> Date: Mon, 24 Aug 2026 15:09:06 -0600 Subject: [PATCH] feat(ops): effect() read-compare-run-write, gated effects on ApplyOp, WatchOp staleness (#1834) --- docs/src/content/docs/guide/ops-reference.mdx | 10 + .../content/docs/guide/watching-lifecycle.mdx | 2 + lexicons/temporal/src/composites/apply-op.ts | 15 +- .../src/composites/composites.test.ts | 92 ++++++ lexicons/temporal/src/composites/watch-op.ts | 27 +- lexicons/temporal/src/index.ts | 3 +- .../temporal/src/op/op-serializer.test.ts | 121 ++++++- lexicons/temporal/src/op/serializer.ts | 252 +++++++++----- packages/core/src/op/builders.ts | 60 +++- packages/core/src/op/effect-step.test.ts | 311 ++++++++++++++++++ packages/core/src/op/index.ts | 10 +- packages/core/src/op/local-executor.ts | 197 +++++++++-- packages/core/src/op/receipt-store.ts | 211 ++++++++++++ packages/core/src/op/types.ts | 34 +- 14 files changed, 1221 insertions(+), 124 deletions(-) create mode 100644 packages/core/src/op/effect-step.test.ts create mode 100644 packages/core/src/op/receipt-store.ts diff --git a/docs/src/content/docs/guide/ops-reference.mdx b/docs/src/content/docs/guide/ops-reference.mdx index f6cabbdff0..dc82133433 100644 --- a/docs/src/content/docs/guide/ops-reference.mdx +++ b/docs/src/content/docs/guide/ops-reference.mdx @@ -23,6 +23,7 @@ Pre-built step builders: | `lifecycleSnapshot(env, opts?)` | `chant lifecycle snapshot` | | `teardown(path, opts?)` | Build + destroy via the project's own `npm run teardown` script | | `envTeardown(env, opts?)` | [`chant lifecycle teardown --yes`](/chant/cli/lifecycle/#lifecycle-teardown-env) in-process: delete the environment's marker-owned resources. A prod-like name needs `confirmProd: true` in `opts`; precede with a `gate(...)` step for a human approval | +| `effect(receipt, steps, opts?)` | Read-compare-run-write over an effect receipt: read the live receipt, skip the wrapped steps when it matches the expectation ("effect already applied"), otherwise run them and write the receipt only on their success, last. `receipt` is the typed `EffectReceipt` declaration — there is no string form. See [Effects](#effects) | ## Retry profiles @@ -134,6 +135,15 @@ One caveat that is not a chant limitation: **floci-az drops resource tags**, so An ARM delete needs an `apiVersion`, and the resource-group listing does not return one per resource. `pruneArmOrphans` takes it from the template when the template still declares the type, then from the lexicon's pinned apiVersion registry (the same one the serializer stamps into the template), then from ARM's provider metadata (`GET /subscriptions/{sub}/providers/{namespace}?api-version=2021-04-01`, newest stable version, one call per namespace per run). Removing the last resource of a type from source therefore still prunes it ([#1472](https://github.com/INTENTIUS/chant/issues/1472)). Only a type none of the three sources know is reported as `not-prunable` with detail `no-api-version`. +## Effects + +The `effect(receipt, steps)` builder wraps its steps in read-compare-run-write over an effect receipt. On each run the workflow reads the receipt through the receipt store (provided by the receipt row's lexicon), compares it against the expectation, and skips the wrapped steps on a match. On a mismatch the steps run in authored order, and the receipt is written only when every one of them succeeded — the effect step is the sole writer of a receipt, and the write is always last. A failed step leaves the receipt untouched (stale), so the next run proposes the effect again. A `gate(...)` authored inside the wrapped steps pauses only when the effect will actually fire. + +| Config | What it does | +|--------|-------------| +| `effects: "gated"` on `ApplyOp` | Insert the durable approval gate before the apply (beside `delete: "gated"`, same signal shape) so the Plan phase's effect-will-fire rows are reviewed before any effect runs | +| `receipts: [...]` on `WatchOp` | Add a read-only `Receipts` phase reporting absent or differing receipts as findings (`StaleReceipts` search attribute) — nothing runs, nothing is written | + ## Codegen `chant build` emits three files per Op under `dist/ops//`: diff --git a/docs/src/content/docs/guide/watching-lifecycle.mdx b/docs/src/content/docs/guide/watching-lifecycle.mdx index d6e57af196..6225a10239 100644 --- a/docs/src/content/docs/guide/watching-lifecycle.mdx +++ b/docs/src/content/docs/guide/watching-lifecycle.mdx @@ -61,6 +61,8 @@ The two phases compile down to a workflow that, on each tick: Set `live: false` on the composite to use digest-only diff (faster, no cloud queries) for environments without `describeResources()` coverage. With `live: true` (the default) you get external-mutation detection. (See the [Runtime observation coverage matrix](/chant/lexicons/overview/#runtime-observation-coverage) for which lexicons report what.) +`receipts: [myReceipt, ...]` (typed `EffectReceipt` references) adds a read-only `Receipts` phase that reads each effect receipt through the receipt store and reports absent or differing receipts as findings, surfaced as a `StaleReceipts` search attribute — it never runs an effect and never writes a receipt. + ## The Temporal UI experience Each generated workflow opens with: diff --git a/lexicons/temporal/src/composites/apply-op.ts b/lexicons/temporal/src/composites/apply-op.ts index 3dcafacb1b..96e93fca73 100644 --- a/lexicons/temporal/src/composites/apply-op.ts +++ b/lexicons/temporal/src/composites/apply-op.ts @@ -54,6 +54,15 @@ export interface ApplyOpConfig { path?: string; /** Delete handling. Default: "never". */ delete?: DeleteMode; + /** + * Effect handling (#1834, epic #1703 decision 6). `"gated"` pauses the run + * at the approval gate whenever the plan proposes an effect, so the Plan + * phase's effect-will-fire rows (#1832) are reviewed before any effect + * runs — the same durable-signal shape as `delete: "gated"`. The generic + * apply itself never writes a receipt regardless (#1832); only an + * `effect()` step does, on success, last. + */ + effects?: "gated"; /** * Approval gate before the apply. Implied when `delete: "gated"`; may also be * set explicitly. Omit `signalName` to default to `approve-`. @@ -100,7 +109,7 @@ export function ApplyOp(config: ApplyOpConfig): ApplyOpResources { const target = config.target ?? "kubectl"; const output = config.output ?? defaultOutput(target); const deleteMode = config.delete ?? "never"; - const gated = deleteMode === "gated" || config.gate !== undefined; + const gated = deleteMode === "gated" || config.effects === "gated" || config.gate !== undefined; const phases = [ phase("Build", [activity("chantBuild", { path: config.path ?? "." })]), @@ -120,7 +129,9 @@ export function ApplyOp(config: ApplyOpConfig): ApplyOpResources { gate(config.gate?.signalName ?? `approve-${config.name}`, { ...(config.gate?.timeout ? { timeout: config.gate.timeout } : {}), description: - config.gate?.description ?? `Approve apply to ${config.env} (delete mode: ${deleteMode})`, + config.gate?.description ?? + `Approve apply to ${config.env} (delete mode: ${deleteMode}` + + `${config.effects === "gated" ? ", effects: gated" : ""})`, }), ]), ); diff --git a/lexicons/temporal/src/composites/composites.test.ts b/lexicons/temporal/src/composites/composites.test.ts index 63965b8a7c..2c9b8b3d6a 100644 --- a/lexicons/temporal/src/composites/composites.test.ts +++ b/lexicons/temporal/src/composites/composites.test.ts @@ -10,6 +10,7 @@ import { ReconcileOp } from "./reconcile-op"; import { ApplyOp } from "./apply-op"; import { serializeOps } from "../op/serializer"; import { DECLARABLE_MARKER } from "@intentius/chant/declarable"; +import { EffectReceipt, receiptExpectation } from "@intentius/chant/effect-receipt"; function getProps(entity: unknown): Record { return (entity as { props: Record }).props; @@ -436,3 +437,94 @@ describe("ApplyOp: compensation (#125, total-or-refused in #1449)", () => { } }); }); + +// ── ApplyOp: gated effects (#1834) ─────────────────────────────────── + +describe("ApplyOp: effects gated (#1834, #1703 decision 6)", () => { + test("effects: gated inserts the Approve gate phase before Apply, like delete: gated", () => { + const { op } = ApplyOp({ name: "p", env: "prod", effects: "gated" }); + const phases = getProps(op).phases as Array>; + expect(phases.map((p) => p.name)).toEqual(["Build", "Plan", "Approve", "Apply"]); + const gateStep = (phases[2].steps as Array>)[0]; + expect(gateStep.kind).toBe("gate"); + expect(gateStep.signalName).toBe("approve-p"); + expect(gateStep.description).toBe("Approve apply to prod (delete mode: never, effects: gated)"); + }); + + test("effects: gated does not change the delete mode riding into nativeApply", () => { + const { op } = ApplyOp({ name: "p", env: "prod", effects: "gated" }); + const phases = getProps(op).phases as Array>; + const applyStep = (phases.find((p) => p.name === "Apply")!.steps as Array>)[0]; + expect((applyStep.args as Record).deleteMode).toBe("never"); + }); + + test("effects: gated composes with delete: gated in one Approve gate", () => { + const { op } = ApplyOp({ name: "p", env: "prod", delete: "gated", effects: "gated" }); + const phases = getProps(op).phases as Array>; + expect(phases.map((p) => p.name)).toEqual(["Build", "Plan", "Approve", "Apply"]); + const gateStep = (phases[2].steps as Array>)[0]; + expect(gateStep.description).toBe("Approve apply to prod (delete mode: gated, effects: gated)"); + }); + + test("gated effects serialize to a durable condition wait before the apply", () => { + const { op } = ApplyOp({ name: "prod-apply", env: "prod", effects: "gated" }); + const ops = new Map([["prod-apply", op]]) as unknown as Parameters[0]; + const wf = serializeOps(ops)["ops/prod-apply/workflow.ts"]; + const gateIdx = wf.indexOf("await condition(() => resumeApproveProdApplyCleared"); + const applyIdx = wf.indexOf("await nativeApply("); + expect(gateIdx).toBeGreaterThan(-1); + expect(applyIdx).toBeGreaterThan(gateIdx); + }); +}); + +// ── WatchOp: receipt staleness (#1834) ─────────────────────────────── + +describe("WatchOp: receipt staleness (#1834)", () => { + const seeded = EffectReceipt("seeded", { + effect: "db-seed", + flavor: "hash", + inputs: { file: "seed.sql" }, + }); + + test("without receipts the op is unchanged (no Receipts phase)", () => { + const { op } = WatchOp({ name: "p", env: "prod", schedule: "* * * * *" }); + const phases = getProps(op).phases as Array>; + expect(phases.map((p) => p.name)).toEqual(["Snapshot", "Diff"]); + }); + + test("receipts add a read-only Receipts phase carrying identity + expectation data", () => { + const { op } = WatchOp({ name: "p", env: "prod", schedule: "* * * * *", receipts: [seeded] }); + const phases = getProps(op).phases as Array>; + expect(phases.map((p) => p.name)).toEqual(["Snapshot", "Diff", "Receipts"]); + const step = (phases[2].steps as Array>)[0]; + expect(step.fn).toBe("receiptStaleness"); + expect(step.args).toEqual({ + receipts: [ + { + receipt: { name: "seeded", effect: "db-seed", flavor: "hash", inputs: { file: "seed.sql" } }, + expectation: receiptExpectation(seeded), + }, + ], + }); + // Staleness surfaces as a workflow search attribute, like Drift. + expect(step.outcomeAttribute).toEqual({ name: "StaleReceipts", from: "stale" }); + }); + + test("the Receipts phase runs nothing: its only step is the staleness read", () => { + const { op } = WatchOp({ name: "p", env: "prod", schedule: "* * * * *", receipts: [seeded] }); + const phases = getProps(op).phases as Array>; + const steps = phases[2].steps as Array>; + expect(steps).toHaveLength(1); + expect(steps.map((s) => s.fn)).toEqual(["receiptStaleness"]); + }); + + test("serializes into a staleness read with a StaleReceipts upsert and no receiptWrite", () => { + const { op } = WatchOp({ name: "prod-watch", env: "prod", schedule: "* * * * *", receipts: [seeded] }); + const ops = new Map([["prod-watch", op]]) as unknown as Parameters[0]; + const wf = serializeOps(ops)["ops/prod-watch/workflow.ts"]; + expect(wf).toContain('upsertSearchAttributes({ Phase: ["Receipts"] });'); + expect(wf).toContain("await receiptStaleness("); + expect(wf).toContain('upsertSearchAttributes({ "StaleReceipts": [String(__r1?.stale)] });'); + expect(wf).not.toContain("receiptWrite"); + }); +}); diff --git a/lexicons/temporal/src/composites/watch-op.ts b/lexicons/temporal/src/composites/watch-op.ts index 21f5f9e2ca..7c19d296a2 100644 --- a/lexicons/temporal/src/composites/watch-op.ts +++ b/lexicons/temporal/src/composites/watch-op.ts @@ -20,7 +20,8 @@ * @see #31 — Continuous observation (the issue this composite addresses) */ -import { Op, phase, activity, OpResource } from "@intentius/chant/op"; +import { Op, phase, activity, OpResource, receiptCheckInput } from "@intentius/chant/op"; +import type { EffectReceiptDeclaration } from "@intentius/chant/effect-receipt"; import { TemporalSchedule } from "../resources"; function kebabToCamel(s: string): string { @@ -51,6 +52,15 @@ export interface WatchOpConfig { * @default true */ live?: boolean; + /** + * Effect receipts to check for staleness between change windows (#1834, + * epic #1703). Typed references only — import each EffectReceipt const. + * Read-only: the watch reads each receipt through the receipt store + * (provided by the receipt row's lexicon, #1835) and reports absent or + * differing values as findings. It never runs an effect and never writes + * a receipt — the `effect()` step is the sole writer. + */ + receipts?: EffectReceiptDeclaration[]; } export interface WatchOpResources { @@ -85,6 +95,21 @@ export function WatchOp(config: WatchOpConfig): WatchOpResources { outcomeAttribute: { name: "Drift", from: "drifted" }, }, ]), + // Receipt staleness (#1834): read-only over the receipt store — absent + // or differing receipts surface as findings (and a StaleReceipts search + // attribute); nothing runs and nothing is written. + ...(config.receipts && config.receipts.length > 0 + ? [ + phase("Receipts", [ + { + kind: "activity" as const, + fn: "receiptStaleness", + args: { receipts: config.receipts.map(receiptCheckInput) }, + outcomeAttribute: { name: "StaleReceipts", from: "stale" }, + }, + ]), + ] + : []), ], }); diff --git a/lexicons/temporal/src/index.ts b/lexicons/temporal/src/index.ts index b1c226b287..d34d66aa14 100644 --- a/lexicons/temporal/src/index.ts +++ b/lexicons/temporal/src/index.ts @@ -58,6 +58,7 @@ export { phase, activity, gate, + effect, build, kubectlApply, helmInstall, @@ -88,4 +89,4 @@ export { gcpDelete, policyGate, } from "@intentius/chant/op"; -export type { OpConfig, PhaseDefinition, StepDefinition, ActivityStep, GateStep } from "@intentius/chant/op"; +export type { OpConfig, PhaseDefinition, StepDefinition, ActivityStep, GateStep, EffectStep } from "@intentius/chant/op"; diff --git a/lexicons/temporal/src/op/op-serializer.test.ts b/lexicons/temporal/src/op/op-serializer.test.ts index 16189445ec..b28ecba72f 100644 --- a/lexicons/temporal/src/op/op-serializer.test.ts +++ b/lexicons/temporal/src/op/op-serializer.test.ts @@ -6,8 +6,9 @@ import { describe, expect, it } from "vitest"; import { serializeOps } from "./serializer"; import { DECLARABLE_MARKER, type Declarable } from "@intentius/chant/declarable"; -import { phase, gate, envTeardown } from "@intentius/chant/op"; +import { phase, gate, effect, envTeardown, shell } from "@intentius/chant/op"; import type { OpConfig } from "@intentius/chant/op"; +import { EffectReceipt, receiptExpectation } from "@intentius/chant/effect-receipt"; // ── Helpers ─────────────────────────────────────────────────────────────────── @@ -704,4 +705,122 @@ describe("serializeOps()", () => { expect(wf).toContain('upsertSearchAttributes({ "BetaOk": [String(__r1?.ok)] });'); }); }); + + describe("effect steps (#1834)", () => { + const seeded = EffectReceipt("seeded", { + effect: "db-seed", + flavor: "hash", + inputs: { file: "seed.sql" }, + }); + + const seedOps = () => + new Map([ + makeOp({ + name: "seed", + overview: "o", + phases: [phase("Seed", [effect(seeded, [shell("npm run db:seed")])])], + }), + ]); + + it("emits read-compare-run-write with the receipt identity and expectation as data", () => { + const wf = serializeOps(seedOps())["ops/seed/workflow.ts"]; + const readArgs = JSON.stringify({ + receipt: { name: "seeded", effect: "db-seed", flavor: "hash", inputs: { file: "seed.sql" } }, + expectation: receiptExpectation(seeded), + }); + expect(wf).toContain(`const __eff0 = await receiptRead(${readArgs});`); + expect(wf).toContain("if (__eff0.current === __eff0.expectation) {"); + expect(wf).toContain('log.info("effect already applied: seeded");'); + expect(wf).toContain("import { proxyActivities, condition, defineSignal, setHandler, upsertSearchAttributes, log } from '@temporalio/workflow';"); + }); + + it("nests the wrapped steps inside the mismatch branch and writes the receipt last", () => { + const wf = serializeOps(seedOps())["ops/seed/workflow.ts"]; + const read = wf.indexOf("const __eff0 = await receiptRead("); + const elseBranch = wf.indexOf("} else {"); + const nested = wf.indexOf('await shellCmd({"cmd":"npm run db:seed"});'); + const write = wf.indexOf("await receiptWrite({ receipt: "); + const close = wf.indexOf("\n }", write); + expect(read).toBeGreaterThan(-1); + expect(elseBranch).toBeGreaterThan(read); + expect(nested).toBeGreaterThan(elseBranch); + expect(write).toBeGreaterThan(nested); + expect(close).toBeGreaterThan(write); + // The write carries the receipt as data and the run-resolved expectation. + expect(wf).toContain("expectation: __eff0.expectation });"); + // Sole writer: exactly one write emitted. + expect(wf.match(/await receiptWrite\(/g)).toHaveLength(1); + }); + + it("binds receiptRead/receiptWrite once, at the fastIdempotent profile (#1698)", () => { + const wf = serializeOps(seedOps())["ops/seed/workflow.ts"]; + expect(wf).toMatch( + /const \{ receiptRead, shellCmd, receiptWrite \} = proxyActivities\(\s*TEMPORAL_ACTIVITY_PROFILES\.fastIdempotent,/, + ); + }); + + it("keeps authored order around a phase-level gate (gate first, effect after) (#1698)", () => { + const ops = new Map([ + makeOp({ + name: "gated-seed", + overview: "o", + phases: [ + phase("Seed", [ + gate("approve-seed"), + effect(seeded, [shell("npm run db:seed")]), + ]), + ], + }), + ]); + const wf = serializeOps(ops)["ops/gated-seed/workflow.ts"]; + const gateIdx = wf.indexOf("await condition(() => resumeApproveSeedCleared"); + const readIdx = wf.indexOf("await receiptRead("); + expect(gateIdx).toBeGreaterThan(-1); + expect(readIdx).toBeGreaterThan(gateIdx); + }); + + it("a gate nested inside the effect pauses only on the effect-will-fire path", () => { + const ops = new Map([ + makeOp({ + name: "inner-gate", + overview: "o", + phases: [ + phase("Seed", [ + effect(seeded, [gate("approve-fire"), shell("npm run db:seed")]), + ]), + ], + }), + ]); + const wf = serializeOps(ops)["ops/inner-gate/workflow.ts"]; + expect(wf).toContain('const resumeApproveFire = defineSignal<[{ approver?: string }?]>("approve-fire");'); + const elseBranch = wf.indexOf("} else {"); + const gateIdx = wf.indexOf("await condition(() => resumeApproveFireCleared"); + const nested = wf.indexOf('await shellCmd({"cmd":"npm run db:seed"});'); + expect(gateIdx).toBeGreaterThan(elseBranch); + expect(nested).toBeGreaterThan(gateIdx); + }); + + it("refuses an effect step in a parallel phase", () => { + const ops = new Map([ + makeOp({ + name: "par-effect", + overview: "o", + phases: [phase("P", [effect(seeded, [shell("x")])], { parallel: true })], + }), + ]); + expect(() => serializeOps(ops)).toThrow(/parallel phase/); + }); + + it("ops without effect steps do not import log (unchanged emission)", () => { + const ops = new Map([ + makeOp({ + name: "plain", + overview: "o", + phases: [phase("P", [shell("x")])], + }), + ]); + const wf = serializeOps(ops)["ops/plain/workflow.ts"]; + expect(wf).toContain("import { proxyActivities, condition, defineSignal, setHandler, upsertSearchAttributes } from '@temporalio/workflow';"); + }); + }); }); diff --git a/lexicons/temporal/src/op/serializer.ts b/lexicons/temporal/src/op/serializer.ts index 40cd187166..4aca8d25ed 100644 --- a/lexicons/temporal/src/op/serializer.ts +++ b/lexicons/temporal/src/op/serializer.ts @@ -10,7 +10,7 @@ import type { Declarable } from "@intentius/chant/declarable"; import { isResourceDeclarable } from "@intentius/chant/declarable"; -import type { OpConfig, PhaseDefinition, StepDefinition, ActivityStep, GateStep } from "@intentius/chant/op"; +import type { OpConfig, PhaseDefinition, StepDefinition, ActivityStep, GateStep, EffectStep } from "@intentius/chant/op"; import { kebabToCamel, signalVarName, generateWorkerBootstrap } from "../codegen-shared"; // ── Name helpers ────────────────────────────────────────────────────────────── @@ -29,14 +29,42 @@ function isGateStep(s: StepDefinition): s is GateStep { return s.kind === "gate"; } +function isEffectStep(s: StepDefinition): s is EffectStep { + return s.kind === "effect"; +} + function effectiveProfile(step: ActivityStep): string { return step.profile ?? "fastIdempotent"; } // ── Workflow code generation ────────────────────────────────────────────────── +// The receipt-store activities an effect step's read-compare-run-write calls +// (#1834). Fixed steps so `bindActivities` gives them one proxy binding at the +// `fastIdempotent` profile; the implementations come from the receipt row's +// lexicon (#1835, aws) via the activity registry. +const RECEIPT_READ_STEP: ActivityStep = { kind: "activity", fn: "receiptRead", profile: "fastIdempotent" }; +const RECEIPT_WRITE_STEP: ActivityStep = { kind: "activity", fn: "receiptWrite", profile: "fastIdempotent" }; + function collectActivitySteps(phases: PhaseDefinition[]): ActivityStep[] { - return phases.flatMap((p) => p.steps.filter(isActivityStep)); + return phases.flatMap((p) => + p.steps.flatMap((s) => + isActivityStep(s) + ? [s] + : isEffectStep(s) + ? [RECEIPT_READ_STEP, ...s.steps.filter(isActivityStep), RECEIPT_WRITE_STEP] + : [], + ), + ); +} + +/** Every gate in a phase, including gates nested inside effect steps. */ +function collectGateSteps(phases: PhaseDefinition[]): GateStep[] { + return phases.flatMap((p) => + p.steps.flatMap((s) => + isGateStep(s) ? [s] : isEffectStep(s) ? s.steps.filter(isGateStep) : [], + ), + ); } /** @@ -84,16 +112,20 @@ function generateWorkflow(config: OpConfig): string { const callee = bindings.ident; const allGateSteps = [ - ...config.phases.flatMap((p) => p.steps.filter(isGateStep)), - ...(config.onFailure ?? []).flatMap((p) => p.steps.filter(isGateStep)), + ...collectGateSteps(config.phases), + ...collectGateSteps(config.onFailure ?? []), ]; + const hasEffects = [...config.phases, ...(config.onFailure ?? [])].some((p) => + p.steps.some(isEffectStep), + ); + const fnName = workflowFnName(config.name); const lines: string[] = [ "// Generated by chant — do not edit directly.", `// Source: ${config.name}.op.ts`, - "import { proxyActivities, condition, defineSignal, setHandler, upsertSearchAttributes } from '@temporalio/workflow';", + `import { proxyActivities, condition, defineSignal, setHandler, upsertSearchAttributes${hasEffects ? ", log" : ""} } from '@temporalio/workflow';`, // Import profiles from the config leaf, not the package root: the root pulls // in the plugin/serializer (node:fs/path), which Temporal's workflow sandbox // forbids and the worker's bundler rejects. config.ts is import-free. @@ -170,97 +202,137 @@ function generateWorkflow(config: OpConfig): string { return `${indent}upsertSearchAttributes({ ${JSON.stringify(name)}: [${stringifyFromPath(varName, from)}] });`; }; + // Counter for effect-step capture variables (workflow-scoped). + let effectCounter = 0; + const nextEffectVar = (): string => `__eff${effectCounter++}`; + + const argsOf = (step: ActivityStep): string => + step.args && Object.keys(step.args).length > 0 ? JSON.stringify(step.args) : "{}"; + + // A run of consecutive activity steps. In a sequential context each is + // awaited in turn; in a parallel phase the run is a single Promise.all. + const emitActivityRun = (run: ActivityStep[], out: string[], indent: string, parallel: boolean) => { + if (parallel && run.length > 1) { + // Capture results into an array if any step has an outcome attribute, + // otherwise just await Promise.all without the destructure. + const anyOutcome = run.some((s) => s.outcomeAttribute); + if (anyOutcome) { + const vars = run.map(() => nextResultVar()); + out.push(`${indent}const [${vars.join(", ")}] = await Promise.all([`); + for (const step of run) { + out.push(`${indent} ${callee(step)}(${argsOf(step)}),`); + } + out.push(`${indent}]);`); + for (let i = 0; i < run.length; i++) { + const upsert = emitOutcomeUpsert(run[i], vars[i], indent); + if (upsert) out.push(upsert); + } + } else { + out.push(`${indent}await Promise.all([`); + for (const step of run) { + out.push(`${indent} ${callee(step)}(${argsOf(step)}),`); + } + out.push(`${indent}]);`); + } + return; + } + for (const step of run) { + if (step.outcomeAttribute) { + const v = nextResultVar(); + out.push(`${indent}const ${v} = await ${callee(step)}(${argsOf(step)});`); + const upsert = emitOutcomeUpsert(step, v, indent); + if (upsert) out.push(upsert); + } else { + out.push(`${indent}await ${callee(step)}(${argsOf(step)});`); + } + } + }; + + const emitGate = (gateStep: GateStep, out: string[], indent: string) => { + const varName = signalVarName(gateStep.signalName); + const timeout = gateStep.timeout ?? "48h"; + if (gateStep.description) { + out.push(`${indent}// Gate: ${gateStep.signalName} — ${gateStep.description}`); + } else { + out.push(`${indent}// Gate: ${gateStep.signalName}`); + } + out.push(`${indent}let ${varName}Cleared = false;`); + // Capture the approver identity from the signal payload. It rides in + // the signal event, so Temporal persists it in the workflow history + // even though the workflow itself only needs the boolean to proceed. + out.push(`${indent}let ${varName}Approver: string | undefined;`); + out.push(`${indent}setHandler(${varName}, (arg) => { ${varName}Approver = arg?.approver; ${varName}Cleared = true; });`); + out.push(`${indent}await condition(() => ${varName}Cleared, ${JSON.stringify(timeout)});`); + // Surface the approver in a search attribute when the caller opted a + // stack into one (config.searchAttributes contains "Approver"): only + // then is the attribute guaranteed registered, so an unconditional + // upsert can never break a gate on a cluster that never declared it. + if (config.searchAttributes && "Approver" in config.searchAttributes) { + out.push(`${indent}upsertSearchAttributes({ Approver: [${varName}Approver ?? "unknown"] });`); + } else { + out.push(`${indent}void ${varName}Approver;`); + } + }; + + // Read-compare-run-write over an effect receipt (#1834). Receipt identity + // and (when static) expectation ride as data; the nested steps render inside + // the mismatch branch, and the receipt write is emitted last — the effect + // step is the sole writer, on success (#1703 decision 3). A nested-step + // failure throws out of the workflow before the write, leaving the receipt + // stale so the next run re-proposes the effect. + const emitEffect = (step: EffectStep, out: string[], indent: string) => { + const v = nextEffectVar(); + out.push(`${indent}// Effect: ${step.receipt.name} (${step.receipt.effect}) — read-compare-run-write (#1834)`); + if (step.description) out.push(`${indent}// ${step.description}`); + const readArgs = JSON.stringify({ + receipt: step.receipt, + ...(step.expectation !== undefined ? { expectation: step.expectation } : {}), + }); + out.push(`${indent}const ${v} = await ${callee(RECEIPT_READ_STEP)}(${readArgs});`); + out.push(`${indent}if (${v}.current === ${v}.expectation) {`); + out.push(`${indent} log.info(${JSON.stringify(`effect already applied: ${step.receipt.name}`)});`); + out.push(`${indent}} else {`); + renderSteps(step.steps, out, `${indent} `, false); + out.push(`${indent} // Sole writer of the receipt — after every nested step succeeded, last (#1703).`); + out.push(`${indent} await ${callee(RECEIPT_WRITE_STEP)}({ receipt: ${JSON.stringify(step.receipt)}, expectation: ${v}.expectation });`); + out.push(`${indent}}`); + }; + + // Walk the steps in authored order. A gate or effect step splits the + // surrounding activities into separate runs, so [gate, activity] waits for + // the gate before the activity runs (and [activity, gate] the other way + // round) — the serializer never reorders what the author wrote (#1698). + const renderSteps = (steps: StepDefinition[], out: string[], indent: string, parallel: boolean) => { + let run: ActivityStep[] = []; + const flush = () => { + emitActivityRun(run, out, indent, parallel); + run = []; + }; + for (const step of steps) { + if (isActivityStep(step)) { + run.push(step); + continue; + } + flush(); + if (isGateStep(step)) emitGate(step, out, indent); + else if (isEffectStep(step)) emitEffect(step, out, indent); + } + flush(); + }; + const renderPhases = (phases: PhaseDefinition[]) => { for (const phase of phases) { + if (phase.parallel && phase.steps.some(isEffectStep)) { + throw new Error( + `Op "${config.name}", phase "${phase.name}": an effect step cannot run in a ` + + `parallel phase — read-compare-run-write is ordered`, + ); + } const phaseLines: string[] = []; phaseLines.push(` // Phase: ${phase.name}`); phaseLines.push(` upsertSearchAttributes({ Phase: ${JSON.stringify([phase.name])} });`); - const argsOf = (step: ActivityStep): string => - step.args && Object.keys(step.args).length > 0 ? JSON.stringify(step.args) : "{}"; - - // A run of consecutive activity steps. In a sequential phase each is - // awaited in turn; in a parallel phase the run is a single Promise.all. - const emitActivityRun = (run: ActivityStep[]) => { - if (phase.parallel && run.length > 1) { - // Capture results into an array if any step has an outcome attribute, - // otherwise just await Promise.all without the destructure. - const anyOutcome = run.some((s) => s.outcomeAttribute); - if (anyOutcome) { - const vars = run.map(() => nextResultVar()); - phaseLines.push(` const [${vars.join(", ")}] = await Promise.all([`); - for (const step of run) { - phaseLines.push(` ${callee(step)}(${argsOf(step)}),`); - } - phaseLines.push(" ]);"); - for (let i = 0; i < run.length; i++) { - const upsert = emitOutcomeUpsert(run[i], vars[i]); - if (upsert) phaseLines.push(upsert); - } - } else { - phaseLines.push(" await Promise.all(["); - for (const step of run) { - phaseLines.push(` ${callee(step)}(${argsOf(step)}),`); - } - phaseLines.push(" ]);"); - } - return; - } - for (const step of run) { - if (step.outcomeAttribute) { - const v = nextResultVar(); - phaseLines.push(` const ${v} = await ${callee(step)}(${argsOf(step)});`); - const upsert = emitOutcomeUpsert(step, v); - if (upsert) phaseLines.push(upsert); - } else { - phaseLines.push(` await ${callee(step)}(${argsOf(step)});`); - } - } - }; - - const emitGate = (gateStep: GateStep) => { - const varName = signalVarName(gateStep.signalName); - const timeout = gateStep.timeout ?? "48h"; - if (gateStep.description) { - phaseLines.push(` // Gate: ${gateStep.signalName} — ${gateStep.description}`); - } else { - phaseLines.push(` // Gate: ${gateStep.signalName}`); - } - phaseLines.push(` let ${varName}Cleared = false;`); - // Capture the approver identity from the signal payload. It rides in - // the signal event, so Temporal persists it in the workflow history - // even though the workflow itself only needs the boolean to proceed. - phaseLines.push(` let ${varName}Approver: string | undefined;`); - phaseLines.push(` setHandler(${varName}, (arg) => { ${varName}Approver = arg?.approver; ${varName}Cleared = true; });`); - phaseLines.push(` await condition(() => ${varName}Cleared, ${JSON.stringify(timeout)});`); - // Surface the approver in a search attribute when the caller opted a - // stack into one (config.searchAttributes contains "Approver"): only - // then is the attribute guaranteed registered, so an unconditional - // upsert can never break a gate on a cluster that never declared it. - if (config.searchAttributes && "Approver" in config.searchAttributes) { - phaseLines.push(` upsertSearchAttributes({ Approver: [${varName}Approver ?? "unknown"] });`); - } else { - phaseLines.push(` void ${varName}Approver;`); - } - }; - - // Walk the steps in authored order. A gate splits the phase's activities - // into separate runs, so [gate, activity] waits for the gate before the - // activity runs (and [activity, gate] the other way round) — the - // serializer never reorders what the author wrote (#1698). - let run: ActivityStep[] = []; - for (const step of phase.steps) { - if (isActivityStep(step)) { - run.push(step); - continue; - } - if (isGateStep(step)) { - emitActivityRun(run); - run = []; - emitGate(step); - } - } - emitActivityRun(run); + renderSteps(phase.steps, phaseLines, " ", phase.parallel ?? false); lines.push(...phaseLines); lines.push(""); diff --git a/packages/core/src/op/builders.ts b/packages/core/src/op/builders.ts index d0771cb650..cd1ce3e1f5 100644 --- a/packages/core/src/op/builders.ts +++ b/packages/core/src/op/builders.ts @@ -1,5 +1,7 @@ import { OpResource } from "./resource"; -import type { OpConfig, PhaseDefinition, StepDefinition, ActivityStep, GateStep } from "./types"; +import type { OpConfig, PhaseDefinition, StepDefinition, ActivityStep, GateStep, EffectStep } from "./types"; +import { isEffectReceipt, type EffectReceiptDeclaration } from "../effect-receipt"; +import { receiptCheckInput } from "./receipt-store"; // ── Core builders ───────────────────────────────────────────────────────────── @@ -58,6 +60,62 @@ export function gate( }; } +/** + * Wrap nested steps in read-compare-run-write over an effect receipt (#1834, + * epic #1703). At run: read the live receipt through the receipt store, + * compare it against the resolved expectation, and on a match skip the nested + * steps ("effect already applied"). On a mismatch the nested steps run in + * authored order, and ONLY when every one of them succeeds is the receipt + * written — last, once. This step is the sole writer of a receipt (decision + * 3); a nested-step failure leaves the receipt untouched (stale), so the next + * run re-proposes the effect. + * + * `receipt` is the typed EffectReceipt declaration — import the const from + * your receipts module. There is no string form: a receipt named by string + * would sever the step from the declaration that lint, plan, and the lexicon + * row all key on. + * + * A gate authored inside `steps` pauses only when the effect will fire (the + * matched path never reaches it). The receipt-store activities (`receiptRead`, + * `receiptWrite`) are provided by the receipt row's lexicon (#1835, aws). + * + * @example + * ```ts + * import { seededReceipt } from "./receipts"; + * phase("Seed", [ + * effect(seededReceipt, [ + * shell("npm run db:seed"), + * ]), + * ]), + * ``` + */ +export function effect( + receipt: EffectReceiptDeclaration, + steps: Array, + opts?: { description?: string }, +): EffectStep { + if (!isEffectReceipt(receipt)) { + throw new Error( + "effect(): `receipt` must be the EffectReceipt declaration itself — import the const; there is no string form", + ); + } + for (const step of steps) { + if ((step as { kind?: unknown }).kind === "effect") { + throw new Error( + `effect("${receipt.name}"): effect steps do not nest — one receipt witnesses one effect`, + ); + } + } + const { receipt: ref, expectation } = receiptCheckInput(receipt); + return { + kind: "effect", + receipt: ref, + ...(expectation !== undefined ? { expectation } : {}), + steps, + ...(opts?.description ? { description: opts.description } : {}), + }; +} + // ── Pre-built activity shortcuts ────────────────────────────────────────────── /** diff --git a/packages/core/src/op/effect-step.test.ts b/packages/core/src/op/effect-step.test.ts new file mode 100644 index 0000000000..2d69a4a634 --- /dev/null +++ b/packages/core/src/op/effect-step.test.ts @@ -0,0 +1,311 @@ +/** + * effect() step + receipt store seam + local-executor semantics (#1834, epic + * #1703). The contract under test: + * + * - the builder takes the typed EffectReceipt declaration only (no string + * form — enforced at the type level and at runtime); + * - read-compare-run-write: a matching receipt skips the nested steps; a + * mismatch runs them and writes the receipt ONLY on their success, last; + * - a nested-step failure leaves the receipt untouched (stale), so a rerun + * re-proposes the effect; + * - `receiptStaleness` (WatchOp's phase) is read-only: it reports absent and + * differing receipts as findings and never writes. + */ +import { describe, test, expect } from "vitest"; +import { EffectReceipt, receiptExpectation, EXISTENCE_EXPECTATION } from "../effect-receipt"; +import { INTRINSIC_MARKER, type Intrinsic } from "../intrinsic"; +import { effect, phase } from "./builders"; +import { + receiptActivities, + receiptCheckInput, + type ReceiptStore, + type EffectReceiptRef, +} from "./receipt-store"; +import type { ActivityFn, ActivityProfile } from "./activity-registry"; +import type { OpConfig, ActivityStep } from "./types"; +import { runOpLocally, findGate, LocalGateUnsupportedError, OpRunFailure } from "./local-executor"; + +function fakeIntrinsic(json: unknown): Intrinsic { + return { + [INTRINSIC_MARKER]: true, + toJSON: () => json, + }; +} + +const seeded = EffectReceipt("seeded", { + effect: "db-seed", + flavor: "hash", + inputs: { file: "seed.sql", version: 3 }, +}); + +const step = (fn: string, args?: Record): ActivityStep => ({ + kind: "activity", + fn, + ...(args ? { args } : {}), +}); + +// ── Builder ─────────────────────────────────────────────────────────────────── + +describe("effect() builder", () => { + test("wraps nested steps with the receipt's identity data and stamps a static expectation", () => { + const s = effect(seeded, [step("shellCmd", { cmd: "npm run db:seed" })]); + expect(s.kind).toBe("effect"); + expect(s.receipt).toEqual({ + name: "seeded", + effect: "db-seed", + flavor: "hash", + inputs: { file: "seed.sql", version: 3 }, + }); + expect(s.expectation).toBe(receiptExpectation(seeded)); + expect(s.steps.map((n) => (n.kind === "activity" ? n.fn : n.signalName))).toEqual(["shellCmd"]); + }); + + test("existence receipts always get the constant expectation, reference inputs or not", () => { + const r = EffectReceipt("booted", { + effect: "bootstrap", + flavor: "existence", + inputs: { endpoint: fakeIntrinsic({ __attrRef: { entity: "Db", attribute: "endpoint" } }) }, + }); + expect(effect(r, []).expectation).toBe(EXISTENCE_EXPECTATION); + }); + + test("a hash receipt with reference inputs carries no synthesis-time expectation (resolves at run, #1703 decision 5)", () => { + const r = EffectReceipt("migrated", { + effect: "db-migrate", + flavor: "hash", + inputs: { endpoint: fakeIntrinsic({ __attrRef: { entity: "Db", attribute: "endpoint" } }) }, + }); + const s = effect(r, []); + expect(s.expectation).toBeUndefined(); + expect("expectation" in s).toBe(false); + }); + + test("preserves authored order and nested gates", () => { + const s = effect(seeded, [ + { kind: "gate", signalName: "approve-seed" }, + step("shellCmd", { cmd: "seed" }), + ]); + expect(s.steps.map((n) => n.kind)).toEqual(["gate", "activity"]); + }); + + test("refuses anything that is not the typed receipt declaration", () => { + expect(() => effect({ name: "seeded" } as never, [])).toThrow(/no string form/); + // Type level: a string receipt name must not compile. + // @ts-expect-error — receipt is the EffectReceipt declaration, never a string + expect(() => effect("seeded", [])).toThrow(/no string form/); + }); + + test("effect steps do not nest", () => { + const inner = effect(seeded, []); + expect(() => effect(seeded, [inner as never])).toThrow(/do not nest/); + }); +}); + +// ── Receipt store seam ──────────────────────────────────────────────────────── + +function memStore(initial?: Record): { + store: ReceiptStore; + values: Map; + writes: Array<{ name: string; expectation: string }>; +} { + const values = new Map(Object.entries(initial ?? {})); + const writes: Array<{ name: string; expectation: string }> = []; + const store: ReceiptStore = { + async read(r: EffectReceiptRef) { + return values.get(r.name); + }, + async write(r: EffectReceiptRef, expectation: string) { + writes.push({ name: r.name, expectation }); + values.set(r.name, expectation); + }, + }; + return { store, values, writes }; +} + +describe("receiptActivities (the injectable store seam)", () => { + const input = receiptCheckInput(seeded); + const expected = receiptExpectation(seeded); + + test("receiptRead: absent receipt reads as current null, applied false", async () => { + const { store } = memStore(); + const { receiptRead } = receiptActivities(store); + expect(await receiptRead(input)).toEqual({ current: null, expectation: expected, applied: false }); + }); + + test("receiptRead: matching receipt reads as applied true", async () => { + const { store } = memStore({ seeded: expected }); + const { receiptRead } = receiptActivities(store); + expect(await receiptRead(input)).toEqual({ current: expected, expectation: expected, applied: true }); + }); + + test("receiptRead: refuses to invent an expectation for a reference-carrying hash receipt without a resolver", async () => { + const r = EffectReceipt("migrated", { + effect: "db-migrate", + flavor: "hash", + inputs: { endpoint: fakeIntrinsic("placeholder") }, + }); + const { store } = memStore(); + const { receiptRead } = receiptActivities(store); + await expect(receiptRead(receiptCheckInput(r))).rejects.toThrow(/resolveExpectation/); + }); + + test("receiptWrite stores the expectation", async () => { + const { store, writes, values } = memStore(); + const { receiptWrite } = receiptActivities(store); + await receiptWrite({ receipt: input.receipt, expectation: expected }); + expect(writes).toEqual([{ name: "seeded", expectation: expected }]); + expect(values.get("seeded")).toBe(expected); + }); + + test("receiptStaleness reports absent and differing receipts as findings, and never writes", async () => { + const fresh = EffectReceipt("fresh", { effect: "e1", flavor: "hash", inputs: { v: 1 } }); + const differs = EffectReceipt("differs", { effect: "e2", flavor: "hash", inputs: { v: 2 } }); + const absent = EffectReceipt("absent", { effect: "e3", flavor: "existence" }); + const { store, writes } = memStore({ + fresh: receiptExpectation(fresh), + differs: "sha256:stale", + }); + const { receiptStaleness } = receiptActivities(store); + const result = await receiptStaleness({ + receipts: [fresh, differs, absent].map(receiptCheckInput), + }); + expect(result.stale).toBe(true); + expect(result.findings).toEqual([ + { receipt: "differs", effect: "e2", kind: "differs", expected: receiptExpectation(differs), current: "sha256:stale" }, + { receipt: "absent", effect: "e3", kind: "absent", expected: EXISTENCE_EXPECTATION }, + ]); + expect(writes).toEqual([]); + }); + + test("receiptStaleness with everything fresh reports stale false", async () => { + const { store } = memStore({ seeded: expected }); + const { receiptStaleness } = receiptActivities(store); + expect(await receiptStaleness({ receipts: [input] })).toEqual({ stale: false, findings: [] }); + }); +}); + +// ── Local executor: read-compare-run-write ──────────────────────────────────── + +const PROFILES: Record = { + fastIdempotent: { startToCloseTimeout: "5m", retry: { maximumAttempts: 1 } }, +}; + +function activityMap( + store: ReceiptStore, + extra: Record, +): Map { + const map = new Map(); + for (const [name, fn] of Object.entries(receiptActivities(store))) { + map.set(name, fn as unknown as ActivityFn); + } + for (const [name, fn] of Object.entries(extra)) map.set(name, fn); + return map; +} + +function seedOp(): OpConfig { + return { + name: "seed-op", + overview: "", + phases: [phase("Seed", [effect(seeded, [step("runSeed")])])], + }; +} + +describe("runOpLocally — effect steps", () => { + test("matching receipt skips the nested steps and writes nothing", async () => { + const { store, writes } = memStore({ seeded: receiptExpectation(seeded) }); + const ran: string[] = []; + const activities = activityMap(store, { runSeed: async () => void ran.push("runSeed") }); + const result = await runOpLocally(seedOp(), activities, PROFILES); + expect(result.ok).toBe(true); + expect(ran).toEqual([]); + expect(writes).toEqual([]); + // The read records the effect as already applied; the nested step is skipped. + expect(result.records.map((r) => [r.fn, r.status])).toEqual([ + ["receiptRead", "ok"], + ["runSeed", "skipped"], + ]); + expect(result.records[0].outcome).toEqual({ name: "EffectApplied", value: true }); + }); + + test("mismatch runs the nested steps, then writes the receipt once, last", async () => { + const { store, writes } = memStore(); + const order: string[] = []; + const activities = activityMap( + { read: store.read, write: async (r, e) => { order.push("write"); await store.write(r, e); } }, + { runSeed: async () => void order.push("runSeed") }, + ); + const result = await runOpLocally(seedOp(), activities, PROFILES); + expect(result.ok).toBe(true); + expect(order).toEqual(["runSeed", "write"]); + expect(writes).toEqual([{ name: "seeded", expectation: receiptExpectation(seeded) }]); + expect(result.records.map((r) => [r.fn, r.status])).toEqual([ + ["receiptRead", "ok"], + ["runSeed", "ok"], + ["receiptWrite", "ok"], + ]); + }); + + test("a nested failure leaves the receipt untouched, and a rerun re-proposes the effect", async () => { + const { store, writes, values } = memStore(); + let healthy = false; + const activities = activityMap(store, { + runSeed: async () => { + if (!healthy) throw new Error("seed blew up"); + }, + }); + + await expect(runOpLocally(seedOp(), activities, PROFILES)).rejects.toThrow(OpRunFailure); + expect(writes).toEqual([]); + expect(values.has("seeded")).toBe(false); + + // The receipt is stale, so the next run runs the effect again — and only + // then writes. + healthy = true; + const rerun = await runOpLocally(seedOp(), activities, PROFILES); + expect(rerun.ok).toBe(true); + expect(writes).toEqual([{ name: "seeded", expectation: receiptExpectation(seeded) }]); + }); + + test("the failed run records the write as skipped, not run", async () => { + const { store } = memStore(); + const activities = activityMap(store, { + runSeed: async () => { + throw new Error("boom"); + }, + }); + const failure = await runOpLocally(seedOp(), activities, PROFILES).catch((e: OpRunFailure) => e); + expect(failure).toBeInstanceOf(OpRunFailure); + expect((failure as OpRunFailure).result.records.map((r) => [r.fn, r.status])).toEqual([ + ["receiptRead", "ok"], + ["runSeed", "fail"], + ["receiptWrite", "skipped"], + ]); + }); + + test("a gate nested in an effect step is rejected up front, like any other gate", () => { + const config: OpConfig = { + name: "gated", + overview: "", + phases: [ + phase("Seed", [effect(seeded, [{ kind: "gate", signalName: "approve-seed" }, step("runSeed")])]), + ], + }; + expect(findGate(config)?.signalName).toBe("approve-seed"); + const { store } = memStore(); + return expect( + runOpLocally(config, activityMap(store, { runSeed: async () => {} }), PROFILES), + ).rejects.toThrow(LocalGateUnsupportedError); + }); + + test("an effect step in a parallel phase is refused — read-compare-run-write is ordered", async () => { + const config: OpConfig = { + name: "par", + overview: "", + phases: [phase("P", [effect(seeded, [step("runSeed")])], { parallel: true })], + }; + const { store } = memStore(); + await expect( + runOpLocally(config, activityMap(store, { runSeed: async () => {} }), PROFILES), + ).rejects.toThrow(/parallel phase/); + }); +}); diff --git a/packages/core/src/op/index.ts b/packages/core/src/op/index.ts index c7b98f292c..3d5f67b1ba 100644 --- a/packages/core/src/op/index.ts +++ b/packages/core/src/op/index.ts @@ -1,4 +1,4 @@ -export { Op, phase, activity, gate, build, kubectlApply, helmInstall, waitForStack, waitForReady, +export { Op, phase, activity, gate, effect, build, kubectlApply, helmInstall, waitForStack, waitForReady, gitlabPipeline, lifecycleSnapshot, shell, ensureSecret, teardown, envTeardown, k3dUp, k3dDown, flociUp, flociDown, flociAzUp, flociAzDown, flociGcpUp, flociGcpDown, httpCheck, azGroupEnsure, azGroupDelete, azApply, azDelete, awsApply, awsDelete, gcpApply, gcpDelete, policyGate, @@ -13,7 +13,13 @@ export { emulatorLifecycle, emulatorsOf, endpointEnvVars } from "./emulator-life export type { EmulatorSpec, EmulatorCapability, EmulatorDeclaration, EmulatorUpArgs, EmulatorLifecycle } from "./emulator-lifecycle"; export { checkFreshness, compare, formatResult, latestRelease, parseVersion, unpinned } from "./emulator-freshness"; export type { FreshnessResult } from "./emulator-freshness"; -export type { OpConfig, PhaseDefinition, StepDefinition, ActivityStep, GateStep } from "./types"; +export type { OpConfig, PhaseDefinition, StepDefinition, ActivityStep, GateStep, EffectStep } from "./types"; +export { receiptActivities, receiptCheckInput } from "./receipt-store"; +export type { + ReceiptStore, EffectReceiptRef, ReceiptCheckInput, ReceiptActivities, ReceiptActivityOptions, + ReceiptReadArgs, ReceiptReadResult, ReceiptWriteArgs, + ReceiptStalenessArgs, ReceiptStalenessResult, ReceiptStaleFinding, +} from "./receipt-store"; export { discoverOps } from "./discover"; export type { DiscoveredOp, OpDiscoveryResult } from "./discover"; export { loadActivities, loadProfiles, resolveActivity } from "./activity-registry"; diff --git a/packages/core/src/op/local-executor.ts b/packages/core/src/op/local-executor.ts index 08131259ec..c23d27476b 100644 --- a/packages/core/src/op/local-executor.ts +++ b/packages/core/src/op/local-executor.ts @@ -11,8 +11,9 @@ * so core never statically depends on `@intentius/chant-lexicon-temporal`. */ -import type { OpConfig, PhaseDefinition, ActivityStep, GateStep, StepDefinition } from "./types"; +import type { OpConfig, PhaseDefinition, ActivityStep, GateStep, EffectStep, StepDefinition } from "./types"; import { resolveActivity, type ActivityFn, type ActivityProfile } from "./activity-registry"; +import type { ReceiptReadResult } from "./receipt-store"; // ── Records ───────────────────────────────────────────────────────────────── @@ -69,6 +70,7 @@ const FALLBACK_TIMEOUT_MS = 5 * 60_000; const isActivity = (s: StepDefinition): s is ActivityStep => s.kind === "activity"; const isGate = (s: StepDefinition): s is GateStep => s.kind === "gate"; +const isEffect = (s: StepDefinition): s is EffectStep => s.kind === "effect"; /** Parse a Temporal duration string ("5m", "30s", "1h30m", "100ms") to ms. */ export function parseDuration(s: string): number { @@ -92,12 +94,18 @@ function resolvePath(value: unknown, path?: string): unknown { ); } -/** Find the first gate step anywhere in the Op (phases + onFailure), if any. */ +/** Find the first gate step anywhere in the Op (phases + onFailure, including + * gates nested inside effect steps), if any. */ export function findGate(config: OpConfig): GateStep | undefined { const all = [...config.phases, ...(config.onFailure ?? [])]; for (const phase of all) { - const gate = phase.steps.find(isGate); - if (gate) return gate; + for (const step of phase.steps) { + if (isGate(step)) return step; + if (isEffect(step)) { + const nested = step.steps.find(isGate); + if (nested) return nested; + } + } } return undefined; } @@ -145,6 +153,13 @@ async function callWithTimeout( // ── Step + phase execution ────────────────────────────────────────────────��─ +/** A finished step: its record plus (on success) the activity's return value — + * the effect-step path needs `receiptRead`'s result, not just its status. */ +interface RanStep { + record: StepRecord; + result?: unknown; +} + /** Run one activity step with retry + timeout. Never throws — returns a record. */ async function runStep( step: ActivityStep, @@ -152,7 +167,7 @@ async function runStep( activities: Map, profiles: Record, signal?: AbortSignal, -): Promise { +): Promise { const args = step.args ?? {}; const base = { phase: phaseName, fn: step.fn, args }; const start = Date.now(); @@ -161,7 +176,7 @@ async function runStep( try { fn = resolveActivity(activities, step.fn); } catch (err) { - return { ...base, status: "fail", durationMs: 0, error: errMessage(err) }; + return { record: { ...base, status: "fail", durationMs: 0, error: errMessage(err) } }; } const profile = profiles[step.profile ?? DEFAULT_PROFILE] ?? {}; @@ -190,7 +205,7 @@ async function runStep( value: resolvePath(result, step.outcomeAttribute.from), }; } - return record; + return { record, result }; } catch (err) { lastErr = err; // Stop retrying on abort (Ctrl-C / timeout cascade) or a non-retryable error. @@ -204,7 +219,105 @@ async function runStep( break; } } - return { ...base, status: "fail", durationMs: Date.now() - start, error: errMessage(lastErr) }; + return { record: { ...base, status: "fail", durationMs: Date.now() - start, error: errMessage(lastErr) } }; +} + +// ── Effect steps (#1834) ────────────────────────────────────────────────────── + +/** The step data the executor synthesizes to read a receipt through the store + * activities (`receiptRead`/`receiptWrite` — provided by the receipt row's + * lexicon, #1835, or a mock store in tests via `receiptActivities`). */ +function receiptReadStep(step: EffectStep): ActivityStep { + return { + kind: "activity", + fn: "receiptRead", + args: { + receipt: step.receipt, + ...(step.expectation !== undefined ? { expectation: step.expectation } : {}), + }, + profile: "fastIdempotent", + outcomeAttribute: { name: "EffectApplied", from: "applied" }, + }; +} + +/** A skipped-record for a step that will not run. */ +function skippedRecord(phaseName: string, fn: string, args?: Record): StepRecord { + return { phase: phaseName, fn, args: args ?? {}, status: "skipped", durationMs: 0 }; +} + +/** + * Run one effect step: read-compare-run-write. On a match the nested steps are + * recorded as skipped ("effect already applied") and nothing is written. On a + * mismatch the nested steps run in authored order; only when every one + * succeeds is the receipt written — last, once (the sole writer, #1703 + * decision 3). Any failure leaves the receipt untouched (stale), so the next + * run re-proposes the effect. + */ +async function runEffectStep( + step: EffectStep, + phaseName: string, + activities: Map, + profiles: Record, + signal?: AbortSignal, +): Promise<{ records: StepRecord[]; failed: boolean }> { + const records: StepRecord[] = []; + + const read = await runStep(receiptReadStep(step), phaseName, activities, profiles, signal); + records.push(read.record); + if (read.record.status === "fail") return { records, failed: true }; + + const result = read.result as Partial | undefined; + if (typeof result?.expectation !== "string") { + records.push({ + phase: phaseName, + fn: `effect:${step.receipt.name}`, + args: {}, + status: "fail", + durationMs: 0, + error: "receiptRead returned no expectation — the receipt store activity must return { current, expectation }", + }); + return { records, failed: true }; + } + const expectation = result.expectation; + + if (result.current === expectation) { + // Effect already applied — skip the nested steps, write nothing. + for (const nested of step.steps) { + if (nested.kind === "activity") records.push(skippedRecord(phaseName, nested.fn, nested.args)); + } + return { records, failed: false }; + } + + // Gates are pre-flighted by findGate; only activities remain here. + const nestedActivities = step.steps.filter(isActivity); + for (let i = 0; i < nestedActivities.length; i++) { + const ran = await runStep(nestedActivities[i], phaseName, activities, profiles, signal); + records.push(ran.record); + if (ran.record.status === "fail") { + // Receipt left untouched (stale) — the next run re-proposes the effect. + for (const skipped of nestedActivities.slice(i + 1)) { + records.push(skippedRecord(phaseName, skipped.fn, skipped.args)); + } + records.push(skippedRecord(phaseName, "receiptWrite")); + return { records, failed: true }; + } + } + + // Sole writer of the receipt: on success of every nested step, last. + const wrote = await runStep( + { + kind: "activity", + fn: "receiptWrite", + args: { receipt: step.receipt, expectation }, + profile: "fastIdempotent", + }, + phaseName, + activities, + profiles, + signal, + ); + records.push(wrote.record); + return { records, failed: wrote.record.status === "fail" }; } /** Run a phase. Throws PhaseFailure (with records so far) if any step fails. */ @@ -214,35 +327,57 @@ async function runPhase( profiles: Record, signal?: AbortSignal, ): Promise { - // Defensive: gates are pre-flighted, but never execute one if it slips through. - const gate = phase.steps.find(isGate); + // Defensive: gates are pre-flighted, but never execute one if it slips + // through — including a gate nested inside an effect step. + const gate = + phase.steps.find(isGate) ?? + phase.steps.filter(isEffect).flatMap((e) => e.steps).find(isGate); if (gate) throw new LocalGateUnsupportedError(gate.signalName); - const steps = phase.steps.filter(isActivity); - if (phase.parallel) { - const records = await Promise.all( - steps.map((s) => runStep(s, phase.name, activities, profiles, signal)), - ); + const eff = phase.steps.find(isEffect); + if (eff) { + throw new Error( + `effect step "${eff.receipt.name}" cannot run in a parallel phase — read-compare-run-write is ordered`, + ); + } + const steps = phase.steps.filter(isActivity); + const records = ( + await Promise.all(steps.map((s) => runStep(s, phase.name, activities, profiles, signal))) + ).map((r) => r.record); if (records.some((r) => r.status === "fail")) throw new PhaseFailure(records); return records; } + const steps = phase.steps.filter((s): s is ActivityStep | EffectStep => !isGate(s)); const records: StepRecord[] = []; + + const skipRemaining = (from: number) => { + for (const skipped of steps.slice(from)) { + if (isEffect(skipped)) { + records.push(skippedRecord(phase.name, `effect:${skipped.receipt.name}`)); + } else { + records.push(skippedRecord(phase.name, skipped.fn, skipped.args)); + } + } + }; + for (let i = 0; i < steps.length; i++) { - const record = await runStep(steps[i], phase.name, activities, profiles, signal); + const step = steps[i]; + if (isEffect(step)) { + const { records: effRecords, failed } = await runEffectStep(step, phase.name, activities, profiles, signal); + records.push(...effRecords); + if (failed) { + skipRemaining(i + 1); + throw new PhaseFailure(records); + } + continue; + } + const { record } = await runStep(step, phase.name, activities, profiles, signal); records.push(record); if (record.status === "fail") { // Mark the remaining steps in this phase as skipped, then abort. - for (const skipped of steps.slice(i + 1)) { - records.push({ - phase: phase.name, - fn: skipped.fn, - args: skipped.args ?? {}, - status: "skipped", - durationMs: 0, - }); - } + skipRemaining(i + 1); throw new PhaseFailure(records); } } @@ -266,6 +401,18 @@ export async function runOpLocally( const gate = findGate(config); if (gate) throw new LocalGateUnsupportedError(gate.signalName); + // Effect steps are ordered (read-compare-run-write): refuse them in a + // parallel phase up front, with the phase named, rather than mid-run. + for (const phase of [...config.phases, ...(config.onFailure ?? [])]) { + const eff = phase.parallel ? phase.steps.find(isEffect) : undefined; + if (eff) { + throw new Error( + `phase "${phase.name}": effect step "${eff.receipt.name}" cannot run in a ` + + `parallel phase — read-compare-run-write is ordered`, + ); + } + } + const records: StepRecord[] = []; const start = Date.now(); diff --git a/packages/core/src/op/receipt-store.ts b/packages/core/src/op/receipt-store.ts new file mode 100644 index 0000000000..22767d0bf2 --- /dev/null +++ b/packages/core/src/op/receipt-store.ts @@ -0,0 +1,211 @@ +/** + * Receipt store seam (#1834, epic #1703) — how the `effect()` step and the + * receipt-reading Ops reach a materialized receipt without knowing which + * lexicon materializes it. + * + * The store is injectable: core defines the {@link ReceiptStore} interface and + * the activity contracts; the receipt row's lexicon implements the store over + * its own resource (#1835's aws row over `AWS::SSM::Parameter`) and exports + * the bound activities (`receiptRead`, `receiptWrite`, `receiptStaleness`) + * from its `op/activities` module via {@link receiptActivities}. The activity + * registry then resolves them by name, exactly like `ensureSecret` + * (#1829/#1830, provided by the k8s lexicon). Tests bind a mock store the + * same way. + * + * Write discipline (epic #1703 decision log, item 3): the `effect()` step is + * the SOLE writer of a receipt — on success of its nested steps, last. The + * store interface carries a `write`, but only the effect step's emitted + * read-compare-run-write (and its local-executor twin) reaches it. + * `receiptStaleness` — the WatchOp phase (#1834) — is read-only by + * construction: it never touches `write` and runs nothing. + * + * Expectation resolution follows the resolution split (decision 5): a fully + * static receipt's expectation is stamped at synthesis and rides the step + * data ({@link receiptCheckInput}); a hash-flavor receipt with reference + * inputs resolves at run, through the store lexicon's + * {@link ReceiptActivityOptions.resolveExpectation} hook — never by hashing + * placeholders. + */ + +import { + EXISTENCE_EXPECTATION, + isEffectReceipt, + receiptExpectation, + referenceInputPaths, + type EffectReceiptDeclaration, + type EffectReceiptFlavor, +} from "../effect-receipt"; + +/** + * The serializable identity + declaration data of an effect receipt — what an + * `effect()` step and a `receiptStaleness` check carry through codegen. Built + * from the typed {@link EffectReceiptDeclaration} only ({@link receiptCheckInput}); + * there is no string form. Reference inputs stay in placeholder form. + */ +export interface EffectReceiptRef { + /** The receipt's own name (the export-level identity of the witness). */ + name: string; + /** The effect this receipt witnesses. */ + effect: string; + /** How the receipt is compared: mere presence, or a digest of the inputs. */ + flavor: EffectReceiptFlavor; + /** The effect's inputs as recorded at synthesis (references as placeholders). */ + inputs: Record; +} + +/** + * The injectable seam over the materialized receipt (#1835 implements it for + * SSM; tests implement it with a map). `read` returns the receipt's current + * stored value, or `undefined` when the receipt is absent. `write` stores the + * expectation as the new value — called only by the effect step, on success, + * last. + */ +export interface ReceiptStore { + read(receipt: EffectReceiptRef): Promise; + write(receipt: EffectReceiptRef, expectation: string): Promise; +} + +/** One receipt to check: its identity plus, when the receipt is fully static, + * the expectation stamped at synthesis. */ +export interface ReceiptCheckInput { + receipt: EffectReceiptRef; + /** Present when the expectation was computable at synthesis; absent when + * reference inputs resolve at run (decision 5). */ + expectation?: string; +} + +/** + * Snapshot a typed receipt declaration into check-input data: the + * {@link EffectReceiptRef} plus the synthesis-time expectation when the + * receipt is fully static. Used by the `effect()` builder and by WatchOp's + * staleness phase — the single place "static enough to hash now" is decided. + */ +export function receiptCheckInput(receipt: EffectReceiptDeclaration): ReceiptCheckInput { + if (!isEffectReceipt(receipt)) { + throw new Error( + "receiptCheckInput: expected an EffectReceipt declaration — import the exported const; there is no string form", + ); + } + const ref: EffectReceiptRef = { + name: receipt.name, + effect: receipt.effect, + flavor: receipt.flavor, + inputs: receipt.inputs as Record, + }; + // An existence receipt's expectation is a constant, references or not; a + // hash receipt is static only when no reference inputs remain. + const isStatic = receipt.flavor === "existence" || referenceInputPaths(receipt).length === 0; + return isStatic ? { receipt: ref, expectation: receiptExpectation(receipt) } : { receipt: ref }; +} + +// ── Activity contracts ──────────────────────────────────────────────────────── + +/** Args of the `receiptRead` activity, as the effect step's codegen emits them. */ +export interface ReceiptReadArgs extends ReceiptCheckInput {} + +/** Result of the `receiptRead` activity. `current` is `null` (not `undefined`) + * for an absent receipt so the value survives JSON transport. */ +export interface ReceiptReadResult { + /** The receipt's live stored value, or null when absent. */ + current: string | null; + /** The resolved expectation the workflow compares and later writes. */ + expectation: string; + /** Convenience: `current === expectation`. */ + applied: boolean; +} + +/** Args of the `receiptWrite` activity — the receipt and the resolved + * expectation returned by the preceding `receiptRead`. */ +export interface ReceiptWriteArgs { + receipt: EffectReceiptRef; + expectation: string; +} + +/** Args of the read-only `receiptStaleness` activity (WatchOp). */ +export interface ReceiptStalenessArgs { + receipts: ReceiptCheckInput[]; +} + +/** One stale receipt, reported as a finding — never acted on. */ +export interface ReceiptStaleFinding { + /** The receipt's name. */ + receipt: string; + /** The effect the receipt witnesses. */ + effect: string; + /** `absent` — no receipt stored; `differs` — stored value is not the expectation. */ + kind: "absent" | "differs"; + /** The resolved expectation. */ + expected: string; + /** The live stored value (present only for `differs`). */ + current?: string; +} + +/** Result of the `receiptStaleness` activity. */ +export interface ReceiptStalenessResult { + stale: boolean; + findings: ReceiptStaleFinding[]; +} + +/** Options for {@link receiptActivities}. */ +export interface ReceiptActivityOptions { + /** + * Resolve a reference-carrying receipt's expectation at run (decision 5) — + * the store lexicon's hook to deploy-time values, typically wrapping core's + * `resolveReceiptExpectation`. Without it, a check input that carries no + * synthesis-time expectation fails loudly rather than hashing placeholders. + */ + resolveExpectation?: (receipt: EffectReceiptRef) => Promise | string; +} + +/** The three receipt activities, bound to one store. */ +export interface ReceiptActivities { + receiptRead: (args: ReceiptReadArgs, signal?: AbortSignal) => Promise; + receiptWrite: (args: ReceiptWriteArgs, signal?: AbortSignal) => Promise<{ written: true; receipt: string }>; + receiptStaleness: (args: ReceiptStalenessArgs, signal?: AbortSignal) => Promise; +} + +/** + * Bind the receipt activities to a store. The store's lexicon calls this once + * and re-exports the result from its `op/activities` module; the activity + * registry picks the functions up by name for both executors. + */ +export function receiptActivities(store: ReceiptStore, opts?: ReceiptActivityOptions): ReceiptActivities { + const expectationOf = async (input: ReceiptCheckInput): Promise => { + if (input.expectation !== undefined) return input.expectation; + if (input.receipt.flavor === "existence") return EXISTENCE_EXPECTATION; + if (opts?.resolveExpectation) return await opts.resolveExpectation(input.receipt); + throw new Error( + `receipt "${input.receipt.name}": no synthesis-time expectation and no resolveExpectation hook — ` + + `a hash-flavor receipt with reference inputs resolves at run (#1703 decision 5), ` + + `and hashing placeholders would be a wrong expectation`, + ); + }; + + return { + async receiptRead(args: ReceiptReadArgs): Promise { + const expectation = await expectationOf(args); + const current = await store.read(args.receipt); + return { current: current ?? null, expectation, applied: current === expectation }; + }, + + async receiptWrite(args: ReceiptWriteArgs): Promise<{ written: true; receipt: string }> { + await store.write(args.receipt, args.expectation); + return { written: true, receipt: args.receipt.name }; + }, + + // Read-only: reads and reports, runs nothing, never writes. + async receiptStaleness(args: ReceiptStalenessArgs): Promise { + const findings: ReceiptStaleFinding[] = []; + for (const input of args.receipts) { + const expected = await expectationOf(input); + const current = await store.read(input.receipt); + if (current === undefined) { + findings.push({ receipt: input.receipt.name, effect: input.receipt.effect, kind: "absent", expected }); + } else if (current !== expected) { + findings.push({ receipt: input.receipt.name, effect: input.receipt.effect, kind: "differs", expected, current }); + } + } + return { stale: findings.length > 0, findings }; + }, + }; +} diff --git a/packages/core/src/op/types.ts b/packages/core/src/op/types.ts index 5394cd4fd5..25b23fc99d 100644 --- a/packages/core/src/op/types.ts +++ b/packages/core/src/op/types.ts @@ -5,6 +5,8 @@ * in core without pulling in @temporalio/* as a dependency. */ +import type { EffectReceiptRef } from "./receipt-store"; + export interface OpConfig { /** Kebab-case identifier. Used as the workflow function name (camelCase) and output directory name. */ name: string; @@ -33,7 +35,7 @@ export interface PhaseDefinition { parallel?: boolean; } -export type StepDefinition = ActivityStep | GateStep; +export type StepDefinition = ActivityStep | GateStep | EffectStep; export interface ActivityStep { kind: "activity"; @@ -61,6 +63,36 @@ export interface ActivityStep { outcomeAttribute?: { name: string; from?: string }; } +/** + * Read-compare-run-write over an effect receipt (#1834, epic #1703). The + * runtime reads the live receipt through the receipt store, compares it + * against the resolved expectation, skips the nested steps on a match, and + * otherwise runs them — writing the receipt only when every nested step + * succeeded, last. A nested-step failure leaves the receipt untouched + * (stale), so the next run re-proposes the effect. + * + * Authored via the `effect()` builder, which takes the typed EffectReceipt + * declaration only — there is no string form. + */ +export interface EffectStep { + kind: "effect"; + /** Receipt identity + declaration data (references in placeholder form). */ + receipt: EffectReceiptRef; + /** + * The expectation stamped at synthesis when the receipt is fully static; + * absent when reference inputs resolve at run (#1703 decision 5). + */ + expectation?: string; + /** + * Steps run when the live receipt does not match, in authored order. A gate + * authored here pauses only when the effect will fire. Effect steps do not + * nest. + */ + steps: Array; + /** Annotation carried into the generated workflow as a comment. */ + description?: string; +} + export interface GateStep { kind: "gate"; /** Signal name. The generated workflow waits for this signal before continuing. */