Skip to content

feat(ci): reject needs.<job>.outputs.<name> references the producer never declares - #6594

Merged
robfrank merged 3 commits into
mainfrom
feat/ci-check-needs-outputs
Aug 22, 2026
Merged

robfrank merged 3 commits into
mainfrom
feat/ci-check-needs-outputs

Conversation

@robfrank

Copy link
Copy Markdown
Collaborator

Follow-up to #6593, suggested in its review. Adds check-workflow-needs-outputs.py, which asserts that every needs.<job>.outputs.<name> expression names an output the referenced job actually declares.

Stacked on #6593 and must merge after it. This branch is based on fix/4894-declare-image-tag-output, because the check fails against main as it stands - which is the point.

Why

GitHub Actions does not validate these references. An output no job declares is accepted as valid YAML and silently evaluates to the empty string at runtime, so the mistake produces a workflow that looks correct, parses correctly, and quietly passes nothing where a value was meant to go.

That is the bug #6593 fixes: build-and-package had no outputs: block while seven jobs passed needs.build-and-package.outputs.image-tag as ARCADEDB_DOCKER_IMAGE. It survived because every consumer was defensive in a way that hid it - e2e-go guards != "", js-bolt-conformance falls back with ||, and two e2e-js suites hardcode :latest and never read the variable. Since the saved artifact carries only the :latest tag, those fallbacks all landed on the right image, so the suites were correct by luck. It took a newly added consumer strict enough to pass "" through to Docker to surface it, as invalid reference format.

This is the same family as check-workflow-artifact-deps.py: valid-looking YAML that is silently wrong at runtime, where the failure mode is indistinguishable from working. It gets a sibling script, runs in the same setup job, and needs no new wiring.

That the check is real, not decorative

Run against main without #6593's fix, it reproduces the defect independently - all seven consumers, each with its exact location:

mvn-test.yml: job 'java-e2e-tests' references needs.build-and-package.outputs.image-tag at
'steps[6].env.ARCADEDB_DOCKER_IMAGE', but job 'build-and-package' declares no such output
(declares: none). GitHub Actions resolves this to an empty string at runtime instead of failing.

With #6593's fix present it exits 0.

Five cases added to test-ci-scripts.sh, pinning both directions the way the existing suites do:

  • rejects a reference to an output the producer never declares
  • accepts the same workflow once the output is declared (same base fixture, one transformation, opposite result)
  • rejects a reference to a name the producer does not declare, where an outputs: block exists but lacks it - the easier mistake to miss, because a reader skims past the block
  • rejects a reference to a job that does not exist, which is the other half of the same typo
  • ignores a reference into a reusable-workflow job

75 checks pass in the harness, up from 70.

Deliberate boundaries

A job delegating to a reusable workflow (jobs.<id>.uses:) declares its outputs in the called workflow, which this script does not follow. References into such a job are skipped rather than reported: this check gates every other job, so a false violation here is expensive. The distinction is explicit in the code - None means "cannot resolve from here", an empty set means "declares nothing", and only the latter is a defect.

A needs reference to a job that does not exist at all is reported, since that is never valid.

@mergify

mergify Bot commented Aug 22, 2026

Copy link
Copy Markdown
Contributor

Tick the box to add this pull request to the merge queue (same as @mergifyio queue).

  • Queue this pull request

@claude

claude Bot commented Aug 22, 2026

Copy link
Copy Markdown

Reviewed the new check-workflow-needs-outputs.py (and its test/wiring additions). Overall this is a well-designed, well-documented check: the None vs. empty-set distinction for reusable-workflow jobs is the right call, the generic tree-walk in references() correctly reaches into env, if, with, matrix, etc. without needing to special-case each, and the 5 new cases in test-ci-scripts.sh cover both directions plus the two "typo" shapes (wrong output name, wrong job name) and the reusable-workflow boundary. The reproduction against main in the PR description is convincing evidence the check is real rather than decorative.

A couple of things worth a look:

1. Missing ImportError guard around import yaml (.github/scripts/check-workflow-needs-outputs.py:60)
Its two closest siblings (check-workflow-artifact-deps.py, check-test-reporter-guards.py) both wrap the import:

try:
    import yaml
except ImportError:  # pragma: no cover - the workflow installs it explicitly
    sys.exit("check-...: PyYAML is required (pip install pyyaml)")

This script does a bare import yaml, so if it's ever run without PyYAML installed (e.g. a contributor running it locally, or the invocation order in the workflow changes), it fails with a raw ModuleNotFoundError traceback instead of the friendly, actionable message its sibling scripts give. Minor, but since the PR explicitly frames this as "the same family as check-workflow-artifact-deps.py," it'd be nice to match that family's convention exactly.

2. Dead no-op sed in the test file (.github/scripts/tests/test-ci-scripts.sh, the "accepts the same workflow once the output is declared" case)

sed 's/    runs-on: ubuntu-latest\n/&/' "$work/needs-undeclared/ci.yml" \
    | awk '...'

sed operates line-by-line by default, so a pattern containing a literal \n never matches anything within a single line - this substitution is a no-op and the file passes through unchanged. It doesn't affect correctness (the awk after it does all the real work), but it reads as if it's doing something and it isn't. Simplifying to just cat "$work/needs-undeclared/ci.yml" | awk ... (or feeding the file to awk directly) would remove the red herring.

Nothing else stood out - no correctness issues in the regex (job-id/output-name character classes match GitHub's actual constraints), no perf/security concerns (local YAML parsing only, no dynamic eval), and the mvn-test.yml wiring is a single additive step in the existing setup job as described.

@codacy-production

codacy-production Bot commented Aug 22, 2026 •

Copy link
Copy Markdown

Not up to standards ⛔

🔴 Issues 2 minor

Alerts:
⚠ 2 issues (≤ 0 issues of at least minor severity)

Results:
2 new issues

Category Results
Documentation 2 minor

View in Codacy

🟢 Metrics 45 complexity

Metric Results
Complexity 45

View in Codacy

🟢 Coverage ∅ diff coverage · -6.55% coverage variation

Metric Results
Coverage variation ✅ -6.55% coverage variation
Diff coverage ✅ ∅ diff coverage

View coverage diff in Codacy

Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (cd29d8a) 164679 131822 80.05%
Head commit (8f4eda7) 197066 (+32387) 144835 (+13013) 73.50% (-6.55%)

Coverage variation is the difference between the coverage for the head and common ancestor commits of the pull request branch: <coverage of head commit> - <coverage of common ancestor commit>

Diff coverage details
Coverable lines Covered lines Diff coverage
Pull request (#6594) 0 0 ∅ (not applicable)

Diff coverage is the percentage of lines that are covered by tests out of the coverable lines that the pull request added or modified: <covered lines added or modified>/<coverable lines added or modified> * 100%

NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer
TIP This summary will be updated as you push new changes.

@robfrank

Copy link
Copy Markdown
Collaborator Author

Both fixed in e34bbc76d7.

PyYAML guard. Verified the convention first: check-workflow-artifact-deps.py:46-49 and check-test-reporter-guards.py:42-45 both use exactly that shape, # pragma: no cover comment included. Mine had a bare import. Matched.

Proved the guard actually fires rather than assuming it, by running the script under a MetaPathFinder that raises on import yaml:

exit: 1
stderr: check-workflow-needs-outputs: PyYAML is required (pip install pyyaml)

Worth noting my first attempt at that probe used the legacy find_module/load_module hooks, which Python 3.12+ removed, so it exited 0 and looked like a pass when it had simply failed to block anything. Inconclusive, not positive - which is the same shape of mistake this whole PR exists to catch, one level up.

No-op sed. Correct, and doubly so: sed's pattern space carries no trailing newline, so a \n in the pattern can never match within a line, and & would be an identity substitution even if it did. The awk was doing all the work. Now feeding the file to awk directly.

I kept deriving the accepting fixture from the rejecting one rather than writing a second file, and said so in a comment: it is what makes the pair evidence rather than two independent assertions, since the added outputs: block is then the only difference between a pass and a failure. Harness still at 75 checks, and the check still exits 0 against this branch and 1 against main without #6593.

@claude

claude Bot commented Aug 22, 2026

Copy link
Copy Markdown

Review of check-workflow-needs-outputs.py

Nice addition, small in scope, well-motivated by a real incident, and the test fixtures pin both directions of every branch in check(). A few notes:

Strengths

  • declared_outputs() correctly distinguishes "cannot resolve" (None, reusable-workflow job) from "declares nothing" (set()), and only the latter is treated as a defect, matching the stated design boundary.
  • yaml.safe_load is used rather than load, so parsing untrusted workflow YAML can't instantiate arbitrary Python objects.
  • Test coverage hits all four branches: missing job, job with no outputs: block at all, job with an outputs: block that's missing the referenced key, and the reusable-workflow skip. The "same fixture, one transformation" trick for the undeclared/declared pair is a nice way to keep the pair as actual evidence rather than two independently-written fixtures that could drift apart.
  • Header comment and PyYAML-missing guard match the sibling check-workflow-artifact-deps.py almost verbatim, so the two scripts read as one family.

Minor nits

  1. workflow_files() doesn't validate that a non-directory argument exists. The sibling script (check-workflow-artifact-deps.py) does elif target.exists(): ... else: sys.exit("...: no such file or directory: %s"). Here, a bad path just gets appended to files, and check()'s path.read_text() will raise an uncaught FileNotFoundError, i.e. a raw Python traceback instead of a clean error message. Only matters when someone invokes the script by hand with a typo'd path (the CI call with no args is unaffected), but worth matching the sibling's behavior for consistency.
  2. Default path is relative (Path(".github/workflows")), while the sibling script resolves an absolute default from Path(__file__).resolve().parents[2]. That makes the new script depend on the caller's cwd being the repo root. Works fine for how mvn-test.yml invokes it today, but would silently find zero workflows (and exit 0, "checked" nothing) if ever run from a different directory.
  3. Violations are printed to stdout here; the sibling script writes violations to stderr and reserves stdout for notes/success. Not a bug (exit code still drives CI), just a small stylistic divergence between the two "family" scripts.
  4. The NEEDS_OUTPUT regex (and the sibling's EXPRESSION) only matches dot notation (needs.build.outputs.name). Bracket notation (needs.build.outputs['name']) is valid GitHub Actions syntax and would silently evade detection (false negative) if anyone ever writes it that way. Probably fine to leave as a documented heuristic rather than a full expression parser, but worth a one-line note in the header alongside the other "known boundaries" if it isn't already covered by repo convention elsewhere.

None of these block anything, they're all low-severity/robustness points on a script that only runs in CI against a small, controlled set of files. The core logic, the None-vs-empty-set distinction, and the test coverage all look correct to me.

Note: the diff also carries the mvn-test.yml / outputs: block changes from the stacked base PR (#6593) since it isn't merged yet, so I've focused this review on what's new here (the checker script + its tests).

@robfrank
robfrank force-pushed the feat/ci-check-needs-outputs branch from e34bbc7 to 6904884 Compare August 22, 2026 18:31
@claude

claude Bot commented Aug 22, 2026

Copy link
Copy Markdown

Reviewed the diff (check-workflow-needs-outputs.py, its tests, and the mvn-test.yml wiring). This is a well-scoped addition that follows the established pattern of check-workflow-artifact-deps.py closely: same docstring style, same None-vs-empty-set boundary distinction, same "runs in the existing setup job, no new wiring" integration. The PR description's reproduction against main (pre-#6593) is convincing evidence the check is real rather than decorative, and the five test cases pin both directions plus the two documented boundaries well.

One correctness gap I'd like the author to weigh in on before merge:

The script doesn't verify the referenced job is actually in the consuming job's needs: closure.

check() only asks two questions about a needs.<job>.outputs.<name> reference: does <job> exist in this workflow, and does <job> declare <name> as an output. It never checks whether the current job actually lists <job> in its own needs:. But GitHub Actions only populates the needs context with jobs the current job depends on - a reference to needs.build.outputs.tag in a job that doesn't have build in its needs: list resolves to the same silent empty string this script exists to catch, even when build correctly declares tag as an output.

This is exactly the failure category the sibling script (check-workflow-artifact-deps.py) already guards against for artifacts - it explicitly computes needs_closure() and flags a download whose producer isn't in it (that's the #5701 bug it was written for). This script has the same shape of gap but for needs.*.outputs.* instead of download-artifact.

Concretely, nothing today would catch:

jobs:
  build:
    outputs:
      tag: ${{ steps.x.outputs.tag }}
    ...
  e2e:
    # no `needs: build`
    steps:
      - run: docker pull ${{ needs.build.outputs.tag }}   # resolves to "" - not flagged

declared_outputs(jobs['build']) returns {tag}, tag in available is true, so no violation is reported, even though e2e never declared the dependency.

It happens that every current usage in this repo's workflows does list the producer in needs: (checked mvn-test.yml - all seven build-and-package consumers have needs: build-and-package), so this wouldn't fire against main today. But given the PR's own framing ("valid-looking YAML that is silently wrong at runtime, indistinguishable from working"), it seems worth closing this half of the gap too, using the same needs_of/needs_closure helpers already proven out in check-workflow-artifact-deps.py - possibly even importable/shareable between the two scripts rather than reimplemented.

Minor, non-blocking nits:

  1. NEEDS_OUTPUT matches the needs.<job>.outputs.<name> substring anywhere inside any string value in a job, not just inside a ${{ }} expression (unlike the sibling script's EXPRESSION = re.compile(r"\$\{\{.*?\}\}") gate). A run: step whose shell text happens to contain that literal substring (e.g. in an echo message or comment) would be misreported as a live reference. Low practical risk given current workflows, but worth a ${{ }}-scoped extraction like the sibling script uses, for robustness.
  2. If the same bad reference appears more than once in a job (e.g. once in env: and again in a run: step), each occurrence produces its own violation line for the same underlying mistake - purely cosmetic, not worth blocking on.

Everything else - the None vs set() semantics for reusable-workflow jobs, the workflow-file discovery, the PyYAML guard matching the sibling script, the test fixtures (especially deriving the "declared" fixture from the "undeclared" one via awk so the pair is minimal evidence) - looks solid and in keeping with the repo's conventions.

@robfrank

Copy link
Copy Markdown
Collaborator Author

All three addressed in 8f4eda791d, but the main one with one deliberate divergence from the suggestion, and it matters.

The needs gap: real, fixed, and it must be DIRECT needs, not the closure.

The gap is exactly as described - the script asked "does the job exist" and "does it declare the output", never "does the consumer depend on it". Fixed.

But the suggested fix, reusing needs_closure() from the artifact-deps script, would have been wrong here, and wrong in the permissive direction. Artifacts and the needs context do not behave the same way:

  • An artifact is uploaded to the RUN, so a job that waits transitively still finds it. That is why the sibling script resolves a full closure, and it is correct there.
  • The needs CONTEXT carries "the outputs of all jobs that are defined as a dependency of the current job". A job reaching the producer only transitively reads an empty string, exactly like a job that never declared the dependency.

So a closure-based check would have accepted this, which is precisely the reference the script exists to reject:

build:   { outputs: { image-tag: ... } }
test:    { needs: build }
report:  { needs: test, env: { IMAGE: "\${{ needs.build.outputs.image-tag }}" } }   # resolves to ""

That case is now a test ("rejects a transitively-reached producer, because the needs context is direct-only"), and the reasoning is in needs_of's docstring so the next person does not "fix" it into a closure.

I also duplicated the four-line needs_of rather than importing it across scripts. Both files are standalone executables run by path from the workflow; making one import the other buys four lines and adds a module-resolution failure mode to two checks that gate every other job.

Proved it fires against the real workflow, not only fixtures. Removing needs: build-and-package from client-smoke-test while leaving the reference intact:

job 'client-smoke-test' references needs.build-and-package.outputs.image-tag at
'steps[4].env.ARCADEDB_DOCKER_IMAGE', but 'client-smoke-test' does not list 'build-and-package'
in its needs (needs: nothing). The needs context carries only DIRECT dependencies, so this
resolves to an empty string at runtime instead of failing.

Restored, and green again.

Nit 1, the ${{ }} gate: taken. references() now extracts \${{ }} blocks first, matching the sibling's EXPRESSION regex. A run: step that merely prints those words is no longer a violation, and that is a test too.

Nit 2, duplicate lines: taken. One line per distinct (job, output) per consuming job. The same bad reference in both env: and run: was making one typo look like two.

Harness at 78 checks, up from 75. The check still exits 0 against current main, which independently confirms your observation that all seven consumers do carry the direct dependency.

@claude

claude Bot commented Aug 22, 2026

Copy link
Copy Markdown

Review of #6594

Solid addition, well-scoped and consistent with the sibling check-workflow-artifact-deps.py in structure, doc style, and boundary handling. I traced the logic against all 8 new test fixtures by hand and didn't find a correctness bug. A couple of small notes below.

Code quality

  • The None (unresolvable/reusable job) vs. empty-set (declares nothing) distinction in declared_outputs is exactly the right modeling choice, and the boundary comment explains why clearly.
  • Good call restricting direct-dependency checking to direct needs only, since that matches the real needs context semantics (not transitive, unlike artifacts). The comment justifying this against the sibling script's transitive closure is useful self-documentation for future readers who might otherwise fix it into a bug.
  • The reported per-job dedup (keyed on (target, output)) correctly avoids reporting the same typo twice when it appears in both env: and run:.

Potential bugs / edge cases (minor, non-blocking)

  • Default path is cwd-relative, unlike the sibling script: check-workflow-artifact-deps.py resolves its default workflows directory with Path(__file__).resolve().parents[2] / ".github" / "workflows", so it works regardless of the caller's working directory. The new script instead defaults to Path(".github/workflows") (relative to cwd). Harmless today since the setup job runs from $GITHUB_WORKSPACE with no working-directory override, but it is a latent inconsistency between two scripts meant to be twins, worth aligning if this is ever invoked from a subdirectory.
  • Bracket-syntax expressions aren't matched: NEEDS_OUTPUT/EXPRESSION only catch dotted access (needs.build.outputs.tag), not needs['build']['outputs']['tag']. This mirrors an existing limitation in check-workflow-artifact-deps.py, so it's consistent with current repo convention rather than a regression, just flagging it as a known false-negative surface.

Performance
No concerns, a one-shot CI lint script over a handful of YAML files, well within the cost of the pip install pyyaml step it rides alongside.

Security
No concerns, static YAML parsing via yaml.safe_load, no eval/shell interpolation of file contents, no untrusted input beyond the repo's own workflow files.

Test coverage
Thorough and well-targeted: undeclared vs. declared pair (same fixture, one diff), wrong-output-name-with-an-outputs:-block-present (the easy-to-skim-past case), missing-job typo, not-a-direct-dependency, transitively-reached-but-not-direct, plain-text false-positive guard, and reusable-workflow skip. Good spread across the branches in check().

One small nit: the PR description says Five cases added to test-ci-scripts.sh, 75 checks pass in the harness, up from 70, but the final diff (after the third commit, which added the outside the job's direct needs checks) actually adds 8 expect calls, not 5. Not a code issue, just worth updating the description so the numbers match what actually merges.

Nice, well-justified change overall, the reasoning captured in the header comment and the needs-context-is-direct-not-transitive note are genuinely useful for whoever touches this next.

@robfrank
robfrank merged commit e26375d into main Aug 22, 2026
27 of 29 checks passed
@robfrank
robfrank deleted the feat/ci-check-needs-outputs branch August 22, 2026 19:41
@codecov

codecov Bot commented Aug 22, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 71.33%. Comparing base (cd29d8a) to head (8f4eda7).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #6594      +/-   ##
==========================================
- Coverage   71.35%   71.33%   -0.03%     
==========================================
  Files        1868     1868              
  Lines      164679   164679              
  Branches    34806    34806              
==========================================
- Hits       117511   117478      -33     
- Misses      32900    32932      +32     
- Partials    14268    14269       +1     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant