Skip to content

Fix issue with heavy contention on TaskQueue updating concurrency limit #1653

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

Conversation

ericallam
Copy link
Member

@ericallam ericallam commented Jan 30, 2025

Summary by CodeRabbit

Release Notes

  • New Features

    • Added support for setting concurrencyLimit to null, allowing for more flexible queue management.
    • Enabled explicit removal of concurrency limits on task queues.
  • Improvements

    • Enhanced task queue creation and management logic.
    • Refined error handling for task queue operations.
    • Streamlined concurrency limit handling across services.
    • Standardized queue name and concurrency settings for triggering processes.
  • Schema Changes

    • Updated concurrencyLimit to accept null values in queue configurations.

Copy link

changeset-bot bot commented Jan 30, 2025

🦋 Changeset detected

Latest commit: 96bd406

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 Jan 30, 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/services/createBackgroundWorker.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.

apps/webapp/app/v3/services/triggerTask.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.

references/v3-catalog/src/trigger/queues.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.

  • 1 others

Walkthrough

The pull request introduces changes to how concurrency limits are handled in task queues across multiple files. The primary modification allows setting the concurrencyLimit to null, which removes any restrictions on concurrent operations. This change affects the schema definition, task triggering services, and queue management logic. The updates provide more flexibility in queue configuration by explicitly supporting the option to have no concurrency limit.

Changes

File Change Summary
packages/core/src/v3/schemas/schemas.ts Updated QueueOptions schema to allow concurrencyLimit to be nullable
apps/webapp/app/v3/services/createBackgroundWorker.server.ts Modified task queue creation logic and concurrency limit handling
apps/webapp/app/v3/services/triggerTask.server.ts Streamlined task queue creation and concurrency limit management
apps/webapp/app/v3/services/replayTaskRun.server.ts Removed explicit concurrencyLimit setting during task run replay
references/v3-catalog/src/trigger/queues.ts Updated queue triggering approach and added concurrency limits

Possibly related PRs

  • Add max queue depth limits #1376: The changes in this PR introduce limits on the number of queued task runs, which relates to the management of concurrency limits in the main PR.
  • Improve worker deployment queries #1616: This PR improves the performance of queries related to worker deployments, which may indirectly relate to how concurrency limits are managed in the main PR.
  • More v1 run engine fixes #1644: The modifications in this PR involve changes to the FairDequeuingStrategy, which includes concurrency management aspects that are relevant to the main PR's focus on concurrency limits.

Suggested reviewers

  • matt-aitken

Poem

🐰 A Rabbit's Ode to Limitless Queues 🐰

Concurrency flows, no bounds in sight,
Null becomes the key to queue's might,
Flexible threads dance free and light,
No limits hold our workers tight,
Code hops with unbridled delight!

Hop hop hooray! 🎉


📜 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 b30697c and 96bd406.

📒 Files selected for processing (6)
  • .changeset/funny-emus-pay.md (1 hunks)
  • apps/webapp/app/v3/services/createBackgroundWorker.server.ts (3 hunks)
  • apps/webapp/app/v3/services/replayTaskRun.server.ts (0 hunks)
  • apps/webapp/app/v3/services/triggerTask.server.ts (3 hunks)
  • packages/core/src/v3/schemas/schemas.ts (1 hunks)
  • references/v3-catalog/src/trigger/queues.ts (2 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: 2

🧹 Nitpick comments (2)
references/v3-catalog/src/trigger/queues.ts (1)

78-78: Update log message to match queue name.

The log message "named-queue 2" is inconsistent with the queue name "controller".

Apply this diff to update the log message:

-    logger.info("named-queue 2");
+    logger.info("controller");
.changeset/funny-emus-pay.md (1)

5-5: Enhance the changeset description with more details.

While the current description is clear, it would be helpful to add more context about:

  • The previous behavior and why this change was needed
  • The impact on existing queues
  • Example usage of the new null concurrencyLimit feature

Here's a suggested enhancement:

-Allow setting concurrencyLimit to null to signal removing the concurrency limit on the queue
+Allow setting concurrencyLimit to null to remove queue concurrency limits. Previously, queues always had a concurrency limit, which could cause heavy contention in high-throughput scenarios. This change allows unlimited concurrent operations when concurrencyLimit is explicitly set to null. Existing queues with undefined concurrencyLimit remain unchanged.
🧰 Tools
🪛 LanguageTool

[uncategorized] ~5-~5: Did you mean “too”?
Context: ...tch --- Allow setting concurrencyLimit to null to signal removing the concurrency...

(TOO_JJ_TO)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4e7c559 and 750c868.

📒 Files selected for processing (6)
  • .changeset/funny-emus-pay.md (1 hunks)
  • apps/webapp/app/v3/services/createBackgroundWorker.server.ts (3 hunks)
  • apps/webapp/app/v3/services/replayTaskRun.server.ts (0 hunks)
  • apps/webapp/app/v3/services/triggerTask.server.ts (3 hunks)
  • packages/core/src/v3/schemas/schemas.ts (1 hunks)
  • references/v3-catalog/src/trigger/queues.ts (2 hunks)
💤 Files with no reviewable changes (1)
  • apps/webapp/app/v3/services/replayTaskRun.server.ts
🧰 Additional context used
🪛 LanguageTool
.changeset/funny-emus-pay.md

[uncategorized] ~5-~5: Did you mean “too”?
Context: ...tch --- Allow setting concurrencyLimit to null to signal removing the concurrency...

(TOO_JJ_TO)

⏰ 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: units / 🧪 Unit Tests
  • GitHub Check: e2e / 🧪 CLI v3 tests (ubuntu-latest - npm)
  • GitHub Check: typecheck / typecheck
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (6)
packages/core/src/v3/schemas/schemas.ts (1)

137-138: LGTM! Documentation updated to reflect schema change.

The addition of .nullable() to concurrencyLimit aligns with the PR objective and maintains backward compatibility. The documentation comment has been appropriately updated.

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

183-183: LGTM! Improved concurrency limit handling.

The change correctly preserves null values from the queue configuration, aligning with the schema update and PR objective.


Line range hint 205-227: LGTM! Improved logging for concurrency limit changes.

The added logging enhances observability by tracking concurrency limit updates and removals.


185-203: Verify race condition handling in high-concurrency scenarios.

The two-step find-then-create approach could lead to race conditions where multiple workers attempt to create the same queue simultaneously. Consider using a transaction or handling unique constraint violations gracefully.

Run the following script to check for potential race conditions:

✅ Verification successful

Race conditions are prevented by database constraints

The code is safe from race conditions because:

  • The friendlyId field has a unique constraint in the Prisma schema
  • If concurrent queue creations occur, the database will enforce uniqueness
  • Only one creation will succeed while others will fail with a constraint violation
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for unique constraint violations in task queue creation

# Search for error logs related to task queue creation
rg -A 5 "Failed to create task queue.*unique constraint"

# Search for concurrent queue creation attempts
rg -A 5 "Creating task queue.*already exists"

Length of output: 106


Script:

#!/bin/bash
# Check Prisma schema for task queue constraints and surrounding code context
fd "schema.prisma" --exec cat {} \; | grep -A 10 "model TaskQueue"

# Check for error handling and transaction usage
ast-grep --pattern 'try {
  $$$
  taskQueue = await prisma.taskQueue.create
  $$$
}'

# Look for transaction usage
rg -B 5 -A 5 "prisma.\$transaction" apps/webapp/app/v3/services/

Length of output: 484

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

599-610: LGTM! Improved error handling for queue creation failures.

The added error handling provides clear feedback when queue creation fails due to unique constraint violations.


Line range hint 453-474: Consider using a transaction for queue creation.

Similar to createBackgroundWorker.server.ts, the two-step find-then-create approach could lead to race conditions. Consider using a transaction to ensure atomicity.

Apply this diff to use a transaction:

-                  let taskQueue = await tx.taskQueue.findFirst({
-                    where: {
-                      runtimeEnvironmentId: environment.id,
-                      name: queueName,
-                    },
-                  });
-
-                  if (!taskQueue) {
-                    // handle conflicts with existing queues
-                    taskQueue = await tx.taskQueue.create({
-                      data: {
-                        friendlyId: generateFriendlyId("queue"),
-                        name: queueName,
-                        concurrencyLimit,
-                        runtimeEnvironmentId: environment.id,
-                        projectId: environment.projectId,
-                        type: "NAMED",
-                      },
-                    });
-                  }
+                  let taskQueue = await tx.taskQueue.upsert({
+                    where: {
+                      runtimeEnvironmentId_name: {
+                        runtimeEnvironmentId: environment.id,
+                        name: queueName,
+                      },
+                    },
+                    create: {
+                      friendlyId: generateFriendlyId("queue"),
+                      name: queueName,
+                      concurrencyLimit,
+                      runtimeEnvironmentId: environment.id,
+                      projectId: environment.projectId,
+                      type: "NAMED",
+                    },
+                    update: {},
+                  });

Copy link

pkg-pr-new bot commented Jan 30, 2025

@trigger.dev/build

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

@trigger.dev/react-hooks

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

trigger.dev

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

@trigger.dev/rsc

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

@trigger.dev/sdk

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

@trigger.dev/core

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

commit: b30697c

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