Skip to content

Retry batch item completion #1675

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 6, 2025
Merged

Retry batch item completion #1675

merged 6 commits into from
Feb 6, 2025

Conversation

matt-aitken
Copy link
Member

@matt-aitken matt-aitken commented Feb 6, 2025

It was possible for a Postgres transaction error to cause a batch to permanently fail in some rare cases.

We now retry this for these Prisma codes

  • P2024: Connection timeout errors
  • P2028: Transaction timeout errors
  • P2034: Transaction deadlock/conflict errors

We use the new Redis worker to reschedule the batch completion in the future. This is retried 10 times.

Other changes

  • Added Postgres connection_timeout with default 20s

Details

Error Handling & Retry Logic

  • Added isPrismaRetriableError() helper function to identify retriable Prisma errors
  • Implemented retry mechanism for completeBatchTaskRunItem on retriable Prisma errors
  • Enhanced handling of race conditions and other retriable errors

Database Improvements

  • Added Postgres connection timeout configuration (default: 20 seconds)

Testing Notes

  • Verified that the retries work by manually introducing a relevant Prisma error, then removing it, and the batch completed.

Summary by CodeRabbit

  • New Features
    • Added configurable database connection timeout settings, offering users more control over database stability.
    • Introduced enhanced batch processing that improves task completion reliability with refined error handling and retry support.
    • Provided a new sample batch task trigger that demonstrates batch execution and monitoring capabilities.

@matt-aitken matt-aitken requested a review from ericallam February 6, 2025 18:14
Copy link

changeset-bot bot commented Feb 6, 2025

⚠️ No Changeset found

Latest commit: b96ddfd

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

Walkthrough

The changes introduce a new connection timeout property in both the database configuration and the environment settings. A new job, completeBatchTaskRunItem, has been added to the worker’s job catalog for handling batch task completions. The batch processing service has been enhanced with an additional retry parameter and refined error handling using new helper functions. Moreover, error handling in database transactions has been improved by exporting error-checking functions, and a new batchTask has been added to initiate batch processing via the trigger module.

Changes

File(s) Change Summary
apps/.../db.server.ts
apps/.../env.server.ts
Added connection_timeout and DATABASE_CONNECTION_TIMEOUT properties to enable configurable database connection timeouts.
apps/.../legacyRunEngineWorker.server.ts Introduced a new job (completeBatchTaskRunItem) in the worker’s job catalog with schema and retry settings for batch task run item completion.
apps/.../batchTriggerV3.server.ts Enhanced completeBatchTaskRunItemV3 by adding an optional retryAttempt parameter and improved error handling using isPrismaRaceConditionError and isPrismaRetriableError.
internal-packages/.../transaction.ts Exported isPrismaKnownError and added new functions (isPrismaRetriableError, isPrismaRaceConditionError) to improve handling of Prisma errors during transactions.
references/.../example.ts Added a new task batchTask that logs the start of a batch process, constructs task items based on a count, and triggers batch processing via childTask.batchTriggerAndWait.

Sequence Diagram(s)

sequenceDiagram
    participant W as Worker
    participant S as BatchTriggerV3 Service
    participant DB as Database Transaction
    participant EH as Error Helpers

    W->>S: Initiate completeBatchTaskRunItem job
    S->>DB: Begin transaction for batch item update
    alt Successful transaction
      DB-->>S: Commit changes
      S-->>W: Job completed
    else Error encountered
      DB-->>S: Return error
      S->>EH: Check if error is retriable or race condition
      alt Error is retriable
         EH-->>S: Confirm retriable error
         S-->>W: Request retry scheduling
      else Non-retriable error
         S-->>W: Report failure
      end
    end
Loading
sequenceDiagram
    participant U as User/Trigger
    participant BT as batchTask Function
    participant CT as Child Task

    U->>BT: Trigger batchTask with payload
    BT->>BT: Build items array based on count
    BT->>CT: Invoke childTask.batchTriggerAndWait with items
    CT-->>BT: Return processing results
    BT-->>U: Return batch count and results
Loading

Possibly related PRs

Suggested reviewers

  • ericallam

Poem

I'm the rabbit in code’s delight,
Hopping through changes, morning to night.
New timeout settings and jobs to embrace,
With batch tasks and errors falling in place.
I nibble on bugs, a coder so spry!
Happy hops, and cheers, as we improve and fly!
(\_/)

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/env.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/legacyRunEngineWorker.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.

internal-packages/database/src/transaction.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.

  • 3 others

Tip

🌐 Web search-backed reviews and chat
  • We have enabled web search-based reviews and chat for all users. This feature allows CodeRabbit to access the latest documentation and information on the web.
  • You can disable this feature by setting web_search: false in the knowledge_base settings.
  • Please share any feedback in the Discord discussion.
✨ 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

🧹 Nitpick comments (3)
internal-packages/database/src/transaction.ts (1)

22-35: Improve error code management using TypeScript enums or constant objects.

Consider using TypeScript enums or constant objects for better maintainability and type safety of error codes.

-const retryCodes = ["P2024", "P2028", "P2034"];
+enum PrismaRetryableErrorCode {
+  CONNECTION_TIMEOUT = "P2024",
+  TRANSACTION_TIMEOUT = "P2028",
+  TRANSACTION_CONFLICT = "P2034",
+}
+
+const retryCodes = Object.values(PrismaRetryableErrorCode);

 export function isPrismaRetriableError(error: unknown): boolean {
   if (!isPrismaKnownError(error)) {
     return false;
   }

   return retryCodes.includes(error.code);
 }
apps/webapp/app/v3/services/batchTriggerV3.server.ts (2)

924-931: Consider adding JSDoc documentation for the new parameters.

While the function signature changes are good, adding JSDoc documentation would help clarify:

  • The purpose of retryAttempt
  • The relationship between taskRunAttemptId and retry logic
+/**
+ * Completes a batch task run item with retry support.
+ * @param itemId - The ID of the batch task run item
+ * @param batchTaskRunId - The ID of the batch task run
+ * @param tx - The Prisma transaction
+ * @param scheduleResumeOnComplete - Whether to schedule a resume on completion
+ * @param taskRunAttemptId - Optional task run attempt ID
+ * @param retryAttempt - Optional retry attempt number, used for tracking retry progress
+ */

1011-1047: Well-structured error handling with retry logic.

The error handling implementation effectively:

  • Distinguishes between retriable and non-retriable errors
  • Implements exponential backoff (2s delay)
  • Provides detailed error logging
  • Handles both initial attempts and retries differently

However, consider extracting the retry delay into a constant for easier configuration.

+const RETRY_DELAY_MS = 2_000;
+
 async function completeBatchTaskRunItemV3(
   // ... existing parameters
 ) {
   // ... existing code
-          availableAt: new Date(Date.now() + 2_000),
+          availableAt: new Date(Date.now() + RETRY_DELAY_MS),
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3ec6983 and b96ddfd.

📒 Files selected for processing (6)
  • apps/webapp/app/db.server.ts (2 hunks)
  • apps/webapp/app/env.server.ts (1 hunks)
  • apps/webapp/app/v3/legacyRunEngineWorker.server.ts (3 hunks)
  • apps/webapp/app/v3/services/batchTriggerV3.server.ts (3 hunks)
  • internal-packages/database/src/transaction.ts (2 hunks)
  • references/hello-world/src/trigger/example.ts (1 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 (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 (6)
apps/webapp/app/v3/legacyRunEngineWorker.server.ts (1)

39-51: LGTM! Well-configured batch completion job.

The configuration is well-aligned with the PR objectives:

  • Max retry attempts of 10 for handling retriable Prisma errors
  • Reasonable visibility timeout of 60 seconds
  • Complete schema definition for batch completion payload
apps/webapp/app/db.server.ts (1)

114-114: LGTM! Consistent connection timeout configuration.

The connection timeout is well-configured:

  • Applied consistently to both main and replica clients
  • Integrated properly with existing connection parameters
  • Uses environment variable for configuration

Also applies to: 166-166

apps/webapp/app/env.server.ts (1)

16-16: LGTM! The new database connection timeout setting is well-integrated.

The addition of DATABASE_CONNECTION_TIMEOUT with a default of 20 seconds aligns well with the PR's objective to handle Prisma connection timeouts. The placement and implementation follow the established pattern for database configuration settings.

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

10-11: LGTM! Good addition of error handling utilities.

The new imports for isPrismaRaceConditionError and isPrismaRetriableError support the PR's objective of handling specific Prisma errors more robustly.


944-1010: Good implementation of transaction boundaries and timeout settings.

The transaction implementation is robust with:

  • Appropriate timeout settings (10s timeout, 4s max wait)
  • Clear error boundaries
  • Proper batch status management

985-1004: Verify the batch completion logic.

The batch completion logic has been updated to use multiple conditions:

  • Status is PENDING
  • Completed count equals expected count
  • Batch is sealed

This looks correct but warrants verification to ensure it handles all edge cases.

✅ Verification successful

🏁 Script executed:

#!/bin/bash
# Search for any other completion status checks that might need similar updates
rg -A 5 'status === "COMPLETED"' 

Length of output: 12384


Batch completion logic verified as consistent

The conditions used in the batch trigger update—ensuring the batch run is in "PENDING" status, that the completedCount equals the expectedCount, and that the batch is sealed—are consistent with how completion is handled elsewhere in the codebase. Our repository scan (via the grep search) did not reveal any alternative or conflicting completion checks that would indicate unhandled edge cases. The logic to enqueue a resume operation when a dependent task exists also aligns with existing patterns.

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