Skip to content

Replace unsafe env mutations with EnvVarGuard in retry tests#124

Merged
leynos merged 1 commit intomainfrom
issue-75-unsafe-environment-variable-mutation
Dec 24, 2025
Merged

Replace unsafe env mutations with EnvVarGuard in retry tests#124
leynos merged 1 commit intomainfrom
issue-75-unsafe-environment-variable-mutation

Conversation

@leynos
Copy link
Copy Markdown
Owner

@leynos leynos commented Dec 24, 2025

The daemon tests in retry_helper.rs contained unsafe environment variable mutations that could cause race conditions when tests run in parallel. This change:

  • Adds EnvVarGuard::remove() method to test-support crate for temporarily removing environment variables with RAII-based restoration
  • Replaces all unsafe env::set_var/remove_var calls with EnvVarGuard guards
  • Adds #[serial_test::serial] attribute to tests that mutate environment to prevent interference between tests
  • Adds test-support as a dev-dependency for comenqd tests

The EnvVarGuard pattern ensures automatic cleanup even if tests panic, eliminating race conditions and making tests more reliable.

Fixes #75

🤖 Generated with Claude Code

Summary by Sourcery

Replace direct environment variable mutations in retry-related tests with RAII-based guards to make test execution safer and more reliable.

New Features:

  • Add EnvVarGuard::remove helper to temporarily unset environment variables with automatic restoration.

Enhancements:

  • Use EnvVarGuard in retry_helper tests to manage CI-related environment variables without unsafe mutations.
  • Mark environment-mutating tests as serial to avoid parallel interference.
  • Add coverage test ensuring EnvVarGuard::remove restores original values.

Build:

  • Add test-support as a dev-dependency for comenqd tests.

Tests:

  • Extend env_guard tests to cover removal semantics and restoration behavior.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Dec 24, 2025

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Summary by CodeRabbit

  • Tests

    • Improved test isolation by using scoped environment guards and marking certain tests to run serially for deterministic CI-related behaviour.
    • Updated test setup to manage socket-related environment state per test world and ensure proper teardown.
  • Chores

    • Added a dev dependency to provide new test utilities.
    • Narrowed the publicly exported test-support API to expose only the guarded env helper.

✏️ Tip: You can customize this high-level summary in your review settings.

Walkthrough

Replace unsafe env var mutations with RAII guards: add EnvVarGuard::remove, narrow test-support exports to EnvVarGuard only, switch tests to EnvVarGuard usage with serial markers, and add test-support as a dev-dependency.

Changes

Cohort / File(s) Summary
Dependency Configuration
crates/comenqd/Cargo.toml
Add test-support = { workspace = true } under [dev-dependencies].
Guard Infrastructure
test-support/src/env_guard.rs, test-support/src/lib.rs
Add pub fn remove(key: &str) -> EnvVarGuard; change set_env_var/remove_env_var visibility to pub(crate); re-export only EnvVarGuard from crate root.
Test Migration — daemon tests
crates/comenqd/tests/retry_helper.rs
Replace unsafe env::set_var/env::remove_var with EnvVarGuard::set/EnvVarGuard::remove; add #[serial_test::serial] to affected tests.
Test Migration — config & steps
crates/comenqd/src/config.rs, tests/steps/config_steps.rs
Import test_support::EnvVarGuard; use EnvVarGuard::remove("COMENQD_SOCKET_PATH") and store per-world socket_guard: Option<EnvVarGuard>; drop/restore in Drop implementation.

Sequence Diagram(s)

(Skipped — changes modify test helpers and test code only, not a new multi-component runtime control flow.)

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related issues

Poem

🛡️ Guard the CI flag, let chaos cease,
No unsafe blocks, just scoped release.
Serial tests align the nightly run,
EnvVarGuard restores what was undone. ✨

Pre-merge checks and finishing touches

✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title directly describes the main change: replacing unsafe environment variable mutations with EnvVarGuard in retry tests, which is the core objective of the PR.
Description check ✅ Passed The description comprehensively explains the problem (unsafe env mutations in retry_helper.rs), the solution (EnvVarGuard::remove() method and RAII-based guards), and relates directly to issue #75.
Linked Issues check ✅ Passed The changeset fully addresses issue #75: replaces unsafe env::set_var/remove_var calls with EnvVarGuard guards, adds serial attributes to prevent test interference, implements EnvVarGuard::remove() method, and adds test-support dev-dependency.
Out of Scope Changes check ✅ Passed All changes align with issue #75 objectives: env-guard improvements, retry_helper refactoring, config.rs updates, and test coverage additions directly support eliminating unsafe environment mutations in daemon tests.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch issue-75-unsafe-environment-variable-mutation

📜 Recent review details

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7a40d2f and 30a2573.

📒 Files selected for processing (6)
  • crates/comenqd/Cargo.toml
  • crates/comenqd/src/config.rs
  • crates/comenqd/tests/retry_helper.rs
  • test-support/src/env_guard.rs
  • test-support/src/lib.rs
  • tests/steps/config_steps.rs
🧰 Additional context used
📓 Path-based instructions (1)
**/*.rs

📄 CodeRabbit inference engine (AGENTS.md)

**/*.rs: Clippy warnings MUST be disallowed.
Fix any warnings emitted during tests in the code itself rather than silencing them.
Where a function is too long, extract meaningfully named helper functions adhering to separation of concerns and CQRS.
Where a function has too many parameters, group related parameters in meaningfully named structs.
Where a function is returning a large error consider using Arc to reduce the amount of data returned.
Write unit and behavioural tests for new functionality. Run both before and after making any change.
Every module must begin with a module level (//! ) comment explaining the module's purpose and utility.
Document public APIs using Rustdoc comments (///) so documentation can be generated with cargo doc.
Prefer immutable data and avoid unnecessary mut bindings.
Handle errors with the Result type 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 for conditional criteria with more than two branches.
Lints must not be silenced except as a last resort.
Lint rule suppressions must be tightly scoped and include a clear reason.
Prefer expect over allow.
Use rstest fixtures for shared setup.
Replace duplicated tests with #[rstest(...)] parameterised cases.
Prefer mockall for mocks/stubs.
Prefer .expect() over .unwrap().
Use concat!() to combine long string literals rather than escaping newlines with a backslash.
Prefer semantic error enums. Derive std::error::Error (via the thiserror crate) for any condition the caller might inspect, retry, or map to an HTTP status.
Use an opaque error only at the app boundary. Use eyre::Report for human-readable logs; these should not be exposed in public APIs.
Never export the opaque type from a library. Convert to domain enums at API boundaries, and to eyre only in the main main() entrypoint or top-level async task.

Files:

  • crates/comenqd/tests/retry_helper.rs
  • tests/steps/config_steps.rs
  • crates/comenqd/src/config.rs
  • test-support/src/lib.rs
  • test-support/src/env_guard.rs

⚙️ CodeRabbit configuration file

**/*.rs: * Seek to keep the cognitive complexity of functions no more than 9.

  • 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 / -yse / -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() in tests.
  • .expect() and .unwrap() are forbidden outside of tests. Errors must be propagated.
  • 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...

Files:

  • crates/comenqd/tests/retry_helper.rs
  • tests/steps/config_steps.rs
  • crates/comenqd/src/config.rs
  • test-support/src/lib.rs
  • test-support/src/env_guard.rs
🧬 Code graph analysis (4)
crates/comenqd/tests/retry_helper.rs (2)
test-support/src/env_guard.rs (2)
  • remove (26-33)
  • set (14-21)
crates/comenqd/tests/util.rs (1)
  • calculate_timeout (35-55)
tests/steps/config_steps.rs (1)
test-support/src/env_guard.rs (1)
  • remove (26-33)
crates/comenqd/src/config.rs (1)
test-support/src/env_guard.rs (1)
  • remove (26-33)
test-support/src/env_guard.rs (1)
tests/steps/config_steps.rs (1)
  • set_env_var (89-91)
🔍 Remote MCP Deepwiki

Summary — additional facts relevant to reviewing PR #124

  • test-support crate already provides EnvVarGuard RAII helper used across BDD/world tests; PR adds new pub fn EnvVarGuard::remove(key) and narrows re-exports (only EnvVarGuard remains public) — verify no callers still use removed set_env_var/remove_env_var.

  • test-support tests cover EnvVarGuard::remove semantics (restores original value or keeps unset); serial_test is used for env-mutating tests to avoid races. Confirm new tests exercise both original Some and None paths.

  • crates/comenqd tests and BDD worlds run concurrently via the cucumber harness (tokio::join!) — environment mutations must be guarded or test marked serial. PR adds EnvVarGuard usage and #[serial_test::serial] to affected tests; ensure all env-mutating tests are either guarded or serialized.

  • ConfigWorld (tests/steps/config_steps.rs) holds Option socket_guard now and Drop impls in worlds must drop/restore these guards to avoid leaking env changes across scenarios — confirm Drop paths cover all branches and panic cases.

  • crates/comenqd/Cargo.toml now lists test-support as a dev-dependency — ensure workspace dev-dep addition is intentional and does not widen public API surface beyond test usage.

Sources: Deepwiki repository documentation and test-support pages (test-support/env_guard, test-support/lib, tests/cucumber/worlds, config_steps, listener/worker steps).

⏰ 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). (1)
  • GitHub Check: Sourcery review
🔇 Additional comments (17)
crates/comenqd/Cargo.toml (1)

30-30: LGTM!

The dev-dependency addition is correct. The workspace test-support crate is now available for tests in this crate, enabling EnvVarGuard usage in retry_helper.rs and the config tests. The existing optional dependency on line 22 remains for the test-support feature used in production code paths.

crates/comenqd/src/config.rs (3)

255-255: LGTM!

The import correctly uses the narrowed public API from test_support, aligning with the crate's updated export surface.


267-267: Correct guard usage for environment isolation.

Using EnvVarGuard::remove() ensures the COMENQD_SOCKET_PATH environment variable does not leak from the test environment, and the original state is restored on drop.


289-289: LGTM!

The EnvVarGuard::set() correctly establishes a scoped override for testing environment variable precedence.

tests/steps/config_steps.rs (5)

9-9: LGTM!

Import correctly uses the narrowed public API.


17-17: LGTM!

The new socket_guard field correctly captures the EnvVarGuard for COMENQD_SOCKET_PATH management across test scenarios.


32-32: Guard correctly isolates socket path environment.

This ensures the COMENQD_SOCKET_PATH environment variable is removed during the test, preventing external configuration from affecting the test assertions.


71-71: LGTM!

Correctly removes the socket path environment variable to test default value behaviour.


141-143: Drop implementation correctly addresses past review feedback.

Both env_guard and socket_guard are now explicitly handled in Drop, ensuring deterministic cleanup regardless of which guards are active.

crates/comenqd/tests/retry_helper.rs (3)

6-7: LGTM!

Import correctly brings in EnvVarGuard for environment variable management in tests.


15-37: Well-structured test with isolated environment scopes.

The scoped blocks with EnvVarGuard::remove("CI") and EnvVarGuard::set("CI", "1") correctly isolate the two test scenarios within a single test function. Combined with #[serial_test::serial], this ensures deterministic behaviour regardless of the ambient CI environment.


39-48: LGTM!

The #[serial_test::serial] marker and EnvVarGuard::set correctly manage the CI environment variable for this test, ensuring automatic restoration on completion or panic.

test-support/src/env_guard.rs (4)

22-33: Well-implemented RAII guard for environment variable removal.

The remove method correctly:

  1. Captures the original value (if any) before removal
  2. Removes the environment variable immediately
  3. Restores the original state on drop via the existing Drop implementation

This enables safe, scoped environment variable removal in tests.


45-59: Correct visibility reduction and documentation.

Making set_env_var and remove_env_var pub(crate) enforces the guard-based pattern for external consumers. The SAFETY documentation clearly states the serial test context requirement.


95-109: Comprehensive test for restoration behaviour.

This test correctly verifies that EnvVarGuard::remove restores the original value when the guard drops, exercising the original: Some(_) path in Drop.


111-124: Test addresses past review feedback.

This test exercises the original: None path in Drop, confirming that a variable which was unset before EnvVarGuard::remove remains unset after the guard drops. This directly addresses the reviewer suggestion from the previous commit.

test-support/src/lib.rs (1)

11-11: Public API narrowed correctly.

Only EnvVarGuard is re-exported, forcing all consumers to use the guard-based pattern. The internal set_env_var and remove_env_var functions are properly scoped as pub(crate) and cannot be imported from outside the crate. No external callers reference the removed exports.


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

@sourcery-ai
Copy link
Copy Markdown

sourcery-ai Bot commented Dec 24, 2025

Reviewer's Guide

This PR replaces ad-hoc unsafe environment variable mutations in retry-related tests with a safe RAII-based EnvVarGuard API, adds a remove() helper and its tests to the test-support crate, and marks env-mutating tests as serial while wiring test-support as a dev-dependency of the comenqd crate.

Sequence diagram for retry test using EnvVarGuard and serial_test

sequenceDiagram
    actor Tester
    participant TestRunner
    participant RetryTest as RetryTest_fn
    participant EnvVarGuard

    Tester->>TestRunner: run tests
    TestRunner->>RetryTest: execute with serial_test::serial
    RetryTest->>EnvVarGuard: remove(COMENQ_RETRY_BACKOFF_MS)
    activate EnvVarGuard
    EnvVarGuard-->>RetryTest: guard instance

    RetryTest->>RetryTest: run retry logic under modified env

    RetryTest-->>TestRunner: test completed (may pass or panic)
    deactivate EnvVarGuard
    EnvVarGuard-->>EnvVarGuard: drop()
    EnvVarGuard->>EnvVarGuard: restore original env var

    TestRunner-->>Tester: report result
Loading

Class diagram for EnvVarGuard with new remove method

classDiagram
    class EnvVarGuard {
        -String key
        -Option~String~ original
        +EnvVarGuard set(String key, String value)
        +EnvVarGuard remove(String key)
        +String key()
        +Option~String~ original()
        +void apply()
        +void restore()
    }

    class EnvVarGuardDrop {
        +void drop()
    }

    EnvVarGuard <|.. EnvVarGuardDrop
Loading

File-Level Changes

Change Details Files
Replace direct env::set_var/remove_var usage in retry helper tests with EnvVarGuard and serialize env-mutating tests.
  • Wrap CI-related timeout assertions in scoped blocks that use EnvVarGuard::remove and EnvVarGuard::set instead of unsafe env::remove_var/set_var.
  • Add #[serial_test::serial] attributes to tests that mutate environment variables to prevent cross-test interference when running in parallel.
crates/comenqd/tests/retry_helper.rs
Extend EnvVarGuard with a remove() API and test its behavior.
  • Implement EnvVarGuard::remove(key) that captures the original value, removes the variable for the guard lifetime, and restores it on Drop if previously set.
  • Add a serial test env_var_guard_remove_restores_value to verify that EnvVarGuard::remove correctly unsets and then restores the original value, and clean up the variable at the end of the test.
test-support/src/env_guard.rs
Make the test-support crate available to comenqd tests.
  • Add test-support as a workspace dev-dependency in the comenqd crate to allow reuse of EnvVarGuard in its tests.
crates/comenqd/Cargo.toml

Assessment against linked issues

Issue Objective Addressed Explanation
#75 Replace unsafe env::set_var/remove_var calls in the calculate_timeout_caps_bounds and calculate_timeout_scales_with_ci_env tests with EnvVarGuard-based RAII management, importing and using EnvVarGuard as specified.
#75 Eliminate race conditions and flaky behavior caused by unsynchronised CI environment variable mutations when tests run in parallel.
#75 Remove unsafe blocks related to environment variable mutation from the affected daemon tests.

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

@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 - I've found 1 issue

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location> `test-support/src/env_guard.rs:96` </location>
<code_context>

+    #[test]
+    #[serial_test::serial]
+    fn env_var_guard_remove_restores_value() {
+        let key = "ENV_GUARD_REMOVE_GUARD";
+        super::set_env_var(key, "original");
</code_context>

<issue_to_address>
**suggestion (testing):** Consider adding a test for `EnvVarGuard::remove` when the variable is not initially set.

Right now we only verify behavior when the variable already has a value. Please also add a test where the variable is unset before `EnvVarGuard::remove` is called and confirm it remains unset after the guard is dropped, exercising the `original: None` path.
</issue_to_address>

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.

Comment thread test-support/src/env_guard.rs
@leynos leynos force-pushed the issue-75-unsafe-environment-variable-mutation branch from 2d0ac61 to 10d14ad Compare December 24, 2025 01:04
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: 0

Caution

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

⚠️ Outside diff range comments (1)
test-support/src/env_guard.rs (1)

45-58: Restrict visibility of raw helper functions to prevent misuse.

These public functions contain unsafe blocks and bypass the EnvVarGuard protection mechanism. If called directly from non-serial test contexts, they introduce race conditions. Make them pub(crate) to limit their use to internal EnvVarGuard implementation, forcing external callers to use the safer guard API.

🔎 Proposed fix
-/// Set an environment variable for tests.
-///
-/// The nightly compiler marks `std::env::set_var` as `unsafe`.
-/// Tests run serially so using it is acceptable here.
-pub fn set_env_var(key: &str, value: &str) {
+/// Set an environment variable for internal guard use.
+///
+/// SAFETY: Must only be called from serial test contexts.
+/// External callers should use `EnvVarGuard::set()` instead.
+pub(crate) fn set_env_var(key: &str, value: &str) {
     unsafe { std::env::set_var(key, value) };
 }
 
-/// Remove an environment variable for tests.
-///
-/// `std::env::remove_var` is also `unsafe` on nightly.
-pub fn remove_env_var(key: &str) {
+/// Remove an environment variable for internal guard use.
+///
+/// SAFETY: Must only be called from serial test contexts.
+/// External callers should use `EnvVarGuard::remove()` instead.
+pub(crate) fn remove_env_var(key: &str) {
     unsafe { std::env::remove_var(key) };
 }
📜 Review details

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8df915c and 10d14ad.

📒 Files selected for processing (3)
  • crates/comenqd/Cargo.toml
  • crates/comenqd/tests/retry_helper.rs
  • test-support/src/env_guard.rs
🧰 Additional context used
📓 Path-based instructions (1)
**/*.rs

📄 CodeRabbit inference engine (AGENTS.md)

**/*.rs: Clippy warnings MUST be disallowed.
Fix any warnings emitted during tests in the code itself rather than silencing them.
Where a function is too long, extract meaningfully named helper functions adhering to separation of concerns and CQRS.
Where a function has too many parameters, group related parameters in meaningfully named structs.
Where a function is returning a large error consider using Arc to reduce the amount of data returned.
Write unit and behavioural tests for new functionality. Run both before and after making any change.
Every module must begin with a module level (//! ) comment explaining the module's purpose and utility.
Document public APIs using Rustdoc comments (///) so documentation can be generated with cargo doc.
Prefer immutable data and avoid unnecessary mut bindings.
Handle errors with the Result type 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 for conditional criteria with more than two branches.
Lints must not be silenced except as a last resort.
Lint rule suppressions must be tightly scoped and include a clear reason.
Prefer expect over allow.
Use rstest fixtures for shared setup.
Replace duplicated tests with #[rstest(...)] parameterised cases.
Prefer mockall for mocks/stubs.
Prefer .expect() over .unwrap().
Use concat!() to combine long string literals rather than escaping newlines with a backslash.
Prefer semantic error enums. Derive std::error::Error (via the thiserror crate) for any condition the caller might inspect, retry, or map to an HTTP status.
Use an opaque error only at the app boundary. Use eyre::Report for human-readable logs; these should not be exposed in public APIs.
Never export the opaque type from a library. Convert to domain enums at API boundaries, and to eyre only in the main main() entrypoint or top-level async task.

Files:

  • test-support/src/env_guard.rs
  • crates/comenqd/tests/retry_helper.rs

⚙️ CodeRabbit configuration file

**/*.rs: * Seek to keep the cognitive complexity of functions no more than 9.

  • 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 / -yse / -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() in tests.
  • .expect() and .unwrap() are forbidden outside of tests. Errors must be propagated.
  • 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...

Files:

  • test-support/src/env_guard.rs
  • crates/comenqd/tests/retry_helper.rs
🧬 Code graph analysis (1)
test-support/src/env_guard.rs (1)
tests/steps/config_steps.rs (1)
  • set_env_var (88-90)
🔍 Remote MCP Deepwiki

Based on the context gathered, here's the relevant information for reviewing this PR:

Additional Context for PR Review

EnvVarGuard Implementation Overview

The EnvVarGuard is an RAII-style helper in the test-support crate designed to safely manage environment variables during tests. The struct contains two fields: key (the environment variable name) and original (an Option<String> storing the variable's value before being set by the guard).

Current methods:

  • EnvVarGuard::set(key: &str, value: &str) -> Self sets an environment variable to a new value for the lifetime of the guard, storing the current value in the original field
  • The Drop::drop(&mut self) implementation checks if an original value was stored; if it exists, it restores the environment variable to that value, and if there was no original value, it removes the variable

New method being added (from PR):
According to the AI summary, the PR adds pub fn remove(key: &str) -> Self which immediately removes the environment variable and stores the original value to restore on drop—providing a complementary constructor to set() for cases where tests need to explicitly ensure a variable is absent.

Serial Test Execution

serial_test::serial prevents race conditions in environment variable mutations by ensuring that tests marked with this attribute run one at a time. This serialization is crucial because environment variables are global state, and concurrent modifications by multiple tests could lead to unpredictable and flaky test results.

Why This PR Matters

The PR addresses a critical race condition issue: The use of serial_test::serial in tests that modify environment variables is important to prevent race conditions because operations like std::env::set_var and std::env::remove_var are marked as unsafe on nightly Rust due to their global effect.

Implementation Pattern

The EnvVarGuard is used to ensure test isolation by managing environment variables, preventing side effects between tests. This pattern is already established in the codebase, as seen in configuration testing, making this PR consistent with existing infrastructure.

⏰ 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). (1)
  • GitHub Check: Sourcery review
🔇 Additional comments (7)
crates/comenqd/Cargo.toml (1)

30-30: LGTM!

The dev-dependency addition enables the use of EnvVarGuard in tests, which aligns with the PR objective to eliminate unsafe environment variable mutations.

test-support/src/env_guard.rs (3)

23-33: LGTM!

The remove() method correctly implements the RAII pattern by storing the original value and delegating to the helper function. The structure mirrors set(), ensuring consistency.


94-108: LGTM!

The test correctly validates that remove() restores the original value on drop. Good use of .expect() with descriptive messages following the coding guidelines.


110-123: LGTM!

This test addresses the past review comment by validating that remove() correctly handles the case where the variable is not initially set. The triple assertion (before, during, after) thoroughly verifies the behaviour.

crates/comenqd/tests/retry_helper.rs (3)

16-16: LGTM!

The #[serial_test::serial] attribute prevents race conditions when mutating the CI environment variable, ensuring deterministic test behaviour.


18-36: LGTM!

The scoped blocks with EnvVarGuard correctly eliminate unsafe environment mutations. The use of remove() for the non-CI case and set() for the CI case properly isolates the test scenarios whilst ensuring automatic cleanup.


40-42: LGTM!

The serial marker and EnvVarGuard::set() eliminate the unsafe environment mutation whilst maintaining test functionality. The guard correctly manages the CI variable lifecycle.

@leynos leynos force-pushed the issue-75-unsafe-environment-variable-mutation branch from 10d14ad to 7a40d2f Compare December 24, 2025 01:12
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: Organization UI

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 10d14ad and 7a40d2f.

📒 Files selected for processing (6)
  • crates/comenqd/Cargo.toml
  • crates/comenqd/src/config.rs
  • crates/comenqd/tests/retry_helper.rs
  • test-support/src/env_guard.rs
  • test-support/src/lib.rs
  • tests/steps/config_steps.rs
🧰 Additional context used
📓 Path-based instructions (1)
**/*.rs

📄 CodeRabbit inference engine (AGENTS.md)

**/*.rs: Clippy warnings MUST be disallowed.
Fix any warnings emitted during tests in the code itself rather than silencing them.
Where a function is too long, extract meaningfully named helper functions adhering to separation of concerns and CQRS.
Where a function has too many parameters, group related parameters in meaningfully named structs.
Where a function is returning a large error consider using Arc to reduce the amount of data returned.
Write unit and behavioural tests for new functionality. Run both before and after making any change.
Every module must begin with a module level (//! ) comment explaining the module's purpose and utility.
Document public APIs using Rustdoc comments (///) so documentation can be generated with cargo doc.
Prefer immutable data and avoid unnecessary mut bindings.
Handle errors with the Result type 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 for conditional criteria with more than two branches.
Lints must not be silenced except as a last resort.
Lint rule suppressions must be tightly scoped and include a clear reason.
Prefer expect over allow.
Use rstest fixtures for shared setup.
Replace duplicated tests with #[rstest(...)] parameterised cases.
Prefer mockall for mocks/stubs.
Prefer .expect() over .unwrap().
Use concat!() to combine long string literals rather than escaping newlines with a backslash.
Prefer semantic error enums. Derive std::error::Error (via the thiserror crate) for any condition the caller might inspect, retry, or map to an HTTP status.
Use an opaque error only at the app boundary. Use eyre::Report for human-readable logs; these should not be exposed in public APIs.
Never export the opaque type from a library. Convert to domain enums at API boundaries, and to eyre only in the main main() entrypoint or top-level async task.

Files:

  • test-support/src/lib.rs
  • tests/steps/config_steps.rs
  • crates/comenqd/src/config.rs
  • crates/comenqd/tests/retry_helper.rs
  • test-support/src/env_guard.rs

⚙️ CodeRabbit configuration file

**/*.rs: * Seek to keep the cognitive complexity of functions no more than 9.

  • 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 / -yse / -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() in tests.
  • .expect() and .unwrap() are forbidden outside of tests. Errors must be propagated.
  • 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...

Files:

  • test-support/src/lib.rs
  • tests/steps/config_steps.rs
  • crates/comenqd/src/config.rs
  • crates/comenqd/tests/retry_helper.rs
  • test-support/src/env_guard.rs
🧬 Code graph analysis (4)
tests/steps/config_steps.rs (1)
test-support/src/env_guard.rs (1)
  • remove (26-33)
crates/comenqd/src/config.rs (1)
test-support/src/env_guard.rs (1)
  • remove (26-33)
crates/comenqd/tests/retry_helper.rs (2)
test-support/src/env_guard.rs (2)
  • remove (26-33)
  • set (14-21)
crates/comenqd/tests/util.rs (1)
  • calculate_timeout (35-55)
test-support/src/env_guard.rs (1)
tests/steps/config_steps.rs (1)
  • set_env_var (89-91)
🔍 Remote MCP Deepwiki

Summary of additional facts relevant to reviewing PR #124 (replace unsafe env mutations with EnvVarGuard)

  • test-support crate already provides EnvVarGuard RAII helper that captures an env var's original value, sets/removes it for the guard's lifetime and restores/removes on Drop — used across BDD/world tests to isolate env changes.
  • test-support exposes utilities used by tests (env_guard, util::wait_for_file, daemon helpers); the crate is intended for test-only consumption and coordinates async test helpers used by comendqd tests.
  • Behavioral tests and worlds run concurrently via the cucumber harness; env mutations therefore require either RAII guards or serialized tests to avoid global-state races — the test suite already uses serial_test for env-sensitive tests elsewhere (test-support lists serial_test in dependencies).
  • ConfigWorld (tests/steps/config_steps.rs) now holds an Option socket_guard; reviewers should check that this new field is always dropped/cleared on world teardown (Drop impls in worlds must restore env) to avoid leaking guards across scenarios.
  • test-support previously re-exported set_env_var/remove_env_var; PR narrows public API to only EnvVarGuard — confirm downstream tests/crates do not rely on the removed direct helpers and that all callsites switched to EnvVarGuard usage.
  • Tests rely on wait_for_file and SOCKET_RETRY_* retry semantics when starting/stopping listeners; ensure EnvVarGuard::remove semantics (temporary removal restores original or removes) do not change test timing or socket setup expectations.

Sources used:

⏰ 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). (1)
  • GitHub Check: Sourcery review
🔇 Additional comments (12)
test-support/src/lib.rs (1)

11-11: LGTM: Narrowed public API enforces guard-based pattern.

The removal of direct remove_env_var and set_env_var re-exports correctly forces all consumers to use the RAII-based EnvVarGuard, preventing unsafe direct environment mutations.

crates/comenqd/Cargo.toml (1)

30-30: LGTM: Dev-dependency addition enables guard-based env management.

The addition of test-support as a dev-dependency correctly enables EnvVarGuard usage in the test modules, supporting the migration away from unsafe environment mutations.

tests/steps/config_steps.rs (2)

9-9: LGTM: Import updated to use narrowed public API.

The import correctly references EnvVarGuard from the updated test_support public API surface.


32-32: LGTM: EnvVarGuard correctly captures socket path removal.

The use of EnvVarGuard::remove("COMENQD_SOCKET_PATH") correctly removes the environment variable for the test's lifetime and will restore the original value (or absence) on drop.

Also applies to: 71-71

crates/comenqd/tests/retry_helper.rs (3)

7-7: LGTM: Import correctly references EnvVarGuard.

The import follows the updated test_support public API, enabling RAII-based environment management.


15-37: LGTM: Test correctly uses EnvVarGuard with serial execution.

The test properly:

  • Adds #[serial_test::serial] to prevent parallel interference
  • Captures guards with _guard to ensure RAII cleanup
  • Uses scoped blocks to control guard lifetimes
  • Removes unsafe environment mutations

39-49: LGTM: Test correctly uses EnvVarGuard with serial execution.

The test properly:

  • Adds #[serial_test::serial] for deterministic environment handling
  • Captures the guard with _guard to ensure cleanup on drop
  • Removes unsafe environment mutations
crates/comenqd/src/config.rs (2)

255-255: LGTM: Test module import correctly references EnvVarGuard.

The import follows the updated test_support public API for RAII-based environment management in tests.


267-267: LGTM: Tests correctly use EnvVarGuard for environment management.

All environment mutations now use EnvVarGuard with proper guard capture (_guard), ensuring RAII-based cleanup. The tests are marked with #[serial_test::serial] for deterministic execution.

Also applies to: 289-289, 341-341

test-support/src/env_guard.rs (3)

23-33: LGTM: EnvVarGuard::remove() correctly implements removal semantics.

The implementation:

  • Captures the original value (if any) before removal
  • Removes the variable for the guard's lifetime
  • Will restore the original state on drop via the existing Drop impl

45-59: LGTM: Helper functions correctly scoped and documented.

The visibility change to pub(crate) correctly restricts direct usage and forces external consumers to use EnvVarGuard. The unsafe blocks are necessary for Rust 2024 edition environment variable mutations, and the safety comments appropriately document the serial test context requirement.


95-124: LGTM: Comprehensive tests cover remove() semantics.

The new tests correctly verify:

  • Line 97: Restoration of original value when present
  • Line 113: Variable remains unset when originally unset (addresses previous review comment)

Both tests use #[serial_test::serial] for safe environment mutation and have descriptive names.

Comment thread tests/steps/config_steps.rs
@leynos
Copy link
Copy Markdown
Owner Author

leynos commented Dec 24, 2025

@coderabbitai Have the following now been resolved?

Please address the comments from this code review:

## Individual Comments

### Comment 1
<location> `test-support/src/env_guard.rs:96` </location>
<code_context>

+    #[test]
+    #[serial_test::serial]
+    fn env_var_guard_remove_restores_value() {
+        let key = "ENV_GUARD_REMOVE_GUARD";
+        super::set_env_var(key, "original");
</code_context>

<issue_to_address>
**suggestion (testing):** Consider adding a test for `EnvVarGuard::remove` when the variable is not initially set.

Right now we only verify behavior when the variable already has a value. Please also add a test where the variable is unset before `EnvVarGuard::remove` is called and confirm it remains unset after the guard is dropped, exercising the `original: None` path.
</issue_to_address>

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Dec 24, 2025

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Read the test file to check for tests covering EnvVarGuard::remove behavior
cat test-support/src/env_guard.rs

Length of output: 4226


@leynos: Yes, this comment has been resolved!

The test file now includes env_var_guard_remove_keeps_unset_when_originally_unset() at Line 109, which specifically tests EnvVarGuard::remove when the variable is not initially set. The test:

  1. Ensures the variable is unset initially
  2. Creates a guard with EnvVarGuard::remove(key)
  3. Verifies the variable remains unset during the guard's lifetime
  4. Confirms the variable stays unset after the guard is dropped

This properly exercises the original: None path in the Drop implementation, addressing the original suggestion.

The daemon tests in retry_helper.rs contained unsafe environment variable
mutations that could cause race conditions when tests run in parallel.
This change:

- Adds EnvVarGuard::remove() method to test-support crate for temporarily
  removing environment variables with RAII-based restoration
- Replaces all unsafe env::set_var/remove_var calls with EnvVarGuard guards
- Adds #[serial_test::serial] attribute to tests that mutate environment
  to prevent interference between tests
- Adds test-support as a dev-dependency for comenqd tests

The EnvVarGuard pattern ensures automatic cleanup even if tests panic,
eliminating race conditions and making tests more reliable.

Fixes #75

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

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
@leynos leynos force-pushed the issue-75-unsafe-environment-variable-mutation branch from 7a40d2f to 30a2573 Compare December 24, 2025 01:37
@leynos leynos merged commit 86bc6e7 into main Dec 24, 2025
2 of 3 checks passed
@leynos leynos deleted the issue-75-unsafe-environment-variable-mutation branch December 24, 2025 12:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Unsafe environment variable mutations in daemon tests lack synchronisation

1 participant