Skip to content

Fix TempDir leak in embedded Postgres tests#155

Merged
leynos merged 4 commits intomainfrom
codex/fix-memory-leak-in-test-util/src/lib.rs
Jun 17, 2025
Merged

Fix TempDir leak in embedded Postgres tests#155
leynos merged 4 commits intomainfrom
codex/fix-memory-leak-in-test-util/src/lib.rs

Conversation

@leynos
Copy link
Copy Markdown
Owner

@leynos leynos commented Jun 17, 2025

Summary

  • preserve the temporary directory handle used for embedded Postgres
  • store the TempDir in PostgresTestDb and TestServer

Testing

  • cargo fmt --all
  • cargo clippy -- -D warnings
  • RUSTFLAGS="-D warnings" cargo test

https://chatgpt.com/codex/tasks/task_e_6851b94c35448322b8ee0881a04629f1

Summary by Sourcery

Retain the temporary directory handle for embedded Postgres instances to prevent premature cleanup of the data directory in tests.

Bug Fixes:

  • Prevent embedded Postgres tests from deleting their temporary data directory prematurely by retaining the TempDir handle.

Enhancements:

  • Extend start_embedded_postgres to return the TempDir and update PostgresTestDb and TestServer to store it.

Summary by CodeRabbit

  • Chores
    • Improved resource management for temporary directories used during embedded PostgreSQL server tests, ensuring proper cleanup and lifecycle handling. No changes to user-facing features or test logic.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jun 17, 2025

Warning

Rate limit exceeded

@leynos has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 16 minutes and 28 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 1cbc9ad and e6bd39a.

📒 Files selected for processing (1)
  • test-util/src/lib.rs (10 hunks)

Walkthrough

This change updates the embedded PostgreSQL test utility to return and retain ownership of the temporary directory used for the database instance. The TempDir is now propagated and stored within relevant structs to ensure proper resource management and automatic cleanup, replacing previous manual memory management.

Changes

File(s) Change Summary
test-util/src/lib.rs Modified start_embedded_postgres to return EmbeddedPg struct containing TempDir; updated PostgresTestDb and TestServer structs and methods to store and propagate TempDir, ensuring correct temporary directory lifetime management.

Sequence Diagram(s)

sequenceDiagram
    participant Test as Test Code
    participant Util as test-util::start_embedded_postgres
    participant PG as Embedded PostgreSQL
    participant Temp as TempDir
    participant Server as TestServer

    Test->>Util: Call start_embedded_postgres(setup)
    Util->>Temp: Create TempDir
    Util->>PG: Start embedded PostgreSQL with TempDir path
    Util-->>Test: Return EmbeddedPg (db_url, PG, TempDir)
    Test->>Server: Pass db_url, PG, TempDir to launch
    Server->>Server: Store TempDir for resource management
Loading

Possibly related issues

Possibly related PRs

Poem

A burrow for Postgres, so snug and so neat,
No more mem::forget—what a tidy retreat!
TempDir is cherished, its lifetime ensured,
Resource leaks banished, our tests reassured.
In the warren of code, where the temp files reside,
The rabbits now hop with a cleaner, safe stride! 🐇

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate Unit Tests
  • Create PR with Unit Tests
  • Post Copyable Unit Tests in Comment
  • Commit Unit Tests in branch codex/fix-memory-leak-in-test-util/src/lib.rs

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai auto-generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai Bot commented Jun 17, 2025

Reviewer's Guide

Preserve TempDir handle for embedded Postgres in test utilities to prevent directory leaks by returning the handle from start_embedded_postgres and storing it in PostgresTestDb and TestServer.

File-Level Changes

Change Details Files
Propagate TempDir handle from embedded Postgres setup
  • Updated start_embedded_postgres signature to return TempDir
  • Replaced tempfile::tempdir().keep() and mem::forget with direct TempDir usage
  • Expanded Ok tuple and match arms to include the TempDir
test-util/src/lib.rs
Persist TempDir in PostgresTestDb
  • Added _temp field as Option to struct
  • Updated constructor to assign Some(tmp) or None for embedded vs external mode
test-util/src/lib.rs
Integrate TempDir persistence into TestServer
  • Adjusted tuple destructuring to include temp handle in setup logic
  • Passed temp handle into Self::launch call for embedded Postgres
test-util/src/lib.rs

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link
Copy Markdown

@codescene-delta-analysis codescene-delta-analysis Bot left a comment

Choose a reason for hiding this comment

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

Gates Passed
6 Quality Gates Passed

See analysis details in CodeScene

Quality Gate Profile: Pay Down Tech Debt
Want more control? Customize Code Health rules or catch issues early with our IDE extension and CLI tool.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🔭 Outside diff range comments (1)
test-util/src/lib.rs (1)

77-84: Drop-order bug – _temp is dropped before pg

TempDir is declared before pg, so it is dropped first when TestServer is destroyed (Rust drops fields in declaration order).
If PostgreSQL’s Drop implementation (executed afterwards) still references the data directory, the directory will already be gone, risking IO errors or silent inconsistencies.

Move _temp after pg to guarantee the directory outlives the database instance:

 pub struct TestServer {
     child: Child,
     port: u16,
     db_url: String,
-    _temp: Option<TempDir>,
     #[cfg(feature = "postgres")]
     pg: Option<PostgreSQL>,
+    _temp: Option<TempDir>,
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 35eaa3f and 13dac43.

📒 Files selected for processing (1)
  • test-util/src/lib.rs (5 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Analyze (actions)
  • GitHub Check: build-test (sqlite)
  • GitHub Check: build-test (postgres)
  • GitHub Check: coverage
🔇 Additional comments (3)
test-util/src/lib.rs (3)

133-141: Double runtime creation guard is solid – LGTM

The try_current/new fallback cleanly handles both async and sync contexts and now propagates TempDir correctly.
Nice work.


245-246: Correct placement in PostgresTestDb

Keeping _temp after pg ensures the directory lives longer than the Postgres process – good attention to detail.


446-456: Happy path looks correct

Call-site propagation of (db_url, pg, temp) matches the new launch signature; compile-time features gate the alternatives cleanly.

Comment thread test-util/src/lib.rs Outdated
Comment thread test-util/src/lib.rs Outdated
Copy link
Copy Markdown
Contributor

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

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

Hey @leynos - I've reviewed your changes - here's some feedback:

  • Rename the private _temp fields in PostgresTestDb and TestServer to _temp_dir so it’s immediately clear they hold a TempDir handle.
  • Consider replacing the (String, PostgreSQL, TempDir) tuple return from start_embedded_postgres with a small struct to improve readability and avoid positional confusion.
  • Add a brief inline comment next to the TempDir fields explaining that they’re kept alive to prevent automatic cleanup during test execution.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- Rename the private `_temp` fields in `PostgresTestDb` and `TestServer` to `_temp_dir` so it’s immediately clear they hold a `TempDir` handle.
- Consider replacing the `(String, PostgreSQL, TempDir)` tuple return from `start_embedded_postgres` with a small struct to improve readability and avoid positional confusion.
- Add a brief inline comment next to the `TempDir` fields explaining that they’re kept alive to prevent automatic cleanup during test execution.

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

Copy link
Copy Markdown

@codescene-delta-analysis codescene-delta-analysis Bot left a comment

Choose a reason for hiding this comment

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

Gates Passed
6 Quality Gates Passed

See analysis details in CodeScene

Quality Gate Profile: Pay Down Tech Debt
Want more control? Customize Code Health rules or catch issues early with our IDE extension and CLI tool.

@leynos
Copy link
Copy Markdown
Owner Author

leynos commented Jun 17, 2025

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jun 17, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@leynos
Copy link
Copy Markdown
Owner Author

leynos commented Jun 17, 2025

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jun 17, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link
Copy Markdown

@codescene-delta-analysis codescene-delta-analysis Bot left a comment

Choose a reason for hiding this comment

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

Gates Passed
6 Quality Gates Passed

See analysis details in CodeScene

Quality Gate Profile: Pay Down Tech Debt
Want more control? Customize Code Health rules or catch issues early with our IDE extension and CLI tool.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 4

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 13dac43 and 1cbc9ad.

📒 Files selected for processing (1)
  • test-util/src/lib.rs (7 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: coverage
  • GitHub Check: build-test (postgres)
🔇 Additional comments (1)
test-util/src/lib.rs (1)

109-117: 👍 Switched to tempfile::Builder with prefix – clearer diagnostics

The change implements the earlier nitpick; log directories will now be
prefixed with mxd-pg, which is useful when inspecting /tmp.

Comment thread test-util/src/lib.rs Outdated
Comment thread test-util/src/lib.rs Outdated
Comment thread test-util/src/lib.rs Outdated
Comment thread test-util/src/lib.rs
Copy link
Copy Markdown

@codescene-delta-analysis codescene-delta-analysis Bot left a comment

Choose a reason for hiding this comment

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

Gates Passed
6 Quality Gates Passed

See analysis details in CodeScene

Quality Gate Profile: Pay Down Tech Debt
Want more control? Customize Code Health rules or catch issues early with our IDE extension and CLI tool.

@leynos
Copy link
Copy Markdown
Owner Author

leynos commented Jun 17, 2025

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jun 17, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@leynos
Copy link
Copy Markdown
Owner Author

leynos commented Jun 17, 2025

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jun 17, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@leynos leynos merged commit b1e4599 into main Jun 17, 2025
5 of 7 checks passed
@leynos leynos deleted the codex/fix-memory-leak-in-test-util/src/lib.rs branch June 17, 2025 23:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant