Skip to content

refactor(nix): per-backend test cohorts + lean ncps build - #1249

Merged
kalbasit merged 19 commits into
mainfrom
improve-flake-check-time
May 24, 2026
Merged

kalbasit merged 19 commits into
mainfrom
improve-flake-check-time

Conversation

@kalbasit

@kalbasit kalbasit commented May 24, 2026 •

Copy link
Copy Markdown
Owner

What this PR actually delivers

A structural rework of nix flake check. CI build-job wall-clock is roughly unchanged from main (~15m → ~15m); the wins are everywhere except total CI time:

Thing Before After
nix build .#ncps (lean binary build, no tests) ~12m ~1m
Build coverage step in CI (nix build .#ncps.coverage) ~6–12m ~3s
Flake check step in CI (was monolith, now cohorts) ~8m ~14m
Backend test failures localized to named cohorts no yes
Coverage piggybacked on per-cohort cover.out no yes

The flake-check step itself got slower, not faster — splitting the monolith into 5 cohort derivations replaces 1 compile + 1 test run with 5 compile + 5 test runs, and the runner doesn't have enough cores to parallelize that away. The coverage piggyback (cohorts emit cover.out, ncps-coverage merges them) eats most of that slowdown back. Net CI: roughly the same total.

I attempted to claim "~12m → ~5m" earlier; that was wrong and I owe an apology. The 5m figure was a local-machine measurement of nix flake check in isolation, not CI's build job which also runs the coverage and OCI steps sequentially after. The honest CI-total number stayed flat.

What's genuinely better

  • nix build .#ncps is now ~1 min instead of ~12. Useful for every downstream that does nix run github:kalbasit/ncps or builds Docker images.
  • ncps-coverage is a 30s Python merger of per-cohort cover.out instead of a 12m monolith re-run. Codecov gets the same merged profile via the same nix build .#ncps.coverage invocation; the symlink name (result-coverage) and payload shape are preserved verbatim, no upstream workflow changes needed.
  • Per-backend failure isolation. When MariaDB flakes, only ncps-mysql-tests fails. CI logs name it directly instead of burying it in a 12m monolith log.
  • packages._ncps-base factored out so cohorts can depend on a shared buildGoModule without cycling through packages.ncps.passthru.coverage.
  • checks attrset is explicit — no longer pulls in docker, docker-dev, push-docker-image, k8s-tests, update-cu-base, deps as side-effect "checks" that aren't quality gates.

Side effect: surfaced existing pkg/cache flakes

The measurement runs during this work hit five pre-existing intermittent failures in pkg/cache, all tracked under #1247. They are NOT fixed by this PR. The fixes landed in sibling PRs that have already merged:

The per-backend cohort topology made these tractable: each fired in a single named cohort instead of buried inside a 12m monolith log.

What's the same (no regression)

  • Race detector still on for every test that had it.
  • Every integration backend (Garage, Postgres, MariaDB, Redis) still exercised.
  • golangci-lint set unchanged.
  • ent-codegen-drift-check, atlas-sum-check, ent-lint-check, helm-unittest-check continue to fail the gate on the same inputs.
  • Codecov receives the same merged coverage profile.
  • Shared CI workflow at kalbasit/gh-actions/.github/workflows/ci.yml unchanged.

Architecture

packages.ncps                  lean buildGoModule, no tests, ~1m
packages._ncps-base            shared buildGoModule (no passthru) for cohorts
packages.ncps-checktools       cmd/ent-lint + cmd/atlas-sum-check, once
packages.ncps-coverage         stdenvNoCC merger of per-cohort cover.out

checks.ncps                    binary build sanity
checks.ncps-checktools         helper binaries sanity
checks.ncps-cmd-tests          cmd/+ent/+main tests
checks.ncps-s3-tests           ./pkg/...,./internal/...,./migrations/...,./testhelper/... with Garage
checks.ncps-postgres-tests     same, with Postgres
checks.ncps-mysql-tests        same, with MariaDB
checks.ncps-redis-tests        same, with Redis
checks.golangci-lint-check     unchanged
checks.ent-codegen-drift-check unchanged
checks.atlas-sum-check         stdenvNoCC consumer of ncps-checktools (was buildGoModule override)
checks.ent-lint-check          stdenvNoCC consumer of ncps-checktools (was buildGoModule override)
checks.helm-unittest-check     unchanged

Cohort selection — env var, not build tag

The design originally proposed //go:build integration_<backend> tags. The Phase 3 audit found five test files mixing gated and ungated test functions in the same file (pkg/cache/cache_test.go, pkg/cache/cache_internal_test.go, pkg/database/migrate/migrate_test.go, pkg/ncps/migrate_narinfo_test.go, pkg/lock/redis/redis_test.go); file-level tags would silently drop ungated tests from cohorts without the tag. Env-var-driven selection (which the test code's existing t.Skip pattern already uses) sidesteps the problem without touching any test file. Documented in openspec/changes/archive/2026-05-23-lean-flake-check/design.md D1.

Stack

main → improve-flake-check-time (this PR, #1249)

The two test-only fix PRs (#1253 timing assertions, #1254 pgx-cascade skip) already merged.

Test plan

  • nix flake check --no-build evaluates cleanly (13 explicit checks)
  • nix build .#ncps succeeds in ~1m
  • nix build .#ncps.coverage produces a merged coverage.txt covering all packages
  • Each cohort builds end-to-end at least once locally
  • Two clean green CI runs on this branch (runs 26353007007, 26353904024)
  • Reviewer call on whether the architectural wins justify the unchanged total CI time

🤖 Generated with Claude Code

@kalbasit

kalbasit commented May 24, 2026 •

Copy link
Copy Markdown
Owner Author

@dosubot dosubot Bot added the size:XXL This PR changes 1000+ lines, ignoring generated files. label May 24, 2026
@coderabbitai

coderabbitai Bot commented May 24, 2026 •

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Restructures the Nix flake check graph to run integration tests as per-backend cohorts, add a reusable helper-binaries package, split coverage into a separate derivation, explicitly enumerate checks, and add profiling tooling plus documentation and timing reports.

Lean Flake Check Optimization

Layer / File(s) Summary
Profiling infrastructure and baseline measurement
dev-scripts/profile-flake-checks.py
New Python CLI that discovers flake checks, deletes top outputs, builds each check, measures wall-clock durations, and renders a sorted markdown report with backend mappings.
Shared helper binary package and flake imports
nix/packages/ncps-checktools/default.nix, nix/packages/flake-module.nix
Adds a narrowed buildGoModule derivation building atlas-sum-check and ent-lint once and imports ./ncps-checktools and ./ncps-coverage into the packages flake.
Main package lean build with coverage forwarding
nix/packages/ncps/default.nix
Sets doCheck = false, includes .golangci.yml in the src fileset, and adds passthru.coverage forwarding from packages.ncps-coverage.
Dedicated coverage derivation with full test scaffold
nix/packages/ncps-coverage/default.nix
New overridden derivation that enables race/coverage tests, wires backend pre/post check scripts with cleanup traps, and exposes coverage output.
Per-backend cohort checks and explicit enumeration
nix/checks/flake-module.nix
Adds mkCohort and cohortTestDeps, replaces implicit checks composition with an explicit checks attrset, and adds unit/s3/postgres/mysql/redis cohort checks (removes schema-equivalence-check from checks).
Quality gate checks refactored for helper reuse
nix/checks/flake-module.nix
atlas-sum-check and ent-lint-check now run prebuilt helper binaries via stdenvNoCC against narrowed src; golangci-lint-check no longer sets src explicitly.
Docker image simplification and CI workflow update
nix/packages/docker.nix, .github/workflows/ci.yml
Removes unused lib param, uses config.packages.ncps directly in Docker contents, and adds ncps-checktools to the reusable CI workflow inputs.
User-facing documentation and design rationale
CLAUDE.md, openspec/changes/archive/2026-05-23-lean-flake-check/design.md
Documents cohort model, env-var gating, coverage split, and the six-phase migration plan with risks and rollback instructions.
Formal specification and profiling requirements
openspec/specs/flake-check-topology/spec.md, openspec/specs/test-suite-efficiency/spec.md
Specifies cohort topology, env-var-driven gating, helper-binary reuse, coverage out-of-band, explicit checks enumeration, mkCohort centralization, and per-derivation profiling and reproducibility requirements.
Per-phase progress and timing validation
openspec/changes/archive/2026-05-23-lean-flake-check/
Records baseline→final timing reports, per-derivation outcomes, flaky-test observations, and archived measurement artifacts.

Sequence Diagram(s)

sequenceDiagram
  participant Flake as Nix Flake (checks attrset)
  participant Builder as nix build
  participant preCheck as preCheck script (derivation)
  participant Backend as Backend service (Garage/Postgres/MySQL/Redis)
  participant Tests as go test -race ./...
  Flake->>Builder: build cohort derivation
  Builder->>preCheck: run preCheck (export NCPS_TEST_*)
  preCheck->>Backend: start needed backend(s)
  Builder->>Tests: execute go test with env
  Tests->>Builder: test results + coverage (when enabled)
  Builder->>preCheck: run postCheck (cleanup)
  preCheck->>Backend: stop services
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • kalbasit/ncps#1223: Overlaps on removing/replacing the standalone schema-equivalence-check in flake checks.
  • kalbasit/ncps#1190: Changes to cmd/ent-lint helper code that the new ncps-checktools and ent-lint-check wiring will consume.
  • kalbasit/ncps#1221: Related migration of ent-lint-check behavior toward helper-based checks.

Suggested labels

enhancement, documentation, dependencies, size:XL

Poem

🐰 I hopped through flakes and scripts tonight,

Built helpers once to keep the builds light,
Split tests to cohorts, let backends play,
CI wakes quicker and hops on its way,
🥕 small wins, big speed — a carrot-bright delight.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 16.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
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.
Title check ✅ Passed The title 'refactor(nix): per-backend test cohorts + lean ncps build' accurately describes the main structural rework of the nix flake check topology, combining per-backend test cohorts and lean package build.
Description check ✅ Passed The PR description is directly related to the changeset. It explains the structural rework of nix flake check, documents the before/after impact on build times, and details the architecture and key changes across multiple files.

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

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

@kalbasit kalbasit changed the title chore(openspec): draft lean-flake-check + baseline profiler chore(nix): cut nix flake check ~12m → ~5m May 24, 2026

@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 restructures the Nix flake check topology to improve CI performance, achieving a 56% reduction in parallel wall-clock time. Key changes include splitting the monolithic test derivation into parallel backend-specific cohorts (S3, Postgres, MySQL, Redis), moving coverage to a dedicated out-of-band derivation, and optimizing lint/drift checks to reuse pre-built helper binaries. However, the implementation introduces a critical infinite recursion between packages.ncps and packages.ncps-coverage due to circular dependencies in their definitions. Additionally, the new profiling script contains flaws that may lead to inaccurate timing data, specifically the omission of the --rebuild flag and suppressed errors during store deletion which could mask permission failures.

Comment thread nix/packages/ncps/default.nix Resolved
Comment thread dev-scripts/profile-flake-checks.py Resolved
Comment thread dev-scripts/profile-flake-checks.py Resolved
@kalbasit
kalbasit force-pushed the improve-flake-check-time branch from a3fe1f8 to adf7a8c Compare May 24, 2026 01:47

@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.

Actionable comments posted: 6

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
.github/workflows/ci.yml (1)

8-11: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

PR trigger includes non-main targets, violating CI workflow policy.

pull_request.branches currently includes release-*; this should be restricted to main only.

Suggested fix
 on:
   pull_request:
     branches:
       - main
-      - "release-*"

As per coding guidelines, ".github/workflows/*.yml: GitHub Actions CI workflows must only run on PRs targeting main (set branches: [main]) to prevent wasted CI resources in stacked PR workflows".

🤖 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 @.github/workflows/ci.yml around lines 8 - 11, Update the pull_request
trigger to only target main by removing the release-* entry from
pull_request.branches; edit the workflow's pull_request.branches setting (the
"pull_request" block and its "branches" array) so it contains only "main" to
comply with the CI policy.
🤖 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.

Inline comments:
In `@dev-scripts/profile-flake-checks.py`:
- Around line 5-7: Update the module/function docstring that currently claims
timings use "nix build ... --rebuild" so it accurately describes the current
behavior: the script removes the flake's top output path and runs "nix build ...
--no-link" to force re-evaluation and measure wall time; mention that we delete
the previous output (top-level store path) rather than using --rebuild, and note
any implications for cached derivations. Locate and edit the docstring at the
top of dev-scripts/profile-flake-checks.py (or the docstring for the main
profiling function) so the text and examples match the actual command and steps
used.

In `@nix/checks/flake-module.nix`:
- Around line 263-270: The pipeline currently only checks ent-lint output via
tee and grep, so failures of ent-lint itself are ignored; fix by ensuring the
ent-lint exit status is observed — either enable shell pipefail (set -o
pipefail) before running ent-lint --root . | tee ent-lint.out or capture the
first command’s exit code from PIPESTATUS (e.g. check PIPESTATUS[0] after
ent-lint --root . | tee ent-lint.out) and exit non‑zero if ent-lint failed,
while keeping the existing grep -q '^\[FAIL\]' ent-lint.out check to handle
invariant violations.

In `@openspec/changes/lean-flake-check/design.md`:
- Around line 272-279: The Phase 3/4 migration steps are outdated: remove the
instructions about adding build tags and refactoring `schema-equivalence-check`
via `mkDbBackedCheck` and instead document the actual executed approach —
describe using env-var cohorts (the env-var based per-backend cohorts) and the
planned deletion of the redundant `schema-equivalence` derivation; update the
Phase 3 text that currently references `ncps-{s3,postgres,mysql,redis}-tests`,
`ncps-unit-tests`, and `ncps-all-tests-compat` to reflect the env-var cohort
naming and gating strategy, and update Phase 4 to remove `mkDbBackedCheck` and
note the derivation deletion and re-measurement steps.
- Around line 236-241: Replace the “**[Build-tag tax]**” risk/mitigation text so
it no longer assumes build-tag based cohorts and instead validates the env-var
cohort selection mandated by decision D1: change the risk description to state
the danger of misconfigured or missing env-var gating (tests silently running in
wrong cohort), and update the mitigation to add a one-shot codemod or script
that annotates/flags integration tests that rely on env-var gating, add CI
checks that validate the env-var gating invariants (e.g., run tests under both
cohort env settings and fail if integration-only tests execute under the unit
env), and include automated unit/integration runtime assertions to detect when a
test lacks the required env-var guard; reference the original heading
“**[Build-tag tax]**” and decision D1 in the text to make the change explicit.

In `@openspec/changes/lean-flake-check/specs/flake-check-topology/spec.md`:
- Around line 26-31: Replace the build-tag trigger in the scenario: instead of
"a developer changes a file tagged `//go:build integration_postgres` and runs
`nix flake check`", describe an env-var-gated flow that sets the cohort for
Postgres (e.g., export COHORT=postgres or TEST_COHORT=postgres) before running
`nix flake check`, so that only the ncps-postgres-tests derivation is selected;
keep the rest of the expectations (only PostgreSQL started during that
derivation's preCheck, and S3/MySQL/Redis/unit-test derivations served from
cache) unchanged and reference ncps-postgres-tests and preCheck to locate the
affected scenario.
- Around line 218-220: The spec currently hard-codes a requirement for the
standalone `schema-equivalence-check`; replace this by expressing the quality
property via cohort execution coverage: remove the explicit mention of
`schema-equivalence-check` from the sentence and reword to state that the
quality invariant is preserved because the cohort (cohort execution coverage)
includes equivalent schema comparison work, i.e., require that the change set is
covered by the appropriate cohort execution (cohort-covered) instead of naming
`schema-equivalence-check` directly while keeping the other checks
(`ent-codegen-drift-check`, `atlas-sum-check`, `ent-lint-check`,
`helm-unittest-check`) behavior unchanged.

---

Outside diff comments:
In @.github/workflows/ci.yml:
- Around line 8-11: Update the pull_request trigger to only target main by
removing the release-* entry from pull_request.branches; edit the workflow's
pull_request.branches setting (the "pull_request" block and its "branches"
array) so it contains only "main" to comply with the CI policy.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 4d7dbfba-2ceb-455b-81bb-39645bfcd428

📥 Commits

Reviewing files that changed from the base of the PR and between 001e23f and a3fe1f8.

📒 Files selected for processing (21)
  • .github/workflows/ci.yml
  • CLAUDE.md
  • dev-scripts/profile-flake-checks.py
  • nix/checks/flake-module.nix
  • nix/packages/docker.nix
  • nix/packages/flake-module.nix
  • nix/packages/ncps-checktools/default.nix
  • nix/packages/ncps-coverage/default.nix
  • nix/packages/ncps/default.nix
  • openspec/changes/lean-flake-check/.openspec.yaml
  • openspec/changes/lean-flake-check/after-checktools-timings.txt
  • openspec/changes/lean-flake-check/after-cohorts-timings.txt
  • openspec/changes/lean-flake-check/after-coverage-split-timings.txt
  • openspec/changes/lean-flake-check/after-helper-timings.txt
  • openspec/changes/lean-flake-check/baseline-timings.txt
  • openspec/changes/lean-flake-check/design.md
  • openspec/changes/lean-flake-check/final-timings.txt
  • openspec/changes/lean-flake-check/proposal.md
  • openspec/changes/lean-flake-check/specs/flake-check-topology/spec.md
  • openspec/changes/lean-flake-check/specs/test-suite-efficiency/spec.md
  • openspec/changes/lean-flake-check/tasks.md

Comment thread dev-scripts/profile-flake-checks.py Resolved
Comment thread nix/checks/flake-module.nix Resolved

@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.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
.github/workflows/ci.yml (1)

8-11: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Restrict pull_request CI triggers to main only.

pull_request.branches still includes release-* (Line 11), which breaks the stacked-PR CI policy and can cause unnecessary workflow runs.

Suggested fix
 on:
   pull_request:
     branches:
       - main
-      - "release-*"

As per coding guidelines: “CI workflows must maintain the branches: [main] restriction in pull_request triggers to keep CI efficient for stacked PR workflows with Graphite.”

🤖 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 @.github/workflows/ci.yml around lines 8 - 11, Update the GitHub Actions
workflow trigger so pull_request only targets the main branch: in the workflow's
pull_request trigger block (the pull_request key and its branches list), remove
the "release-*" entry and ensure branches contains only "main" to enforce the CI
policy for stacked PRs.
🧹 Nitpick comments (1)
nix/checks/flake-module.nix (1)

32-41: ⚡ Quick win

Only pull backend daemons for the active cohort.

nativeBuildInputs currently adds every backend service to every cohort, so even ncps-unit-tests still realizes Garage, MariaDB, PostgreSQL, and Redis. That eats into the closure and wall-clock savings this split is trying to buy. Keep the shared utilities common, but make the actual backend daemons conditional on backends.

♻️ Proposed refactor
-      cohortTestDeps = with pkgs; [
+      commonCohortTestDeps = with pkgs; [
         awscli2 # init-garage smoke test (put/get/presign)
         curl # HTTP health checks
-        garage # S3-compatible storage
         jq # init-garage validation
-        mariadb # MySQL/MariaDB integration tests
-        postgresql # PostgreSQL integration tests
         python3 # ephemeral port allocation
-        redis # Redis distributed-lock integration tests
       ];
+
+      backendServiceDeps = backend:
+        {
+          garage = [ pkgs.garage ];
+          mysql = [ pkgs.mariadb ];
+          postgres = [ pkgs.postgresql ];
+          redis = [ pkgs.redis ];
+        }.${backend} or [ ];
@@
-          nativeBuildInputs = oa.nativeBuildInputs ++ cohortTestDeps;
+          nativeBuildInputs =
+            oa.nativeBuildInputs
+            ++ commonCohortTestDeps
+            ++ lib.concatMap backendServiceDeps backends;

Also applies to: 51-51

🤖 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 `@nix/checks/flake-module.nix` around lines 32 - 41, cohortTestDeps currently
unconditionally includes all backend daemons; change it so cohortTestDeps only
lists shared utilities (e.g., awscli2, curl, jq, python3) and move the actual
backend daemon packages into a conditional list derived from the backends
variable, then append that conditional backend list to nativeBuildInputs;
specifically, update the cohortTestDeps definition to remove
garage/mariadb/postgresql/redis, and implement a small helper or use
lib.concatMap / lib.optionalAttrs to map each entry of backends to the
corresponding pkgs.<backend> and include those only when present so
nativeBuildInputs becomes cohortTestDeps ++ backendDeps (this also applies where
the same pattern is used around the backends handling referenced near the other
location in the file).
🤖 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.

Inline comments:
In `@openspec/specs/flake-check-topology/spec.md`:
- Around line 232-234: The spec currently contradicts itself by both requiring
`schema-equivalence-check` to remain a gate and also forbidding standalone
derivations or duplicated cohort work that would justify removing that check;
update the wording to resolve this: state that `schema-equivalence-check` is
required to remain a gate by default, but allow its removal only when an
explicit, documented replacement exists (e.g., a cohort derivation that subsumes
the exact validation semantics) and the removal is approved with justification;
reference `schema-equivalence-check`, `ent-codegen-drift-check`,
`atlas-sum-check`, `ent-lint-check`, and `helm-unittest-check` when describing
the preservation-or-substitution rule so reviewers can verify consistency.

---

Outside diff comments:
In @.github/workflows/ci.yml:
- Around line 8-11: Update the GitHub Actions workflow trigger so pull_request
only targets the main branch: in the workflow's pull_request trigger block (the
pull_request key and its branches list), remove the "release-*" entry and ensure
branches contains only "main" to enforce the CI policy for stacked PRs.

---

Nitpick comments:
In `@nix/checks/flake-module.nix`:
- Around line 32-41: cohortTestDeps currently unconditionally includes all
backend daemons; change it so cohortTestDeps only lists shared utilities (e.g.,
awscli2, curl, jq, python3) and move the actual backend daemon packages into a
conditional list derived from the backends variable, then append that
conditional backend list to nativeBuildInputs; specifically, update the
cohortTestDeps definition to remove garage/mariadb/postgresql/redis, and
implement a small helper or use lib.concatMap / lib.optionalAttrs to map each
entry of backends to the corresponding pkgs.<backend> and include those only
when present so nativeBuildInputs becomes cohortTestDeps ++ backendDeps (this
also applies where the same pattern is used around the backends handling
referenced near the other location in the file).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 941f5068-3d61-4bc8-b377-8fb9cc8be918

📥 Commits

Reviewing files that changed from the base of the PR and between a3fe1f8 and adf7a8c.

📒 Files selected for processing (23)
  • .github/workflows/ci.yml
  • CLAUDE.md
  • dev-scripts/profile-flake-checks.py
  • nix/checks/flake-module.nix
  • nix/packages/docker.nix
  • nix/packages/flake-module.nix
  • nix/packages/ncps-checktools/default.nix
  • nix/packages/ncps-coverage/default.nix
  • nix/packages/ncps/default.nix
  • openspec/changes/archive/2026-05-23-lean-flake-check/.openspec.yaml
  • openspec/changes/archive/2026-05-23-lean-flake-check/after-checktools-timings.txt
  • openspec/changes/archive/2026-05-23-lean-flake-check/after-cohorts-timings.txt
  • openspec/changes/archive/2026-05-23-lean-flake-check/after-coverage-split-timings.txt
  • openspec/changes/archive/2026-05-23-lean-flake-check/after-helper-timings.txt
  • openspec/changes/archive/2026-05-23-lean-flake-check/baseline-timings.txt
  • openspec/changes/archive/2026-05-23-lean-flake-check/design.md
  • openspec/changes/archive/2026-05-23-lean-flake-check/final-timings.txt
  • openspec/changes/archive/2026-05-23-lean-flake-check/proposal.md
  • openspec/changes/archive/2026-05-23-lean-flake-check/specs/flake-check-topology/spec.md
  • openspec/changes/archive/2026-05-23-lean-flake-check/specs/test-suite-efficiency/spec.md
  • openspec/changes/archive/2026-05-23-lean-flake-check/tasks.md
  • openspec/specs/flake-check-topology/spec.md
  • openspec/specs/test-suite-efficiency/spec.md
💤 Files with no reviewable changes (3)
  • openspec/changes/archive/2026-05-23-lean-flake-check/specs/test-suite-efficiency/spec.md
  • openspec/changes/archive/2026-05-23-lean-flake-check/.openspec.yaml
  • openspec/changes/archive/2026-05-23-lean-flake-check/proposal.md
✅ Files skipped from review due to trivial changes (6)
  • openspec/changes/archive/2026-05-23-lean-flake-check/after-helper-timings.txt
  • openspec/changes/archive/2026-05-23-lean-flake-check/after-cohorts-timings.txt
  • openspec/specs/test-suite-efficiency/spec.md
  • openspec/changes/archive/2026-05-23-lean-flake-check/baseline-timings.txt
  • nix/packages/ncps-checktools/default.nix
  • openspec/changes/archive/2026-05-23-lean-flake-check/design.md

@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.

Actionable comments posted: 1

🤖 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.

Inline comments:
In `@nix/checks/flake-module.nix`:
- Around line 32-41: cohortTestDeps currently lists all backend binaries and is
applied to every cohort, causing unrelated cohorts to pull unnecessary closures;
refactor by scoping dependencies per-backend (e.g., replace the global
cohortTestDeps with a function or attribute set like cohortTestDepsForBackend or
cohortTestDeps.backendName that returns only the needed packages for a given
backend) and update callers to request cohortTestDepsForBackend(backend) (or
cohortTestDeps[backend]) instead of the monolithic cohortTestDeps; ensure
symbols to change include cohortTestDeps and any call sites that reference it
(note this also applies at the other occurrence around lines referenced in the
review).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 1611646d-65ed-4c81-b3b4-1a7be7418e5f

📥 Commits

Reviewing files that changed from the base of the PR and between dea9564 and 01a43dd.

📒 Files selected for processing (23)
  • .github/workflows/ci.yml
  • CLAUDE.md
  • dev-scripts/profile-flake-checks.py
  • nix/checks/flake-module.nix
  • nix/packages/docker.nix
  • nix/packages/flake-module.nix
  • nix/packages/ncps-checktools/default.nix
  • nix/packages/ncps-coverage/default.nix
  • nix/packages/ncps/default.nix
  • openspec/changes/archive/2026-05-23-lean-flake-check/.openspec.yaml
  • openspec/changes/archive/2026-05-23-lean-flake-check/after-checktools-timings.txt
  • openspec/changes/archive/2026-05-23-lean-flake-check/after-cohorts-timings.txt
  • openspec/changes/archive/2026-05-23-lean-flake-check/after-coverage-split-timings.txt
  • openspec/changes/archive/2026-05-23-lean-flake-check/after-helper-timings.txt
  • openspec/changes/archive/2026-05-23-lean-flake-check/baseline-timings.txt
  • openspec/changes/archive/2026-05-23-lean-flake-check/design.md
  • openspec/changes/archive/2026-05-23-lean-flake-check/final-timings.txt
  • openspec/changes/archive/2026-05-23-lean-flake-check/proposal.md
  • openspec/changes/archive/2026-05-23-lean-flake-check/specs/flake-check-topology/spec.md
  • openspec/changes/archive/2026-05-23-lean-flake-check/specs/test-suite-efficiency/spec.md
  • openspec/changes/archive/2026-05-23-lean-flake-check/tasks.md
  • openspec/specs/flake-check-topology/spec.md
  • openspec/specs/test-suite-efficiency/spec.md
✅ Files skipped from review due to trivial changes (5)
  • openspec/changes/archive/2026-05-23-lean-flake-check/.openspec.yaml
  • nix/packages/flake-module.nix
  • openspec/changes/archive/2026-05-23-lean-flake-check/specs/test-suite-efficiency/spec.md
  • openspec/changes/archive/2026-05-23-lean-flake-check/after-helper-timings.txt
  • openspec/changes/archive/2026-05-23-lean-flake-check/after-cohorts-timings.txt

Comment thread nix/checks/flake-module.nix Resolved
@kalbasit
kalbasit force-pushed the improve-flake-check-time branch from 01a43dd to 24e6384 Compare May 24, 2026 02:42
kalbasit added a commit that referenced this pull request May 24, 2026
## Summary

Three pre-existing `pkg/cache` flakes from #1247 share one root cause:
assertions that race against absolute wall-clock time and break under CI
load even when the production code is correct. Surfaced repeatedly
during the lean-flake-check measurement runs in #1249 (which sits
stacked on top of this branch).

All three fixes are **test-only**. No production code is touched.

## What changed

| Flake (from #1247) | Test | Before | After |
| --- | --- | --- | --- |
| #5 |
`TestCDCBackends/{SQLite,MySQL}/first_pull_completes_before_CDC_chunking_finishes`
| `assert.Less(elapsed, 500ms)` racing the slow chunker | Happens-before
check: `select { case <-chunkingStarted: t.Fatal(…) }` after
`io.ReadAll`. `slowChunker` grew an optional `started chan struct{}`
closed when its delay expires. Delay bumped 500 ms → 10 s (only matters
under regression). |
| #1 | `TestCacheBackends/MySQL/PutNarInfoDeadlock` |
`context.WithTimeout(2s)` then `assert.NoError`. Could not distinguish
"deadlock" from "MariaDB slow." | Timeout bumped 2 s → 60 s. A real
deadlock still fails fast; non-deadlocked slow path now passes. |
| #2 | Six instances of `assert.WithinDuration(CreatedAt,
LastAccessedAt, 2s)` across `TestCacheBackends` | 2 s tolerance was
tight enough that two CLOSE-TO-NOW() timestamps from different SQL
operations under MariaDB load could fall outside it (observed -3 s
spread). | Tolerance bumped 2 s → 30 s. Still tight enough to catch a
genuinely broken "set both timestamps at row creation" semantic. |

## Why "test-only" and not "fix the production bug"

These three are *measurement bugs*: the assertions encode an assumption
("operation X completes within Y milliseconds") that's an artifact of
the dev host's speed, not a property the codebase ever promised. The
behavior the tests *want* to verify (no deadlock, timestamps set close
together at creation, GetNar doesn't block on chunking) is still being
verified — the encoding is just no longer wall-clock-dependent.

Flakes #3 and #4 from #1247 are NOT addressed here because they are not
the same shape:

- **#3** (`ConcurrentDownloadCancelOneClientOthersContinue`, 20-min
hang) is a real hang in `io.ReadAll(readerB)` or `wg.Wait()` after all
the existing 5–10 s guards have passed — almost certainly a
production-code bug in the shared-reader-fanout path. Filed as **#1252**
for separate investigation.
- **#4** (`GetNarInfoConcurrentPutNarInfoDuringMigration`) exercises the
same concurrent-migration-vs-PutNarInfo window that the next test
(`testGetNarInfoMultipleConcurrentPutsDuringMigration`) explicitly
`t.Skip`s with `"blocked on pgx transaction-abort cascade in PutNarInfo
re-fetch path"`. That tracked production bug is the actual root cause;
this test exercising it less reliably isn't a separate issue.

## Stack

This PR is stacked under #1249 (`improve-flake-check-time`); landing
this first should unblock #1249's CI by eliminating three of the five
flakes that were causing intermittent reds.

```
main → fix-cache-test-timing-assertions (this PR, #1253)
     → improve-flake-check-time (#1249)
```

## Test plan

- [x] `nix develop -- go test -race -count=1 -run
"TestCDCBackends/SQLite/first_pull_completes_before_CDC_chunking_finishes"
./pkg/cache/` passes locally.
- [x] `nix develop -- go test -race -count=1 -run
"TestCacheBackends/SQLite/(PutNarInfoDeadlock|GetNarInfo/narinfo_exists_upstream/nar_does_exist)"
./pkg/cache/` passes locally.
- [x] `golangci-lint run` clean (run inside `nix develop` so the
toolchain resolves).

---------

Co-authored-by: Claude Opus 4.7 <[email protected]>
Base automatically changed from fix-cache-test-timing-assertions to main May 24, 2026 02:55
@kalbasit
kalbasit force-pushed the improve-flake-check-time branch from 24e6384 to ea06a38 Compare May 24, 2026 02:56

@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.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
.github/workflows/ci.yml (1)

8-11: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Remove release-* from pull_request branches to comply with coding guidelines.

The workflow triggers on PRs targeting both main and release-* branches. As per coding guidelines, CI workflows must only run on PRs targeting main (branches: [main]) to avoid wasted resources in stacked PR workflows.

📋 Proposed fix
 on:
   pull_request:
     branches:
       - main
-      - "release-*"

As per coding guidelines: "CI workflows must only run on PRs targeting main (branches: [main]) to avoid wasted resources in stacked PR workflows"

🤖 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 @.github/workflows/ci.yml around lines 8 - 11, Remove the "release-*" branch
pattern from the pull_request trigger so CI only runs for PRs targeting main;
edit the workflow's pull_request -> branches list to keep only main (remove
"release-*") in the .github/workflows/ci.yml file, ensuring the pull_request
trigger references branches: [main] and leaving other triggers untouched.
🤖 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.

Inline comments:
In `@nix/checks/flake-module.nix`:
- Around line 48-52: mkCohort currently inherits the broad src from
config.packages.ncps which pulls in every backend’s scripts and causes
cross-backend invalidation; update the mkCohort invocation to override src
(inside the mkCohort/overrideAttrs flow that touches config.packages.ncps,
nativeBuildInputs/cohortTestDeps) so that each cohort’s derivation composes only
the shared test inputs plus that cohort’s specific backend scripts (e.g., build
a src = lib.makeSource or stdenv.mkDerivation that copies common test files and
the cohort backend dir), ensuring each cohort exports its own NCPS_TEST_* env
and prevents unrelated rebuilds.

---

Outside diff comments:
In @.github/workflows/ci.yml:
- Around line 8-11: Remove the "release-*" branch pattern from the pull_request
trigger so CI only runs for PRs targeting main; edit the workflow's pull_request
-> branches list to keep only main (remove "release-*") in the
.github/workflows/ci.yml file, ensuring the pull_request trigger references
branches: [main] and leaving other triggers untouched.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 20627f52-2830-468d-88e0-033c818d6435

📥 Commits

Reviewing files that changed from the base of the PR and between 01a43dd and ea06a38.

📒 Files selected for processing (23)
  • .github/workflows/ci.yml
  • CLAUDE.md
  • dev-scripts/profile-flake-checks.py
  • nix/checks/flake-module.nix
  • nix/packages/docker.nix
  • nix/packages/flake-module.nix
  • nix/packages/ncps-checktools/default.nix
  • nix/packages/ncps-coverage/default.nix
  • nix/packages/ncps/default.nix
  • openspec/changes/archive/2026-05-23-lean-flake-check/.openspec.yaml
  • openspec/changes/archive/2026-05-23-lean-flake-check/after-checktools-timings.txt
  • openspec/changes/archive/2026-05-23-lean-flake-check/after-cohorts-timings.txt
  • openspec/changes/archive/2026-05-23-lean-flake-check/after-coverage-split-timings.txt
  • openspec/changes/archive/2026-05-23-lean-flake-check/after-helper-timings.txt
  • openspec/changes/archive/2026-05-23-lean-flake-check/baseline-timings.txt
  • openspec/changes/archive/2026-05-23-lean-flake-check/design.md
  • openspec/changes/archive/2026-05-23-lean-flake-check/final-timings.txt
  • openspec/changes/archive/2026-05-23-lean-flake-check/proposal.md
  • openspec/changes/archive/2026-05-23-lean-flake-check/specs/flake-check-topology/spec.md
  • openspec/changes/archive/2026-05-23-lean-flake-check/specs/test-suite-efficiency/spec.md
  • openspec/changes/archive/2026-05-23-lean-flake-check/tasks.md
  • openspec/specs/flake-check-topology/spec.md
  • openspec/specs/test-suite-efficiency/spec.md
✅ Files skipped from review due to trivial changes (2)
  • openspec/changes/archive/2026-05-23-lean-flake-check/.openspec.yaml
  • openspec/changes/archive/2026-05-23-lean-flake-check/specs/flake-check-topology/spec.md

Comment thread nix/checks/flake-module.nix Resolved
@kalbasit
kalbasit changed the base branch from main to skip-concurrent-put-migration-flake May 24, 2026 03:39
@kalbasit
kalbasit force-pushed the improve-flake-check-time branch from ea06a38 to 9c68b2b Compare May 24, 2026 03:39
kalbasit added a commit that referenced this pull request May 24, 2026
## Summary

Adds a `t.Skip` to `testGetNarInfoConcurrentPutNarInfoDuringMigration`
in `pkg/cache/cache_test.go`, mirroring the existing skip on its sibling
`testGetNarInfoMultipleConcurrentPutsDuringMigration`. Both tests
exercise the same `pgx transaction-abort cascade in PutNarInfo re-fetch
path` production bug; the sibling skips deterministically because it
triggers reliably under many concurrent puts, while this test (with just
one concurrent put) hits it intermittently and surfaces as a CI flake.

Most recently observed blocking #1249 (build run 26350206306). Tracked
under #1247.

## Why skip rather than fix

The underlying production bug is real: the PutNarInfo re-fetch path does
not roll back the pgx transaction before re-issuing the query, so it
cascades into `current transaction is aborted, commands ignored until
end of transaction block (SQLSTATE 25P02)`. The sibling test that hits
this deterministically has been skipped since at least the
migrate-to-ent-and-atlas work and the bug remains open. Fixing it is a
real production change worth its own PR cycle.

