Skip to content

Avoid clobbering manifests in test helper#159

Merged
leynos merged 4 commits intomainfrom
codex/fix-unsafe-file-handling-in-tests
Sep 15, 2025
Merged

Avoid clobbering manifests in test helper#159
leynos merged 4 commits intomainfrom
codex/fix-unsafe-file-handling-in-tests

Conversation

@leynos
Copy link
Copy Markdown
Owner

@leynos leynos commented Sep 14, 2025

Summary

  • avoid overwriting manifests during tests by using persist_noclobber

Testing

  • make fmt
  • make check-fmt
  • make lint
  • make test

closes #58


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

Summary by Sourcery

Bug Fixes:

  • Use persist_noclobber in ensure_manifest_exists to avoid clobbering concurrently created manifest files

@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai Bot commented Sep 14, 2025

Reviewer's guide (collapsed on small PRs)

Reviewer's Guide

This PR enhances the test helper to prevent overwriting existing manifest files by switching from persist to persist_noclobber, adding a comment for clarity.

File-Level Changes

Change Details Files
Use non-clobbering file persistence in manifest helper
  • Replaced file.persist with file.persist_noclobber
  • Added comment explaining the purpose of persist_noclobber
test_support/src/lib.rs

Assessment against linked issues

Issue Objective Addressed Explanation
#58 Replace NamedTempFile::persist() with a safer alternative in process tests to avoid overwriting existing files.

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

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Sep 14, 2025

Note

Reviews paused

Use the following commands to manage reviews:

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

Summary by CodeRabbit

  • Bug Fixes
    • Prevents accidental overwriting of an existing manifest during concurrent operations, enhancing data integrity and reliability in multi-process scenarios.
    • Adds a safeguard to ensure an existing manifest is preserved without altering the overall flow or outcomes.
    • No changes to public interfaces or configuration are required; behaviour remains consistent aside from improved robustness.

Walkthrough

Switch the manifest write path in test_support/src/lib.rs to use persist_noclobber instead of persist within ensure_manifest_exists. This change adds a clarifying comment. No signatures or overall flow otherwise changed.

Changes

Cohort / File(s) Summary of Changes
Manifest write safety
test_support/src/lib.rs
Replace persist with persist_noclobber in ensure_manifest_exists; add comment explaining non-clobber behaviour. No other functional or signature changes.

Sequence Diagram(s)

sequenceDiagram
    autonumber
    actor T as Test/Caller
    participant E as ensure_manifest_exists
    participant FS as Filesystem
    participant TF as TempFile

    T->>E: ensure_manifest_exists(manifest_path)
    E->>FS: Check if manifest_path exists
    alt Not exists
        E->>FS: Create parent dir(s)
        E->>TF: Create temp file with manifest content
        E->>FS: persist_noclobber(temp -> manifest_path)
        FS-->>E: OK or AlreadyExists
        alt AlreadyExists
            E-->>T: Return manifest_path (existing)
        else OK
            E-->>T: Return manifest_path (created)
        end
    else Exists
        E-->>T: Return manifest_path
    end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related issues

Poem

A file stands guard where tests convene,
No clobber storms disturb the scene.
A temp to path, then pause—be sure,
If something’s there, we won’t obscure.
With gentle locks and careful lore,
The manifest endures once more.

Pre-merge checks

✅ Passed checks (5 passed)
Check name Status Explanation
Title Check ✅ Passed Confirm that the title succinctly and accurately summarises the primary change: preventing manifest clobbering in the test helper by switching to persist_noclobber, which matches the modification to test_support/src/lib.rs. The title is concise, specific, and directly related to the changeset.
Linked Issues Check ✅ Passed Verify that the change replaces persist with persist_noclobber in ensure_manifest_exists, addressing the core coding requirement from issue [#58] to avoid unsafe NamedTempFile::persist usage; the modification in test_support/src/lib.rs implements the suggested persist_noclobber solution.
Out of Scope Changes Check ✅ Passed Confirm that the changes are narrowly scoped to ensure_manifest_exists in test_support/src/lib.rs and the PR does not introduce unrelated file or API changes.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Description Check ✅ Passed Confirm that the PR description aligns with the changeset: it states switching to persist_noclobber to avoid overwriting manifests in tests, lists the testing commands, and references closing issue #58. Cross-check the raw_summary which shows ensure_manifest_exists now uses persist_noclobber in test_support/src/lib.rs, so the description is directly related. Approve the description as sufficient for this lenient check.

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

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 there - I've reviewed your changes and they look great!


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.

codescene-delta-analysis[bot]

This comment was marked as outdated.

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: 1

📜 Review details

Configuration used: CodeRabbit UI

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7348128 and b4c3e95.

📒 Files selected for processing (1)
  • test_support/src/lib.rs (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.rs

📄 CodeRabbit inference engine (AGENTS.md)

**/*.rs: Use en-GB-oxendict spelling and grammar in code comments (exceptions allowed for external API names)
Function documentation must include clear examples; test documentation should omit redundant examples
Keep file size manageable: no Rust source file longer than 400 lines; split large switches/dispatch tables and move big test data to external files
Disallow Clippy warnings; fix warnings in code rather than silencing them
Extract helper functions for long functions; maintain separation of concerns and CQRS
Group many related parameters into meaningful structs
If returning a large error type, consider using Arc to reduce data copied/returned
Each Rust module must begin with a module-level //! comment stating purpose and utility
Document public APIs with Rustdoc (///) so cargo doc can generate documentation
Prefer immutable data; avoid unnecessary mut bindings
Handle errors with Result instead of panicking where feasible
Avoid unsafe code unless absolutely necessary and document any usage clearly
Place function attributes after doc comments
Do not use return in single-line functions
Use predicate functions when conditional criteria have more than two branches
Do not silence lints except as a last resort; suppressions must be tightly scoped and include a clear reason
Prefer expect over allow for lint management
Use conditional compilation (#[cfg]/#[cfg_attr]) for functions unused under specific feature sets
Prefer .expect() over .unwrap()
Use concat!() for long string literals instead of escaping newlines with backslashes
Prefer single-line function bodies when appropriate (e.g., pub fn new(id: u64) -> Self { Self(id) })
Prefer semantic error enums (derive std::error::Error via thiserror) for inspectable conditions
Use an opaque eyre::Report only at the application boundary for human-readable logs; do not expose in public APIs
Never export eyre::Report from libraries; convert to domain error enums at API boundaries and to eyre only in main/top-level async tas...

Files:

  • test_support/src/lib.rs

⚙️ CodeRabbit configuration file

**/*.rs: * Seek to keep the cyclomatic complexity of functions no more than 12.

  • Adhere to single responsibility and CQRS

  • Place function attributes after doc comments.

  • Do not use return in single-line functions.

  • Move conditionals with >2 branches into a predicate function.

  • Avoid unsafe unless absolutely necessary.

  • Every module must begin with a //! doc comment that explains the module's purpose and utility.

  • Comments and docs must follow en-GB-oxendict (-ize / -our) spelling and grammar

  • Lints must not be silenced except as a last resort.

    • #[allow] is forbidden.
    • Only narrowly scoped #[expect(lint, reason = "...")] is allowed.
    • No lint groups, no blanket or file-wide suppression.
    • Include FIXME: with link if a fix is expected.
  • Where code is only used by specific features, it must be conditionally compiled or a conditional expectation for unused_code applied.

  • Use rstest fixtures for shared setup and to avoid repetition between tests.

  • Replace duplicated tests with #[rstest(...)] parameterised cases.

  • Prefer mockall for mocks/stubs.

  • Prefer .expect() over .unwrap()

  • Ensure that any API or behavioural changes are reflected in the documentation in docs/

  • Ensure that any completed roadmap steps are recorded in the appropriate roadmap in docs/

  • Files must not exceed 400 lines in length

    • Large modules must be decomposed
    • Long match statements or dispatch tables should be decomposed by domain and collocated with targets
    • Large blocks of inline data (e.g., test fixtures, constants or templates) must be moved to external files and inlined at compile-time or loaded at run-time.
  • Environment access (env::set_var and env::remove_var) are always unsafe in Rust 2024 and MUST be marked as such

    • For testing of functionality depending upon environment variables, dependency injection and the mockable crate are the preferred option.
    • If mockable cannot be used, env mutations in tests ...

Files:

  • test_support/src/lib.rs
🔍 Remote MCP Ref

Additional context for reviewing PR #159 (Avoid clobbering manifests)

  • Change implemented: tests now use NamedTempFile::persist_noclobber when writing manifests to avoid overwriting an existing file created concurrently.
  • Behavior of persist_noclobber: it fails if the destination path already exists (so it prevents accidental clobbering). Verify the PR checks/handles the returned error appropriately in tests.
  • Alternatives noted in the linked issue (#58): drop the temp file and use std::fs::write, or use persist_noclobber — PR chooses persist_noclobber (matches the issue recommendation).
  • Reviewer checklist (concise, actionable):
    • Ensure persist_noclobber errors are handled/propagated (no silent unwrap that could mask failures).
    • Confirm tests include or could simulate the “target exists” case to assert the new behavior.
    • Check for any OS-specific rename/atomicity implications (persist_noclobber behavior can differ by platform); consider using explicit write+fsync if atomic semantics are required.
  • Note: some remote fetch attempts were partially blocked during research (limited retrievals). If you want full upstream diffs or exact docs pages fetched, I can re-run targeted fetches.

Sources:

  • tempfile docs (NamedTempFile::persist_noclobber).
  • Issue/PR search for netsuke and issue #58 (proposal and alternatives).
⏰ Context from checks skipped due to timeout of 120000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Sourcery review
  • GitHub Check: build-test (stable)

Comment thread test_support/src/lib.rs Outdated
@leynos
Copy link
Copy Markdown
Owner Author

leynos commented Sep 14, 2025

@coderabbitai pause

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Sep 14, 2025

✅ Actions performed

Reviews paused.

codescene-delta-analysis[bot]

This comment was marked as outdated.

Break ensure_manifest_exists into smaller helpers to reduce nested control flow while preserving behaviour.
codescene-delta-analysis[bot]

This comment was marked as outdated.

Repository owner deleted a comment from coderabbitai Bot Sep 15, 2025
@leynos leynos merged commit f6439b0 into main Sep 15, 2025
7 checks passed
@leynos leynos deleted the codex/fix-unsafe-file-handling-in-tests branch September 15, 2025 18:21
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.

Replace NamedTempFile::persist() with safer alternatives in process tests

1 participant