diff --git a/CHANGELOG.md b/CHANGELOG.md index 86bd5bb..efa96d0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -83,6 +83,59 @@ A `Migration` section is added to any release that bumps `schema_version`. exclusions, which existed only to mask this generator style, so the rule is now enforced. +- **generate:** Promote's required-input validation is lane-aware: an operator + input a manifest declares under a deploy's `inputs:` counts as available + only on the matrix deploy job, the one promote job that threads it. The + prod deploy job, the rollback job, and the single-environment deploy path + call the same callback without operator inputs, and GitHub rejects a + reusable-workflow call that omits a required input (the same shape + actionlint's `[workflow-call]` check refuses), so a callback declaring an + operator input `required: true` fails generation with a message naming the + deploy, the input, and the lane(s) that omit it. The contract inputs + (`environment`, `sha`, `image_tag`, `image_digest`) remain available on + every lane, and a required input that is neither a contract input nor + manifest-declared still fails with the previous message, whose available + list now includes the manifest-declared inputs. + +- **generate:** The hotfix workflow's `deploy-` and `rollback-` jobs + now thread the full deploy input surface to the configured deploy callback + instead of only the `environment`/`sha`/`dry_run` contract (#697). Operator + inputs (`inputs:`/`env_inputs:`) ride a one-entry matrix the context job + resolves at run time for the target environment (promote's + `DEFAULT_INPUTS`/`ENV_INPUTS` payload routed through step `env:`, with + `${{ state.* }}` references resolved at generation time as promote resolves + them and passthrough expressions such as `${{ vars.x }}` emitted verbatim); + the deploy lane threads `image_tag`/`image_digest` from the `depends_on` + builds' declared `workflow_call` outputs (`image_tag` and `artifact_id`); + and the rollback lane threads the N-1 refs the context job reads from + manifest state alongside the rollback SHA (`rollback_image_tag` from the + environment's recorded version, `rollback_image_digest` from the first + non-empty build `artifact_id`). The cascade-owned input names + (`environment`, `sha`, `dry_run`, `image_tag`, `image_digest`) always + thread with the lane's own value - an operator input carrying one of those + names is dropped rather than overriding the lane's - and values referencing + `${{ matrix.* }}` or `needs.` (other than `context`), or a passthrough + with no `inputs:` default, are left out because no hotfix lane can resolve + them for the run-time target environment. Every line stays gated on the + inputs the callee declares, so a deploy declaring none of the new surface + generates byte-identical output. A deploy callback that declares a required + input a hotfix lane cannot supply now fails `cascade generate-workflow` - + the hotfix port of promote's required-input validation, evaluated per lane + (the deploy job and the rollback job both call the callback, so a required + input must be suppliable on each): `image_tag`/`image_digest` count as + supplied on the deploy lane only when a `depends_on` build declares the + matching output (`image_tag`, `artifact_id`), so a required image input with + no producing build fails with an error naming the deploy, the input, and + the deploy lane - the rollback lane's manifest-state reads alone do not + satisfy it. The matrix `include:` guards on `needs.context.result == + 'success'` and falls back to `[]`: the hotfix file carries both triggers, + the context job runs only on the merged-pull-request path, and a runner + that evaluates every job's `strategy` even on the dispatch path (act does, + before the `if:` gates) would otherwise feed `fromJSON` the skipped job's + unresolved output and die parsing the matrix; the fallback keeps that path + evaluable while the merged path - where the context job always succeeded - + threads the real one-entry matrix unchanged. + - **generate:** The hotfix workflow's `deploy-` and `rollback-` jobs now invoke the configured deploy workflow instead of printing the deploy they stand in for and succeeding (#678). Each deploy is a reusable-workflow call on diff --git a/docs/src/content/docs/guides/hotfix.md b/docs/src/content/docs/guides/hotfix.md index 3bcb304..a7fca54 100644 --- a/docs/src/content/docs/guides/hotfix.md +++ b/docs/src/content/docs/guides/hotfix.md @@ -23,6 +23,8 @@ The `plan` job fetches env branches and tags and runs `cascade hotfix plan`. The Each hotfix deploy passes the callback contract's `environment` (the hotfix target), `sha` (the merge SHA, or the pre-hotfix SHA on the rollback lane), and `dry_run` inputs to your deploy workflow, each only when your workflow declares it. Declare the `environment:` key on the job inside your reusable workflow (see [the callback contract](/cascade/reference/callbacks/#environment-protection)) so the target environment's protection rules - manual approval on prod, for example - gate the hotfix deploy; GitHub Actions does not allow that key on the job cascade generates, because it calls your workflow with `uses:`. +Beyond the contract inputs, each hotfix deploy also threads the deploy's `inputs:` and `env_inputs:` - the entry for the resolved target environment is selected at run time by the context job, so the `env_inputs:` override keyed on the hotfix target is the one your callback receives - plus `image_tag` and `image_digest`: on the deploy lane they come from the `depends_on` builds' declared outputs, and on the rollback lane from the environment's recorded state (the last version and the first non-empty build digest). `${{ state.* }}` references inside those inputs resolve at generation time, exactly as promote resolves them. If your callback declares a required input, every hotfix lane that calls it must be able to supply it - the deploy job and the rollback job both do - or `cascade generate-workflow` fails and names the deploy, the input, and the lane; in particular `image_tag`/`image_digest` reach the deploy lane only from a `depends_on` build's declared outputs, so a callback requiring one needs such a build. + Finalize is rerun-safe. It records the diverged state on trunk, then creates the hotfix tag and release. If the run fails partway (for example the release API errors after the state commit), rerun the finalize job: the rerun completes the missing tag or release with the version already recorded, without double-applying state or allocating a new version. ## Environment branches and the stale-branch self-heal diff --git a/docs/src/content/docs/reference/generated-workflows.md b/docs/src/content/docs/reference/generated-workflows.md index 339e5d3..6514a87 100644 --- a/docs/src/content/docs/reference/generated-workflows.md +++ b/docs/src/content/docs/reference/generated-workflows.md @@ -111,12 +111,14 @@ Both carry two triggers in one file, and both drive the same deploy callbacks pr | apply | `workflow_dispatch` (not dry-run) | Cherry-pick onto each environment bottom-up; opens a resolution pull request. | | check | `pull_request` opened against `env/*` | Validate the manifest while the hotfix pull request is open. | | build | merged hotfix pull request | Build the merge SHA (a cherry-pick has no prebuilt artifact). | -| deploy | merged hotfix pull request | Invoke the configured deploy callback on the merge SHA, threading the contract `environment`, `sha`, and `dry_run` inputs (each gated on the inputs the callback declares). Paired with a rollback job that re-invokes the same callback keyed on the pre-hotfix SHA when the deploy fails. | +| deploy | merged hotfix pull request | Invoke the configured deploy callback on the merge SHA, threading the contract `environment`, `sha`, and `dry_run` inputs plus the deploy's operator inputs, `image_tag`, and `image_digest` (each gated on the inputs the callback declares). Deploys with operator inputs fan out on a one-entry matrix the context job resolves for the target environment. Paired with a rollback job that re-invokes the same callback keyed on the pre-hotfix SHA - threading the N-1 image refs from manifest state - when the deploy fails. | | finalize | deploy jobs succeed | Run `cascade hotfix finalize`: write the diverged state, tag, and release. | Dispatch inputs: `commit` (one or more trunk fix SHAs), `target_env` (every configured environment except the first), `pr_number` (optional, to replay an existing resolution pull request), `dry_run`. The second trigger is `pull_request` on `types: [closed]` against `branches: ['env/*']`, gated on the pull request having merged with the `cascade-hotfix` label. -The deploy and rollback jobs are reusable-workflow (`uses:`) calls, so they cannot carry a job-level `environment:` key; the target environment is threaded as the `environment` input and protection rules apply through the `environment:` key your callback declares on its own job ([environment protection](/cascade/reference/callbacks/#environment-protection)). Operator-authored deploy inputs (`inputs:`/`env_inputs:`) are not threaded on the hotfix path: `env_inputs` key on a target environment the hotfix resolves at run time from the merged pull request's base ref, so there is no generation-time value to emit. +The deploy and rollback jobs are reusable-workflow (`uses:`) calls, so they cannot carry a job-level `environment:` key; the target environment is threaded as the `environment` input and protection rules apply through the `environment:` key your callback declares on its own job ([environment protection](/cascade/reference/callbacks/#environment-protection)). + +Operator-authored deploy inputs (`inputs:`/`env_inputs:`) thread through a one-entry matrix the context job builds at run time for the resolved target environment, using the same serialized payload promote's preflight uses: the default inputs and per-environment overrides are baked into the workflow as `DEFAULT_INPUTS_`/`ENV_INPUTS_` JSON (routed through step `env:`), the context step merges the target environment's override with jq and appends the environment key, and the deploy and rollback jobs fan out on the single resulting entry, threading each input as `matrix.`. The matrix `include:` guards on `needs.context.result == 'success'` and falls back to `[]`: the hotfix file carries both triggers, the context job runs only on the merged-pull-request path, and a runner that evaluates every job's strategy even on the dispatch path (act does, before the `if:` gates) would otherwise read the skipped job's unresolved output - so the fallback keeps that path evaluable while leaving the merged path, where the context job always succeeded, unchanged. `${{ state.* }}` references inside those inputs resolve at generation time, as promote's do; pure passthrough expressions (for example `${{ vars.x }}`) emit verbatim in `with:` instead of riding the matrix - only a passthrough declared as the `inputs:` default threads, since an `env_inputs:`-only passthrough has no generation-time value that is correct for the run-time-resolved target environment. Values referencing `${{ matrix.* }}` or `needs.` (other than `context`) are left out: the hotfix matrix is synthetic and no lane can resolve them. The cascade-owned names (`environment`, `sha`, `dry_run`, `image_tag`, `image_digest`) are always threaded with the lane's own value, so an operator input carrying one of those names is dropped rather than overriding it. `image_tag`/`image_digest` come from the `depends_on` builds' declared `workflow_call` outputs on the deploy lane (omitted when no such build declares them), and from the target environment's manifest state on the rollback lane (`rollback_image_tag` is the recorded version, `rollback_image_digest` the first non-empty build `artifact_id`). `cascade generate-workflow` refuses a deploy callback whose required input any hotfix lane that calls it cannot supply, naming the deploy, the input, and the lane: the deploy lane threads `image_tag`/`image_digest` only from the `depends_on` builds' declared outputs, so a required image input with no producing build names the deploy lane - the rollback lane's state reads alone do not satisfy it. ### `cascade-rollback.yaml` diff --git a/e2e/scenarios/hotfix/hotfix-deploy-callback-inputs.yaml b/e2e/scenarios/hotfix/hotfix-deploy-callback-inputs.yaml new file mode 100644 index 0000000..0262dc9 --- /dev/null +++ b/e2e/scenarios/hotfix/hotfix-deploy-callback-inputs.yaml @@ -0,0 +1,237 @@ +name: "Hotfix Deploy Callback Inputs" +description: | + Verifies, as a runtime outcome, that the merged-hotfix deploy stage threads + the full deploy-input surface through to the deploy callback: the + run-time-resolved target environment, an operator-authored input the + manifest declares under the deploy's `inputs:` with an `env_inputs:` + override keyed on the resolved target environment, and the image_tag the + depends_on build callback emitted. + + The deploy callback declares `environment` (required), `release_channel`, + and `image_tag` as workflow_call inputs and echoes them on one dedicated + log line. `release_channel` is deliberately not `required: true`: promote's + prod deploy job and rollback job (and the standalone rollback workflow's + deploy job) call the same callback without operator inputs - only the + matrix deploy job threads them - so a callback that required one would fail + `cascade generate-workflow` outright instead of generating a workflow whose + prod and rollback dispatches GitHub rejects. The hotfix_merged step's + expect_log asserts the echoed line, carrying environment=test (resolved by + the context job from the merged resolution PR's base ref and threaded + through the one-entry matrix), image_tag=hotfix-image (the build callback's + declared output, threaded from the depends_on build job), and + release_channel=hotfix-stable (the env_inputs[test] override, selected at + run time by the context job's jq merge over the manifest default). This is + the assertion a reviewer turns red by reverting the with: threading alone: + a caller that drops any of the three logs an empty value, so the expect_log + line goes red while the emitted workflow source still carries the marker + text. A workflow_files contains check would stay green there, which is + why the runtime assertion targets the job's log line instead. + + The rollback lane cannot be asserted at runtime in this scenario: driving + it requires the deploy job to fail, and under act v0.2.99 a failed + reusable-workflow job makes act skip every later stage of the plan, so + the rollback job would never run. Its proof is the wiring assertion on + the first step (the rollback job re-invokes the same callback keyed on + the pre-hotfix SHA, threading rollback_image_tag and rollback_image_digest + from the context job's manifest-state reads), the internal/generate tests + that pin the emitted rollback call, and the live fleet. + +config: + trunk_branch: main + environments: [dev, test, prod] + builds: + - name: app + workflow: build.yaml + triggers: ["src/**"] + deploys: + - name: service + workflow: deploy.yaml + triggers: ["src/**"] + depends_on: [app] + inputs: + release_channel: canary + env_inputs: + test: + release_channel: hotfix-stable + prod: + release_channel: prod-stable + +# The build callback declares the image_tag / artifact_id workflow_call +# outputs the hotfix deploy lane sources image_tag and image_digest from +# (orchestrate's direct-dependency rule), and emits a stable image_tag value +# the deploy callback can echo back. The deploy callback declares the inputs +# under test and echoes all of them on a single dedicated line so the +# expect_log assertion proves all of them arrived in one substring. +# release_channel is declared but not required: promote's prod deploy job and +# rollback job call the same callback without operator inputs (only the +# matrix deploy job threads them), so a required operator input fails +# generate-workflow rather than producing prod/rollback dispatches GitHub +# would reject; the echoed line still proves the hotfix lane threads it. +setup_workflows: + ".github/workflows/build.yaml": | + name: build + on: + workflow_call: + inputs: + environment: + required: true + type: string + sha: + required: false + type: string + outputs: + image_tag: + description: built image tag + value: ${{ jobs.build.outputs.image_tag }} + artifact_id: + description: immutable image digest + value: ${{ jobs.build.outputs.artifact_id }} + jobs: + build: + runs-on: ubuntu-latest + outputs: + image_tag: ${{ steps.out.outputs.image_tag }} + artifact_id: ${{ steps.out.outputs.artifact_id }} + steps: + - id: out + run: | + echo "image_tag=hotfix-image" >> "$GITHUB_OUTPUT" + echo "artifact_id=sha256:hotfix" >> "$GITHUB_OUTPUT" + ".github/workflows/deploy.yaml": | + name: deploy + on: + workflow_call: + inputs: + environment: + required: true + type: string + sha: + required: false + type: string + image_tag: + required: false + type: string + image_digest: + required: false + type: string + release_channel: + required: false + type: string + jobs: + deploy: + runs-on: ubuntu-latest + steps: + - run: echo "hotfix deploy callback environment=${{ inputs.environment }} image_tag=${{ inputs.image_tag }} release_channel=${{ inputs.release_channel }}" + +steps: + - name: "Initial app commit; assert hotfix wires the deploy input surface" + action: commit + commit: + message: "feat: initial app" + files: + src/app.go: | + package main + func main() {} + expect: + # Wiring assertions on the staged repo: the rollback lane's proof (it + # cannot run under act; see the description) plus the matrix payload + # the runtime assertion below exercises. + workflow_files: + - path: ".github/workflows/cascade-hotfix.yaml" + contains: + # The context job routes the generation-time input payload and + # exposes the one-entry matrix and the N-1 image refs as outputs. + - "DEFAULT_INPUTS_SERVICE: '{\"release_channel\":\"canary\"}'" + - "ENV_INPUTS_SERVICE: '{\"prod\":{\"release_channel\":\"prod-stable\"},\"test\":{\"release_channel\":\"hotfix-stable\"}}'" + - "deploy_service_matrix: ${{ steps.ctx.outputs.deploy_service_matrix }}" + - "rollback_image_tag: ${{ steps.ctx.outputs.rollback_image_tag }}" + - "rollback_image_digest: ${{ steps.ctx.outputs.rollback_image_digest }}" + # Both deploy lanes fan out on the one-entry matrix. The include + # expression guards on the context job's result: this same file's + # workflow_dispatch (plan) path skips the context job, and a + # runner that evaluates every job's strategy even on that path + # (act v0.2.99 does, before any if: gate) would feed fromJSON the + # skipped job's unresolved output and die parsing the matrix; the + # '[]' fallback keeps that path evaluable while the merged path + # (context succeeded) threads the real one-entry matrix. + - "include: ${{ fromJSON(needs.context.result == 'success' && needs.context.outputs.deploy_service_matrix || '[]') }}" + # The deploy lane threads the image refs from the depends_on + # build's declared outputs; the rollback lane threads the N-1 + # refs from the context job's manifest-state reads. + - "image_tag: ${{ needs.build-app.outputs.image_tag }}" + - "image_digest: ${{ needs.build-app.outputs.artifact_id }}" + - "image_tag: ${{ needs.context.outputs.rollback_image_tag }}" + - "image_digest: ${{ needs.context.outputs.rollback_image_digest }}" + + - name: "Orchestrate dev at commit1" + action: orchestrate + expect: + state: + dev: + sha: commit1 + version: "v0.1.0-rc.0" + + - name: "Promote dev to test" + action: promote + promote: + mode: default + expect: + state: + test: + sha: commit1 + version: "v0.1.0-rc.0" + dev: + sha: commit1 + + - name: "Hotfix commit" + action: commit + commit: + message: "fix: apply critical patch" + files: + src/fix.go: | + package main + // patch applied + + - name: "Plan hotfix for test at commit2" + action: hotfix_plan + hotfix_plan: + commit_ref: commit2 + target_env: test + dry_run: true + + - name: "Apply hotfix to test" + action: hotfix_apply + hotfix_apply: + target_env: test + commit_ref: commit2 + expect: + branches: + exist: ["env/test"] + prs: + open_with_label: "cascade-hotfix" + + - name: "Merge hotfix PR" + action: merge_pr + merge_pr: + label: "cascade-hotfix" + + - name: "Finalize hotfix for test; assert the deploy callback logged its inputs" + action: hotfix_merged + hotfix_merged: + target_env: test + expect: + # The running hotfix deploy job invoked the callback with the + # run-time-resolved target environment, the build's image_tag output, + # and the env_inputs[test] operator input. The marker line is emitted + # by the callback itself, so the assertion is red the moment any of + # the three stops being threaded, even though the emitted workflow + # source still contains the marker text. + expect_log: "hotfix deploy callback environment=test image_tag=hotfix-image release_channel=hotfix-stable" + state: + test: + ref: "env/test" + base_sha: commit1 + patches: [commit2] + version: "v0.1.0-rc.0.hotfix.1" + dev: + sha: commit1 diff --git a/internal/generate/hotfix.go b/internal/generate/hotfix.go index 6f31b66..02dcd9e 100644 --- a/internal/generate/hotfix.go +++ b/internal/generate/hotfix.go @@ -4,6 +4,7 @@ import ( "fmt" "os" "path/filepath" + "slices" "sort" "strings" @@ -201,13 +202,25 @@ func (g *HotfixGenerator) getManifestFilePath() string { // Generate renders the cascade-hotfix workflow. func (g *HotfixGenerator) Generate() (string, error) { + // The plans are computed once here: the required-input refusal below and + // the emission below it must agree about which inputs thread, and the + // callee files are read once per deploy instead of once per consumer. + plans := g.deployPlans() + + // Refuse up front a deploy whose callback requires an input no hotfix + // lane can supply (#697): the emitted reusable-workflow call would fail + // the dispatch at run time instead. + if err := g.validateDeployRequiredInputs(plans); err != nil { + return "", err + } + var sb strings.Builder g.writeHeader(&sb) g.writeTriggers(&sb) g.writePermissions(&sb) g.writeConcurrency(&sb) - if err := g.writeJobs(&sb); err != nil { + if err := g.writeJobs(&sb, plans); err != nil { return "", err } @@ -311,16 +324,16 @@ func (g *HotfixGenerator) writeConcurrency(sb *strings.Builder) { sb.WriteString("\n") } -func (g *HotfixGenerator) writeJobs(sb *strings.Builder) error { +func (g *HotfixGenerator) writeJobs(sb *strings.Builder, plans []*hotfixDeployPlan) error { sb.WriteString("jobs:\n") g.writePlanJob(sb) g.writeApplyJob(sb) g.writeCheckJob(sb) - g.writeContextJob(sb) + g.writeContextJob(sb, plans) if err := g.writeBuildJobs(sb); err != nil { return err } - g.writeDeployJobs(sb) + g.writeDeployJobs(sb, plans) g.writeFinalizeJob(sb) return nil } @@ -636,17 +649,55 @@ func (g *HotfixGenerator) writeCheckJob(sb *strings.Builder) { // exposes these plus a rollback sha as outputs for the build, deploy, and // finalize stages. The plan job does not run on the pull_request (merged) path, // so its job outputs are unavailable here; the PR-body trailers are the carrier. -func (g *HotfixGenerator) writeContextJob(sb *strings.Builder) { +// +// Since #697 the context job doubles as the deploy lane's preflight, the +// hotfix counterpart of promote's preflight for inputs that key on the target +// environment: it builds, per deploy whose operator inputs ride the matrix, a +// one-entry matrix for the resolved target environment from promote's +// generation-time DEFAULT_INPUTS/ENV_INPUTS payload, and it reads the N-1 +// image refs (rollback_image_tag / rollback_image_digest) from live manifest +// state alongside the rollback SHA it already resolves. +func (g *HotfixGenerator) writeContextJob(sb *strings.Builder, plans []*hotfixDeployPlan) { sb.WriteString(" context:\n") sb.WriteString(" name: Hotfix Context\n") // The 'cascade-hotfix' literal must match hotfixLabel. sb.WriteString(" if: github.event_name == 'pull_request' && github.event.pull_request.merged == true && contains(github.event.pull_request.labels.*.name, 'cascade-hotfix')\n") sb.WriteString(" runs-on: ubuntu-latest\n") + + // The N-1 image refs are emitted only when some deploy's callback + // declares the matching input, so a manifest whose deploys consume no + // image refs keeps today's outputs block byte-identical. The names pair + // with a future target_image_tag preflight output for the deploy lane + // (#664); until then the deploy lane sources its image refs from the + // depends_on build jobs' outputs instead. + anyImageTag, anyImageDigest := false, false + for _, plan := range plans { + if plan.declared["image_tag"] { + anyImageTag = true + } + if plan.declared["image_digest"] { + anyImageDigest = true + } + } + sb.WriteString(" outputs:\n") sb.WriteString(" target_env: ${{ steps.ctx.outputs.target_env }}\n") sb.WriteString(" fix_sha: ${{ steps.ctx.outputs.fix_sha }}\n") sb.WriteString(" base_sha: ${{ steps.ctx.outputs.base_sha }}\n") sb.WriteString(" rollback_sha: ${{ steps.ctx.outputs.rollback_sha }}\n") + if anyImageTag { + sb.WriteString(" rollback_image_tag: ${{ steps.ctx.outputs.rollback_image_tag }}\n") + } + if anyImageDigest { + sb.WriteString(" rollback_image_digest: ${{ steps.ctx.outputs.rollback_image_digest }}\n") + } + for i, plan := range plans { + if !plan.needsMatrix { + continue + } + outputName := strings.ReplaceAll(g.config.Deploys[i].Name, "-", "_") + fmt.Fprintf(sb, " deploy_%s_matrix: ${{ steps.ctx.outputs.deploy_%s_matrix }}\n", outputName, outputName) + } sb.WriteString(" steps:\n") // The context job reads the target env's pre-hotfix state SHA from the // committed manifest, so the repo must be checked out first. fetch-depth: 0 @@ -659,6 +710,23 @@ func (g *HotfixGenerator) writeContextJob(sb *strings.Builder) { sb.WriteString(" env:\n") sb.WriteString(" BASE_REF: ${{ github.event.pull_request.base.ref }}\n") sb.WriteString(" PR_BODY: ${{ github.event.pull_request.body }}\n") + // Route each matrix deploy's serialized input JSON through env: + // indirection (the injection-hardened pattern promote's Build Deploy + // Matrices step uses) so operator-authored values never appear inside a + // shell quote literal in the run script. ${{ state.* }} refs inside the + // payload were already resolved at generation time, as promote resolves + // them; passthrough expressions never enter the payload (they emit + // verbatim in the deploy job's with: block). + for i, plan := range plans { + if !plan.needsMatrix { + continue + } + d := &g.config.Deploys[i] + upper := strings.ToUpper(strings.ReplaceAll(d.Name, "-", "_")) + defaultJSON, envJSON := matrixInputsJSON(plan.matrixPayload(d), g.config.EnvironmentNames(), g.state) + fmt.Fprintf(sb, " DEFAULT_INPUTS_%s: %s\n", upper, yamlSingleQuote(defaultJSON)) + fmt.Fprintf(sb, " ENV_INPUTS_%s: %s\n", upper, yamlSingleQuote(envJSON)) + } sb.WriteString(" run: |\n") fmt.Fprintf(sb, " TARGET_ENV=\"${BASE_REF#%s}\"\n", g.envBranchPrefix()) // Recover the full comma-joined set of trunk fix commits and the trunk base @@ -686,14 +754,77 @@ func (g *HotfixGenerator) writeContextJob(sb *strings.Builder) { sb.WriteString(" ROLLBACK_SHA=$(yq eval \".$MANIFEST_KEY.state.${TARGET_ENV}.sha // \\\"\\\"\" \"$MANIFEST_FILE\")\n") } sb.WriteString(" if [ \"$ROLLBACK_SHA\" = \"null\" ]; then ROLLBACK_SHA=\"\"; fi\n") + // The N-1 image refs read the same live manifest state the rollback SHA + // does (#697): the tag is the target env's recorded version (the tag the + // pre-hotfix deployment ran), the digest is the first non-empty build + // artifact_id in sorted build-name order (promote's first-non-empty rule: + // artifact_id is per-build but the deploy threads one env-level value). + // The same component scoping as the SHA read applies. + if anyImageTag { + tagExpr := fmt.Sprintf(".$MANIFEST_KEY.state.%s${TARGET_ENV}.version // \\\"\\\"", stateScopePrefix(g.componentName)) + fmt.Fprintf(sb, " ROLLBACK_IMAGE_TAG=$(yq eval \"%s\" \"$MANIFEST_FILE\")\n", tagExpr) + sb.WriteString(" if [ \"$ROLLBACK_IMAGE_TAG\" = \"null\" ]; then ROLLBACK_IMAGE_TAG=\"\"; fi\n") + } + if anyImageDigest { + // `// {}` tolerates an env whose state has no builds map at all + // (to_entries on an explicit empty map yields nothing) instead of + // relying on the runner's yq version treating a null input the same + // way. + digestExpr := fmt.Sprintf("[.$MANIFEST_KEY.state.%s${TARGET_ENV}.builds // {} | to_entries | sort_by(.key) | .[].value.artifact_id // \\\"\\\" | select(. != \\\"\\\")] | .[0] // \\\"\\\"", stateScopePrefix(g.componentName)) + fmt.Fprintf(sb, " ROLLBACK_IMAGE_DIGEST=$(yq eval \"%s\" \"$MANIFEST_FILE\")\n", digestExpr) + sb.WriteString(" if [ \"$ROLLBACK_IMAGE_DIGEST\" = \"null\" ]; then ROLLBACK_IMAGE_DIGEST=\"\"; fi\n") + } + // Build each matrix deploy's one-entry matrix for the resolved target + // environment: the default inputs merged with the target env's + // env_inputs override, the environment key appended last (promote's + // matrix-entry shape). Exactly one entry exists, so there is no + // promotions loop to walk. + for i, plan := range plans { + if !plan.needsMatrix { + continue + } + d := &g.config.Deploys[i] + outputName := strings.ReplaceAll(d.Name, "-", "_") + upper := strings.ToUpper(outputName) + fmt.Fprintf(sb, " # Build the one-entry matrix for deploy: %s (resolved target env)\n", d.Name) + fmt.Fprintf(sb, " DEFAULT_INPUTS=\"$DEFAULT_INPUTS_%s\"\n", upper) + fmt.Fprintf(sb, " ENV_INPUTS=\"$ENV_INPUTS_%s\"\n", upper) + sb.WriteString(" ENV_OVERRIDE=$(echo \"$ENV_INPUTS\" | jq -c --arg env \"$TARGET_ENV\" '.[$env] // {}')\n") + sb.WriteString(" RESOLVED=$(echo \"$DEFAULT_INPUTS\" | jq -c --argjson override \"$ENV_OVERRIDE\" '. + $override')\n") + sb.WriteString(" RESOLVED=$(echo \"$RESOLVED\" | jq -c --arg env \"$TARGET_ENV\" '. + {environment: $env}')\n") + fmt.Fprintf(sb, " MATRIX_%s=\"[$RESOLVED]\"\n", upper) + } sb.WriteString(" {\n") sb.WriteString(" echo \"target_env=${TARGET_ENV}\"\n") sb.WriteString(" echo \"fix_sha=${FIX_SHA}\"\n") sb.WriteString(" echo \"base_sha=${BASE_SHA}\"\n") sb.WriteString(" echo \"rollback_sha=${ROLLBACK_SHA}\"\n") + if anyImageTag { + sb.WriteString(" echo \"rollback_image_tag=${ROLLBACK_IMAGE_TAG}\"\n") + } + if anyImageDigest { + sb.WriteString(" echo \"rollback_image_digest=${ROLLBACK_IMAGE_DIGEST}\"\n") + } + for i, plan := range plans { + if !plan.needsMatrix { + continue + } + outputName := strings.ReplaceAll(g.config.Deploys[i].Name, "-", "_") + fmt.Fprintf(sb, " echo \"deploy_%s_matrix=${MATRIX_%s}\"\n", outputName, strings.ToUpper(outputName)) + } sb.WriteString(" } >> \"$GITHUB_OUTPUT\"\n") } +// stateScopePrefix returns the yq path prefix that scopes a state read to this +// generator's component subtree, including the trailing dot: "" for the flat +// state. form, "components.." for a component-scoped workflow. +func stateScopePrefix(componentName string) string { + if componentName != "" { + return fmt.Sprintf("components.%s.", componentName) + } + return "" +} + // mergedHotfixGuard is the if-condition gating the post-merge stages: the PR // merged and carried the cascade-hotfix label. func mergedHotfixGuard() string { @@ -889,6 +1020,400 @@ func declaredCallbackInputs(baseDir string, callbackType string, workflow string return set } +// hotfixDeployLane distinguishes the two hotfix lanes that invoke the +// configured deploy callback: the deploy lane runs it on the merged hotfix +// commit, the rollback lane re-invokes it keyed on the pre-hotfix (N-1) SHA. +// They differ only in where the sha and image inputs come from. +type hotfixDeployLane int + +const ( + hotfixLaneDeploy hotfixDeployLane = iota + hotfixLaneRollback +) + +// hotfixDeployPlan captures everything the hotfix deploy and rollback lanes +// thread into the configured deploy callback beyond the +// environment/sha/dry_run contract (#697): which operator inputs ride the +// one-entry matrix the context job resolves for the run-time target +// environment, which emit verbatim, and which depends_on build's declared +// workflow_call outputs source the image inputs on the deploy lane. +type hotfixDeployPlan struct { + // declared is the callee's declared workflow_call inputs, the same set + // declaredCallbackInputs returns; every with: line is gated on it. + declared map[string]bool + // matrixKeys are the sorted operator input keys (from inputs: and + // env_inputs:) threaded as ${{ matrix. }}: literals and + // generation-time-resolved state values. Passthrough keys are excluded + // (they emit verbatim), and so are keys no hotfix lane can resolve (see + // hotfixDeployInputDrops). + matrixKeys []string + // passthroughKeys are the sorted operator input keys whose inputs: + // default is a pure passthrough expression; they emit verbatim in with: + // and never enter the matrix JSON. Only a default-level passthrough + // threads: an env_inputs-only passthrough (or a passthrough override of a + // non-passthrough default) has no generation-time value that is correct + // for the run-time-resolved target environment, so it is dropped rather + // than silently passing another environment's expression. + passthroughKeys []string + // needsMatrix is true when at least one matrix key is declared by the + // callee: only then does the deploy/rollback job fan out on the context + // job's matrix. A deploy whose operator inputs are all undeclared or + // passthrough keeps today's matrix-free shape. + needsMatrix bool + // imageTagBuild / imageDigestBuild name the build job ("build-") + // whose callback declares the image_tag / artifact_id workflow_call + // output the deploy lane sources that input from, or "" when no + // depends_on build declares it. The rollback lane never uses these: it + // reads the N-1 refs from manifest state in the context job instead. + imageTagBuild string + imageDigestBuild string +} + +// hotfixReservedInputNames are the input names cascade itself threads on the +// hotfix deploy lanes: the callback contract (environment, sha, dry_run) plus +// the image inputs (#697). The lane's own wiring always wins for these names - +// the sha is the merge commit on the deploy lane and the pre-hotfix N-1 SHA on +// the rollback lane, so an operator-wired value would break the lanes' meaning +// - so an operator input carrying one of these names is dropped rather than +// threaded or duplicated. The hotfix build lane applies the same rule through +// renderOperatorInputs' seen() skip, and orchestrate and promote let their +// standard wiring win the same way. +var hotfixReservedInputNames = map[string]struct{}{ + "environment": {}, + "sha": {}, + "dry_run": {}, + "image_tag": {}, + "image_digest": {}, +} + +// hotfixDeployInputDrops reports whether an operator input value cannot be +// threaded on the hotfix deploy lanes, either shape: +// +// - it references the matrix context (whole, embedded, or deeper inside an +// expression like format('{0}', matrix.os)): the hotfix deploy's matrix is +// a synthetic one-entry construct, so no leg resolves the placeholder +// (promote substitutes matrix.environment/sha/version per promotion; the +// hotfix lane has no promotion), and threading one would pass the literal +// expression text to the callback. Mirrors the hotfix build lane's +// no-matrix filter; +// - it references the needs context for any job other than `context`: both +// lanes need only `context` in common (the deploy lane adds the builds, +// the rollback lane the failing deploy), so a needs.build-* reference +// resolves on one lane but not the other, where actionlint rejects it. +// The hotfix build lane applies the same filter. +// +// A key with any such value is dropped entirely: passing nothing leaves the +// callee's default visible, which is safer than passing a value the lane +// cannot resolve. +func hotfixDeployInputDrops(value string) bool { + return referencesMatrixContext(value) || referencesNeedsContextExcept(value, "context") +} + +// matrixPayload returns a shallow copy of the deploy whose inputs:/env_inputs: +// maps carry only the matrix keys, so the serialized DEFAULT_INPUTS / +// ENV_INPUTS JSON matches exactly the keys the deploy job threads: values left +// out of the with: block (passthroughs are excluded by the shared payload +// helpers; matrix-context references are filtered here) do not ride the +// payload either. Keys the callee does not declare stay, matching promote's +// payload: a matrix entry may hold unconsumed keys. +func (p *hotfixDeployPlan) matrixPayload(d *config.DeployConfig) *config.DeployConfig { + keep := make(map[string]struct{}, len(p.matrixKeys)) + for _, k := range p.matrixKeys { + keep[k] = struct{}{} + } + filtered := *d + if len(d.Inputs) > 0 { + inputs := make(map[string]interface{}, len(d.Inputs)) + for k, v := range d.Inputs { + if _, ok := keep[k]; ok { + inputs[k] = v + } + } + filtered.Inputs = inputs + } + if len(d.EnvInputs) > 0 { + envInputs := make(map[string]map[string]interface{}, len(d.EnvInputs)) + for env, m := range d.EnvInputs { + filteredEnv := make(map[string]interface{}, len(m)) + for k, v := range m { + if _, ok := keep[k]; ok { + filteredEnv[k] = v + } + } + envInputs[env] = filteredEnv + } + filtered.EnvInputs = envInputs + } + return &filtered +} + +// deployPlans computes the emission plan for every configured deploy once, so +// the required-input validation, the context job's preflight emission, and the +// deploy/rollback lanes cannot disagree about which inputs thread (#697). +func (g *HotfixGenerator) deployPlans() []*hotfixDeployPlan { + plans := make([]*hotfixDeployPlan, 0, len(g.config.Deploys)) + for i := range g.config.Deploys { + plans = append(plans, g.newHotfixDeployPlan(&g.config.Deploys[i])) + } + return plans +} + +// newHotfixDeployPlan computes the emission plan for one configured deploy. +// The operator-input classification mirrors the two deploy-input surfaces: +// - a key is dropped when any of its declared values (inputs: default or an +// env_inputs override) is unresolvable on the hotfix lanes +// (hotfixDeployInputDrops) or carries a reserved cascade-owned name +// (hotfixReservedInputNames: the lanes' own wiring always wins); +// - a key whose inputs: default is a pure passthrough expression threads +// verbatim (promote's default-wins rule). A passthrough override without +// a passthrough default is dropped: no generation-time value is correct +// for the run-time-resolved target environment, and passing another +// environment's expression would be silently wrong; +// - every other key from inputs: or env_inputs: rides the matrix. +func (g *HotfixGenerator) newHotfixDeployPlan(d *config.DeployConfig) *hotfixDeployPlan { + plan := &hotfixDeployPlan{ + declared: declaredCallbackInputs(g.baseDir, config.CallbackTypeDeploy, d.Workflow, d.Inputs), + } + + // Collect every declared value per key across the default inputs and all + // env_inputs overrides, so the drop rules see the whole key. + values := make(map[string][]interface{}) + collect := func(k string, v interface{}) { + values[k] = append(values[k], v) + } + for k, v := range d.Inputs { + collect(k, v) + } + for _, envMap := range d.EnvInputs { + for k, v := range envMap { + collect(k, v) + } + } + + defaultIsPassthrough := func(k string) bool { + s, ok := d.Inputs[k].(string) + return ok && classifyInputValue(s) == inputPassthrough + } + anyPassthrough := func(k string) bool { + for _, v := range values[k] { + if s, ok := v.(string); ok && classifyInputValue(s) == inputPassthrough { + return true + } + } + return false + } + + for k := range values { + if _, reserved := hotfixReservedInputNames[k]; reserved { + continue + } + dropped := false + for _, v := range values[k] { + if s, ok := v.(string); ok && hotfixDeployInputDrops(s) { + dropped = true + break + } + } + if dropped { + continue + } + switch { + case defaultIsPassthrough(k): + plan.passthroughKeys = append(plan.passthroughKeys, k) + case anyPassthrough(k): + // A passthrough override with no passthrough default: dropped + // (see the method comment). + continue + default: + plan.matrixKeys = append(plan.matrixKeys, k) + } + } + sort.Strings(plan.matrixKeys) + sort.Strings(plan.passthroughKeys) + + for _, k := range plan.matrixKeys { + if plan.declared[k] { + plan.needsMatrix = true + break + } + } + + plan.imageTagBuild = g.deployImageSourceBuild(d, "image_tag") + plan.imageDigestBuild = g.deployImageSourceBuild(d, "artifact_id") + return plan +} + +// deployImageSourceBuild returns the build job id ("build-") whose +// callback declares the named workflow_call output, searching the deploy's +// depends_on entries in manifest order (orchestrate's direct-dependency rule: +// outputs thread from direct dependencies only), or "" when no depends_on +// build declares it. +func (g *HotfixGenerator) deployImageSourceBuild(d *config.DeployConfig, outputName string) string { + for _, dep := range d.DependsOn { + for i := range g.config.Builds { + if g.config.Builds[i].Name != dep { + continue + } + for _, out := range g.buildCallbackOutputs(&g.config.Builds[i]) { + if out == outputName { + return "build-" + dep + } + } + } + } + return "" +} + +// buildCallbackOutputs returns the workflow_call output names a build's +// callback declares. A local workflow is parsed from disk; a cross-repo +// workflow cannot be read locally, so the callback contract's assumed outputs +// apply (builds declare artifact_id, mirroring orchestrate's crossRepoOutputs). +// An unreadable or unparsable local callback yields an empty set, the same +// leniency declaredCallbackInputs applies to inputs. +func (g *HotfixGenerator) buildCallbackOutputs(b *config.BuildConfig) []string { + if config.IsExternalWorkflow(b.Workflow) { + return crossRepoOutputs(config.CallbackTypeBuild) + } + path := filepath.Join(g.baseDir, normalizeWorkflowPath(b.Workflow)) + data, err := os.ReadFile(path) + if err != nil { + return nil + } + outputs, err := ParseWorkflowOutputs(data) + if err != nil { + return nil + } + return outputs +} + +// validateDeployRequiredInputs ports promote's validateRequiredInputs to the +// hotfix lanes (#697): a deploy callback that declares a required input a +// hotfix lane cannot supply fails generation with a message naming the +// deploy, the input, and the lane, instead of emitting a reusable-workflow +// dispatch GitHub would reject. writeDeployJobs emits the deploy job and the +// rollback job for every configured deploy, so both lanes call the callback +// and a required input must be suppliable on each: +// - environment, sha, and dry_run come from the callback contract, which +// both lanes thread; +// - every manifest-declared operator input that threads (a matrix key or a +// passthrough) is serialized into the context job's one-entry matrix and +// emitted by both lanes; +// - image_tag and image_digest always reach the rollback lane, which reads +// the N-1 refs from manifest state in the context job, but reach the +// deploy lane only when a depends_on build declares the matching +// workflow_call output (image_tag, artifact_id) - without one the deploy +// job omits the with: line and a callback requiring the input would fail +// that lane's dispatch, so the check refuses with a message naming the +// deploy lane and the output it would source the input from. +// +// The rollback lane supplies everything the deploy lane does (the shared +// contract and operator threading) plus the state-sourced image refs, so an +// input the rollback lane cannot supply is suppliable on no lane at all and +// fails with the union message. +// +// A matrix-context-referencing input value is not suppliable (the synthetic +// matrix resolves no placeholder), and a cross-repo callback cannot be parsed +// locally so the check skips it, mirroring promote. +func (g *HotfixGenerator) validateDeployRequiredInputs(plans []*hotfixDeployPlan) error { + var errs []string + for i := range g.config.Deploys { + d := &g.config.Deploys[i] + if config.IsExternalWorkflow(d.Workflow) { + continue + } + required, err := g.deployRequiredInputs(d) + if err != nil || len(required) == 0 { + // An unreadable or unparsable callee is as unknowable here as it + // is to declaredCallbackInputs; the check stays silent rather + // than failing generation for a workflow the input gating already + // tolerates. + continue + } + plan := plans[i] + + // Per-lane suppliable sets. Both lanes thread the callback contract + // and every threaded operator input; the image inputs diverge - the + // rollback lane always reads them from manifest state, the deploy + // lane threads them only from a depends_on build's declared output. + threaded := func(name string) bool { + return slices.Contains(plan.matrixKeys, name) || slices.Contains(plan.passthroughKeys, name) + } + rollbackSupplies := func(name string) bool { + switch name { + case "environment", "sha", "dry_run", "image_tag", "image_digest": + return true + } + return threaded(name) + } + deploySupplies := func(name string) bool { + switch name { + case "environment", "sha", "dry_run": + return true + case "image_tag": + return plan.imageTagBuild != "" + case "image_digest": + return plan.imageDigestBuild != "" + } + return threaded(name) + } + + // The available list leads with the contract inputs in their emitted + // order, then the manifest-declared inputs sorted, so the union + // message reads like promote's. + names := []string{"environment", "sha", "dry_run", "image_tag", "image_digest"} + extra := make([]string, 0, len(plan.matrixKeys)+len(plan.passthroughKeys)) + extra = append(extra, plan.matrixKeys...) + extra = append(extra, plan.passthroughKeys...) + sort.Strings(extra) + for _, name := range extra { + if !slices.Contains(names, name) { + names = append(names, name) + } + } + + for _, req := range required { + if rollbackSupplies(req) && deploySupplies(req) { + continue + } + if !rollbackSupplies(req) { + // The rollback lane supplies everything the deploy lane does, + // so this input is suppliable on no lane at all. + errs = append(errs, fmt.Sprintf( + "deploy-%s requires input '%s' but it cannot be provided in the hotfix workflow (available: %s)", + d.Name, req, strings.Join(names, ", "))) + continue + } + // Only the deploy lane starves it. Today that is exactly a + // required image input with no depends_on build declaring the + // matching output; say where the deploy lane would source it. + source, n1 := "image_tag", "tag" + if req == "image_digest" { + source, n1 = "artifact_id", "digest" + } + errs = append(errs, fmt.Sprintf( + "deploy-%s requires input '%s' but the hotfix deploy lane cannot supply it (the deploy lane threads it only from a depends_on build's declared %s output; the rollback lane reads the N-1 %s from manifest state)", + d.Name, req, source, n1)) + } + } + if len(errs) > 0 { + return fmt.Errorf("required input validation failed:\n - %s", strings.Join(errs, "\n - ")) + } + return nil +} + +// deployRequiredInputs returns the workflow_call inputs the deploy's callback +// declares as required (required: true with no default), or an error when the +// callback cannot be read or parsed. Callers treat an error as "unknowable" +// and skip the check for that deploy. +func (g *HotfixGenerator) deployRequiredInputs(d *config.DeployConfig) ([]string, error) { + path := filepath.Join(g.baseDir, normalizeWorkflowPath(d.Workflow)) + data, err := os.ReadFile(path) + if err != nil { + return nil, err + } + return ParseWorkflowRequiredInputs(data) +} + // buildJobNames returns the build job identifiers emitted by writeBuildJobs so // deploy jobs can declare correct needs: references. func (g *HotfixGenerator) buildJobNames() []string { @@ -912,16 +1437,25 @@ func (g *HotfixGenerator) buildJobNames() []string { // run:/shell: callbacks and requires workflow: on every deploy (#161), the same // invariant the promote and rollback generators rely on, so both lanes are // always uses: calls. -func (g *HotfixGenerator) writeDeployJobs(sb *strings.Builder) { +// +// Since #697 both lanes also thread the deploy's operator inputs +// (inputs:/env_inputs:), image_tag, and image_digest: a deploy whose operator +// inputs ride the matrix fans out on the context job's one-entry matrix, the +// deploy lane sources the image refs from the depends_on builds' outputs, and +// the rollback lane reads the N-1 refs from the context job's manifest-state +// outputs. A deploy declaring none of these keeps today's shape byte-for-byte. +func (g *HotfixGenerator) writeDeployJobs(sb *strings.Builder, plans []*hotfixDeployPlan) { buildNeeds := g.buildJobNames() needsList := append([]string{"context"}, buildNeeds...) needsStr := "[" + strings.Join(needsList, ", ") + "]" - for _, d := range g.config.Deploys { + for i, d := range g.config.Deploys { + plan := plans[i] fmt.Fprintf(sb, " deploy-%s:\n", d.Name) fmt.Fprintf(sb, " name: Deploy %s\n", d.Name) fmt.Fprintf(sb, " needs: %s\n", needsStr) fmt.Fprintf(sb, " if: %s\n", mergedHotfixGuard()) + writeHotfixDeployMatrixStrategy(sb, plan, d.Name) // The deploy is a reusable-workflow (uses:) call to the configured // callback, the same shape the promote and rollback generators emit // for it. GitHub Actions forbids a job-level environment: key on a @@ -932,7 +1466,7 @@ func (g *HotfixGenerator) writeDeployJobs(sb *strings.Builder) { // promote and rollback deploy calls rely on. writeCallbackPermissions(sb, " ", d.Permissions) fmt.Fprintf(sb, " uses: %s\n", normalizeWorkflowPath(d.Workflow)) - g.writeHotfixDeployWith(sb, d, " sha: ${{ github.event.pull_request.merge_commit_sha }}") + g.writeHotfixDeployWith(sb, &d, plan, hotfixLaneDeploy, " sha: ${{ github.event.pull_request.merge_commit_sha }}") writeSecretsBlock(sb, d.Secrets) // Rollback job: gated on a rollback sha being available and the deploy @@ -949,24 +1483,64 @@ func (g *HotfixGenerator) writeDeployJobs(sb *strings.Builder) { fmt.Fprintf(sb, " name: Rollback %s\n", d.Name) fmt.Fprintf(sb, " needs: [context, deploy-%s]\n", d.Name) fmt.Fprintf(sb, " if: always() && needs.context.outputs.rollback_sha != '' && needs.deploy-%s.result == 'failure'\n", d.Name) + writeHotfixDeployMatrixStrategy(sb, plan, d.Name) writeCallbackPermissions(sb, " ", d.Permissions) fmt.Fprintf(sb, " uses: %s\n", normalizeWorkflowPath(d.Workflow)) - g.writeHotfixDeployWith(sb, d, " sha: ${{ needs.context.outputs.rollback_sha }}") + g.writeHotfixDeployWith(sb, &d, plan, hotfixLaneRollback, " sha: ${{ needs.context.outputs.rollback_sha }}") writeSecretsBlock(sb, d.Secrets) } } +// writeHotfixDeployMatrixStrategy emits the one-entry matrix strategy block a +// hotfix deploy or rollback job fans out on when the deploy's operator inputs +// ride the context job's matrix (#697), the hotfix counterpart of promote's +// matrix deploy strategy. fail-fast is moot with exactly one entry but is +// emitted false to match promote's strategy shape. A deploy that threads no +// matrix input emits nothing, keeping today's matrix-free job. +// +// The include expression guards on needs.context.result: the workflow file +// carries two triggers, and the context job runs only on the +// pull_request(closed) path, so a runner that evaluates every job's strategy +// even on the workflow_dispatch path - where the plan/apply jobs run and the +// context job is skipped - sees needs.context.outputs.deploy__matrix +// unresolved. act v0.2.99 does exactly that (its plan executor evaluates each +// job's strategy before any if: gate) and leaves a skipped job's declared +// outputs uninterpolated, so the raw "${{ steps.ctx.outputs... }}" text +// reaches fromJSON and the run dies parsing the matrix. The expression +// therefore falls back to '[]', a zero-entry matrix that leaves the job +// skipped exactly as its if: gate already decided. On the merged path the +// guard is a no-op: the deploy job's needs gate carries no status override +// and the rollback job's non-empty rollback_sha output gate can only hold +// after the context job succeeded, so the matrix is evaluated only when +// needs.context.result == 'success' selects the real one-entry matrix, and +// GitHub's behavior is unchanged. +func writeHotfixDeployMatrixStrategy(sb *strings.Builder, plan *hotfixDeployPlan, deployName string) { + if !plan.needsMatrix { + return + } + outputName := strings.ReplaceAll(deployName, "-", "_") + sb.WriteString(" strategy:\n") + sb.WriteString(" fail-fast: false\n") + sb.WriteString(" matrix:\n") + fmt.Fprintf(sb, " include: ${{ fromJSON(needs.context.result == 'success' && needs.context.outputs.deploy_%s_matrix || '[]') }}\n", outputName) +} + // writeHotfixDeployWith emits the with: block a hotfix deploy or rollback job // threads into the configured deploy callback: the callback-contract // environment, sha, and dry_run inputs, with the sha line the caller supplies // (the merged hotfix commit for a deploy, the pre-hotfix N-1 SHA for a -// rollback). +// rollback), plus the #697 surface: image_tag / image_digest and the deploy's +// operator inputs. // // Each input is gated on the callee's declared workflow_call inputs, mirroring // the hotfix build path: GitHub Actions rejects a reusable-workflow call that // passes an input the callee does not declare, so a callee that declares none // of the contract inputs gets no with: block, and a callee that declares only -// some of them receives those alone. +// some of them receives those alone. The cascade-owned names (environment, +// sha, dry_run, image_tag, image_digest) always win over operator wiring of +// the same names - the plan drops those keys - so the block can never emit a +// duplicate mapping key, and the lane's own sha (merge commit vs pre-hotfix +// SHA) is never overridden by a manifest value. // // dry_run uses the null-safe github.event.inputs accessor coerced to a real // boolean (the same expression orchestrate and promote emit): the deploy and @@ -975,24 +1549,68 @@ func (g *HotfixGenerator) writeDeployJobs(sb *strings.Builder) { // that marks it required: true - receives a real false rather than the empty // string that would fail the dispatch. // -// Operator inputs (inputs:/env_inputs:) are deliberately not threaded: -// env_inputs key on a target environment the hotfix resolves at run time from -// the merged resolution PR's base ref, so no generation-time value exists to -// emit, and plain inputs have no hotfix lane sourcing them - promote threads -// them from its preflight outputs, and the hotfix workflow has no equivalent -// of that preflight. -func (g *HotfixGenerator) writeHotfixDeployWith(sb *strings.Builder, d config.DeployConfig, shaLine string) { - declared := declaredCallbackInputs(g.baseDir, config.CallbackTypeDeploy, d.Workflow, d.Inputs) +// The image inputs are lane-specific: the deploy lane threads image_tag / +// image_digest from the depends_on build jobs' declared workflow_call outputs +// (image_tag and artifact_id, orchestrate's direct-dependency rule), but only +// when such a build exists; the rollback lane threads the N-1 refs +// (rollback_image_tag / rollback_image_digest) the context job read from live +// manifest state. A deploy lane with no output-sourcing build omits the lines +// rather than referencing an output the callee does not declare. +// +// Operator inputs split the way promote splits them: passthrough expressions +// (e.g. ${{ vars.x }}) emit verbatim, resolved by GitHub Actions at run time; +// every other value rides the context job's one-entry matrix and threads as +// matrix., because env_inputs key on the target environment the context +// job resolves only at run time from the merged resolution PR's base ref. +func (g *HotfixGenerator) writeHotfixDeployWith(sb *strings.Builder, d *config.DeployConfig, plan *hotfixDeployPlan, lane hotfixDeployLane, shaLine string) { var withLines []string - if declared["environment"] { - withLines = append(withLines, " environment: ${{ needs.context.outputs.target_env }}") + if plan.declared["environment"] { + // From the matrix entry when the deploy fans out on one (promote's + // matrix deploy shape); else the context job's resolved target env. + if plan.needsMatrix { + withLines = append(withLines, " environment: ${{ matrix.environment }}") + } else { + withLines = append(withLines, " environment: ${{ needs.context.outputs.target_env }}") + } } - if declared["sha"] { + if plan.declared["sha"] { withLines = append(withLines, shaLine) } - if declared["dry_run"] { + if plan.declared["dry_run"] { withLines = append(withLines, " dry_run: ${{ github.event.inputs.dry_run == 'true' }}") } + if plan.declared["image_tag"] { + if lane == hotfixLaneRollback { + withLines = append(withLines, " image_tag: ${{ needs.context.outputs.rollback_image_tag }}") + } else if plan.imageTagBuild != "" { + withLines = append(withLines, fmt.Sprintf(" image_tag: ${{ needs.%s.outputs.image_tag }}", plan.imageTagBuild)) + } + } + if plan.declared["image_digest"] { + if lane == hotfixLaneRollback { + withLines = append(withLines, " image_digest: ${{ needs.context.outputs.rollback_image_digest }}") + } else if plan.imageDigestBuild != "" { + withLines = append(withLines, fmt.Sprintf(" image_digest: ${{ needs.%s.outputs.artifact_id }}", plan.imageDigestBuild)) + } + } + // Passthrough inputs emit verbatim (sorted for deterministic output); + // GitHub Actions resolves them at run time. Only a key whose inputs: + // default is itself a passthrough threads (the default value), so the + // emitted expression never depends on the run-time-resolved target + // environment. + for _, name := range plan.passthroughKeys { + if plan.declared[name] { + withLines = append(withLines, fmt.Sprintf(" %s: %s", name, passthroughInputValue(d, name))) + } + } + // Remaining operator inputs thread from the matrix entry (sorted for + // deterministic output): literals and generation-time-resolved state + // values arrived there through the context job's JSON merge. + for _, name := range plan.matrixKeys { + if plan.declared[name] { + withLines = append(withLines, fmt.Sprintf(" %s: ${{ matrix.%s }}", name, name)) + } + } if len(withLines) == 0 { return } diff --git a/internal/generate/hotfix_test.go b/internal/generate/hotfix_test.go index d61fdda..adb8ed3 100644 --- a/internal/generate/hotfix_test.go +++ b/internal/generate/hotfix_test.go @@ -6,6 +6,7 @@ import ( "os/exec" "path/filepath" "regexp" + "sort" "strings" "testing" @@ -758,6 +759,994 @@ func TestHotfixGenerator_DeployInputGating(t *testing.T) { assert.Contains(t, rollback, "sha: ${{ needs.context.outputs.rollback_sha }}") assert.Contains(t, rollback, "dry_run: ${{ github.event.inputs.dry_run == 'true' }}") }) + + t.Run("declared operator input threads through the context matrix", func(t *testing.T) { + // #697: a manifest-declared deploy input the callee declares must ride + // the one-entry matrix the context job resolves for the run-time target + // environment, because env_inputs key on that environment and no + // generation-time value exists. + dir := writeHotfixDeployStub(t, "environment", "sha", "replicas") + cfg := threeEnvHotfixConfig() + cfg.Deploys[0].Inputs = map[string]interface{}{"replicas": 2} + content, err := NewHotfixGenerator(cfg, dir).Generate() + require.NoError(t, err) + + for _, jobID := range []string{"deploy-service", "rollback-service"} { + block := jobBlock(t, content, jobID) + assert.Contains(t, block, " replicas: ${{ matrix.replicas }}", + "%s must thread the declared operator input from its matrix entry", jobID) + assert.Contains(t, block, + " include: ${{ fromJSON(needs.context.result == 'success' && needs.context.outputs.deploy_service_matrix || '[]') }}", + "%s must fan out on the context job's one-entry matrix", jobID) + assert.Contains(t, block, " environment: ${{ matrix.environment }}", + "%s must thread the contract environment from the matrix entry", jobID) + } + }) + + t.Run("matrix include survives the dispatch path's skipped context job", func(t *testing.T) { + // The hotfix file carries two triggers: workflow_dispatch runs the + // plan/apply jobs and pull_request(closed) runs the context/build/ + // deploy/rollback/finalize chain. The context job is skipped on the + // dispatch path, and a runner that still evaluates every job's + // strategy there (act v0.2.99's plan executor does, before any if: + // gate) sees the skipped job's outputs unresolved - act leaves them + // as the raw "${{ steps.ctx.outputs... }}" text, which fromJSON + // rejects ("invalid character '$'"), and the raw include scalar then + // fails the matrix decode fatally. The include expression must + // therefore stay evaluable on both paths: guard on + // needs.context.result so a skipped (or failed) context job yields + // '[]' - a zero-entry matrix that leaves the job skipped exactly as + // its if: gate already decided - while a succeeded context job + // threads the real one-entry matrix unchanged. (On GitHub the guard + // is a no-op: the deploy job's needs gate and the rollback job's + // rollback_sha output gate both mean the matrix is evaluated only + // after the context job succeeded.) + dir := writeHotfixDeployStub(t, "environment", "sha", "replicas") + cfg := threeEnvHotfixConfig() + cfg.Deploys[0].Inputs = map[string]interface{}{"replicas": 2} + content, err := NewHotfixGenerator(cfg, dir).Generate() + require.NoError(t, err) + + for _, jobID := range []string{"deploy-service", "rollback-service"} { + block := jobBlock(t, content, jobID) + assert.Contains(t, block, "needs.context.result == 'success'", + "%s must guard the matrix on the context job's result so the skipped-context dispatch path stays evaluable", jobID) + assert.Contains(t, block, "|| '[]') }}", + "%s must fall back to an empty matrix when the context job did not succeed", jobID) + assert.Equal(t, 1, strings.Count(block, "include:"), + "%s must carry exactly one include line", jobID) + } + }) + + t.Run("undeclared operator input keeps today's output shape", func(t *testing.T) { + // A callee that does not declare the operator input must not drag the + // matrix machinery into the workflow: the input is dropped exactly as + // before, and the deploy/rollback jobs stay byte-shaped like today. + dir := writeHotfixDeployStub(t, "environment", "sha") + cfg := threeEnvHotfixConfig() + cfg.Deploys[0].Inputs = map[string]interface{}{"replicas": 2} + content, err := NewHotfixGenerator(cfg, dir).Generate() + require.NoError(t, err) + + deploy := jobBlock(t, content, "deploy-service") + assert.NotContains(t, deploy, "replicas:", + "an operator input the callee does not declare must not be threaded") + assert.NotContains(t, deploy, "strategy:", + "no matrix is needed when nothing threads through it") + assert.NotContains(t, content, "deploy_service_matrix", + "the context job must not emit a matrix output nothing consumes") + assert.NotContains(t, content, "DEFAULT_INPUTS_", + "no input JSON is routed when no matrix is built") + assert.Contains(t, deploy, "environment: ${{ needs.context.outputs.target_env }}", + "the environment line keeps today's form without a matrix") + }) + + t.Run("passthrough operator input stays verbatim without a matrix", func(t *testing.T) { + // A pure passthrough expression (${{ vars.x }}) resolves at run time by + // GitHub Actions and does not depend on the target environment, so it + // emits verbatim in with: and never enters the matrix JSON. + dir := writeHotfixDeployStub(t, "environment", "region") + cfg := threeEnvHotfixConfig() + cfg.Deploys[0].Inputs = map[string]interface{}{ + "region": "${{ vars.DEPLOY_REGION }}", + } + content, err := NewHotfixGenerator(cfg, dir).Generate() + require.NoError(t, err) + + for _, jobID := range []string{"deploy-service", "rollback-service"} { + block := jobBlock(t, content, jobID) + assert.Contains(t, block, " region: ${{ vars.DEPLOY_REGION }}", + "%s must emit the passthrough expression verbatim", jobID) + assert.NotContains(t, block, "strategy:", + "%s needs no matrix for a passthrough-only input", jobID) + assert.Contains(t, block, "environment: ${{ needs.context.outputs.target_env }}", + "%s keeps today's environment line without a matrix", jobID) + } + assert.NotContains(t, content, "DEFAULT_INPUTS_SERVICE", + "a passthrough input must not enter the matrix JSON") + }) + + t.Run("operator input named like a cascade-owned input is dropped", func(t *testing.T) { + // The lanes' own sha wiring is load-bearing (the merge commit on the + // deploy lane, the pre-hotfix N-1 SHA on the rollback lane), so an + // operator wiring `sha` under inputs: cannot override it; the value + // is dropped exactly as before #697 (when operator inputs were not + // threaded at all) and the standard line threads once. + dir := writeHotfixDeployStub(t, "environment", "sha") + cfg := threeEnvHotfixConfig() + cfg.Deploys[0].Inputs = map[string]interface{}{"sha": "operators-own-sha"} + content, err := NewHotfixGenerator(cfg, dir).Generate() + require.NoError(t, err) + + deploy := jobBlock(t, content, "deploy-service") + assert.Contains(t, deploy, "sha: ${{ github.event.pull_request.merge_commit_sha }}", + "the standard sha wiring must keep threading the merge commit") + assert.NotContains(t, deploy, "operators-own-sha", + "an operator input sharing a cascade-owned name must be dropped, not threaded") + assert.Equal(t, 1, strings.Count(deploy, " sha:"), + "the sha input must appear exactly once in the with: block") + + rollback := jobBlock(t, content, "rollback-service") + assert.Contains(t, rollback, "sha: ${{ needs.context.outputs.rollback_sha }}", + "the rollback lane must keep threading the pre-hotfix SHA; an operator-wired sha would break the rollback") + assert.Equal(t, 1, strings.Count(rollback, " sha:"), + "the rollback lane's sha input must appear exactly once") + }) + + t.Run("operator-wired image_tag does not duplicate the lane's line", func(t *testing.T) { + // image_tag is cascade-owned on these lanes (build output on the + // deploy lane, manifest state on the rollback lane), so an + // operator-wired value is dropped and the lane's line threads once - + // emitting both would duplicate the mapping key and GitHub would + // reject the whole workflow. + dir := writeHotfixBuildStubOutputs(t, + []string{"environment", "sha"}, + []string{"image_tag", "artifact_id"}, + ) + writeHotfixCallbackStub(t, dir, "deploy.yaml", "environment", "sha", "image_tag") + cfg := threeEnvHotfixConfig() + cfg.Deploys[0].DependsOn = []string{"app"} + cfg.Deploys[0].Inputs = map[string]interface{}{"image_tag": "operators-own-tag"} + content, err := NewHotfixGenerator(cfg, dir).Generate() + require.NoError(t, err) + + deploy := jobBlock(t, content, "deploy-service") + assert.Contains(t, deploy, " image_tag: ${{ needs.build-app.outputs.image_tag }}", + "the deploy lane's build-output image_tag must keep threading") + assert.NotContains(t, deploy, "operators-own-tag", + "an operator-wired image_tag must be dropped, not threaded beside the lane's") + assert.Equal(t, 1, strings.Count(deploy, " image_tag:"), + "the image_tag input must appear exactly once in the with: block") + + rollback := jobBlock(t, content, "rollback-service") + assert.Contains(t, rollback, " image_tag: ${{ needs.context.outputs.rollback_image_tag }}", + "the rollback lane's state-sourced image_tag must keep threading") + assert.Equal(t, 1, strings.Count(rollback, " image_tag:"), + "the rollback lane's image_tag must appear exactly once") + }) + + t.Run("byte-identical when the operator input is undeclared", func(t *testing.T) { + // The hard #697 constraint: an operator input the callee does not + // declare changes nothing at all - the output is byte-identical to a + // manifest that declares no deploy inputs in the first place. + dir := writeHotfixDeployStub(t, "environment", "sha") + + withInputs := threeEnvHotfixConfig() + withInputs.Deploys[0].Inputs = map[string]interface{}{"replicas": 2} + got, err := NewHotfixGenerator(withInputs, dir).Generate() + require.NoError(t, err) + + withoutInputs := threeEnvHotfixConfig() + want, err := NewHotfixGenerator(withoutInputs, dir).Generate() + require.NoError(t, err) + + assert.Equal(t, want, got, + "a deploy whose operator input the callee does not declare must generate byte-identical output to a deploy with no inputs at all") + }) +} + +// hotfixDeployInputConfig returns the three-env hotfix config with the service +// deploy's operator inputs and env_inputs set to the given maps, the shared +// fixture for the #697 deploy-input threading tests. +func hotfixDeployInputConfig(inputs map[string]interface{}, envInputs map[string]map[string]interface{}) *config.TrunkConfig { + cfg := threeEnvHotfixConfig() + cfg.Deploys[0].Inputs = inputs + cfg.Deploys[0].EnvInputs = envInputs + return cfg +} + +// TestHotfixGenerator_DeployMatrixPreflight guards the context job's half of +// the #697 deploy-input threading: the context step becomes a preflight for +// the deploy lane, building promote's DEFAULT_INPUTS/ENV_INPUTS JSON at +// generation time, routing it through step env: (the injection-hardened +// pattern), and resolving the one matrix entry for the run-time target +// environment with jq on TARGET_ENV. state.* refs resolve at generation time +// through SetState exactly as promote resolves them. +func TestHotfixGenerator_DeployMatrixPreflight(t *testing.T) { + t.Run("context emits the matrix output and env-routed input JSON", func(t *testing.T) { + dir := writeHotfixDeployStub(t, "environment", "sha", "replicas") + cfg := hotfixDeployInputConfig( + map[string]interface{}{"replicas": 2}, + map[string]map[string]interface{}{ + "test": {"replicas": 4}, + "prod": {"replicas": 6}, + }, + ) + content, err := NewHotfixGenerator(cfg, dir).Generate() + require.NoError(t, err) + + contextJob := extractJobSection(t, content, "context:") + require.NotEmpty(t, contextJob, "context job section should be present") + + // The context job exposes the matrix as an output the deploy and + // rollback jobs fan out on. + assert.Contains(t, contextJob, "deploy_service_matrix: ${{ steps.ctx.outputs.deploy_service_matrix }}", + "the context job must expose the deploy matrix as an output") + + // The input JSON rides env: indirection, never a shell quote literal, + // mirroring promote's Build Deploy Matrices step. + assert.Contains(t, contextJob, `DEFAULT_INPUTS_SERVICE: '{"replicas":2}'`, + "the default inputs must route through env: as serialized JSON") + assert.Contains(t, contextJob, `ENV_INPUTS_SERVICE: '{"prod":{"replicas":6},"test":{"replicas":4}}'`, + "the env_inputs must route through env: keyed per environment (sorted keys, json.Marshal order)") + + // The script merges the default inputs with the resolved target + // environment's override and appends the environment key, then emits + // the one-entry matrix. + for _, line := range []string{ + `DEFAULT_INPUTS="$DEFAULT_INPUTS_SERVICE"`, + `ENV_INPUTS="$ENV_INPUTS_SERVICE"`, + `ENV_OVERRIDE=$(echo "$ENV_INPUTS" | jq -c --arg env "$TARGET_ENV" '.[$env] // {}')`, + `RESOLVED=$(echo "$DEFAULT_INPUTS" | jq -c --argjson override "$ENV_OVERRIDE" '. + $override')`, + `RESOLVED=$(echo "$RESOLVED" | jq -c --arg env "$TARGET_ENV" '. + {environment: $env}')`, + `MATRIX_SERVICE="[$RESOLVED]"`, + `echo "deploy_service_matrix=${MATRIX_SERVICE}"`, + } { + assert.Contains(t, contextJob, line, + "the context step must resolve the one-entry matrix the promote way: %q", line) + } + }) + + t.Run("state refs resolve into the env payload at generation time", func(t *testing.T) { + // A ${{ state.. }} reference resolves at generation time + // against the named environment, exactly as promote resolves the same + // deploy input: the default-level state ref seeds every env entry of + // the ENV_INPUTS payload, so the run-time merge selects the already + // resolved value. + dir := writeHotfixDeployStub(t, "environment", "sha", "prev") + cfg := hotfixDeployInputConfig( + map[string]interface{}{"prev": "${{ state.prod.version }}"}, + nil, + ) + gen := NewHotfixGenerator(cfg, dir) + gen.SetState(map[string]*config.EnvState{ + "prod": {Version: "v2.0.0"}, + }) + content, err := gen.Generate() + require.NoError(t, err) + + contextJob := extractJobSection(t, content, "context:") + require.NotEmpty(t, contextJob, "context job section should be present") + assert.Contains(t, contextJob, `DEFAULT_INPUTS_SERVICE: '{}'`, + "a default-level state ref must not sit in the default payload (promote moves it to the env entries)") + assert.Contains(t, contextJob, `ENV_INPUTS_SERVICE: '{"dev":{"prev":"v2.0.0"},"prod":{"prev":"v2.0.0"},"test":{"prev":"v2.0.0"}}'`, + "the resolved state ref must seed every env entry of the payload (sorted keys, json.Marshal order)") + + deploy := jobBlock(t, content, "deploy-service") + assert.Contains(t, deploy, " prev: ${{ matrix.prev }}", + "the state-ref input must thread from the matrix entry") + assert.NotContains(t, content, "state.prod.version", + "the raw state reference must not survive into the emitted workflow") + }) + + t.Run("unresolved state ref keeps the raw expression like promote", func(t *testing.T) { + // The matrix payload is promote's: an unresolved state ref keeps the + // raw expression rather than failing generation, and the surviving + // ${{ state.* }} text fails loudly when GitHub parses the workflow. + // (The hotfix build lane fails generation instead; the deploy lane + // deliberately matches promote, its oracle for this payload.) + dir := writeHotfixDeployStub(t, "environment", "sha", "prev") + cfg := hotfixDeployInputConfig( + map[string]interface{}{"prev": "${{ state.prod.version }}"}, + nil, + ) + gen := NewHotfixGenerator(cfg, dir) + gen.SetState(map[string]*config.EnvState{}) + _, err := gen.Generate() + require.NoError(t, err, + "an unresolved state ref on the deploy matrix path must keep promote's keep-raw semantics, not fail generation") + + content, err := NewHotfixGenerator(cfg, dir).Generate() + require.NoError(t, err) + assert.Contains(t, content, "state.prod.version", + "the raw state reference must stay visible in the payload rather than being silently dropped") + }) + + t.Run("env-inputs-only key threads without a default", func(t *testing.T) { + // A key that exists only under env_inputs (no inputs: default) still + // threads: the matrix entry carries the resolved target env's value. + dir := writeHotfixDeployStub(t, "environment", "sha", "replicas") + cfg := hotfixDeployInputConfig( + nil, + map[string]map[string]interface{}{ + "test": {"replicas": 4}, + "prod": {"replicas": 6}, + }, + ) + content, err := NewHotfixGenerator(cfg, dir).Generate() + require.NoError(t, err) + + deploy := jobBlock(t, content, "deploy-service") + assert.Contains(t, deploy, " replicas: ${{ matrix.replicas }}", + "an env-inputs-only key must thread from the matrix entry") + contextJob := extractJobSection(t, content, "context:") + assert.Contains(t, contextJob, `DEFAULT_INPUTS_SERVICE: '{}'`, + "no default payload keys exist for an env-inputs-only input") + }) + + t.Run("matrix-referencing input is left out", func(t *testing.T) { + // The hotfix deploy's matrix is a synthetic one-entry construct; an + // operator value referencing ${{ matrix.* }} - whole, embedded, or + // deeper inside an expression - has no leg set to resolve against + // (promote substitutes per promotion; hotfix has none), so it is left + // out rather than threaded as a literal the callback would receive + // verbatim. A threadable key beside it still rides the matrix, which + // keeps this assertion non-vacuous: the payload exists and must not + // carry the dropped key. + dir := writeHotfixDeployStub(t, "environment", "sha", "os", "image", "runner", "replicas") + cfg := hotfixDeployInputConfig( + map[string]interface{}{ + "os": "${{ matrix.os }}", + "image": "img-${{ matrix.os }}", + "runner": "${{ format('{0}', matrix.os) }}", + "replicas": 2, + }, + nil, + ) + content, err := NewHotfixGenerator(cfg, dir).Generate() + require.NoError(t, err) + + deploy := jobBlock(t, content, "deploy-service") + assert.NotContains(t, deploy, "matrix.os", + "a matrix-referencing operator value must not be threaded in any form") + assert.Contains(t, deploy, " replicas: ${{ matrix.replicas }}", + "a non-matrix-referencing key beside the dropped ones must still thread") + + contextJob := extractJobSection(t, content, "context:") + require.NotEmpty(t, contextJob, "context job section should be present") + assert.Contains(t, contextJob, `"replicas":2`, + "the threadable key rides the payload (this is what makes the os assertions below meaningful)") + for _, dropped := range []string{`"os"`, `"image"`, `"runner"`, `matrix.os`} { + assert.NotContains(t, contextJob, dropped, + "a matrix-referencing value must not ride the matrix JSON: %q", dropped) + } + }) + + t.Run("needs-referencing input is left out", func(t *testing.T) { + // Both lanes need only `context` in common (the deploy lane adds the + // builds, the rollback lane the failing deploy), so a needs.build-* + // reference resolves on one lane but not the other, where actionlint + // rejects it. Such values are dropped on both lanes, the same filter + // the hotfix build lane applies. + dir := writeHotfixDeployStub(t, "environment", "sha", "upstream", "fix", "note") + cfg := hotfixDeployInputConfig( + map[string]interface{}{ + "upstream": "${{ needs.build-app.outputs.image_tag }}", + "fix": "sha-${{ needs.setup.outputs.fix_sha }}", + "note": "needs.setup", + }, + nil, + ) + content, err := NewHotfixGenerator(cfg, dir).Generate() + require.NoError(t, err) + + for _, jobID := range []string{"deploy-service", "rollback-service"} { + block := jobBlock(t, content, jobID) + assert.NotContains(t, block, "needs.build-app.outputs.image_tag", + "%s must not thread a build-output reference; the rollback lane cannot resolve it", jobID) + assert.NotContains(t, block, "needs.setup.outputs.fix_sha", + "%s must not thread a needs reference to a job not in its needs list", jobID) + assert.NotContains(t, block, " upstream:", + "%s must leave the needs-referencing input out entirely", jobID) + assert.NotContains(t, block, " fix:", + "%s must leave the embedded needs-referencing input out entirely", jobID) + // A literal merely containing the text "needs.setup" is not a + // needs reference; on the deploy lane it rides the matrix like + // any other literal (the build lane renders it verbatim instead). + assert.Contains(t, block, " note: ${{ matrix.note }}", + "a literal merely containing the text needs.setup is not a needs reference and must thread (via the matrix, like every deploy literal)", jobID) + } + assert.NotContains(t, content, "needs.build-app.outputs.image_tag", + "a needs reference must not survive anywhere in the emitted workflow") + assert.NotContains(t, content, "needs.setup.outputs.fix_sha", + "an embedded needs reference must not survive anywhere either") + contextJob := extractJobSection(t, content, "context:") + assert.Contains(t, contextJob, `"note":"needs.setup"`, + "the literal rides the matrix payload verbatim") + }) + + t.Run("passthrough needs a default; env-only passthroughs drop", func(t *testing.T) { + // Only a passthrough whose inputs: default is itself a passthrough + // threads (the default value, verbatim). An env_inputs-only + // passthrough has no generation-time value that is correct for the + // run-time-resolved target environment, and passing another + // environment's expression would be silently wrong, so those keys - + // and a passthrough override of a literal default - drop entirely. + dir := writeHotfixDeployStub(t, "environment", "sha", "region", "role", "flavor") + cfg := hotfixDeployInputConfig( + map[string]interface{}{"region": "${{ vars.DEPLOY_REGION }}"}, + map[string]map[string]interface{}{ + "test": {"role": "${{ vars.TEST_ROLE }}"}, + "prod": {"role": "${{ vars.PROD_ROLE }}", "flavor": "${{ vars.PROD_FLAVOR }}"}, + }, + ) + cfg.Deploys[0].Inputs["flavor"] = "literal-default" + content, err := NewHotfixGenerator(cfg, dir).Generate() + require.NoError(t, err) + + deploy := jobBlock(t, content, "deploy-service") + assert.Contains(t, deploy, " region: ${{ vars.DEPLOY_REGION }}", + "a default-level passthrough threads its default verbatim") + assert.NotContains(t, deploy, "role:", + "an env_inputs-only passthrough must drop: no generation-time value is correct for the resolved target env") + assert.NotContains(t, deploy, "flavor: ${{ vars.PROD_FLAVOR }}", + "a passthrough override of a non-passthrough default must drop rather than emit another env's expression") + assert.NotContains(t, deploy, "TEST_ROLE", + "no other environment's passthrough expression may leak onto the hotfix lane") + assert.NotContains(t, deploy, "PROD_ROLE", + "no other environment's passthrough expression may leak onto the hotfix lane") + + // The literal-default key with a passthrough override drops as a + // whole (not even the literal threads), so nothing duplicates or + // half-threads it. + assert.NotContains(t, deploy, "flavor:", + "a key with a passthrough override and a literal default drops entirely rather than half-threading") + }) + + t.Run("component scope keeps the flat reads for matrix inputs", func(t *testing.T) { + // The matrix payload derives from the manifest's inputs/env_inputs, so + // a component-scoped hotfix workflow resolves it exactly like the + // single-component one (only the state reads are component-scoped). + dir := writeHotfixDeployStub(t, "environment", "sha", "replicas") + cfg := hotfixDeployInputConfig( + map[string]interface{}{"replicas": 2}, + map[string]map[string]interface{}{"test": {"replicas": 4}}, + ) + content, err := NewHotfixGenerator(cfg, dir, WithHotfixComponentName("api")).Generate() + require.NoError(t, err) + + deploy := jobBlock(t, content, "deploy-service") + assert.Contains(t, deploy, " replicas: ${{ matrix.replicas }}", + "the component-scoped deploy must thread the matrix input the same way") + assert.Contains(t, deploy, + " include: ${{ fromJSON(needs.context.result == 'success' && needs.context.outputs.deploy_service_matrix || '[]') }}", + "the component-scoped deploy must fan out on the same matrix") + }) +} + +// TestHotfixGenerator_DeployThreadsImageRefs guards the image half of #697: +// the deploy lane threads image_tag/image_digest from the depends_on build +// jobs' workflow_call outputs (orchestrate's direct-dependency rule), and the +// rollback lane reads the N-1 image refs from live manifest state in the +// context job (version for the tag, the first non-empty builds artifact_id +// for the digest, promote's first-non-empty rule). +func TestHotfixGenerator_DeployThreadsImageRefs(t *testing.T) { + t.Run("deploy lane threads build outputs", func(t *testing.T) { + dir := writeHotfixBuildStubOutputs(t, + []string{"environment", "sha"}, + []string{"image_tag", "artifact_id"}, + ) + writeHotfixCallbackStub(t, dir, "deploy.yaml", "environment", "sha", "image_tag", "image_digest") + cfg := threeEnvHotfixConfig() + cfg.Deploys[0].DependsOn = []string{"app"} + content, err := NewHotfixGenerator(cfg, dir).Generate() + require.NoError(t, err) + + deploy := jobBlock(t, content, "deploy-service") + assert.Contains(t, deploy, " image_tag: ${{ needs.build-app.outputs.image_tag }}", + "the deploy lane must thread image_tag from the depends_on build's output") + assert.Contains(t, deploy, " image_digest: ${{ needs.build-app.outputs.artifact_id }}", + "the deploy lane must thread image_digest from the depends_on build's artifact_id output") + }) + + t.Run("rollback lane threads manifest-state refs", func(t *testing.T) { + dir := writeHotfixBuildStubOutputs(t, + []string{"environment", "sha"}, + []string{"image_tag", "artifact_id"}, + ) + writeHotfixCallbackStub(t, dir, "deploy.yaml", "environment", "sha", "image_tag", "image_digest") + cfg := threeEnvHotfixConfig() + cfg.Deploys[0].DependsOn = []string{"app"} + content, err := NewHotfixGenerator(cfg, dir).Generate() + require.NoError(t, err) + + rollback := jobBlock(t, content, "rollback-service") + assert.Contains(t, rollback, " image_tag: ${{ needs.context.outputs.rollback_image_tag }}", + "the rollback lane must thread the N-1 image tag from the context job") + assert.Contains(t, rollback, " image_digest: ${{ needs.context.outputs.rollback_image_digest }}", + "the rollback lane must thread the N-1 image digest from the context job") + + contextJob := extractJobSection(t, content, "context:") + require.NotEmpty(t, contextJob, "context job section should be present") + assert.Contains(t, contextJob, "rollback_image_tag: ${{ steps.ctx.outputs.rollback_image_tag }}", + "the context job must expose the N-1 image tag output") + assert.Contains(t, contextJob, "rollback_image_digest: ${{ steps.ctx.outputs.rollback_image_digest }}", + "the context job must expose the N-1 image digest output") + // The tag read mirrors the rollback_sha read; the digest read is + // promote's first-non-empty rule over the sorted build names. + assert.Contains(t, contextJob, `ROLLBACK_IMAGE_TAG=$(yq eval ".$MANIFEST_KEY.state.${TARGET_ENV}.version // \"\"" "$MANIFEST_FILE")`, + "the context step must read the N-1 version as the rollback image tag") + assert.Contains(t, contextJob, `ROLLBACK_IMAGE_DIGEST=$(yq eval "[.$MANIFEST_KEY.state.${TARGET_ENV}.builds // {} | to_entries | sort_by(.key) | .[].value.artifact_id // \"\" | select(. != \"\")] | .[0] // \"\"" "$MANIFEST_FILE")`, + "the context step must read the first non-empty build artifact_id as the rollback image digest, tolerating an env with no builds map") + assert.Contains(t, contextJob, `echo "rollback_image_tag=${ROLLBACK_IMAGE_TAG}"`, + "the N-1 image tag must be emitted as a context output") + assert.Contains(t, contextJob, `echo "rollback_image_digest=${ROLLBACK_IMAGE_DIGEST}"`, + "the N-1 image digest must be emitted as a context output") + }) + + t.Run("component scope reads the component state subtree", func(t *testing.T) { + dir := writeHotfixBuildStubOutputs(t, + []string{"environment", "sha"}, + []string{"image_tag", "artifact_id"}, + ) + writeHotfixCallbackStub(t, dir, "deploy.yaml", "environment", "sha", "image_tag", "image_digest") + cfg := threeEnvHotfixConfig() + cfg.Deploys[0].DependsOn = []string{"app"} + content, err := NewHotfixGenerator(cfg, dir, WithHotfixComponentName("api")).Generate() + require.NoError(t, err) + + contextJob := extractJobSection(t, content, "context:") + require.NotEmpty(t, contextJob, "context job section should be present") + assert.Contains(t, contextJob, `ROLLBACK_IMAGE_TAG=$(yq eval ".$MANIFEST_KEY.state.components.api.${TARGET_ENV}.version // \"\"" "$MANIFEST_FILE")`, + "the component-scoped context job must read the component's own state subtree for the tag") + assert.Contains(t, contextJob, `ROLLBACK_IMAGE_DIGEST=$(yq eval "[.$MANIFEST_KEY.state.components.api.${TARGET_ENV}.builds // {} | to_entries | sort_by(.key) | .[].value.artifact_id // \"\" | select(. != \"\")] | .[0] // \"\"" "$MANIFEST_FILE")`, + "the component-scoped context job must read the component's own builds for the digest") + assert.NotContains(t, contextJob, `state.${TARGET_ENV}.version`, + "the component-scoped read must not fall back to the flat state path") + }) + + t.Run("build without outputs leaves the deploy lane without image inputs", func(t *testing.T) { + // No depends_on build declares the outputs, so the deploy lane has no + // source and must omit the inputs; the rollback lane still threads the + // manifest-state refs, which need no build output. + dir := writeHotfixBuildStub(t, "environment", "sha") + writeHotfixCallbackStub(t, dir, "deploy.yaml", "environment", "sha", "image_tag", "image_digest") + cfg := threeEnvHotfixConfig() + cfg.Deploys[0].DependsOn = []string{"app"} + content, err := NewHotfixGenerator(cfg, dir).Generate() + require.NoError(t, err) + + deploy := jobBlock(t, content, "deploy-service") + assert.NotContains(t, deploy, "image_tag:", + "the deploy lane must not reference an output the build does not declare") + assert.NotContains(t, deploy, "image_digest:", + "the deploy lane must not reference an artifact_id the build does not declare") + + rollback := jobBlock(t, content, "rollback-service") + assert.Contains(t, rollback, " image_tag: ${{ needs.context.outputs.rollback_image_tag }}", + "the rollback lane still threads the state-sourced image tag") + assert.Contains(t, rollback, " image_digest: ${{ needs.context.outputs.rollback_image_digest }}", + "the rollback lane still threads the state-sourced image digest") + }) + + t.Run("image inputs gated on declaration", func(t *testing.T) { + // The build declares the outputs but the callee declares neither image + // input, so nothing threads and the context job emits neither rollback + // image output. + dir := writeHotfixBuildStubOutputs(t, + []string{"environment", "sha"}, + []string{"image_tag", "artifact_id"}, + ) + writeHotfixCallbackStub(t, dir, "deploy.yaml", "environment", "sha") + cfg := threeEnvHotfixConfig() + cfg.Deploys[0].DependsOn = []string{"app"} + content, err := NewHotfixGenerator(cfg, dir).Generate() + require.NoError(t, err) + + for _, jobID := range []string{"deploy-service", "rollback-service"} { + block := jobBlock(t, content, jobID) + assert.NotContains(t, block, "image_tag:", + "%s must not pass the image_tag input a callee does not declare", jobID) + assert.NotContains(t, block, "image_digest:", + "%s must not pass the image_digest input a callee does not declare", jobID) + } + contextJob := extractJobSection(t, content, "context:") + assert.NotContains(t, contextJob, "rollback_image_tag", + "the context job must not emit a rollback image output nothing consumes") + assert.NotContains(t, contextJob, "rollback_image_digest", + "the context job must not emit a rollback image output nothing consumes") + }) + + t.Run("image_digest alone threads without image_tag", func(t *testing.T) { + // The two image inputs gate independently, mirroring promote's + // additive image_digest threading. + dir := writeHotfixBuildStubOutputs(t, + []string{"environment", "sha"}, + []string{"image_tag", "artifact_id"}, + ) + writeHotfixCallbackStub(t, dir, "deploy.yaml", "environment", "sha", "image_digest") + cfg := threeEnvHotfixConfig() + cfg.Deploys[0].DependsOn = []string{"app"} + content, err := NewHotfixGenerator(cfg, dir).Generate() + require.NoError(t, err) + + deploy := jobBlock(t, content, "deploy-service") + assert.Contains(t, deploy, " image_digest: ${{ needs.build-app.outputs.artifact_id }}", + "a callee declaring only image_digest must still receive it") + assert.NotContains(t, deploy, "image_tag:", + "a callee not declaring image_tag must not receive it") + + rollback := jobBlock(t, content, "rollback-service") + assert.Contains(t, rollback, " image_digest: ${{ needs.context.outputs.rollback_image_digest }}", + "the rollback lane threads image_digest alone too") + assert.NotContains(t, rollback, "image_tag:", + "the rollback lane must not thread an undeclared image_tag") + + contextJob := extractJobSection(t, content, "context:") + assert.Contains(t, contextJob, "rollback_image_digest: ${{ steps.ctx.outputs.rollback_image_digest }}", + "the context job emits only the digest output") + assert.NotContains(t, contextJob, "rollback_image_tag", + "the context job must not emit an unconsumed tag output") + }) + + t.Run("cross-repo build is assumed to declare artifact_id only", func(t *testing.T) { + // A cross-repo build cannot be parsed locally, so the deploy lane + // assumes the callback contract's artifact_id output (crossRepoOutputs) + // and threads image_digest but not image_tag, which no contract + // output backs. + dir := writeHotfixDeployStub(t, "environment", "sha", "image_tag", "image_digest") + cfg := threeEnvHotfixConfig() + cfg.Builds[0].Workflow = "org/satellite/.github/workflows/build.yaml@v1" + cfg.Deploys[0].DependsOn = []string{"app"} + content, err := NewHotfixGenerator(cfg, dir).Generate() + require.NoError(t, err) + + deploy := jobBlock(t, content, "deploy-service") + assert.Contains(t, deploy, " image_digest: ${{ needs.build-app.outputs.artifact_id }}", + "the assumed artifact_id output backs image_digest for a cross-repo build") + assert.NotContains(t, deploy, "image_tag: ${{ needs.build-app.outputs.image_tag }}", + "no assumed output backs image_tag for a cross-repo build") + }) +} + +// TestHotfixGenerator_DeployRequiredInputCheck guards the #697 generate-time +// check, the hotfix port of promote's validateRequiredInputs: a deploy whose +// callback declares a required input no hotfix lane can supply fails +// generation with a message naming the deploy and the input. +func TestHotfixGenerator_DeployRequiredInputCheck(t *testing.T) { + t.Run("required input no lane supplies fails generation", func(t *testing.T) { + dir := writeHotfixDeployStubRequired(t, map[string]bool{ + "environment": true, + "zone": true, + }) + cfg := threeEnvHotfixConfig() + _, err := NewHotfixGenerator(cfg, dir).Generate() + require.Error(t, err, + "a required input nothing supplies must fail generation instead of emitting a dispatch GitHub would reject") + assert.Contains(t, err.Error(), "deploy-service requires input 'zone'", + "the error must name the deploy and the input") + assert.Contains(t, err.Error(), "cannot be provided in the hotfix workflow", + "the error must say which workflow cannot provide it") + assert.Contains(t, err.Error(), "required input validation failed", + "the error keeps promote's validation-failed framing") + }) + + t.Run("required operator input passed by the manifest passes", func(t *testing.T) { + dir := writeHotfixDeployStubRequired(t, map[string]bool{ + "environment": true, + "zone": true, + }) + cfg := hotfixDeployInputConfig(map[string]interface{}{"zone": "us-east-1"}, nil) + content, err := NewHotfixGenerator(cfg, dir).Generate() + require.NoError(t, err, + "a required input the manifest passes under inputs: is supplied by the matrix and must generate") + deploy := jobBlock(t, content, "deploy-service") + assert.Contains(t, deploy, " zone: ${{ matrix.zone }}", + "the required operator input must actually be threaded") + }) + + t.Run("required operator input passed only by env_inputs passes", func(t *testing.T) { + dir := writeHotfixDeployStubRequired(t, map[string]bool{ + "environment": true, + "zone": true, + }) + cfg := hotfixDeployInputConfig(nil, map[string]map[string]interface{}{ + "test": {"zone": "us-test-1"}, + "prod": {"zone": "us-prod-1"}, + }) + _, err := NewHotfixGenerator(cfg, dir).Generate() + require.NoError(t, err, + "a required input the manifest passes under env_inputs: is supplied by the matrix and must generate") + }) + + t.Run("required image inputs fail on the deploy lane with no producing build", func(t *testing.T) { + // No depends_on build declares the image_tag / artifact_id outputs, + // so the deploy lane has no source for either input and omits the + // with: lines. The rollback lane still reads both refs from manifest + // state, but that is not enough: both lanes call the callback, so a + // required input must be suppliable on each, and the deploy lane's + // dispatch would fail - generation must refuse and name the lane. + dir := writeHotfixBuildStub(t, "environment", "sha") + writeHotfixDeployStubRequiredIn(t, dir, map[string]bool{ + "environment": true, + "image_tag": true, + "image_digest": true, + }) + cfg := threeEnvHotfixConfig() + cfg.Deploys[0].DependsOn = []string{"app"} + _, err := NewHotfixGenerator(cfg, dir).Generate() + require.Error(t, err, + "the rollback lane's manifest-state reads do not help the deploy lane: a required image input with no depends_on build declaring the output must fail generation") + assert.Contains(t, err.Error(), + "deploy-service requires input 'image_tag' but the hotfix deploy lane cannot supply it", + "the error must name the deploy, the input, and the lane that cannot supply it") + assert.Contains(t, err.Error(), + "depends_on build's declared image_tag output", + "the error must say where the deploy lane sources image_tag") + assert.Contains(t, err.Error(), + "deploy-service requires input 'image_digest' but the hotfix deploy lane cannot supply it", + "the digest divergence must be reported too") + assert.Contains(t, err.Error(), + "depends_on build's declared artifact_id output", + "the error must say where the deploy lane sources image_digest") + assert.Contains(t, err.Error(), "required input validation failed", + "the error keeps promote's validation-failed framing") + }) + + t.Run("required image inputs pass when a depends_on build outputs them", func(t *testing.T) { + // The depends_on build declares the image_tag / artifact_id outputs, + // so the deploy lane threads both from the build job's outputs while + // the rollback lane keeps its manifest-state source: every lane that + // calls the callback supplies the inputs, so generation succeeds. + dir := writeHotfixBuildStubOutputs(t, []string{"environment", "sha"}, []string{"image_tag", "artifact_id"}) + writeHotfixDeployStubRequiredIn(t, dir, map[string]bool{ + "environment": true, + "image_tag": true, + "image_digest": true, + }) + cfg := threeEnvHotfixConfig() + cfg.Deploys[0].DependsOn = []string{"app"} + content, err := NewHotfixGenerator(cfg, dir).Generate() + require.NoError(t, err, + "with a depends_on build declaring the outputs, both hotfix lanes supply the required image inputs and generation must succeed") + + deploy := jobBlock(t, content, "deploy-service") + assert.Contains(t, deploy, " image_tag: ${{ needs.build-app.outputs.image_tag }}", + "the deploy lane is the lane that was starving image_tag; it must now thread the build's output") + assert.Contains(t, deploy, " image_digest: ${{ needs.build-app.outputs.artifact_id }}", + "the deploy lane must thread the build's artifact_id as image_digest") + rollback := jobBlock(t, content, "rollback-service") + assert.Contains(t, rollback, " image_tag: ${{ needs.context.outputs.rollback_image_tag }}", + "the rollback lane keeps its manifest-state source for image_tag") + assert.Contains(t, rollback, " image_digest: ${{ needs.context.outputs.rollback_image_digest }}", + "the rollback lane keeps its manifest-state source for image_digest") + }) + + t.Run("required contract inputs pass", func(t *testing.T) { + dir := writeHotfixDeployStubRequired(t, map[string]bool{ + "environment": true, + "sha": true, + "dry_run": true, + }) + _, err := NewHotfixGenerator(threeEnvHotfixConfig(), dir).Generate() + require.NoError(t, err, + "the contract inputs are supplied by both lanes and must not fail generation") + }) + + t.Run("required passthrough input passes", func(t *testing.T) { + dir := writeHotfixDeployStubRequired(t, map[string]bool{ + "environment": true, + "region": true, + }) + cfg := hotfixDeployInputConfig(map[string]interface{}{"region": "${{ vars.DEPLOY_REGION }}"}, nil) + _, err := NewHotfixGenerator(cfg, dir).Generate() + require.NoError(t, err, + "a required input supplied as a verbatim passthrough must not fail generation") + }) + + t.Run("matrix-referencing input is not suppliable", func(t *testing.T) { + // The hotfix deploy matrix is synthetic; a ${{ matrix.* }} value has + // no leg to resolve against, so it cannot supply a required input. + dir := writeHotfixDeployStubRequired(t, map[string]bool{ + "environment": true, + "os": true, + }) + cfg := hotfixDeployInputConfig(map[string]interface{}{"os": "${{ matrix.os }}"}, nil) + _, err := NewHotfixGenerator(cfg, dir).Generate() + require.Error(t, err, + "a required input whose only manifest value references matrix.* has no hotfix source and must fail generation") + assert.Contains(t, err.Error(), "deploy-service requires input 'os'", + "the error must name the deploy and the input") + }) + + t.Run("cross-repo deploy is not checked", func(t *testing.T) { + // A cross-repo callee cannot be parsed locally, so its required-input + // set is unknowable and the check skips it, mirroring promote. + dir := writeHotfixDeployStubRequired(t, map[string]bool{"environment": true}) + cfg := threeEnvHotfixConfig() + cfg.Deploys[0].Workflow = "org/satellite/.github/workflows/deploy.yaml@v1" + _, err := NewHotfixGenerator(cfg, dir).Generate() + require.NoError(t, err, + "a cross-repo deploy callback cannot be parsed and must not fail the check") + }) + + t.Run("available list names the manifest-declared inputs", func(t *testing.T) { + dir := writeHotfixDeployStubRequired(t, map[string]bool{ + "environment": true, + "zone": true, + "flavor": true, + }) + cfg := hotfixDeployInputConfig(map[string]interface{}{"zone": "us-east-1"}, nil) + _, err := NewHotfixGenerator(cfg, dir).Generate() + require.Error(t, err) + assert.Contains(t, err.Error(), + "(available: environment, sha, dry_run, image_tag, image_digest, zone)", + "the error's available list must include the manifest-declared inputs") + }) +} + +// writeHotfixBuildStubOutputs stages a reusable build-callback workflow +// declaring the given workflow_call inputs and outputs into a temp repo +// layout, returning the base directory. The outputs matter to the hotfix +// deploy lane, which sources image_tag/image_digest from the depends_on +// builds' declared outputs; each declared output is emitted by the stub job +// so actionlint resolves the caller's needs..outputs. references +// under full strictness. +func writeHotfixBuildStubOutputs(t *testing.T, inputNames, outputNames []string) string { + t.Helper() + dir := t.TempDir() + writeHotfixCallbackStubOutputs(t, dir, "build.yaml", inputNames, outputNames) + return dir +} + +// writeHotfixCallbackStubOutputs writes a reusable callback workflow declaring +// the given input names and workflow_call output names at +// .github/workflows/ under dir. Inputs render exactly like +// writeHotfixCallbackStub (dry_run as boolean); each output is declared on the +// workflow_call block, mapped from the stub job's outputs, and emitted by a +// step so the stub is a valid, resolvable callee. +func writeHotfixCallbackStubOutputs(t *testing.T, dir, name string, inputNames, outputNames []string) { + t.Helper() + require.NoError(t, os.MkdirAll(filepath.Join(dir, ".github", "workflows"), 0o755)) + var inputs strings.Builder + for _, in := range inputNames { + typ := "string" + if in == "dry_run" { + typ = "boolean" + } + fmt.Fprintf(&inputs, " %s:\n required: false\n type: %s\n", in, typ) + } + var callOutputs, jobOutputs, echoStep strings.Builder + for _, out := range outputNames { + fmt.Fprintf(&callOutputs, " %s:\n description: stub output\n value: ${{ jobs.callback.outputs.%s }}\n", out, out) + fmt.Fprintf(&jobOutputs, " %s: ${{ steps.stub.outputs.%s }}\n", out, out) + fmt.Fprintf(&echoStep, " echo \"%s=stub-%s\" >> \"$GITHUB_OUTPUT\"\n", out, out) + } + callOutputsBlock := "" + if len(outputNames) > 0 { + callOutputsBlock = " outputs:\n" + callOutputs.String() + } + jobOutputsBlock := "" + echoBlock := "" + if len(outputNames) > 0 { + jobOutputsBlock = " outputs:\n" + jobOutputs.String() + echoBlock = " - id: stub\n run: |\n" + echoStep.String() + } + stub := fmt.Sprintf(`name: Callback +on: + workflow_call: + inputs: +%s +%sjobs: + callback: + runs-on: ubuntu-latest +%s steps: +%s - run: 'true' +`, inputs.String(), callOutputsBlock, jobOutputsBlock, echoBlock) + require.NoError(t, os.WriteFile(filepath.Join(dir, ".github", "workflows", name), []byte(stub), 0o644)) +} + +// writeHotfixDeployStubRequired writes a deploy-callback stub whose +// workflow_call inputs carry the caller-chosen required flags into a temp repo +// layout, returning the base directory. required: true entries carry no +// default, so ParseWorkflowRequiredInputs counts them; dry_run renders as a +// boolean input like writeHotfixCallbackStub. +func writeHotfixDeployStubRequired(t *testing.T, required map[string]bool) string { + t.Helper() + dir := t.TempDir() + writeHotfixDeployStubRequiredIn(t, dir, required) + return dir +} + +// writeHotfixDeployStubRequiredIn writes the required-flag deploy-callback +// stub into an existing base directory, so a test can stage build and deploy +// stubs in one repo layout. +func writeHotfixDeployStubRequiredIn(t *testing.T, dir string, required map[string]bool) { + t.Helper() + require.NoError(t, os.MkdirAll(filepath.Join(dir, ".github", "workflows"), 0o755)) + names := make([]string, 0, len(required)) + for name := range required { + names = append(names, name) + } + sort.Strings(names) + var inputs strings.Builder + for _, name := range names { + typ := "string" + if name == "dry_run" { + typ = "boolean" + } + if required[name] { + fmt.Fprintf(&inputs, " %s:\n required: true\n type: %s\n", name, typ) + } else { + fmt.Fprintf(&inputs, " %s:\n required: false\n type: %s\n", name, typ) + } + } + stub := fmt.Sprintf(`name: Deploy +on: + workflow_call: + inputs: +%s +jobs: + deploy: + runs-on: ubuntu-latest + steps: + - run: 'true' +`, inputs.String()) + require.NoError(t, os.WriteFile(filepath.Join(dir, ".github", "workflows", "deploy.yaml"), []byte(stub), 0o644)) +} + +// TestHotfixGenerator_ActionlintDeployInputs is the #697 feature-matrix proof +// under actionlint: a hotfix deploy whose callback declares image_tag as +// REQUIRED, the manifest threading operator inputs (a literal and a vars +// passthrough) plus env_inputs, against a build callback that declares the +// image_tag/artifact_id outputs. actionlint validates the emitted call end to +// end -- the one-entry matrix on a uses: job under the pull_request (closed) +// event, the matrix.* with: references, the needs.build-*.outputs.* image +// references, and the context step's jq/yq script under shellcheck -- so the +// generated workflow is the shape GitHub accepts. +func TestHotfixGenerator_ActionlintDeployInputs(t *testing.T) { + bin, err := exec.LookPath("actionlint") + if err != nil { + t.Skip("actionlint not installed") + } + + dir := writeHotfixBuildStubOutputs(t, + []string{"environment", "sha"}, + []string{"image_tag", "artifact_id"}, + ) + writeHotfixDeployStubRequiredIn(t, dir, map[string]bool{ + "environment": true, + "image_tag": true, + "replicas": false, + "region": false, + }) + cfg := threeEnvHotfixConfig() + cfg.Deploys[0].DependsOn = []string{"app"} + cfg.Deploys[0].Inputs = map[string]interface{}{ + "replicas": 2, + "region": "${{ vars.DEPLOY_REGION }}", + } + cfg.Deploys[0].EnvInputs = map[string]map[string]interface{}{ + "test": {"replicas": 4}, + "prod": {"replicas": 6}, + } + gen := NewHotfixGenerator(cfg, dir) + content, err := gen.Generate() + require.NoError(t, err) + + wfPath := filepath.Join(dir, ".github", "workflows", "cascade-hotfix.yaml") + require.NoError(t, os.WriteFile(wfPath, []byte(content), 0644)) + + // Initialize the temp dir as its own git repository so actionlint's + // reusable-workflow resolution stays scoped to it. + gitInit := exec.Command("git", "init", "-q") + gitInit.Dir = dir + require.NoError(t, gitInit.Run(), "git init for actionlint project root") + + cmd := exec.Command(bin, wfPath) + cmd.Dir = dir + out, runErr := cmd.CombinedOutput() + assert.NoError(t, runErr, "actionlint reported issues:\n%s", string(out)) } // TestHotfixGenerator_DeployCallbackSecretsAndPermissions verifies the hotfix diff --git a/internal/generate/promote.go b/internal/generate/promote.go index 3c79c8d..b87f475 100644 --- a/internal/generate/promote.go +++ b/internal/generate/promote.go @@ -187,16 +187,103 @@ func (g *PromoteGenerator) discoverDeployInputs() error { return nil } -// validateRequiredInputs checks that all required inputs can be satisfied -func (g *PromoteGenerator) validateRequiredInputs() error { - // In promote workflow, available inputs come from preflight outputs - availableInputs := map[string]string{ - "environment": "preflight.outputs.target_env", - "sha": "preflight.outputs.source_sha", - "image_tag": "preflight.outputs.source_image_tag", - "image_digest": "preflight.outputs.source_image_digest", +// promoteDeployLane describes one job the promote generator emits that calls a +// configured deploy's callback. validateRequiredInputs must agree with +// writeDeployJobs and writeRollbackJobs about which lanes exist and which +// inputs each threads: GitHub validates every emitted call against the +// callee's workflow_call inputs (actionlint's [workflow-call] check enforces +// the same rule), so a required input an emitted lane omits is a dispatch the +// generated workflow can never make successfully. +type promoteDeployLane struct { + // label names the lane in validation errors, e.g. "prod deploy job + // (deploy-service-prod)". + label string + // emitted reports whether writeJobs generates the lane's job for this + // deploy. + emitted bool + // threadsOperatorInputs reports whether the lane's with: block threads + // the keys the manifest declares under the deploy's inputs:. Only the + // matrix deploy job does: it emits every such key (passthrough + // expressions verbatim, the rest as matrix.). The other lanes thread + // only the callback contract: environment and sha always (the rollback + // job gates both on the callee's declared inputs and threads no image + // input - it has no source for either, #705), image_tag when the callee + // declares it on the single-environment and prod paths, and - on the + // single-environment path only - image_digest when declared. An operator + // input never reaches them, and the matrix deploy job itself auto-threads + // only environment and sha beyond its operator inputs - image_tag/ + // image_digest reach it only when the manifest wires them under inputs:. + threadsOperatorInputs bool +} + +// promoteDeployLanes returns, in writeJobs' emission order, the jobs the +// promote workflow generates that call d's callback. A deploy with inputs: +// takes the matrix deploy job; without inputs: it takes the +// single-environment deploy job instead; the prod deploy job and the rollback +// job are emitted for every deploy. All four are gated on the workflow having +// at least one environment - writeDeployJobs' opening condition, which +// writeRollbackJobs shares - so a deploy whose matrix job is emitted always +// carries the prod and rollback jobs alongside it. +func (g *PromoteGenerator) promoteDeployLanes(d *config.DeployConfig) []promoteDeployLane { + deployJobsEmitted := len(g.config.Environments) > 0 + hasInputs := len(d.Inputs) > 0 + return []promoteDeployLane{ + { + label: fmt.Sprintf("matrix deploy job (deploy-%s)", d.Name), + emitted: deployJobsEmitted && hasInputs, + threadsOperatorInputs: true, + }, + { + // Only emitted for a deploy declaring no inputs:, so it can never + // starve an operator input; modeled for completeness. + label: fmt.Sprintf("single-environment deploy job (deploy-%s)", d.Name), + emitted: deployJobsEmitted && !hasInputs, + threadsOperatorInputs: false, + }, + { + label: fmt.Sprintf("prod deploy job (deploy-%s-prod)", d.Name), + emitted: deployJobsEmitted, + threadsOperatorInputs: false, + }, + { + label: fmt.Sprintf("rollback job (rollback-%s)", d.Name), + emitted: deployJobsEmitted, + threadsOperatorInputs: false, + }, } +} +// validateRequiredInputs checks that every input a deploy callback declares as +// required is passed by every job the promote workflow emits that calls it. +// +// The contract inputs (environment, sha, image_tag, image_digest) are threaded +// by promote's own wiring on every deploy lane, so they stay blanket-available +// here with one deliberate exception: the rollback lane has no source for +// image_tag or image_digest (preflight resolves no image tag for the rollback +// target), so a callee that requires either is refused whenever rollback jobs +// are emitted (#698; #664 tracks giving rollback a real image-tag source). +// The remaining per-lane gaps - the matrix deploy job threads image_tag/ +// image_digest only when the manifest wires them under the deploy's inputs:, +// and the prod job threads image_tag (when the callee declares it) but never +// image_digest - are tracked separately (#664) and are otherwise not this +// check's business. +// +// A declared dry_run is counted separately from both sets: the dry_run +// passthrough threads github.event.inputs.dry_run, not a preflight output, so +// it is providable exactly when the callee declares the input (#698), which is +// when the deploy jobs emit the passthrough - the same validation/emission +// agreement the orchestrate generator follows (#684). +// +// An operator input the manifest declares under the deploy's inputs: is +// threaded only by the matrix deploy job, so it counts as available only +// there. Where promote also emits the prod deploy job, the rollback job, or +// the single-environment deploy job for that deploy - which is every promote +// workflow with at least one environment - a callback that requires it would +// produce calls GitHub rejects at dispatch, so generation fails instead with a +// message naming the deploy, the input, and the starving lane(s). A required +// input no lane threads at all (neither a contract input nor manifest +// declared) keeps the unchanged refusal. +func (g *PromoteGenerator) validateRequiredInputs() error { // image_tag and image_digest are available on the deploy lanes, which // thread preflight's source_image_* outputs, but the rollback lane has no // source for either: preflight resolves no image tag for the rollback @@ -208,7 +295,7 @@ func (g *PromoteGenerator) validateRequiredInputs() error { // unaffected (#698; #664 tracks giving rollback a real image-tag source). rollbackEmitted := g.rollbackJobsEmitted() - var errors []string + var errs []string for _, d := range g.config.Deploys { requiredInputs := g.requiredInputs[d.Name] @@ -225,18 +312,64 @@ func (g *PromoteGenerator) validateRequiredInputs() error { // rejected as unprovidable while the emitted with: block satisfies it. declared := g.declaredDeployInputs(d.Workflow, d.Inputs) + // The contract names are available on every lane; the manifest + // operator inputs are available on the matrix deploy job. The list is + // the no-lane message's available set. + contract := map[string]bool{ + "environment": true, + "sha": true, + "image_tag": true, + "image_digest": true, + } + names := []string{"environment", "sha", "image_tag", "image_digest"} + extra := make([]string, 0, len(d.Inputs)) + for name := range d.Inputs { + if !contract[name] { + extra = append(extra, name) + } + } + sort.Strings(extra) + names = append(names, extra...) + + lanes := g.promoteDeployLanes(&d) for _, required := range requiredInputs { - if _, ok := availableInputs[required]; !ok { - if required == "dry_run" && declared["dry_run"] { - continue + if required == "dry_run" && declared["dry_run"] { + continue + } + if contract[required] { + // The rollback lane has no source for the image inputs + // (#698), so a callee that requires one is refused whenever + // rollback jobs are emitted, manifest wiring notwithstanding. + if rollbackEmitted && isRollbackUnsourcedImageInput(required) { + errs = append(errs, rollbackUnsourcedImageInputError(d.Name, required)) } - errors = append(errors, - fmt.Sprintf("deploy-%s requires input '%s' but it cannot be provided in promote workflow (available: environment, sha, image_tag, image_digest)", - d.Name, required)) continue } - if rollbackEmitted && isRollbackUnsourcedImageInput(required) { - errors = append(errors, rollbackUnsourcedImageInputError(d.Name, required)) + if _, operatorInput := d.Inputs[required]; !operatorInput { + // Neither a contract input nor manifest-declared: no lane + // threads it, not even the matrix deploy job, which emits + // only declared inputs: keys. + errs = append(errs, fmt.Sprintf( + "deploy-%s requires input '%s' but it cannot be provided in promote workflow (available: %s)", + d.Name, required, strings.Join(names, ", "))) + continue + } + // Operator input: only the matrix deploy job threads it. Name + // every other emitted lane that calls the callee without it. + var starving []string + for _, lane := range lanes { + if lane.emitted && !lane.threadsOperatorInputs { + starving = append(starving, "the "+lane.label) + } + } + if len(starving) > 0 { + verb := "do" + if len(starving) == 1 { + verb = "does" + } + errs = append(errs, fmt.Sprintf( + "deploy-%s requires input '%s' but %s %s not pass it (operator inputs under the deploy's inputs: are threaded only by the matrix deploy job)", + d.Name, required, strings.Join(starving, " and "), verb)) } } } @@ -255,15 +388,15 @@ func (g *PromoteGenerator) validateRequiredInputs() error { } for _, required := range g.requiredDeployInputs(d.Workflow) { if isRollbackUnsourcedImageInput(required) { - errors = append(errors, rollbackUnsourcedImageInputError(d.Name, required)) + errs = append(errs, rollbackUnsourcedImageInputError(d.Name, required)) } } } } } - if len(errors) > 0 { - return fmt.Errorf("required input validation failed:\n - %s", strings.Join(errors, "\n - ")) + if len(errs) > 0 { + return fmt.Errorf("required input validation failed:\n - %s", strings.Join(errs, "\n - ")) } return nil } @@ -368,7 +501,7 @@ func (g *PromoteGenerator) writeMatrixBuildingStep(sb *strings.Builder) { continue } upper := strings.ToUpper(strings.ReplaceAll(d.Name, "-", "_")) - defaultInputsJSON, envInputsJSON := g.matrixInputsJSON(&d) + defaultInputsJSON, envInputsJSON := matrixInputsJSON(&d, g.config.EnvironmentNames(), g.state) fmt.Fprintf(sb, " DEFAULT_INPUTS_%s: %s\n", upper, yamlSingleQuote(defaultInputsJSON)) fmt.Fprintf(sb, " ENV_INPUTS_%s: %s\n", upper, yamlSingleQuote(envInputsJSON)) } @@ -427,7 +560,9 @@ func passthroughInputNames(deploy *config.DeployConfig) []string { // passthroughInputValue returns the verbatim expression to emit for a // passthrough input key. The default value wins; an env override is used only -// when the default is absent. Passthrough expressions (vars/secrets/env/...) are +// when the default is absent, taking the first override in sorted env order +// so generation stays deterministic (map iteration order must not leak into +// the emitted with: line). Passthrough expressions (vars/secrets/env/...) are // resolved by GitHub Actions at run time, so a single verbatim emission is // correct across the matrix. func passthroughInputValue(deploy *config.DeployConfig, key string) string { @@ -436,20 +571,27 @@ func passthroughInputValue(deploy *config.DeployConfig, key string) string { return strings.TrimSpace(s) } } - for _, envMap := range deploy.EnvInputs { - if v, ok := envMap[key]; ok { - if s, ok := v.(string); ok && classifyInputValue(s) == inputPassthrough { - return strings.TrimSpace(s) - } + type envValue struct { + env, value string + } + var matches []envValue + for env, envMap := range deploy.EnvInputs { + if s, ok := envMap[key].(string); ok && classifyInputValue(s) == inputPassthrough { + matches = append(matches, envValue{env: env, value: strings.TrimSpace(s)}) } } + sort.Slice(matches, func(i, j int) bool { return matches[i].env < matches[j].env }) + if len(matches) > 0 { + return matches[0].value + } return "" } -// matrixInputsJSON returns the default-inputs JSON with passthrough-expression -// keys removed and state.* references resolved against the manifest state for -// the given environment. Used to build the per-env matrix payload. -func (g *PromoteGenerator) matrixDefaultInputs(deploy *config.DeployConfig) map[string]interface{} { +// matrixDefaultInputs returns the default-inputs map with passthrough-expression +// keys removed and state.* references held out (they resolve per-env into the +// env-specific maps instead). Shared by the promote and hotfix generators so +// both serialize the same payload for the same deploy. +func matrixDefaultInputs(deploy *config.DeployConfig) map[string]interface{} { out := make(map[string]interface{}) for k, v := range deploy.Inputs { if s, ok := v.(string); ok { @@ -469,18 +611,20 @@ func (g *PromoteGenerator) matrixDefaultInputs(deploy *config.DeployConfig) map[ } // matrixEnvInputs returns env_inputs with passthrough keys removed and state.* -// references resolved at generation time per environment. -func (g *PromoteGenerator) matrixEnvInputs(deploy *config.DeployConfig) map[string]map[string]interface{} { +// references resolved at generation time per environment. envNames seeds the +// environment set (the manifest's environments plus every env_inputs key) so +// default-level state refs resolve into each env entry. Shared by the promote +// and hotfix generators. +func matrixEnvInputs(deploy *config.DeployConfig, envNames []string, state map[string]*config.EnvState) map[string]map[string]interface{} { out := make(map[string]map[string]interface{}) - // Seed every env so default-level state refs resolve into each env entry. - envNames := make(map[string]struct{}) + seed := make(map[string]struct{}) for env := range deploy.EnvInputs { - envNames[env] = struct{}{} + seed[env] = struct{}{} } - for _, env := range g.config.EnvironmentNames() { - envNames[env] = struct{}{} + for _, env := range envNames { + seed[env] = struct{}{} } - for env := range envNames { + for env := range seed { merged := make(map[string]interface{}) // Default-level state refs resolve per env. An unresolved ref keeps // the raw expression: the deploy must not silently run without its @@ -488,7 +632,7 @@ func (g *PromoteGenerator) matrixEnvInputs(deploy *config.DeployConfig) map[stri // loudly at workflow parse. for k, v := range deploy.Inputs { if s, ok := v.(string); ok && classifyInputValue(s) == inputStateRef { - if resolved, rerr := resolveInputValue(s, g.state); rerr == nil { + if resolved, rerr := resolveInputValue(s, state); rerr == nil { merged[k] = resolved } else { merged[k] = s @@ -501,7 +645,7 @@ func (g *PromoteGenerator) matrixEnvInputs(deploy *config.DeployConfig) map[stri case inputPassthrough: continue case inputStateRef: - if resolved, rerr := resolveInputValue(s, g.state); rerr == nil { + if resolved, rerr := resolveInputValue(s, state); rerr == nil { merged[k] = resolved } else { // Keep the unresolved expression visible rather than @@ -522,13 +666,14 @@ func (g *PromoteGenerator) matrixEnvInputs(deploy *config.DeployConfig) map[stri // matrixInputsJSON serializes a deploy's default inputs and env_inputs as // compact JSON (passthrough expressions excluded; state.* refs resolved -// per-env into env_inputs). -func (g *PromoteGenerator) matrixInputsJSON(deploy *config.DeployConfig) (string, string) { - defaultInputsJSON, err := json.Marshal(g.matrixDefaultInputs(deploy)) +// per-env into env_inputs). Shared by the promote and hotfix generators: both +// route the same JSON through step env: indirection. +func matrixInputsJSON(deploy *config.DeployConfig, envNames []string, state map[string]*config.EnvState) (string, string) { + defaultInputsJSON, err := json.Marshal(matrixDefaultInputs(deploy)) if err != nil { defaultInputsJSON = []byte("{}") } - envInputsJSON, err := json.Marshal(g.matrixEnvInputs(deploy)) + envInputsJSON, err := json.Marshal(matrixEnvInputs(deploy, envNames, state)) if err != nil { envInputsJSON = []byte("{}") } diff --git a/internal/generate/promote_test.go b/internal/generate/promote_test.go index 6bc5e51..7a96b6a 100644 --- a/internal/generate/promote_test.go +++ b/internal/generate/promote_test.go @@ -1769,3 +1769,140 @@ func TestPromoteGenerator_SelectiveDeploysAndForcePassthrough(t *testing.T) { assert.Contains(t, content, "contains(fromJSON(needs.preflight.outputs.deploys_to_run), 'infra')") assert.Contains(t, content, "contains(fromJSON(needs.preflight.outputs.deploys_to_run), 'app')") } + +// TestPromoteGenerator_ValidateRequiredInputs_OperatorInputsThreadOnlyOnMatrixLane +// guards the validation/emission agreement across promote's deploy lanes: an +// operator input the manifest declares under a deploy's inputs: is threaded +// only by the matrix deploy job (writeDeployJobs' hasInputs branch emits every +// such key, passthrough expressions verbatim and the rest as matrix.). +// The prod deploy job, the rollback job, and the single-environment deploy +// path call the same callback without operator inputs, and GitHub rejects a +// reusable-workflow call that omits a required input - the exact shape +// actionlint's [workflow-call] check refuses - so a callback that requires an +// operator input must fail generation with a message naming the deploy, the +// input, and the lane(s) that omit it, instead of generating dispatches that +// can never run. A required input no lane threads at all keeps the unchanged +// refusal, an inputs: key every lane threads via promote's contract wiring +// (image_tag) still passes, and a manifest promoting no environments emits no +// deploy lane at all, so nothing starves the callee there. +func TestPromoteGenerator_ValidateRequiredInputs_OperatorInputsThreadOnlyOnMatrixLane(t *testing.T) { + t.Run("required operator input fails when the prod and rollback jobs are emitted", func(t *testing.T) { + dir := writeDeployStubRequiredInputs(t, map[string]bool{ + "environment": true, + "release_channel": true, + }) + cfg := &config.TrunkConfig{ + TrunkBranch: "main", + Environments: config.EnvNames("dev", "test", "prod"), + Deploys: []config.DeployConfig{ + { + Name: "service", + Workflow: ".github/workflows/deploy.yaml", + Inputs: map[string]interface{}{"release_channel": "canary"}, + }, + }, + } + + _, err := NewPromoteGenerator(cfg, dir).Generate() + require.Error(t, err, + "the prod deploy job and the rollback job are emitted alongside the matrix deploy job and neither threads operator inputs, so the generated calls would fail the reusable-workflow dispatch") + assert.Contains(t, err.Error(), "deploy-service requires input 'release_channel'", + "the error must name the deploy and the input") + assert.Contains(t, err.Error(), + "the prod deploy job (deploy-service-prod) and the rollback job (rollback-service) do not pass it", + "the error must name every emitted lane that omits the input") + assert.Contains(t, err.Error(), + "operator inputs under the deploy's inputs: are threaded only by the matrix deploy job", + "the error must say why those lanes omit it") + assert.Contains(t, err.Error(), "required input validation failed", + "the error keeps the validation-failed framing") + }) + + t.Run("required input not passed still fails with the message naming it", func(t *testing.T) { + dir := writeDeployStubRequiredInputs(t, map[string]bool{ + "environment": true, + "zone": true, + }) + cfg := &config.TrunkConfig{ + TrunkBranch: "main", + Environments: config.EnvNames("dev", "test", "prod"), + Deploys: []config.DeployConfig{ + { + Name: "service", + Workflow: ".github/workflows/deploy.yaml", + Inputs: map[string]interface{}{"release_channel": "canary"}, + }, + }, + } + + _, err := NewPromoteGenerator(cfg, dir).Generate() + require.Error(t, err, + "a required input neither the contract nor the manifest passes must still fail generation") + assert.Contains(t, err.Error(), "deploy-service requires input 'zone' but it cannot be provided in promote workflow (available: environment, sha, image_tag, image_digest, release_channel)", + "the message must name the deploy and input, and list the manifest-passed inputs among the available set") + }) + + t.Run("required operator input generates when no deploy lane is emitted", func(t *testing.T) { + // With zero environments writeDeployJobs and writeRollbackJobs emit + // nothing, so no prod or rollback job exists to call the callee + // without the input. (With one or more environments the prod and + // rollback jobs are always emitted alongside the matrix deploy job - + // writeDeployJobs' and writeRollbackJobs' shared environments + // condition - which is why the multi-environment case above must + // refuse.) + dir := writeDeployStubRequiredInputs(t, map[string]bool{ + "environment": true, + "release_channel": true, + }) + cfg := &config.TrunkConfig{ + TrunkBranch: "main", + Deploys: []config.DeployConfig{ + { + Name: "service", + Workflow: ".github/workflows/deploy.yaml", + Inputs: map[string]interface{}{"release_channel": "canary"}, + }, + }, + } + + content, err := NewPromoteGenerator(cfg, dir).Generate() + require.NoError(t, err, + "with no environments promote emits no job that calls the deploy callback, so a required operator input starves nothing") + assert.NotContains(t, content, "deploy-service:", + "with no environments no deploy, prod, or rollback job is emitted") + }) + + t.Run("required image_tag wired under inputs still hits the rollback refusal", func(t *testing.T) { + // image_tag is both an operator input and a contract name: the matrix + // deploy job threads the operator's value as matrix.image_tag and the + // prod deploy job threads promote's own wiring because the callee + // declares image_tag. But the rollback job threads neither anymore + // (#705): preflight resolves no image tag for the rollback target, so + // writeRollbackWith leaves image_tag out entirely, and a callee that + // requires it is refused at generate time regardless of the manifest + // wiring - the rollback-unsourced-input refusal, not the lane check, + // owns the image inputs (#664 tracks a real rollback source). + dir := writeDeployStubRequiredInputs(t, map[string]bool{ + "environment": true, + "image_tag": true, + }) + cfg := &config.TrunkConfig{ + TrunkBranch: "main", + Environments: config.EnvNames("dev", "test", "prod"), + Deploys: []config.DeployConfig{ + { + Name: "service", + Workflow: ".github/workflows/deploy.yaml", + Inputs: map[string]interface{}{"image_tag": "v1.0.0"}, + }, + }, + } + + _, err := NewPromoteGenerator(cfg, dir).Generate() + require.Error(t, err, + "the rollback job is emitted and cannot source a required image_tag, so the manifest must be refused (#705)") + assert.Contains(t, err.Error(), + "deploy-service requires input 'image_tag' but the promote rollback jobs have no source for it yet (#664)", + "the refusal is the rollback-unsourced-image-input error, not the lane-starvation message") + }) +}