Skip to content

perf(nix): compile cohort test binaries once, share via GOCACHE - #1292

Merged
kalbasit merged 1 commit into
mainfrom
user/wnasreddine/build-once
May 29, 2026
Merged

kalbasit merged 1 commit into
mainfrom
user/wnasreddine/build-once

Conversation

@kalbasit

Copy link
Copy Markdown
Owner

Why

After #1291, the x86_64-linux build leg (~17m) is CI's bottleneck, and the "Flake check" step is 16.3m of it (measured, run 26661047200). dd9622c split flake-check into 5 cohort derivations, each of which recompiles the race+coverage-instrumented test binaries from scratch — Go's build cache isn't shared across Nix sandboxes. The 4 backend cohorts compile byte-identical binaries (cgo mattn/go-sqlite3 under -race, ~2 min apiece on CI's 4-core runners), so 3 of those compiles are pure waste that core contention can't parallelize away (this is dd9622c's 8m→14m regression).

What

Add a _ncps-test-cache derivation that compiles both cohort test sets exactly once (go test -run '^$', runs zero tests so no backend is needed) and exports the populated GOCACHE. Each cohort seeds a writable copy of that cache before its go test, turning compilation into a cache hit. Cohort isolation, per-cohort cover.out, the merged Codecov profile, the race detector, and t.Skip gating are all unchanged.

Two Nix-specific details (documented in the code):

  • disallowedReferences = [ ] — the cache legitimately references the Go toolchain.
  • dontFixup = true — patchelf/strip would rewrite cached objects and invalidate Go's content hashes.
  • Cohorts copy the cache preserving mode then chmod -R u+w — --no-preserve=mode would strip the covdata helper's +x bit and break coverage.

Verification

  • _ncps-test-cache builds (821M cache).
  • cmd cohort passes reusing the cache — confirmed compile reuse (a pre-fix run failed only on fork/exec of the cached covdata binary, proving compilation was served from cache, not rebuilt).
  • The postgres cohort's local TestSchemaEquivalence failure is environmental: it fails identically with this change stashed, and the cohort passes in CI on this branch.

This PR's own CI run will give the real before/after x86-leg number.

OpenSpec: flake-check-topology spec gains "Race+coverage test binaries are compiled once and shared".

The 5 flake-check cohorts each recompiled the race+coverage-instrumented
test binaries from scratch (Go's build cache isn't shared across Nix
sandboxes). The 4 backend cohorts compile byte-identical binaries — cgo
mattn/go-sqlite3 under -race, ~2 min apiece on CI's 4-core runners — so 3
of those compiles were pure waste that core contention couldn't
parallelize away (dd9622c's 8m->14m flake-check regression).

Add a _ncps-test-cache derivation that compiles both cohort test sets once
(`go test -run '^$'`) and exports the populated GOCACHE; each cohort seeds
a writable copy of it before `go test`, turning compilation into a cache
hit. Cohort isolation, per-cohort cover.out, the merged Codecov profile,
the race detector, and t.Skip gating are all unchanged.

Verified: cache builds (821M); cmd cohort passes reusing the cache
(compile served from cache, not rebuilt). The postgres cohort's local
TestSchemaEquivalence failure is environmental — it fails identically
without this change and passes in CI.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@kalbasit

Copy link
Copy Markdown
Owner Author

This change is part of the following stack:

Change managed by git-spice.

@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. enhancement New feature or request go Pull requests that update go code labels May 29, 2026
@coderabbitai

coderabbitai Bot commented May 29, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Summary by CodeRabbit

  • Chores
    • Optimized Go test build performance in nix flake check by implementing a shared compilation cache. Test binaries with race detection and coverage instrumentation are now compiled once and reused across all test cohorts, significantly reducing redundant recompilation and CI build times while maintaining all existing quality checks and coverage reporting.

Walkthrough

This PR introduces a shared Go test compilation cache that compiles race+coverage-instrumented test binaries once in a dedicated derivation, then has all cohort derivations consume that cache to avoid redundant recompilation. The Nix flake module is refactored to factor compile-affecting flags, seed writable caches in cohorts, and expose the cache derivation as a Nix package. Supporting design, proposal, and specification documents are added to the OpenSpec archive.

Changes

Shared Test Cache Infrastructure

Layer / File(s) Summary
Design, proposal, and specification
openspec/changes/archive/2026-05-29-speed-up-flake-check/proposal.md, openspec/changes/archive/2026-05-29-speed-up-flake-check/design.md, openspec/specs/flake-check-topology/spec.md, openspec/changes/archive/2026-05-29-speed-up-flake-check/specs/flake-check-topology/spec.md
Documents the optimization goal (compile race+coverage test binaries once, reuse across cohorts), specifies cache behavior and flag consistency requirements, defines scenarios for backend and cmd cohort integration, and states that race detector enablement, per-cohort coverage output, and merged Codecov profile behavior are preserved.
Shared cache derivation and test specification
nix/checks/flake-module.nix (lines 43–102)
Introduces testSpecs and compileFlags that factorize compile-affecting flags (-race, -covermode, -coverpkg, package paths), and creates the testCache derivation that compiles test binaries via go test -run '^$' for both backend and cmd cohorts, then exports the populated GOCACHE to Nix output.
Cohort cache seeding and checkPhase alignment
nix/checks/flake-module.nix (lines 146–225)
Updates mkCohort preCheck to copy the shared cache into a writable GOCACHE, makes backend pre/post script sourcing conditional on non-empty backends (unit cohorts excluded), refactors checkPhase to use the same compileFlags from the cache derivation so compilation cache keys remain consistent, and exposes the cache as packages._ncps-test-cache.
Task tracking and metadata
openspec/changes/archive/2026-05-29-speed-up-flake-check/.openspec.yaml, openspec/changes/archive/2026-05-29-speed-up-flake-check/tasks.md
Records Phase 1 implementation (cache derivation, cohort integration, flag alignment), Phase 2 verification (testCache builds locally, cmd cohort confirms cache reuse, postgres environmental failure noted, coverage build deferred to CI), Phase 3 deferred follow-ups (optional golangci-lint-check cache seeding), and adds OpenSpec metadata.

Sequence Diagram

sequenceDiagram
  participant testCache as testCache<br/>(one-time build)
  participant cohort1 as Backend Cohort 1<br/>(e.g., postgres)
  participant cohort2 as Backend Cohort 2<br/>(e.g., mysql)
  participant cohort3 as Cmd Cohort<br/>(unit tests)
  participant gotest as go test
  
  testCache->>testCache: Compile race+coverage<br/>test binaries once<br/>(go test -run '^$')
  testCache->>testCache: Export GOCACHE
  
  cohort1->>cohort1: Copy shared GOCACHE<br/>to writable preCheck cache
  cohort1->>gotest: Run go test<br/>(GOCACHE hits)
  gotest->>cohort1: Reuse compiled objects<br/>Skip recompilation
  
  cohort2->>cohort2: Copy shared GOCACHE<br/>to writable preCheck cache
  cohort2->>gotest: Run go test<br/>(GOCACHE hits)
  gotest->>cohort2: Reuse compiled objects<br/>Skip recompilation
  
  cohort3->>cohort3: Copy shared GOCACHE<br/>to writable preCheck cache
  cohort3->>gotest: Run go test<br/>(GOCACHE hits)
  gotest->>cohort3: Reuse compiled objects<br/>Skip recompilation
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • kalbasit/ncps#1249: Both PRs modify nix/checks/flake-module.nix's cohort derivation machinery (mkCohort, preCheck, checkPhase), but this PR further optimizes by adding and seeding a shared _ncps-test-cache GOCACHE—a direct extension of the earlier cohort implementation work.

Suggested labels

size:M, kind/optimization, area/nix, area/ci

Poem

🐰 Once we compiled each test with care,
Identical binaries, repeated everywhere.
But now one cache serves them all,
And CI clock beats a faster call! ✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: compiling cohort test binaries once and sharing the compiled cache via GOCACHE, which directly addresses the performance bottleneck described in the PR objectives.
Description check ✅ Passed The description is well-related to the changeset, explaining the motivation (CI bottleneck), what the solution does (shared cache via _ncps-test-cache derivation), and relevant verification results.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Comment @coderabbitai help to get the list of available commands and usage tips.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request optimizes the CI pipeline by introducing a shared Go test compilation cache (_ncps-test-cache) in Nix. Instead of each test cohort recompiling the race- and coverage-instrumented binaries from scratch, the binaries are compiled once in a dedicated derivation and shared via a populated GOCACHE. This is integrated into nix/checks/flake-module.nix and documented with design, proposal, and specification files under openspec/. There are no review comments to address.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
openspec/changes/archive/2026-05-29-speed-up-flake-check/design.md (1)

36-36: ⚡ Quick win

Add language identifiers to fenced code blocks.

markdownlint (MD040) flags both fences; adding bash keeps docs lint-clean.

Proposed patch
-```
+```bash
 export GOCACHE=$TMPDIR/gocache
 # backend cohort binary set
 go test -race -count=1 -covermode=atomic \
   -coverpkg=./pkg/...,./internal/...,./migrations/...,./testhelper/... \
   -run '^$' ./pkg/... ./internal/... ./migrations/... ./testhelper/...
 # cmd cohort binary set
 go test -race -count=1 -covermode=atomic -coverpkg=./cmd/...,./ent/...,. \
   -run '^$' ./cmd/... ./ent/... .
 cp -r "$GOCACHE" "$out"

- +bash
export GOCACHE="$TMPDIR/gocache"
cp -r --no-preserve=mode,ownership ${testCache}/* "$GOCACHE"/

Also applies to: 56-56

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@openspec/changes/archive/2026-05-29-speed-up-flake-check/design.md` at line
36, Update the two fenced code blocks in the design document so their opening
fences include the bash language identifier (change ``` to ```bash for the
blocks containing the GOCACHE/export snippets); ensure both occurrences (the
block with the go test commands and the block with cp -r --no-preserve usage)
are updated so markdownlint MD040 is satisfied.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@openspec/changes/archive/2026-05-29-speed-up-flake-check/design.md`:
- Line 36: Update the two fenced code blocks in the design document so their
opening fences include the bash language identifier (change ``` to ```bash for
the blocks containing the GOCACHE/export snippets); ensure both occurrences (the
block with the go test commands and the block with cp -r --no-preserve usage)
are updated so markdownlint MD040 is satisfied.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: e754c83c-571b-4883-95bd-74b9802d9fd3

📥 Commits

Reviewing files that changed from the base of the PR and between e10cff0 and c302488.

📒 Files selected for processing (7)
  • nix/checks/flake-module.nix
  • openspec/changes/archive/2026-05-29-speed-up-flake-check/.openspec.yaml
  • openspec/changes/archive/2026-05-29-speed-up-flake-check/design.md
  • openspec/changes/archive/2026-05-29-speed-up-flake-check/proposal.md
  • openspec/changes/archive/2026-05-29-speed-up-flake-check/specs/flake-check-topology/spec.md
  • openspec/changes/archive/2026-05-29-speed-up-flake-check/tasks.md
  • openspec/specs/flake-check-topology/spec.md

@kalbasit
kalbasit merged commit b5fd1e4 into main May 29, 2026
25 checks passed
@kalbasit
kalbasit deleted the user/wnasreddine/build-once branch May 29, 2026 21:49
kalbasit added a commit that referenced this pull request May 29, 2026
## Why

After compile-once (#1292) CI is ~10m, bottlenecked by a single `nix
flake check` building **~13 check derivations on one contended 4-core
runner**. They're logically parallel but CPU-starved; the remaining
costs (backend-cohort test execution, golangci's own analysis) aren't
cacheable — they need more cores in parallel.

## What

Replace the monolithic check with a **CI matrix**:
- `check-matrix` job enumerates checks: `nix eval .#checks.x86_64-linux
--apply builtins.attrNames --json`.
- `checks` job runs each as its own parallel runner: `nix build
.#checks.x86_64-linux.<name>` (`fail-fast: false`), pulling the shared
`_ncps-test-cache`/`_ncps-base` from Cachix instead of rebuilding.
- `coverage` job (`needs: checks`) merges per-cohort profiles → Codecov.
- The shared build job sets **`run_flake_check: false`**
(kalbasit/gh-actions#9) so it only builds/pushes the OCI image.

Wall-clock collapses from sum-under-contention (~10m) to
**slowest-single-check + nix setup (~3–4m)** — the path to the ~5m
target. The per-job times on this run also give us the first clean
per-check breakdown.

## ⚠️ Merge order
Depends on **kalbasit/gh-actions#9** (adds `run_flake_check`). The
caller is **temporarily pinned to the gh-actions branch** to validate
now; revert to `@main` before merging once #9 lands.

OpenSpec: `flake-check-topology` gains "CI runs each check as an
independent parallel job" + "Coverage is produced by a job consuming the
fanned-out cohorts".

---------

Co-authored-by: Claude Opus 4.8 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request go Pull requests that update go code size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant