Repository navigation
Conversation
The Kani scope wrapper left a failed transient unit behind on every run that did not finish cleanly. `CollectMode` defaults to `inactive`, so a scope stopped at its runtime deadline, OOM-killed, or refused a resource property stays loaded until someone resets it, and on 2026-11-01 the user manager was `degraded` partly because of scopes this repository created. The test suite made it worse: `reset_failed` was called only on the normal path, so an early `?` return or a panic skipped it. Routine invocations now pass `--collect`, which is `CollectMode=inactive-or-failed`, and the suite owns each unit through a guard created before the unit is launched. The guard tears the unit down from `Drop` as well as from a fallible `finish`, always by exact name, and keeps the capture when a body fails so the defect can be explained. Collection is deferred only where the evidence is the stopped unit's own `Result`, which is unreadable once the unit unloads. The suite is split into support modules and the tests it gained cover the collected shape, a collected non-zero status, an injected body error, a panic, a still-running scope, name reuse and concurrent runs. Unit names now carry a start stamp and a counter as well as the pid, so a successive run cannot collide with a unit a previous one left behind. The `-ok` anomaly is explained rather than removed. A payload that exits zero can leave a scope recorded `Result=timeout`, because the runtime deadline covers the whole control group and can fire during teardown; driving the cap to 5 ms reproduced it. No wrapper flag was at fault. The routine scenarios therefore use a wide cap and no timing assertion, and the docs state that a scope's `Result` is not the payload's exit status. Documentation records the evidence contract: routine versus deferred collection, the `LoadState=loaded` prerequisite, the status sidecar and bounded journal extract, unit-specific cleanup, and prefix-scoped recovery after a runner kill. Workflow contracts pin the wrapper step in `kani-smoke` before the proofs, the documented flags in all three documents, and the Makefile's strict-mode default. Co-Authored-By: Claude Code <noreply@anthropic.com>
`cargo check` does not run Clippy's pedantic set, so the first full `make lint` found nine violations the earlier typecheck could not see. All are in the new test module. The two `&Option<T>` parameters become `Option<&T>`, which removes the `ref_option` reports and lets the bodies state the borrow they take; the callers now pass `as_ref()`. The `option_if_let_else` and `match_same_arms` sites use `map_or_else`, and `unsettled_reason` reads the snapshot through `?` so its settled arms are one path rather than two that happen to agree. The concurrency test's spawn closure was four levels deep. Its body and its outcome collection are now named functions, so the spawn is a call. The panic test keeps its injected panic: it is the scenario, and it is caught by `catch_unwind` inside the same function, so it never escapes. That is recorded in a scoped `#[expect]` with its reason rather than left as an unexplained `allow`. Co-Authored-By: Claude Code <noreply@anthropic.com>
The df12 house lint `R9104` reports a function that only forwards an attribute as a `trivial-attribute-wrapper`, and the parametrized test id helper was exactly that: `_document_id` returned `path.stem` and nothing else. The parametrization now carries `pytest.param(..., id=...)` entries instead, which is the shape the other contract suites use and which also pins the reported ids: a case keeps the name `developers-guide` or `plan-4-2-2` if the file behind it is ever renamed. Co-Authored-By: Claude Code <noreply@anthropic.com>
Ten findings, nine of them real. The substantive ones: `reset-failed` does not stop an active unit — measured: it returns 0 and leaves the payload running — so the documented recovery after a runner kill only cleaned up half the residue. It now lists active and failed units, stops the active ones by name, waits, and resets what is left. The exceptional-path teardown tests could pass with the guard doing nothing, because a `Retention::Collect` payload is unloaded by the manager either way. Each now leaves its scope failed and retained before injecting the error or panic, so the settling assertion can only pass if teardown ran. They take about five seconds each as a result, which is the cost of the test meaning something. `scope_snapshot` read three properties in three queries, so a unit that unloaded between them reported defaults it no longer held; `ActiveState` alone also answers `inactive` for an absent unit, which made `wait_for_terminal` accept a collected scope as a clean stop. Both read the three properties in one query and require `LoadState=loaded` first. The failed-unit check now names the unit it owns rather than matching a prefix. Every test in one binary shares a process id, so a prefix query under libtest could see a sibling's retained failure and blame the wrong scenario. A missing `systemctl`, `/sys/fs/cgroup`, or `cgroup.controllers` is now a missing prerequisite rather than an error, so such a host skips as the suite documents instead of failing every scenario. Journal reads distinguish "read and empty" from "could not be read", are preceded by a best-effort `--sync`, and pass `-q`. The docs contract extracts the quoted `bash -c` argument instead of searching the block's suffix, with a negative control proving an outer pipeline is rejected. The crate root was 513 lines, over the 400-line rule; the timeout scenarios moved to `timeout_tests.rs`. One finding was not actionable as stated: `-o cat` does not print `-- No entries --` for an empty journal on this host — measured empty stdout with a zero exit — so the skip path already fired. The explicit `Journal` representation is kept because it is what makes that distinction auditable. Co-Authored-By: Claude Code <noreply@anthropic.com>
|
Important Draft PR not reviewedDraft PRs are not automatically reviewed by default.
To automatically review draft PRs, update your CodeRabbit configuration: reviews:
auto_review:
drafts: truePre-merge checks:
|
| Check name | Status | Explanation |
|---|---|---|
| Testing (Overall) | Summary: The PR adds tests for its behavioural changes. The tests exercise the real systemd-run wrapper and the teardown guard. Each new behaviour has a check that fails when the behaviour is re… |
|
| User-Facing Documentation | The check is not applicable. It requires new or changed user-facing functionality to be documented in docs/users-guide.md. This PR changes only maintainer tooling for the Kani scope wrapper. Evidence:… | |
| Developer Documentation | The pull request meets the Developer documentation check. It documents its changed tooling in docs/developers-guide.md and records the Kani wrapper decisions in the 4.2.2 and 4.2.3 ExecPlans. Eviden… |
|
| Module-Level Documentation | The check passes. Every Rust and Python module that this pull request adds or changes carries a module-level docstring. Scope: I checked the eight commits that make up the Kani scope-wrapper work (5c6… | |
| Testing (Unit And Behavioural) | The check passes. The PR adds behavioural and end-to-end tests for the changed externally observable workflow, and adds contract tests with negative controls for the documented command. **Behavioural … | |
| Testing (Compile-Time / Ui) | The check is not applicable to this pull request, so it passes. Evidence: - PR #1191 (leynos/netsuke, head 5256449) changes the Kani scope-wrapper test harness (tests/kani_scope_wrapper_e2e_tests.rs… |
|
| Unit Architecture | Summary: The change makes fallibility, state mutation, dependencies and responsibilities more visible overall. No explicit failure condition of the Unit Architecture check is met. Minor, non-block… | |
| Domain Architecture | The Domain Architecture check does not apply to this pull request, so it passes. Evidence: - PR #1191 targets main from `issue-1078-collect-transient-kani-scopes-and-guarantee-teardown-after-evidenc… |
|
| Observability | The change alters operational behaviour only for the local Kani scope wrapper and its test harness. It does not touch a production service. The observability it adds or keeps is adequate for this scop… |
Full details: Testing (Overall)
-
Explanation
Summary: The PR adds tests for its behavioural changes. The tests exercise the real
systemd-runwrapper and the teardown guard. Each new behaviour has a check that fails when the behaviour is removed. I found no vacuous test that would pass after the implementation was removed. Evidence reviewed (PR head5256449against merge-base4f58b3e): ---collect(routine and deferred collection):tests/kani_scope_wrapper_e2e_tests/harness.rsadds--collectonly forRetention::Collect. The collected-scope scenarios inteardown_tests.rsand the root suite callwait_until_unloaded, which pollsLoadStateuntil it is notloaded. If--collectwere removed, the unit would stay loaded and failed, and the wait would fail afterTERMINAL_CEILING. - Timeout and additive grace:timeout_tests.rschecks the lifetime from the manager's monotonic timestamps. It checks the upper bound,Result=timeout, and the journal's runtime-limit and SIGKILL entries. A removedTimeoutStopSecwould let the 60 s payload live past the 9 s ceiling. A nested grace would fail the additive lower bound, which the file justifies with the tolerance arithmetic. - Teardown guard:guard.rsprovidesfinishand a logging-onlyDrop.teardown_tests.rsmakes the scope failed and retained before injecting an error or a panic. This is needed because a successful scope is collected anyway, so a no-op guard would otherwise still pass. The injected-error test checks that the original error survives and that the capture is retained. The panic test checks the payload is unchanged. Both then assert the unit settles. - Negative controls:failing_payload_is_masked_without_pipefailis the control for the pipefail assertion. The environment-clearingmanaged_commandis tested by the same control. - Docs contracts:kani_scope_wrapper_docs_test.pychecks every routine example for the flags, bounded values andnice. It also includes negative controls (test_the_property_check_rejects_an_unbounded_value,test_the_payload_check_rejects_an_outer_pipeline). The Makefile strict-export test includes a commented-out-assignment control. Limitations (not failures): - The docs contracts check Markdown text. They do not prove that the documented command runs. The e2e suite covers the executed behaviour, so this weakness is partly offset. - Outside strict mode, a missing prerequisite produces a passing skip. Themake test-kani-scope-wrappertarget setsKANI_SCOPE_WRAPPER_STRICT ?= 1, so the gated lane does not skip silently. - The suite relies on systemd's ownCollectModeandResultbehaviour. The wrapper and guard interact heavily with that behaviour, so the check's third-party exemption does not remove the need for these tests. Repository-wide behaviour outside this PR was not assessed.
Full details: User-Facing Documentation
-
Explanation
The check is not applicable. It requires new or changed user-facing functionality to be documented in docs/users-guide.md. This PR changes only maintainer tooling for the Kani scope wrapper. Evidence: - The PR's changed files are limited to the Kani scope-wrapper test suite (tests/kani_scope_wrapper_e2e_tests.rs and its support modules), the workflow contract tests under tests/workflow_contracts/ (kani_scope_wrapper_docs_test.py, kani_scope_wrapper_makefile_test.py, kani_smoke_scope_wiring_test.py, kani_proof_scope_test.py), docs/developers-guide.md, and the ExecPlans 4.2.2 and 4.2.3. - No changed file is in the Netsuke CLI or runtime source for the scope wrapper. The wrapper is a developer-side systemd-run invocation for Kani proof runs. -
git diff origin/main...HEAD -- docs/users-guide.mdproduced no output, so the users guide is unchanged by this PR. - The users guide has no Kani or systemd scope content to update. The new--collectguidance lives in docs/developers-guide.md (for example, around lines 8177 to 8421), which is the correct audience for maintainer workflow changes. Note: the localorigin/main...HEADdiff also lists many unrelated files (for example, discovery and locale files). The sandbox base appears to be out of step with the PR base. Those files fall outside this PR's Kani-related changes and do not alter the verdict. The Kani-related paths above were checked directly. Applicability limit: if a later change exposes the wrapper or its flags to Netsuke end users, this check would then apply and the users guide would need an update.Resolution
None required for this check. Keep the Kani scope-wrapper guidance in docs/developers-guide.md. If a future change exposes user-facing Netsuke behaviour, add the matching entry to docs/users-guide.md and signpost it in the n+1 migration document.
Full details: Developer Documentation
-
Explanation
The pull request meets the Developer documentation check. It documents its changed tooling in
docs/developers-guide.mdand records the Kani wrapper decisions in the 4.2.2 and 4.2.3 ExecPlans. Evidence: - Developer guide: The Kani wrapper section now names the unit, passes--collect, and writes a$capture.statussidecar. It adds subsections on routine versus deferred collection, harvesting evidence, reading a scope'sResult(including theLoadState=loadedprerequisite), and cleaning up a failed scope by exact name. It also records the-okinvestigation, including the limit on what it claims. - ExecPlans: Both 4.2.2 and 4.2.3 carry the updated wrapper examples and a dated revision entry (2026-11-23, issue#1078). The examples were changed in place, which the linked issue requested. Each entry logs the change, and the header and roadmap status are unchanged. - Roadmap and design docs: No new roadmap item is introduced, so no checkbox change is needed. No other design document describes the systemd wrapper, so none is stale. - Decisions: The--collectand deferred-collection decisions are recorded in the guide and ExecPlans. The change is operational and bounded in scope, so an ADR is not required under the check's size-based rule. - Localization: No non-English documentation exists indocs/. Minor gap (non-blocking): the newtest_scope_wrapper_is_verified_before_the_proofscontract pins the existing CI stepmake test-kani-scope-wrapperbeforemake kani-ir. Thekani-smokeparagraph indocs/developers-guide.md(around lines 8700–8720) listsmake kani-irandmake test-kani-mutationsbut omits this wrapper gate. Add the wrapper step to that paragraph so the documented CI sequence matches the enforced one.
Full details: Module-Level Documentation
-
Explanation
The check passes. Every Rust and Python module that this pull request adds or changes carries a module-level docstring. Scope: I checked the eight commits that make up the Kani scope-wrapper work (5c6fa66 to 5256449, based on 4f58b3e). The local
maindiffers from the pull request base, sogit diff main...HEADalso lists unrelated discovery and interpolation files. I did not treat those as part of this pull request. Rust modules (first line is a//!inner doc comment): -tests/kani_scope_wrapper_e2e_tests.rs: crate-root purpose, host prerequisites, and the evidence contract. -tests/kani_scope_wrapper_e2e_tests/evidence.rs: the durable outcome record. It explains that a scope'sResultis not the payload exit status. -guard.rs:ScopeGuardownership and teardown. It names thefinishandDropsplit and links toAppliedPatch. -harness.rs: the documented invocation and naming scheme. -host.rs: prerequisite checks and the strict-mode skip rule. -manager.rs: what a reading means. It namessuper::propertiesas the reader andsuper::guardas the owner of teardown. -properties.rs: thesystemctl showlayer and its single-query rule. -teardown_tests.rsandtimeout_tests.rs: scenario scope, with links to the guard and to the retained-unit rule. Python modules (first line is a triple-quoted docstring): -kani_scope_wrapper_docs_test.py: the document contract, with the Make run command. -kani_scope_wrapper_makefile_test.py: the Makefile half. It explains why the module was split from the docs test. -kani_smoke_scope_wiring_test.py(changed) andkani_proof_scope_test.py(changed): purpose and the ADR and scope relationships. Each docstring states purpose and function. Where the module depends on another component, it names that component. The check does not fail on docstring quality, so no remediation is needed.
Full details: Testing (Unit And Behavioural)
-
Explanation
The check passes. The PR adds behavioural and end-to-end tests for the changed externally observable workflow, and adds contract tests with negative controls for the documented command. Behavioural and end-to-end coverage (Rust,
tests/kani_scope_wrapper_e2e_tests.rsand its six support modules) - The suite runs realsystemd-run --user --scopeunits. It has 13 test functions: 5 in the main file, 5 inteardown_tests.rsand 3 intimeout_tests.rs. - Success, failing payload,pipefailmasking, collected unload, and collected failing status are covered. - Timeout, additive stop grace and journal escalation (SIGKILL) are covered. - Guard teardown is covered for body errors, panics, active scopes, unit-name reuse and concurrent scopes. - The error and panic tests leave the scope failed and retained before injecting the fault. The PR description says this makes the assertion depend on the guard acting. I readteardown_tests.rslines 60–140 and they match that description. Contract tests (Python,tests/workflow_contracts/) -kani_scope_wrapper_docs_test.pychecks every routine example in three documents. It includes negative controls, such astest_the_property_check_rejects_an_unbounded_valueandtest_the_payload_check_rejects_an_outer_pipeline. -kani_scope_wrapper_makefile_test.pychecks the strict-mode export. Its negative control istest_the_strict_export_check_rejects_a_commented_assignment. -kani_smoke_scope_wiring_test.pychecks the gate order. Gaps (not decisive) - The Rust helpersparse_properties,monotonic_microsandmissing_controllerscontain local logic. No direct unit tests exist for them, and no#[cfg(test)]unit blocks exist in the suite. They are exercised only through the end-to-end scenarios. Edge cases, such as property values that contain=, are not tested in isolation. - The suite skips scenarios when prerequisites are missing unless strict mode is set. The Makefile defaults strict mode to 1 and the contract tests pin that default, so this does not weaken the gate. Recommendation (not a failure condition) - Add direct unit tests forparse_properties,monotonic_microsandmissing_controllers. Cover malformed lines, duplicate keys, empty values and missing controllers. Evidence came from the PR diff (origin/main...HEAD), the new test files, and the test function listings. I did not run the suite, as the sandbox does not allow builds.
Full details: Testing (Compile-Time / Ui)
-
Explanation
The check is not applicable to this pull request, so it passes. Evidence: - PR
#1191(leynos/netsuke, head 5256449) changes the Kani scope-wrapper test harness (tests/kani_scope_wrapper_e2e_tests.rsand six support modules), three Python workflow-contract tests,Makefile/tools/kani/proof-scope.toml, and developer and ExecPlan documents. - The Rust changes are runtime integration tests. They drivesystemd-run,systemctl --userandjournalctl. They do not add or change compile-time behaviour. The diff adds no proc-macro, nocompile_failortrybuildtarget, and no newCargo.tomldev-dependency.Cargo.tomlhas notrybuildentry. - The changed output is process status, unit properties and journal text. The suite checks these with explicit semantic assertions, such asResult=timeout,LoadState=loaded, the SIGKILL escalation and the own-prefix failed-unit count. The Python contracts check documented flags and Makefile values. No compile-time or UI output is introduced. - The rule for snapshot tests uses advisory wording ("should be recommended where appropriate"). It sets no explicit failure condition for a missing snapshot. The PR's text outputs also carry targeted assertions. A snapshot recommendation is therefore not a FAIL basis here. Gaps: the sandbox does not run the test suite. This verdict rests on the diff and the file contents, not on a test run.
Full details: Unit Architecture
-
Explanation
Summary: The change makes fallibility, state mutation, dependencies and responsibilities more visible overall. No explicit failure condition of the Unit Architecture check is met. Minor, non-blocking points are listed below. Scope reviewed. The PR's Kani scope-wrapper work sits in
tests/kani_scope_wrapper_e2e_tests.rsand its six support modules. Those areguard.rs,harness.rs,manager.rs,properties.rs,evidence.rsandhost.rs. Two further modules,teardown_tests.rsandtimeout_tests.rs, hold the scenarios. The Python contracts were checked only at their headers. Thegit diff origin/main...HEADstat lists many unrelated files, such as canonical-value and config-discovery tests. Those were not assessed. This may reflect a stale localorigin/main. Evidence supporting PASS: - Query/command separation.properties.rsscope_snapshotandscope_lifetimeare read-only. They issue a singlesystemctl showquery. Commands are separate:guard.rsteardown(stop and reset by exact name) andmanager.rsremove_capture. - Explicit fallibility. Environmental failures returnResultwith context. Examples arescope_property,scope_properties,monotonic_microsandsystemctl_verb. TheJournalenum separatesReadfromUnavailable, so an unreadable journal is not reported as empty.evidence.rsRead<T>keeps capture read failures visible, andcapture_available()surfaces them. - Visible teardown semantics.ScopeGuard::finishreturns a fallible result.Droplogs and does not raise, which is documented.with_unitkeeps the body's error and attaches the capture path. - Visible dependencies and ambient state.managed_commandclears the environment and restores only named variables. It carries an#[expect(clippy::disallowed_methods)]with a reason.strict_modeis the single documented environment read.Retention::{Collect, Retain}makes the collection policy an explicit argument. - Responsibility split. The former 802-line monolith is divided by concern. Host probing, command construction, manager reads, evidence harvesting, teardown and scenarios each have their own module. - Tests reflect boundaries. Teardown scenarios exercise the guard through its realwith_unitentry point. They assert observable manager state rather than mocked internals. The E2E suite exercises the realsystemd-runandsystemctlboundary, which the check asks for. Non-blocking observations (minor, do not change the verdict): 1.host.rsrustix_uid()maps a failedid -utou32::MAXwithunwrap_or. This hides a failure. Return aResultand propagate it, so the diagnostic names the real cause. 2.manager.rsjournal_extract()is a query path, but it runsjournalctl --syncand discards its result withdrop(...). The comment documents this as a best-effort barrier. Name it as an explicit barrier step, or move it to the harvest boundary, so the query remains read-only in name and type. 3.manager.rswait_for_terminal()mixes polling with lifetime retrieval. Separate the wait from the lifetime read, or rename it so the return value is visible. 4.unit_name()and the wait loops readSystemTime::now()andInstant::now()directly. This is confined to the test harness and does not drive a decision about production state. Accept it, or add a small clock seam if the harness grows.
Full details: Domain Architecture
-
Explanation
The Domain Architecture check does not apply to this pull request, so it passes. Evidence: - PR
#1191targetsmainfromissue-1078-collect-transient-kani-scopes-and-guarantee-teardown-after-evidence-capture. The provider-reported author isleynos. - Against the merge base4f58b3e, the changed files are all test and tooling artefacts:tests/kani_scope_wrapper_e2e_tests.rsand its six support modules, fourtests/workflow_contracts/*.pycontract tests, andtools/kani/proof-scope.toml. Docs, CHANGELOG and ExecPlans also change. - The diff touches no file undersrc/. No domain model, command, repository, or adapter code changes. The changes only add--collect, a teardown guard, and test scenarios for systemd transient scopes. These sit in test and harness code outside the domain model. The check's concerns (leaking transport, storage, or vendor details into domain code) cannot arise from these changes. Non-blocking note: the Rust test harness wraps systemd through thesystemd-runCLI andsystemctl. That is infrastructure, and it stays in the test layer. It does not entersrc/.
Full details: Observability
-
Explanation
The change alters operational behaviour only for the local Kani scope wrapper and its test harness. It does not touch a production service. The observability it adds or keeps is adequate for this scope. Evidence gathered on the checked-out head (5256449): - Diagnostics for failed or timed-out runs.
docs/developers-guide.md(around lines 8177–8320) now sets a named unit, passes--collect, writes a$capture.statussidecar with the caller status, and writes a bounded journal extract (journalctl ... -n 40 > "$capture.journal"). It also waits forLoadStateto leaveloadedbefore reading the journal, so the extract includes the stop-time entries. This keeps the outcome durable after collection. - Failure-boundary logging in teardown.tests/kani_scope_wrapper_e2e_tests/guard.rs(lines 123–143) logs teardown failures aterrorlevel. The log carries the stableunitfield and the error. It names the manual recovery step (systemctl --user reset-failed). TheDroppath logs without raising, so a cleanup failure does not hide the original defect. - Operator recovery. The guide documents prefix-scoped recovery after a runner kill. It also states thatreset-faileddoes not stop an active unit, which prevents a misleading recovery step. - ReadingResult=. The guide explains that an unloaded unit reports default properties and that a payload exit status is not the scopeResult. This guards maintainers against misreading the signal. Non-applicable parts of the check: - Metrics. The change does not alter service throughput, latency, queue depth, retry behaviour, or externally observable reliability. A local test harness has no metric surface, so none is required. - Alerts. No alert is added or changed. Nothing in this change is an alertable production failure mode. - Tracing. The wrapper crosses a process boundary throughsystemd-run. The harness records the caller status, captured output and journal, which serve as the diagnostic trail for that boundary. Adding spans to a developer test harness is not required by the check. Remaining gap, not a failure: the wrapper emits no log line at launch or on a successful stop. The sidecar, capture file and journal extract cover this. The check does not require routine success logging for this tool.
Full details: Testing (Property / Proof)
-
Explanation
Summary: This PR introduces invariants over inputs and state transitions. It adds no property test, bounded model check or proof for them. The new tests are example-based systemd scenarios. The check calls for a property test or proof recommendation in this case, so the check fails. Evidence gathered (repository checked out at PR head 5256449, diff against merge-base 4f58b3e): - The diff adds no
proptest,prop_assert,#[kani::proof], Hypothesis, fast-check, CrossHair or Verus code. The PR touches 17 files, all example-based or contract checks. -tests/kani_scope_wrapper_e2e_tests/properties.rs(new) contains pure functions over arbitrary text and numbers: -parse_properties(lines 88–93) splits each line at the first=. Its contract depends on values that may contain=, and on lines with no=. -monotonic_micros(lines 161–169) rejects empty and0values and parsesu64. -scope_lifetime(lines 142–153) computesdeactivated.saturating_sub(activated). That subtraction is an ordering invariant over timestamps. No unit tests or property tests cover these functions in the file. -tests/kani_scope_wrapper_e2e_tests/guard.rs(new) defines aScopeGuardstate machine. It has anarmedflag (lines 59–68).finish(lines 91–96) andDrop(lines 139–143) both reach teardown.teardown(lines 104–121) branches onis_busyandfailedafter a fresh read. The invariant is that teardown runs at most once and never on an unloaded unit. The PR checks this with specific scenarios (injected error, injected panic, collected scope), not over a range of transition sequences. -tests/kani_scope_wrapper_e2e_tests/harness.rs(lines 97–115) generates unit names from pid, aOnceLockstamp and anAtomicU64sequence. The invariant is uniqueness across scenarios and threads. The PR checks it with 13 named scenarios and three concurrent cases, not with a property over sequences. -proptest = "1.11.0"is already a dependency (Cargo.toml:201). Other suites use it, for exampletests/config_discovery_e2e_tests.rsandtests/ast_tests/string_or_list.rs. The project therefore has the tooling to add these tests. Why the invariants are not covered by a parameterized table: The input space ofparse_propertiesand the transition space of the guard are not small or complete. A reader cannot audit them from a handful of examples. The E2E scenarios also require a live user systemd manager, so they do not exercise these functions in isolation. Not claimed: The E2E scenarios are not shown to be wrong. The PR's runtime evidence is not disputed. The finding concerns only missing property-based or proof coverage of the new invariants. Standing failure: The prior FAIL had no recorded details, so there is no specific claim to refute. This verdict reaches the same outcome for the reasons above.Resolution
Add property tests for the new invariants. Use the existing
proptestdependency. 1. Intests/kani_scope_wrapper_e2e_tests/properties.rs, add aproptest!block forparse_properties. Generate arbitraryName=valuelines, including values that contain=, and assert that the name is the text before the first=and that the value is the trimmed remainder. Add a case for lines without=, which must be dropped. 2. In the same file, add property tests formonotonic_microsandscope_lifetime. Assert that0, empty and non-numeric values fail. Assert that a deactivation stamp before the activation stamp gives a zero lifetime, not a panic or wrap-around. 3. Intests/kani_scope_wrapper_e2e_tests/harness.rs, add a property test forunit_name. Generate many names across sequences of calls and assert that all names are distinct and that each name starts withUNIT_PREFIX. 4. ForScopeGuard, extract the teardown decision fromteardowninto a pure function over a snapshot (Option<ScopeSnapshot>) that returns the action to take. Add a property test over generated snapshot sequences. Assert that astopis never issued for an unloaded unit and thatreset-failedis issued only for afailedunit. Keep the systemd scenarios for the real-manager behaviour. 5. Recommend a bounded model check or Verus proof only if the guard'sarmedstate machine needs stronger guarantees than the property test provides. Do not add one forparse_properties, which the property test covers.
Reviewer's GuideConfigurationAdd the scope-wrapper support directory to the Kani proof-scope infrastructure inputs so the refactored suite remains covered by the proof-scope contract.
DocumentationUpdate the developer guide and both Kani ExecPlans to use named, collected routine scopes and document the evidence, result-reading, and cleanup contract.
TestsRefactor the scope-wrapper end-to-end suite into focused helpers and scenarios, adding durable evidence harvesting, retention choices, guarded teardown, and coverage for collection, timeout, error, panic, concurrency, and unit reuse.
Add workflow contract checks that require the scope-wrapper suite before Kani proofs and keep the published wrapper examples, durable evidence guidance, and strict-mode wiring synchronized.
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
The second CodeRabbit pass raised five findings; all five held up. The significant one is a defect in the timeout scenarios themselves. `wait_for_terminal` started its clock after `run_scoped` returned, but `systemd-run --scope` blocks only until the *launcher* dies, which for the piped payload happens at the runtime deadline. Measured on the reference host: a 2s cap with a 3s grace has a true lifetime of 5.07s, yet the caller returns after 2.27s and the function reported 2.80s — the grace alone. An additive grace and a nested one cannot be told apart from that figure, which is exactly the property those tests exist to prove. The lifetime now comes from the manager's own `ActiveEnterTimestampMonotonic` and `InactiveEnterTimestampMonotonic`, which recorded the full 5.08s. `prerequisites_met` raised on an empty `cgroup.controllers` instead of reporting a missing prerequisite, so such a host failed every scenario rather than skipping as documented. The evidence harvest aborted when the capture was absent, discarding the caller's stderr, the journal and the manager snapshot — the three things that explain why no capture exists. It now represents an unreadable capture explicitly, keeps every other read, and records the caller's stderr. The documented recovery still reset without stopping. A scope left active by a runner kill is not failed, so `reset-failed` returns success and leaves the payload running; it also never waits on `failed`, which is where a stop that exhausts `TimeoutStopSec` lands. The sequence now stops by exact name, waits for `inactive` or `failed`, and resets only a unit that is still loaded and failed. Co-Authored-By: Claude Code <noreply@anthropic.com>
Whitaker's `module_max_lines` reported `manager.rs` at 414 lines, over the 400-line limit. The lifetime helpers pushed it across; the module had been 373 lines at the previous head. The property layer moves to `properties.rs`: reading `systemctl show`, parsing `Name=value` output, deciding that an absent unit is not evidence, and deriving the scope's lifetime from the manager's timestamps. That is a coherent subject — how to read the manager without being fooled by its defaults — and it is the layer a future scenario would extend. `manager.rs` keeps what a reading *means*: whether a unit is busy, when to stop waiting, and the capture and journal reads that outlive the unit. It re-exports the three property functions its callers use, so the rest of the suite still names one module for the manager's state. Co-Authored-By: Claude Code <noreply@anthropic.com>
Seven findings, all verified before acting. Two were defects in the harness. `run_scoped` and `run_without_pipefail` inherited the caller's environment, and bash imports `SHELLOPTS` at startup: measured, an exported `SHELLOPTS=pipefail` makes the no-pipefail control report 1 instead of 0, which is the one thing that control exists to distinguish. Both now build through one helper that clears the environment and restores only `XDG_RUNTIME_DIR`, `DBUS_SESSION_BUS_ADDRESS` and `PATH`. The additive-grace test asserted only `lifetime > RUNTIME_CAP`, which a grace shortened to 1s satisfies at about 3s. It now requires the sum less half the grace, which rejects both a 3s shortened-grace lifetime and a 2s nested one while accepting the real 5s. The prerequisite check read the hierarchy root's `cgroup.controllers`, which lists what the root offers, not what the user manager's own cgroup enables. Those differ on the reference host, so the check could pass while every scope launch failed. It now reads the manager's own cgroup, requiring `cpu`, `memory` and `pids` in both `cgroup.controllers` and `cgroup.subtree_control`. The documented recovery reconstructed a unit name from a prefix and the scenario, but a name also carries a stamp and a sequence, so the reconstruction addressed a different unit and the stop did nothing. It now takes each listed name verbatim. The documented wrapper swallowed the verifier's status: the last command was the `printf` that writes the sidecar, so the snippet reported 0 whenever the sidecar was written. Measured, then fixed with a trailing `(exit "$caller_status")` in the guide and in both ExecPlan examples. Two contract gaps: the docs check matched property *names*, so `MemoryMax=infinity` passed while removing the cap; and the Makefile check matched the strict-mode export as a substring, so a commented-out assignment passed. Both now check the effective thing — documented values, and the export on an executable recipe line — each with a negative control proving the check fires on the weakening it exists to catch. Co-Authored-By: Claude Code <noreply@anthropic.com>
Pylint's `max-module-lines = 400` reported `kani_scope_wrapper_docs_test.py` at 435 lines. The previous commit added the executable-recipe and unbounded-value checks, which pushed it across. The Makefile half moves to a new `kani_scope_wrapper_makefile_test.py`: the strict-mode default, the export as an executable recipe line, and the negative control that proves a commented-out assignment is rejected. That is a coherent subject — what makes the lane meaningful rather than green by absence — and it is separate from the document contract, which stays where it was. The two modules are 330 and 120 lines. Both pass plain Pylint 4.0.9, the df12 house lints at 10.00/10, and Ruff. Co-Authored-By: Claude Code <noreply@anthropic.com>
Four findings, each verified against the system before acting. The prerequisite check required `cpu`, `memory` and `pids` to be enabled in the user manager's `cgroup.subtree_control`. systemd.resource-control(5) is explicit that this is wrong: "There is no need to explicitly enable a cgroup controller for a unit. systemd will instruct the kernel to enable a controller for a given unit when this unit has configuration for a given controller", and the user manager repeats that logic for its children. So `CPUQuota=` and `MemoryMax=` on the scope are what enable them. Requiring them pre-enabled would have rejected a capable host and skipped every scenario — the exact failure the prerequisite check exists to prevent. The check still requires the controllers to be *offered* in the manager's own `cgroup.controllers`, which is the delegation question. The journal assertion accepted `Stopping timed out` plus `SIGKILL`, and systemd's `Stopping timed out. Skipping SIGKILL.` — emitted when `SendSIGKILL` is disabled — contains both while proving no escalation happened. Measured on the reference host, the positive message is `Stopping timed out. Killing.`, followed by `with signal SIGKILL`; the check now requires that sentence and that phrase. The documented wrapper was not `set -e` safe: a bare failing command terminates the invoking shell before the sidecar is written, leaving no record or a stale one. Measured. It now initializes `caller_status=0` and captures failure with `|| caller_status=$?`, in the guide and both ExecPlan examples. The Makefile contract accepted an export whose continuation backslash had been dropped, which Make runs in a separate shell so the command never sees it. The check now joins continuation lines and requires the export to land in the same statement as the test command, with a negative control that removes only the backslash. Co-Authored-By: Claude Code <noreply@anthropic.com>
Three findings from the fifth review, each about a check that could pass while the thing it describes was not true. `journalctl --sync` establishes journald's storage guarantee, and the reference host refuses it for the user journal under Varlink. The code treated that refusal as harmless and read once, so a scenario asserting on the stop entries could see the earlier entries only. The journal now records whether the sync succeeded, and a scenario that needs specific lines reads again to a bounded deadline. The deadline bounds the waiting, not the claim: an entry that never appears still fails. The docs snippet polled for collection and then read the journal, which waits for the unit to go but says nothing about journald having flushed it. It now syncs explicitly and documents the refusal path, including the measured `Failed to connect to Varlink socket: Permission denied`. The document contract matched property values against whole-block text, so an example running `-p MemoryMax=16G` with a comment quoting `8G` passed. The values are now read from the parsed `-p` arguments, with the payload cut off first; a negative control proves a comment cannot stand in for the setting. The document contract crossed the 400-line Pylint ceiling, so the block reader — fences, wrapper selection, payload extraction, argument parsing — moves to `kani_scope_wrapper_blocks.py`. The two contracts are 311 and 169 lines. Co-Authored-By: Claude Code <noreply@anthropic.com>
Seven findings, all measured before acting. Three were documentation defects. The recovery snippet assigned `prefix=netsuke-kani-wrapper-<pid>`, which is a Bash syntax error — `<` starts a redirection — so the listing never ran; it now shows a quoted numeric placeholder. The harvesting snippet ran `journalctl --user --sync` bare, which under `set -e` ends the snippet before it writes anything, and then read the journal once even though the prose requires a bounded re-read; both are now in the snippet, and the prose explains reading for the entry a given claim depends on. Two were the same class of vacuity the fifth round fixed, in the checks themselves. Options were matched against whole-block text, so a wrapper omitting `--collect` passed if its payload echoed the string; they are now read from the wrapper's own argument tokens, with a negative control for the payload case. The Makefile check accepted `VAR=x; cargo ...`, which sets a shell variable and exports nothing — measured: the prefix form appears in the child environment, the semicolon form does not. It is now required to reach the command's environment, with a control for the unexported shape. The fence scanner ignored `~~~` blocks and accepted a shorter closing fence, so a document could gain an unchecked tilde-fenced example. It now follows the CommonMark rules for both fence characters, closing length and trailing content. On the Rust side, a claim about an *absence* — that no failure line was written — was checked before the journal could have stopped growing. That test now waits for two identical reads. The panic test removed neither its unit's capture nor the file: `Drop` cannot, and the passing path never did, so every passing run left one behind. Measured before the fix at 14 retained `panic-teardown` captures; after it, a full suite run adds nothing. Co-Authored-By: Claude Code <noreply@anthropic.com>
Four findings from the seventh review, each about a check that could pass while the thing it describes was false. The documented harvest loop ended with a `sleep`, so a run whose expected journal entry never arrived still exited 0 — a bounded wait that says nothing instead of failing. It now ends with a `grep` that fails. The collected-failure test asserted an absence in the journal: that no "Failed with result" line was written. Without a successful `--sync` that absence is unprovable — a partial extract looks exactly like a complete one that never had the line — and it was redundant besides, because `Result=` read from the still-loaded unit answers the same question from the manager's own record. The assertion and its stability helper are gone, and the developer guide now says not to make that claim from the journal at all. The argument tokeniser kept comment lines, so a block whose comment quoted `-p MemoryMax=8G` while the command omitted it would satisfy the cap check. Whole-line comments are now dropped before tokenising. The Makefile export check accepted `NAME=value && cargo ...`. Measured: the prefix form appears in the child environment and the `&&` form does not, so it is now rejected, with a negative control. Also measured: with a clean /tmp the suite leaves zero capture files and zero failed units, which is what the previous commit's panic-test cleanup was for. An earlier "6 leaked" reading was an artifact of a second suite run overlapping the first. Co-Authored-By: Claude Code <noreply@anthropic.com>
Four findings from the eighth review, all measured first. The documented extraction required the SIGKILL escalation entry after *any* non-zero status. That is wrong for an ordinary verifier failure: a payload that exits 7 leaves a scope the manager collects as a success, so its journal has no escalation entry, and the snippet would have reported a wrapped verifier failure as a harvest fault. The timeout-shaped wait is now a separate block, and the text says which claim needs it. The documented recovery fell through its polling bound and reported success while the workload could still be running. It now checks the final state and exits non-zero unless the unit reached a terminal one. Two contract checks accepted text that only looked like the thing they require. A payload printing `set -o pipefail` satisfied the pipefail check without enabling it, so the payload's statements are now split and compared; and an export quoted in a trailing comment satisfied the Makefile check, so inline comments are stripped before the statement is examined. Each has a negative control for its shape. Regenerated `typos.toml` is unchanged, and `make typecheck` — which the previous round's report flagged as unrun despite covering the changed Python — passes: `ty check` clean, then `cargo check` over the workspace. Co-Authored-By: Claude Code <noreply@anthropic.com>
There was a problem hiding this comment.
Gates Failed
Enforce critical code health rules
(2 files with Bumpy Road Ahead)
Enforce advisory code health rules
(5 files with String Heavy Function Arguments, Code Duplication)
Our agent can fix these. Install it.
Gates Passed
4 Quality Gates Passed
Reason for failure
| Enforce critical code health rules | Violations | Code Health Impact | |
|---|---|---|---|
| kani_scope_wrapper_makefile_test.py | 1 critical rule | 9.24 | Suppress |
| kani_scope_wrapper_blocks.py | 1 critical rule | 9.84 | Suppress |
| Enforce advisory code health rules | Violations | Code Health Impact | |
|---|---|---|---|
| harness.rs | 2 advisory rules | 9.10 | Suppress |
| manager.rs | 2 advisory rules | 9.10 | Suppress |
| kani_scope_wrapper_makefile_test.py | 1 advisory rule | 9.24 | Suppress |
| guard.rs | 1 advisory rule | 9.69 | Suppress |
| properties.rs | 1 advisory rule | 9.69 | Suppress |
Quality Gate Profile: Pay Down Tech Debt
Install CodeScene MCP: safeguard and uplift AI-generated code. Catch issues early with our IDE extension and CLI tool.
| def _single_statement_with(recipe: list[str], needle: str) -> str | None: | ||
| r"""Return the shell statement containing ``needle``, continuations joined. | ||
|
|
||
| Make hands each recipe line to its own shell, and a trailing backslash is | ||
| what joins two lines into one invocation. This models that: consecutive | ||
| executable lines are concatenated while the previous one ends in `\\`. | ||
|
|
||
| Returns | ||
| ------- | ||
| str | None | ||
| The joined statement containing ``needle``, or ``None`` when no | ||
| executable statement contains it. | ||
| """ | ||
| statements: list[str] = [] | ||
| current = "" | ||
| for line in _executable_lines(recipe): | ||
| stripped = _strip_inline_comment(line).rstrip() | ||
| continued = stripped.endswith("\\") | ||
| current += stripped.removesuffix("\\") | ||
| if not continued: | ||
| statements.append(current) | ||
| current = "" | ||
| if current: | ||
| statements.append(current) | ||
| for statement in statements: | ||
| if needle in statement and _assigns_to_command(statement, needle): | ||
| return statement | ||
| return None |
There was a problem hiding this comment.
❌ New issue: Bumpy Road Ahead
_single_statement_with has 2 blocks with nested conditional logic. Any nesting of 2 or deeper is considered. Threshold is 2 blocks per function
Summary
Closes #1078.
Every local Kani run happens inside a
systemd-run --user --scopewrapper, andthat wrapper was leaving a failed transient unit behind whenever a run did not
finish cleanly.
CollectModedefaults toinactive, which unloads a scope thatsucceeds but keeps a failed one loaded until someone resets it. A scope
stopped at its runtime deadline, killed by the OOM killer, or refused a
resource property therefore accumulated, one run at a time, until
systemctl --user is-system-runningreporteddegraded.The suite made it worse.
tests/kani_scope_wrapper_e2e_tests.rscalledreset_failedonly on the normal path, so an assertion failure, an early?return or a panic skipped the cleanup and left precisely the failed units the
issue reports.
Two changes close both halves:
--collect(CollectMode=inactive-or-failed), so afinished unit unloads whether it succeeded or failed.
ScopeGuardcreated before the unit islaunched. The guard tears the unit down from
Dropas well as from afallible
finish, always by exact name, never with a glob or a blanketreset.
Collection is deferred exactly where it must be: a scope's own
Resultisunreadable once the unit unloads, so the timeout scenarios keep their unit
loaded, read
Result=timeoutand the SIGKILL escalation, and reset itafterwards.
The
-okanomalyTwo
-okunits were among seven retained wrapper scopes reported failed on2026-11-01 even though their payloads exited zero. The investigation, recorded
in full in the developers' guide, establishes two things and declines to claim
a third:
Result. A payload that exits 7leaves a scope the manager collects as a success, because a scope has no main
process and nothing maps an exit status onto
Result=.Result=timeoutscope, because theruntime deadline covers the whole control group and can fire while
teeandthe rest of the pipeline are still tearing down. Driving
RuntimeMaxSecdownto 5 ms reproduced it on the reference host: several runs reported caller
status 0 while the unit was retained as failed with
Result=timeout.What is not claimed is what those particular units recorded. They had been
reset before this work started and the user journal no longer covers that date,
so their individual
Result=values are unrecoverable. The name-okis thescenario, not evidence about the scope. No wrapper flag was at fault. Routine
scenarios now use a wide runtime cap and assert no timing bound, which removes
the reachable cause, and the suite retains a failed unit long enough to report
its
Result=if it ever happens again.What changed
tests/kani_scope_wrapper_e2e_tests.rsplus six support modules):unique names from pid, a
OnceLockstart stamp and anAtomicU64counter;Retention::{Collect, Retain}; aScopeGuardwith falliblefinishand alogging-only
Drop; a durable outcome harvest (caller status, capture pathand contents, unit identity, bounded journal, and a
Resultonly from aloaded unit); and a read-only own-prefix failed-unit query.
names the runtime limit and the SIGKILL), a collected
exit 7, an injectedbody error, an injected panic, a still-running scope with launcher reaping,
name reuse (a second
--unitunder one name only works if the first reallyunloaded), and three concurrent scenarios.
--collect, writes a/tmp/<capture>.statussidecar, and is followed by abounded journal extract. Four new subsections state the evidence contract:
routine versus deferred collection, harvesting evidence from a routine run,
reading a scope's
Result, and cleaning up a failed scope — includingprefix-scoped recovery after a runner kill.
<kani-command>template carry--collectand a named unit, with a datedrevision entry in each. Historical records are otherwise untouched.
kani_smoke_scope_wiring_test.pynow requiresmake test-kani-scope-wrapperbeforemake kani-irunder the same proofgate. A new
kani_scope_wrapper_docs_test.pyholds every routine example inall three documents to the documented flags, caps and
nice, requiresset -o pipefailandteeinside thebash -cpayload, and pins theMakefile's
KANI_SCOPE_WRAPPER_STRICT ?= 1and its export. The proof scope'sinfrastructure list gains the suite's new support directory.
Runtime enforcement is unchanged:
RuntimeMaxSec,TimeoutStopSec,CPUQuota=200%,MemoryMax=8G,MemorySwapMax=0,TasksMax=96,IOWeight=20,/usr/bin/nice -n 15,teeinside the scope and the innerset -o pipefailare all preserved, and a contract now fails if any of them isdropped from the documentation.
Verification
Focused suite, in strict mode:
Afterwards the read-only own-prefix query is empty:
The wider gate set, on the pushed head
5256449b3:make check-fmtmake lintmake typecheckty 0.0.74clean;cargo check --workspace --all-targets --all-featurescleanmake doc-coveragemake testmake test-workflow-contractsmake markdownlinttypos.tomlunchanged; 241 files, 0 issuesmake test-kani-scope-wrapperThe 11 skipped tests are the tree's
#[ignore]set: child-process workers andKani-mutation targets gated behind their own targets. Logs are under
/tmp,suffixed with the branch name.
Review rounds
Three CodeRabbit passes ran against successive heads, and each one found
something. The substantive corrections, all measured before being acted on:
wait_for_terminalstarted its clock after
run_scopedreturned, butsystemd-run --scopereturns when the launcher dies — at the deadline, not at the end of the
stop. A 2 s cap with a 3 s grace has a true lifetime of 5.07 s, and the
test reported 2.80 s: the grace alone. An additive grace and a nested one
were indistinguishable from that figure, which is the one property those
tests exist to prove. The lifetime now comes from the manager's own
ActiveEnterTimestampMonotonicandInactiveEnterTimestampMonotonic.reset-faileddoes not stop an active unit. Measured: it returns 0 andleaves the payload running. The documented recovery now stops by exact
name, waits for
inactiveorfailed, and resets only a unit stillloaded and failed.
lifetime > RUNTIME_CAPaccepted a grace shortened to 1 s. It now requires the sum less half the
grace, which rejects both a shortened and a nested grace.
nothing, because a successful scope is collected either way. Each now
leaves its scope failed and retained before injecting the error or panic.
SHELLOPTS=pipefailmade the no-pipefail control report 1 instead of 0 —the one thing that control distinguishes. Both builders now clear the
environment and restore only what reaches the user manager.
than values (so
MemoryMax=infinitypassed), and the strict-mode export asa substring (so a commented-out assignment passed). Both now check the
effective thing, each with a negative control proving it fires.
Two findings were not actionable as written and are not silently dropped. One
claimed
journalctl -o catprints-- No entries --for an empty journal;measured, it prints nothing and exits 0, so the skip path already fired — the
explicit
Journalrepresentation was kept anyway because it makes thedistinction auditable. The other claimed
reset-failedleaves an active unitrunning, which is true, but the guard already stopped before resetting; only
the documentation was wrong.
Closes #1078
References
TimeoutStopSecand leavesteeoutside the scope #769 (theTimeoutStopSecfix this builds on)systemd-run(1)--collectsystemd.unit(5)CollectMode=🤖 Generated with Claude Code