Skip to content

fix(ncps): close dbClient on shutdown; use FORCE drop in tests - #1243

Merged
kalbasit merged 1 commit into
mainfrom
fix-ncps-close-dbclient-on
May 23, 2026
Merged

kalbasit merged 1 commit into
mainfrom
fix-ncps-close-dbclient-on

Conversation

@kalbasit

Copy link
Copy Markdown
Owner

Found while shrinking the integration-test wall time. Every ncps
subcommand (serve, fsck, migrate-narinfo, migrate-nar-to-chunks)
opens a *database.Client via createDatabaseClient but never registers
its Close in the cli After-hook. In production the process just
exits so it's invisible; in tests the connection pool lingers, and
every integration-test cleanup paid a flat ~5s waiting for
DROP DATABASE to drain the leaked connections.

Quantified impact (full integration run, all deps live):

  • pkg/ncps total: 23.07s -> 6.28s
  • 18 TestFsckBackends/PostgreSQL/CDC/* tests all dropped off the
    "elapsed > 500ms" list (was uniformly ~5s each).
  • Cumulative go test -race ./... with integration backends:
    80.09s -> 64.40s (~20% reduction in this commit alone).

Changes:

  • pkg/ncps/{fsck,serve,migrate_narinfo,migrate_nar_to_chunks}.go:
    register dbClient.Close as a shutdown function right after
    createDatabaseClient. Captured by closure so the body of the
    Action continues to use the same client; After-hook calls Close
    in parallel with otelShutdown via wg.Go.
  • nix/process-compose/postgres-dblink-create-drop-functions.sql:
    drop_test_db now issues DROP DATABASE ... WITH (FORCE) (PG 13+)
    as a belt-and-braces measure in case any future test still leaks
    a connection past Close. The Go-side fix above is the actual
    reason the per-test wait disappeared.

Also captures the integration timings before and after this commit
under openspec/changes/less-tests/integration-*-timings.txt.

Verified: go test -race on every touched package passes;
`golangci-lint run` is clean. The applied SQL function update was
also run against the live PG instance by hand so subsequent local
runs immediately benefit.

@dosubot dosubot Bot added the size:S This PR changes 10-29 lines, ignoring generated files. label May 23, 2026
@coderabbitai

coderabbitai Bot commented May 23, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: b6f99db9-0e60-480c-b9c2-2ae95e4c43a0

📥 Commits

Reviewing files that changed from the base of the PR and between 2362605 and a13d438.

📒 Files selected for processing (5)
  • nix/process-compose/postgres-dblink-create-drop-functions.sql
  • pkg/ncps/fsck.go
  • pkg/ncps/migrate_nar_to_chunks.go
  • pkg/ncps/migrate_narinfo.go
  • pkg/ncps/serve.go

📝 Walkthrough

Summary by CodeRabbit

Release Notes

  • Bug Fixes

    • Improved test database cleanup to properly handle idle connections during per-test teardown.
  • Chores

    • Added database connection cleanup across multiple service components to ensure resources are properly released when services shutdown.

Walkthrough

This PR improves database resource cleanup in two ways: the PostgreSQL test database drop function now forces disconnection using WITH (FORCE) to avoid waiting for idle connections, and four command entrypoints register shutdown hooks to properly close their database clients on exit.

Changes

Database client cleanup and test database maintenance

Layer / File(s) Summary
Test database cleanup with FORCE
nix/process-compose/postgres-dblink-create-drop-functions.sql
drop_test_db appends WITH (FORCE) to the remote DROP DATABASE command with comments explaining PostgreSQL 13+ behavior and the avoidance of connection drain delays during per-test cleanup.
Command-level database client shutdown hooks
pkg/ncps/fsck.go, pkg/ncps/migrate_nar_to_chunks.go, pkg/ncps/migrate_narinfo.go, pkg/ncps/serve.go
Four commands register registerShutdown callbacks immediately after database client creation to ensure dbClient.Close() is called during graceful shutdown, releasing the connection pool for all entrypoints.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

  • kalbasit/ncps#1210: Refactored ncps to thread and use the shared *database.Client in command paths (serve, fsck, and NAR migrations), which this PR now properly cleans up via shutdown hooks.
  • kalbasit/ncps#1216: Also modifies migrateNarInfoCommand in migrate_narinfo.go, refactoring how it calls cache.MigrateNarInfo.

Suggested labels

bug

Poem

🐰 Database clients now rest with grace,
Each shutdown hook finds its place.
Test drops with force end the wait,
No more connections seal their fate!
Resources freed, the cleanup's done. ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% 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
Title check ✅ Passed The title accurately summarizes the two main changes: closing dbClient on shutdown and using FORCE in database drops for tests.
Description check ✅ Passed The description provides comprehensive context about the resource leak issue, quantified performance improvements, detailed changes made, and verification steps.
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.

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

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 introduces explicit database client shutdown registration across several commands (fsck, migrate_nar_to_chunks, migrate_narinfo, and serve) to mitigate connection leaks. Additionally, the PostgreSQL cleanup script is updated to use 'DROP DATABASE ... WITH (FORCE)' to prevent blocking during test teardown. Feedback suggests evaluating whether these lifecycle management changes, which primarily benefit the testing environment, should be scoped differently or extended to other components like the cache and HTTP server.

Comment thread pkg/ncps/serve.go Resolved
@kalbasit
kalbasit force-pushed the test-shrink-fsck-security-large branch from 6df6ab4 to abf4c46 Compare May 23, 2026 21:26
@kalbasit
kalbasit force-pushed the fix-ncps-close-dbclient-on branch from 411ed9e to 743ec78 Compare May 23, 2026 21:26
@kalbasit
kalbasit force-pushed the test-shrink-fsck-security-large branch from abf4c46 to f807885 Compare May 23, 2026 21:51
@kalbasit
kalbasit force-pushed the fix-ncps-close-dbclient-on branch from 743ec78 to 0d81c5c Compare May 23, 2026 21:51
@kalbasit
kalbasit force-pushed the test-shrink-fsck-security-large branch from f807885 to ee204a9 Compare May 23, 2026 22:03
@kalbasit
kalbasit force-pushed the fix-ncps-close-dbclient-on branch from 0d81c5c to 6aacbc7 Compare May 23, 2026 22:03
@kalbasit
kalbasit force-pushed the test-shrink-fsck-security-large branch from ee204a9 to f3627df Compare May 23, 2026 22:17
@kalbasit
kalbasit force-pushed the fix-ncps-close-dbclient-on branch 3 times, most recently from d0524aa to 4a6c1a2 Compare May 23, 2026 22:45
Base automatically changed from test-shrink-fsck-security-large to main May 23, 2026 22:58
Found while shrinking the integration-test wall time. Every ncps
subcommand (serve, fsck, migrate-narinfo, migrate-nar-to-chunks)
opens a *database.Client via createDatabaseClient but never registers
its Close in the cli After-hook. In production the process just
exits so it's invisible; in tests the connection pool lingers, and
every integration-test cleanup paid a flat ~5s waiting for
DROP DATABASE to drain the leaked connections.

Quantified impact (full integration run, all deps live):
- pkg/ncps total: 23.07s -> 6.28s
- 18 TestFsckBackends/PostgreSQL/CDC/* tests all dropped off the
  "elapsed > 500ms" list (was uniformly ~5s each).
- Cumulative `go test -race ./...` with integration backends:
  80.09s -> 64.40s (~20% reduction in this commit alone).

Changes:
- pkg/ncps/{fsck,serve,migrate_narinfo,migrate_nar_to_chunks}.go:
  register `dbClient.Close` as a shutdown function right after
  createDatabaseClient. Captured by closure so the body of the
  Action continues to use the same client; After-hook calls Close
  in parallel with otelShutdown via wg.Go.
- nix/process-compose/postgres-dblink-create-drop-functions.sql:
  drop_test_db now issues `DROP DATABASE ... WITH (FORCE)` (PG 13+)
  as a belt-and-braces measure in case any future test still leaks
  a connection past Close. The Go-side fix above is the actual
  reason the per-test wait disappeared.

Also captures the integration timings before and after this commit
under openspec/changes/less-tests/integration-*-timings.txt.

Verified: `go test -race` on every touched package passes;
\`golangci-lint run\` is clean. The applied SQL function update was
also run against the live PG instance by hand so subsequent local
runs immediately benefit.
@kalbasit
kalbasit force-pushed the fix-ncps-close-dbclient-on branch from 4a6c1a2 to a13d438 Compare May 23, 2026 22:58
@kalbasit
kalbasit enabled auto-merge (squash) May 23, 2026 22:59
@codecov

codecov Bot commented May 23, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 5.50%. Comparing base (2362605) to head (a13d438).

Additional details and impacted files
@@          Coverage Diff          @@
##            main   #1243   +/-   ##
=====================================
  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
kalbasit merged commit d73a8a2 into main May 23, 2026
21 checks passed
@kalbasit
kalbasit deleted the fix-ncps-close-dbclient-on branch May 23, 2026 23:11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

go Pull requests that update go code merge-stack size:S This PR changes 10-29 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant