Skip to content

Exit 130 When a Ctrl+C Ends a Tool Before the Signal Handler Runs - #1310

Merged
ptr727 merged 5 commits into
developfrom
fix-signal-race
Nov 26, 2026
Merged

ptr727 merged 5 commits into
developfrom
fix-signal-race

Conversation

@ptr727

@ptr727 ptr727 commented Nov 26, 2026 •

Copy link
Copy Markdown
Owner

Why

A terminal Ctrl+C signals the whole foreground process group, so a running tool receives SIGINT at the same instant as PlexCleaner. .NET dispatches a PosixSignalRegistration handler asynchronously on a separate thread. So the tool can exit and fail the command before the handler has cancelled the run or set the exit code.

Measured in the Docker image, a Ctrl+C during startup tool verification logged the tool as not found and exited 1 rather than 130. A file interrupted mid-tool was kept as a tool error rather than as cancelled, with the cancelled tool run logged at error level.

What Changes

  • A command that fails waits up to the existing 100 ms in IsCancelledError() for a pending handler before Main reads the signal exit code.
  • System and folder tool verification return the cancel without logging the tool as not found.
  • A file interrupted by a cancel is kept as Cancelled ahead of Tool error and Tool signal.
  • The tool run a cancel ends logs as cancelled at warning level on every path. That covers the cancelled-token catches and the FFprobe analysis packet scan. It also covers a tool that exited first, through MediaTool.LogFailedExecution, which LogFailedResult and the FFmpeg verify now share.
  • Operation-level errors a caller logs after a cancelled tool, such as failing to find closed captions, stay at error level.

Verification

  • Clean compile, with zero warnings and no format changes, and all 584 unit tests pass.
  • A/B in ptr727/plexcleaner against a framework-dependent publish of develop, with synthetic testsrc2 media and Ctrl+C sent through the container's terminal at identical delays.
    • Startup Ctrl+C, 30 runs each: develop exited 1 in 4 runs, each logging a tool as not found. This branch exited 130 in every run that the signal reached.
    • Ctrl+C and docker stop with a tool running: develop logged ERR Cancelled execution or ERR Failed execution and kept the file as Tool error or Tool signal. This branch logged WRN Cancelled execution and kept it as Cancelled. Both exited 130 or 143 with the summary logged.
  • The cancel paths have no unit test, by the maintainer's decision. Program's cancel source is process-wide and deliberately never reset or disposed, so a unit test cannot cancel it without cancelling every later test. The image A/B above is the verification.
  • Every other stop path exited 128 plus the signal number with the summary logged, before and after this change. Those are docker stop, docker kill --signal INT, QUIT, and TERM, Ctrl+\, a proxied signal to a non-TTY client, and --init.

Findings from the Local Review

The opening push left these open once the local strict review's edit budget was spent. Each has its outcome:

  • PlexCleaner/MediaTool.cs and PlexCleaner/FfProbeTool.cs, introduced, design: the cancelled-token catches each repeated the cancelled-execution warning and the tool error record. Fixed in 2188b94, which moves them onto RecordCancelledExecution.
  • PlexCleaner/FfProbeTool.cs GetAnalysisPackets, introduced, design: its failure branch checks the cancel by hand rather than calling LogFailedExecution. Declined by the maintainer's decision. Routing it through the helper would thread an exit code through GetPackets and GetPacketsAsync. It would also change a real failure's log from the full FFprobe stderr to a one-line summary.

Related

#1309 stays open. Its internal CLR error did not reproduce in about 120 interrupted runs, and this change fixes the race it describes rather than that fault. The fleet-wide .NET interrupt rule these findings led to is ptr727/ProjectTemplate#4507.

The comments label is on this pull request because the exit-code comment in Program.Main is reworded. It states the race, which the code alone does not carry.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Improved handling of cancelled tool runs: interrupted files are now marked as Cancelled instead of being treated as tool errors, and cancellation is logged as a warning.
    • Fixed startup cancellations being reported as missing tools.
    • Ctrl+C interruptions now exit with code 130 when the signal is handled before the application can process it.

ptr727 and others added 3 commits November 26, 2026 14:26
A terminal Ctrl+C signals the whole process group, so a running tool can
exit before PlexCleaner's asynchronously dispatched signal handler runs.
A failed command now waits for that handler before choosing its exit
code, startup tool verification reports the cancel rather than a missing
tool, and an interrupted file is kept as cancelled rather than as a tool
error. The handlers register before the logger is created, and a
cancelled tool run logs a warning.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A tool that the same signal ended before the handler ran returns an
ordinary failed result, so LogFailedResult and the FFmpeg verify log it
as a failed execution at error level. Both now log it as cancelled at
warning level once the cancel is seen, and folder tool verification
skips its "not found" error on a cancel as system tool verification does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The FFmpeg verify logged its failed execution inline with a copy of
LogFailedResult's templates, so the cancel check had two homes. Both now
call LogFailedExecution, and the FFprobe analysis packet scan logs a
cancel as a warning too. Moving the signal registration ahead of the
logger fixed none of the startup failures, since tool verification runs
inside the command, so it returns to where it was.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@ptr727 ptr727 added the comments Permits the comment lines the pull request adds or edits, which the prose gate otherwise refuses label Nov 26, 2026
Copilot AI lite review requested due to automatic review settings November 26, 2026 22:50
@ptr727 ptr727 added the comments Permits the comment lines the pull request adds or edits, which the prose gate otherwise refuses label Nov 26, 2026
@coderabbitai

coderabbitai Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

Tool cancellation handling now uses shared warning-level logging and checks cancellation separately from tool failures. Interrupted files are classified as Cancelled, and the release notes describe the behavior.

Changes: Tool cancellation handling

Layer / File(s) Summary
Centralize tool failure and cancellation logging
PlexCleaner/MediaTool.cs, PlexCleaner/FfMpegTool.cs
MediaTool centralizes failure and cancellation logging. FfMpegTool passes the exit code and cleaned error summary to the shared failure logger.
Apply cancellation handling across tool paths
PlexCleaner/Program.cs, PlexCleaner/Tools.cs, PlexCleaner/FfProbeTool.cs, PlexCleaner/MediaTool.cs
Command execution and packet retrieval use the shared cancellation recorder. Cancellation checks prevent tool lookup and packet retrieval failures caused by cancellation from being logged as missing-tool or generic failures. Main waits up to 100 ms for cancellation handling after a non-success command exit.
Classify interrupted files
PlexCleaner/ProcessFile.cs, HISTORY.md
KeepFailedFileReason checks cancellation before tool errors and signals, while rename collisions remain highest priority. The release notes describe the cancellation behavior.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix

Possibly related issues

  • ptr727/PlexCleaner#1194 — The PR changes cancellation paths discussed in the issue, but does not add the requested cancellation seam or test coverage.
  • ptr727/PlexCleaner#1309 — The PR changes handling of SIGINT during tool execution and interrupted-file classification. The reported CLR fault remains unfixed.

Possibly related PRs

  • ptr727/PlexCleaner#1112 — Both PRs change how signal-ended tool runs are recorded and how affected files are classified.
  • ptr727/PlexCleaner#1089 — Both PRs address classification of FFmpeg verification failures and how those failures affect file handling.
Merge Risk: Minimal · up to 81ac3

This change makes Ctrl+C handling more reliable. It exits with code 130, logs cancelled tool runs as warnings, and keeps interrupted files marked as Cancelled. No merge-blocking risk was found.

Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title names the main behavior change: Ctrl+C that ends a tool before the signal handler runs now results in exit code 130. The changeset matches this. Program.cs keeps the signal exit-code overrid…
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.
Full details: Title check

Explanation

The title names the main behavior change: Ctrl+C that ends a tool before the signal handler runs now results in exit code 130. The changeset matches this. Program.cs keeps the signal exit-code override and waits up to 100 ms for cancellation handling after a non-success exit. The title is specific and concise. It is a single sentence with no file lists or vague terms.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 52c9574 and 81ac3b0.

Files selected for processing: 7

  • HISTORY.md
  • PlexCleaner/FfMpegTool.cs
  • PlexCleaner/FfProbeTool.cs
  • PlexCleaner/MediaTool.cs
  • PlexCleaner/ProcessFile.cs
  • PlexCleaner/Program.cs
  • PlexCleaner/Tools.cs

Included review availability: This review used your included allowance. Your plan provides up to 2 included reviews per hour; 1 remain after this review.

@ptr727

ptr727 commented Nov 26, 2026

Copy link
Copy Markdown
Owner Author

A recorded local strict-review pass covers head de617830fa54d7924363ea657f10aada355a09a4, the content this pull request carries at that commit against develop, and it recorded 2 findings.

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

PR Summary by Qodo

Preserve signal exit codes and cancellation status when tools exit first

🐞 Bug fix 🕐 20-40 Minutes

Grey Divider

AI Description

• Wait briefly for a pending signal handler before reporting a failed command’s exit code.
• Treat interrupted startup checks and file processing as cancellations, not tool failures.
• Log cancelled tool runs as warnings across buffered, streamed, and packet-scan paths.
Merge Risk 🟡 Medium

Blast radius 🟡 Medium 💥 2 capabilities

  • 2 affected capabilities within one bounded functional scope: graceful cancellation handling.
  • The changed helper, signal wait, and tool call sites jointly determine how an interrupted media operation is classified and logged.
  • These are execution and reporting facets of one bounded cancellation integration, not independent user capabilities.
  • This capability is the per-file outcome of the same cancellation integration: the file-processing caller consumes tool cancellation state and chooses whether to retain the unproven file.
  • It is a distinct user-visible outcome within the bounded integration.
Sources

PlexCleaner/ProcessFile.cs[2013-2018]

    private string? KeepFailedFileReason() =>
        _renameCollision ? "Rename collision"
        : Program.IsCancelledError() ? "Cancelled"
        : ToolErrorScope.Count > 0 ? "Tool error"
        : ToolErrorScope.SignalCount > 0 ? "Tool signal"
        : null;
Behavioral complexity 🔴 High 🧩 Interacting branches, Concurrent ordering

  • Before, cancellation, signal, and ordinary tool-error outcomes were handled at separate call sites.
  • After, shared helpers and a post-command wait coordinate signal-handler timing, tool exit classification, error-scope recording, startup guards, and file-retention precedence.
  • New correctness conditions are that a signal-induced tool exit must be classified consistently across the handler race, and cancellation must outrank tool-error state when retaining the file.
  • The existing cancellation token and logging infrastructure are reused; the newly interacting ordering is the material complexity.
Sources

PlexCleaner/ProcessFile.cs[2013-2018]

    private string? KeepFailedFileReason() =>
        _renameCollision ? "Rename collision"
        : Program.IsCancelledError() ? "Cancelled"
        : ToolErrorScope.Count > 0 ? "Tool error"
        : ToolErrorScope.SignalCount > 0 ? "Tool signal"
        : null;
Potential damage 🟡 Medium 🩹 Recoverable

  • If cancellation is misclassified, the interrupted file can receive the wrong diagnostic reason and follow the ordinary tool-error handling path.
  • The file is retained as unproven rather than deleted by this changed branch, and a later retry can restore normal processing.
  • A subsequent run can retry the retained file.
  • Reverting stops new misclassification; any already-written diagnostic state would need the normal retry or sidecar processing path, but no irreversible media effect is established.
Sources

PlexCleaner/ProcessFile.cs[2013-2018]

    private string? KeepFailedFileReason() =>
        _renameCollision ? "Rename collision"
        : Program.IsCancelledError() ? "Cancelled"
        : ToolErrorScope.Count > 0 ? "Tool error"
        : ToolErrorScope.SignalCount > 0 ? "Tool signal"
        : null;
Assessed commit 81ac3b0
Diagram

graph TD
  SIG["Signal handler"] --> TOKEN["Cancel token"] --> CHECK{"Cancellation detected?"} --> LOG["Tool warning"] --> KEEP["File retention"] --> EXIT["Signal exit"]
  TOOL["Tool failure"] --> CHECK
  CHECK --> VERIFY["Startup verification"] --> EXIT
Loading
High-Level Assessment

The bounded wait reuses the existing cancellation check and preserves the signal handler as the authority for exit codes. Inferring a signal solely from a tool’s exit code would be ambiguous, so the PR’s approach is preferable.

Files changed (7) +60 / -35

Bug fix (6) +56 / -35
FfMpegTool.csShare failure logging for FFmpeg verification +6/-26

Share failure logging for FFmpeg verification

• Routes decode-verification failures through the shared logger so cancellations receive warning-level treatment while ordinary failures retain their error summaries.

PlexCleaner/FfMpegTool.cs

FfProbeTool.csClassify interrupted packet scans as cancellations +6/-1

Classify interrupted packet scans as cancellations

• Logs token-cancelled packet execution as a warning. Suppresses the analysis-packet failure error when cancellation caused the scan to stop.

PlexCleaner/FfProbeTool.cs

MediaTool.csCentralize cancellation-aware tool failure logging +30/-6

Centralize cancellation-aware tool failure logging

• Introduces a shared failed-execution logger that emits cancellation warnings instead of failure errors. Changes cancelled-token catches in buffered and streamed execution to warning level.

PlexCleaner/MediaTool.cs

ProcessFile.csPrioritize cancellation when retaining failed files +1/-1

Prioritize cancellation when retaining failed files

• Places Cancelled ahead of Tool error and Tool signal when selecting why an interrupted file is kept. Rename collisions retain their existing priority.

PlexCleaner/ProcessFile.cs

Program.csWait for pending signal handling before choosing an exit code +5/-1

Wait for pending signal handling before choosing an exit code

• On command failure, invokes the existing bounded cancellation check before reading the signal exit code. This lets a tool that exits first still produce the signal-specific process code.

PlexCleaner/Program.cs

Tools.csAvoid missing-tool errors during cancelled verification +8/-0

Avoid missing-tool errors during cancelled verification

• System and folder tool verification return on cancellation without reporting an interrupted tool as not found.

PlexCleaner/Tools.cs

Documentation (1) +4 / -0
HISTORY.mdDocument interrupted-tool behavior +4/-0

Document interrupted-tool behavior

• Records the corrected Ctrl+C exit code, cancellation classification, and warning-level tool logs.

HISTORY.md

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (1) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Remediation recommended

1. Failed media files slow batch processing 🐞 Bug ➹ Performance
Description
LogFailedExecution calls Program.IsCancelledError() for every failed tool result, which blocks
for 100 ms when no cancellation is pending. During batch processing, ordinary tool failures
therefore occupy a file-processing worker for an additional 100 ms per invocation, even when no
signal was sent.
Code

PlexCleaner/MediaTool.cs[241]

+        if (Program.IsCancelledError())
Evidence
The new call in the shared logger reaches a 100 ms wait whenever the cancellation source has not
been cancelled. FFmpeg verification calls this logger on a decode failure, and the file-processing
driver runs that work synchronously on a bounded number of workers.

PlexCleaner/MediaTool.cs[234-250]
PlexCleaner/Program.cs[546-557]
PlexCleaner/FfMpegTool.cs[196-212]
PlexCleaner/ProcessDriver.cs[189-202]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The shared failed-execution logger adds a 100 ms cancellation wait to every ordinary tool failure in batch processing.
## Fix Focus Areas
- PlexCleaner/MediaTool.cs[234-250]
- PlexCleaner/Program.cs[546-557]
- PlexCleaner/FfMpegTool.cs[199-212]
## Recommended Fix
Keep the bounded wait where it is needed to distinguish a signal-ended child from a tool failure, but avoid repeating it indiscriminately for ordinary failures. Reuse an established cancellation decision where available, or narrowly gate the wait while preserving detection of a child that exits before the signal handler runs.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Tip of the day
💡 Did you know, you can tweak Display settings with a live preview to see your comment before it ships

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

Copilot AI 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.

🟡 Changes recommended

Approval is blocked by three active nit findings: an unclear cancellation history entry and duplicated cancellation-handling logic that should be centralized.

1 open issue
What changed in this PR

This PR hardens Ctrl+C handling when a child media tool exits before PlexCleaner’s signal handler runs. It preserves signal-derived exit codes, classifies interrupted files as cancelled, suppresses misleading startup errors, and adjusts cancellation logging.

Changes:

  • Waits briefly for pending signal handling before selecting the final exit code.
  • Treats interrupted tool verification and media processing as cancellation.
  • Centralizes failed-tool logging behavior and records cancelled executions at warning level.
  • Documents the updated cancellation behavior.
