Skip to content

feat(perl): harden managed producer mode — SPEC argv + timeout/kill + atomic + cache + freshness (Campaign 31 item 4) - #1456

Merged
EffortlessSteven merged 1 commit into
mainfrom
perl-managed-producer-harden
Jul 2, 2026
Merged

EffortlessSteven merged 1 commit into
mainfrom
perl-managed-producer-harden

Conversation

@EffortlessSteven

Copy link
Copy Markdown
Member

What

Hardens [perl] producer = \"perllsp\" managed mode so a real perllsp can be invoked safely. The prior invoke_perl_lsp_producer used a non-SPEC arg surface (--ripr-*), did not enforce timeout_ms (blocked forever), omitted --base/--head, wrote non-atomically, keyed the cache on root only, and had no freshness check. This resolves 7 of 8 sub-points; the capability handshake is deferred (cross-repo dependency).

Changes (2 files, +385/−58)

app/check.rs — invoke_perl_lsp_producer

Sub-point Implementation
SPEC-0064-canonical arg surface ripr-facts --schema --root --base --head --fact-classes --out (mirrors PerlLspFactExportRequest::render_command). Single-source via parity tests. Permanently fixes the item-3 divergence.
--base/--head passed wired from input.base (head = HEAD)
Real timeout enforcement spawn + poll try_wait @ 50ms up to timeout_ms; on timeout child.kill() + child.wait() (reap, no orphan). std only — no new crate.
Atomic packet writes producer writes <hash>.json.tmp; ripr rename→<hash>.json only after success+exists. Terminated producer leaves .tmp, never consumed.
Content-aware cache key simple_hash(root + base + head + schema + executable + timeout_ms). Different base/diff/producer → different file → no cross-run staleness reuse.
Freshness validation before reuse: cached schema_version == current AND mtime within PERL_FACTS_MAX_AGE_SECS (86400). Any failure → regenerate (never error).
Clean stderr/states distinguish spawn-failed ("configure [perl].executable or put perllsp on PATH"), non-zero exit, timeout, packet-missing-after-success. Pipeline's perl_run_status_for_err (item 2) maps to Unavailable/Invalid.
Capability handshake DEFERRED — requires a defined perllsp probe surface (--version/--capabilities), a perl-lsp-swarm question. Flagged; do not fabricate a capability taxonomy.

perl/tests.rs — parity test

render_command_matches_spec_canonical_surface pins render_command to the same SPEC surface that perl_facts_export_argv (in app/check) produces. If either diverges, one test fails.

Tests (6 new, all green)

perl_facts_export_argv_matches_spec_canonical_surface, perl_facts_export_argv_omits_base_head_when_absent, perl_facts_cache_key_is_deterministic_and_input_sensitive, cached_packet_freshness_rejects_missing_and_stale_schema, invoke_perl_lsp_producer_surfaces_missing_producer_clearly, render_command_matches_spec_canonical_surface.

Gates (all green)

default lib + --features lang-perl lib + lang-perl integration; goldens check (zero drift), dogfood, check-process-policy (Command::new count unchanged — reused the single spawn), check-no-panic-family, check-static-language, check-local-context, check-architecture, check-public-api, check-output-contracts, check-fixture-contracts, check-evidence-promotion-honesty, check-spec-format, check-traceability, check-goals, check-doc-index, fmt, default clippy.

Scope / non-goals

One semantic slice (trustworthy producer invocation, 7 sub-points). Capability handshake deferred. No change to perl_preview_card, GapRecord, public projection (item 6), doctor UX (item 5).

… atomic writes + content-aware cache + freshness (Campaign 31 item 4)

Hardens the [perl] producer = "perllsp" managed mode so a real perllsp can be
invoked safely. The prior invoke_perl_lsp_producer used a non-SPEC arg surface
(--ripr-*), did not enforce timeout_ms (blocked forever), omitted --base/--head,
wrote non-atomically, keyed the cache on root only, and had no freshness check.
This resolves 7 of 8 sub-points; the capability handshake is deferred (cross-repo
dependency on perllsp exposing a probe surface).

Sub-points implemented (app/check.rs invoke_perl_lsp_producer):
- SPEC-0064-canonical arg surface: ripr-facts --schema --root --base --head
  --fact-classes --out (mirrors PerlLspFactExportRequest::render_command). A
  parity test in the perl module pins render_command to the same surface; a
  companion test in app/check pins perl_facts_export_argv. Single-source via
  test, not shared code (the perl module is cfg(lang-perl); the managed producer
  must compile without it). Permanently fixes the item-3 divergence.
- --base/--head passed: wired from input.base (head = HEAD).
- Real timeout enforcement: spawn + poll try_wait on a 50ms interval up to
  timeout_ms; on timeout, child.kill() + child.wait() (reap, no orphan handle).
  std only — no new crate.
- Atomic packet writes: producer writes <hash>.json.tmp; ripr renames to
  <hash>.json only after success + file exists. A terminated/failing producer
  leaves a .tmp that is never consumed.
- Content-aware cache key: simple_hash(root + base + head + schema + executable
  + timeout_ms). Different base/diff/producer/config -> different file -> no
  cross-run staleness reuse. FNV, non-crypto, cache-naming only.
- Freshness validation: before reuse, the cached packet's schema_version must
  match the current schema AND its mtime must be within PERL_FACTS_MAX_AGE_SECS
  (86400s). Any failure falls through to regeneration (never an error).
- Clean stderr/states: error strings distinguish spawn-failed (missing producer
  -> "configure [perl].executable or put perllsp on PATH"), non-zero exit (no
  packet), timeout (process terminated), packet-missing-after-success. The
  pipeline's perl_run_status_for_err (item 2) maps these to Unavailable/Invalid.

Capability handshake: DEFERRED. Requires a defined perllsp probe surface
(--version/--capabilities) — a perl-lsp-swarm question. Flagged in a comment;
fabricating a capability taxonomy now would violate "no fabricated taxonomy".

Tests: perl_facts_export_argv_matches_spec_canonical_surface,
perl_facts_export_argv_omits_base_head_when_absent,
perl_facts_cache_key_is_deterministic_and_input_sensitive,
cached_packet_freshness_rejects_missing_and_stale_schema,
invoke_perl_lsp_producer_surfaces_missing_producer_clearly,
render_command_matches_spec_canonical_surface (perl module, lang-perl).

Gates: default lib + lang-perl lib + lang-perl integration all green; goldens
check (zero drift), dogfood, check-process-policy (Command::new count unchanged
— reused the single spawn), check-no-panic-family, check-static-language,
check-local-context, check-architecture, check-public-api, check-output-contracts,
check-fixture-contracts, check-evidence-promotion-honesty, check-spec-format,
check-traceability, check-goals, check-doc-index, fmt, default clippy all green.

Scope: one semantic slice (trustworthy producer invocation, 7 sub-points).
Capability handshake deferred. No change to perl_preview_card, GapRecord,
public projection (item 6), doctor UX (item 5).
@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 Jul 2, 2026 •

Copy link
Copy Markdown

Review Change Stack

Summary by CodeRabbit

  • New Features

    • Managed Perl fact generation now uses the standardized command-line format and supports base/head-aware requests.
  • Bug Fixes

    • Improved cache reuse so results are refreshed when they are stale or incompatible.
    • Added stronger timeout handling for Perl fact generation, including cleanup if the process overruns.
    • Made failures clearer when the Perl producer executable is missing or output is incomplete.
  • Tests

    • Added regression coverage for command rendering, cache behavior, freshness checks, and error reporting.

Walkthrough

This PR replaces the Perl LSP producer's non-canonical --ripr-* argv with a SPEC-0064-canonical ripr-facts argv builder, adds input-sensitive cache keys, freshness checks against schema/mtime, atomic packet writes via temp-then-rename, and enforced process timeouts, with new regression tests.

Changes

Perl Facts Producer Hardening

Layer / File(s) Summary
Canonical argv parity test
crates/ripr/src/analysis/language/perl/tests.rs
New test pins render_command() output to the exact SPEC-0064 canonical ripr-facts argv (program, fact-classes order, --base/--head) and asserts no --ripr-* flags are emitted.
Argv builder and constants
crates/ripr/src/app/check.rs
Adds perl_facts_export_argv builder for the canonical perllsp ripr-facts argv surface plus PERL_FACT_PACKET_SCHEMA and PERL_FACTS_MAX_AGE_SECS constants, replacing the old non-canonical arg surface.
Producer invocation, caching, and timeout enforcement
crates/ripr/src/app/check.rs
Rewrites invoke_perl_lsp_producer with a cache key derived from root/base/head/schema/executable/timeout, a cached_packet_is_fresh freshness check (schema match + mtime), atomic .tmp-then-rename packet writes, and a custom ChildWaitTimeoutExt::wait_timeout that kills/reaps the process on timeout.
Hardening tests
crates/ripr/src/app/check.rs
Adds tests covering canonical argv correctness (base/head omission), cache key determinism/sensitivity, cache freshness acceptance/rejection, and clearer error messaging for a missing producer executable.

Estimated code review effort: 4 (Complex) | ~45 minutes

Possibly related issues

Poem

A rabbit hops through cache and clock,
Renames the packet, turns the lock. 🥕
No more stray --ripr-* flags in sight,
Just canonical argv, clean and right.
Timeout ticks, then kill and reap—
This burrow's producer sleeps no more, but leaps!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is detailed, but it omits many required template sections such as source links, scope classification, proof, rollback, traceability, and policy/impact checklists. Add the missing template sections, especially Summary, Source-of-truth Links, Scope Classification, Proof, Claim Boundary, Rollback, Traceability, and the required checklists.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: hardening Perl managed producer mode with SPEC argv, timeout handling, atomic writes, caching, and freshness checks.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch perl-managed-producer-harden

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f3b41eb969

ℹ️ 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".

Comment on lines +229 to +233
"{}|{}|{}|{}|{}|{}",
root_str,
base.unwrap_or(""),
head,
PERL_FACT_PACKET_SCHEMA,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Include current diff content in the cache key

When managed producer mode is run twice for the same root/base/head within the 24-hour cache window after the Perl diff changes, this key stays identical and cached_packet_is_fresh returns the old packet without invoking perllsp. The Perl adapter ignores the current changed_files and does not validate input.diff_id, so a new Perl change, especially in a file absent from the previous packet, can be silently missed. Include the current diff/worktree content identity in the key or validate the cached packet against the current diff before reuse.

Useful? React with 👍 / 👎.

