Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions docs/src/content/docs/guide/ops-reference.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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 <env> --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

Expand Down Expand Up @@ -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/<name>/`:
Expand Down
2 changes: 2 additions & 0 deletions docs/src/content/docs/guide/watching-lifecycle.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
15 changes: 13 additions & 2 deletions lexicons/temporal/src/composites/apply-op.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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-<name>`.
Expand Down Expand Up @@ -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 ?? "." })]),
Expand All @@ -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" : ""})`,
}),
]),
);
Expand Down
92 changes: 92 additions & 0 deletions lexicons/temporal/src/composites/composites.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown> {
return (entity as { props: Record<string, unknown> }).props;
Expand Down Expand Up @@ -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<Record<string, unknown>>;
expect(phases.map((p) => p.name)).toEqual(["Build", "Plan", "Approve", "Apply"]);
const gateStep = (phases[2].steps as Array<Record<string, unknown>>)[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<Record<string, unknown>>;
const applyStep = (phases.find((p) => p.name === "Apply")!.steps as Array<Record<string, unknown>>)[0];
expect((applyStep.args as Record<string, unknown>).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<Record<string, unknown>>;
expect(phases.map((p) => p.name)).toEqual(["Build", "Plan", "Approve", "Apply"]);
const gateStep = (phases[2].steps as Array<Record<string, unknown>>)[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<typeof serializeOps>[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<Record<string, unknown>>;
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<Record<string, unknown>>;
expect(phases.map((p) => p.name)).toEqual(["Snapshot", "Diff", "Receipts"]);
const step = (phases[2].steps as Array<Record<string, unknown>>)[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<Record<string, unknown>>;
const steps = phases[2].steps as Array<Record<string, unknown>>;
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<typeof serializeOps>[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");
});
});
27 changes: 26 additions & 1 deletion lexicons/temporal/src/composites/watch-op.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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" },
},
]),
]
: []),
],
});

Expand Down
3 changes: 2 additions & 1 deletion lexicons/temporal/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ export {
phase,
activity,
gate,
effect,
build,
kubectlApply,
helmInstall,
Expand Down Expand Up @@ -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";
121 changes: 120 additions & 1 deletion lexicons/temporal/src/op/op-serializer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 ───────────────────────────────────────────────────────────────────

Expand Down Expand Up @@ -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<typeof activities>\(\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';");
});
});
});
Loading
Loading