Skip to content

fix(agents): terminate background CLI tasks on cron timeout - #143355

Closed
MasterSwords1 wants to merge 3 commits into
openclaw:mainfrom
MasterSwords1:fix/138499-cron-timeout-cli-task
Closed

MasterSwords1 wants to merge 3 commits into
openclaw:mainfrom
MasterSwords1:fix/138499-cron-timeout-cli-task

Conversation

@MasterSwords1

@MasterSwords1 MasterSwords1 commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Closes #138499

What Problem This Solves

Resolves a problem where cron jobs running automated agent turns that launch background CLI tasks via the exec tool leave orphaned processes running on the host when the cron job times out, causing the Gateway restart drain loop to block and eventually force-shutdown.

Why This Change Was Made

When a cron job hits its execution deadline, cleanupTimedOutAgentRun triggers an abort with reason "cron_timeout". We ensure this timeout reason propagates through abortEmbeddedAgentRun and EmbeddedAgentQueueHandle.abort to prepareEmbeddedAttemptStream, where the abort is classified as a timeout with TimeoutError.

Key design decisions:

  1. Timeout reason ordering & re-entrancy: In prepareEmbeddedAttemptStream, input.abortRun(true, createTimeoutAbortReason()) and attempt.onDeferredLifecycleAbort?.(reason) are invoked before attempt.onAttemptAbort?.(), preventing re-entrant generic cancellation callbacks from the lane controller from latching first and discarding the TimeoutError.
  2. Selective background process termination: In bash-tools.exec-run.ts, backgrounded execution retains its abort signal listener until process settlement (settlement.onSettled = detachAbortListener;), allowing isSignalTimeoutReason(signal?.reason) to terminate background processes on TimeoutError while preserving them across ordinary turn cancellations and restarts.
  3. Task settlement & restart unblocking: Process settlement triggers finalizeBackgroundExecTask, recording the task's terminal state and clearing the background-exec active work restart blocker in gateway-active-work.ts.

User Impact

Scheduled cron jobs that launch background CLI commands will no longer leak orphaned processes when the cron job reaches its execution deadline, preventing host resource exhaustion and enabling graceful Gateway restarts.

Evidence

1. Real Behavior Runtime Verification

Executed an end-to-end integration test against the real process supervisor, real exec tool, real process registry, and real gateway active work monitor (verify-cron-timeout-real.ts):

=== STEP 1: Setting up Embedded Agent Run & Tool Execution ===
=== STEP 2: Spawning Real Background CLI Task via Exec Tool ===
Exec tool result status: running
Background Session ID: plaid-tidepool
Child PID: 321092
Active background exec session count: 1
Gateway restart blocked before timeout? true
Active blocker before: 1 active background exec session(s)
Child process alive in OS before timeout: true

=== STEP 3: Triggering Cron Timeout Abort ===
Simulating cron scheduler: queueHandle.abort('cron_timeout')
[Attempt] External abort marked
Run abort signal aborted? true
Run abort signal reason: TimeoutError
Abort state terminal outcome: {"kind":"timeout","phase":"prompt","source":"runtime","aborted":true}

=== STEP 4: Waiting for Process Settlement & Task Finalization ===
Finished session found: true
Finished session terminal status: failed
Finished session exit signal/code: SIGTERM
Child process alive in OS after timeout: false
Active background exec session count after timeout: 0
Gateway restart blocked after timeout? false

=== VERIFICATION SUMMARY ===
Real cron timeout process cleanup verified: SUCCESS

2. Targeted Vitest Test Suites

All targeted suites pass cleanly (node scripts/run-vitest.mjs <file>):

  • src/agents/bash-tools.exec.background-abort.test.ts (9/9 passed):
    • background exec is not killed when tool signal aborts
    • pty background exec is not killed when tool signal aborts
    • background exec still times out after tool signal abort
    • background exec without explicit timeout applies default timeout
    • background exec with timeout zero bypasses default timeout
    • yielded background exec still times out
    • yieldMs exec without explicit timeout applies default timeout
    • background exec is killed when tool signal aborts with TimeoutError
    • yielded background exec is killed when tool signal aborts with TimeoutError
  • src/agents/embedded-agent-runner/run/attempt-stream-prepare.test.ts (30/30 passed):
    • processes cron_timeout abort through external-abort sequence as a timeout
    • preserves timeout classification when onAttemptAbort synchronously triggers re-entrant generic abort
  • src/agents/bash-tools.test.ts (33/33 passed):
    • removes the abort listener when an exec process is backgrounded and exits
  • src/agents/embedded-agent-runner/runs.lifecycle.test.ts (23/23 passed):
    • forwards cron_timeout reason to abortEmbeddedAgentRun
  • src/agents/embedded-agent-runner/run/deferred-lifecycle-owner.test.ts (2/2 passed):
    • publishes CLI cancellation authority before releasing the embedded attempt
    • records only the accepted candidate terminal trajectory

3. Static Checks & Ratchets (node scripts/check-changed.mjs --staged)

  • Max-lines suppression ratchet: 840 grandfathered suppressions (0 new)
  • Assertion SAFETY comment ratchet: 11,704 grandfathered assertions (0 new)
  • Typecheck core & all test shards: Passed
  • Dead code scan (knip): 0 unused exports
  • Linter (oxlint --type-aware): 0 warnings, 0 errors

@clawsweeper

clawsweeper Bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime agents Agent runtime and tooling size: M labels Sep 9, 2026
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 9, 2026
@clawsweeper

clawsweeper Bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge.

What this changes

This PR propagates cron timeout reasons through agent cancellation and terminates background exec processes when their owning run times out.

Example: A cron timeout occurs while background session plaid-tidepool, child PID 321092, is running.

  • Before: The child remains alive and the background-exec restart blocker remains active.
  • After: The supplied trace shows SIGTERM, a failed terminal task, zero active background sessions, and no restart blocker.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The focused patch has meaningful process-boundary proof and no discrete correctness finding, while product acceptance remains unresolved.
Proof confidence 🦐 gold shrimp (3/6) Sufficient (terminal): The supplied runtime trace exercises the changed queue-handle cancellation path with the real exec tool, supervisor, registry, and restart monitor, showing TimeoutError propagation, child termination, task settlement, and restart unblocking.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Needs a maintainer decision · Fix scope: Complete
User problem: A timed-out scheduled agent turn leaves its background CLI task running and prevents graceful Gateway restart.
Reason: The cleanup has concrete operational value, but the generic TimeoutError guard reaches independent services beyond the reported cron case and the widened abort overload is publicly exported.

Merge readiness

⛔ Blocked before merge - 1 item remains

Keep this PR open: it contains useful, demonstrated cleanup work, but the persistent-command lifetime contract remains undecided and GitHub reports merge conflicts.

Priority: P1
Reviewed head: e7904fb86a5378ed3d0461c6fcb10dfa158a07a1
Owner decision: Required. See Decision needed.

Decision needed

  • Question: Should owning-run timeouts terminate deliberately independent background:true commands, including timeoutSeconds:0 services, and should plugins receive cron_timeout through the public cancellation API?
  • Recommendation: Keep the repair scoped to cron ownership: Define cron expiry as terminal for commands owned by that occurrence, document the timeoutSeconds:0 exception, and use an internal cancellation path unless the public SDK addition is independently needed.
  • Why: The cleanup incident warrants repair, but current main explicitly distinguishes independent services from request-owned commands, and neither the discussion nor prior review records an accepted exception for deadlines.

Before merge

  • Complete next step - After the contract is settled, resolve the GitHub-reported conflicts against current lifecycle owners and validate the resulting cancellation paths.

Findings

None.

Tests

  • Missing end-to-end proof: The supplied proof exercises the real process boundary rather than a scheduled Gateway invocation, and no failing-base run of the new regression tests is recorded.
Agent review details

How this fits together

Cron cleanup enters the agent cancellation owners, which abort exec processes through the process supervisor; process settlement finalizes task tracking consumed by Gateway restart monitoring.

flowchart TD
  A[Cron deadline] --> B[Agent cancellation owner]
  B --> C[Attempt timeout signal]
  C --> D[Exec process supervisor]
  D --> E[Process settlement]
  E --> F[Task tracking]
  F --> G[Gateway restart monitor]
Loading

Technical review

Best possible solution:

Define the cron-owned command lifetime explicitly, then integrate timeout cleanup through the current session/request and process-settlement owners.

Do we have a high-confidence way to reproduce the issue?

Source establishes the explicit-background cleanup path, and the supplied real-process trace demonstrates the candidate's termination behavior; no current-main runtime reproduction was run.

Is this the best way to solve the issue?

Propagating timeout classification before reentrant cancellation addresses the original mechanism, but integration should use current lifecycle owners and an accepted independent-service contract.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against e7f054619274.

