Replace unsafe env mutations with EnvVarGuard in retry tests#124
Conversation
|
Note Other AI code review bot(s) detectedCodeRabbit 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
✏️ Tip: You can customize this high-level summary in your review settings. WalkthroughReplace 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
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
Pre-merge checks and finishing touches✅ Passed checks (5 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
📜 Recent review detailsConfiguration used: Organization UI Review profile: ASSERTIVE Plan: Pro 📒 Files selected for processing (6)
🧰 Additional context used📓 Path-based instructions (1)**/*.rs📄 CodeRabbit inference engine (AGENTS.md)
Files:
⚙️ CodeRabbit configuration file
Files:
🧬 Code graph analysis (4)crates/comenqd/tests/retry_helper.rs (2)
tests/steps/config_steps.rs (1)
crates/comenqd/src/config.rs (1)
test-support/src/env_guard.rs (1)
🔍 Remote MCP DeepwikiSummary — additional facts relevant to reviewing PR #124
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)
🔇 Additional comments (17)
Comment |
Reviewer's GuideThis 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_testsequenceDiagram
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
Class diagram for EnvVarGuard with new remove methodclassDiagram
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
File-Level Changes
Assessment against linked issues
Possibly linked issues
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
There was a problem hiding this comment.
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>Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.
2d0ac61 to
10d14ad
Compare
There was a problem hiding this comment.
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
EnvVarGuardprotection mechanism. If called directly from non-serial test contexts, they introduce race conditions. Make thempub(crate)to limit their use to internalEnvVarGuardimplementation, 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
📒 Files selected for processing (3)
crates/comenqd/Cargo.tomlcrates/comenqd/tests/retry_helper.rstest-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.rscrates/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
returnin single-line functions.- Move conditionals with >2 branches into a predicate function.
- Avoid
unsafeunless 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
rstestfixtures for shared setup and to avoid repetition between tests.- Replace duplicated tests with
#[rstest(...)]parameterised cases.- Prefer
mockallfor 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.rscrates/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) -> Selfsets an environment variable to a new value for the lifetime of the guard, storing the current value in theoriginalfield- The
Drop::drop(&mut self)implementation checks if anoriginalvalue 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
EnvVarGuardin 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 mirrorsset(), 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 theCIenvironment variable, ensuring deterministic test behaviour.
18-36: LGTM!The scoped blocks with
EnvVarGuardcorrectly eliminate unsafe environment mutations. The use ofremove()for the non-CI case andset()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 theCIvariable lifecycle.
10d14ad to
7a40d2f
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
📜 Review details
Configuration used: Organization UI
Review profile: ASSERTIVE
Plan: Pro
📒 Files selected for processing (6)
crates/comenqd/Cargo.tomlcrates/comenqd/src/config.rscrates/comenqd/tests/retry_helper.rstest-support/src/env_guard.rstest-support/src/lib.rstests/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.rstests/steps/config_steps.rscrates/comenqd/src/config.rscrates/comenqd/tests/retry_helper.rstest-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
returnin single-line functions.- Move conditionals with >2 branches into a predicate function.
- Avoid
unsafeunless 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
rstestfixtures for shared setup and to avoid repetition between tests.- Replace duplicated tests with
#[rstest(...)]parameterised cases.- Prefer
mockallfor 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.rstests/steps/config_steps.rscrates/comenqd/src/config.rscrates/comenqd/tests/retry_helper.rstest-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_varandset_env_varre-exports correctly forces all consumers to use the RAII-basedEnvVarGuard, 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-supportas a dev-dependency correctly enablesEnvVarGuardusage 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
EnvVarGuardfrom the updatedtest_supportpublic 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_supportpublic 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
_guardto 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
_guardto 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_supportpublic API for RAII-based environment management in tests.
267-267: LGTM: Tests correctly use EnvVarGuard for environment management.All environment mutations now use
EnvVarGuardwith 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 useEnvVarGuard. Theunsafeblocks 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.
|
@coderabbitai Have the following now been resolved? |
|
Tip For best results, initiate chat on the files or code changes. 🧩 Analysis chain🏁 Script executed: Length of output: 4226 @leynos: Yes, this comment has been resolved! The test file now includes
This properly exercises the |
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>
7a40d2f to
30a2573
Compare
The daemon tests in retry_helper.rs contained unsafe environment variable mutations that could cause race conditions when tests run in parallel. This change:
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:
Enhancements:
Build:
Tests: