Repository navigation
test: shrink go test wall time ~48% - #1241
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
📝 WalkthroughSummary by CodeRabbit
WalkthroughThis PR speeds and stabilizes tests: it builds a shared test binary once, adds a go-test profiling script, tightens timing in cache/upstream/redis tests for determinism, and replaces S3 mock errors with realistic 403 AccessDenied responses. ChangesTest Infrastructure and Optimization
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
Comment |
|
This change is part of the following stack:
Change managed by git-spice. |
There was a problem hiding this comment.
Code Review
This pull request focuses on optimizing test execution time and improving test reliability across the codebase. Key changes include implementing a singleton pattern for binary builds in migration tests with TestMain cleanup, reducing sleep durations and refining timeouts in cache and upstream tests, and introducing a new Python script for profiling Go test performance. Additionally, S3 storage tests were refactored to use a custom error response helper that prevents unnecessary SDK retries during failure simulations. I have no feedback to provide.
`nix flake check` and `go test -race ./...` were slow enough (~88s
on a quiet machine) to discourage running the full suite locally.
This change keeps every assertion but stops paying for real network
sleeps, SDK retry backoffs, oversized payloads, and per-test go
builds.
Profiling tool:
- Add dev-scripts/profile-tests.py to rank packages and tests by
wall time from `go test -json` output. Kept as a permanent project
tool so future drift is easy to spot.
pkg/cache/upstream (13.6s -> 2.0s):
- The four "timeout if server takes more than 3 seconds before first
byte" subtests now pass an explicit ResponseHeaderTimeout=50ms and
stall the server only 500ms, instead of waiting on the production
default 3s timeout.
- The "custom DialerTimeout" subtest previously used a slow-Accept
listener, which does NOT delay the dialer (the kernel auto-
completes the SYN handshake), so the original test was indirectly
hitting ResponseHeaderTimeout. Rewrite it to dial 192.0.2.1
(TEST-NET-1, RFC 5737) with DialerTimeout=50ms, which actually
trips the dialer's timer.
pkg/storage/s3 (12.2s -> 1.5s):
- minio-go retries RoundTripper errors with exponential backoff,
taking 3-5s per ErrorPath test (15+ tests).
- Replace those mocks with a new s3ErrorResponse() helper that
returns a non-retryable 403 AccessDenied. Where assertions check
for sentinel text ("put failed", "list objects failed", etc.) the
message is embedded in the response body so minio-go surfaces it
verbatim into err.Error() and existing assertions keep working.
pkg/cache (16.5s -> ~4s):
- DeadlockContextCancellationDuringDownload: 1MB / 1024-chunk /
10ms-per-chunk payload shrunk to 50KB / 50-chunk / 5ms-per-chunk.
Background-completion timeouts trimmed from 10s/15s to 3s/3s.
- Four 1s sleeps in last-accessed-at tests cut to 100ms; all
supported engines store timestamps with sub-second precision.
- TestIssue990 upstream sleep 1s -> 200ms, post-cancel wait 1.5s ->
500ms.
- TestCDCBackends first-pull chunking delay 2s -> 500ms.
pkg/lock/redis (7.8s -> 2.0s):
- TestNewLocker_ReturnType wrapped each NewLocker call in a 500ms
context so the degraded-mode Ping retries don't burn the go-redis
default DialTimeout (5s) per attempt.
cmd/generate-migrations (5.1s -> 3.0s):
- buildGenerateMigrations now uses sync.Once + TestMain so the
binary is built once per package run instead of per-test.
Also scaffolds the OpenSpec change (proposal, design, two specs,
tasks) that drove this work, plus the baseline / post-batch timing
captures used to verify progress.
All edits keep the race detector on; lint is clean; every
re-profiled package passed \`go test -race\`.
b3101c9 to
b7413a2
Compare
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
pkg/cache/cache_test.go (1)
3422-3434:⚠️ Potential issue | 🟠 Major | ⚡ Quick winReplace fixed post-cancel sleep with
require.Eventuallyto avoid flakiness.Line 3423 uses a hardcoded 500ms wait before asserting DB state. This can intermittently fail on slower
-raceCI runners even when behavior is correct.Suggested fix
- // 4. Wait for the background job to finish (upstream takes 200ms + DB write). - time.Sleep(500 * time.Millisecond) - - // 5. Check if the narinfo is in the database - var count int - - err = dbClient.DB().QueryRowContext(context.Background(), - rebind("SELECT COUNT(*) FROM narinfos WHERE hash = ?"), hash).Scan(&count) - require.NoError(t, err) - assert.Equal(t, 1, count, "NarInfo should be in database even if the original request was canceled") + // 4. Wait for the background job to finish (poll to avoid fixed-sleep flakes). + require.Eventually(t, func() bool { + var count int + qErr := dbClient.DB().QueryRowContext( + context.Background(), + rebind("SELECT COUNT(*) FROM narinfos WHERE hash = ?"), + hash, + ).Scan(&count) + return qErr == nil && count == 1 + }, 2*time.Second, 50*time.Millisecond, + "NarInfo should be in database even if the original request was canceled")🤖 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 `@pkg/cache/cache_test.go` around lines 3422 - 3434, Replace the fixed time.Sleep with a polling assertion using require.Eventually: instead of sleeping 500ms then querying, call require.Eventually(t, func() bool { query the DB via dbClient.DB().QueryRowContext(... rebind("SELECT COUNT(*) FROM narinfos WHERE hash = ?"), hash).Scan(&count) and return count == 1 }, timeout, pollInterval) so the test repeatedly queries until the narinfo exists (e.g., timeout 2s, poll 10-50ms); keep the final assert/assertion logic using count/hash or replace with require.True on the eventual result to avoid flakiness under -race.
🤖 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 `@cmd/generate-migrations/main_test.go`:
- Around line 110-117: The build invocation uses context.Background(), so make
it use a bounded context: create a ctx, cancel :=
context.WithTimeout(context.Background(), 30*time.Second) (choose an appropriate
timeout), defer cancel(), then call exec.CommandContext(ctx, "go", "build",
"-o", sharedBinary, ".") and keep using cmd.CombinedOutput(); after the call, if
ctx.Err() == context.DeadlineExceeded set errSharedBuild = ctx.Err() and
sharedBuildOut = string(out) (otherwise keep the existing err/out handling).
Update imports to include time and ensure exec.CommandContext, sharedBinary,
errSharedBuild, and sharedBuildOut are unchanged otherwise.
In `@pkg/cache/cdc_test.go`:
- Around line 1679-1684: The 500ms chunkingDelay makes the timing assertion (the
check that elapsed < chunkingDelay) flaky under the race detector; adjust the
test to make the timing window more robust by increasing chunkingDelay to a
larger value (e.g., 1s) or replace the fragile timing check with an explicit
completion signal/timeout approach so the assertion no longer depends on tight
timing; update references to the chunkingDelay constant and the assertion that
compares elapsed to chunkingDelay in the test in pkg/cache/cdc_test.go (the
injected slow chunker and the elapsed < chunkingDelay check) so CI with -race is
deterministic.
---
Outside diff comments:
In `@pkg/cache/cache_test.go`:
- Around line 3422-3434: Replace the fixed time.Sleep with a polling assertion
using require.Eventually: instead of sleeping 500ms then querying, call
require.Eventually(t, func() bool { query the DB via
dbClient.DB().QueryRowContext(... rebind("SELECT COUNT(*) FROM narinfos WHERE
hash = ?"), hash).Scan(&count) and return count == 1 }, timeout, pollInterval)
so the test repeatedly queries until the narinfo exists (e.g., timeout 2s, poll
10-50ms); keep the final assert/assertion logic using count/hash or replace with
require.True on the eventual result to avoid flakiness under -race.
🪄 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: bc996efe-71a6-49bf-aece-bf6449f82798
📒 Files selected for processing (7)
cmd/generate-migrations/main_test.godev-scripts/profile-tests.pypkg/cache/cache_test.gopkg/cache/cdc_test.gopkg/cache/upstream/cache_test.gopkg/lock/redis/return_type_test.gopkg/storage/s3/s3_test.go
MySQL TIMESTAMP has second-level precision (no fractional seconds). The 100ms sleep introduced in the test-speedup refactor was not long enough to guarantee that last_accessed_at lands in a different second than created_at, causing the NotEqual assertion to fail on fast runners. Increase the sleep to 1100ms for the two "should update last_accessed_at" subtests (GetNarInfo and GetNar) so the timestamps always differ under MySQL. The "should NOT update" subtests keep 100ms since their assertion uses WithinDuration(2s) and does not require crossing a second boundary. Also corrects the inaccurate comment claiming PG/MySQL keep microsecond precision — MySQL TIMESTAMP is second-granular by default. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
In Nix build sandboxes (especially aarch64-linux), connecting to 192.0.2.1 (TEST-NET-1) returns ENETUNREACH immediately rather than timing out, because the sandboxed kernel has no route to that subnet. Broaden the error assertion to accept errors containing "unreachable" alongside the existing "timeout" / context.DeadlineExceeded checks. The elapsed-time guard (< 2s) remains and continues to catch any regression where DialerTimeout is wired incorrectly and the client waits for the full ResponseHeaderTimeout (5s) instead. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #1241 +/- ##
=====================================
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. 🚀 New features to boost your workflow:
|
- parseSkip validates and normalises each dialect token, returning an error on unknown values (e.g. "myslq") instead of silently skipping nothing and running the dialect anyway. - --sql-only path now calls ensureAtlasSum after writing the stub so atlas.sum stays in sync when only empty stubs are generated. - Replace non-fatal assert.Len with require.Len in TestSQLOnlyEmitsThreeDialects so the test fails cleanly before indexing stamps[0..2] when fewer than 3 files are produced. - Wrap the one-time go build in a 60-second context instead of context.Background() to prevent an indefinite hang. Addresses PR #1187 (PRRT_kwDONV6tZs6EK6w5), PR #1185, PR #1241 (PRRT_kwDONV6tZs6EVhVP). Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
dev-scripts/test-migration-e2e.py (PR #1233): - PRRT_kwDONV6tZs6EU7OZ: raise in stop_ncps if port never closes (was silently ignored). - PRRT_kwDONV6tZs6EU7Ob: raise on unparseable idempotency output instead of downgrading to a WARN log. - PRRT_kwDONV6tZs6EVEfJ: wait_ready() takes the process handle and exits early when ncps dies before becoming ready, avoiding the full 120s timeout. dev-scripts/run.py (PR #1232): - PRRT_kwDONV6tZs6EU663: guard dbmate create with shutil.which(), matching the existing pattern for perform_clean(); raises FileNotFoundError with a clear message instead of a confusing FileNotFoundError from subprocess. pkg/cache/cdc_test.go (PR #1241): - PRRT_kwDONV6tZs6EVhVS: increase chunkingDelay 500ms→1s to reduce flakiness under -race on loaded CI. pkg/cache/cache_distributed_test.go (PR #1244): - PRRT_kwDONV6tZs6EVZVc: replace Lock+200ms timeout with TryLock (non-blocking) for lock-contention check; deterministic and immune to slow Redis round-trips. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…1251) ## Summary Consolidation branch addressing unresolved reviewer threads left open across merged PRs #1179–#1246. Each fix has its own atomic commit referencing the source PR and thread ID; all threads are resolved on GitHub after each change. ### Bug fixes - **cache:** touch `nar_file` by fetched row ID, not by narURL fields — `getNarFileFromDB` can return a `compression=none` fallback whose key differs from `narURL`, causing stale `last_accessed_at` and LRU regressions (#1206) - **cache:** fail fast on `nil` eager-loaded chunk edges in `streamCompleteChunks` and `streamProgressiveChunks` instead of silently `continue`-ing, which caused count mismatches or infinite re-streaming (#1207) - **cache:** include `narURLsToRemove` in the LRU early-return guard so orphaned `NarFile` blobs are passed to `parallelDeleteFromStores` instead of being silently leaked in storage (#1215) - **cache:** log a warning when LRU candidate fetch hits the `maxFetchRows` cap so operators know eviction scanned only a partial window (#1206) - **cache/relink:** lower `relinkBatchSize` from 500 → 499 to stay under SQLite's 999-placeholder limit (500 rows × 2 binds = 1000 > 999) (#1208) - **database:** close `*sql.DB` in `Open()` when `NewClient` fails (#1208) - **migrate/adopt:** use `ErrUnknownState` (not `ErrUnknownDialect`) for unrecognised `State` values — fixes false-positive `errors.Is` checks (#1188) - **generate-migrations:** `parseSkip` validates dialect names, returning an error on unknown values like `"myslq"` instead of silently skipping them (#1187) - **generate-migrations:** `--sql-only` path now calls `ensureAtlasSum` after writing the stub so `atlas.sum` stays in sync (#1187) - **generate-migrations:** `runDialect` now returns the generated file path and prints it to stdout; `main()` warns when a second boundary falls between dialect runs so callers know to re-run for a consistent timestamp set (#1215) - **generate-migrations:** add `"empty"` to `validateName` reject list (#1185) - **nix/ent-lint-check:** add `set -o pipefail` so `ent-lint | tee` propagates a non-zero exit through the pipeline (#1221) - **e2e:** fix docstring path (`var/ncps/e2e-results/` → `.e2e-results/`); `mc mb` and `redis-cli flushall` now use `check=True` so reset failures abort the test immediately (#1233) - **e2e:** `stop_ncps` now verifies the port closes within timeout; `wait_ready` exits early if the child process dies before becoming ready (#1233) - **run.py:** guard `dbmate` usage with a `shutil.which` check so a missing binary fails fast with a clear message instead of an obscure error (#1234) - **CI:** pin all external GitHub Action refs to immutable commit SHAs to prevent supply-chain mutation (#1223) - **CI:** remove `release-*` from pull_request/push triggers; add `go.mod` and `go.sum` to the ent paths-filter (#1235) - **docs:** replace distroless-incompatible `wget` healthcheck in Docker Compose example with `garage status` (#1223) ### Test fixes - Replace non-fatal `assert.Len` → `require.Len` before indexing `stamps[0..2]` in `generate-migrations` tests (#1185) - Add 60 s timeout to the one-time `go build` in the test setup (#1241) - Fix `cache_prefetch_test.go` to look up `nar_file` by `(hash, compression, query)` instead of hard-coded `id=1` (#1218) - Apply `NarSize` fallback when `FileSize == 0` in `testhelper/sqlite.go` to avoid impossible `file_size=0` fixture rows for `compression=none` narinfos (#1218) - Increase `chunkingDelay` from 500 ms → 1 s in `cdc_test.go` to reduce flakiness on slow CI machines (#1217) - Replace `Lock`-with-timeout with `TryLock` in `cache_distributed_test.go` to avoid spurious failures when the lock-hold window is tight (#1217) ### Docs / skills - Quote PostgreSQL DSNs in shell-command examples to prevent `?`-glob expansion by shells (#1234) - `migrate-new/SKILL.md`: ent-lint checks A1, A2, A4 — not all five invariants as previously stated (#1225) - `migrate-down/SKILL.md`: clarify that `DROP COLUMN` is sensitive/forbidden DDL per the migration spec and is only permissible as the terminal expand-contract step; add the missing "deploy code that always writes non-null" step to the NOT NULL recipe (#1225) - `openspec/changes/archive/2026-05-23-less-tests/`: fix stale paths, add `bash` fence tag, replace "branch coverage" with "statement/block coverage" (#1245) - `openspec/specs/test-suite-efficiency/spec.md`: same coverage terminology fix (#1245) - `openspec/changes/archive/2026-05-21-migrate-to-ent-and-atlas/design.md`: add language tag to decision-tree fence block; fix grammar (#1186) - `openspec/changes/archive/2026-05-21-migrate-to-ent-and-atlas/tasks.md`: update §10.1/§11.1 notes to reflect that `*database.Client` threading was completed in §11, not deferred (#1191, #1192) ## Test plan - [x] `nix flake check` (includes all unit + integration tests, lint, ent-lint, atlas-sum, helm-unittest, schema-equivalence) - [x] `go test -race ./...` locally with `eval "$(enable-integration-tests)"` - [x] Verify all referenced GitHub threads are marked resolved 🤖 Generated with [Claude Code](https://claude.ai/claude-code) --------- Co-authored-by: Claude Sonnet 4.6 <[email protected]>
nix flake checkandgo test -race ./...were slow enough (~88son a quiet machine) to discourage running the full suite locally.
This change keeps every assertion but stops paying for real network
sleeps, SDK retry backoffs, oversized payloads, and per-test go
builds.
Profiling tool:
wall time from
go test -jsonoutput. Kept as a permanent projecttool so future drift is easy to spot.
pkg/cache/upstream (13.6s -> 2.0s):
byte" subtests now pass an explicit ResponseHeaderTimeout=50ms and
stall the server only 500ms, instead of waiting on the production
default 3s timeout.
listener, which does NOT delay the dialer (the kernel auto-
completes the SYN handshake), so the original test was indirectly
hitting ResponseHeaderTimeout. Rewrite it to dial 192.0.2.1
(TEST-NET-1, RFC 5737) with DialerTimeout=50ms, which actually
trips the dialer's timer.
pkg/storage/s3 (12.2s -> 1.5s):
taking 3-5s per ErrorPath test (15+ tests).
returns a non-retryable 403 AccessDenied. Where assertions check
for sentinel text ("put failed", "list objects failed", etc.) the
message is embedded in the response body so minio-go surfaces it
verbatim into err.Error() and existing assertions keep working.
pkg/cache (16.5s -> ~4s):
10ms-per-chunk payload shrunk to 50KB / 50-chunk / 5ms-per-chunk.
Background-completion timeouts trimmed from 10s/15s to 3s/3s.
supported engines store timestamps with sub-second precision.
500ms.
pkg/lock/redis (7.8s -> 2.0s):
context so the degraded-mode Ping retries don't burn the go-redis
default DialTimeout (5s) per attempt.
cmd/generate-migrations (5.1s -> 3.0s):
binary is built once per package run instead of per-test.
Also scaffolds the OpenSpec change (proposal, design, two specs,
tasks) that drove this work, plus the baseline / post-batch timing
captures used to verify progress.
All edits keep the race detector on; lint is clean; every
re-profiled package passed `go test -race`.