Provenance checked

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 73bead1 adds src/agents/bash-tools.exec-run.ts:630 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 73bead12393e; files: src/agents/bash-tools.exec-run.ts)
  • joshavant: Raw commit 5cc2fa6 adds src/agents/embedded-agent-runner/runs.ts:894 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 5cc2fa624925; files: src/agents/embedded-agent-runner/runs.ts)
  • xingzhou: Raw commit af74c9c adds src/agents/embedded-agent-runner/run/deferred-lifecycle-owner.ts:94 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: af74c9c0e004; files: src/agents/embedded-agent-runner/run/deferred-lifecycle-owner.ts)

PR surface

Source +49, Tests +173. Total +222 across 14 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 10 82 33 +49
Tests 4 175 2 +173
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 14 257 35 +222

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #138499
Summary: This PR targets the canonical background-command timeout report; replacement-run protection and late completion admission are separate work.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Labels

Label changes:

No label changes.

Label justifications:

  • P1: The linked incident describes a cron-owned command surviving for hours and exhausting graceful Gateway restart drainage.
  • merge-risk: 🚨 compatibility: The patch changes persistent background-command lifetime, including timeoutSeconds:0 commands, and widens an existing plugin-facing cancellation API.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Record and document the accepted persistent-command lifetime and public SDK timeout contract.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (7 earlier review cycles)
  • reviewed 2026-09-09T19:49:05.760Z sha 275692df47885649522edaa6673da8cd46979428 :: needs real behavior proof before merge. :: [P1] Propagate the timeout before invoking generic abort cleanup
  • reviewed 2026-09-09T20:36:00.610Z sha 801b17d6c99019a72d247b0f9ef301c9d995a7a6 :: needs real behavior proof before merge. :: [P1] Propagate the timeout before invoking generic abort cleanup
  • reviewed 2026-09-09T20:51:01.037Z sha 801b17d6c99019a72d247b0f9ef301c9d995a7a6 :: needs real behavior proof before merge. :: [P1] Propagate the timeout before invoking generic abort cleanup
  • reviewed 2026-09-10T05:53:15.657Z sha 90d09ad7f6a57305a5f549111f40f799ef1d5cf5 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-12T18:51:05.567Z sha e7904fb :: blocked before merge. :: none
  • reviewed 2026-09-23T14:58:15.599Z sha e7904fb :: blocked before merge. :: none
  • reviewed 2026-10-04T14:30:17.982Z sha e7904fb :: blocked before merge. :: none

Reviewed October 27, 2026, 9:15 PM ET / October 28, 2026, 01:15 UTC (Revision 8).

@MasterSwords1
MasterSwords1 force-pushed the fix/138499-cron-timeout-cli-task branch from 275692d to 801b17d Compare September 9, 2026 20:27
@MasterSwords1

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@MasterSwords1

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 10, 2026
@jalehman jalehman self-assigned this Sep 10, 2026
…lback

Ensure external cron_timeout aborts latch the TimeoutError reason before
notifying onAttemptAbort callbacks, preventing synchronous lane controller
cancellation from preempting the timeout classification with a generic abort.

Also update bash-tools backgrounded listener test to assert listener retention
until process exit and add regression test for re-entrant attempt aborts.
@openclaw-barnacle

Copy link
Copy Markdown

This assigned pull request has been automatically marked as stale after being open for 27 days.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label Oct 7, 2026
@ekinnee

ekinnee commented Oct 9, 2026

Copy link
Copy Markdown
Contributor

Following up on the cancellation work connected in #163568: #163704 has merged the stale-timeout repair that protects a replacement run. This PR addresses the separate background-process cleanup path.
The remaining decision in the review is whether an owning run’s timeout should also terminate persistent background commands, including timeoutSeconds: 0, and expose that behavior through the public cancellation API—or whether this should remain an internal cron-only change.
Could the assigned maintainer settle that contract first, so the author can integrate and validate against an agreed scope?

@openclaw-barnacle openclaw-barnacle Bot removed the stale Marked as stale due to inactivity label Oct 10, 2026
@openclaw-barnacle

Copy link
Copy Markdown

This assigned pull request has been automatically marked as stale after being open for 27 days.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label Oct 10, 2026
@roboclaw-bot roboclaw-bot added the clawtributors PR from a clawtributor label Oct 28, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Oct 28, 2026
@MasterSwords1

Copy link
Copy Markdown
Contributor Author

Closing: #138499 is a protected maintainer issue labeled no-new-fix-pr and needs-product-decision, and this branch has conflicted with main since September. The command-lifetime contract should be decided by maintainers first; this PR cannot land ahead of that decision.

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

Labels

agents Agent runtime and tooling clawtributors PR from a clawtributor gateway Gateway runtime merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: M stale Marked as stale due to inactivity status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Timed-out cron session leaves session-scoped CLI task running

4 participants