Comment on lines +283 to +284
if tmp_path.is_file() {
std::fs::rename(&tmp_path, &packet_path).map_err(|e| {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Reject non-zero producer exits before finalizing

If perllsp writes the temp packet and then exits non-zero, this branch still renames the file and returns Ok because it only checks tmp_path.is_file(). The previous implementation rejected non-success statuses, and treating a failed exporter as a successful managed run can cache and consume incomplete or diagnostic output as facts. Check status.success() before finalizing the temp file and surface the failure instead.

Useful? React with 👍 / 👎.

Comment on lines +260 to +262
.args(&argv)
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output();

// Note: full timeout enforcement (spawned-thread + join_timeout) lands
// with the process-policy gate. For now the producer runs without a
// timeout; the timeout_ms config is read but not enforced. This is safe
// because managed mode is explicit opt-in only.

match result {
Ok(output) => {
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(format!(
"perllsp ripr-facts failed (exit {:?}): {stderr}",
output.status.code()
));
}
if !packet_path.exists() {
return Err(format!(
"perllsp ripr-facts completed but packet not found at {}",
packet_path.display()
));
.stderr(std::process::Stdio::piped());

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Drain or avoid producer pipes while waiting

With stdout and stderr set to piped() but never read while try_wait polls, a verbose producer can fill an OS pipe buffer and block before it exits; managed mode then waits until the timeout and kills an otherwise successful export. The old .output() path drained both streams, so this is a regression for producers that emit enough diagnostics. Use null/inherited stdio or drain the pipes concurrently while enforcing the timeout.

Useful? React with 👍 / 👎.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 7

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@crates/ripr/src/app/check.rs`:
- Around line 225-238: The cache key in `check.rs` is still based on symbolic
`base`/`head` values, so `packet_path` can be reused across different commits or
worktree states. Update the `cache_key` construction in the packet caching logic
to use resolved commit IDs and any relevant diff/worktree inputs instead of ref
names, while keeping the existing schema/executable/timeout components. Make the
change in the code that builds `cache_key` and `packet_hash` so the cache stays
tied to the actual content used to generate the packet.
- Around line 539-568: The missing-producer test in
invoke_perl_lsp_producer_surfaces_missing_producer_clearly is nondeterministic
because it relies on perllsp being absent on PATH instead of forcing a spawn
failure. Update the test to build PerlConfig with a guaranteed-missing
executable path, or add a small test-only constructor/helper for PerlConfig that
sets the executable explicitly, so the invoke_perl_lsp_producer path always
exercises the missing-producer error.
- Around line 277-291: In check.rs, the packet finalization path in the
Ok(Some(status)) branch currently renames tmp_path whenever it exists, even if
the producer exited unsuccessfully. Update this logic to require
status.success() before calling std::fs::rename and returning packet_path;
otherwise treat it as a producer failure and surface the existing error path.
Use the existing Ok(Some(status)) handling and the tmp_path.is_file() check to
locate the change.
- Around line 258-275: The subprocess in `check.rs` pipes `stdout` and `stderr`
in the `Command` setup but never drains them, so a noisy Perl producer can block
before the timeout path. Update the `spawn`/`wait_timeout` flow to either stop
piping output when it is not needed or actively consume both streams from the
spawned child while waiting, using the existing `command`, `child`, and
`wait_timeout` logic as the place to fix it.
- Around line 251-254: The temporary file name in check.rs is shared across
concurrent invocations because `tmp_path` is derived only from `packet_hash`, so
one run can delete or overwrite another run’s in-flight output. Update the
temp-path generation in the `check` flow to use a unique per-invocation name
(for example, include a random suffix, PID, or similar) while keeping the final
rename target unchanged, and keep the stale-temp cleanup scoped to that unique
path.
- Around line 328-342: The freshness check in the check.rs logic returns early
on future-dated mtimes, so malformed or stale-schema files bypass JSON
validation. Update the logic around the modified.elapsed branch in the relevant
freshness function so clock skew only affects the age decision, not the schema
check, and still read/parse the file and verify schema_version against
PERL_FACT_PACKET_SCHEMA before returning fresh. Keep the change localized to the
existing elapsed/read_to_string/from_str flow.
- Line 256: The argv construction in check.rs always passes Some(head) to
perl_facts_export_argv, which causes --head to be emitted even when base is
None. Update the call site around perl_facts_export_argv so head is only
supplied when base is present, and ensure repo-mode/no-base paths omit both
flags as expected.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 7ee71017-2532-4bd7-abd6-3c1f6efe395f

📥 Commits

Reviewing files that changed from the base of the PR and between 5a9c6bb and f3b41eb.

📒 Files selected for processing (2)
  • crates/ripr/src/analysis/language/perl/tests.rs
  • crates/ripr/src/app/check.rs

Comment on lines +225 to 238
// Cache key: content/diff/schema/producer/config, not root only. A packet
// built for a different base/diff/producer/timeout must not be reused for
// this run. FNV-1a, non-crypto, cache-naming only (see `simple_hash` doc).
let cache_key = format!(
"{}|{}|{}|{}|{}|{}",
root_str,
base.unwrap_or(""),
head,
PERL_FACT_PACKET_SCHEMA,
executable_str,
timeout_ms,
);
let packet_hash = format!("{:016x}", simple_hash(&cache_key));
let packet_path = cache_dir.join(format!("{packet_hash}.json"));

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Make the cache key content-sensitive, not ref-name-sensitive.

The key stores symbolic base/HEAD, so a new commit at HEAD, a moved base ref, or changed worktree can reuse yesterday’s packet for up to PERL_FACTS_MAX_AGE_SECS. Include resolved commit IDs and relevant diff/worktree inputs in the key before reusing packets.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/ripr/src/app/check.rs` around lines 225 - 238, The cache key in
`check.rs` is still based on symbolic `base`/`head` values, so `packet_path` can
be reused across different commits or worktree states. Update the `cache_key`
construction in the packet caching logic to use resolved commit IDs and any
relevant diff/worktree inputs instead of ref names, while keeping the existing
schema/executable/timeout components. Make the change in the code that builds
`cache_key` and `packet_hash` so the cache stays tied to the actual content used
to generate the packet.

Comment on lines +251 to +254
let tmp_path = cache_dir.join(format!("{packet_hash}.json.tmp"));

// Remove any stale `.tmp` from a prior terminated run before invoking.
let _ = std::fs::remove_file(&tmp_path);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Use a unique temp path per invocation.

{packet_hash}.json.tmp is shared by concurrent runs with the same cache key; one run can remove or overwrite another producer’s in-flight output before rename.

Suggested direction
-    let tmp_path = cache_dir.join(format!("{packet_hash}.json.tmp"));
-
-    // Remove any stale `.tmp` from a prior terminated run before invoking.
-    let _ = std::fs::remove_file(&tmp_path);
+    let tmp_suffix = std::time::SystemTime::now()
+        .duration_since(std::time::UNIX_EPOCH)
+        .map_or(0, |duration| duration.as_nanos());
+    let tmp_path = cache_dir.join(format!(
+        "{packet_hash}.{}.{}.json.tmp",
+        std::process::id(),
+        tmp_suffix
+    ));
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
let tmp_path = cache_dir.join(format!("{packet_hash}.json.tmp"));
// Remove any stale `.tmp` from a prior terminated run before invoking.
let _ = std::fs::remove_file(&tmp_path);
let tmp_suffix = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |duration| duration.as_nanos());
let tmp_path = cache_dir.join(format!(
"{packet_hash}.{}.{}.json.tmp",
std::process::id(),
tmp_suffix
));
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/ripr/src/app/check.rs` around lines 251 - 254, The temporary file name
in check.rs is shared across concurrent invocations because `tmp_path` is
derived only from `packet_hash`, so one run can delete or overwrite another
run’s in-flight output. Update the temp-path generation in the `check` flow to
use a unique per-invocation name (for example, include a random suffix, PID, or
similar) while keeping the final rename target unchanged, and keep the
stale-temp cleanup scoped to that unique path.

// Remove any stale `.tmp` from a prior terminated run before invoking.
let _ = std::fs::remove_file(&tmp_path);

let argv = perl_facts_export_argv(&root_str, &tmp_path.display().to_string(), base, Some(head));

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Do not pass --head when --base is absent.

The helper test says repo-mode/no-base runs must omit both flags, but invocation always passes Some(head), producing --head HEAD even when base is None.

Suggested fix
-    let argv = perl_facts_export_argv(&root_str, &tmp_path.display().to_string(), base, Some(head));
+    let argv = perl_facts_export_argv(
+        &root_str,
+        &tmp_path.display().to_string(),
+        base,
+        base.map(|_| head),
+    );
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
let argv = perl_facts_export_argv(&root_str, &tmp_path.display().to_string(), base, Some(head));
let argv = perl_facts_export_argv(
&root_str,
&tmp_path.display().to_string(),
base,
base.map(|_| head),
);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/ripr/src/app/check.rs` at line 256, The argv construction in check.rs
always passes Some(head) to perl_facts_export_argv, which causes --head to be
emitted even when base is None. Update the call site around
perl_facts_export_argv so head is only supplied when base is present, and ensure
repo-mode/no-base paths omit both flags as expected.

Comment on lines +258 to +275
let mut command = Command::new(&executable);
command
.args(&argv)
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output();

// Note: full timeout enforcement (spawned-thread + join_timeout) lands
// with the process-policy gate. For now the producer runs without a
// timeout; the timeout_ms config is read but not enforced. This is safe
// because managed mode is explicit opt-in only.

match result {
Ok(output) => {
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(format!(
"perllsp ripr-facts failed (exit {:?}): {stderr}",
output.status.code()
));
}
if !packet_path.exists() {
return Err(format!(
"perllsp ripr-facts completed but packet not found at {}",
packet_path.display()
));
.stderr(std::process::Stdio::piped());

let mut child = command.spawn().map_err(|e| {
format!(
"failed to spawn Perl producer at `{}`: {e}. Configure [perl].executable or \
put `perllsp` on PATH.",
executable.display()
)
})?;

// Real timeout enforcement (item 4): wait up to `timeout_ms`; on timeout,
// kill the child and reap it so no orphan process holds a handle (the
// AGENTS.md Windows file-lock warning). `std` only — no new crate.
let wait_result = child.wait_timeout(std::time::Duration::from_millis(timeout_ms));

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Avoid undrained subprocess pipes.

stdout/stderr are piped but never read; a verbose producer can block on a full pipe and then hit the timeout path.

Suggested fix if output is not consumed
     command
         .args(&argv)
-        .stdout(std::process::Stdio::piped())
-        .stderr(std::process::Stdio::piped());
+        .stdout(std::process::Stdio::null())
+        .stderr(std::process::Stdio::null());
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
let mut command = Command::new(&executable);
command
.args(&argv)
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.output();
// Note: full timeout enforcement (spawned-thread + join_timeout) lands
// with the process-policy gate. For now the producer runs without a
// timeout; the timeout_ms config is read but not enforced. This is safe
// because managed mode is explicit opt-in only.
match result {
Ok(output) => {
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(format!(
"perllsp ripr-facts failed (exit {:?}): {stderr}",
output.status.code()
));
}
if !packet_path.exists() {
return Err(format!(
"perllsp ripr-facts completed but packet not found at {}",
packet_path.display()
));
.stderr(std::process::Stdio::piped());
let mut child = command.spawn().map_err(|e| {
format!(
"failed to spawn Perl producer at `{}`: {e}. Configure [perl].executable or \
put `perllsp` on PATH.",
executable.display()
)
})?;
// Real timeout enforcement (item 4): wait up to `timeout_ms`; on timeout,
// kill the child and reap it so no orphan process holds a handle (the
// AGENTS.md Windows file-lock warning). `std` only — no new crate.
let wait_result = child.wait_timeout(std::time::Duration::from_millis(timeout_ms));
let mut command = Command::new(&executable);
command
.args(&argv)
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null());
let mut child = command.spawn().map_err(|e| {
format!(
"failed to spawn Perl producer at `{}`: {e}. Configure [perl].executable or \
put `perllsp` on PATH.",
executable.display()
)
})?;
// Real timeout enforcement (item 4): wait up to `timeout_ms`; on timeout,
// kill the child and reap it so no orphan process holds a handle (the
// AGENTS.md Windows file-lock warning). `std` only — no new crate.
let wait_result = child.wait_timeout(std::time::Duration::from_millis(timeout_ms));
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/ripr/src/app/check.rs` around lines 258 - 275, The subprocess in
`check.rs` pipes `stdout` and `stderr` in the `Command` setup but never drains
them, so a noisy Perl producer can block before the timeout path. Update the
`spawn`/`wait_timeout` flow to either stop piping output when it is not needed
or actively consume both streams from the spawned child while waiting, using the
existing `command`, `child`, and `wait_timeout` logic as the place to fix it.

Comment on lines +277 to 291
Ok(Some(status)) => {
// Child exited within the timeout. If it produced the packet,
// atomically rename to the final path. If not, surface a clear
// producer-failed message (the producer's own stderr went to its
// piped stderr; we rely on the packet-existence check because
// `try_wait` does not drain the pipes).
if tmp_path.is_file() {
std::fs::rename(&tmp_path, &packet_path).map_err(|e| {
format!(
"failed to finalize Perl facts packet `{}`: {e}",
packet_path.display()
)
})?;
return Ok(packet_path);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Require a successful exit before finalizing the packet.

A non-zero producer exit with a leftover temp file is currently renamed and consumed. Check status.success() before rename.

Suggested fix
         Ok(Some(status)) => {
+            if !status.success() {
+                let _ = std::fs::remove_file(&tmp_path);
+                return Err(format!(
+                    "perllsp ripr-facts exited with non-zero status ({status}); no packet consumed"
+                ));
+            }
             // Child exited within the timeout. If it produced the packet,
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
Ok(Some(status)) => {
// Child exited within the timeout. If it produced the packet,
// atomically rename to the final path. If not, surface a clear
// producer-failed message (the producer's own stderr went to its
// piped stderr; we rely on the packet-existence check because
// `try_wait` does not drain the pipes).
if tmp_path.is_file() {
std::fs::rename(&tmp_path, &packet_path).map_err(|e| {
format!(
"failed to finalize Perl facts packet `{}`: {e}",
packet_path.display()
)
})?;
return Ok(packet_path);
}
Ok(Some(status)) => {
if !status.success() {
let _ = std::fs::remove_file(&tmp_path);
return Err(format!(
"perllsp ripr-facts exited with non-zero status ({status}); no packet consumed"
));
}
// Child exited within the timeout. If it produced the packet,
// atomically rename to the final path. If not, surface a clear
// producer-failed message (the producer's own stderr went to its
// piped stderr; we rely on the packet-existence check because
// `try_wait` does not drain the pipes).
if tmp_path.is_file() {
std::fs::rename(&tmp_path, &packet_path).map_err(|e| {
format!(
"failed to finalize Perl facts packet `{}`: {e}",
packet_path.display()
)
})?;
return Ok(packet_path);
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/ripr/src/app/check.rs` around lines 277 - 291, In check.rs, the packet
finalization path in the Ok(Some(status)) branch currently renames tmp_path
whenever it exists, even if the producer exited unsuccessfully. Update this
logic to require status.success() before calling std::fs::rename and returning
packet_path; otherwise treat it as a producer failure and surface the existing
error path. Use the existing Ok(Some(status)) handling and the
tmp_path.is_file() check to locate the change.

Comment on lines +328 to +342
let Ok(elapsed) = modified.elapsed() else {
// mtime in the future (clock skew): treat as fresh rather than churning.
return true;
};
if elapsed.as_secs() > PERL_FACTS_MAX_AGE_SECS {
return false;
}
// schema_version field must match the current schema.
let Ok(text) = std::fs::read_to_string(path) else {
return false;
};
let Ok(value) = serde_json::from_str::<serde_json::Value>(&text) else {
return false;
};
value.get("schema_version").and_then(|v| v.as_str()) == Some(PERL_FACT_PACKET_SCHEMA)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Still validate schema when mtime is in the future.

The clock-skew branch returns true before reading JSON, so a future-dated malformed or stale-schema file is treated as fresh.

Suggested fix
-    let Ok(elapsed) = modified.elapsed() else {
-        // mtime in the future (clock skew): treat as fresh rather than churning.
-        return true;
-    };
-    if elapsed.as_secs() > PERL_FACTS_MAX_AGE_SECS {
+    let elapsed = match modified.elapsed() {
+        Ok(elapsed) => Some(elapsed),
+        Err(_) => None,
+    };
+    if let Some(elapsed) = elapsed
+        && elapsed.as_secs() > PERL_FACTS_MAX_AGE_SECS
+    {
         return false;
     }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
let Ok(elapsed) = modified.elapsed() else {
// mtime in the future (clock skew): treat as fresh rather than churning.
return true;
};
if elapsed.as_secs() > PERL_FACTS_MAX_AGE_SECS {
return false;
}
// schema_version field must match the current schema.
let Ok(text) = std::fs::read_to_string(path) else {
return false;
};
let Ok(value) = serde_json::from_str::<serde_json::Value>(&text) else {
return false;
};
value.get("schema_version").and_then(|v| v.as_str()) == Some(PERL_FACT_PACKET_SCHEMA)
let elapsed = match modified.elapsed() {
Ok(elapsed) => Some(elapsed),
Err(_) => None,
};
if let Some(elapsed) = elapsed
&& elapsed.as_secs() > PERL_FACTS_MAX_AGE_SECS
{
return false;
}
// schema_version field must match the current schema.
let Ok(text) = std::fs::read_to_string(path) else {
return false;
};
let Ok(value) = serde_json::from_str::<serde_json::Value>(&text) else {
return false;
};
value.get("schema_version").and_then(|v| v.as_str()) == Some(PERL_FACT_PACKET_SCHEMA)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/ripr/src/app/check.rs` around lines 328 - 342, The freshness check in
the check.rs logic returns early on future-dated mtimes, so malformed or
stale-schema files bypass JSON validation. Update the logic around the
modified.elapsed branch in the relevant freshness function so clock skew only
affects the age decision, not the schema check, and still read/parse the file
and verify schema_version against PERL_FACT_PACKET_SCHEMA before returning
fresh. Keep the change localized to the existing elapsed/read_to_string/from_str
flow.

Comment on lines +539 to +568
fn invoke_perl_lsp_producer_surfaces_missing_producer_clearly() -> Result<(), String> {
// A non-existent executable must surface a clear "configure
// [perl].executable or put perllsp on PATH" message, not a raw spawn
// error. Uses a guaranteed-absent executable path.
use crate::config::PerlConfig;
let config = PerlConfig::default();
// Override the executable to a path that cannot exist.
let mut config = config;
// PerlConfig may not expose a setter; reach the field via the public
// API by constructing from the TOML-shaped default and checking the
// error wording. If there is no clean override, this test asserts the
// missing-producer wording against a default-constructed config that
// has no perllsp on PATH in CI.
let mut input = sample_diff_input();
input.base = Some("origin/main".to_string());
input.perl_facts_path = None;
let _ = &mut config;
// The producer name check happens in run_check before this function;
// here we exercise the spawn-failure path directly with a bogus
// executable by relying on the config default resolving to `perllsp`,
// which is absent in ripr-swarm CI.
let result = invoke_perl_lsp_producer(&config, &input);
// In an environment WITHOUT perllsp, this must be an Err naming the
// missing producer. If perllsp IS present (perl-lsp-swarm CI), skip.
if let Err(reason) = result {
assert!(
reason.contains("failed to spawn Perl producer") || reason.contains("perllsp"),
"missing producer must surface a clear message: {reason}"
);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Make the missing-producer test deterministic.

This test does not set a bogus executable and silently passes when perllsp exists on PATH, so it may not exercise the spawn-failure branch. Construct PerlConfig with a guaranteed-missing executable path or add a small test-only constructor.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/ripr/src/app/check.rs` around lines 539 - 568, The missing-producer
test in invoke_perl_lsp_producer_surfaces_missing_producer_clearly is
nondeterministic because it relies on perllsp being absent on PATH instead of
forcing a spawn failure. Update the test to build PerlConfig with a
guaranteed-missing executable path, or add a small test-only constructor/helper
for PerlConfig that sets the executable explicitly, so the
invoke_perl_lsp_producer path always exercises the missing-producer error.

@codecov

codecov Bot commented Jul 2, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 75.00000% with 42 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/ripr/src/app/check.rs 75.00% 42 Missing ⚠️

📢 Thoughts on this report? Let us know!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant