Retire EnvLock and the env-mutation guards from test_support (#494) - #583
Retire EnvLock and the env-mutation guards from test_support (#494)#583leynos wants to merge 37 commits into
Conversation
|
Warning Your free Security trial is over. An organization admin can activate billing to continue. |
1 similar comment
|
Warning Your free Security trial is over. An organization admin can activate billing to continue. |
Reviewer's GuideRetires test-support environment and CWD mutation utilities by introducing explicit base-directory seams in manifest/glob code, updating tests to use injected bases, and enforcing a new lint/grep gate that forbids in-process environment mutation. Sequence diagram for manifest glob expansion with an injected workspace rootsequenceDiagram
participant CLI as CLI composition boundary
participant Query as Manifest query
participant Manifest as Manifest renderer
participant Glob as Glob expansion
participant FS as Filesystem
CLI->>Query: open_manifest_workspace(path, base)
Query->>Manifest: from_str_named(manifest_root)
Manifest->>Glob: expand_glob(pattern, manifest_root)
Glob->>FS: glob_with(base.join(pattern))
FS-->>Glob: matched paths
Glob-->>Manifest: pattern-relative paths
Manifest-->>CLI: rendered manifest result
File-Level Changes
Assessment against linked issues
Possibly linked issues
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
Important Approval pendingCodeRabbit has no unresolved comments, but it has not reviewed the latest commit. Use the checkbox below to review the latest commit. CodeRabbit will approve the changes if it finds no blocking issues.
Summary
Documentation
Tests
WalkthroughChangesPath resolution and mutation control
Suggested labels: Poem
Merge Risk: 🟡 Moderate · up to The PR replaces process-wide directory and environment mutation with explicit path inputs and adds enforcement, but the current head still has a likely Windows build failure in the new tests and a way to bypass the mutation lint gate by creating a matching filesystem entry. These issues should be fixed before merging. Caution Pre-merge checks failedPlease resolve all errors before merging. Addressing warnings is optional.
❌ Failed checks (4 errors, 7 warnings)
✅ Passed checks (9 passed)
Full details: Linked Issues checkExplanation Accept the implementation for issue Full details: Docstring CoverageExplanation Docstring coverage is 94.59% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 37 functions across 16 files. (4 skipped: 4 unsupported.) Full details: Testing (Overall)Explanation FAIL — The new environment-mutation gate has no durable behavioural test. Resolution Add committed tests for the new enforcement behaviour. Exercise Full details: User-Facing DocumentationExplanation The PR changes Resolution Replace the stale working-directory wording in Full details: Developer DocumentationExplanation Fail this check. The PR introduces a new Resolution Update Full details: Module-Level DocumentationExplanation PASS — All Rust modules introduced or modified by the PR have module-level Full details: Testing (Unit And Behavioural)Explanation Fail the testing check because the new enforcement behaviour has no durable test coverage. The PR adds Resolution Add a committed test harness for Full details: Testing (Property / Proof)Explanation The PR introduces range-based invariants in Resolution Add substantive Full details: Testing (Compile-Time / Ui)Explanation The pull request introduces compile-time Clippy behaviour: both Resolution Add a committed Rust compile-time/UI test for the new Clippy restriction. Compile a fixture containing Full details: Unit ArchitectureExplanation Fail: Resolution Separate text preparation from base resolution. Resolve the base only for a relative pattern in a small, explicitly fallible helper. Return and propagate canonicalisation errors with the existing glob error context, or define and return a typed expected outcome for a missing base instead of catching every error. Do not canonicalize an unused base for absolute patterns. Update the API documentation to list base-resolution and filesystem failures, and add tests for missing, inaccessible, and unresolvable bases plus the absolute-pattern case. Full details: Domain ArchitectureExplanation Pass the Domain Architecture check. The pull request does not change Full details: ObservabilityExplanation PASS — the changed production path is manifest glob resolution, and the existing Jinja glob adapter still records every completed expansion at the composition boundary. Full details: Security And PrivacyExplanation Fix the injected-base glob construction before merging. Resolution Escape every metacharacter in every injected base component before concatenating it with the normalized glob pattern, using the Full details: Performance And Resource UseExplanation The base-anchored glob path adds an avoidable allocation for every matched file. Resolution Refactor match handling so the owned path is stripped and separator-normalized in one final conversion, with no intermediate Full details: Concurrency And StateExplanation The changed Resolution Restore an exactly-once gate around the whole completion effect: return before calling the inner reporter when the completion transition was already taken, or compute and check a Full details: Architectural Complexity And MaintainabilityExplanation Accept the architectural change. Use the explicit base-directory seam because it removes process-global CWD mutation from manifest and glob paths. Keep Full details: Rust Compiler Lint IntegrityExplanation The PR introduces cross-platform compiler-lint failures in test imports. In Resolution Restore the unconditional ✨ Finishing Touches 💡 1🛠️ Fix failing CI checks 💡
📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 89ce5d9341
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
89ce5d9 to
939a042
Compare
This comment was marked as resolved.
This comment was marked as resolved.
|
@coderabbitai Please suggest a fix for this issue and supply a prompt for an AI coding agent to enable it to apply the fix. Include the file and symbol names indicated in the issue at the head of your response. Ensure that this is validated against the current version of the codegraph. If further refinement to address this finding would be deleterious, please supply a clear explanatory one to two paragraph markdown message in a code block that I can paste into the CodeScene web ui's diagnostic suppression function so this diagnostic can be silenced. Comment on lines +204 to +207 pub(super) fn expand_glob(
pattern: &str,
base: Option<&Path>,
) -> std::result::Result<GlobExpansion, Error> {❌ New issue: Large Method |
This comment was marked as resolved.
This comment was marked as resolved.
This comment was marked as resolved.
This comment was marked as resolved.
|
@coderabbitai review |
939a042 to
6e937a2
Compare
This comment was marked as resolved.
This comment was marked as resolved.
a106707 to
37d9ea9
Compare
|
@coderabbitai review |
✅ Action performedReview finished.
|
4d35b32 to
888a5f1
Compare
The 3.11.5 parent task and its four open sub-items are satisfied by the #494 work on this branch: env_lock.rs and cwd_guard.rs are deleted, zero EnvLock/CwdGuard references remain in any Rust source, the environment-mutation gate reports no violations, and tests use injected mockable::Env seams or isolated child processes. Check off the parent and sub-items accordingly.
|
@coderabbitai Please suggest a fix for this issue and supply a prompt for an AI coding agent to enable it to apply the fix. Include the file and symbol names indicated in the issue at the head of your response. Ensure that this is validated against the current version of the codegraph. If further refinement to address this finding would be deleterious, please supply a clear explanatory one to two paragraph markdown message in a code block that I can paste into the CodeScene web ui's diagnostic suppression function so this diagnostic can be silenced. Bumpy Road Aheadscripts/check_env_mutation.py: scan_root What lead to degradation?scan_root has 2 blocks with nested conditional logic. Any nesting of 2 or deeper is considered. Threshold is 2 blocks per function Why does this problem occur?A Bumpy Road is a function that contains multiple chunks of nested conditional logic inside the same function. The deeper the nesting and the more bumps, the lower the code health. How to fix it?Bumpy Road implementations indicate a lack of encapsulation. Check out the detailed description of the Bumpy Road code health issue. |
|
@coderabbitai Please suggest a fix for this issue and supply a prompt for an AI coding agent to enable it to apply the fix. Include the file and symbol names indicated in the issue at the head of your response. Ensure that this is validated against the current version of the codegraph. If further refinement to address this finding would be deleterious, please supply a clear explanatory one to two paragraph markdown message in a code block that I can paste into the CodeScene web ui's diagnostic suppression function so this diagnostic can be silenced. Deep, Nested Complexityscripts/check_env_mutation.py: scan_root What lead to degradation?scan_root has a nested complexity depth of 4, threshold = 4 Why does this problem occur?Deep nested logic means that you have control structures like if-statements or loops inside other control structures. Deep nested logic increases the cognitive load on the programmer reading the code. The human working memory has a maximum capacity of 3-4 items; beyond that threshold, we struggle with keeping things in our head. Consequently, deep nested logic has a strong correlation to defects and accounts for roughly 20% of all programming mistakes. How to fix it?Occassionally, it's possible to get rid of the nested logic by Replacing Conditionals with Guard Clauses. |
This comment was marked as resolved.
This comment was marked as resolved.
This comment was marked as resolved.
This comment was marked as resolved.
This comment was marked as resolved.
This comment was marked as resolved.
This comment was marked as resolved.
This comment was marked as resolved.
Extract directory resolution (scan_directories) and per-file scanning (scan_file) out of scan_root so the orchestrator has no nested conditional blocks, addressing the CodeScene Bumpy Road finding. Behaviour is unchanged: same scan order, output format, FileNotFoundError text for a missing scan directory, and test coverage.
Address the CodeScene Deep, Nested Complexity finding in scripts/check_env_mutation.py::scan_root by splitting it into scan_subdirectory (owns the missing-directory FileNotFoundError and sorted rglob ordering) and scan_rust_file (owns one-based line numbering and the file:line:text finding format). scan_root is now one shallow loop over _SCAN_SUBDIRS with no nested file and line scanning. Behaviour, output, exit statuses, and the CLI are unchanged. Add two helper-contract tests pinning the exact error message and the directory-then-path-then-line finding order.
|
@coderabbitai Please investigate the cause of the following issue using codegraph exploration and research, identify a fix and provide an AI coding agent prompt for the fix: https://github.com/leynos/netsuke/actions/runs/33194269118/job/98927282835?pr=583 |
This comment was marked as resolved.
This comment was marked as resolved.
This comment was marked as resolved.
This comment was marked as resolved.
All tests in src/manifest/glob/tests/base.rs are #[cfg(unix)], but the glob_paths, Utf8Path, tempfile, and test_support::fs imports were not, producing unused-import warnings on non-Unix targets. Gate each with #[cfg(unix)] to match the tests; the anyhow import keeps its existing gate. No test behaviour changes.
The #[cfg(unix)] gate on the anyhow import removed Context, Result, anyhow!, and ensure! from Windows builds even though six capability tests compile on every platform and use them, producing missing-macro and E0107 errors in the Windows CI job. Restore the unconditional anyhow import, gate only the genuinely Unix-only imports (walk::literal_dir_prefix and minijinja::ErrorKind, both used solely by cfg(unix) tests), and gate the entirely Unix-only base test module in tests/mod.rs so its Unix-only imports and bodies do not compile on non-Unix targets. base_property stays unconditional.
Keep matched paths structured until base stripping and final separator normalization, then cover literal metacharacter bases and missing-base failures. Add a deterministic glob benchmark and document the base-directory and selector contracts. Execute the POSIX compatibility shim through a shell so its gate test runs on Windows.
Summary
Closes #494
Retire the environment-mutation machinery in
test_supportand add a hard gate so the pattern cannot be reintroduced. All production seams now accept injected base-directory/environment data instead of reading ambient process state; the real CWD is read only at the command-line composition boundary.Changes
Phase 1 — explicit base-directory seams
src/manifest/workspace.rs:resolve_absolute_workspace_rootnow takes an explicit base directory;open_manifest_workspaceand wrappers thread it through. No more internalstd::env::current_dir().src/manifest/glob/{mod.rs,walk.rs}:expand_glob,glob_paths,open_root_dir,open_literal_prefixaccept an explicit base for relative literal prefixes. TheDir::open_ambient_dir(".", ...)call is removed.src/manifest/mod.rs/query.rs: captures the already-resolvedManifestWorkspace.rootin theglob()Jinja closure and threads it intoexpand_glob.Phase 2 — test migration
All manifest, glob, and BDD tests now pass explicit base directories instead of mutating CWD.
GlobalStateGuard/ensure_global_state_lockand theirEnvLock/CwdGuardusage are gone;project_scope_file(directory: Option<&Path>)is used for configuration discovery.Phase 3 — deletion + audit
test_support/src/env_lock.rs,test_support/src/cwd_guard.rs(previouslyenv_guard.rs,env_var_guard.rs,path_guard.rswere already removed).test_support/src/env.rsnow holds only the pure helpersprepend_path_valueandwrite_manifest.test_support/src/http/mod.rsduration_from_env/from_env_providerread through themockable::Envseam (env.raw(...)), notstd::env::var— confirmed, no change needed.Phase 4 — enforcement gate (demonstrated to fail)
make lintnow runslint-env-mutationfirst. The grep gate (scripts/check-env-mutation.sh) rejectsstd::env::set_var,std::env::remove_var, andstd::env::set_current_dirundersrc/,tests/, andtest_support/, matching only the fullstd::env::path soCommand::env/env_clear/current_dirstay allowed. Bothclippy.tomlandtest_support/clippy.tomlgain theset_current_dirdisallowed-method entry in lockstep.Deliberate-violation proof — a temporary
tests/env_mutation_gate_proof.rscontaininglet _ = std::env::set_current_dir("/tmp");produced:and independently via clippy
disallowed-methods:The temporary file was removed and the tree left clean.
Validation
make check-fmt✓ (exit 0)make lint✓ (exit 0) — includeslint-env-mutation, clippy-D warnings, and Whitakermake test✓ (exit 0) — suite + doctests green (30 passed, 6 ignored in test_support)--agentreview: 0 findings across 28 reviewed filesReferences
Summary by Sourcery
Eliminate ambient process-state mutation from manifest and test infrastructure by injecting base-directory data and enforcing the policy with lint and test gates.
Bug Fixes:
-C/--directorycontract while preserving absolute-path behavior and unanchored resolution when no directory is supplied.Enhancements:
Build:
Documentation:
Tests:
Chores:
References
Issue: Retire EnvLock and the env mutation guards from test_support #494
Lody session: https://lody.ai/leynos/sessions/25818303-60fe-4eee-b1ac-cffbd2f3a196