Skip to content

Comments

perf(ci): replace ldflags version injection with generated source file#19138

Draft
davdhacs wants to merge 4 commits intomasterfrom
davdhacs/version-codegen
Draft

perf(ci): replace ldflags version injection with generated source file#19138
davdhacs wants to merge 4 commits intomasterfrom
davdhacs/version-codegen

Conversation

@davdhacs
Copy link
Contributor

Replace the //XDef: + ldflags mechanism for injecting version data with a generated zversion.go file, following the same pattern Go itself uses for zbootstrap.go. This eliminates all -X ldflags for version stamping.

Previously, go-tool.sh would grep for //XDef: annotations in Go source, match them to status.sh output, and pass the values via -X ldflags to the linker. This caused the linker cache to be invalidated on every version change (including GitShortSha which changed on every commit).

Now, go-tool.sh generates pkg/version/internal/zversion.go with an init() function that sets the version variables. The file is only written when content changes (skip-if-same), so rebuilds with the same version produce zero cache churn -- neither the compile cache nor the link cache is invalidated.

Additional changes:

  • Add -buildvcs=false to suppress Go's automatic VCS stamping, which also changes on every commit and invalidates the main package cache
  • Replace internal.GitShortSha with getGitCommitFromMainVersion() that extracts the SHA from MainVersion at runtime (e.g. "4.11.x-143-g4982da58fd" -> "4982da58fd")
  • Remove STABLE_GIT_SHORT_SHA from status.sh (no longer needed)
  • Allow GHA cache saves on PRs with ci-save-cache label

Cache impact with -trimpath (already used):

  • Compile cache: 100% stable across commits with unchanged source
  • Link cache: stable when version string unchanged (skip-if-same)
  • No ldflags in the build at all (only -s -w for stripping)

Description

change me!

User-facing documentation

Testing and quality

  • the change is production ready: the change is GA, or otherwise the functionality is gated by a feature flag
  • CI results are inspected

Automated testing

  • added unit tests
  • added e2e tests
  • added regression tests
  • added compatibility tests
  • modified existing tests

How I validated my change

change me!

@openshift-ci
Copy link

openshift-ci bot commented Feb 23, 2026

Skipping CI for Draft Pull Request.
If you want CI signal for your change, please convert it to an actual PR.
You can still manually trigger a test run with /test all

Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 3 issues, and left some high level feedback:

  • In go-tool.sh's generate_version_file, consider explicitly validating that each expected status_* variable (e.g. status_STABLE_MAIN_VERSION, status_STABLE_COLLECTOR_VERSION, etc.) is non-empty and failing fast if missing, so version generation errors don't silently produce empty fields.
  • The GitHub Actions cache conditions are getting complex; adding explicit parentheses around the default_branch vs ci-save-cache label checks in both save and restore branches would make the precedence of &&/|| unambiguous and ensure the two conditions remain exact logical complements.
  • The generator still references status_STABLE_GIT_SHORT_SHA while the description mentions removing STABLE_GIT_SHORT_SHA and deriving the SHA from MainVersion; it would be good to align the implementation with the intended design so GitShortSha has a single, consistent source of truth.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In `go-tool.sh`'s `generate_version_file`, consider explicitly validating that each expected `status_*` variable (e.g. `status_STABLE_MAIN_VERSION`, `status_STABLE_COLLECTOR_VERSION`, etc.) is non-empty and failing fast if missing, so version generation errors don't silently produce empty fields.
- The GitHub Actions cache conditions are getting complex; adding explicit parentheses around the `default_branch` vs `ci-save-cache` label checks in both save and restore branches would make the precedence of `&&`/`||` unambiguous and ensure the two conditions remain exact logical complements.
- The generator still references `status_STABLE_GIT_SHORT_SHA` while the description mentions removing `STABLE_GIT_SHORT_SHA` and deriving the SHA from `MainVersion`; it would be good to align the implementation with the intended design so `GitShortSha` has a single, consistent source of truth.

## Individual Comments

### Comment 1
<location path="scripts/go-tool.sh" line_range="35-44" />
<code_context>
+# the Go build/link cache when only the version string changes.
+# The file is only written when content changes (skip-if-same), so unchanged
+# versions produce zero cache churn.
+generate_version_file() {
+	local target="${SCRIPT_DIR}/../pkg/version/internal/zversion.go"
+	local new_content
+	new_content="// Code generated by go-tool.sh; DO NOT EDIT.
+
+package internal
+
+func init() {
+	MainVersion = \"${status_STABLE_MAIN_VERSION}\"
+	CollectorVersion = \"${status_STABLE_COLLECTOR_VERSION}\"
+	FactVersion = \"${status_STABLE_FACT_VERSION}\"
+	ScannerVersion = \"${status_STABLE_SCANNER_VERSION}\"
+	GitShortSha = \"${status_STABLE_GIT_SHORT_SHA}\"
+}"
+	if [[ -f "$target" ]] && [[ "$(cat "$target")" == "$new_content" ]]; then
+		return
 	fi
</code_context>
<issue_to_address>
**issue (bug_risk):** Missing validation that required status_* variables are populated before generating zversion.go.

Previously, the //XDef: flow failed fast if a referenced status var was missing. This generator now interpolates ${status_STABLE_*} directly, so missing or changed vars would quietly become empty strings in zversion.go. Please add explicit checks that each status_STABLE_* var is set (non-empty) and fail with a clear error before writing the file to retain the earlier safety guarantees.
</issue_to_address>

### Comment 2
<location path=".github/actions/cache-go-dependencies/action.yaml" line_range="17" />
<code_context>
         echo "GOMODCACHE=$(go env GOMODCACHE)" >> "$GITHUB_OUTPUT"
         echo "GOARCH=$(go env GOARCH)" >> "$GITHUB_OUTPUT"
-        echo "TAG=$(date +%Yw%U)" >> "$GITHUB_OUTPUT"
+        TAG="${{ contains(github.event.pull_request.labels.*.name, 'ci-save-cache') && github.event.pull_request.number || '' }}"
+        echo "TAG=${TAG:-$(date +%Yw%U)}" >> "$GITHUB_OUTPUT"
       shell: bash
</code_context>
<issue_to_address>
**issue (bug_risk):** Using github.event.pull_request.* unguarded can fail on non-PR events.

This job runs on both push and PR events, but `github.event.pull_request` only exists for PRs. On a push, accessing `github.event.pull_request.labels` or `.number` will fail expression evaluation. Please guard this with a check like `github.event_name == 'pull_request'` (or a ternary that returns an empty value when not a PR) so push workflows don’t break.
</issue_to_address>

### Comment 3
<location path=".github/actions/cache-go-dependencies/action.yaml" line_range="24-27" />
<code_context>
+    # ci-save-cache label (for testing cache-affecting changes on branches).
     - name: Cache Go Dependencies (save)
-      if: inputs.save == 'true' && (github.event_name == 'push' && github.ref_name == github.event.repository.default_branch)
+      if: inputs.save == 'true' && (github.event_name == 'push' && github.ref_name == github.event.repository.default_branch || contains(github.event.pull_request.labels.*.name, 'ci-save-cache'))
       uses: actions/cache@v5
       with:
</code_context>
<issue_to_address>
**issue:** Condition uses github.event.pull_request.* without guarding against non-PR events.

The `contains(github.event.pull_request.labels.*.name, 'ci-save-cache')` expression will still be evaluated on non-PR events, where `github.event.pull_request` is undefined, which can break push workflows. Please guard the `contains(...)` call (e.g., by checking `github.event_name == 'pull_request'` first or using a nested ternary) so `pull_request` is only accessed for PR events.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

echo "GOMODCACHE=$(go env GOMODCACHE)" >> "$GITHUB_OUTPUT"
echo "GOARCH=$(go env GOARCH)" >> "$GITHUB_OUTPUT"
echo "TAG=$(date +%Yw%U)" >> "$GITHUB_OUTPUT"
TAG="${{ contains(github.event.pull_request.labels.*.name, 'ci-save-cache') && github.event.pull_request.number || '' }}"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (bug_risk): Using github.event.pull_request.* unguarded can fail on non-PR events.

This job runs on both push and PR events, but github.event.pull_request only exists for PRs. On a push, accessing github.event.pull_request.labels or .number will fail expression evaluation. Please guard this with a check like github.event_name == 'pull_request' (or a ternary that returns an empty value when not a PR) so push workflows don’t break.

Comment on lines +24 to 27
if: inputs.save == 'true' && (github.event_name == 'push' && github.ref_name == github.event.repository.default_branch || contains(github.event.pull_request.labels.*.name, 'ci-save-cache'))
uses: actions/cache@v5
with:
path: ${{ steps.cache-paths.outputs.GOMODCACHE }}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue: Condition uses github.event.pull_request.* without guarding against non-PR events.

The contains(github.event.pull_request.labels.*.name, 'ci-save-cache') expression will still be evaluated on non-PR events, where github.event.pull_request is undefined, which can break push workflows. Please guard the contains(...) call (e.g., by checking github.event_name == 'pull_request' first or using a nested ternary) so pull_request is only accessed for PR events.

@rhacs-bot
Copy link
Contributor

rhacs-bot commented Feb 23, 2026

Images are ready for the commit at 3036436.

To use with deploy scripts, first export MAIN_IMAGE_TAG=4.11.x-160-g30364365a0.

@davdhacs davdhacs force-pushed the davdhacs/version-codegen branch from 50cced5 to 117594a Compare February 23, 2026 19:59
@davdhacs davdhacs added the ci-save-cache Enable Go cache saves on this PR branch for testing label Feb 23, 2026
@davdhacs davdhacs force-pushed the davdhacs/version-codegen branch from 117594a to 1b5962b Compare February 23, 2026 20:17
@codecov
Copy link

codecov bot commented Feb 23, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 49.52%. Comparing base (573923b) to head (3036436).
⚠️ Report is 2 commits behind head on master.

Additional details and impacted files
@@           Coverage Diff           @@
##           master   #19138   +/-   ##
=======================================
  Coverage   49.52%   49.52%           
=======================================
  Files        2672     2672           
  Lines      201665   201665           
=======================================
+ Hits        99870    99875    +5     
+ Misses      94337    94332    -5     
  Partials     7458     7458           
Flag Coverage Δ
go-unit-tests 49.52% <ø> (+<0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

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

🚀 New features to boost your workflow:
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@davdhacs davdhacs force-pushed the davdhacs/version-codegen branch from 4afe452 to 3036436 Compare February 24, 2026 00:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants