Skip to content

Fix managed run controller edge cases #1987

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 16 commits into from
Apr 28, 2025
Merged

Conversation

nicktrn
Copy link
Collaborator

@nicktrn nicktrn commented Apr 28, 2025

  • ensure previous executions are always killed
  • improve websocket disconnect logs
  • protect against unexpected attempt number changes
  • don't handle snapshot changes when shutting down
  • prevent parallel snapshot polling intervals
  • improve child process preparedness checks

Summary by CodeRabbit

  • Bug Fixes

    • Resolved issues with polling interval resets to prevent duplicate intervals and overlapping executions.
    • Fixed problems where run executions could become stuck or duplicated after warm starts, ensuring proper cleanup.
    • Added safeguards against unexpected changes in execution attempt numbers.
  • New Features

    • Improved lifecycle management for run executions, including enhanced tracking and validation of execution attempts.
    • Enhanced debug logging for better visibility during execution and socket disconnect events.
  • Refactor

    • Streamlined internal state management for polling and execution processes, improving reliability and idempotency.
    • Removed deprecated heartbeat utility in favor of improved interval management.

Copy link

changeset-bot bot commented Apr 28, 2025

🦋 Changeset detected

Latest commit: aef9ccb

The changes in this PR will be included in the next version bump.

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

Copy link
Contributor

coderabbitai bot commented Apr 28, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

This set of changes enhances the execution lifecycle management for run executions, focusing on preventing duplicate polling intervals, handling attempt number mismatches, and avoiding orphaned or "zombie" executions after warm starts. The updates introduce new state-tracking properties and methods to classes responsible for execution and polling, ensuring idempotent operations and robust cleanup. Debug logging is standardized and improved for better traceability. The interval service is updated to prevent overlapping handler executions. No public API signatures are altered, but several new internal methods and properties are added to support these behaviors.

Changes

File(s) Change Summary
.changeset/tidy-books-smell.md Documents the bug fixes and enhancements to polling, attempt number handling, and zombie execution prevention in the "trigger.dev" and "@trigger.dev/core" packages.
packages/cli-v3/src/entryPoints/managed/controller.ts Improves run execution lifecycle by ensuring existing executions are killed before creating new ones, updates debug logging, and introduces a helper for structured socket disconnect messages.
packages/cli-v3/src/entryPoints/managed/execution.ts Adds attempt number tracking, improves validation and lifecycle management for retries, introduces shutdown state handling, and updates method names and visibility for clarity and robustness.
packages/cli-v3/src/entryPoints/managed/poller.ts Adds an enabled flag for poller state, consolidates debug logging, and ensures idempotent start/stop operations for the polling interval.
packages/cli-v3/src/executions/taskRunProcess.ts Introduces tracking for "prepared for next attempt" state, adds corresponding getter, and updates execution preparation logic without changing cancellation/cleanup behavior.
packages/core/src/v3/utils/interval.ts Adds an _isExecuting flag to prevent overlapping interval handler executions, ensures consistent scheduling, and exposes the interval duration via a getter.
packages/core/src/v3/index.ts Removes export of the heartbeat.js utility module, stopping its re-export from the barrel file.
packages/core/src/v3/utils/heartbeat.ts Removes the entire deprecated HeartbeatService class and its related types, eliminating the old heartbeat mechanism in favor of the newer interval service.

Sequence Diagram(s)

sequenceDiagram
    participant Controller
    participant Execution
    participant Poller
    participant TaskRunProcess

    Controller->>Execution: Start new run execution
    alt Existing execution not ready
        Execution->>TaskRunProcess: Kill existing execution
        Execution-->>Controller: Execution killed
    end
    Controller->>Execution: Create new execution if canExecute

    Poller->>Execution: Poll for snapshot changes
    Execution->>TaskRunProcess: Validate attempt number
    alt Attempt number mismatch
        Execution->>TaskRunProcess: Suspend process
        Execution-->>Poller: Abort processing
    else
        Execution->>TaskRunProcess: Continue execution
    end

    Execution->>TaskRunProcess: Start/Retry attempt
    TaskRunProcess-->>Execution: Update attempt state
Loading

Possibly related PRs

  • triggerdotdev/trigger.dev#1905: Both PRs address execution lifecycle and state handling, focusing on robustness and cleanup of run executions.
  • triggerdotdev/trigger.dev#1987: Identical in content, addressing fixes and improvements to the managed run controller including execution lifecycle and attempt number validation.
  • triggerdotdev/trigger.dev#1963: Both PRs improve handling of run execution states and snapshot changes, including suspension and error logging for unexpected attempt numbers.

Suggested reviewers

  • matt-aitken

Poem

In the warren of code, no zombies arise,
With intervals neat and no duplicate tries.
Attempts are now counted, no numbers amiss,
Pollers behave, and nothing’s remiss.
Debug logs are tidy, the shutdown is clean—
A rabbit’s delight: robust and serene!
🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e25a08e and aef9ccb.

📒 Files selected for processing (2)
  • packages/core/src/v3/index.ts (0 hunks)
  • packages/core/src/v3/utils/heartbeat.ts (0 hunks)
✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (1)
packages/cli-v3/src/entryPoints/managed/poller.ts (1)

65-75: Minor: duplicated runId inside properties

runId is already sent at the top level of the log payload. Duplicating it inside properties increases payload size and may confuse downstream log processors.

If you need it only once, consider:

-      properties: {
-        ...properties,
-        runId: this.runFriendlyId,
+      properties: {
+        ...properties,
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7bdbbdc and 239e2b2.

📒 Files selected for processing (6)
  • .changeset/tidy-books-smell.md (1 hunks)
  • packages/cli-v3/src/entryPoints/managed/controller.ts (3 hunks)
  • packages/cli-v3/src/entryPoints/managed/execution.ts (10 hunks)
  • packages/cli-v3/src/entryPoints/managed/poller.ts (3 hunks)
  • packages/cli-v3/src/executions/taskRunProcess.ts (3 hunks)
  • packages/core/src/v3/utils/interval.ts (5 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
packages/cli-v3/src/entryPoints/managed/controller.ts (2)
packages/cli-v3/src/entryPoints/managed/execution.ts (2)
  • runFriendlyId (953-959)
  • runFriendlyId (961-963)
packages/cli-v3/src/entryPoints/dev-run-controller.ts (1)
  • runFriendlyId (262-268)
⏰ Context from checks skipped due to timeout of 90000ms (7)
  • GitHub Check: e2e / 🧪 CLI v3 tests (windows-latest - pnpm)
  • GitHub Check: e2e / 🧪 CLI v3 tests (windows-latest - npm)
  • GitHub Check: e2e / 🧪 CLI v3 tests (ubuntu-latest - pnpm)
  • GitHub Check: e2e / 🧪 CLI v3 tests (ubuntu-latest - npm)
  • GitHub Check: typecheck / typecheck
  • GitHub Check: units / 🧪 Unit Tests
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (16)
packages/core/src/v3/utils/interval.ts (5)

16-16: Added execution guard to prevent concurrent interval handler executions.

The new _isExecuting flag is introduced to track whether the interval handler is currently running, initialized to false in the constructor. This prevents overlapping executions of the same interval handler.

Also applies to: 26-26


57-59: Early return during execution prevents duplicate interval scheduling.

This protection in resetCurrentInterval() prevents scheduling a new interval while the handler is still executing, avoiding potential race conditions that could create duplicate intervals.


81-86: Prevent concurrent execution of interval handler.

This check prevents the interval handler from running multiple times in parallel, which could lead to race conditions or unexpected behavior when the execution time exceeds the interval duration.


98-100: Ensure scheduler runs in finally block and reset execution flag.

Moving the interval scheduling to the finally block ensures it always happens, regardless of success or failure. Resetting the _isExecuting flag to false is also crucial to allow future executions.


70-72: Added getter for interval duration.

The new intervalMs getter exposes the current interval duration, which is useful for debugging and logging purposes.

.changeset/tidy-books-smell.md (1)

1-8: Clear and concise changeset for this fix.

The changeset properly documents the patches applied to the related packages, listing the three main issues being addressed:

  1. Fixing duplicate intervals in polling
  2. Adding protection against unexpected attempt number changes
  3. Preventing run execution zombies after warm starts

These align well with the code changes observed in the other files.

packages/cli-v3/src/executions/taskRunProcess.ts (3)

92-92: Added tracking of preparation state for next attempt.

The new _isPreparedForNextAttempt property distinguishes between being prepared for a completely new run versus being prepared for a retry attempt of the current run. This initialization in the constructor ensures it starts in a ready state.

Also applies to: 96-96


103-105: Added getter for attempt preparation state.

This public getter exposes the attempt preparation state, allowing other components (like RunExecution) to check if the process is ready for a new attempt before deciding to reuse or kill it.


232-232: Execution lifecycle tracking for attempt management.

Setting _isPreparedForNextAttempt to false at the start of execution and back to true after completion ensures proper tracking of whether the process can accept a new attempt. This helps prevent issues with immediately retried executions.

Also applies to: 276-276

packages/cli-v3/src/entryPoints/managed/controller.ts (5)

181-190: Prevent zombie executions by killing stale ones.

This new logic explicitly kills any existing execution that is not ready to execute before creating a new one. This prevents resource leaks and ensures clean execution states, especially after warm starts.


191-191: Update condition to use new execution readiness check.

Changed from checking isPreparedForNextRun to using canExecute, which aligns with the new execution readiness logic implemented in the RunExecution class.


279-280: Improved debug message and added clarifying comment.

The debug message now more accurately describes what's happening - creating a fresh execution for the next run rather than just recreating the task run process. The added comment makes the intention clearer for future maintainers.

Also applies to: 285-285


500-520: Better socket disconnect error handling and logging.

The new parseDescription helper function normalizes error descriptions from socket disconnects, providing structured data for logging instead of just calling toString(). This improves debugging capabilities by ensuring consistent log formats regardless of the error type.


525-525: Use structured error data in disconnect logs.

Spreading the parsed description properties into the log ensures all relevant context is captured in a structured way, making it easier to analyze disconnect events in logs.

packages/cli-v3/src/entryPoints/managed/execution.ts (2)

692-695: 🛠️ Refactor suggestion

Return a Promise<void> from kill() for consistent async usage

Down-stream callers use await this.kill().
Returning void when taskRunProcess is undefined forces them to add extra guards (see previous bug).
Always return a Promise to simplify callers:

-  public async kill() {
-    await this.taskRunProcess?.kill("SIGKILL");
-  }
+  public kill(): Promise<void> {
+    return this.taskRunProcess?.kill("SIGKILL") ?? Promise.resolve();
+  }

Likely an incorrect or invalid review comment.


620-627: ⚠️ Potential issue

this.kill() may return undefined, causing a runtime error

When taskRunProcess is undefined, this.kill() returns void.
Calling .catch(...) on void throws a TypeError, masking the original intent.

-      this.sendDebugLog("killing existing task run process before executing next attempt");
-      await this.kill().catch(() => {});
+      this.sendDebugLog("killing existing task run process before executing next attempt");
+      if (this.taskRunProcess) {
+        await this.kill().catch(() => {});
+      }

Likely an incorrect or invalid review comment.

@nicktrn nicktrn merged commit 09a859d into main Apr 28, 2025
3 of 10 checks passed
@nicktrn nicktrn deleted the fix/managed-controller-state branch April 28, 2025 12:22
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.

2 participants