Skip to content

fix(check): typed analysis_worker_stopped refusal when the check worker dies (#11116) - #11289

Merged
EffortlessSteven merged 4 commits into
mainfrom
claude/fix-11116-typed-worker-failure
Oct 31, 2026
Merged

EffortlessSteven merged 4 commits into
mainfrom
claude/fix-11116-typed-worker-failure

Conversation

@EffortlessSteven

Copy link
Copy Markdown
Member

Governing issue or accepted claim: #11116
Acceptance delta (one sentence): a ripr check analysis worker that dies before producing a result now refuses with the typed analysis_worker_stopped identity (route analysis/worker-stopped) and a readable diagnostic instead of an untyped message (residual (a)).

What changed

  • New CheckFailureKind::AnalysisWorkerStopped + CoreError::analysis_worker_stopped; the Disconnected branch of run_with_budget (check_budget.rs) returns it. Exit and envelope behavior follow the other typed check failures; no findings, never clean or exposed.
  • The diagnostic says the worker stopped (likely a panic, message printed above on stderr), that no result exists, and to re-run, report with the panic hook output, and narrow the diff/base range. The panic payload is not echoed.
  • ripr pilot (same string in pilot.rs) shares the wording and points at --max-seams; it stays a plain pilot error string, not a check envelope.
  • Docs: OUTPUT_SCHEMA identity table, RIPR-SPEC-0241 table/count/code references; changelog fragment.

Proof

  • check_budget::tests::panicking_worker_refuses_with_the_typed_worker_stopped_failure drives the production run_with_budget with a worker that unwinds (resume_unwind); on old code the kind is None and the test does not hold. Envelope test extended in limited_check for the new identity/route. Pilot unwind test added.
  • Passed locally: focused cargo test -p ripr --lib filters, check-output-contracts, check-identity-registry, check-doc-artifacts, cargo xtask precommit (exit 0).
  • Not established: goldens check was INCOMPLETE locally (environment gap: fixture dependency preparation for owner_return_pin_fallible_literal); hosted CI owns it. Hosted CI not requested; independent review pending.

Generated by Claude Code

…r dies (#11116)

A ripr check (or pilot) analysis worker that stops before producing a result
now yields the typed analysis_worker_stopped refusal (analysis/worker-stopped)
with a readable diagnostic instead of an untyped message.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YVdGzUDFA3cS1NVbf3sPQL
@gemini-code-assist

Copy link
Copy Markdown

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

@coderabbitai

coderabbitai Bot commented Oct 30, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

  • Ask an admin to enable usage-based reviews

Open in CodeRabbit

Reviews can continue after your included limit without a manual trigger. An admin must approve usage-based billing.

Next included review available in 49 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available. Your 148 included PR review attempts over the past 7 days set your current allowance at 1 review per hour.

Learn how review limits work.

Review configuration:

Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: ASSERTIVE
  • Plan: Essentials
  • Run ID: ef435a4f-a462-4eaf-9a94-2ece123de4b5
Commits

Reviewing files that changed from the base of the PR and between 018a7d8 and fb456c8.

Files selected for processing: 7
  • changelog.d/11116-typed-worker-failure.md
  • crates/ripr/src/cli/commands/check_budget.rs
  • crates/ripr/src/cli/commands/pilot.rs
  • crates/ripr/src/core_error.rs
  • crates/ripr/src/output/limited_check.rs
  • docs/OUTPUT_SCHEMA.md
  • docs/specs/RIPR-SPEC-0241-check-json-refusal-envelope.md
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verification questions

  • Confirm the scoped scan does not establish that no other analysis worker disconnect paths exist or require equivalent typing.
  • Confirm the new tests stop at CoreError and rendered-envelope levels; no changed test directly exercises the complete CLI's exit code, stdout document, stderr diagnostic, and empty findings.
  • Confirm the limited_check change is an identity-mapping unit case, not a full CLI-level proof of the newly promised refusal envelope behavior.
  • Confirm the new panic-based tests exercise production timeout/disconnect wrappers, but do not verify every machine-readable renderer or downstream exit-code adapter.
  • Confirm the shared pilot diagnostic says “the panic message is printed above on stderr,” although the pilot path is not documented as guaranteeing a panic hook or panic payload.

Refuted

  • The new test could pass without exercising the production disconnect route because it might only test a helper or synthetic error.; refuted because: The test calls run_with_budget with a worker that unwinds, so channel disconnection occurs through the production receiver boundary; it then asserts the typed kind, identity, route, diagnostic text, and payload non-disclosure.
  • The worker-stop condition could represent a resource exhaustion or denial-of-service condition that requires a security finding.; refuted because: The diff classifies an already-existed worker termination as a refusal; it does not introduce an unbounded allocation, attacker-controlled recursion, or a new panic trigger. It does not address the root cause of a panic, so robustness of the underlying worker remains residual operational risk.
  • The worker-stopped branch could retain stale length or backing-store state from a partially produced result.; refuted because: The receive branch is entered only when the sender is disconnected without a result; the patch constructs a typed CoreError and does not read or reuse a result buffer.
  • The new error identity introduces a lifetime, aliasing, or unsafe native-contract hazard.; refuted because: The changed path uses safe Rust channel result handling and owned String/CoreError values; there is no unsafe block, raw pointer, borrowed callback state, or result payload retained after disconnect.
  • Sharing worker_stopped_detail between check and pilot creates an inappropriate coupling of pilot to check's typed refusal contract.; refuted because: The helper returns only diagnostic text and accepts command-specific scope guidance; typed CoreError construction remains in check_budget, so pilot keeps its plain error boundary.

Evidence gaps

  • The PR claims the worker-stopped result “carries no findings” and is never exposed, but the packet does not include the scheduled cargo-test receipt to verify every machine-readable check renderer rejects it identically.
  • Model proof intent was rejected by deterministic validation.

Copy link
Copy Markdown
Member Author

Required is red on b499afc, but not from this PR. Golden output contracts fails on one fixture, python_trailing_whitespace_in_multiline_string [human.txt], one line:

  • expected: Verify command: python -m pytest tests/test_q.py::test_build_query (high)
  • actual: Verify command (Bash): (cd -P -- <cwd>/fixtures/.../input && python -m pytest ...)

This PR touches none of that. The fixture was added by #11210 after main moved every other python fixture to the Bash form, so main's golden is stale and red too.

I've started a one-line re-bless PR against main. Once it lands I'll merge main into this branch and re-apply merge-ready. The independent review of this head found no defect; the bot review is advisory and its questions are covered by the reviewer's reading.


Generated by Claude Code

Copy link
Copy Markdown
Member Author

Required is red on 5664bf6 again, and again not from this PR. Repository policy preflight fails in check-user-text:

  • golden-human discriminator: 3264 lines against a ceiling of 3255
  • golden-human seam: 594 lines against a ceiling of 593

This PR changes no golden or fixture. The ceilings were set by #11321 at 03:15Z and goldens landing on main since have outrun them. Main's own run had not finished that step when I checked, so "main is also red" is likely but not confirmed. I have asked the main-health owner to fix the baseline on main (raise the two ceilings, or reword the new goldens). Once that lands I'll merge main in and re-apply merge-ready. I'm not bundling an unrelated baseline bump into this PR.


Generated by Claude Code

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verification questions

  • Confirm the change was scoped to the check and pilot timeout wrappers visible in the diff; the review did not establish broad coverage of other analysis-worker disconnect or early-exit paths.
  • Confirm changed coverage exercises the production disconnect boundary but not the complete CLI observable contract (exit code, stdout refusal document, stderr diagnostic, and empty findings).
  • Confirm crates/ripr/src/cli/commands/pilot.rs:1047 — Avoid unconditionally promising that “the panic message is printed above on stderr.” A disconnect does not itself prove a panic hook ran, and this test injects resume_unwind without capturing hook output. Use wording that reports the worker stopped and advises attaching panic-hook output if available.
  • Confirm the added tests prove the core error identity and one rendered-envelope mapping, but not the complete CLI contract of nonzero exit, machine-readable stdout, stderr diagnostic, and empty findings.
  • Confirm the repository-wide completeness of the new identity cannot be established from the seven-file diff and available lane evidence.
  • Confirm the changed limited_check test proves identity/route rendering only, not the full CLI refusal envelope.
  • Confirm the shared pilot diagnostic claims a panic message was printed on stderr, but its test uses resume_unwind and does not establish that pilot guarantees panic-hook output.
  • Confirm the check panic test reaches the production disconnect branch but does not prove the complete CLI refusal contract.
  • Confirm the shared diagnostic states that a panic message is printed above on stderr, but the pilot path does not itself guarantee a panic hook or payload.

Refuted

  • The new limited_check test proves the complete machine-readable refusal envelope.; refuted because: It proves identity/route rendering only; it does not establish CLI exit behavior, stdout/stderr separation, or empty findings. This objection remains applicable but is captured as a medium test gap rather than a claim of full proof.
  • A worker disconnect could leave a stale active view or represent a resized, detached, or transferred backing store.; refuted because: The changed path only observes an mpsc receiver disconnect and constructs an immutable diagnostic String; it performs no buffer or view operation.

Evidence gaps

  • Model proof intent was rejected by deterministic validation.

Copy link
Copy Markdown
Member Author

Recovered bounded execution on ef108a2/tree9f1b2e78960bda8e2b43c62d72919d399cf3849a using supported Rust-only profile after full-feature builds hit memory limits. Disposable test-build children dispatch the actual check command/renderer with injected worker outcomes: stopped ->exit2/analysis_worker_stopped/failed progress; ordinary error ->2/analysis_failed/failed; timeout ->2/analysis_timeout/cancelled; empty-diff success ->0/complete/completed. Assertion driver exits0.

Each owned primary was reaped and grandchild no longer running (observable zombie remained); primary-only kill negative left its grandchild alive. Important scope: fixture explicitly assigns a group-owning cancellation token, proving that cleanup path, NOT that ordinary standalone Unix check owns every subprocess group. Injection is cfg(test), success uses empty diff. Earlier full-feature SIGKILL/15GiB termination never ran tests. PR base/current owner metadata still unverified; no shared production change or hosted clearance.

Copy link
Copy Markdown
Member Author

Complete bounded reproducer for receipt6539963338, same frozen ef108a2. Parent verified bundle and both exact files. Patch5288bytes SHA25687776daa898c3cad534366a54264b9d59c80b0856e80d1f717bc641ae9fc4738; driver3111bytes SHA256aebd9b38fdb57eb54a328502840028340d25fb2e7e838e94a38496b3478e2773.

Successful build: CARGO_BUILD_JOBS=1 CARGO_INCREMENTAL=0 CARGO_PROFILE_TEST_DEBUG=0 cargo test --locked -p ripr --lib --no-default-features --features lang-rust disposable_check_command_fixture -- --nocapture. Then RIPR_TEST_BINARY= python3 assert_fixture.py exits0. Group-owning token is explicit: this does not prove standalone default subprocess ownership. Zombie-but-not-running grandchildren and reaped primaries are intentionally distinguished. Test-only source proposal, not canonical production change or hosted clearance.

--- a/crates/ripr/src/app/check.rs
+++ b/crates/ripr/src/app/check.rs
@@ -278,6 +278,34 @@
     CoreError,
 > {
     let mut progress = ProgressRun::new(sink, scope);
+    #[cfg(all(test, unix))]
+    if let Ok(case) = std::env::var("RIPR_TEST_WORKER_CASE") {
+        use crate::analysis::cancellation::{AnalysisCancellationToken, with_token};
+        use std::sync::{Arc, atomic::AtomicBool};
+        progress.emit(AnalysisProgressStage::LoadingInput);
+        let dir = std::path::PathBuf::from(std::env::var("RIPR_TEST_WORKER_DIR").expect("fixture dir"));
+        let group_token = AnalysisCancellationToken::with_server_interrupt(Arc::new(AtomicBool::new(false)));
+        let mut command = std::process::Command::new("sh");
+        command.arg("-c").arg(r#"sleep 20 & echo $! > "$1"; wait"#).arg("fixture").arg(dir.join("grandchild"));
+        command.stdin(std::process::Stdio::null()).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null());
+        let mut owned = with_token(&group_token, || crate::process_owner::OwnedProcess::spawn(command)).expect("spawn owned fixture");
+        std::fs::write(dir.join("primary"), owned.id().to_string()).expect("record primary");
+        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(3);
+        while !dir.join("grandchild").exists() {
+            assert!(std::time::Instant::now() < deadline, "fixture child did not start");
+            std::thread::sleep(std::time::Duration::from_millis(5));
+        }
+        if case == "stopped" { std::panic::resume_unwind(Box::new("fixture stopped")); }
+        if case == "timeout" {
+            while crate::analysis::cancellation::checkpoint_typed().is_ok() {
+                std::thread::sleep(std::time::Duration::from_millis(5));
+            }
+        }
+        owned.terminate_tree().expect("terminate fixture tree");
+        if case == "error" || case == "timeout" {
+            return Err(CoreError::message("fixture ordinary error"));
+        }
+    }
     // #9922: a user-fixable input failure (unresolvable base, unusable root
     // or config, missing `--diff` file) is reported by the real error the
     // caller prints; the CLI progress sink must not also project `failed`.
--- a/crates/ripr/src/cli/commands/check_budget.rs
+++ b/crates/ripr/src/cli/commands/check_budget.rs
@@ -364,4 +364,59 @@
             Ok(Some(AnalysisAbortKind::DeadlineExceeded))
         );
     }
-}
+    #[test]
+    fn budget_outcomes_reach_check_json_refusal_renderer() {
+        use crate::app::{CheckInput, Mode, OutputFormat};
+        let input = CheckInput {
+            root: ".".into(), base: Some("origin/main".into()),
+            diff_file: Some("example.diff".into()), mode: Mode::Draft,
+            format: OutputFormat::Json, include_unchanged_tests: true,
+            perl_facts_path: None, suppression_policy: None, git_timeout: None,
+            git_candidate: None, scope: Default::default(),
+        };
+        for case in ["stopped", "error", "timeout", "success"] {
+            let result = run_with_budget(Some(Duration::from_millis(100)), || {}, move || {
+                match case {
+                    "stopped" => std::panic::resume_unwind(Box::new("fixture panic")),
+                    "error" => Err(CoreError::message("fixture ordinary error")),
+                    "timeout" => {
+                        std::thread::sleep(Duration::from_millis(300));
+                        Ok(42)
+                    }
+                    _ => Ok(42),
+                }
+            });
+            if case == "success" {
+                assert_eq!(result, Ok(42));
+                continue;
+            }
+            let error = result.expect_err("fixture must refuse");
+            let json = super::super::check::machine_refusal_document(&input, OutputFormat::Json, &error)
+                .expect("JSON has a refusal renderer").expect("renderer succeeds");
+            let value: serde_json::Value = serde_json::from_str(&json).expect("valid JSON");
+            let (status, route) = match case {
+                "stopped" => ("analysis_worker_stopped", "analysis/worker-stopped"),
+                "timeout" => ("analysis_timeout", "analysis/timeout"),
+                _ => ("analysis_failed", "analysis/failure"),
+            };
+            assert_eq!(value["analysis_scope"]["run_status"], status, "{case}: {value}");
+            assert_eq!(value["analysis_scope"]["repair_route"], route, "{case}: {value}");
+            assert_eq!(value["findings"].as_array().map(Vec::len), Some(0));
+            assert_eq!(value["analysis_scope"]["downstream_consumable"], false);
+        }
+    }
+
+    #[cfg(unix)]
+    #[test]
+    fn disposable_check_command_fixture() {
+        let Ok(dir) = std::env::var("RIPR_TEST_WORKER_DIR") else { return; };
+        let args = vec!["ripr".to_string(), "check".into(), "--root".into(), dir.clone(),
+            "--diff".into(), format!("{dir}/input.diff"), "--format".into(), "json".into(),
+            "--timeout".into(), "1".into()];
+        match crate::cli::run(args) {
+            Ok(()) => std::process::exit(0),
+            Err(error) => { eprintln!("{error}"); std::process::exit(error.exit_code()); }
+        }
+    }
+
+}
import json, os, pathlib, signal, subprocess, tempfile, time
binary=os.environ['RIPR_TEST_BINARY']
test='cli::commands::check_budget::tests::disposable_check_command_fixture'
def state(pid):
    try: return pathlib.Path(f'/proc/{pid}/stat').read_text().split(') ')[1].split()[0]
    except FileNotFoundError: return 'gone'
def terminal(pid):
    deadline=time.monotonic()+3
    while state(pid) not in ('Z','gone') and time.monotonic()<deadline: time.sleep(.02)
    return state(pid)
for case, code, status, route, stage in [
    ('stopped',2,'analysis_worker_stopped','analysis/worker-stopped','failed'),
    ('error',2,'analysis_failed','analysis/failure','failed'),
    ('timeout',2,'analysis_timeout','analysis/timeout','cancelled'),
    ('success',0,None,None,'completed')]:
    with tempfile.TemporaryDirectory(prefix='ripr-child-') as d:
        p=pathlib.Path(d); (p/'input.diff').write_text('')
        env=os.environ.copy(); env.update(RIPR_TEST_WORKER_DIR=d,RIPR_TEST_WORKER_CASE=case)
        r=subprocess.run([binary,'--exact',test,'--nocapture'],env=env,capture_output=True,text=True,timeout=15)
        assert r.returncode==code,(case,r.returncode,r.stderr)
        payload=json.loads(r.stdout[r.stdout.index('{'):])
        if status:
            scope=payload['analysis_scope']; assert scope['run_status']==status and scope['repair_route']==route
            assert scope['downstream_consumable'] is False and payload['findings']==[]
        else: assert payload['analysis_outcome']['analysis_complete'] is True
        terminals=[line for line in r.stderr.splitlines() if line.startswith('ripr progress: ') and any(f' {x} [' in line for x in ('failed','cancelled','completed'))]
        assert terminals==[f'ripr progress: {stage} [diff]'],(case,terminals)
        primary=int((p/'primary').read_text()); grandchild=int((p/'grandchild').read_text())
        assert terminal(primary)=='gone',(case,'primary unreaped',state(primary))
        assert terminal(grandchild) in ('Z','gone'),(case,'grandchild alive',state(grandchild))
        print(case,'exit',r.returncode,'status',status or 'success','terminal',stage,'primary reaped','grandchild',state(grandchild),flush=True)
# Discriminator: primary-only kill must leave the independently started child alive.
with tempfile.TemporaryDirectory(prefix='ripr-control-') as d:
    f=pathlib.Path(d)/'grandchild'
    child=subprocess.Popen(['sh','-c','sleep 20 & echo $! > "$1"; wait','control',str(f)],stdin=subprocess.DEVNULL,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
    deadline=time.monotonic()+3
    while not f.exists() and time.monotonic()<deadline: time.sleep(.01)
    assert f.exists(),'control grandchild did not start'
    pid=int(f.read_text())
    try:
        child.kill(); child.wait(timeout=3)
        assert state(pid) not in ('gone','Z'),'primary-only kill unexpectedly removed grandchild'
        print('primary-only control: grandchild remained alive',flush=True)
    finally:
        if state(pid) not in ('gone','Z'): os.kill(pid,signal.SIGKILL)
        assert terminal(pid) in ('Z','gone'),'control cleanup failed'

@EffortlessSteven
EffortlessSteven merged commit a2e1906 into main Oct 31, 2026
59 checks passed
@EffortlessSteven
EffortlessSteven deleted the claude/fix-11116-typed-worker-failure branch October 31, 2026 08:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants