Skip to content

fix: efficient task trigger queue updates #1489

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

Closed
wants to merge 2 commits into from

Conversation

ericallam
Copy link
Member

@ericallam ericallam commented Nov 22, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced task queue management with updated concurrency limits.
    • Introduced a new function for handling batch tasks with retry mechanisms.
  • Improvements

    • Refined logic for task run attempts and error handling.
    • Streamlined retry logic for task attempts.
    • Expanded input type for batch processing to allow more flexibility.
  • Method Updates

    • Renamed method for uploading data to clarify its purpose.

…e if the concurrency limit changes, instead of on every single trigger task call
Copy link
Contributor

coderabbitai bot commented Nov 22, 2024

Walkthrough

The pull request introduces significant updates to the CompleteAttemptService and TriggerTaskService classes, along with modifications to the batchChildTask function in the batch processing module. Key changes include the removal of transaction wrappers in the CompleteAttemptService, enhancing clarity in task completion logic. The TriggerTaskService sees improvements in task queue management, including concurrency limit handling and renaming of methods for clarity. Additionally, the batchChildTask function's parameter type is broadened, and a new function for handling task failures is introduced.

Changes

File Path Change Summary
apps/webapp/app/v3/services/completeAttempt.server.ts Refactored #completeAttemptSuccessfully to remove transaction wrapper; #completeAttemptFailed logic unchanged; updated #enqueueReattempt for clarity.
apps/webapp/app/v3/services/triggerTask.server.ts Added existingConcurrencyLimit; streamlined task queue creation and updates; renamed uploadToObjectStore to uploadPacketToObjectStore.
references/v3-catalog/src/trigger/batch.ts Changed batchChildTask parameter type from string to any; added batchParentWitFailsTask function with retry mechanism.

Possibly related PRs

Suggested reviewers

  • matt-aitken

🐰 In the code where bunnies hop,
Changes made, we’ll never stop!
Tasks are queued, and retries flow,
With clearer paths, our logic will grow.
From attempts that fail to those that succeed,
We refine our work with every need! 🐇

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 (1.23.1)

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/services/triggerTask.server.ts

(node:9963) ESLintIgnoreWarning: The ".eslintignore" file is no longer supported. Switch to using the "ignores" property in "eslint.config.js": https://eslint.org/docs/latest/use/configure/migration-guide#ignoring-files
(Use node --trace-warnings ... to show where the warning was created)

Oops! Something went wrong! :(

ESLint: 9.15.0

ESLint couldn't find an eslint.config.(js|mjs|cjs) file.

From ESLint v9.0.0, the default configuration file is now eslint.config.js.
If you are using a .eslintrc.* file, please follow the migration guide
to update your configuration file to the new format:

https://eslint.org/docs/latest/use/configure/migration-guide

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


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 12b666b and 40e5001.

📒 Files selected for processing (1)
  • apps/webapp/app/v3/services/triggerTask.server.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/webapp/app/v3/services/triggerTask.server.ts

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

🧹 Outside diff range and nitpick comments (2)
references/v3-catalog/src/trigger/batch.ts (1)

Line range hint 31-54: Several improvements needed in batchParentWitFailsTask

  1. There's a typo in the variable name 'respone2'
  2. Missing return type
  3. Missing error handling for potential failures
  4. Consider adding comments explaining the test scenarios
 export const batchParentWitFailsTask = task({
   id: "batch-parent-with-fails-task",
   retry: {
     maxAttempts: 1,
   },
-  run: async () => {
+  run: async (): Promise<void> => {
+    // Test scenario 1: Mix of failing and succeeding tasks
     const response = await taskThatFails.batchTriggerAndWait([
       { payload: false },
       { payload: true },
       { payload: false },
-    ]);
+    ]).catch((error) => {
+      logger.error("Batch operation failed", { error });
+      throw error;
+    });

     logger.info("Batch response", { response });

+    // Test scenario 2: Different combination of failing and succeeding tasks
-    const respone2 = await taskThatFails.batchTriggerAndWait([
+    const response2 = await taskThatFails.batchTriggerAndWait([
       { payload: true },
       { payload: false },
       { payload: true },
-    ]);
+    ]).catch((error) => {
+      logger.error("Second batch operation failed", { error });
+      throw error;
+    });

-    logger.info("Batch response2", { respone2 });
+    logger.info("Batch response2", { response2 });
   },
 });
apps/webapp/app/v3/services/triggerTask.server.ts (1)

Line range hint 446-466: Enhance error handling and code organization in queue creation

While the addition of friendly IDs improves queue tracking, there are opportunities to enhance the code:

Consider these improvements:

 const queueId = generateFriendlyId("queue");
+try {
   taskQueue = await tx.taskQueue.create({
     data: {
       friendlyId: queueId,
       name: queueName,
       concurrencyLimit,
       runtimeEnvironmentId: environment.id,
       projectId: environment.projectId,
       rateLimit: body.options.queue.rateLimit,
       type: "NAMED",
     },
   });

   if (typeof taskQueue.concurrencyLimit === "number") {
     await marqs?.updateQueueConcurrencyLimits(
       environment,
       taskQueue.name,
       taskQueue.concurrencyLimit
     );
   }
+} catch (error) {
+  logger.error("Failed to create task queue", {
+    queueId,
+    queueName,
+    error,
+  });
+  throw error;
+}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between e7fc592 and 12b666b.

📒 Files selected for processing (3)
  • apps/webapp/app/v3/services/completeAttempt.server.ts (1 hunks)
  • apps/webapp/app/v3/services/triggerTask.server.ts (3 hunks)
  • references/v3-catalog/src/trigger/batch.ts (1 hunks)
🔇 Additional comments (2)
references/v3-catalog/src/trigger/batch.ts (1)

Line range hint 31-54: Verify the retry configuration

The task has a single retry attempt, but it's triggering multiple failures intentionally. Ensure this aligns with the expected behavior and error handling strategy.

✅ Verification successful

The retry configuration is intentionally set for testing batch failure scenarios

The task's single retry attempt is intentional as it's part of a test suite demonstrating batch task failure handling. This is evidenced by:

  1. The task batchParentWitFailsTask is specifically designed to test failure scenarios, as indicated by its name and the fact that it calls taskThatFails with intentionally failing payloads.
  2. The child task taskThatFails has 2 retry attempts, while the parent task intentionally has 1 attempt to demonstrate how batch operations handle failures.
  3. The test includes both successful and failing scenarios in the batch operations to verify the behavior:
    • First batch: [false, true, false]
    • Second batch: [true, false, true]
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for retry configurations across the codebase to verify consistency
rg --type typescript "maxAttempts:" -B 2 -A 2

Length of output: 80


Script:

#!/bin/bash
# Search for retry configurations using ripgrep without file type filter
rg "maxAttempts:" -B 2 -A 2

Length of output: 49370


Script:

#!/bin/bash
# Search for task configurations with retry patterns
ast-grep --pattern 'task({
  $$$
  retry: {
    $$$
  },
  $$$
})'

Length of output: 19119


Script:

#!/bin/bash
# Look for the specific test file content
cat references/v3-catalog/src/trigger/batch.ts

Length of output: 1884

apps/webapp/app/v3/services/triggerTask.server.ts (1)

417-444: Consider potential race conditions in queue updates

While the optimization to update the queue only when the concurrency limit changes is good, there's a potential race condition when multiple concurrent updates occur to the same queue. The marqs service operations are outside the transaction scope.

Let's verify if there are other places in the codebase where queue updates occur:

Consider these improvements:

  1. Add optimistic locking to prevent concurrent updates to the same queue
  2. Consider implementing a queue update queue to serialize updates
  3. Add logging around queue updates to track potential issues

@@ -599,7 +617,7 @@ export class TriggerTaskService extends BaseService {

const filename = `${pathPrefix}/payload.json`;

await uploadToObjectStore(filename, packet.data, packet.dataType, environment);
await uploadPacketToObjectStore(filename, packet.data, packet.dataType, environment);
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Inconsistency found in method renaming

The method is still named uploadToObjectStore in both files, but it's being called as uploadPacketToObjectStore in the code snippet. This indicates a mismatch that needs to be corrected.

  • apps/webapp/app/v3/r2.server.ts: Method is defined as uploadToObjectStore
  • apps/webapp/app/v3/services/triggerTask.server.ts: Imports and attempts to use uploadPacketToObjectStore but imports uploadToObjectStore
🔗 Analysis chain

Verify all call sites for renamed upload method

The rename from uploadToObjectStore to uploadPacketToObjectStore improves clarity, but we should verify all call sites have been updated.

Let's check for any remaining references to the old method name:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining references to the old method name
rg "uploadToObjectStore"

# Search for any imports of the old method name
ast-grep --pattern 'import { $$$, uploadToObjectStore, $$$ } from'

Length of output: 376


Script:

#!/bin/bash
# Let's check the implementation and usage in both files
echo "=== Content of r2.server.ts ==="
cat apps/webapp/app/v3/r2.server.ts

echo -e "\n=== Content of triggerTask.server.ts ==="
cat apps/webapp/app/v3/services/triggerTask.server.ts

Length of output: 26530

Copy link

changeset-bot bot commented Nov 22, 2024

⚠️ No Changeset found

Latest commit: 40e5001

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

pkg-pr-new bot commented Nov 22, 2024

@trigger.dev/react-hooks

pnpm add https://pkg.pr.new/triggerdotdev/trigger.dev/@trigger.dev/react-hooks@1489

@trigger.dev/rsc

pnpm add https://pkg.pr.new/triggerdotdev/trigger.dev/@trigger.dev/rsc@1489

@trigger.dev/sdk

pnpm add https://pkg.pr.new/triggerdotdev/trigger.dev/@trigger.dev/sdk@1489

trigger.dev

pnpm add https://pkg.pr.new/triggerdotdev/trigger.dev@1489

@trigger.dev/build

pnpm add https://pkg.pr.new/triggerdotdev/trigger.dev/@trigger.dev/build@1489

@trigger.dev/core

pnpm add https://pkg.pr.new/triggerdotdev/trigger.dev/@trigger.dev/core@1489

commit: 40e5001

@ericallam ericallam closed this Nov 22, 2024
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