In the meantime, leaving this test enabled means the flake
intermittently blocks every PR that touches anything in `pkg/cache`.
Skipping it makes the bug's coverage trail consistent: both tests will
re-enable as a pair once the cascade is fixed.

## Stack

```
main → skip-concurrent-put-migration-flake (this PR)
     → improve-flake-check-time (#1249)
```

Landing this first should let #1249's CI go green deterministically. The
two test-only PR fixes (this one + the merged #1253) collectively
neutralize four of the five flakes from #1247 that have been blocking
#1249; the fifth (#1252, the 20-min hang in
`ConcurrentDownloadCancelOneClientOthersContinue`) is a real production
bug we have not observed during recent measurement runs and is filed
separately.

## Test plan

- [x] `go test -race -count=1 -v -run
"TestCacheBackends/SQLite/GetNarInfoConcurrentPutNarInfoDuringMigration"
./pkg/cache/` prints `SKIP: ... blocked on pgx transaction-abort cascade
in PutNarInfo re-fetch path` and passes.
- [x] `golangci-lint run` clean.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 4.7 <[email protected]>
Base automatically changed from skip-concurrent-put-migration-flake to main May 24, 2026 03:39
@kalbasit
kalbasit force-pushed the improve-flake-check-time branch from 9c68b2b to d1d610b Compare May 24, 2026 03:40
@codecov

codecov Bot commented May 24, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 5.50%. Comparing base (211083d) to head (d1d610b).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@          Coverage Diff          @@
##            main   #1249   +/-   ##
=====================================
  Coverage   5.50%   5.50%           
=====================================
  Files          6       6           
  Lines        400     400           
=====================================
  Hits          22      22           
  Misses       374     374           
  Partials       4       4           

☔ View full report in Codecov by Sentry.
📢 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.

kalbasit and others added 4 commits May 23, 2026 21:21
Add the lean-flake-check change directory (proposal, design, specs for
flake-check-topology and test-suite-efficiency, tasks) and a
dev-scripts/profile-flake-checks.py helper that times each entry of
the flake's checks attrset by deleting only the top-level output and
timing a fresh build. Intermediate dependency derivations are left
warm, so the local numbers track CI's post-substitution state.

baseline-timings.txt captures the starting wall-clock against main
HEAD (61405fb) for comparison across the upcoming phases. Refs #1247
for the pre-existing MariaDB flake observed during baseline.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Replace the per-check buildGoModule overrides for ent-lint-check and
atlas-sum-check with stdenvNoCC.mkDerivation consumers of a new
packages.ncps-checktools derivation, which compiles cmd/ent-lint and
cmd/atlas-sum-check once from a narrow fileset (the two cmd dirs plus
go.mod / go.sum — neither helper imports any internal package). The
per-check filesets shrink to just ent/ and migrations/, so a touch to
either tree only invalidates the matching check.

Also drop the src = ../../. override on golangci-lint-check so it
shares src, vendorHash, and the fixed-output goModules derivation
with packages.ncps. Required adding .golangci.yml to ncps's fileset
so the linter still finds its configuration. ent-codegen-drift-check
can't share — proxyVendor mode produces a structurally different
goModules — and now carries a comment explaining why.

Phase 2 of openspec/changes/lean-flake-check. See
after-checktools-timings.txt for measured deltas (atlas-sum-check
5s → 0s, ent-lint-check 4s → 0s; golangci-lint-check win is structural,
not wall-clock).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Add five new check derivations under nix/checks/flake-module.nix that
split the integration test work currently done by the monolithic
packages.ncps:

  ncps-unit-tests       no backends; integration subtests skip via env
  ncps-s3-tests         garage only; exports NCPS_TEST_S3_*
  ncps-postgres-tests   postgres only; exports NCPS_TEST_ADMIN_POSTGRES_URL
  ncps-mysql-tests      mariadb only; exports NCPS_TEST_ADMIN_MYSQL_URL
  ncps-redis-tests      redis only; exports NCPS_ENABLE_REDIS_TESTS=1

A small `mkCohort` helper builds each cohort as a stripped-down
overrideAttrs of packages.ncps that skips the binary build, sources
only its own pre/post-check scripts, and runs `go test -race ./...`
unchanged — the existing per-subtest t.Skip on the NCPS_TEST_* env
vars handles cohort membership at runtime.

Build tags were rejected after the Phase 3 audit found five test
files that mix gated and ungated test functions (cache_test.go,
cache_internal_test.go, migrate_test.go, migrate_narinfo_test.go,
redis_test.go). File-level tags would silently drop ungated tests
from cohorts without the tag. Env-var-driven selection sidesteps
that without touching any test file. design.md D1 and the
flake-check-topology spec are updated to record the pivot.

Phase 3 is additive: packages.ncps still carries doCheck = true and
remains in the checks attrset, so this change does not yet move the
flake-check wall-clock. Phases 5–6 drop the monolith; after that the
parallel-cohort wall-clock will be max(cohorts) ≈ 6 min (mysql
cohort) vs the current ~12 min monolith. Per-cohort wall-clocks
recorded in after-cohorts-timings.txt.

Also expand dev-scripts/profile-flake-checks.py BACKEND_MAP to
annotate the new cohort derivations in profiler output.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
TestSchemaEquivalence in migrations/equivalence_test.go iterates
SQLite + Postgres + MySQL with t.Skip on the matching
NCPS_TEST_ADMIN_* env var, exactly the same skip pattern the rest
of the integration suite uses. After Phase 3 introduced per-backend
cohorts, that test now runs automatically in ncps-postgres-tests
(SQLite + Postgres paths), ncps-mysql-tests (SQLite + MySQL paths),
and ncps-unit-tests (SQLite path) via the unchanged
`go test ./...` invocation.

The standalone schema-equivalence-check derivation therefore did
~1m12s of duplicate work (spinning up Postgres + MariaDB a second
time and re-running TestSchemaEquivalence) without adding incremental
coverage. Delete it.

The original Phase 4 plan was to refactor schema-equivalence-check
to call a new mkDbBackedCheck helper. Deleting is strictly better:
fewer derivations, less duplicate runtime, no helper rename. The
shared-helper requirement in the flake-check-topology spec is now
satisfied by the existing mkCohort (introduced in Phase 3), which
the spec wording is updated to acknowledge.

Sequential profile sum drops from 17m04s (post-Phase-3) to 15m34s;
projected post-monolith parallel wall-clock drops from ~6m to ~5m.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
kalbasit and others added 9 commits May 23, 2026 21:22
Cut nix build .#ncps from ~12m to ~1m10s by moving the test scaffold
out of packages.ncps into a new packages.ncps-coverage derivation.

packages.ncps changes:

  - doCheck = false; outputs = [ "out" ] only.
  - nativeBuildInputs trimmed to makeBinaryWrapper; the integration
    backend tools (garage, mariadb, postgresql, redis, awscli2, jq,
    curl, python3) only existed for preCheck and have no place in
    a pure binary build.
  - preCheck / checkFlags / postCheck removed.
  - passthru.coverage = packages.ncps-coverage.coverage so
    `nix build .#ncps.coverage` still resolves to a coverage-named
    output of a multi-output derivation. The shared CI workflow at
    kalbasit/gh-actions/.github/workflows/build.yml relies on this
    path (its codecov step consumes result-coverage) and is unchanged
    by this work.

packages.ncps-coverage carries everything packages.ncps shed: the
backend nativeBuildInputs, the four pre/post-check sources, the
race + -coverprofile checkFlags, and the multi-output [ out coverage ]
layout that produces the merged coverage.txt the codecov step expects.

nix/checks/flake-module.nix:

  - mkCohort re-adds the backend tools via cohortTestDeps so the
    per-backend cohort derivations can still spin services up after
    packages.ncps dropped them.
  - ncps-coverage is filtered out of the checks attrset; nix flake
    check MUST NOT pay for the ~12m coverage instrumentation on
    every PR. Phase 6 will replace the filter with a full explicit
    enumeration.

nix/packages/docker.nix:

  - Drops the doCheck and outputs = lib.remove "coverage" overrides
    on the embedded ncps reference. packages.ncps already provides
    both (doCheck = false, single out output), so the overrides are
    not just redundant but actively broken once outputs no longer
    contains "coverage".

Net wall-clock: pre-Phase-5 nix flake check ≈ max(monolith 12m, ...);
post-Phase-5 ≈ max(cohort group ~5m, lean ncps 1m, ...) ≈ 5m. The
remaining floor inside the shared CI build job is the Docker image
build, which is unaffected by this work.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Replace `checks = self'.packages // self'.devShells // {...}` in
nix/checks/flake-module.nix with an explicit 13-entry attrset.
The merge had been pulling in eight derivations that are not quality
gates and never should have run on every PR:

  default              alias of packages.ncps
  deps                 process-compose dev dependencies
  docker, docker-dev   runtime images, built explicitly by CI
  push-docker-image    CLI wrapper for the CI image push step
  k8s-tests            CLI tool for local Kind testing
  update-cu-base       CLI tool for the container-use base image
  ncps-coverage        coverage build, invoked only by the codecov step

All eight remain buildable as `nix build .#<name>`; they are simply
no longer part of `nix flake check`. The targeted
`lib.filterAttrs (n: _: n != "ncps-coverage")` filter introduced in
Phase 5 is gone — the explicit enumeration supersedes it.

The 13 remaining checks: ncps, ncps-checktools, the five cohort
derivations, golangci-lint-check, ent-codegen-drift-check,
atlas-sum-check, ent-lint-check, helm-unittest-check, plus treefmt
(which enters via treefmt-nix's own flake-module).

Also expand CLAUDE.md's integration-test section to describe the
new cohort topology and how to invoke a single cohort.

Final wall-clock model (cold local, after this commit):

  nix flake check parallel  ≈ 5m24s   (ncps-mysql-tests gates)
  nix flake check sequential ≈ 17m16s

vs the pre-change ~12m20s monolith, that is a 56% reduction in the
parallel wall-clock, above the 40% target in the
flake-check-topology spec. CI's `shared / build / build` job
should drop from ~14m to ~7–8m; the residual is the Docker image
build inside the same job, unaffected by this work.

Closes the lean-flake-check openspec change (36/36 tasks done).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Move openspec/changes/lean-flake-check/ to
openspec/changes/archive/2026-05-23-lean-flake-check/ and apply the
two delta specs to the main specs tree:

  - openspec/specs/flake-check-topology/spec.md is new (the change
    introduced this capability).
  - openspec/specs/test-suite-efficiency/spec.md gains one ADDED
    requirement ("Profiling at Nix-check-derivation granularity")
    that extends the existing profiling workflow rules to cover
    per-derivation wall-clock figures.

Required for the openspec-guard CI step, which fails any PR that
leaves an active change directory unarchived.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Three related comments on the same script:

  - Docstring claimed `--rebuild` but the implementation deletes the
    top output and runs `nix build` without `--rebuild`. The header
    now describes the actual delete-then-build approach and explains
    why `--rebuild` is unsuitable here (it asserts determinism against
    a prior output and errors on uncached derivations).

  - The `--rebuild` discussion noted that Cachix substitution can
    still serve a deleted top output, masking the real build cost.
    Added an explicit note in the docstring documenting this trade-off
    and why suppressing substituters wholesale is the wrong fix.

  - `delete_top_output` swallowed `nix store delete` errors silently,
    which on multi-user installs (where only trusted users can delete
    store paths) would lead to the next build being a no-op cache hit
    reporting ~0s. The function now prints stderr on failure so the
    user notices instead of trusting misleading timings.

No behavioral change to the measurement itself, only diagnostics.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
`ent-lint --root . | tee ent-lint.out` propagates only tee's exit
code by default, so a non-zero exit from ent-lint that doesn't
produce a [FAIL] line (binary crash, signal, vendor-cache surprise)
silently passes the check. Add `set -o pipefail` so the pipeline
inherits ent-lint's failure status.

The [FAIL] grep check stays as-is — it covers the explicit
invariant-violation path; pipefail covers everything else.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
design.md's Risks/Trade-offs section and Migration Plan still read
as if Phase 3 used file-level build tags and Phase 4 refactored
schema-equivalence-check via a new mkDbBackedCheck helper. Both
plans were superseded mid-implementation and the decisions section
(D1, D4) was rewritten to record that, but the supporting sections
weren't, leaving the document internally inconsistent.

- [Build-tag tax] risk → [Env-var gating tax]: the actual risk
  shape under the executed env-var approach is a new integration
  test forgetting its t.Skip guard, which would run in every
  cohort rather than only its own. The mitigation calls out the
  established convention as the safeguard.
- Migration plan: rewrite Phases 3, 4, 6 to describe what actually
  shipped (cohorts via mkCohort + env vars, schema-equivalence
  deletion not refactor, explicit checks enumeration).
- Open question on build-tag naming: resolved by pointing at D1.

No code change, no semantic change to the design's conclusions —
just bringing the supporting prose in line with the decisions
already recorded.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Two issues in the flake-check-topology spec that survived the
Phase 3 build-tag pivot and the Phase 4 schema-equivalence-check
deletion. Fix in both the archived change spec and the synced live
spec under openspec/specs/.

- "Touching a Postgres-only integration test" scenario triggered on
  a build-tagged file change, contradicting the env-var-only
  requirement on the lines immediately below it. Rewrite the
  scenario to a backend-specific *input* the design actually
  per-cohort-invalidates on (`pre-check-postgres.sh`), and add a
  note explaining that Go-source changes in shared packages
  invalidate every cohort by design.

- "Quality invariants preserved" listed `schema-equivalence-check`
  among the derivations that "continue to fail the gate on the
  same inputs they fail on today." That derivation was deleted in
  Phase 4. Drop it from the list and add a sibling invariant that
  spells out how the cohorts now cover the work it used to do.

No code change; only spec wording. The wording on the change side
and the live side stay byte-for-byte identical so a future re-sync
is a no-op.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
CI's build job runs `nix flake check -L` then `nix build
.#ncps.coverage -L` sequentially as two separate steps. With
ncps-coverage previously excluded from the checks attrset, the
coverage build was paying its full ~12 min runtime on top of the
~12 min flake-check, even though Nix could have run it in parallel
with the cohorts.

Re-include ncps-coverage in the checks attrset. nix flake check
now schedules it alongside the cohorts; the wall-clock is
max(coverage, slowest cohort) ≈ coverage. The subsequent
`nix build .#ncps.coverage -L` step in CI resolves to the same
store path Nix just built and becomes a near-instant substitution
hit, dropping the CI build job by ~10–12 min per arch.

Trade-off: local `nix flake check` now pays the coverage cost too.
In practice developers iterate against specific cohort derivations
(e.g. `nix build .#checks.x86_64-linux.ncps-postgres-tests`), not
the full flake-check, so the local cost is rarely felt.

The earlier Phase-6 comment exclusion rationale was wrong —
excluding ncps-coverage from checks didn't save CI work, it just
serialized it.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@kalbasit
kalbasit force-pushed the improve-flake-check-time branch from d1d610b to dfc6eca Compare May 24, 2026 04:27
kalbasit and others added 6 commits May 23, 2026 21:36
Iteration 1 of the CI-reduction work increased nix-level parallelism
(packages.ncps-coverage now runs alongside the five cohorts under
nix flake check). That exposed a pre-existing fragility in
cmd/generate-migrations/main_test.go: the shared go-build helper has
a 60 s context timeout, and the resulting 6+ concurrent `go build`
invocations across cohorts on a CI runner blew that budget under
load (observed at exactly 60.08 s on aarch64 run 26351855777,
TestNameValidation and TestSQLOnlyEmitsThreeDialects both timing
out at the build step).

The compile itself takes ~5-10 s on a quiet machine. Bumping the
window to 180 s makes the test robust to CI contention without
softening any real assertion — a regression where the binary
genuinely takes >180 s to build would still surface clearly.

No production code touched.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Eliminate the redundant monolith test run by ncps-coverage. Cohorts
now emit cover.out profiles; ncps-coverage merges them via an
embedded Python script (gocovmerge isn't packaged in nixpkgs).

mkCohort changes:
  - outputs = [ "out" "coverage" ]
  - go test gains -coverprofile=cover.out -covermode=atomic
    -coverpkg=./...
  - postCheck stages cover.out into $coverage

ncps-coverage rewritten:
  - Was: monolithic buildGoModule with all 4 backends in preCheck.
  - Now: stdenvNoCC.mkDerivation that merges per-cohort cover.out via
    nix/packages/ncps-coverage/merge_coverage.py.
  - ~30s instead of ~12m.

Cycle break via packages._ncps-base: ncps-coverage's dependency on
the cohorts would have formed a cycle (cohorts → mkCohort overrides
packages.ncps → ncps.passthru.coverage → ncps-coverage). Extract
a private packages._ncps-base derivation (bare buildGoModule with
shared src + vendorHash, no passthru) and have mkCohort override
from THAT. packages.ncps keeps its passthru.coverage so
`nix build .#ncps.coverage` still works for the shared CI workflow.

Reverts iteration 1's "ncps-coverage in checks" addition: now moot
since coverage depends on cohort outputs that the CI step finds
already cached.

Verified locally: cohorts emit 27 MB cover.out each; merger reduces
838k input lines to 14k merged (correct dedup + hit-count summing).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
cmd/generate-migrations tests do a `go build` of the binary they
test, which on aarch64 CI under 5 concurrent cohort builds blows
even a 180s context timeout. The tests don't gate on any backend
env var — running them in every cohort was 5x redundant work for
zero incremental coverage.

Restrict backend cohorts (s3, postgres, mysql, redis) to the trees
that actually contain backend-gated tests:

  ./pkg/... ./internal/... ./migrations/... ./testhelper/...

Unit cohort still runs `./...` so cmd/* tests get coverage exactly
once. The merged profile is unchanged in scope because
-coverpkg=./... continues to capture production code in every
package regardless of which packages' tests ran.

Expected effect on CI: aarch64 mysql cohort goes from ~8 min
(dominated by cmd/generate-migrations build contention) to ~5 min
(only its backend tests), bringing the cohort wall-clock under the
8-min CI target.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Backend cohorts (s3, postgres, mysql, redis) test only ./pkg/...,
./internal/..., ./migrations/..., ./testhelper/... after iteration 3.
But the coverage scope was still -coverpkg=./..., which instruments
cmd/*, ent/*, main.go too — packages whose tests this cohort doesn't
run. With -race amplifying instrumentation cost, that's pure waste
on a 2-4 core CI runner already at saturation.

Narrow backend cohorts' coverage to match their test scope:
  -coverpkg=./pkg/...,./internal/...,./migrations/...,./testhelper/...

Unit cohort keeps -coverpkg=./... so cmd/* and the rest still
contribute to the merged coverage profile. The merger sums hit counts
for keys that appear in multiple profiles, so reducing one cohort's
instrumentation scope doesn't lose coverage — it just stops
re-measuring code the cohort isn't exercising.

Expected: per-cohort wall-clock drops 10-30% from less instrumentation
overhead, which should bring x86_64 build job from ~15 min toward
the 8 min target.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Cohort cumulative test times from iter 3 measurement:
  ncps-unit-tests:     4.4 min  ← longest
  ncps-postgres-tests: 3.2 min
  ncps-mysql-tests:    2.6 min
  ncps-redis-tests:    2.4 min
  ncps-s3-tests:       2.3 min

The unit cohort dominated because it ran `./...` — all of pkg/* on
top of cmd/*+ent/*+main. But backend cohorts already test pkg/*
(non-gated tests run in all of them; gated tests skip via env var).
The unit cohort's pkg/* run was strictly redundant work.

Replace ncps-unit-tests with ncps-cmd-tests:
  - Tests only ./cmd/... ./ent/... .
  - Covers the paths backend cohorts SKIP (since they restrict to
    ./pkg/... ./internal/... ./migrations/... ./testhelper/...)
  - -coverpkg=./cmd/...,./ent/...,. matches the test scope.

Trade-off: non-gated unit tests in pkg/* still run 4 times (once per
backend cohort). Eliminating that duplication would require either
file-level build tags (rejected — five files mix gated and ungated
tests in the same file) or test-name selection via -run patterns
(brittle). Accept the 4x cost on small unit tests; the much larger
cmd cohort run is what gets eliminated.

Updated:
  - ncps-coverage merger references ncps-cmd-tests instead of
    ncps-unit-tests.
  - dev-scripts/profile-flake-checks.py BACKEND_MAP for the new
    cohort name; ncps-coverage marked as []-backend now that it's a
    pure merger.

Expected: x86_64 build job from ~15 min (iter 3 green) → ~5 min,
matching the < 5 min stretch target.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
cmd/generate-migrations tests invoke the binary via exec.Command,
which they build in-test with `go build`. On aarch64 CI runners that
build has been observed taking >180 s (Atlas + Ent imports are heavy;
race-instrumented compilation amplifies that) and times out — even
in the isolated ncps-cmd-tests cohort with no contention from other
cohorts. Iter 1.5 bumped 60 s → 180 s; still not enough.

Real fix: don't rebuild what Nix already has. Pre-build the binary
once in the cohort's buildPhase and pass the path to the test via
NCPS_TEST_GENERATE_MIGRATIONS_BIN. The test reads the env var and
skips its own go-build when present.

Local `go test` keeps working: the env var is empty, the test falls
back to the existing `go build` path with the same 180 s budget.

mkCohort change: backend cohorts (which don't run cmd/* tests anyway
after iter 3) keep the no-op buildPhase. The cmd cohort runs
`go build -o $TMPDIR/cohort-bin/generate-migrations ./cmd/generate-migrations`
in buildPhase and exports NCPS_TEST_GENERATE_MIGRATIONS_BIN for
checkPhase. (Nix runs all phases in the same shell, so the export
carries over.)

Coverage is unaffected: cmd/generate-migrations is tested as a black
box via exec.Command in both code paths, so no instrumentation flows
through the binary regardless of where it's built.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@kalbasit kalbasit changed the title chore(nix): cut nix flake check ~12m → ~5m refactor(nix): per-backend test cohorts + lean ncps build May 24, 2026
@kalbasit
kalbasit merged commit dd9622c into main May 24, 2026
28 of 38 checks passed
@kalbasit
kalbasit deleted the improve-flake-check-time branch May 24, 2026 07:11
@dosubot

dosubot Bot commented May 24, 2026

Copy link
Copy Markdown

Documentation Updates

1 document(s) were updated by changes in this PR:

Development Environment with Garage
View Changes
@@ -175,6 +175,14 @@
 
 **CI and Nix Builds:**
 
-When building with Nix or running CI, all integration test dependencies (Garage, PostgreSQL, MariaDB) are started automatically, and the environment variables are set for you. This ensures comprehensive backend testing in all environments.
+Integration tests run in per-backend cohort derivations under `nix/checks/flake-module.nix`. Each cohort starts only its own backend in `preCheck` and runs only the tests gated on the corresponding `NCPS_TEST_*` env var:
+
+- `ncps-cmd-tests` — cmd/*, ent/*, main package (no backends)
+- `ncps-s3-tests` — Garage
+- `ncps-postgres-tests` — PostgreSQL
+- `ncps-mysql-tests` — MariaDB
+- `ncps-redis-tests` — Redis
+
+`nix flake check` runs all cohorts in parallel (alongside lint/drift checks). `nix build .#ncps` now performs a lean binary build only (~1 min, `doCheck=false`) without starting any backends or running tests. Coverage generation happens in a separate `packages.ncps-coverage` derivation (accessible via `nix build .#ncps.coverage`), which merges per-cohort coverage profiles and is not part of the `checks` attrset. CI runs the full test suite via these cohort derivations.
 
 For more details, see the project's CONTRIBUTING.md and CLAUDE.md.

How did I do? Any feedback?  Join Discord

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

Labels

size:XXL This PR changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant