From 8f1827dfadb6f7428d118fc4b713ae9b737f9c4c Mon Sep 17 00:00:00 2001 From: Ray Karnes Date: Wed, 2 Dec 2026 11:31:22 -0700 Subject: [PATCH 1/5] test(generate): pin the promote per-environment retry ladder and its sinks Add internal/generate/promote_retry_test.go ahead of the #626 generator change, pinning the chosen design end to end: - a deploy with declared inputs and retries > 0 replaces its promote matrix with one job per promotion target (every declared environment except the first), gated on preflight's deploy__envs list, with its with: block reading per-environment resolved-input JSON; - each per-environment job gets an orchestrate-style retry chain gated on its predecessor failing, as do the single no-inputs deploy job and the prod deployment job; - every result sink judges the effective result across environments and attempts: the rollback gate (aggregate success, exhaustion with rescue exemption), DEPLOY_RESULT_ as one three-way aggregate value (failure/success/skipped), and the native deployments status; - the build-matrices step emits the envs list and per-environment inputs (executed against jq, mirroring the matrix script tests); - skipped-leg semantics and the byte-frozen retries 0 boundary (an explicit retries: 0 is byte-identical to an omitted retries). Rewrite the two pinned inertness tests rather than deleting them: DoesNotEmitRetryLadder becomes EmitsRetryLadder with the design rationale, and RetriesDoNotPerturbOutput keeps its byte-compare method at the retries 0 versus unset boundary. Add CLI-side tests driving the three aggregate values through the finalize gate (pointer hold, deploy row recording, all-skipped refusal). Closes #626 Signed-off-by: Ray Karnes --- internal/generate/effective_result_test.go | 128 ++++- internal/generate/promote_retry_test.go | 598 +++++++++++++++++++++ internal/promote/command_finalize_test.go | 119 ++++ 3 files changed, 816 insertions(+), 29 deletions(-) create mode 100644 internal/generate/promote_retry_test.go diff --git a/internal/generate/effective_result_test.go b/internal/generate/effective_result_test.go index e2af4fe4..42d44974 100644 --- a/internal/generate/effective_result_test.go +++ b/internal/generate/effective_result_test.go @@ -1,6 +1,7 @@ package generate import ( + "fmt" "os" "path/filepath" "testing" @@ -168,46 +169,115 @@ func TestEffectiveResult_AllAttemptsFail_StillFails(t *testing.T) { assert.Contains(t, result, `if [[ "$WEB_RESULT" == "success" ]]; then`) } -// TestEffectiveResult_Promote_DoesNotEmitRetryLadder pins the scope decision for -// F2, so that a later author who adds a promote ladder must confront the reason -// one is not there today rather than discovering it in production. +// TestEffectiveResult_Promote_EmitsRetryLadder pins the scope of the promote +// retry design (#626), so a later author who changes the ladder's shape must +// confront the reasoning rather than discovering it in production. // -// retries is an orchestrate-only capability. A promote deploy that declares -// inputs compiles to a matrix job fanned across environments with -// fail-fast: false (see writeDeployJobs), and a matrix job exposes a single -// aggregate result: 'failure' if ANY leg failed. A caller-side shim gated on -// that aggregate re-invokes the reusable workflow for EVERY leg, redeploying the -// environments that already succeeded. GitHub Actions offers no caller-side way -// to re-run only the failed legs of a dependency's matrix, so a ladder here -// would redeploy healthy production environments on account of an unrelated -// environment's transient failure. That is worse than no retry. +// History: retries was orchestrate-only for years, deliberately. A promote +// deploy that declares inputs compiles to a matrix job fanned across +// environments with fail-fast: false (see writeDeployJobs), and a matrix job +// exposes a single aggregate result: 'failure' if ANY leg failed. A +// caller-side shim gated on that aggregate re-invokes the reusable workflow +// for EVERY leg, redeploying the environments that already succeeded. GitHub +// Actions offers no caller-side way to re-run only the failed legs of a +// dependency's matrix (re-checked for this design; still impossible), so a +// ladder on the matrix would redeploy healthy production environments on +// account of an unrelated environment's transient failure, and emitting one +// only on the non-matrix path would make retries silently work or not work +// depending on whether the deploy happened to declare inputs. // -// Emitting a ladder only on the non-matrix path was rejected too: it would make -// retries silently work or not work depending on whether the deploy happened to -// declare inputs. The documented claim is scoped to orchestrate instead. -func TestEffectiveResult_Promote_DoesNotEmitRetryLadder(t *testing.T) { - for _, retries := range []int{0, 2} { +// The design that resolved it: a deploy with inputs and retries > 0 replaces +// its matrix with ONE JOB PER PROMOTION TARGET (every declared environment +// except the first), each carrying its own ladder (promote_retry_test.go pins +// the fan-out's shape). With per-environment jobs, a shim re-invokes only the +// one environment whose attempt failed, which is the whole point. The single +// no-inputs deploy job and the prod deploy job are already +// single-environment, so they get plain ladders directly. This test pins the +// baseline shape on the no-inputs fixture; the fan-out shape is pinned in +// promote_retry_test.go. +func TestEffectiveResult_Promote_EmitsRetryLadder(t *testing.T) { + for _, retries := range []int{1, 2} { cfg, tmpDir := retriesFixture(t, retries) result, err := NewPromoteGenerator(cfg, tmpDir).Generate() require.NoError(t, err) - assert.NotContains(t, result, "deploy-web-retry-", - "promote emits no retry ladder at retries=%d; see this test's rationale", retries) + // The single deploy job and the prod job each get an orchestrate-style + // ladder, chained on the attempt before them. + assert.Contains(t, result, "deploy-web-retry-1:", + "promote emits a retry ladder at retries=%d", retries) + assert.Contains(t, result, + "if: ${{ !cancelled() && needs.deploy-web.result == 'failure' }}", + "the first shim gates on the base job failing, with the !cancelled() status function") + if retries > 1 { + assert.Contains(t, result, "deploy-web-retry-2:") + assert.Contains(t, result, + "if: ${{ !cancelled() && needs.deploy-web-retry-1.result == 'failure' }}", + "later shims chain on their predecessor, not all on the base job") + } + + // Sinks judge the ladder's effective result, not the immutable base. + assert.Contains(t, result, "DEPLOY_RESULT_WEB: ${{ (contains(", + "DEPLOY_RESULT must aggregate across attempts at retries=%d", retries) + + // And exactly N shims: the ladder is bounded by the declared retries. + assert.NotContains(t, result, fmt.Sprintf("deploy-web-retry-%d:", retries+1), + "retries=%d emits exactly %d shims", retries, retries) } + + // The retry-free manifest still emits no ladder at all. + cfg, tmpDir := retriesFixture(t, 0) + result, err := NewPromoteGenerator(cfg, tmpDir).Generate() + require.NoError(t, err) + assert.NotContains(t, result, "deploy-web-retry-", + "a retry-free manifest must emit no ladder") } -// TestEffectiveResult_Promote_RetriesDoNotPerturbOutput proves retries is inert -// on the promote path rather than partially wired: a manifest that declares -// retries must emit byte-identical promote output to one that does not. +// TestEffectiveResult_Promote_RetriesDoNotPerturbOutput pins the frozen +// boundary of the promote retry design: retries > 0 deliberately changes the +// promote output (that is #626), so the frozen-schema promise narrows to the +// zero boundary — a manifest that declares retries: 0 explicitly must emit +// byte-identical promote output to one that omits the field entirely, keeping +// the retry-free shape stable for every existing manifest. The comparison is +// at the manifest level (one YAML carries an explicit `retries: 0`, the other +// omits the key) because that is the boundary an operator can observe. func TestEffectiveResult_Promote_RetriesDoNotPerturbOutput(t *testing.T) { - withRetries, dirA := retriesFixture(t, 2) - without, dirB := retriesFixture(t, 0) + tmpDir := t.TempDir() + require.NoError(t, os.MkdirAll(filepath.Join(tmpDir, ".github/workflows"), 0o755)) + deployWorkflow := ` +name: Deploy Web +on: + workflow_call: + inputs: + environment: + type: string +` + require.NoError(t, os.WriteFile( + filepath.Join(tmpDir, ".github/workflows/deploy.yaml"), + []byte(deployWorkflow), 0o644)) - a, err := NewPromoteGenerator(withRetries, dirA).Generate() - require.NoError(t, err) - b, err := NewPromoteGenerator(without, dirB).Generate() - require.NoError(t, err) + const base = `ci: + config: + trunk_branch: main + environments: [dev] + deploys: + - name: web + workflow: .github/workflows/deploy.yaml + triggers: ["src/**"] +` + generate := func(manifest string) string { + file, err := config.ParseManifestBytes([]byte(manifest), config.DefaultManifestKey) + require.NoError(t, err) + content, err := NewPromoteGenerator(file.Config, tmpDir).Generate() + require.NoError(t, err) + return content + } + + explicitZero := generate(base + " retries: 0\n") + unset := generate(base) - assert.Equal(t, b, a, "retries must not perturb promote output while it is orchestrate-only") + assert.Equal(t, unset, explicitZero, + "an explicit retries: 0 must emit byte-identical promote output to an omitted retries") + assert.NotContains(t, explicitZero, "deploy-web-retry-", + "the zero boundary must emit no ladder") } diff --git a/internal/generate/promote_retry_test.go b/internal/generate/promote_retry_test.go new file mode 100644 index 00000000..3709a6c5 --- /dev/null +++ b/internal/generate/promote_retry_test.go @@ -0,0 +1,598 @@ +package generate + +import ( + "encoding/json" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + "github.com/stablekernel/cascade/internal/config" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// A promote deploy that declares retries now gets a retry ladder of its own +// (#626). The ladder's shape follows from the matrix problem: a promote deploy +// with declared inputs compiles to a matrix job across environments, and a +// matrix job exposes ONE aggregate result, so a caller-side shim would +// re-invoke every leg. GitHub Actions still cannot re-run only a dependency's +// failed legs, so a deploy with inputs and retries > 0 replaces its matrix +// with one job per promotion target (every declared environment except the +// first), each carrying its own orchestrate-style ladder. The single +// (no-inputs) deploy job and the prod deploy job are already +// single-environment, so they get plain ladders. These tests pin the emitted +// shape, the gates, every result sink's effective-result wiring, and the +// frozen retry-free boundary. + +// promoteRetriesFixture stages a repo whose single deploy points at a +// reusable workflow declaring the callback contract's environment and sha +// inputs plus cluster, and returns the manifest config. withInputs wires +// operator inputs on the deploy (cluster, with a prod override), which selects +// the matrix path at retries 0 and the per-environment fan-out at +// retries > 0. +func promoteRetriesFixture(t *testing.T, retries int, withInputs bool) (*config.TrunkConfig, string) { + t.Helper() + + tmpDir := t.TempDir() + require.NoError(t, os.MkdirAll(filepath.Join(tmpDir, ".github/workflows"), 0o755)) + + deployWorkflow := ` +name: Deploy Web +on: + workflow_call: + inputs: + environment: + type: string + sha: + type: string + cluster: + type: string +` + require.NoError(t, os.WriteFile( + filepath.Join(tmpDir, ".github/workflows/deploy.yaml"), + []byte(deployWorkflow), 0o644)) + + cfg := &config.TrunkConfig{ + TrunkBranch: "main", + Environments: config.EnvNames("dev", "staging", "prod"), + Deploys: []config.DeployConfig{ + { + Name: "web", + Workflow: ".github/workflows/deploy.yaml", + Triggers: []string{"src/**"}, + Retries: retries, + }, + }, + } + if withInputs { + cfg.Deploys[0].Inputs = map[string]interface{}{"cluster": "dev-cluster"} + cfg.Deploys[0].EnvInputs = map[string]map[string]interface{}{ + "prod": {"cluster": "prod-cluster"}, + } + } + return cfg, tmpDir +} + +// TestPromoteRetry_InputsDeployFansOutPerEnvironmentJobs pins the fan-out +// itself. A deploy with declared inputs and retries replaces its matrix with +// one job per promotion target, gated on preflight's deploy__envs list, +// and the with: block reads the per-environment resolved-input JSON instead of +// matrix.* contexts. +func TestPromoteRetry_InputsDeployFansOutPerEnvironmentJobs(t *testing.T) { + cfg, dir := promoteRetriesFixture(t, 2, true) + + result, err := NewPromoteGenerator(cfg, dir).Generate() + require.NoError(t, err) + + // One job per declared promotion target: staging and prod. Never dev: the + // first environment is the promotion source and is never a target. + assert.Contains(t, result, " deploy-web-to-staging:\n") + assert.Contains(t, result, " deploy-web-to-prod:\n") + assert.NotContains(t, result, "deploy-web-to-dev", + "the first environment is never a promotion target, so no job may target it") + assert.NotContains(t, result, " deploy-web:\n", + "a deploy with inputs and retries emits per-environment jobs, not the matrix job") + + // The matrix and its preflight output are gone on this path. + assert.NotContains(t, result, "deploy_web_matrix", + "the matrix output must not be emitted when the matrix job is replaced by the fan-out") + assert.NotContains(t, result, " strategy:\n", + "per-environment jobs are separate jobs, not matrix legs, so no strategy block is emitted") + + // Each job runs only when the promotion includes its environment, and the + // gate carries the dry-run guard exactly as the matrix job's did. + assert.Contains(t, result, + "if: ${{ github.event.inputs.dry_run != 'true' && contains(fromJSON(needs.preflight.outputs.deploy_web_envs), 'staging') }}") + assert.Contains(t, result, + "if: ${{ github.event.inputs.dry_run != 'true' && contains(fromJSON(needs.preflight.outputs.deploy_web_envs), 'prod') }}") + + // The with: block reads the per-environment resolved-input JSON; the + // environment itself is the literal the job stands for. + staging := extractJobBlock(result, "deploy-web-to-staging") + assert.Contains(t, staging, " name: Deploy web (staging)\n") + assert.Contains(t, staging, " needs: [preflight, promote]\n") + assert.Contains(t, staging, " environment: staging\n") + assert.Contains(t, staging, "sha: ${{ fromJSON(needs.preflight.outputs.deploy_web_inputs_staging).sha }}") + assert.Contains(t, staging, "cluster: ${{ fromJSON(needs.preflight.outputs.deploy_web_inputs_staging).cluster }}") + + // A different environment reads its own JSON, so env_inputs overrides + // still resolve per environment. + prodLeg := extractJobBlock(result, "deploy-web-to-prod") + assert.Contains(t, prodLeg, "cluster: ${{ fromJSON(needs.preflight.outputs.deploy_web_inputs_prod).cluster }}") + + // The prod leg coexists with the prod-deployment job: the fan-out's -to- + // infix keeps deploy-web-to-prod from colliding with the pre-existing + // deploy-web-prod job id (GitHub rejects duplicate job keys at parse). + assert.Contains(t, result, " deploy-web-prod:\n", + "the prod deployment job must keep its own id; the fan-out's prod leg needs a distinct one") +} + +// TestPromoteRetry_HyphenatedEnvFoldsOutputKey pins the output-key folding for +// environments whose names carry hyphens: the job id keeps the hyphen (job ids +// allow it) while the preflight output key folds it to an underscore, matching +// the deploy-name folding the matrix outputs already use. +func TestPromoteRetry_HyphenatedEnvFoldsOutputKey(t *testing.T) { + cfg, dir := promoteRetriesFixture(t, 1, true) + cfg.Environments = config.EnvNames("dev", "pre-prod", "prod") + + result, err := NewPromoteGenerator(cfg, dir).Generate() + require.NoError(t, err) + + assert.Contains(t, result, " deploy-web-to-pre-prod:\n") + assert.Contains(t, result, + "deploy_web_inputs_pre_prod: ${{ steps.build-matrices.outputs.deploy_web_inputs_pre_prod }}") + assert.Contains(t, result, "cluster: ${{ fromJSON(needs.preflight.outputs.deploy_web_inputs_pre_prod).cluster }}") +} + +// TestPromoteRetry_PerEnvChainGatesOnPredecessorFailure pins the ladder: each +// per-environment job gets its own shims, each gated on the attempt +// immediately before it failing, chained (retry-2 waits on retry-1), with the +// !cancelled() status function so GitHub's implicit needs-success gate does +// not skip a shim exactly when its predecessor failed. +func TestPromoteRetry_PerEnvChainGatesOnPredecessorFailure(t *testing.T) { + cfg, dir := promoteRetriesFixture(t, 2, true) + + result, err := NewPromoteGenerator(cfg, dir).Generate() + require.NoError(t, err) + + assert.Contains(t, result, " deploy-web-to-staging-retry-1:\n") + assert.Contains(t, result, " deploy-web-to-staging-retry-2:\n") + assert.Contains(t, result, " deploy-web-to-prod-retry-1:\n") + assert.NotContains(t, result, "deploy-web-to-staging-retry-3", + "retries: 2 emits exactly two shims per environment") + + // Sequential chaining: each shim waits on the attempt before it. + assert.Contains(t, result, "if: ${{ !cancelled() && needs.deploy-web-to-staging.result == 'failure' }}") + assert.Contains(t, result, "if: ${{ !cancelled() && needs.deploy-web-to-staging-retry-1.result == 'failure' }}") + assert.Contains(t, result, "needs: [preflight, deploy-web-to-staging-retry-1]", + "the second shim chains on the first, not on the base job") + + // A skipped environment is not retried: the gate reads 'failure', so a + // chain whose environment is not in the promotion (result 'skipped') or a + // dry run (gate skipped) never fires a shim. + assert.NotContains(t, result, "if: needs.deploy-web-to-staging.result == 'failure'", + "the bare form has no status function; GitHub's implicit needs-success gate would skip the shim on the only path it should run") + + // The shim re-invokes the same reusable workflow with the same inputs. + shim := extractJobBlock(result, "deploy-web-to-staging-retry-1") + assert.Contains(t, shim, " name: Deploy web (staging) - Retry 1\n") + assert.Contains(t, shim, " uses: ./.github/workflows/deploy.yaml\n") + assert.Contains(t, shim, "cluster: ${{ fromJSON(needs.preflight.outputs.deploy_web_inputs_staging).cluster }}") +} + +// TestPromoteRetry_SingleJobAndProdGetPlainChains pins the non-matrix shapes: +// the single no-inputs deploy job and the prod deployment job are already +// single-environment, so retries attaches a plain ladder to each, exactly like +// orchestrate's writeRetryJob. +func TestPromoteRetry_SingleJobAndProdGetPlainChains(t *testing.T) { + cfg, dir := promoteRetriesFixture(t, 2, false) + + result, err := NewPromoteGenerator(cfg, dir).Generate() + require.NoError(t, err) + + // The single deploy job keeps today's shape and gains a ladder. + assert.Contains(t, result, " deploy-web:\n") + assert.Contains(t, result, " deploy-web-retry-1:\n") + assert.Contains(t, result, " deploy-web-retry-2:\n") + assert.Contains(t, result, "if: ${{ !cancelled() && needs.deploy-web.result == 'failure' }}") + assert.Contains(t, result, "if: ${{ !cancelled() && needs.deploy-web-retry-1.result == 'failure' }}") + assert.Contains(t, result, "needs: [preflight, deploy-web-retry-1]") + + // The prod job gains its own ladder, separate from the deploy job's. + assert.Contains(t, result, " deploy-web-prod-retry-1:\n") + assert.Contains(t, result, "if: ${{ !cancelled() && needs.deploy-web-prod.result == 'failure' }}") + + // No per-environment fan-out on the no-inputs path: the single job already + // targets one environment (preflight's target_env). + assert.NotContains(t, result, "deploy-web-to-", + "the per-environment fan-out exists to split a matrix; a single job needs no split") +} + +// TestPromoteRetry_PreflightDeclaresFanOutOutputs pins the preflight outputs +// contract: with retries the build-matrices step's outputs are surfaced as +// deploy__envs plus one deploy__inputs_ per promotion target, +// and the matrix output is not declared. At retries 0 the matrix output is +// declared exactly as before. +func TestPromoteRetry_PreflightDeclaresFanOutOutputs(t *testing.T) { + cfg, dir := promoteRetriesFixture(t, 1, true) + + result, err := NewPromoteGenerator(cfg, dir).Generate() + require.NoError(t, err) + + assert.Contains(t, result, "deploy_web_envs: ${{ steps.build-matrices.outputs.deploy_web_envs }}") + assert.Contains(t, result, "deploy_web_inputs_staging: ${{ steps.build-matrices.outputs.deploy_web_inputs_staging }}") + assert.Contains(t, result, "deploy_web_inputs_prod: ${{ steps.build-matrices.outputs.deploy_web_inputs_prod }}") + assert.NotContains(t, result, "deploy_web_matrix") + + // The retry-free manifest keeps the matrix output declaration verbatim. + cfgZero, dirZero := promoteRetriesFixture(t, 0, true) + zero, err := NewPromoteGenerator(cfgZero, dirZero).Generate() + require.NoError(t, err) + assert.Contains(t, zero, "deploy_web_matrix: ${{ steps.build-matrices.outputs.deploy_web_matrix }}") + assert.NotContains(t, zero, "deploy_web_envs") +} + +// TestPromoteRetry_BuildMatricesEmitsEnvsAndPerEnvInputs executes the emitted +// build-matrices step (the production path that resolves deploy inputs at +// promotion time) and pins its outputs on the retries path: the environment +// list the per-environment jobs gate on, and each environment's resolved +// inputs. The publish "release" marker promotion is carried verbatim into the +// envs list, mirroring the matrix's behavior: it is not a declared +// environment, so no job gates on it. +func TestPromoteRetry_BuildMatricesEmitsEnvsAndPerEnvInputs(t *testing.T) { + if _, err := exec.LookPath("jq"); err != nil { + t.Skip("jq not available; the emitted fan-out script requires it") + } + + cfg, dir := promoteRetriesFixture(t, 1, true) + + content, err := NewPromoteGenerator(cfg, dir).Generate() + require.NoError(t, err) + + script, stepEnv := extractStepRun(t, content, "build-matrices") + + promotionResult := `{"promotions":[` + + `{"environment":"staging","sha":"aaa111","version":"v1.0.0-rc.1"},` + + `{"environment":"release","sha":"aaa111","version":"v1.0.0"},` + + `{"environment":"prod","sha":"aaa111","version":"v1.0.0"}]}` + + outFile := filepath.Join(t.TempDir(), "github_output") + require.NoError(t, os.WriteFile(outFile, nil, 0o600)) + + cmd := exec.Command("bash", "-e", "-c", script) + cmd.Env = os.Environ() + for k, v := range stepEnv { + cmd.Env = append(cmd.Env, k+"="+v) + } + cmd.Env = append(cmd.Env, + "PROMOTION_RESULT="+promotionResult, + "GITHUB_OUTPUT="+outFile, + ) + out, err := cmd.CombinedOutput() + require.NoError(t, err, "emitted fan-out script failed:\n%s", out) + + data, err := os.ReadFile(outFile) + require.NoError(t, err) + outputs := make(map[string]string) + for _, line := range strings.Split(strings.TrimSpace(string(data)), "\n") { + if k, v, ok := strings.Cut(line, "="); ok { + outputs[k] = v + } + } + + // The envs list mirrors the promotions verbatim, like the matrix did. + assert.JSONEq(t, `["staging","release","prod"]`, outputs["deploy_web_envs"]) + + // Per-environment resolved inputs: defaults merged with the prod override, + // the promotion's sha, and the environment on the entry like a matrix leg. + var staging map[string]interface{} + require.NoError(t, json.Unmarshal([]byte(outputs["deploy_web_inputs_staging"]), &staging)) + assert.Equal(t, map[string]interface{}{ + "cluster": "dev-cluster", + "environment": "staging", + "sha": "aaa111", + }, staging) + + var prod map[string]interface{} + require.NoError(t, json.Unmarshal([]byte(outputs["deploy_web_inputs_prod"]), &prod)) + assert.Equal(t, map[string]interface{}{ + "cluster": "prod-cluster", + "environment": "prod", + "sha": "aaa111", + }, prod) + + // The publish marker's entry is emitted (verbatim parity with the matrix) + // but no job consumes it. + assert.Contains(t, outputs, "deploy_web_inputs_release") +} + +// TestPromoteRetry_EmptyPromotionsProduceEmptyEnvs pins the skip case: with no +// promotions, the envs list is an empty JSON array, so every per-environment +// job's contains() gate is false and every chain reports 'skipped'. +func TestPromoteRetry_EmptyPromotionsProduceEmptyEnvs(t *testing.T) { + if _, err := exec.LookPath("jq"); err != nil { + t.Skip("jq not available; the emitted fan-out script requires it") + } + + cfg, dir := promoteRetriesFixture(t, 1, true) + + content, err := NewPromoteGenerator(cfg, dir).Generate() + require.NoError(t, err) + + script, stepEnv := extractStepRun(t, content, "build-matrices") + + outFile := filepath.Join(t.TempDir(), "github_output") + require.NoError(t, os.WriteFile(outFile, nil, 0o600)) + + cmd := exec.Command("bash", "-e", "-c", script) + cmd.Env = os.Environ() + for k, v := range stepEnv { + cmd.Env = append(cmd.Env, k+"="+v) + } + cmd.Env = append(cmd.Env, + "PROMOTION_RESULT="+`{"promotions":[]}`, + "GITHUB_OUTPUT="+outFile, + ) + out, err := cmd.CombinedOutput() + require.NoError(t, err, "emitted fan-out script failed:\n%s", out) + + data, err := os.ReadFile(outFile) + require.NoError(t, err) + for _, line := range strings.Split(strings.TrimSpace(string(data)), "\n") { + if k, v, ok := strings.Cut(line, "="); ok { + if k == "deploy_web_envs" { + assert.Equal(t, "[]", v, "no promotions must yield an empty envs array") + } + } + } +} + +// TestPromoteRetry_RollbackGateJudgesEffectiveResult pins the rollback gate. +// Rollback fires only when some environment's chain is exhausted, never when a +// retry rescued it, and the deploy's own success is judged on the aggregate +// across its per-environment chains (the matrix 'success' equivalent: every +// chain that ran ended in success, and at least one ran). +func TestPromoteRetry_RollbackGateJudgesEffectiveResult(t *testing.T) { + cfg, dir := promoteRetriesFixture(t, 1, true) + + result, err := NewPromoteGenerator(cfg, dir).Generate() + require.NoError(t, err) + + // The deploy's own success gate: any chain succeeded AND no chain + // exhausted. A rescued chain counts as success; an exhausted one in any + // environment means the deploy failed, matching matrix semantics where any + // failed leg fails the matrix. + assert.Contains(t, result, + "(needs.deploy-web-to-staging.result == 'success' || needs.deploy-web-to-staging-retry-1.result == 'success' || "+ + "needs.deploy-web-to-prod.result == 'success' || needs.deploy-web-to-prod-retry-1.result == 'success') && "+ + "!((needs.deploy-web-to-staging.result == 'failure' && !(needs.deploy-web-to-staging-retry-1.result == 'success')) || "+ + "(needs.deploy-web-to-prod.result == 'failure' && !(needs.deploy-web-to-prod-retry-1.result == 'success'))) &&", + "rollback's success gate must judge the aggregate across environments and attempts") + + // The failure trigger: some chain exhausted, with the rescue exemption. + // The prod-deployment ladder participates exactly as its job did before. + assert.Contains(t, result, + "(needs.deploy-web-to-staging.result == 'failure' && !(needs.deploy-web-to-staging-retry-1.result == 'success'))", + "the failure trigger must exempt a chain a retry rescued") + assert.Contains(t, result, + "(needs.deploy-web-prod.result == 'failure' && !(needs.deploy-web-prod-retry-1.result == 'success'))", + "the prod ladder is a failure trigger exactly as it was before retries") + + // needs: must list every job the gate reads (needs:/if: agreement). + assert.Contains(t, result, + "needs: [preflight, deploy-web-to-staging, deploy-web-to-staging-retry-1, "+ + "deploy-web-to-prod, deploy-web-to-prod-retry-1, deploy-web-prod, deploy-web-prod-retry-1]", + "rollback's needs must carry every chain job its if: reads") +} + +// TestPromoteRetry_RollbackGateSingleChain pins the single-job ladder's +// rollback wiring: with no declared inputs the deploy is one job, so the +// success gate is the plain effective-success disjunction. +func TestPromoteRetry_RollbackGateSingleChain(t *testing.T) { + cfg, dir := promoteRetriesFixture(t, 2, false) + + result, err := NewPromoteGenerator(cfg, dir).Generate() + require.NoError(t, err) + + assert.Contains(t, result, + "(needs.deploy-web.result == 'success' || needs.deploy-web-retry-1.result == 'success' || needs.deploy-web-retry-2.result == 'success') &&", + "a rescued single-job deploy must still count as the deploy's success for rollback") + assert.Contains(t, result, + "(needs.deploy-web.result == 'failure' && !(needs.deploy-web-retry-1.result == 'success' || needs.deploy-web-retry-2.result == 'success'))", + "the single-job failure trigger must exempt a rescued ladder") +} + +// TestPromoteRetry_DeployResultAggregate pins DEPLOY_RESULT_: a single +// aggregate value across all of the deploy's promotion chains and attempts — +// 'failure' if any chain exhausted (a cancelled, unrescued chain too, since +// the raw result the CLI used to read could carry 'cancelled'), else 'success' +// if any environment succeeded, else 'skipped'. The all-skipped case must +// still produce 'skipped'. The prod-deployment ladder is not part of the +// aggregate: the matrix result this replaces never read it either. +func TestPromoteRetry_DeployResultAggregate(t *testing.T) { + cfg, dir := promoteRetriesFixture(t, 1, true) + + result, err := NewPromoteGenerator(cfg, dir).Generate() + require.NoError(t, err) + + exhausted := + "(contains(fromJSON('[\"failure\", \"cancelled\"]'), needs.deploy-web-to-staging.result) && !(needs.deploy-web-to-staging-retry-1.result == 'success'))" + + " || " + + "(contains(fromJSON('[\"failure\", \"cancelled\"]'), needs.deploy-web-to-prod.result) && !(needs.deploy-web-to-prod-retry-1.result == 'success'))" + succeeded := + "needs.deploy-web-to-staging.result == 'success' || needs.deploy-web-to-staging-retry-1.result == 'success'" + + " || " + + "needs.deploy-web-to-prod.result == 'success' || needs.deploy-web-to-prod-retry-1.result == 'success'" + + assert.Contains(t, result, + "DEPLOY_RESULT_WEB: ${{ ("+exhausted+") && 'failure' || ("+succeeded+") && 'success' || 'skipped' }}", + "DEPLOY_RESULT must stay one value: failure if any chain exhausted, success if any environment succeeded, else skipped") + + // The aggregate must not bind to a per-environment base result alone, and + // must not drag the prod-deployment ladder in. + assert.NotContains(t, result, "DEPLOY_RESULT_WEB: ${{ needs.deploy-web.result }}") + assert.NotContains(t, result, "DEPLOY_RESULT_WEB: ${{ needs.deploy-web-to-staging.result }}") + assert.NotContains(t, result, "needs.deploy-web-prod.result }}\n", + "the prod ladder is not part of DEPLOY_RESULT, matching the matrix result it replaces") + + // Finalize needs every chain job so the aggregate's references resolve. + assert.Contains(t, result, + "needs: [preflight, promote, deploy-web-to-staging, deploy-web-to-staging-retry-1, "+ + "deploy-web-to-prod, deploy-web-to-prod-retry-1, deploy-web-prod, deploy-web-prod-retry-1]", + "finalize's needs must carry every chain job the aggregate reads") +} + +// TestPromoteRetry_DeployResultSingleChain pins the no-inputs aggregate: one +// chain, so the expression is the single ladder's three-way effective result. +func TestPromoteRetry_DeployResultSingleChain(t *testing.T) { + cfg, dir := promoteRetriesFixture(t, 2, false) + + result, err := NewPromoteGenerator(cfg, dir).Generate() + require.NoError(t, err) + + assert.Contains(t, result, + "DEPLOY_RESULT_WEB: ${{ "+ + "(contains(fromJSON('[\"failure\", \"cancelled\"]'), needs.deploy-web.result) && "+ + "!(needs.deploy-web-retry-1.result == 'success' || needs.deploy-web-retry-2.result == 'success'))"+ + " && 'failure' || "+ + "(needs.deploy-web.result == 'success' || needs.deploy-web-retry-1.result == 'success' || needs.deploy-web-retry-2.result == 'success')"+ + " && 'success' || 'skipped' }}") +} + +// TestPromoteRetry_SkippedLegIsNotFailure pins the skipped-leg semantics at +// the expression level: a chain whose environment was not in the promotion +// reports 'skipped' on every attempt, which is neither exhaustion nor success, +// so the aggregate's skipped branch is the only one it can select. +func TestPromoteRetry_SkippedLegIsNotFailure(t *testing.T) { + cfg, dir := promoteRetriesFixture(t, 1, true) + + result, err := NewPromoteGenerator(cfg, dir).Generate() + require.NoError(t, err) + + // The exhaustion anchor is failure-or-cancelled on the BASE job, so a + // skipped base never selects 'failure'. + assert.Contains(t, result, + "contains(fromJSON('[\"failure\", \"cancelled\"]'), needs.deploy-web-to-staging.result) && !(needs.deploy-web-to-staging-retry-1.result == 'success')") + // The success branch is a positive signal only; skipped never selects it. + assert.Contains(t, result, "&& 'success' || 'skipped' }}", + "the aggregate must be able to select 'skipped' when every chain skipped") + // The per-environment gate is what makes an out-of-promotion chain skip + // rather than fail. + assert.Contains(t, result, "contains(fromJSON(needs.preflight.outputs.deploy_web_envs), 'staging')") +} + +// TestPromoteRetry_NativeDeploymentsJudgesEffectiveResult pins the native +// deployments terminal status: every chain (per-environment legs and the prod +// ladder) contributes success-or-skipped on its effective result, so a rescued +// chain reports success and an exhausted one failure. +func TestPromoteRetry_NativeDeploymentsJudgesEffectiveResult(t *testing.T) { + cfg := &config.TrunkConfig{ + TrunkBranch: "main", + Environments: config.EnvNames("dev", "staging", "prod"), + Deployments: &config.DeploymentsConfig{Enabled: boolPtr(true)}, + Deploys: []config.DeployConfig{ + { + Name: "web", + Workflow: ".github/workflows/deploy.yaml", + Triggers: []string{"src/**"}, + Retries: 1, + }, + }, + } + dir := t.TempDir() + require.NoError(t, os.MkdirAll(filepath.Join(dir, ".github/workflows"), 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(dir, ".github/workflows/deploy.yaml"), + []byte("on:\n workflow_call:\n inputs:\n environment:\n type: string\n sha:\n type: string\n"), 0o644)) + + result, err := NewPromoteGenerator(cfg, dir).Generate() + require.NoError(t, err) + + assert.Contains(t, result, + "(needs.deploy-web.result == 'success' || needs.deploy-web-retry-1.result == 'success' || needs.deploy-web.result == 'skipped')") + assert.Contains(t, result, + "(needs.deploy-web-prod.result == 'success' || needs.deploy-web-prod-retry-1.result == 'success' || needs.deploy-web-prod.result == 'skipped')") + assert.Contains(t, result, "&& 'success' || 'failure' }}") +} + +// TestPromoteRetry_ZeroRetriesIsByteFrozen pins the frozen boundary: a +// manifest that does not use retries emits exactly today's promote output. +// The comparison is at the manifest level — an explicit `retries: 0` in YAML +// versus the field omitted entirely — because that is the boundary an operator +// can observe; both parse to the same zero value and must generate identical +// bytes, with the matrix job and its sinks keeping their exact retry-free +// forms and no ladder or fan-out artifact anywhere. +func TestPromoteRetry_ZeroRetriesIsByteFrozen(t *testing.T) { + dir := t.TempDir() + require.NoError(t, os.MkdirAll(filepath.Join(dir, ".github/workflows"), 0o755)) + require.NoError(t, os.WriteFile(filepath.Join(dir, ".github/workflows/deploy.yaml"), + []byte("on:\n workflow_call:\n inputs:\n environment:\n type: string\n sha:\n type: string\n cluster:\n type: string\n"), 0o644)) + + const base = `ci: + config: + trunk_branch: main + environments: [dev, staging, prod] + deploys: + - name: web + workflow: .github/workflows/deploy.yaml + triggers: ["src/**"] + inputs: + cluster: dev-cluster + env_inputs: + prod: + cluster: prod-cluster +` + generate := func(manifest string) string { + file, err := config.ParseManifestBytes([]byte(manifest), config.DefaultManifestKey) + require.NoError(t, err) + content, err := NewPromoteGenerator(file.Config, dir).Generate() + require.NoError(t, err) + return content + } + + a := generate(base + " retries: 0\n") + b := generate(base) + + assert.Equal(t, b, a, + "an explicit retries: 0 must generate byte-identical promote output to an omitted retries") + + // Today's forms, verbatim. + assert.Contains(t, a, " deploy-web:\n") + assert.Contains(t, a, " name: Deploy web (${{ matrix.environment }})\n") + assert.Contains(t, a, " include: ${{ fromJSON(needs.preflight.outputs.deploy_web_matrix) }}\n") + assert.Contains(t, a, " cluster: ${{ matrix.cluster }}\n") + assert.Contains(t, a, "needs.deploy-web.result == 'success' &&") + assert.Contains(t, a, "needs.deploy-web.result == 'failure'") + assert.Contains(t, a, "DEPLOY_RESULT_WEB: ${{ needs.deploy-web.result }}\n") + assert.Contains(t, a, + "(needs.deploy-web.result == 'success' || needs.deploy-web.result == 'skipped')") + + // No retry artifact of any kind. + assert.NotContains(t, a, "-retry-") + assert.NotContains(t, a, "deploy-web-to-") + assert.NotContains(t, a, "deploy_web_envs") +} + +// TestPromoteRetry_MixedManifestsKeepSinksPerDeploy pins a manifest that mixes +// a retried deploy with a retry-free one: only the retried deploy's jobs and +// sinks change, and the retry-free deploy keeps every retry-free form. +func TestPromoteRetry_MixedManifestsKeepSinksPerDeploy(t *testing.T) { + cfg, dir := promoteRetriesFixture(t, 1, true) + cfg.Deploys = append(cfg.Deploys, config.DeployConfig{ + Name: "edge", + Workflow: ".github/workflows/deploy.yaml", + Triggers: []string{"edge/**"}, + }) + + result, err := NewPromoteGenerator(cfg, dir).Generate() + require.NoError(t, err) + + // The retry-free deploy keeps the matrix and its sinks. + assert.Contains(t, result, "deploy_edge_matrix: ${{ steps.build-matrices.outputs.deploy_edge_matrix }}") + assert.Contains(t, result, "needs.deploy-edge.result == 'success' &&") + assert.Contains(t, result, "DEPLOY_RESULT_EDGE: ${{ needs.deploy-edge.result }}\n") + // ... and gains no ladder. + assert.NotContains(t, result, "deploy-edge-retry-") + assert.NotContains(t, result, "deploy-edge-to-") +} diff --git a/internal/promote/command_finalize_test.go b/internal/promote/command_finalize_test.go index b2d3128d..195ff4a1 100644 --- a/internal/promote/command_finalize_test.go +++ b/internal/promote/command_finalize_test.go @@ -213,3 +213,122 @@ func TestFinalizeCommand_WithJobQuery(t *testing.T) { // Should succeed even if job query fails (with warning) require.NoError(t, err) } + +// TestFinalize_DeployResultAggregateDrivesGate pins the promote retry +// fan-out's DEPLOY_RESULT contract against the CLI gates that consume it +// (#626). A deploy with retries reports ONE aggregate across its +// per-environment chains and attempts: 'failure' when any chain exhausted, +// 'success' when any environment succeeded, and 'skipped' when every chain +// skipped. Each value must drive the same CLI behavior the raw per-job result +// always did — failure holds the env pointer, success records the per-deploy +// row and advances, skipped neither holds the pointer nor counts as a deploy +// that ran — because the aggregate is only sound if every gate treats it +// exactly as the value it replaced. +func TestFinalize_DeployResultAggregateDrivesGate(t *testing.T) { + writeManifest := func(t *testing.T) string { + t.Helper() + configPath := filepath.Join(t.TempDir(), "manifest.yaml") + initial := `ci: + config: + environments: [dev, test, prod] + deploys: + - name: web + workflow: .github/workflows/deploy.yaml + - name: edge + workflow: .github/workflows/deploy.yaml + state: + dev: + sha: abc123 + version: v1.2.0 + test: {} +` + require.NoError(t, os.WriteFile(configPath, []byte(initial), 0o644)) + return configPath + } + + promotion := &PromotionResult{ + Promotions: []EnvPromotion{{Environment: "test", SHA: "abc123", Version: "v1.2.0"}}, + } + + t.Run("aggregate failure holds the pointer but still proceeds", func(t *testing.T) { + configPath := writeManifest(t) + // The generated finalize step forwards the aggregate through the + // DEPLOY_RESULT_ env var; the reader must carry it verbatim. + t.Setenv("DEPLOY_RESULT_WEB", "failure") + t.Setenv("DEPLOY_RESULT_EDGE", "success") + + results := readDeployResultsFromEnv([]string{"web", "edge"}) + require.Equal(t, "failure", results["web"]) + + // A reported failure is a result, so the silent-skip gate proceeds: + // the per-deploy success rows are still worth recording. + require.NoError(t, gateOnExpectedDeploys([]string{"web", "edge"}, results)) + + fin, err := NewFinalizer(configPath, "test") + require.NoError(t, err) + for name, conclusion := range results { + fin.SetDeployResult(name, conclusion) + } + fin.SetPromotionResult(promotion) + require.NoError(t, fin.Run()) + + cicdFile, err := config.ParseManifestFile(configPath, config.DefaultManifestKey) + require.NoError(t, err) + testState := cicdFile.State["test"] + require.NotNil(t, testState) + require.Equal(t, "", testState.SHA, "an exhausted chain holds the env pointer") + require.Equal(t, "", testState.Version, "an exhausted chain holds the env version") + // The sibling's success row is still recorded (partial success is not + // lost), exactly as it was when the value came from one job's result. + require.NotNil(t, testState.Deploys["edge"]) + }) + + t.Run("aggregate success records the deploy and advances", func(t *testing.T) { + configPath := writeManifest(t) + t.Setenv("DEPLOY_RESULT_WEB", "success") + t.Setenv("DEPLOY_RESULT_EDGE", "skipped") + + results := readDeployResultsFromEnv([]string{"web", "edge"}) + require.NoError(t, gateOnExpectedDeploys([]string{"web", "edge"}, results)) + + fin, err := NewFinalizer(configPath, "test") + require.NoError(t, err) + for name, conclusion := range results { + fin.SetDeployResult(name, conclusion) + } + fin.SetPromotionResult(promotion) + require.NoError(t, fin.Run()) + + cicdFile, err := config.ParseManifestFile(configPath, config.DefaultManifestKey) + require.NoError(t, err) + testState := cicdFile.State["test"] + require.NotNil(t, testState) + require.Equal(t, "abc123", testState.SHA, "a chain that succeeded (directly or via rescue) advances the pointer") + require.Equal(t, "v1.2.0", testState.Version) + require.NotNil(t, testState.Deploys["web"], "the aggregate success records the per-deploy row") + }) + + t.Run("all skipped neither holds the pointer nor counts as ran", func(t *testing.T) { + configPath := writeManifest(t) + t.Setenv("DEPLOY_RESULT_WEB", "skipped") + t.Setenv("DEPLOY_RESULT_EDGE", "skipped") + + results := readDeployResultsFromEnv([]string{"web", "edge"}) + + // Preflight planned both deploys, but every chain skipped: the state + // write is refused rather than advancing env state over a no-op. + err := gateOnExpectedDeploys([]string{"web", "edge"}, results) + require.Error(t, err) + require.Contains(t, err.Error(), "none reported a result") + + fin, err := NewFinalizer(configPath, "test") + require.NoError(t, err) + for name, conclusion := range results { + fin.SetDeployResult(name, conclusion) + } + fin.SetPromotionResult(promotion) + failed, held := fin.inScopeDeployFailed() + require.False(t, held, "a skipped chain must not hold the env pointer") + require.Empty(t, failed) + }) +} From 4e66384a874a85f77c72ca8ad7b3e792d177dcd6 Mon Sep 17 00:00:00 2001 From: Ray Karnes Date: Wed, 2 Dec 2026 11:45:02 -0700 Subject: [PATCH 2/5] feat(generate): fan promote deploys with retries out per environment Wire retries into the promote workflow (#626), to the design that keeps every retry scoped to the one environment whose attempt failed: - Extract writeRetryShimJob from the orchestrate generator's writeRetryJob so the promote ladders reuse the single copy of the shim emission: the !cancelled() status-function gate, the predecessor chaining, the name shape, needs: construction, uses:/with:/secrets ordering. - A deploy with declared inputs and retries > 0 replaces its promote matrix with one job per promotion target (every declared environment except the first), gated on preflight's new deploy__envs output, each with: block reading per-environment resolved-input JSON from the new deploy__inputs_ outputs. A matrix exposes one aggregate result, so a caller-side shim would redeploy every leg; per-environment jobs are the only caller-side shape that can retry just the failed environment. The job id carries a -to- infix (deploy-web-to-staging) because the pre-existing deploy--prod job would otherwise collide with a per-environment job for an environment literally named prod. - The single no-inputs deploy job and the prod deployment job are already single-environment and get plain ladders directly. - The build-matrices step emits the fan-out contract (the envs list and per-environment inputs) instead of the matrix when retries is set; the resolved-input computation is shared verbatim with the matrix path. - Rewire every result sink to the effective result across environments and attempts, via the shared retryShimJobIDs/effectiveSuccessCond/ effectiveFailureOrCancelledCond helpers: the rollback gate fires only when some environment's chain is exhausted and judges the deploy's own success on the aggregate across its chains; DEPLOY_RESULT_ stays one value (failure/success/skipped) that drives the finalize CLI gate exactly as the per-job result did; the native deployments status judges each chain's effective result. - retries 0 or unset emits byte-identical output everywhere: every new path is gated on retries > 0, and the byte-identical baseline goldens do not move. - on_failure stays abort-only and run_policy stays orchestrate-scoped (promote has no dependency skips to bind run_policy to; the force dispatch input is promote's continue-past-failure control). - Add the promote_per_env_retries actionlint feature-matrix case so real GitHub's parse of the fan-out (fromJSON with: reads, contains() gates, shim chaining, needs:/if: agreement across the aggregate sinks) is under permanent guard. Signed-off-by: Ray Karnes --- .../actionlint_feature_matrix_test.go | 28 + internal/generate/generator.go | 91 ++- internal/generate/promote.go | 593 +++++++++++++++--- internal/generate/promote_retry_test.go | 40 +- 4 files changed, 629 insertions(+), 123 deletions(-) diff --git a/internal/generate/actionlint_feature_matrix_test.go b/internal/generate/actionlint_feature_matrix_test.go index 8eda6469..6732392c 100644 --- a/internal/generate/actionlint_feature_matrix_test.go +++ b/internal/generate/actionlint_feature_matrix_test.go @@ -478,6 +478,34 @@ deploys: `), stubs: contractStubs(), }, + { + // #626: a deploy with declared inputs and retries replaces the + // promote matrix with one job per promotion target (every declared + // environment except the first), each with its own retry chain. This + // case proves real GitHub would accept the fan-out at parse: the + // contains() gates on preflight's deploy__envs output, the + // fromJSON(needs.preflight.outputs.deploy__inputs_) with: + // reads, the shims chained on their predecessor, and the needs:/if: + // agreement across the rollback and finalize jobs that read every + // chain's result for the aggregate DEPLOY_RESULT and rollback gates. + name: "promote_per_env_retries", + manifest: wrap(`trunk_branch: main +environments: [dev, staging, prod] +deploys: + - name: cdk + workflow: deploy.yaml + triggers: ["cdk/**"] + retries: 2 + inputs: + cluster: dev-cluster + env_inputs: + prod: + cluster: prod-cluster +`), + stubs: map[string]string{ + "deploy.yaml": callbackStub("environment", "sha", "dry_run", "cluster"), + }, + }, { name: "cancel_in_progress_true", manifest: wrap(buildDeploy + `concurrency: diff --git a/internal/generate/generator.go b/internal/generate/generator.go index 8597ca4a..b7562e58 100644 --- a/internal/generate/generator.go +++ b/internal/generate/generator.go @@ -1710,16 +1710,55 @@ func renderOperatorInputs(declared map[string]interface{}, declaredByCallee func return lines, nil } -func (g *Generator) writeRetryJob(sb *strings.Builder, info CallbackInfo, workflow string, retryNum int) error { - retryJobName := fmt.Sprintf("%s-retry-%d", info.JobID, retryNum) - prevJobName := info.JobID - if retryNum > 1 { - prevJobName = fmt.Sprintf("%s-retry-%d", info.JobID, retryNum-1) - } - - fmt.Fprintf(sb, " %s:\n", retryJobName) - fmt.Fprintf(sb, " name: %s - Retry %d\n", info.DisplayName, retryNum) - fmt.Fprintf(sb, " needs: [setup, %s]\n", prevJobName) +// retryShimJob carries the surface-independent facts of one retry shim job: +// a job that re-invokes the same reusable workflow when the attempt before it +// failed. Both the orchestrate generator (writeRetryJob) and the promote +// generator (the per-environment deploy chains and the single/prod deploy +// jobs, #626) emit their shims through writeRetryShimJob so the gate, name, +// needs:, uses: and secrets contract cannot drift between the surfaces. +type retryShimJob struct { + // BaseJobID is the ladder's base job (deploy-web, deploy-web-to-staging). + BaseJobID string + // DisplayName is the base job's display name; the shim appends + // " - Retry ". + DisplayName string + // RetryNum is the attempt number, 1-based. + RetryNum int + // NeedsBefore carries needs: entries that precede the predecessor job: + // orchestrate threads "setup", promote threads "preflight" (the shims + // read preflight outputs, which GitHub only exposes to direct needs). + NeedsBefore []string + // Permissions and Secrets are the callback's, re-emitted on the shim so + // the re-invocation carries the same least-privilege scopes and secrets. + Permissions map[string]string + Secrets *config.SecretsConfig + // Workflow is the uses: target: the same reusable workflow as the base. + Workflow string + // WriteWith emits the shim's with: block (surface-specific input wiring; + // the shim re-invokes the callback with the same inputs as the base). + WriteWith func(sb *strings.Builder) error + // Matrix, when non-nil, re-emits the strategy block so ${{ matrix.* }} + // references in the reusable workflow's inputs stay bound (orchestrate + // builds only; a promote fan-out has no matrix). + Matrix *config.MatrixConfig +} + +// writeRetryShimJob emits one retry shim job. It is the single copy of the +// shim emission logic: the gate, the name shape, the needs: construction and +// the uses:/with:/secrets ordering all live here. +func writeRetryShimJob(sb *strings.Builder, shim retryShimJob) error { + retryJobID := fmt.Sprintf("%s-retry-%d", shim.BaseJobID, shim.RetryNum) + prevJobID := shim.BaseJobID + if shim.RetryNum > 1 { + prevJobID = fmt.Sprintf("%s-retry-%d", shim.BaseJobID, shim.RetryNum-1) + } + needs := make([]string, 0, len(shim.NeedsBefore)+1) + needs = append(needs, shim.NeedsBefore...) + needs = append(needs, prevJobID) + + fmt.Fprintf(sb, " %s:\n", retryJobID) + fmt.Fprintf(sb, " name: %s - Retry %d\n", shim.DisplayName, shim.RetryNum) + fmt.Fprintf(sb, " needs: [%s]\n", strings.Join(needs, ", ")) // The gate must carry a status-check function. GitHub applies an implicit // needs-success requirement to any job whose if: has no status function, so a // BARE "needs..result == 'failure'" is skipped exactly when the @@ -1736,7 +1775,7 @@ func (g *Generator) writeRetryJob(sb *strings.Builder, info CallbackInfo, workfl // "!" is a YAML tag indicator and the "&&" trips the anchor parser, both of // which actionlint and GitHub reject. The wrapper keeps the "!" inside the // expression context where it is the boolean-negation operator. - fmt.Fprintf(sb, " if: ${{ !cancelled() && needs.%s.result == 'failure' }}\n", prevJobName) + fmt.Fprintf(sb, " if: ${{ !cancelled() && needs.%s.result == 'failure' }}\n", prevJobID) // timeout-minutes is forbidden on a reusable-workflow caller job // (jobs..uses): GitHub rejects the workflow at parse time. A retry shim // re-invokes the reusable workflow via uses:, so no timeout is emitted here. @@ -1747,22 +1786,40 @@ func (g *Generator) writeRetryJob(sb *strings.Builder, info CallbackInfo, workfl // references in the reusable workflow's inputs remain bound. Without this, // the retry job runs in a matrix-less context and GHA treats the expressions // as unresolved empty strings. - if info.Matrix != nil && len(info.Matrix.Dimensions) > 0 { - writeStrategyBlock(sb, info.Matrix) + if shim.Matrix != nil && len(shim.Matrix.Dimensions) > 0 { + writeStrategyBlock(sb, shim.Matrix) } // The retry shim re-invokes the same reusable workflow, so it needs the same // least-privilege job-level permissions: as the original callback. - writeCallbackPermissions(sb, " ", info.Permissions) + writeCallbackPermissions(sb, " ", shim.Permissions) - fmt.Fprintf(sb, " uses: %s\n", normalizeWorkflowPath(workflow)) - if err := g.writeWithInputs(sb, info); err != nil { + fmt.Fprintf(sb, " uses: %s\n", normalizeWorkflowPath(shim.Workflow)) + if err := shim.WriteWith(sb); err != nil { return err } - writeSecretsBlock(sb, info.Secrets) + writeSecretsBlock(sb, shim.Secrets) return nil } +// writeRetryJob emits retry for an orchestrate callback through the +// shared writeRetryShimJob, threading the callback's own with: wiring. +func (g *Generator) writeRetryJob(sb *strings.Builder, info CallbackInfo, workflow string, retryNum int) error { + return writeRetryShimJob(sb, retryShimJob{ + BaseJobID: info.JobID, + DisplayName: info.DisplayName, + RetryNum: retryNum, + NeedsBefore: []string{"setup"}, + Permissions: info.Permissions, + Secrets: info.Secrets, + Workflow: workflow, + WriteWith: func(sb *strings.Builder) error { + return g.writeWithInputs(sb, info) + }, + Matrix: info.Matrix, + }) +} + func (g *Generator) writeFinalizeJob(sb *strings.Builder, sorted []string) { // Collect all job IDs including retries var allJobs []string diff --git a/internal/generate/promote.go b/internal/generate/promote.go index 3c79c8d3..142a1e91 100644 --- a/internal/generate/promote.go +++ b/internal/generate/promote.go @@ -145,7 +145,9 @@ func (g *PromoteGenerator) Generate() (string, error) { g.writeHeader(&sb) g.writeWorkflowTriggers(&sb) g.writeConcurrency(&sb) - g.writeJobs(&sb) + if err := g.writeJobs(&sb); err != nil { + return "", err + } return sb.String(), nil } @@ -384,15 +386,32 @@ func (g *PromoteGenerator) writeMatrixBuildingStep(sb *strings.Builder) { } outputName := strings.ReplaceAll(d.Name, "-", "_") + upper := strings.ToUpper(outputName) + + if d.Retries > 0 { + // Retries declared (#626): emit the per-environment fan-out + // contract instead of a matrix — the promotion envs list the + // per-environment jobs gate on, plus each environment's resolved + // inputs. + fmt.Fprintf(sb, " # Build per-environment deploy entries for deploy: %s\n", d.Name) + fmt.Fprintf(sb, " ENVS_%s='['\n", upper) + g.writeMatrixBuildingLogic(sb, outputName, true) + fmt.Fprintf(sb, " ENVS_%s=\"${ENVS_%s}]\"\n", upper, upper) + fmt.Fprintf(sb, " echo \"deploy_%s_envs=$ENVS_%s\" >> \"$GITHUB_OUTPUT\"\n", outputName, upper) + fmt.Fprintf(sb, " echo \"::notice::Deploy %s envs: $ENVS_%s\"\n", d.Name, upper) + sb.WriteString(" \n") + continue + } + fmt.Fprintf(sb, " # Build matrix for deploy: %s\n", d.Name) - fmt.Fprintf(sb, " MATRIX_%s='['\n", strings.ToUpper(outputName)) + fmt.Fprintf(sb, " MATRIX_%s='['\n", upper) // The input JSON is env-routed on the step; the logic reads it back. - g.writeMatrixBuildingLogic(sb, outputName) + g.writeMatrixBuildingLogic(sb, outputName, false) - fmt.Fprintf(sb, " MATRIX_%s=\"${MATRIX_%s}]\"\n", strings.ToUpper(outputName), strings.ToUpper(outputName)) - fmt.Fprintf(sb, " echo \"deploy_%s_matrix=$MATRIX_%s\" >> \"$GITHUB_OUTPUT\"\n", outputName, strings.ToUpper(outputName)) - fmt.Fprintf(sb, " echo \"::notice::Deploy %s matrix: $MATRIX_%s\"\n", d.Name, strings.ToUpper(outputName)) + fmt.Fprintf(sb, " MATRIX_%s=\"${MATRIX_%s}]\"\n", upper, upper) + fmt.Fprintf(sb, " echo \"deploy_%s_matrix=$MATRIX_%s\" >> \"$GITHUB_OUTPUT\"\n", outputName, upper) + fmt.Fprintf(sb, " echo \"::notice::Deploy %s matrix: $MATRIX_%s\"\n", d.Name, upper) sb.WriteString(" \n") } } @@ -535,14 +554,21 @@ func (g *PromoteGenerator) matrixInputsJSON(deploy *config.DeployConfig) (string return string(defaultInputsJSON), string(envInputsJSON) } -// writeMatrixBuildingLogic generates the bash logic to build a matrix for a single deploy. -// It iterates through promotions and builds matrix entries with resolved inputs. -func (g *PromoteGenerator) writeMatrixBuildingLogic(sb *strings.Builder, outputName string) { - // The serialized input JSON carries operator-authored values verbatim, so - // it must never sit inside a shell quote literal in the script (a single - // quote in an ordinary value would break parsing; a crafted value would - // execute). The step env: map carries the JSON and the script reads it - // back through quoted variable references. +// writeMatrixBuildingLogic generates the bash logic that resolves a deploy's +// inputs for each promotion. It iterates through promotions and builds +// resolved input entries (defaults merged with env-specific overrides, the +// special variables substituted, and the promotion's environment and sha +// carried on the entry). perEnv selects what happens to each resolved entry: +// appended to the deploy's matrix array (the matrix mode, retries 0), or +// written as a per-environment preflight output plus collected into the envs +// list (the per-environment fan-out mode, retries > 0, #626). +// +// The serialized input JSON carries operator-authored values verbatim, so +// it must never sit inside a shell quote literal in the script (a single +// quote in an ordinary value would break parsing; a crafted value would +// execute). The step env: map carries the JSON and the script reads it +// back through quoted variable references. +func (g *PromoteGenerator) writeMatrixBuildingLogic(sb *strings.Builder, outputName string, perEnv bool) { upper := strings.ToUpper(outputName) fmt.Fprintf(sb, " DEFAULT_INPUTS=\"$DEFAULT_INPUTS_%s\"\n", upper) fmt.Fprintf(sb, " ENV_INPUTS=\"$ENV_INPUTS_%s\"\n", upper) @@ -577,13 +603,31 @@ func (g *PromoteGenerator) writeMatrixBuildingLogic(sb *strings.Builder, outputN sb.WriteString(" --arg sha \"$SHA\" \\\n") sb.WriteString(" '. + {environment: $env, sha: $sha}')\n") sb.WriteString(" \n") - sb.WriteString(" # Add to matrix (with comma separator)\n") - sb.WriteString(" if [ \"$FIRST\" = \"true\" ]; then\n") - fmt.Fprintf(sb, " MATRIX_%s=\"${MATRIX_%s}${RESOLVED}\"\n", strings.ToUpper(outputName), strings.ToUpper(outputName)) - sb.WriteString(" FIRST=false\n") - sb.WriteString(" else\n") - fmt.Fprintf(sb, " MATRIX_%s=\"${MATRIX_%s},${RESOLVED}\"\n", strings.ToUpper(outputName), strings.ToUpper(outputName)) - sb.WriteString(" fi\n") + if perEnv { + sb.WriteString(" # Emit the resolved inputs under this promotion's environment\n") + sb.WriteString(" # (hyphens folded to underscores in the output key, matching the\n") + sb.WriteString(" # deploy-name folding the preflight outputs use) and collect the\n") + sb.WriteString(" # environment into the fan-out list the per-environment jobs gate\n") + sb.WriteString(" # on. The publish \"release\" marker promotion is carried verbatim,\n") + sb.WriteString(" # mirroring the matrix: it is not a declared environment, so no\n") + sb.WriteString(" # job gates on it.\n") + sb.WriteString(" ENV_KEY=${ENV//-/_}\n") + fmt.Fprintf(sb, " echo \"deploy_%s_inputs_${ENV_KEY}=$RESOLVED\" >> \"$GITHUB_OUTPUT\"\n", outputName) + sb.WriteString(" if [ \"$FIRST\" = \"true\" ]; then\n") + fmt.Fprintf(sb, " ENVS_%s=\"${ENVS_%s}\\\"$ENV\\\"\"\n", upper, upper) + sb.WriteString(" FIRST=false\n") + sb.WriteString(" else\n") + fmt.Fprintf(sb, " ENVS_%s=\"${ENVS_%s},\\\"$ENV\\\"\"\n", upper, upper) + sb.WriteString(" fi\n") + } else { + sb.WriteString(" # Add to matrix (with comma separator)\n") + sb.WriteString(" if [ \"$FIRST\" = \"true\" ]; then\n") + fmt.Fprintf(sb, " MATRIX_%s=\"${MATRIX_%s}${RESOLVED}\"\n", upper, upper) + sb.WriteString(" FIRST=false\n") + sb.WriteString(" else\n") + fmt.Fprintf(sb, " MATRIX_%s=\"${MATRIX_%s},${RESOLVED}\"\n", upper, upper) + sb.WriteString(" fi\n") + } sb.WriteString(" done\n") sb.WriteString(" \n") } @@ -721,13 +765,16 @@ func (g *PromoteGenerator) writeWorkflowTriggers(sb *strings.Builder) { writeTopLevelPermissions(sb, base) } -func (g *PromoteGenerator) writeJobs(sb *strings.Builder) { +func (g *PromoteGenerator) writeJobs(sb *strings.Builder) error { sb.WriteString("jobs:\n") g.writePreflightJob(sb) g.writePromoteJob(sb) - g.writeDeployJobs(sb) + if err := g.writeDeployJobs(sb); err != nil { + return err + } g.writeRollbackJobs(sb) g.writeFinalizeJob(sb) + return nil } func (g *PromoteGenerator) writePreflightJob(sb *strings.Builder) { @@ -760,10 +807,23 @@ func (g *PromoteGenerator) writePreflightJob(sb *strings.Builder) { sb.WriteString(" can_proceed: ${{ steps.preflight.outputs.can_proceed }}\n") sb.WriteString(" promotion_result: ${{ steps.preflight.outputs.promotion_result }}\n") - // Add matrix outputs for each deploy with inputs + // Add build-matrices outputs for each deploy with inputs: the matrix at + // retries 0, or (retries > 0, #626) the per-environment fan-out contract — + // the promotion-target envs list the jobs gate on, plus each target's + // resolved-input JSON. for _, d := range g.config.Deploys { - if len(d.Inputs) > 0 { - outputName := strings.ReplaceAll(d.Name, "-", "_") + if len(d.Inputs) == 0 { + continue + } + outputName := strings.ReplaceAll(d.Name, "-", "_") + if d.Retries > 0 { + fmt.Fprintf(sb, " deploy_%s_envs: ${{ steps.build-matrices.outputs.deploy_%s_envs }}\n", outputName, outputName) + for _, env := range g.perEnvTargetEnvs() { + envKey := strings.ReplaceAll(env, "-", "_") + fmt.Fprintf(sb, " deploy_%s_inputs_%s: ${{ steps.build-matrices.outputs.deploy_%s_inputs_%s }}\n", + outputName, envKey, outputName, envKey) + } + } else { fmt.Fprintf(sb, " deploy_%s_matrix: ${{ steps.build-matrices.outputs.deploy_%s_matrix }}\n", outputName, outputName) } } @@ -870,10 +930,135 @@ func (g *PromoteGenerator) writeDeployStrategyOptions(sb *strings.Builder, rollo } } -func (g *PromoteGenerator) writeDeployJobs(sb *strings.Builder) { +// promoteJobChain is one retry-aware job chain a promote result sink reasons +// about: a base job plus its retry shims. retryShimJobIDs is the single +// source of truth for the shim ids, so a sink's needs: list and its if: +// condition can never reference different ladders. +type promoteJobChain struct { + jobID string + retries int +} + +// jobIDs returns the chain's job ids in ladder order (base first). +func (c promoteJobChain) jobIDs() []string { + return append([]string{c.jobID}, retryShimJobIDs(c.jobID, c.retries)...) +} + +// perEnvTargetEnvs returns the environments a promote deploy can be promoted +// into: every declared environment except the first, which is the promotion +// source and never a target. +func (g *PromoteGenerator) perEnvTargetEnvs() []string { + envs := g.config.EnvironmentNames() + if len(envs) <= 1 { + return nil + } + return envs[1:] +} + +// promotionChains returns the chains that carry a deploy's promotion legs — +// the jobs whose aggregate result replaces the matrix/single job's result in +// every promote result sink: +// - retries == 0: the matrix job (declared inputs) or the single deploy +// job, with no shims — today's shape; +// - retries > 0 with declared inputs: one chain per promotion target; +// - retries > 0 without declared inputs: the single deploy job's chain. +// +// The prod-deployment ladder is deliberately NOT a promotion chain: the +// matrix result these chains replace never read it, and the DEPLOY_RESULT +// aggregate keeps that scope. +func (g *PromoteGenerator) promotionChains(d *config.DeployConfig) []promoteJobChain { + if d.Retries <= 0 || len(d.Inputs) == 0 { + return []promoteJobChain{{jobID: fmt.Sprintf("deploy-%s", d.Name), retries: d.Retries}} + } + envs := g.perEnvTargetEnvs() + chains := make([]promoteJobChain, 0, len(envs)) + for _, env := range envs { + chains = append(chains, promoteJobChain{ + jobID: fmt.Sprintf("deploy-%s-to-%s", d.Name, env), + retries: d.Retries, + }) + } + return chains +} + +// deployChains returns every chain emitted for a local deploy: its +// promotion-leg chain(s) followed by the prod-deployment ladder, in the order +// the jobs are emitted (and therefore the order needs: lists them). +func (g *PromoteGenerator) deployChains(d *config.DeployConfig) []promoteJobChain { + chains := g.promotionChains(d) + return append(chains, promoteJobChain{ + jobID: fmt.Sprintf("deploy-%s-prod", d.Name), + retries: d.Retries, + }) +} + +// promoteChainFailedCond builds the condition that a chain terminally failed +// for the ROLLBACK gate: the base job failed and no retry shim rescued it. It +// anchors on 'failure' only — not 'cancelled' — because the retry-free gate +// it replaces reads 'failure' only, and a cancelled promote run must not fire +// rollbacks, exactly as before retries existed. Collapses to the bare base +// result at retries 0, so a retry-free manifest emits byte-identical output. +func promoteChainFailedCond(c promoteJobChain) string { + cond := fmt.Sprintf("needs.%s.result == 'failure'", c.jobID) + if rescued := retrySucceededCond(c.jobID, c.retries); rescued != "" { + cond = fmt.Sprintf("(%s && !(%s))", cond, rescued) + } + return cond +} + +// orGroup joins conditions with " || " and parenthesizes the result whenever +// it is a disjunction that will sit next to && or ||. A single condition that +// is already a self-contained unit — parenthesized by its builder, or a +// simple comparison — passes through bare. +func orGroup(conds []string) string { + joined := strings.Join(conds, " || ") + if len(conds) > 1 || (!strings.HasPrefix(joined, "(") && strings.Contains(joined, " || ")) { + return "(" + joined + ")" + } + return joined +} + +// promoteAggregateSuccessCond renders the matrix-'success' equivalent for a +// deploy's promotion chains: at least one chain succeeded and none exhausted. +// A chain a retry rescued counts as success; a chain that never ran (its +// environment was not in the promotion) counts as neither. For a single chain +// the exhaustion term is implied by success and omitted. +func promoteAggregateSuccessCond(chains []promoteJobChain) string { + succs := make([]string, 0, len(chains)) + for _, c := range chains { + succs = append(succs, effectiveSuccessCond(c.jobID, c.retries)) + } + if len(chains) == 1 { + return orGroup(succs) + } + exhs := make([]string, 0, len(chains)) + for _, c := range chains { + exhs = append(exhs, promoteChainFailedCond(c)) + } + return fmt.Sprintf("%s && !%s", orGroup(succs), orGroup(exhs)) +} + +// promoteAggregateResultExpr renders DEPLOY_RESULT_ for a deploy with +// retries: one value across every promotion chain and attempt. 'failure' when +// any chain exhausted — anchored on failure OR cancelled, because the raw +// per-job result this replaces could carry 'cancelled' and the finalize gate +// holds the state write on both — else 'success' when any environment +// succeeded, else 'skipped' (nothing ran). +func promoteAggregateResultExpr(chains []promoteJobChain) string { + exhs := make([]string, 0, len(chains)) + succs := make([]string, 0, len(chains)) + for _, c := range chains { + exhs = append(exhs, effectiveFailureOrCancelledCond(c.jobID, c.retries)) + succs = append(succs, effectiveSuccessCond(c.jobID, c.retries)) + } + return fmt.Sprintf("${{ %s && 'failure' || %s && 'success' || 'skipped' }}", + orGroup(exhs), orGroup(succs)) +} + +func (g *PromoteGenerator) writeDeployJobs(sb *strings.Builder) error { // Skip deploy jobs if no environments if len(g.config.Environments) == 0 { - return + return nil } // The prod deploy job targets the release environment, which is role-aware: @@ -894,6 +1079,16 @@ func (g *PromoteGenerator) writeDeployJobs(sb *strings.Builder) { // put an undeclared dry_run into the with: block. declared := g.declaredDeployInputs(d.Workflow, d.Inputs) + if hasInputs && d.Retries > 0 { + // Retries declared on an inputs deploy (#626): replace the matrix + // with one job per promotion target, each with its own ladder. See + // writePerEnvDeployJobs for why the matrix cannot be retried. + if err := g.writePerEnvDeployJobs(sb, &d, outputName); err != nil { + return err + } + continue + } + fmt.Fprintf(sb, " deploy-%s:\n", d.Name) if hasInputs { @@ -981,34 +1176,24 @@ func (g *PromoteGenerator) writeDeployJobs(sb *strings.Builder) { // must be declared inside the reusable workflow's own job. writeCallbackPermissions(sb, " ", d.Permissions) fmt.Fprintf(sb, " uses: %s\n", normalizeWorkflowPath(d.Workflow)) - sb.WriteString(" with:\n") - sb.WriteString(" environment: ${{ needs.preflight.outputs.target_env }}\n") - sb.WriteString(" sha: ${{ needs.preflight.outputs.source_sha }}\n") - // Pass image_tag if the deploy workflow accepts it - if g.deployHasInput(d.Name, "image_tag") { - sb.WriteString(" image_tag: ${{ needs.preflight.outputs.source_image_tag }}\n") - } - // Additively pass image_digest (the immutable artifact id) when the - // deploy workflow declares it. This is gated independently of image_tag - // so deploys that only want the digest, only the tag, or both all work. - if g.deployHasInput(d.Name, "image_digest") { - sb.WriteString(" image_digest: ${{ needs.preflight.outputs.source_image_digest }}\n") - } - // When the callback declares the dry_run input, forward the dispatch - // input so it can emulate internally. A cross-repo callee is assumed - // to declare it (the standard contract). - if declared["dry_run"] { - sb.WriteString(" dry_run: ${{ github.event.inputs.dry_run == 'true' }}\n") - } + g.writeSingleDeployWith(sb, &d) } writeSecretsBlock(sb, d.Secrets) + + // A no-inputs deploy with retries gets a plain ladder on its single + // job: it already targets one environment (#626). + if d.Retries > 0 { + if err := g.writeDeployRetryLadder(sb, &d, + fmt.Sprintf("deploy-%s", d.Name), fmt.Sprintf("Deploy %s", d.Name), + func(sb *strings.Builder) { g.writeSingleDeployWith(sb, &d) }); err != nil { + return err + } + } } // Add prod deploy jobs for cascade mode (separate from intermediate promotions) // These run in parallel with other deploy jobs when has_prod_deployment == 'true' for _, d := range g.config.Deploys { - // Same declared-inputs gating as the non-prod deploy paths (#698). - declared := g.declaredDeployInputs(d.Workflow, d.Inputs) fmt.Fprintf(sb, " deploy-%s-prod:\n", d.Name) fmt.Fprintf(sb, " name: Deploy %s (%s)\n", d.Name, finalEnv) sb.WriteString(" needs: [preflight, promote]\n") @@ -1026,27 +1211,201 @@ func (g *PromoteGenerator) writeDeployJobs(sb *strings.Builder) { // workflow's own job. writeCallbackPermissions(sb, " ", d.Permissions) fmt.Fprintf(sb, " uses: %s\n", normalizeWorkflowPath(d.Workflow)) - sb.WriteString(" with:\n") - fmt.Fprintf(sb, " environment: %s\n", finalEnv) - sb.WriteString(" sha: ${{ needs.preflight.outputs.prod_sha }}\n") - // Pass image_tag if the deploy workflow accepts it - if g.deployHasInput(d.Name, "image_tag") { - sb.WriteString(" image_tag: ${{ needs.preflight.outputs.prod_version }}\n") - } - // image_digest is intentionally not threaded on the prod path: there is no - // prod_image_digest preflight output today, so prod-path digest pinning is - // not yet supported. - // When the callback declares the dry_run input, forward the dispatch - // input so it can emulate internally. A cross-repo callee is assumed - // to declare it (the standard contract). - if declared["dry_run"] { - sb.WriteString(" dry_run: ${{ github.event.inputs.dry_run == 'true' }}\n") - } + g.writeProdDeployWith(sb, &d, finalEnv) writeSecretsBlock(sb, d.Secrets) + + // The prod job is already single-environment, so retries attaches a + // plain ladder to it directly (#626). + if d.Retries > 0 { + if err := g.writeDeployRetryLadder(sb, &d, + fmt.Sprintf("deploy-%s-prod", d.Name), fmt.Sprintf("Deploy %s (%s)", d.Name, finalEnv), + func(sb *strings.Builder) { g.writeProdDeployWith(sb, &d, finalEnv) }); err != nil { + return err + } + } } // Write external deploy jobs (for multi-repo orchestration) g.writeExternalDeployJobs(sb, finalEnv) + return nil +} + +// writeSingleDeployWith emits the with: block of the single (no declared +// inputs) deploy job: preflight's target environment and source sha, plus the +// optional image inputs. The dry_run passthrough is gated on the callee's +// declared workflow_call inputs (#705), the same rule every deploy lane +// follows. Extracted so the job and its retry shims share one emission. +func (g *PromoteGenerator) writeSingleDeployWith(sb *strings.Builder, d *config.DeployConfig) { + sb.WriteString(" with:\n") + sb.WriteString(" environment: ${{ needs.preflight.outputs.target_env }}\n") + sb.WriteString(" sha: ${{ needs.preflight.outputs.source_sha }}\n") + // Pass image_tag if the deploy workflow accepts it + if g.deployHasInput(d.Name, "image_tag") { + sb.WriteString(" image_tag: ${{ needs.preflight.outputs.source_image_tag }}\n") + } + // Additively pass image_digest (the immutable artifact id) when the + // deploy workflow declares it. This is gated independently of image_tag + // so deploys that only want the digest, only the tag, or both all work. + if g.deployHasInput(d.Name, "image_digest") { + sb.WriteString(" image_digest: ${{ needs.preflight.outputs.source_image_digest }}\n") + } + // When the callback declares the dry_run input, forward the dispatch + // input so it can emulate internally. A cross-repo callee is assumed + // to declare it (the standard contract). + if g.declaredDeployInputs(d.Workflow, d.Inputs)["dry_run"] { + sb.WriteString(" dry_run: ${{ github.event.inputs.dry_run == 'true' }}\n") + } +} + +// writeProdDeployWith emits the with: block of the prod deployment job, with +// the dry_run passthrough gated on the callee's declared workflow_call inputs +// (#705) like every deploy lane. Extracted so the job and its retry shims +// share one emission. +func (g *PromoteGenerator) writeProdDeployWith(sb *strings.Builder, d *config.DeployConfig, finalEnv string) { + sb.WriteString(" with:\n") + fmt.Fprintf(sb, " environment: %s\n", finalEnv) + sb.WriteString(" sha: ${{ needs.preflight.outputs.prod_sha }}\n") + // Pass image_tag if the deploy workflow accepts it + if g.deployHasInput(d.Name, "image_tag") { + sb.WriteString(" image_tag: ${{ needs.preflight.outputs.prod_version }}\n") + } + // image_digest is intentionally not threaded on the prod path: there is no + // prod_image_digest preflight output today, so prod-path digest pinning is + // not yet supported. + // When the callback declares the dry_run input, forward the dispatch + // input so it can emulate internally. A cross-repo callee is assumed + // to declare it (the standard contract). + if g.declaredDeployInputs(d.Workflow, d.Inputs)["dry_run"] { + sb.WriteString(" dry_run: ${{ github.event.inputs.dry_run == 'true' }}\n") + } +} + +// writeDeployRetryLadder emits the retry shims for one promote deploy job, +// re-invoking the callback through the shared writeRetryShimJob so the gate +// and chaining contract stay identical to orchestrate's ladders. The shims +// need preflight directly (their with: reads preflight outputs, which GitHub +// only exposes to direct needs) and chain on the attempt before them. +func (g *PromoteGenerator) writeDeployRetryLadder(sb *strings.Builder, d *config.DeployConfig, baseJobID, displayName string, with func(*strings.Builder)) error { + for i := 1; i <= d.Retries; i++ { + if err := writeRetryShimJob(sb, retryShimJob{ + BaseJobID: baseJobID, + DisplayName: displayName, + RetryNum: i, + NeedsBefore: []string{"preflight"}, + Permissions: d.Permissions, + Secrets: d.Secrets, + Workflow: d.Workflow, + WriteWith: func(sb *strings.Builder) error { + with(sb) + return nil + }, + }); err != nil { + return err + } + } + return nil +} + +// writePerEnvDeployJobs emits the per-environment fan-out for a deploy with +// declared inputs and retries > 0 (#626): one job per promotion target (every +// declared environment except the first), each gated on preflight's +// deploy__envs list and each with its own retry ladder. +// +// Why the matrix is replaced: a matrix job exposes ONE aggregate result — +// 'failure' if any leg failed — so a caller-side shim gated on that aggregate +// would re-invoke the callback for every leg, redeploying the environments +// that already succeeded. GitHub Actions offers no caller-side way to re-run +// only the failed legs of a dependency's matrix, so a retry must be scoped to +// the one environment whose attempt failed, which requires one job per +// environment. With no retries the matrix stays: a retry-free manifest keeps +// byte-identical output. +// +// The job id carries a -to- infix (deploy-web-to-staging) because the +// pre-existing prod deployment job is deploy--prod: a per-environment +// job for an environment literally named "prod" would otherwise collide with +// it, and GitHub rejects duplicate job keys at parse. +func (g *PromoteGenerator) writePerEnvDeployJobs(sb *strings.Builder, d *config.DeployConfig, outputName string) error { + for _, env := range g.perEnvTargetEnvs() { + envKey := strings.ReplaceAll(env, "-", "_") + jobID := fmt.Sprintf("deploy-%s-to-%s", d.Name, env) + displayName := fmt.Sprintf("Deploy %s (%s)", d.Name, env) + + fmt.Fprintf(sb, " %s:\n", jobID) + fmt.Fprintf(sb, " name: %s\n", displayName) + sb.WriteString(" needs: [preflight, promote]\n") + // The gate mirrors the matrix job's: run only when the promotion + // includes this environment, and not on a dry run unless the callback + // handles dry runs itself. An environment outside the promotion skips + // (result 'skipped'), which no sink counts as failure. + if d.SupportsDryRun { + fmt.Fprintf(sb, " if: ${{ contains(fromJSON(needs.preflight.outputs.deploy_%s_envs), '%s') }}\n", outputName, env) + } else { + fmt.Fprintf(sb, " if: ${{ github.event.inputs.dry_run != 'true' && contains(fromJSON(needs.preflight.outputs.deploy_%s_envs), '%s') }}\n", outputName, env) + } + writeCallbackPermissions(sb, " ", d.Permissions) + fmt.Fprintf(sb, " uses: %s\n", normalizeWorkflowPath(d.Workflow)) + g.writePerEnvWithInputs(sb, d, outputName, env, envKey) + writeSecretsBlock(sb, d.Secrets) + + if err := g.writeDeployRetryLadder(sb, d, jobID, displayName, func(sb *strings.Builder) { + g.writePerEnvWithInputs(sb, d, outputName, env, envKey) + }); err != nil { + return err + } + } + return nil +} + +// writePerEnvWithInputs emits the with: block of one per-environment deploy +// job. It mirrors the matrix job's contract exactly — the environment and +// (when the callback declares it) the sha from the promotion entry, +// passthrough expressions verbatim, every other declared input resolved at +// promotion time — but reads each value from the per-environment +// resolved-input JSON preflight emitted instead of a matrix context. +func (g *PromoteGenerator) writePerEnvWithInputs(sb *strings.Builder, d *config.DeployConfig, outputName, env, envKey string) { + sb.WriteString(" with:\n") + // The job stands for exactly this environment, which the gate already + // proved is in the promotion, so the environment input is the literal. + // Skip when the manifest wires environment explicitly so the with: block + // never emits a duplicate mapping key (the input loop below covers it). + if _, ok := d.Inputs["environment"]; !ok { + fmt.Fprintf(sb, " environment: %s\n", env) + } + if _, ok := d.Inputs["sha"]; !ok && g.deployHasInput(d.Name, "sha") { + fmt.Fprintf(sb, " sha: ${{ fromJSON(needs.preflight.outputs.deploy_%s_inputs_%s).sha }}\n", outputName, envKey) + } + // When the callback declares the dry_run input, forward the dispatch + // input so it can emulate internally (#705's declared-inputs rule, the + // same one the matrix path applies). Skip when the manifest already wires + // dry_run as an explicit input, so the with: block never emits a duplicate + // mapping key (the input loop below threads it from the per-environment + // JSON, the fan-out's counterpart of the matrix entry). + if _, ok := d.Inputs["dry_run"]; !ok && g.declaredDeployInputs(d.Workflow, d.Inputs)["dry_run"] { + sb.WriteString(" dry_run: ${{ github.event.inputs.dry_run == 'true' }}\n") + } + // Passthrough-expression inputs (e.g. ${{ vars.X }}) survive verbatim, as + // on the matrix path. + passthrough := passthroughInputNames(d) + passSet := make(map[string]struct{}, len(passthrough)) + for _, name := range passthrough { + passSet[name] = struct{}{} + fmt.Fprintf(sb, " %s: %s\n", name, passthroughInputValue(d, name)) + } + // Remaining inputs (literals, resolved state.* refs, and the values the + // matrix path keyed on matrix.*) read from the per-environment JSON. + // Sorted for deterministic output. + inputNames := make([]string, 0, len(d.Inputs)) + for inputName := range d.Inputs { + if _, ok := passSet[inputName]; ok { + continue + } + inputNames = append(inputNames, inputName) + } + sort.Strings(inputNames) + for _, inputName := range inputNames { + fmt.Fprintf(sb, " %s: ${{ fromJSON(needs.preflight.outputs.deploy_%s_inputs_%s).%s }}\n", + inputName, outputName, envKey, inputName) + } } func (g *PromoteGenerator) writeExternalDeployJobs(sb *strings.Builder, finalEnv string) { @@ -1124,31 +1483,40 @@ func (g *PromoteGenerator) writeRollbackJobs(sb *strings.Builder) { return } - // Collect all deploy job names for failure detection - var allDeployJobs []string - for _, d := range g.config.Deploys { - allDeployJobs = append(allDeployJobs, fmt.Sprintf("deploy-%s", d.Name)) - allDeployJobs = append(allDeployJobs, fmt.Sprintf("deploy-%s-prod", d.Name)) + // Collect every deploy chain (base job plus retry shims, #626) for the + // needs: lists and the failure conditions. A deploy with retries + // contributes one chain per promotion target plus the prod ladder; the + // failure condition for each chain is its exhaustion — the base failed and + // no retry shim rescued it — so a retry that saved an environment never + // triggers a rollback. At retries 0 every chain collapses to the bare job + // result, keeping a retry-free manifest byte-identical. + var allChains []promoteJobChain + for i := range g.config.Deploys { + allChains = append(allChains, g.deployChains(&g.config.Deploys[i])...) } for _, ext := range g.config.External { for _, d := range ext.Deploys { - allDeployJobs = append(allDeployJobs, fmt.Sprintf("deploy-%s", d.Name)) - allDeployJobs = append(allDeployJobs, fmt.Sprintf("deploy-%s-prod", d.Name)) + // External deploys declare no retries (their config carries no + // such field), so each is a bare chain on its two jobs. + allChains = append(allChains, + promoteJobChain{jobID: fmt.Sprintf("deploy-%s", d.Name)}, + promoteJobChain{jobID: fmt.Sprintf("deploy-%s-prod", d.Name)}) } } - // Build the failure condition: any deploy job failed + var allDeployJobs []string var failureConditions []string - for _, job := range allDeployJobs { - failureConditions = append(failureConditions, fmt.Sprintf("needs.%s.result == 'failure'", job)) + for _, chain := range allChains { + allDeployJobs = append(allDeployJobs, chain.jobIDs()...) + failureConditions = append(failureConditions, promoteChainFailedCond(chain)) } anyFailure := strings.Join(failureConditions, " || ") sb.WriteString(" # Rollback jobs - revert successful deploys if any deploy fails\n") // Write rollback jobs for local deploys - for _, d := range g.config.Deploys { - jobName := fmt.Sprintf("deploy-%s", d.Name) + for i := range g.config.Deploys { + d := &g.config.Deploys[i] fmt.Fprintf(sb, " rollback-%s:\n", d.Name) fmt.Fprintf(sb, " name: Rollback %s\n", d.Name) @@ -1157,7 +1525,17 @@ func (g *PromoteGenerator) writeRollbackJobs(sb *strings.Builder) { sb.WriteString(" always() &&\n") sb.WriteString(" needs.preflight.outputs.rollback_on_failure == 'true' &&\n") sb.WriteString(" needs.preflight.outputs.rollback_sha != '' &&\n") - fmt.Fprintf(sb, " needs.%s.result == 'success' &&\n", jobName) + // The deploy's own success gate. At retries 0 this is the bare job + // result (the matrix/single job). With retries it is the aggregate + // across the deploy's promotion chains — matrix-'success' semantics: + // every chain that ran ended in success, and at least one ran — so a + // chain a retry rescued still counts as the deploy's success, and an + // exhausted chain in any environment means the deploy failed. + if d.Retries > 0 { + fmt.Fprintf(sb, " %s &&\n", promoteAggregateSuccessCond(g.promotionChains(d))) + } else { + fmt.Fprintf(sb, " needs.deploy-%s.result == 'success' &&\n", d.Name) + } fmt.Fprintf(sb, " (%s)\n", anyFailure) writeCallbackPermissions(sb, " ", d.Permissions) fmt.Fprintf(sb, " uses: %s\n", normalizeWorkflowPath(d.Workflow)) @@ -1232,14 +1610,25 @@ func (g *PromoteGenerator) writeFinalizeJob(sb *strings.Builder) { // writeDeployJobs). With no environments there are no deploy jobs, so // referencing them in needs: would produce a "needs job X which does not // exist" parse error on GitHub. + // + // A deploy with retries contributes its whole ladder — every promotion + // chain (per-environment jobs at retries > 0, #626) plus the prod ladder — + // because the DEPLOY_RESULT aggregate below reads each chain's result, and + // GitHub only exposes a needs: entry's result to direct dependents. needs := []string{"preflight", "promote"} if len(g.config.Environments) > 0 { - for _, d := range g.config.Deploys { - needs = append(needs, fmt.Sprintf("deploy-%s", d.Name)) + for i := range g.config.Deploys { + for _, chain := range g.promotionChains(&g.config.Deploys[i]) { + needs = append(needs, chain.jobIDs()...) + } } // Add prod deploy jobs - for _, d := range g.config.Deploys { - needs = append(needs, fmt.Sprintf("deploy-%s-prod", d.Name)) + for i := range g.config.Deploys { + prodChain := promoteJobChain{ + jobID: fmt.Sprintf("deploy-%s-prod", g.config.Deploys[i].Name), + retries: g.config.Deploys[i].Retries, + } + needs = append(needs, prodChain.jobIDs()...) } // Add external deploy jobs for _, ext := range g.config.External { @@ -1503,9 +1892,20 @@ func (g *PromoteGenerator) writeFinalizeJob(sb *strings.Builder) { // deploy jobs exist. if len(g.config.Environments) > 0 { sb.WriteString(" DEPLOYS_TO_RUN: ${{ needs.preflight.outputs.deploys_to_run }}\n") - for _, d := range g.config.Deploys { + for i := range g.config.Deploys { + d := &g.config.Deploys[i] envKey := "DEPLOY_RESULT_" + strings.ToUpper(strings.ReplaceAll(d.Name, "-", "_")) - fmt.Fprintf(sb, " %s: ${{ needs.deploy-%s.result }}\n", envKey, d.Name) + if d.Retries > 0 { + // One aggregate value across the deploy's promotion chains and + // attempts (#626): 'failure' if any chain exhausted, 'success' + // if any environment succeeded, else 'skipped'. The finalize + // CLI gate consumes exactly these three behaviors: failure (or + // the cancelled it folds in) holds the env pointer, success + // records the per-deploy row, skipped does neither. + fmt.Fprintf(sb, " %s: %s\n", envKey, promoteAggregateResultExpr(g.promotionChains(d))) + } else { + fmt.Fprintf(sb, " %s: ${{ needs.deploy-%s.result }}\n", envKey, d.Name) + } } } sb.WriteString(" run: |\n") @@ -1549,7 +1949,8 @@ func (g *PromoteGenerator) writeFinalizeJob(sb *strings.Builder) { // writeNativeDeploymentSteps wires the GitHub Deployments API lifecycle into the // promote finalize job. A promotion targets a single environment resolved at run // time (needs.preflight.outputs.target_env), so the Deployment targets that -// name. The terminal status reflects whether every deploy job succeeded. +// name. The terminal status reflects whether every deploy chain (a job and its +// retry shims, #626) succeeded. func (g *PromoteGenerator) writeNativeDeploymentSteps(sb *strings.Builder) { if !nativeDeploymentsEnabled(g.config) { return @@ -1560,16 +1961,26 @@ func (g *PromoteGenerator) writeNativeDeploymentSteps(sb *strings.Builder) { resultExpr := "success" if len(g.config.Environments) > 0 && len(g.config.Deploys) > 0 { var conds []string - for _, d := range g.config.Deploys { + for i := range g.config.Deploys { + d := &g.config.Deploys[i] // A promotion runs a subset of deploys (only those whose scope // includes the target env), and the prod deploy runs only in cascade // mode, so a deploy job legitimately SKIPS. A skip is not a deploy - // failure, so success-or-skipped is the per-job success signal. The - // prod job is included so a failed prod deploy is not omitted from - // the Deployment's terminal status. - for _, job := range []string{fmt.Sprintf("deploy-%s", d.Name), fmt.Sprintf("deploy-%s-prod", d.Name)} { - conds = append(conds, fmt.Sprintf("(needs.%s.result == 'success' || needs.%s.result == 'skipped')", job, job)) + // failure, so success-or-skipped is the per-chain success signal. + // The prod ladder is included so a failed prod deploy is not omitted + // from the Deployment's terminal status. With retries each chain's + // success is its effective result (any attempt succeeded), so a + // chain a retry rescued reports success here too. + for _, chain := range g.promotionChains(d) { + conds = append(conds, fmt.Sprintf("(%s || needs.%s.result == 'skipped')", + effectiveSuccessCond(chain.jobID, chain.retries), chain.jobID)) + } + prodChain := promoteJobChain{ + jobID: fmt.Sprintf("deploy-%s-prod", d.Name), + retries: d.Retries, } + conds = append(conds, fmt.Sprintf("(%s || needs.%s.result == 'skipped')", + effectiveSuccessCond(prodChain.jobID, prodChain.retries), prodChain.jobID)) } resultExpr = fmt.Sprintf("${{ (%s) && 'success' || 'failure' }}", strings.Join(conds, " && ")) } diff --git a/internal/generate/promote_retry_test.go b/internal/generate/promote_retry_test.go index 3709a6c5..632f419e 100644 --- a/internal/generate/promote_retry_test.go +++ b/internal/generate/promote_retry_test.go @@ -486,27 +486,30 @@ func TestPromoteRetry_SkippedLegIsNotFailure(t *testing.T) { // TestPromoteRetry_NativeDeploymentsJudgesEffectiveResult pins the native // deployments terminal status: every chain (per-environment legs and the prod // ladder) contributes success-or-skipped on its effective result, so a rescued -// chain reports success and an exhausted one failure. +// chain reports success and an exhausted one failure. The retry-free form is +// pinned too: it must stay byte-identical to the pre-retry emission. func TestPromoteRetry_NativeDeploymentsJudgesEffectiveResult(t *testing.T) { - cfg := &config.TrunkConfig{ - TrunkBranch: "main", - Environments: config.EnvNames("dev", "staging", "prod"), - Deployments: &config.DeploymentsConfig{Enabled: boolPtr(true)}, - Deploys: []config.DeployConfig{ - { - Name: "web", - Workflow: ".github/workflows/deploy.yaml", - Triggers: []string{"src/**"}, - Retries: 1, + newConfig := func(retries int) *config.TrunkConfig { + return &config.TrunkConfig{ + TrunkBranch: "main", + Environments: config.EnvNames("dev", "staging", "prod"), + Deployments: &config.DeploymentsConfig{Enabled: boolPtr(true)}, + Deploys: []config.DeployConfig{ + { + Name: "web", + Workflow: ".github/workflows/deploy.yaml", + Triggers: []string{"src/**"}, + Retries: retries, + }, }, - }, + } } dir := t.TempDir() require.NoError(t, os.MkdirAll(filepath.Join(dir, ".github/workflows"), 0o755)) require.NoError(t, os.WriteFile(filepath.Join(dir, ".github/workflows/deploy.yaml"), []byte("on:\n workflow_call:\n inputs:\n environment:\n type: string\n sha:\n type: string\n"), 0o644)) - result, err := NewPromoteGenerator(cfg, dir).Generate() + result, err := NewPromoteGenerator(newConfig(1), dir).Generate() require.NoError(t, err) assert.Contains(t, result, @@ -514,6 +517,13 @@ func TestPromoteRetry_NativeDeploymentsJudgesEffectiveResult(t *testing.T) { assert.Contains(t, result, "(needs.deploy-web-prod.result == 'success' || needs.deploy-web-prod-retry-1.result == 'success' || needs.deploy-web-prod.result == 'skipped')") assert.Contains(t, result, "&& 'success' || 'failure' }}") + + // The retry-free form stays exactly as it was. + zero, err := NewPromoteGenerator(newConfig(0), dir).Generate() + require.NoError(t, err) + assert.Contains(t, zero, + "(needs.deploy-web.result == 'success' || needs.deploy-web.result == 'skipped') && "+ + "(needs.deploy-web-prod.result == 'success' || needs.deploy-web-prod.result == 'skipped')") } // TestPromoteRetry_ZeroRetriesIsByteFrozen pins the frozen boundary: a @@ -565,8 +575,6 @@ func TestPromoteRetry_ZeroRetriesIsByteFrozen(t *testing.T) { assert.Contains(t, a, "needs.deploy-web.result == 'success' &&") assert.Contains(t, a, "needs.deploy-web.result == 'failure'") assert.Contains(t, a, "DEPLOY_RESULT_WEB: ${{ needs.deploy-web.result }}\n") - assert.Contains(t, a, - "(needs.deploy-web.result == 'success' || needs.deploy-web.result == 'skipped')") // No retry artifact of any kind. assert.NotContains(t, a, "-retry-") @@ -579,10 +587,12 @@ func TestPromoteRetry_ZeroRetriesIsByteFrozen(t *testing.T) { // sinks change, and the retry-free deploy keeps every retry-free form. func TestPromoteRetry_MixedManifestsKeepSinksPerDeploy(t *testing.T) { cfg, dir := promoteRetriesFixture(t, 1, true) + // edge declares inputs but no retries, so it keeps the matrix path. cfg.Deploys = append(cfg.Deploys, config.DeployConfig{ Name: "edge", Workflow: ".github/workflows/deploy.yaml", Triggers: []string{"edge/**"}, + Inputs: map[string]interface{}{"cluster": "edge-cluster"}, }) result, err := NewPromoteGenerator(cfg, dir).Generate() From 1387b1b81523b0cdc50b63e7ecbc396ca5e2d6fa Mon Sep 17 00:00:00 2001 From: Ray Karnes Date: Wed, 2 Dec 2026 11:47:50 -0700 Subject: [PATCH 3/5] test(e2e): pin promote retry exhaustion and its rollback trigger boundary Add promote/promote-retries-exhaustion.yaml, the executing scenario for the promote retry fan-out (#626). app declares manifest inputs plus retries: 1, so the promote fans it out per promotion target; a marker commit arms the app callback to fail test deploys, so the second dev-to-test promote exhausts app's test chain and the run concludes in failure with the asymmetric deploy outcome (infra deployed, app failed) that is the sole rollback-on-failure trigger. Finalize holds the test pointer at the pre-promote SHA through the DEPLOY_RESULT aggregate. The scenario states its boundaries honestly, the way 73-deploy-retries.yaml does: act v0.2.99 skips every later stage after a failed reusable-workflow job, so the rollback job's own execution and the fail-then-rescue path are not observable here and are asserted through the trigger boundary (plus the emitted YAML, unit tests, and the actionlint feature matrix) instead. The emitted assertions are verified against real generated output for this exact manifest. Register the scenario under the promote kind in the coverage registry. Signed-off-by: Ray Karnes --- .../promote/promote-retries-exhaustion.yaml | 287 ++++++++++++++++++ internal/coverage/registry.yaml | 1 + 2 files changed, 288 insertions(+) create mode 100644 e2e/scenarios/promote/promote-retries-exhaustion.yaml diff --git a/e2e/scenarios/promote/promote-retries-exhaustion.yaml b/e2e/scenarios/promote/promote-retries-exhaustion.yaml new file mode 100644 index 00000000..3da82008 --- /dev/null +++ b/e2e/scenarios/promote/promote-retries-exhaustion.yaml @@ -0,0 +1,287 @@ +name: "Promote retries exhaust per environment and only then trigger rollback" +description: | + Exercises the promote retry fan-out (#626) end to end at its observable + boundaries. app declares manifest inputs plus retries: 1, so the generated + promote replaces app's matrix with one job per promotion target + (deploy-app-to-test, deploy-app-to-prod), each with its own one-shim ladder; + infra declares neither, so it keeps today's single retry-free job. The app + callback always fails once a marker file is present on the promoted SHA and + the deploy targets test, so the dev-to-test promote exhausts app's test + chain and the run concludes in failure with the asymmetric deploy outcome + (infra deployed, app failed) that is the sole trigger for + rollback-on-failure. + + What is asserted, and at which boundary, is stated honestly: + + 1. Emitted (step 1): the fan-out jobs, their contains() gates on preflight's + deploy_app_envs output, the per-environment with: reads, the shim gates + chained on their predecessor, and every result sink's effective-result + wiring (the rollback gate's exhaustion clauses, DEPLOY_RESULT_APP as one + three-way aggregate, the retry-free infra deploy keeping today's bare + forms). + + 2. Executing (final step): the app callback body genuinely ran and failed + (expect_log proves the body, not just a job object), the promote + concludes in failure, and finalize holds the test env pointer at the SHA + test held before the promote (DEPLOY_RESULT_APP's 'failure' aggregate + drives the same finalize gate the per-job result always did). + + 3. NOT asserted, and why: the rollback job's own execution, and the retry + shim's, are not observable here. act v0.2.99 skips every later stage + after a failed reusable-workflow job, so rollback-infra (a uses: job + needing the failed deploy) never runs in this harness; its trigger + boundary — the run failing with infra deployed and app exhausted — is + what the final step asserts instead. And fail-then-rescue (a first + attempt failing, the shim re-running and succeeding) cannot be expressed + by this harness at all, for the structural reasons 73-deploy-retries.yaml + documents: each shim is a separate job with its own workspace (no local + marker counting), no artifact server (no cross-job state), and identical + with: inputs (no self-discrimination). The rescue path is therefore + pinned as unit tests (internal/generate/promote_retry_test.go) and the + parse-level acceptance of the fan-out by the actionlint feature matrix + (case promote_per_env_retries), not here. + +config: + trunk_branch: main + environments: [dev, test, prod] + builds: + - name: app + workflow: build.yaml + triggers: ["src/**"] + deploys: + # infra is a reusable workflow that always succeeds and declares no + # manifest inputs and no retries, so the generated promote keeps today's + # single retry-free deploy job for it (the mixed-manifest coexistence). + - name: infra + workflow: .github/workflows/deploy-infra.yaml + triggers: ["**"] + # app declares inputs plus retries: 1, so promote fans it out to one job + # per promotion target with a one-shim ladder each. It fails its deploy + # when the marker file is present on the promoted SHA and the target is + # test, which exhausts the test chain on the second promote. + - name: app + workflow: .github/workflows/deploy-app.yaml + triggers: ["**"] + retries: 1 + inputs: + message: "deploying via promote" + env_inputs: + prod: + message: "deploying via promote to prod" + +steps: + - name: "Commit app source and custom deploy workflows" + action: commit + commit: + message: "feat: add app source and deploy callbacks" + files: + src/app.go: | + package main + + func main() {} + # infra deploy: always succeeds. Declares the environment/sha inputs + # the generated promote workflow threads. Its inner job is named + # infradeploy so act keys it distinctly from the app deploy and from + # build-app. + .github/workflows/deploy-infra.yaml: | + name: deploy-infra + on: + workflow_call: + inputs: + environment: + required: false + type: string + sha: + required: false + type: string + jobs: + infradeploy: + runs-on: ubuntu-latest + steps: + - run: echo "infra deployed env=${{ inputs.environment }} sha=${{ inputs.sha }}" + # app deploy: probes the marker from the public repo at the promoted + # SHA over the internal gitea alias (no checkout step, no auth), and + # fails when the marker is present at that SHA and the target is + # test. The marker is committed after the first promote, so the first + # promote to test (SHA without the marker) succeeds and the second + # (SHA with the marker) fails. The environment guard keeps the + # orchestrate deploys (which target dev) green even after the marker + # SHA exists. Declares the message input the manifest wires, plus the + # callback contract's environment/sha. Its inner job is named + # appdeploy so act keys it distinctly. + .github/workflows/deploy-app.yaml: | + name: deploy-app + on: + workflow_call: + inputs: + environment: + required: false + type: string + sha: + required: false + type: string + message: + required: false + type: string + jobs: + appdeploy: + runs-on: ubuntu-latest + steps: + - name: Fail when marker present for a test deploy + env: + DEPLOY_ENV: ${{ inputs.environment }} + DEPLOY_SHA: ${{ inputs.sha }} + run: | + set -eu + # No actions/checkout: act resolves a reusable callback's + # actions/checkout by cloning the action from the per-scenario + # gitea, which rejects the unauthenticated clone. Instead probe + # the marker straight from the public repo at the promoted SHA + # over the internal gitea alias, which needs no auth. + git clone --quiet --no-checkout "http://gitea:3000/${GITHUB_REPOSITORY}.git" /tmp/markerchk + git -C /tmp/markerchk fetch --quiet origin "$DEPLOY_SHA" + if [ "$DEPLOY_ENV" = "test" ] && git -C /tmp/markerchk cat-file -e "$DEPLOY_SHA:deploy/fail-marker" 2>/dev/null; then + echo "cascade-e2e-retry-probe: marker present at $DEPLOY_SHA and target is test: deploy-app failing on purpose" + exit 1 + fi + echo "cascade-e2e-retry-probe: app deployed env=$DEPLOY_ENV sha=$DEPLOY_SHA message=${{ inputs.message }}" + expect: + workflow_files: + - path: ".github/workflows/promote.yaml" + contains: + # The fan-out: one job per promotion target (test and prod, never + # dev), replacing app's matrix. The -to- infix keeps the prod leg + # distinct from the pre-existing deploy-app-prod job. + - "deploy-app-to-test:" + - "deploy-app-to-prod:" + - "deploy-app-prod:" + # Each job runs only when the promotion includes its environment. + - "if: ${{ github.event.inputs.dry_run != 'true' && contains(fromJSON(needs.preflight.outputs.deploy_app_envs), 'test') }}" + - "if: ${{ github.event.inputs.dry_run != 'true' && contains(fromJSON(needs.preflight.outputs.deploy_app_envs), 'prod') }}" + # Preflight surfaces the fan-out contract: the envs list and each + # target's resolved-input JSON, and no matrix. + - "deploy_app_envs: ${{ steps.build-matrices.outputs.deploy_app_envs }}" + - "deploy_app_inputs_test: ${{ steps.build-matrices.outputs.deploy_app_inputs_test }}" + - "deploy_app_inputs_prod: ${{ steps.build-matrices.outputs.deploy_app_inputs_prod }}" + # The with: block reads the per-environment resolved inputs. + - "message: ${{ fromJSON(needs.preflight.outputs.deploy_app_inputs_test).message }}" + - "message: ${{ fromJSON(needs.preflight.outputs.deploy_app_inputs_prod).message }}" + # The one-shim ladder per environment, gated on its predecessor + # failing, with the !cancelled() status function so GitHub's + # implicit needs-success gate cannot skip the shim exactly when + # its predecessor failed. + - "deploy-app-to-test-retry-1:" + - "if: ${{ !cancelled() && needs.deploy-app-to-test.result == 'failure' }}" + - "if: ${{ !cancelled() && needs.deploy-app-to-prod.result == 'failure' }}" + - "needs: [preflight, deploy-app-to-test]" + # The retry-free infra deploy keeps today's single job and bare + # sinks (the mixed-manifest boundary). + - "deploy-infra:" + - "DEPLOY_RESULT_INFRA: ${{ needs.deploy-infra.result }}" + # app's aggregate: failure when any chain exhausted, success when + # any environment succeeded, else skipped. The all-skipped case + # must stay 'skipped' for the finalize gate. + - "DEPLOY_RESULT_APP: ${{ ((contains(fromJSON('[\"failure\", \"cancelled\"]'), needs.deploy-app-to-test.result) && !(needs.deploy-app-to-test-retry-1.result == 'success')) || (contains(fromJSON('[\"failure\", \"cancelled\"]'), needs.deploy-app-to-prod.result) && !(needs.deploy-app-to-prod-retry-1.result == 'success'))) && 'failure' || (needs.deploy-app-to-test.result == 'success' || needs.deploy-app-to-test-retry-1.result == 'success' || needs.deploy-app-to-prod.result == 'success' || needs.deploy-app-to-prod-retry-1.result == 'success') && 'success' || 'skipped' }}" + # The rollback gate fires only when some environment's chain is + # exhausted, never when a retry rescued it; the trigger clauses + # carry the rescue exemption. + - "(needs.deploy-app-to-test.result == 'failure' && !(needs.deploy-app-to-test-retry-1.result == 'success'))" + - "(needs.deploy-app-prod.result == 'failure' && !(needs.deploy-app-prod-retry-1.result == 'success'))" + # needs:/if: agreement: the aggregate readers list every chain, + # in manifest order (infra first, then app, then the prod jobs). + - "needs: [preflight, promote, deploy-infra, deploy-app-to-test, deploy-app-to-test-retry-1, deploy-app-to-prod, deploy-app-to-prod-retry-1, deploy-infra-prod, deploy-app-prod, deploy-app-prod-retry-1]" + not_contains: + # retries: 1 emits exactly one shim per environment. + - "deploy-app-to-test-retry-2:" + # The matrix is gone for the retried deploy, and no per-env job + # may target the first environment (never a promotion target). + - "deploy_app_matrix" + - "deploy-app-to-dev" + # The retry-free infra deploy gains no ladder. + - "deploy-infra-retry-" + + - name: "Orchestrate the clean commit into dev" + action: orchestrate + expect: + state: + dev: + sha: commit1 + # The orchestrate deploys target dev, so the marker guard does not fire. + jobs: + infradeploy: success + appdeploy: success + + - name: "First promote dev to test succeeds and populates test state" + action: promote + promote: + mode: cascade + target: test + expect: + state: + test: + sha: commit1 + jobs: + preflight: success + promote: success + # act keys reusable deploys by their inner job name (infradeploy / + # appdeploy), not the caller job id (deploy-infra, deploy-app-to-test). + infradeploy: success + appdeploy: success + + - name: "Commit the fail marker so the next app deploy fails" + action: commit + commit: + message: "chore: arm deploy-app failure marker" + files: + deploy/fail-marker: | + fail the app deploy on the next promote + + - name: "Orchestrate the marker commit into dev" + action: orchestrate + expect: + state: + dev: + sha: commit2 + # The orchestrate deploys target dev, so the marker guard does not fire + # and both deploys stay green even though the marker now exists on HEAD. + jobs: + infradeploy: success + appdeploy: success + + - name: "Promote with retries: app's test chain exhausts, run fails, test pointer held" + action: promote + promote: + mode: cascade + target: test + rollback_on_failure: true + expect_failure: true + # Re-read state after the failed run so the assertion below observes + # what finalize actually committed (finalize runs under always()). + sync_state_on_failure: true + expect: + jobs: + preflight: success + promote: success + # The asymmetric deploy outcome is the rollback trigger: infra + # succeeded, app's test chain exhausted (base failed, and the single + # retry re-invoked the same callback against the same marker and + # failed again — act collapses all of app's invocations onto the one + # inner job key, so the exhaustion is observed as appdeploy's + # failure). With rollback_on_failure=true and a non-empty preflight + # rollback_sha, the generated rollback-infra job re-deploys infra at + # the SHA test held before this promote on real GitHub; act skips + # every later stage after a failed reusable-workflow job, so the + # rollback is asserted through its trigger boundary here (see the + # description). + infradeploy: success + appdeploy: failure + # Proves the callback BODY executed, not merely that a job object + # exists. + expect_log: "cascade-e2e-retry-probe: marker present" + state: + # The env pointer must NOT advance to commit2: app's test chain + # exhausted, so DEPLOY_RESULT_APP reports 'failure' and finalize + # holds the pointer at commit1 (the sha test held before this + # promote), exactly as a plain failed deploy always did. + test: + sha: commit1 diff --git a/internal/coverage/registry.yaml b/internal/coverage/registry.yaml index 8131122c..fca173b0 100644 --- a/internal/coverage/registry.yaml +++ b/internal/coverage/registry.yaml @@ -23,6 +23,7 @@ kinds: scenarios: - 04-cascade-promotion.yaml - 50-component-promote-fanout.yaml + - promote/promote-retries-exhaustion.yaml external-update: summary: Primary-repo coordination workflow that adopts deploy updates from external repositories. From 338f636354696829522910e01ddc20f97863f253 Mon Sep 17 00:00:00 2001 From: Ray Karnes Date: Wed, 2 Dec 2026 11:50:21 -0700 Subject: [PATCH 4/5] docs: retries applies to promote; run_policy and on_failure stay trunk-only Update the manifest reference's Policy fields to the #626 design: retries now applies to trunk runs and promotions alike, with a note explaining the per-environment fan-out (deploy--to- jobs, one ladder per promotion target), the effective-result sinks (rollback exhaustion, DEPLOY_RESULT aggregate, deployments status), and the two stated consequences (rollout fail_fast/max_parallel do not apply while retries fans a deploy out; the publish marker runs no deploy legs). run_policy and on_failure remain orchestrate-only, with the reason: promote has no dependency skips to bind run_policy to, and the force dispatch input is promote's continue-past-failure control. Mirror the scope in the callbacks reference, the promote guide, the generated-workflows deploy strategy block, and the coverage matrix, and add the CHANGELOG entry. Signed-off-by: Ray Karnes --- CHANGELOG.md | 24 +++++++++++++++ docs/src/content/docs/guides/promote.md | 6 ++-- .../content/docs/internals/coverage-matrix.md | 2 +- docs/src/content/docs/reference/callbacks.md | 2 +- .../docs/reference/generated-workflows.md | 2 ++ docs/src/content/docs/reference/manifest.md | 30 ++++++++++++++----- 6 files changed, 54 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 86bd5bb5..c226336b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,30 @@ A `Migration` section is added to any release that bumps `schema_version`. ## [Unreleased] +### Added + +- **generate:** `retries` now applies to promote deploys (#626). A promote + deploy that declares `inputs` and `retries` replaces its matrix with one job + per promotion target (`deploy--to-`, every declared environment + except the first), each gated on preflight's new `deploy__envs` output + and each reading its resolved inputs from the new + `deploy__inputs_` outputs, so a retry re-invokes the callback for + only the environment whose attempt failed. A promote deploy without declared + inputs, and the prod deployment job, are already single-environment and get + plain retry ladders, emitted through the same shared shim writer the + orchestrate generator uses. Every promote result sink now judges the + effective result across environments and attempts: the rollback gate fires + only when some environment's ladder is exhausted (never when a retry rescued + it), `DEPLOY_RESULT_` stays a single aggregate value + (`failure`/`success`/`skipped`) that drives `cascade promote finalize`'s + pointer gate exactly as the per-job result did, and the GitHub Deployments + status reflects each ladder's effective result. Manifests that do not use + `retries` keep byte-identical promote output, including the matrix form and + its `rollout` handling (`fail_fast`/`max_parallel` do not apply to a deploy + while `retries` fans it out). `run_policy` and `on_failure` remain + orchestrate-only: promote has no dependency skips to bind `run_policy` to, + and the `force` dispatch input is promote's continue-past-failure control. + ### Fixed - **generate:** The promote workflow's rollback jobs no longer thread diff --git a/docs/src/content/docs/guides/promote.md b/docs/src/content/docs/guides/promote.md index f318e26a..be34c486 100644 --- a/docs/src/content/docs/guides/promote.md +++ b/docs/src/content/docs/guides/promote.md @@ -42,7 +42,9 @@ With `rollback_on_failure: true` (the default), a promotion is all-or-nothing. P Either way, finalize holds the environment's recorded pointer (`state..sha` and `state..version`) at its prior value when any in-scope deploy failed or was cancelled, so recorded state matches what the environment is actually running. The per-deployable rows for the deploys that did succeed are still recorded, so a re-run re-plans and retries only the failed deploy. The environment pointer advances only when every in-scope deploy succeeds. -This is a different knob from `rollout.fail_fast` and `rollout.max_parallel` on a `deploys[].rollout` entry in the manifest. Those two control the GitHub Actions `strategy:` block on that one deploy's matrix job (whether one failed matrix leg cancels the rest, and how many legs run in parallel); `rollback_on_failure` controls what promote does across deploys after a failure. See [the deploy strategy block](/cascade/reference/generated-workflows/#the-deploy-strategy-block) for the manifest-to-YAML mapping. Everything else under `rollout` (`type`, `canary`, `blue_green`) is reserved and has no effect on generated output. +This is a different knob from `rollout.fail_fast` and `rollout.max_parallel` on a `deploys[].rollout` entry in the manifest. Those two control the GitHub Actions `strategy:` block on that one deploy's matrix job (whether one failed matrix leg cancels the rest, and how many legs run in parallel); `rollback_on_failure` controls what promote does across deploys after a failure. A deploy that declares `retries` has no matrix job to tune: it fans out to one job per environment instead, so `fail_fast` and `max_parallel` do not apply to it. See [the deploy strategy block](/cascade/reference/generated-workflows/#the-deploy-strategy-block) for the manifest-to-YAML mapping. Everything else under `rollout` (`type`, `canary`, `blue_green`) is reserved and has no effect on generated output. + +A deploy that declares `retries` is retried per environment inside the same run: each per-environment job carries its own retry ladder, and a ladder that rescues an environment does not fire the rollback — only an exhausted ladder does. Finalize still holds the environment pointer when any ladder is exhausted. ## Selective deploys @@ -64,7 +66,7 @@ For the release stage, version is the latest semver tag auto-incremented from co ## What to watch - **Preflight** fails fast on a bad source/target pair, a non-ancestor SHA, or the breaking-change gate; the run log names which one. -- **Deploy jobs** run as a matrix; check each deployable's own job for its callback's output, not just the aggregate status. +- **Deploy jobs** run as a matrix (or, when the deploy declares `retries`, as one job per environment, each with its own retry ladder); check each deployable's own job for its callback's output, not just the aggregate status. - **Rollback jobs** only appear when `rollback_on_failure: true` and a deploy actually failed; their presence in the run means something needed reverting. - **Finalize** is where state, changelog, and release actually get written. A promotion that finishes deploy but fails finalize has redeployed without updating recorded state; rerun finalize rather than the whole promotion. diff --git a/docs/src/content/docs/internals/coverage-matrix.md b/docs/src/content/docs/internals/coverage-matrix.md index 44676b5c..66b36cd4 100644 --- a/docs/src/content/docs/internals/coverage-matrix.md +++ b/docs/src/content/docs/internals/coverage-matrix.md @@ -108,7 +108,7 @@ only under real installation tokens on the fleet, never in the token-free harnes | Least-privilege permissions | `orchestrate/least-privilege-permissions`, `09-single-env-repo` | least-priv posture (callbacks); gen-time wiring (3env); single-env release posture (single-env) | `internal/generate` | Permissions are scoped to the job that needs them, not the top level | | OIDC id-token propagation | `orchestrate/callback-permissions-oidc` | OIDC posture at callee (callbacks); gen-time `id-token: write` scoped (3env) | `internal/generate` | `id-token: write` propagates to the caller job without leaking workflow-wide | | Callback dependency ordering (`depends_on`) | `11-job-timeouts-and-optional-deps` | needs ordering (callbacks); base to app order (3env gen-time) | `internal/generate` | A dependent callback starts only after its prerequisite concludes | -| Callback retry wrapper | `73-deploy-retries` | retry rescue and dependent-of-a-retried-deploy gating (retries); retry-wrapper jobs present (callbacks); retry shim jobs (3env gen-time) | `internal/generate` | The retry jobs are emitted and wired for `retries: N`, including a dependent deploy's `needs:` carrying its dependency's retry shims | +| Callback retry wrapper | `73-deploy-retries`, `promote/promote-retries-exhaustion` | retry rescue and dependent-of-a-retried-deploy gating (retries); retry-wrapper jobs present (callbacks); retry shim jobs (3env gen-time) | `internal/generate` | The retry jobs are emitted and wired for `retries: N`, including a dependent deploy's `needs:` carrying its dependency's retry shims; in promote, a retried deploy with inputs fans out per environment and its exhausted ladder holds the env pointer and arms rollback | | Signed auto-commit identity (`auto_commits`) | `03-three-env-repo` | auto_commits author and message (3env) | `internal/promote/auto_commit_sha*.go` | The state commit carries the configured author and message | See [the `auto_commits` field](/cascade/reference/manifest/) in the manifest reference for what a callback must do to trigger this capture. diff --git a/docs/src/content/docs/reference/callbacks.md b/docs/src/content/docs/reference/callbacks.md index 7bbb9a69..387579af 100644 --- a/docs/src/content/docs/reference/callbacks.md +++ b/docs/src/content/docs/reference/callbacks.md @@ -529,7 +529,7 @@ Callback failures are handled by the `on_failure` policy: With `retries: N`, a failed callback is retried up to N times before it counts as a final failure. Each retry is a separate job that re-invokes the same reusable workflow, and the chain stops at the first attempt that succeeds. A callback that fails and is then rescued by a retry counts as a success: the run stays green and the deploy is recorded in state. -`run_policy`, `on_failure`, and `retries` apply to trunk runs (`orchestrate.yaml`). They are not emitted into `promote.yaml`; see [Policy fields](/reference/manifest/#policy-fields). +`run_policy` and `on_failure` apply to trunk runs (`orchestrate.yaml`) only; see [Policy fields](/reference/manifest/#policy-fields) for why a promotion has nothing to bind them to. `retries` applies to trunk runs and promotions alike: in a promotion, a deploy with declared inputs fans out to one job per environment so each retry is scoped to the one environment whose attempt failed. ## Migrating from inline `run:`/`shell:` callbacks diff --git a/docs/src/content/docs/reference/generated-workflows.md b/docs/src/content/docs/reference/generated-workflows.md index 339e5d3e..ac099ad9 100644 --- a/docs/src/content/docs/reference/generated-workflows.md +++ b/docs/src/content/docs/reference/generated-workflows.md @@ -95,6 +95,8 @@ jobs: Only `fail_fast` and `max_parallel` reach this block. `rollout.type`, `rollout.canary`, and `rollout.blue_green` parse and validate but are reserved: they carry zero generator consumption today. See [Progressive rollout](/cascade/reference/versioning/#progressive-rollout) for the full reserved-field list. +A deploy that declares `retries` does not carry this block: with retries, the matrix is replaced by one `deploy--to-` job per promotion target, each with its own retry ladder, so a retry re-invokes the callback for only the environment whose attempt failed (a matrix reports one aggregate result, and GitHub Actions cannot re-run only a dependency's failed legs). `fail_fast` and `max_parallel` apply to the matrix form only. See [Policy fields](/cascade/reference/manifest/#policy-fields). + ### Publish When the manifest has a `publish:` callback, promote adds a publish step that runs once per build at the prerelease-to-release boundary. It reads `artifact_id` from the source environment's build state and dispatches the publish workflow with `build_name`, `old_version`, `new_version`, `sha`, and `artifact_id`; the callback performs the registry operation (retag, copy, sign). diff --git a/docs/src/content/docs/reference/manifest.md b/docs/src/content/docs/reference/manifest.md index 0146e910..3e6d2868 100644 --- a/docs/src/content/docs/reference/manifest.md +++ b/docs/src/content/docs/reference/manifest.md @@ -351,7 +351,7 @@ ci: | `env_inputs` | emitted | map | {} | Per-environment input overrides. | | `run_policy` | emitted | string | `default` | Execution policy. See [Policy fields](#policy-fields). | | `on_failure` | emitted | string | `abort` | Failure handling. See [Policy fields](#policy-fields). | -| `retries` | emitted | int | 0 | Retry attempts (0-3). Trunk runs only. See [Policy fields](#policy-fields). | +| `retries` | emitted | int | 0 | Retry attempts (0-3). Trunk runs and promotions. See [Policy fields](#policy-fields). | ## builds @@ -497,9 +497,9 @@ ci: | `rollout` | partial | object | No | Deploy rollout strategy. See [rollout](#rollout). | | `state_tags` | emitted (behavior) | list | No | State-capture tags recorded for this deploy. | | `auto_commits` | emitted (behavior) | bool | No | Captures the advanced HEAD sha, as for builds. | -| `run_policy` | emitted | string | No | Execution policy. | -| `on_failure` | emitted | string | No | Failure handling. | -| `retries` | emitted | int | No | Retry attempts (0-3). | +| `run_policy` | emitted | string | No | Execution policy. Trunk runs only. | +| `on_failure` | emitted | string | No | Failure handling. Trunk runs only. | +| `retries` | emitted | int | No | Retry attempts (0-3). Trunk runs and promotions. See [Policy fields](#policy-fields). | | `artifact_upload` | emitted | object | No | GitHub Actions artifact passthrough between jobs in one orchestrate run, as for builds (`upload`/`downloads`). | | `runs_on` | validated-only | object | No | Parsed and validated, never emitted. | | `concurrency` | validated-only | object | No | Parsed and validated, never emitted. | @@ -1069,12 +1069,26 @@ versioning](/cascade/reference/versioning/#per-component-versioning). `run_policy`, `on_failure`, and `retries` apply to `validate`, each `builds` entry, and each `deploys` entry. -:::caution[Trunk runs only] -These three fields shape `orchestrate.yaml`, the workflow that runs on a trunk merge. They are **not** emitted into `promote.yaml`, so a promotion runs each deploy once, with no retry and no `on_failure` handling. +`retries` applies to both trunk runs and promotions: a failed deploy callback is retried up to N times, each retry a separate job that re-invokes the same reusable workflow, and the chain stops at the first attempt that succeeds. A callback that fails and is then rescued by a retry counts as a success — the run stays green, the deploy is recorded in state, and a promotion's rollback does not fire for it. + +:::caution[`run_policy` and `on_failure` shape trunk runs only] +`run_policy` and `on_failure` shape `orchestrate.yaml`, the workflow that runs on a trunk merge. They are **not** emitted into `promote.yaml`: + +- `on_failure` supports only `abort` (see below), and a promotion already behaves exactly that way: a deploy failure fails the run and, with `rollback_on_failure`, reverts the deploys that succeeded. +- `run_policy` gates a callback on its dependencies' results, and a promote deploy has no dependency graph to bind the policy to. A promotion dispatches each in-scope deploy for the promotion's environments; the `force` dispatch input is promote's continue-past-failure control. +::: + +:::note[How retries works in a promotion] +A promote deploy that declares `inputs` compiles to one job per environment it can be promoted into — every declared environment except the first, which is the promotion source — named `deploy--to-`. Each job runs only when the promotion includes its environment, and each carries its own retry ladder, so a retry re-invokes the callback for **only the one environment whose attempt failed**. A deploy without declared inputs, and the prod deployment job, are already single-environment and carry plain ladders. + +This per-environment shape is what makes caller-side retries sound: a matrix job reports one aggregate result (`failure` if any environment failed), and GitHub Actions offers no way for a calling workflow to re-run only the failed legs of a dependency's matrix, so a retry gated on that aggregate would redeploy the environments that already succeeded. + +Every result the promote workflow consumes is judged on the effective result across environments and attempts: the rollback gate fires only when some environment's ladder is exhausted, `DEPLOY_RESULT_` reports a single aggregate (`failure` when any ladder is exhausted, `success` when any environment succeeded, `skipped` when nothing ran) that `cascade promote finalize` reads to decide whether the environment pointer advances, and the GitHub Deployments status reflects each ladder's effective result. -`retries` is deliberately not emitted into `promote.yaml`. A promote deploy that declares `inputs` compiles to a matrix job fanned across environments, and a matrix job reports one aggregate result: `failure` if any environment failed. A retry gated on that aggregate would re-invoke the callback for **every** environment, redeploying the ones that already succeeded, and GitHub Actions offers no way for a calling workflow to re-run only the failed legs of a dependency's matrix. Retrying a healthy production environment because an unrelated environment failed is worse than not retrying, so a promote-side retry needs a design that retries per environment. Track it in [issue #626](https://github.com/stablekernel/cascade/issues/626). +Two consequences of the fan-out, stated plainly: -To make a promotion resilient to a transient failure, handle the retry inside the reusable workflow the deploy points at, where it can be scoped to the one environment that failed. +- The per-environment jobs are separate jobs, not matrix legs, so a deploy's [`rollout`](#rollout) settings (`fail_fast`, `max_parallel`) do not apply while `retries` fans it out. A retry-free deploy keeps the matrix form and its `rollout` handling unchanged. +- A promotion's publish marker (the prerelease → release advance) is a metadata step, not a deployable environment, so it runs no per-environment deploy legs. ::: | `run_policy` | Behavior | From 02c4bc28afe4e6f58e9c310e61814242942b8df3 Mon Sep 17 00:00:00 2001 From: Ray Karnes Date: Wed, 2 Dec 2026 12:10:51 -0700 Subject: [PATCH 5/5] fix(generate): keep the matrix form when a promote deploy has no fan-out target Review findings on the #626 branch, fixed: - A single-environment manifest fed to the promote generator (reachable per component through an environments: override, since both the generate command and Plan gate only the root config on IsSingleEnvironment) left an inputs deploy with retries with ZERO promotion chains, rendering a malformed DEPLOY_RESULT expression and a malformed rollback success line. Introduce perEnvFanOut as the single predicate for the fan-out (retries, declared inputs, and at least one environment to promote into) and gate the deploy jobs, the preflight outputs, and the build-matrices section on it: with no promotion target the deploy keeps the matrix form, whose chain carries no shims and whose sinks keep the bare forms. The sinks now derive ladder presence from the chain model (chainsHaveLadder) rather than the raw retries field, so the corner is byte-identical to a retry-free manifest. Pinned by TestPromoteRetry_SingleEnvironmentKeepsMatrix, both directly and through promoteTargets for the component route. - The prod-deployment ladder's chain was constructed inline at three sites; extract prodChain as the single source for its job id and retry binding, and collapse the native-deployments loop onto deployChains (byte-identical output). - State the two behavior notes for retries adopters in the CHANGELOG: the publish marker runs no deploy leg where the matrix previously invoked the callback with environment="release" (no recorded state ever depended on it), and a single-environment component keeps the matrix form. Signed-off-by: Ray Karnes --- CHANGELOG.md | 10 ++- internal/generate/promote.go | 110 ++++++++++++++++-------- internal/generate/promote_retry_test.go | 54 ++++++++++++ 3 files changed, 137 insertions(+), 37 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c226336b..4c27312f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -37,7 +37,15 @@ A `Migration` section is added to any release that bumps `schema_version`. status reflects each ladder's effective result. Manifests that do not use `retries` keep byte-identical promote output, including the matrix form and its `rollout` handling (`fail_fast`/`max_parallel` do not apply to a deploy - while `retries` fans it out). `run_policy` and `on_failure` remain + while `retries` fans it out). Two behavior notes for manifests that adopt + `retries` on an inputs deploy: the publish marker (the prerelease → release + advance) is a metadata step, so the fan-out runs no deploy leg for it where + the matrix previously invoked the callback once with + `environment="release"` — no recorded state ever depended on that invocation + (finalize skips the marker for per-deploy rows and preflight plans no + deploys for it); and a single-environment component (an `environments:` + override) has no promotion target, so its inputs deploy keeps the matrix + form there. `run_policy` and `on_failure` remain orchestrate-only: promote has no dependency skips to bind `run_policy` to, and the `force` dispatch input is promote's continue-past-failure control. diff --git a/internal/generate/promote.go b/internal/generate/promote.go index 142a1e91..29df3829 100644 --- a/internal/generate/promote.go +++ b/internal/generate/promote.go @@ -388,7 +388,7 @@ func (g *PromoteGenerator) writeMatrixBuildingStep(sb *strings.Builder) { outputName := strings.ReplaceAll(d.Name, "-", "_") upper := strings.ToUpper(outputName) - if d.Retries > 0 { + if g.perEnvFanOut(&d) { // Retries declared (#626): emit the per-environment fan-out // contract instead of a matrix — the promotion envs list the // per-environment jobs gate on, plus each environment's resolved @@ -816,7 +816,7 @@ func (g *PromoteGenerator) writePreflightJob(sb *strings.Builder) { continue } outputName := strings.ReplaceAll(d.Name, "-", "_") - if d.Retries > 0 { + if g.perEnvFanOut(&d) { fmt.Fprintf(sb, " deploy_%s_envs: ${{ steps.build-matrices.outputs.deploy_%s_envs }}\n", outputName, outputName) for _, env := range g.perEnvTargetEnvs() { envKey := strings.ReplaceAll(env, "-", "_") @@ -960,15 +960,26 @@ func (g *PromoteGenerator) perEnvTargetEnvs() []string { // every promote result sink: // - retries == 0: the matrix job (declared inputs) or the single deploy // job, with no shims — today's shape; -// - retries > 0 with declared inputs: one chain per promotion target; +// - retries > 0 with declared inputs and at least one promotion target: +// one chain per target; // - retries > 0 without declared inputs: the single deploy job's chain. // +// A single-environment manifest (reachable per component through an +// environments: override) has no promotion target, so its inputs deploy keeps +// the matrix form, whose chain carries no shims (a matrix aggregate cannot be +// retried) and whose sinks keep the bare forms. +// // The prod-deployment ladder is deliberately NOT a promotion chain: the // matrix result these chains replace never read it, and the DEPLOY_RESULT // aggregate keeps that scope. func (g *PromoteGenerator) promotionChains(d *config.DeployConfig) []promoteJobChain { - if d.Retries <= 0 || len(d.Inputs) == 0 { - return []promoteJobChain{{jobID: fmt.Sprintf("deploy-%s", d.Name), retries: d.Retries}} + if !g.perEnvFanOut(d) { + chainRetries := d.Retries + if len(d.Inputs) > 0 { + // The matrix job carries no ladder, so its chain has no shims. + chainRetries = 0 + } + return []promoteJobChain{{jobID: fmt.Sprintf("deploy-%s", d.Name), retries: chainRetries}} } envs := g.perEnvTargetEnvs() chains := make([]promoteJobChain, 0, len(envs)) @@ -981,15 +992,46 @@ func (g *PromoteGenerator) promotionChains(d *config.DeployConfig) []promoteJobC return chains } +// perEnvFanOut reports whether deploy d's promote surface is the +// per-environment fan-out: retries to scope per environment, declared inputs +// to resolve per promotion, and at least one environment to promote into. +// Single-environment manifests reach the promote generator only per component +// (an environments: override); with no promotion target there is nothing a +// retry can be scoped to, so the deploy keeps the matrix form and retries has +// no per-environment surface there. +func (g *PromoteGenerator) perEnvFanOut(d *config.DeployConfig) bool { + return d.Retries > 0 && len(d.Inputs) > 0 && len(g.perEnvTargetEnvs()) > 0 +} + +// prodChain returns the prod-deployment ladder chain for a local deploy: the +// single source for the prod job's id and retry binding that deployChains, +// finalize's needs: list, the native deployments status, and the prod retry +// ladder all share. +func prodChain(d *config.DeployConfig) promoteJobChain { + return promoteJobChain{ + jobID: fmt.Sprintf("deploy-%s-prod", d.Name), + retries: d.Retries, + } +} + // deployChains returns every chain emitted for a local deploy: its // promotion-leg chain(s) followed by the prod-deployment ladder, in the order // the jobs are emitted (and therefore the order needs: lists them). func (g *PromoteGenerator) deployChains(d *config.DeployConfig) []promoteJobChain { - chains := g.promotionChains(d) - return append(chains, promoteJobChain{ - jobID: fmt.Sprintf("deploy-%s-prod", d.Name), - retries: d.Retries, - }) + return append(g.promotionChains(d), prodChain(d)) +} + +// chainsHaveLadder reports whether any of a deploy's promotion chains carry +// retry shims. The sinks use it to pick the aggregate form (retries act on +// this deploy's promotion legs) over the bare per-job form: promotionChains +// encodes ladder presence per chain, so this is the single decision point. +func chainsHaveLadder(chains []promoteJobChain) bool { + for _, c := range chains { + if c.retries > 0 { + return true + } + } + return false } // promoteChainFailedCond builds the condition that a chain terminally failed @@ -1079,7 +1121,7 @@ func (g *PromoteGenerator) writeDeployJobs(sb *strings.Builder) error { // put an undeclared dry_run into the with: block. declared := g.declaredDeployInputs(d.Workflow, d.Inputs) - if hasInputs && d.Retries > 0 { + if g.perEnvFanOut(&d) { // Retries declared on an inputs deploy (#626): replace the matrix // with one job per promotion target, each with its own ladder. See // writePerEnvDeployJobs for why the matrix cannot be retried. @@ -1181,8 +1223,11 @@ func (g *PromoteGenerator) writeDeployJobs(sb *strings.Builder) error { writeSecretsBlock(sb, d.Secrets) // A no-inputs deploy with retries gets a plain ladder on its single - // job: it already targets one environment (#626). - if d.Retries > 0 { + // job: it already targets one environment (#626). An inputs deploy + // never takes a ladder here: with promotion targets it took the + // fan-out branch above, and without them it keeps the matrix form, + // whose aggregate result a ladder cannot soundly retry. + if !hasInputs && d.Retries > 0 { if err := g.writeDeployRetryLadder(sb, &d, fmt.Sprintf("deploy-%s", d.Name), fmt.Sprintf("Deploy %s", d.Name), func(sb *strings.Builder) { g.writeSingleDeployWith(sb, &d) }); err != nil { @@ -1218,7 +1263,7 @@ func (g *PromoteGenerator) writeDeployJobs(sb *strings.Builder) error { // plain ladder to it directly (#626). if d.Retries > 0 { if err := g.writeDeployRetryLadder(sb, &d, - fmt.Sprintf("deploy-%s-prod", d.Name), fmt.Sprintf("Deploy %s (%s)", d.Name, finalEnv), + prodChain(&d).jobID, fmt.Sprintf("Deploy %s (%s)", d.Name, finalEnv), func(sb *strings.Builder) { g.writeProdDeployWith(sb, &d, finalEnv) }); err != nil { return err } @@ -1525,14 +1570,16 @@ func (g *PromoteGenerator) writeRollbackJobs(sb *strings.Builder) { sb.WriteString(" always() &&\n") sb.WriteString(" needs.preflight.outputs.rollback_on_failure == 'true' &&\n") sb.WriteString(" needs.preflight.outputs.rollback_sha != '' &&\n") - // The deploy's own success gate. At retries 0 this is the bare job - // result (the matrix/single job). With retries it is the aggregate - // across the deploy's promotion chains — matrix-'success' semantics: - // every chain that ran ended in success, and at least one ran — so a - // chain a retry rescued still counts as the deploy's success, and an - // exhausted chain in any environment means the deploy failed. - if d.Retries > 0 { - fmt.Fprintf(sb, " %s &&\n", promoteAggregateSuccessCond(g.promotionChains(d))) + // The deploy's own success gate. Without a promotion ladder this is + // the bare job result (the matrix/single job). With one it is the + // aggregate across the deploy's promotion chains — matrix-'success' + // semantics: every chain that ran ended in success, and at least one + // ran — so a chain a retry rescued still counts as the deploy's + // success, and an exhausted chain in any environment means the deploy + // failed. + chains := g.promotionChains(d) + if chainsHaveLadder(chains) { + fmt.Fprintf(sb, " %s &&\n", promoteAggregateSuccessCond(chains)) } else { fmt.Fprintf(sb, " needs.deploy-%s.result == 'success' &&\n", d.Name) } @@ -1624,11 +1671,7 @@ func (g *PromoteGenerator) writeFinalizeJob(sb *strings.Builder) { } // Add prod deploy jobs for i := range g.config.Deploys { - prodChain := promoteJobChain{ - jobID: fmt.Sprintf("deploy-%s-prod", g.config.Deploys[i].Name), - retries: g.config.Deploys[i].Retries, - } - needs = append(needs, prodChain.jobIDs()...) + needs = append(needs, prodChain(&g.config.Deploys[i]).jobIDs()...) } // Add external deploy jobs for _, ext := range g.config.External { @@ -1895,14 +1938,15 @@ func (g *PromoteGenerator) writeFinalizeJob(sb *strings.Builder) { for i := range g.config.Deploys { d := &g.config.Deploys[i] envKey := "DEPLOY_RESULT_" + strings.ToUpper(strings.ReplaceAll(d.Name, "-", "_")) - if d.Retries > 0 { + chains := g.promotionChains(d) + if chainsHaveLadder(chains) { // One aggregate value across the deploy's promotion chains and // attempts (#626): 'failure' if any chain exhausted, 'success' // if any environment succeeded, else 'skipped'. The finalize // CLI gate consumes exactly these three behaviors: failure (or // the cancelled it folds in) holds the env pointer, success // records the per-deploy row, skipped does neither. - fmt.Fprintf(sb, " %s: %s\n", envKey, promoteAggregateResultExpr(g.promotionChains(d))) + fmt.Fprintf(sb, " %s: %s\n", envKey, promoteAggregateResultExpr(chains)) } else { fmt.Fprintf(sb, " %s: ${{ needs.deploy-%s.result }}\n", envKey, d.Name) } @@ -1971,16 +2015,10 @@ func (g *PromoteGenerator) writeNativeDeploymentSteps(sb *strings.Builder) { // from the Deployment's terminal status. With retries each chain's // success is its effective result (any attempt succeeded), so a // chain a retry rescued reports success here too. - for _, chain := range g.promotionChains(d) { + for _, chain := range g.deployChains(d) { conds = append(conds, fmt.Sprintf("(%s || needs.%s.result == 'skipped')", effectiveSuccessCond(chain.jobID, chain.retries), chain.jobID)) } - prodChain := promoteJobChain{ - jobID: fmt.Sprintf("deploy-%s-prod", d.Name), - retries: d.Retries, - } - conds = append(conds, fmt.Sprintf("(%s || needs.%s.result == 'skipped')", - effectiveSuccessCond(prodChain.jobID, prodChain.retries), prodChain.jobID)) } resultExpr = fmt.Sprintf("${{ (%s) && 'success' || 'failure' }}", strings.Join(conds, " && ")) } diff --git a/internal/generate/promote_retry_test.go b/internal/generate/promote_retry_test.go index 632f419e..65c00e28 100644 --- a/internal/generate/promote_retry_test.go +++ b/internal/generate/promote_retry_test.go @@ -582,6 +582,60 @@ func TestPromoteRetry_ZeroRetriesIsByteFrozen(t *testing.T) { assert.NotContains(t, a, "deploy_web_envs") } +// TestPromoteRetry_SingleEnvironmentKeepsMatrix pins the degenerate corner +// found in review: a single-environment manifest has no promotion target, so +// an inputs deploy with retries keeps the matrix form — never the fan-out, +// never a ladder on the matrix job (a matrix aggregate result cannot soundly +// be retried), and never a malformed empty aggregate expression. The corner +// is reachable per component through an environments: override, because both +// the generate command and Plan gate only the ROOT config on +// IsSingleEnvironment before fanning out to per-component promote generators. +func TestPromoteRetry_SingleEnvironmentKeepsMatrix(t *testing.T) { + cfg, dir := promoteRetriesFixture(t, 1, true) + cfg.Environments = config.EnvNames("dev") // single: no promotion target + + result, err := NewPromoteGenerator(cfg, dir).Generate() + require.NoError(t, err) + + // The matrix form and its bare sink forms, exactly as at retries 0. + assert.Contains(t, result, "deploy_web_matrix: ${{ steps.build-matrices.outputs.deploy_web_matrix }}") + assert.Contains(t, result, " deploy-web:\n") + assert.Contains(t, result, "DEPLOY_RESULT_WEB: ${{ needs.deploy-web.result }}\n") + assert.Contains(t, result, "needs.deploy-web.result == 'success' &&") + // No fan-out and no ladder on the matrix job. + assert.NotContains(t, result, "deploy-web-to-") + assert.NotContains(t, result, "deploy-web-retry-") + // The prod deployment job is single-environment and keeps its ladder. + assert.Contains(t, result, " deploy-web-prod-retry-1:\n") + // The pre-fix defect: an empty chain list rendered a malformed aggregate + // (an expression with a dangling && and no condition). + assert.NotContains(t, result, "${{ &&") + assert.NotContains(t, result, "&& ! &&") + + // The component route: a component overriding environments down to one + // resolves to a single-environment promote generator through the same + // promoteTargets the generate command and Plan use. + root, dirRoot := promoteRetriesFixture(t, 1, true) + root.Components = map[string]config.ComponentConfig{ + "solo": { + Path: "services/solo", + TagGrammar: &config.TagGrammarConfig{Prefix: strptr("solo-")}, + Environments: []config.EnvironmentEntry{{Name: "prod"}}, + }, + } + targets, err := promoteTargets(root, dirRoot, ".github/workflows/promote.yaml", nil) + require.NoError(t, err) + require.Len(t, targets, 1) + require.Equal(t, ".github/workflows/promote-solo.yaml", targets[0].Path) + + content, err := targets[0].Gen.Generate() + require.NoError(t, err) + assert.Contains(t, content, "deploy_web_matrix: ${{ steps.build-matrices.outputs.deploy_web_matrix }}") + assert.NotContains(t, content, "deploy-web-to-") + assert.NotContains(t, content, "${{ &&") + assert.NotContains(t, content, "&& ! &&") +} + // TestPromoteRetry_MixedManifestsKeepSinksPerDeploy pins a manifest that mixes // a retried deploy with a retry-free one: only the retried deploy's jobs and // sinks change, and the retry-free deploy keeps every retry-free form.