Skip to content

Improve reliability of completion submission #1711

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 6 commits into from
Feb 14, 2025

Conversation

nicktrn
Copy link
Collaborator

@nicktrn nicktrn commented Feb 14, 2025

Retries were previously driven by the run controller exclusively. This change makes it possible for the coordinator to do the same. We retry with exponential backoff, by default for up to ~2m.

Timeout and max retries can be configured with the following env vars:

  • TASK_RUN_COMPLETED_WITH_ACK_TIMEOUT_MS
  • TASK_RUN_COMPLETED_WITH_ACK_MAX_RETRIES

Summary by CodeRabbit

  • New Features

    • Introduced a robust task completion acknowledgment mechanism with a retry strategy and enhanced error reporting.
    • Added support for configurable timeouts during message acknowledgments to strengthen communication reliability.
  • Refactor

    • Updated the task completion flow to ensure acknowledgments are processed before finalizing completions, improving overall system resiliency.

Copy link

changeset-bot bot commented Feb 14, 2025

🦋 Changeset detected

Latest commit: 7299840

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

This PR includes changesets to release 12 packages
Name Type
@trigger.dev/core Patch
@trigger.dev/build Patch
trigger.dev Patch
@trigger.dev/sdk Patch
@internal/redis-worker Patch
@internal/zod-worker Patch
@trigger.dev/react-hooks Patch
@trigger.dev/rsc Patch
@trigger.dev/database Patch
@trigger.dev/otlp-importer Patch
references-nextjs-realtime Patch
@internal/testcontainers Patch

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 Feb 14, 2025

Warning

Rate limit exceeded

@nicktrn has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 24 minutes and 10 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 24fc9ae and 7299840.

📒 Files selected for processing (2)
  • .changeset/witty-jars-approve.md (1 hunks)
  • apps/coordinator/src/index.ts (6 hunks)

Walkthrough

This pull request updates the task completion flow by introducing an acknowledgment mechanism. The changes include new constants and a refactored method in the TaskCoordinator class to send completion acknowledgments using an exponential backoff strategy. A new socket event handler and corresponding message type for task completions with acknowledgment are added, and the messaging schema is adjusted accordingly. Additionally, the socket messaging utility now accepts an optional timeout parameter for acknowledgments, allowing for configurable retry behavior and improved error handling.

Changes

File(s) Change Summary
apps/coordinator/src/index.ts
apps/webapp/app/v3/handleSocketIo.server.ts
Updated task completion flow in the coordinator: added new constants, introduced sendCompletionWithAck with exponential backoff, and implemented a new handler for TASK_RUN_COMPLETED_WITH_ACK with enhanced error reporting.
packages/core/src/v3/schemas/messages.ts
packages/core/src/v3/zodSocket.ts
Introduced a new TASK_RUN_COMPLETED_WITH_ACK message type and updated the existing TASK_RUN_COMPLETED schema; modified sendWithAck to include an optional timeout parameter for better control over message acknowledgment.

Sequence Diagram(s)

sequenceDiagram
    participant TC as TaskCoordinator
    participant EB as ExponentialBackoff
    participant SS as Socket Service
    participant WH as Webapp Handler
    TC->>EB: Call sendCompletionWithAck()
    EB->>SS: Emit TASK_RUN_COMPLETED_WITH_ACK (with timeout/retries)
    SS->>WH: Forward acknowledgment request
    WH-->>SS: Return completion result
    SS-->>EB: Relay acknowledgment response
    EB-->>TC: Return ack result
Loading
sequenceDiagram
    participant Caller as Message Sender
    participant ZS as ZodSocketMessageSender
    participant Socket as Socket Instance
    Caller->>ZS: sendWithAck(type, payload, timeout?)
    alt Timeout provided
      ZS->>Socket: this.#socket.timeout(timeout)
    else No timeout
      ZS->>Socket: Use default socket
    end
    Socket->>ZS: Emit message with acknowledgment
    ZS-->>Caller: Return acknowledgment result
Loading

Possibly related PRs

Suggested reviewers

  • ericallam

Poem

I'm a happy bunny hopping through code,
Enhancing tasks on this long winding road.
Acks now whisper with a gentle retry,
In exponential leaps, they soar up high.
With each small fix, my heart softly sings—
CodeRabbit cheers and joyful joy it brings!
🐇✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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. (Beta)
  • @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.

@nicktrn nicktrn merged commit 8f3f373 into main Feb 14, 2025
3 of 8 checks passed
@nicktrn nicktrn deleted the fix/timeout-after-completion branch February 14, 2025 15:14
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: 0

🧹 Nitpick comments (5)
apps/coordinator/src/index.ts (4)

33-37: Consider logging or validating the parsed environment variables.

The parse logic correctly falls back to defaults if the environment variables are invalid or missing. However, you might want to:

  1. Log the resultant values (30 seconds / 7 retries by default).
  2. Validate against negative or excessively large values if misconfiguration is a potential issue.

728-759: Improve granularity of error handling and reporting.

This new sendCompletionWithAck() function robustly handles errors and logs them. However, returning a simple boolean might limit insights into the cause of the failure. Consider returning more descriptive error information or rethrowing errors so that upstream logic can decide how to proceed.


760-797: Factor out exponential backoff flow for clarity.

The added logic in completeWithoutCheckpoint integrates exponential backoff for acknowledgment, which is correct and improves reliability. To keep this function focused, consider extracting the backoff steps into a dedicated helper method. This helps maintain readability and testability.


800-800: Revisit function naming to improve maintainability.

These newly introduced calls to await completeWithoutCheckpoint(...) unify the finalization flow. However, the function name doesn’t clearly convey the shouldExit argument’s behavior. For better clarity, consider renaming the function or splitting the logic to reflect whether we're “exiting” or “continuing” post-completion.

Also applies to: 808-808, 813-813, 818-818, 827-827, 836-836, 860-860

packages/core/src/v3/schemas/messages.ts (1)

440-440: Consider consistent version defaults across related message types.

The TASK_RUN_COMPLETED message defaults to "v1" while TASK_RUN_COMPLETED_WITH_ACK defaults to "v2". Consider using the same default version for consistency, or document why they differ.

-      version: z.enum(["v1", "v2"]).default("v1"),
+      version: z.enum(["v1", "v2"]).default("v2"),

Also applies to: 427-427

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 36fea7d and 24fc9ae.

📒 Files selected for processing (4)
  • apps/coordinator/src/index.ts (6 hunks)
  • apps/webapp/app/v3/handleSocketIo.server.ts (1 hunks)
  • packages/core/src/v3/schemas/messages.ts (1 hunks)
  • packages/core/src/v3/zodSocket.ts (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: e2e / 🧪 CLI v3 tests (windows-latest - pnpm)
  • GitHub Check: e2e / 🧪 CLI v3 tests (windows-latest - npm)
  • GitHub Check: typecheck / typecheck
🔇 Additional comments (5)
apps/coordinator/src/index.ts (1)

14-14: Validate version compatibility for new imports.

Importing ExponentialBackoff, HttpReply, and getTextBody from @trigger.dev/core/v3/apps looks correct, but ensure that all other files and dependencies consuming these are on a compatible version to avoid runtime errors.

apps/webapp/app/v3/handleSocketIo.server.ts (1)

139-176: Good addition for acknowledgment-based completions.

This new TASK_RUN_COMPLETED_WITH_ACK handler cleanly logs errors and returns structured success/failure responses. The approach effectively captures stack traces for debugging, which is recommended. No concerns noted.

packages/core/src/v3/zodSocket.ts (1)

296-298: Optional timeout parameter enhances robustness.

Allowing an optional timeout in sendWithAck provides a clear mechanism for controlling acknowledgment waits. Ensure to handle edge cases (e.g., very large or negative timeouts) and confirm that callers handle potential timeout rejections gracefully.

Also applies to: 311-312, 314-314

packages/core/src/v3/schemas/messages.ts (2)

438-451: LGTM! The new message type enhances reliability through acknowledgment.

The implementation correctly adds acknowledgment support for task run completion messages, which aligns with the PR's objective of improving reliability. The schema is well-structured and consistent with other message types in the file.


438-451:

✅ Verification successful

Verify the coordinator's handling of the new message type.

Let's ensure the coordinator is properly implementing this new message type with acknowledgment support.


🏁 Script executed:

#!/bin/bash
# Search for implementations using the new message type
rg "TASK_RUN_COMPLETED_WITH_ACK" -A 5

# Search for potential places that should be updated to use the new type
rg "TASK_RUN_COMPLETED[^_]" -A 5

Length of output: 18449


Coordinator’s handling of TASK_RUN_COMPLETED_WITH_ACK verified

  • The new message type is correctly implemented in the coordinator (see apps/coordinator/src/index.ts) with appropriate timeout, retry/backoff, and error logging for acknowledgment support.
  • The schema update in packages/core/src/v3/schemas/messages.ts reflects the intended design (using version "v1" or "v2" along with an optional checkpoint).
  • Legacy references to TASK_RUN_COMPLETED are still in use across various modules (e.g., CLI and webapp), which appears intentional for backward compatibility. Please ensure that these legacy flows continue to operate as expected without interfering with the new ACK-based message handling.

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