Skip to content

Fix: Prevent failed resumes for very large batches #1598

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 7 commits into from
Jan 10, 2025

Conversation

nicktrn
Copy link
Collaborator

@nicktrn nicktrn commented Jan 10, 2025

This could sometimes fail due to transaction timeouts.

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a new method to retrieve resume payload for task run attempts.
    • Enhanced flexibility in batch processing with dynamic control over batch sizes and task completion handling.
  • Improvements

    • Streamlined database interactions for resume attempt handling.
    • Improved error handling in the resume attempt service.
    • Simplified transaction management for task run attempts.
  • Technical Updates

    • Updated method signatures for better type safety and clarity.
    • Refined payload retrieval and processing mechanisms.

Copy link

changeset-bot bot commented Jan 10, 2025

⚠️ No Changeset found

Latest commit: 691235d

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

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

Copy link
Contributor

coderabbitai bot commented Jan 10, 2025

Caution

Review failed

The pull request is closed.

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 eslint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

apps/webapp/app/v3/marqs/sharedQueueConsumer.server.ts

Oops! Something went wrong! :(

ESLint: 8.45.0

ESLint couldn't find the config "custom" to extend from. Please check that the name of the config is correct.

The config "custom" was referenced from the config file in "/.eslintrc.js".

If you still have problems, please stop by https://eslint.org/chat/help to chat with the team.

Walkthrough

The changes enhance the task run attempt processing in the shared queue consumer and resume attempt service. New types for improved type safety are introduced, along with refactored method signatures and enhanced error handling. Key additions include the getResumePayload method and simplifications in database interactions, aiming to make the code more organized and robust.

Changes

File Changes
apps/webapp/app/v3/marqs/sharedQueueConsumer.server.ts - Added AttemptForCompletion and AttemptForExecution types
- Added private methods _completionPayloadFromAttempt and _executionFromAttempt
- Updated getCompletionPayloadFromAttempt and getExecutionPayloadFromAttempt methods
- Added new public method getResumePayload
apps/webapp/app/v3/services/resumeAttempt.server.ts - Removed $transaction, using direct this._prisma calls
- Introduced latestAttemptSelect constant
- Updated #handleDependencyResume method signature
- Changed payload retrieval to use getResumePayload
- Refactored #setPostResumeStatuses with enhanced error handling
references/v3-catalog/src/trigger/batch.ts - Updated batchParentTask method signature to accept payload parameter
- Modified logic for triggering child tasks based on payload.wait

Possibly related PRs

Poem

🐰 Hopping through code with glee and grace,
Task attempts now find their perfect place!
Types refined, payloads clear and bright,
Resuming work with algorithmic might!
A rabbit's dance of refactored delight! 🚀


📜 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 a655fee and 691235d.

📒 Files selected for processing (1)
  • apps/webapp/app/v3/marqs/sharedQueueConsumer.server.ts (6 hunks)

Finishing Touches

  • 📝 Generate Docstrings (Beta)

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.

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: 1

🔭 Outside diff range comments (1)
apps/webapp/app/v3/services/resumeAttempt.server.ts (1)

Line range hint 149-197: Handle potential concurrency issues with asynchronous operations

Within the #handleDependencyResume method, multiple asynchronous database calls are made inside a loop. Consider the impact of concurrent executions and ensure that the async operations are properly awaited and that errors are handled correctly.

Consider using Promise.all if appropriate or ensuring that the database calls are sequential if required by the logic.

🧹 Nitpick comments (6)
apps/webapp/app/v3/marqs/sharedQueueConsumer.server.ts (4)

1002-1048: Consider potential performance impact of deep includes in type definitions

The AttemptForCompletion and AttemptForExecution types include multiple nested relations, which could lead to performance issues when retrieving data from the database. Ensure that only necessary fields are included to optimize query performance.

You might consider selecting only the fields required for your methods:

 type AttemptForCompletion = Prisma.TaskRunAttemptGetPayload<{
   include: {
     backgroundWorker: true;
     backgroundWorkerTask: true;
     taskRun: {
       include: {
         runtimeEnvironment: {
           include: {
-            organization: true;
-            project: true;
+            organization: { select: { id: true, slug: true, title: true } },
+            project: { select: { id: true, slug: true, name: true, externalRef: true } },
           };
         };
         tags: true;
       };
     };
     queue: true;
   };
 }>;

 // Similarly for AttemptForExecution

1050-1071: Ensure consistent handling of output and outputType

In the _completionPayloadFromAttempt method, when constructing the success result, you set output: attempt.output ?? undefined. If attempt.output is null, this will set output to undefined. Ensure the consuming code handles undefined appropriately.

Consider explicitly handling null values:

-    output: attempt.output ?? undefined,
+    output: attempt.output,

1139-1141: Simplify conditional expression using optional chaining

You can simplify the conditional expression when accessing taskRun.batchItems by using optional chaining. This makes the code more concise and improves readability.

Apply this diff to use optional chaining:

-      batch:
-        taskRun.batchItems[0] && taskRun.batchItems[0].batchTaskRun
-          ? { id: taskRun.batchItems[0].batchTaskRun.friendlyId }
-          : undefined,
+      batch: taskRun.batchItems[0]?.batchTaskRun
+        ? { id: taskRun.batchItems[0].batchTaskRun.friendlyId }
+        : undefined,
🧰 Tools
🪛 Biome (1.9.4)

[error] 1139-1139: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


1297-1300: Avoid reassigning parameters

In the _executionFromAttempt method, you check if machinePreset is not defined and then assign a value to it. Reassigning function parameters can lead to unexpected behavior and make the code harder to understand.

Consider using a local variable instead:

-    if (!machinePreset) {
-      machinePreset = machinePresetFromConfig(backgroundWorkerTask.machineConfig ?? {});
-    }
+    const preset = machinePreset ?? machinePresetFromConfig(backgroundWorkerTask.machineConfig ?? {});

And use preset in the rest of the method.

apps/webapp/app/v3/services/resumeAttempt.server.ts (2)

12-13: Organize imports and remove unused ones

The imports for Prisma and TaskRunAttempt seem to have been added. Ensure that all imported modules are necessary. Also, consider organizing imports for better readability.

If any imports are unused, consider removing them to keep the code clean.


77-86: Improve error message specificity

The error message "Run is not resumable" could be more specific by including the run status. This would aid in debugging.

Modify the error log to include the run status:

-      this._logger.error("Run is not resumable");
+      this._logger.error(`Run is not resumable; current status: ${attempt.taskRun.status}`);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 51a054f and 6026810.

📒 Files selected for processing (2)
  • apps/webapp/app/v3/marqs/sharedQueueConsumer.server.ts (6 hunks)
  • apps/webapp/app/v3/services/resumeAttempt.server.ts (5 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
apps/webapp/app/v3/marqs/sharedQueueConsumer.server.ts

[error] 1139-1139: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

⏰ 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 (buildjet-8vcpu-ubuntu-2204 - pnpm)
  • GitHub Check: units / 🧪 Unit Tests
  • GitHub Check: e2e / 🧪 CLI v3 tests (buildjet-8vcpu-ubuntu-2204 - npm)
  • GitHub Check: typecheck / typecheck
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (6)
apps/webapp/app/v3/marqs/sharedQueueConsumer.server.ts (3)

20-20: Imports look good

The added imports from Prisma and other modules are appropriate for the new code additions.


1073-1151: Validate metadata parsing and error handling

In _executionFromAttempt, the parsePacket function is used to parse taskRun.metadata. Ensure that parsePacket can handle potential parsing errors, and that any exceptions are properly caught and handled to prevent runtime errors.

Since the parsing of metadata is crucial, verify that all possible formats of taskRun.metadata are accounted for, and consider adding error handling or validation as needed.

🧰 Tools
🪛 Biome (1.9.4)

[error] 1139-1139: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


1319-1375: ⚠️ Potential issue

Ensure proper error handling in getResumePayload

In the getResumePayload method, if the attempt is not found, an error is logged but the method proceeds without returning. This might lead to undefined behavior when attempt is undefined.

Add a return statement after logging the error to prevent further execution:

        if (!attempt) {
          logger.error("getExecutionPayloadFromAttempt: No attempt found", { id: attemptId });
+         return;
        }

Likely invalid or redundant comment.

apps/webapp/app/v3/services/resumeAttempt.server.ts (3)

23-31: Reuse latestAttemptSelect across the codebase

The latestAttemptSelect constant is defined to encapsulate the selection logic for the latest attempt. Ensure this constant is reused wherever the latest attempt selection is required to maintain consistency.

Good use of a constant to avoid repetition.


33-70: Check for potential null values in nested includes

When performing findFirst with nested includes, ensure that the data you expect is always present. There might be cases where included relations are null, which could lead to runtime errors if not handled properly.

Verify that all necessary related data is present and handle cases where relations might be missing.


88-122: Ensure all dependency cases are handled

In the switch statement handling different resume types, double-check that all possible cases are accounted for, and that appropriate actions are taken for each type.

Review the logic to ensure that no dependency types are missed and that the correct methods are called for each case.

Copy link

pkg-pr-new bot commented Jan 10, 2025

@trigger.dev/build

npm i https://pkg.pr.new/triggerdotdev/trigger.dev/@trigger.dev/build@1598

trigger.dev

npm i https://pkg.pr.new/triggerdotdev/trigger.dev@1598

@trigger.dev/react-hooks

npm i https://pkg.pr.new/triggerdotdev/trigger.dev/@trigger.dev/react-hooks@1598

@trigger.dev/rsc

npm i https://pkg.pr.new/triggerdotdev/trigger.dev/@trigger.dev/rsc@1598

@trigger.dev/sdk

npm i https://pkg.pr.new/triggerdotdev/trigger.dev/@trigger.dev/sdk@1598

@trigger.dev/core

npm i https://pkg.pr.new/triggerdotdev/trigger.dev/@trigger.dev/core@1598

commit: 6026810

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: 3

🧹 Nitpick comments (2)
apps/webapp/app/v3/services/resumeAttempt.server.ts (1)

33-70: Consider pagination for large result sets

The query includes nested relations with include statements. For very large batches, this could still lead to performance issues. Consider implementing pagination or limiting the depth of included relations.

references/v3-catalog/src/trigger/batch.ts (1)

Line range hint 19-49: Implementation aligns well with PR objectives.

The changes effectively address the issue of failed resumes for large batches by:

  1. Adding dynamic batch size control
  2. Providing flexibility in execution mode with the wait option
  3. Maintaining backward compatibility with default values

Consider adding telemetry to monitor batch processing times and success rates to help identify optimal batch sizes.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6026810 and a655fee.

📒 Files selected for processing (2)
  • apps/webapp/app/v3/services/resumeAttempt.server.ts (5 hunks)
  • references/v3-catalog/src/trigger/batch.ts (2 hunks)
⏰ 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 (buildjet-8vcpu-ubuntu-2204 - pnpm)
  • GitHub Check: e2e / 🧪 CLI v3 tests (buildjet-8vcpu-ubuntu-2204 - npm)
  • GitHub Check: units / 🧪 Unit Tests
  • GitHub Check: typecheck / typecheck
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (1)
apps/webapp/app/v3/services/resumeAttempt.server.ts (1)

211-235: Reconsider transaction removal

The removal of transactions might introduce race conditions. As mentioned in a previous review, consider using transactions to ensure atomicity of status updates.

#!/bin/bash
# Check for other status update operations that might conflict
rg -A 5 "taskRunAttempt.update.*status"

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