File Description
PlexCleaner/​Tools.cs Detects cancellation during system and folder tool verification to avoid misleading missing-tool errors.
PlexCleaner/​Program.cs Waits for pending signal handling before finalizing failed command exit codes.
PlexCleaner/​ProcessFile.cs Prioritizes cancelled processing when determining the reason an interrupted file is retained.
PlexCleaner/​MediaTool.cs Centralizes failed-execution logging and records cancelled tool runs as warnings.
PlexCleaner/​FfProbeTool.cs Handles cancelled packet analysis and applies warning-level cancellation logging.
PlexCleaner/​FfMpegTool.cs Routes verification failures through the shared cancellation-aware logger.
HISTORY.md Documents the updated Ctrl+C exit-code, file-state, and cancellation-logging behavior.

Review effort: Lite

Comment thread HISTORY.md Resolved
The three cancelled-token catches each logged the same cancelled
execution warning and recorded a tool error. RecordCancelledExecution
now does both beside LogFailedExecution.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@ptr727

ptr727 commented Nov 26, 2026

Copy link
Copy Markdown
Owner Author

A recorded local strict-review pass covers head 2188b946082d4327c42c29d4a9336e6cfc56d0d1, the content this pull request carries at that commit against develop, and it recorded 0 findings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@ptr727

ptr727 commented Nov 26, 2026

Copy link
Copy Markdown
Owner Author

@qodo-free-for-open-source-projects please dismiss the finding "Failed media files slow batch processing" at PlexCleaner/MediaTool.cs line 241 (LogFailedExecution, the Program.IsCancelledError() call).

Disproven. The up-to-100 ms wait is the fix itself, not an accidental cost.

  • It runs only on a failed tool run. A successful run never reaches LogFailedExecution.
  • A terminal Ctrl+C signals the tool and PlexCleaner together, and the .NET signal handler runs asynchronously. So a tool killed by the shared SIGINT can return before the handler has cancelled the token. Without the wait, that run is logged as a failed execution at error level, which is the race this pull request fixes.
  • It is the existing IsCancelledError() contract, which Convert.cs already applies on its remux failure path for the same reason.
  • The cost is bounded at 100 ms per failed tool run, and each such run has already started a process and run a media tool.

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

please dismiss the finding "Failed media files slow batch processing" at PlexCleaner/MediaTool.cs line 241 (LogFailedExecution, the Program.IsCancelledError() call).

Disproven. The up-to-100 ms wait is the fix itself, not an accidental cost.

  • It runs only on a failed tool run. A successful run never reaches LogFailedExecution.
  • A terminal Ctrl+C signals the tool and PlexCleaner together, and the .NET signal handler runs asynchronously. So a tool killed by the shared SIGINT can return before the handler has cancelled the token. Without the wait, that run is logged as a failed execution at error level, which is the race this pull request fixes.
  • It is the existing IsCancelledError() contract, which Convert.cs already applies on its remux failure path for the same reason.
  • The cost is bounded at 100 ms per failed tool run, and each such run has already started a process and run a media tool.

I haven't dismissed it. The published report lists "Failed media files slow batch processing" as finding 1 in the main list, but this PR's findings index is currently empty, so I can't map it to a stable finding ID. Dismissing requires that ID.

Options:

  • Ask me again in a few minutes. The index may not have synced yet.
  • Ask me to run a new review (@qodo review again). Once the finding is indexed, I can dismiss it if you still want that.

Your reasoning is clear: the 100 ms wait only runs on failed tool runs and guards against the SIGINT race. If the finding is dismissed, the report should still reflect that decision.

@ptr727

ptr727 commented Nov 26, 2026

Copy link
Copy Markdown
Owner Author

A recorded local strict-review pass covers head 81ac3b078055d77725447d589abdd333f76ee0a5, the content this pull request carries at that commit against develop, and it recorded 0 findings.

@ptr727

ptr727 commented Nov 26, 2026

Copy link
Copy Markdown
Owner Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@ptr727
ptr727 merged commit fcd0acc into develop Nov 26, 2026
25 checks passed
@ptr727
ptr727 deleted the fix-signal-race branch November 26, 2026 23:38
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comments Permits the comment lines the pull request adds or edits, which the prose gate otherwise refuses

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants