Skip to content
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

OOM retrying on larger machines #1691

Merged
merged 4 commits into from
Feb 10, 2025
Merged

OOM retrying on larger machines #1691

merged 4 commits into from
Feb 10, 2025

Conversation

matt-aitken
Copy link
Member

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

Sometimes you might see one of your runs fail with an "Out Of Memory" error.

TASK_PROCESS_OOM_KILLED. Your task ran out of memory. Try increasing the machine specs. If this doesn't fix it there might be a memory leak.

If this happens regularly you need to either optimize the memory-efficiency of your code, or increase the machine.

If you are seeing rare OOM errors, you can add a setting to your task to retry with a large machine if you get an OOM error:

export const yourTask = task({
  id: "your-task",
  machine: "medium-1x",
  retry: {
    outOfMemory: {
      machine: "large-1x",
    },
  },
  run: async (payload: any, { ctx }) => {
    //...
  },
});

Note
This will only retry the task if you get an OOM error. It won't permanently change the machine that a new run starts on, so if you consistently see OOM errors you should change the machine in the machine property.

Summary by CodeRabbit

  • New Features

    • Introduced automatic retries for tasks that encounter out-of-memory errors, allowing processes to rerun on machines with higher resource presets.
    • Simplified task configuration by using machine preset strings instead of complex objects.
    • Added an example task demonstrating OOM error handling.
  • Documentation

    • Updated guidelines with a new section on handling out-of-memory errors and configuring retry strategies.

Copy link

changeset-bot bot commented Feb 10, 2025

🦋 Changeset detected

Latest commit: 2de9e8d

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/sdk Patch
@trigger.dev/build Patch
@trigger.dev/core Patch
@trigger.dev/react-hooks Patch
@trigger.dev/rsc Patch
@trigger.dev/database Patch
@trigger.dev/otlp-importer Patch
trigger.dev Patch
@internal/redis-worker Patch
@internal/zod-worker 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 10, 2025

Warning

Rate limit exceeded

@matt-aitken has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 10 minutes and 57 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 5f929be and 2de9e8d.

📒 Files selected for processing (2)
  • .changeset/forty-windows-shop.md (1 hunks)
  • apps/webapp/app/v3/services/completeAttempt.server.ts (9 hunks)

Walkthrough

This pull request implements a new mechanism for retrying tasks that encounter Out Of Memory (OOM) errors. It revises method signatures and error handling logic in task run management and task attempt services. Changes include a new helper method to compute retry configurations for OOM scenarios, updates to the machine configuration format in both documentation and schemas, and the introduction of a new task that simulates OOM conditions for testing.

Changes

Files Summary of Changes
.changeset/forty…shop.md, apps/webapp/.../failedTaskRun.server.ts, apps/webapp/.../completeAttempt.server.ts Implements an OOM error retry mechanism: updates method signatures in FailedTaskRunRetryHelper and CompleteAttemptService, adds new helper methods (getRetryConfig, isOOMError), and introduces a forceRequeue parameter for retry flows.
docs/m…achines.mdx, packages/core/src/v3/.../schemas.ts, packages/core/src/v3/.../tasks.ts Updates machine configuration from nested objects to preset strings; extends schemas with an optional OOM retry option; and revises documentation to include guidance and examples for handling OOM errors.
references/hello-world/src/trigger/oom.ts Introduces a new task (oomTask) that simulates OOM conditions with a retry configuration to run on a different machine preset.

Sequence Diagram(s)

sequenceDiagram
    participant TR as Task Runner
    participant CAS as CompleteAttemptService
    participant FTR as FailedTaskRunRetryHelper
    TR->>CAS: Execute task attempt
    CAS->>CAS: Call isOOMError(error)
    alt OOM Error Detected
        CAS->>FTR: getExecutionRetry(taskRun, execution)
        FTR->>FTR: Execute getRetryConfig(taskRun, execution)
        FTR-->>CAS: Return retry configuration (new machine preset)
        CAS->>TR: Requeue task with forceRequeue flag
    else Normal Error
        CAS->>TR: Proceed with standard retry logic
    end
Loading

Possibly related PRs

Suggested reviewers

  • nicktrn

Poem

I'm a rabbit with a clever code hop,
Fixing OOM errors till the bugs all drop.
With retries and presets, my leaps are so bright,
Jumping over errors in the code at night.
In a garden of functions, I nibble with delight,
Celebrating each fix with a joyful byte!
🐇✨


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

🧹 Nitpick comments (4)
references/hello-world/src/trigger/oom.ts (2)

12-16: Consider clarifying the parameter name.
succeedOnLargerMachine is understandable for demonstration purposes. However, if you plan to expand usage beyond a simple test scenario, a more descriptive parameter name (e.g., shouldSucceedIfMachineIsLarger) might improve readability.


17-18: Optional: Make timeout configurable.
Currently, the 2-second wait might introduce unnecessary delays in certain environments. If you plan to keep this in production, consider making the timeout configurable or documented.

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

253-285: Revisiting machinePreset on OOM.
Assigning a new machinePreset for OOM is valid; however, confirm that permanently updating the DB aligns with the desired design. If the intention is to revert back after just one attempt, additional logic might be needed.

docs/machines.mdx (1)

29-34: Consider improving error message formatting.

The error message could be more readable with proper punctuation.

Apply this diff to improve readability:

-TASK_PROCESS_OOM_KILLED. Your task ran out of memory. Try increasing the machine specs. If this doesn't fix it there might be a memory leak.
+TASK_PROCESS_OOM_KILLED: Your task ran out of memory. Try increasing the machine specs. If this doesn't fix it, there might be a memory leak.
🧰 Tools
🪛 LanguageTool

[typographical] ~33-~33: Consider adding a comma.
Context: ...he machine specs. If this doesn't fix it there might be a memory leak. If this happen...

(IF_THERE_COMMA)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4dd42cd and 5f929be.

📒 Files selected for processing (7)
  • .changeset/forty-windows-shop.md (1 hunks)
  • apps/webapp/app/v3/failedTaskRun.server.ts (3 hunks)
  • apps/webapp/app/v3/services/completeAttempt.server.ts (9 hunks)
  • docs/machines.mdx (2 hunks)
  • packages/core/src/v3/schemas/schemas.ts (2 hunks)
  • packages/core/src/v3/types/tasks.ts (1 hunks)
  • references/hello-world/src/trigger/oom.ts (1 hunks)
🧰 Additional context used
🪛 LanguageTool
docs/machines.mdx

[typographical] ~33-~33: Consider adding a comma.
Context: ...he machine specs. If this doesn't fix it there might be a memory leak. If this happen...

(IF_THERE_COMMA)


[uncategorized] ~35-~35: Possible missing comma found.
Context: ...ight be a memory leak. If this happens regularly you need to either optimize the memory-...

(AI_HYDRA_LEO_MISSING_COMMA)

⏰ Context from checks skipped due to timeout of 90000ms (6)
  • 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: typecheck / typecheck
  • GitHub Check: units / 🧪 Unit Tests
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (22)
references/hello-world/src/trigger/oom.ts (5)

1-2: Imports look good.
No concerns. The imports from @trigger.dev/sdk/v3 and timers/promises are appropriate and align with the usage below.


4-11: Nice approach for specifying out-of-memory retry logic.
Defining the outOfMemory retry option with an alternate machine is a great demonstration of how to handle OOM errors by switching to a higher configuration.


19-24: Logic is straightforward.
The success path is well-defined by checking the current machine and the succeedOnLargerMachine flag. This makes the behavior transparent.


26-31: Intentionally triggering OOM.
Using a while loop to continuously double a string will reliably push memory usage. This is fine for a demonstration, but be cautious if run in environments with limited safeguards.


32-39: Catch block duplicates OOM attempt.
The second infinite loop further ensures an OOM scenario. As this is purposeful, just be careful in a production environment to avoid system instability.

apps/webapp/app/v3/services/completeAttempt.server.ts (8)

4-4: Imported TaskRunError usage looks correct.
Good move to leverage the typed error, making it easier to discern internal error subtypes.


239-249: Ensuring retry logic is inferred during system failures.
Recomputing executionRetry via FailedTaskRunRetryHelper.getExecutionRetry() if none is provided is a clean approach to unify retry logic.


249-251: Introducing retriableError and isOOMRetry.
Naming these variables explicitly clarifies branching logic for different error scenarios.


299-299: Forcing requeue on OOM.
Tying forceRequeue to the isOOMRetry flag ensures these attempts enter the queue. This appears consistent with the new retry mechanism.


421-429: Introduction of forceRequeue parameter.
Allowing the caller to forcibly re-queue improves flexibility in orchestrating retry attempts.


479-483: Conditional re-queue logic.
This ensures a fallback path if the checkpoint-based approach is unavailable. The branching logic is clear and robust.


516-525: Extending #retryAttempt with forceRequeue.
The new parameter nicely complements the existing retry logic, providing a structured way to push attempts through the queue flow.


688-695: isOOMError function.
Detecting TASK_PROCESS_OOM_KILLED or TASK_PROCESS_MAYBE_OOM_KILLED is an elegant and straightforward approach. Consider verifying if there are any other relevant error codes to catch.

Below is a script to search the codebase for additional OOM-related codes:

✅ Verification successful

🏁 Script executed:

#!/bin/bash
# Checking for OOM or 'killed' references in code to confirm coverage.
rg -i 'oom|killed'

Length of output: 65557


No Additional OOM Error Codes Found.
The repository search only returns references to "TASK_PROCESS_OOM_KILLED" and "TASK_PROCESS_MAYBE_OOM_KILLED" (with "OOMKilled" mapping to TASK_PROCESS_OOM_KILLED in the Kubernetes provider). Based on our grep, there aren’t any other OOM-related error codes to address, so the current implementation of the isOOMError function appears sufficient.

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

3-3: New import for MachinePresetName.
This import is necessary for the new OOM configuration below. Good addition.


99-108: outOfMemory configuration is a valuable extension.
This new optional property in RetryOptions allows specifying a different machine for OOM errors, aligning well with the PR objectives.

apps/webapp/app/v3/failedTaskRun.server.ts (2)

183-220: Improved error handling in getExecutionRetry method.

The method has been simplified by removing the async keyword and adding proper error handling with logging.


222-299: Verify retry configuration parsing.

The new getRetryConfig method includes robust error handling and version checking for SDK compatibility. However, we should verify that the retry configuration is correctly parsed.

Run this script to check retry configuration parsing:

❌ Verification inconclusive

🏁 Script executed:

#!/bin/bash
# Description: Check retry configuration parsing in the codebase.

# Test: Search for retry configuration usage
rg -A 5 'retry: \{.*outOfMemory'

Length of output: 34


Manual Verification Needed: Confirm Retry Configuration Parsing

  • The initial shell script produced no output for the pattern used.
  • The getRetryConfig implementation appears robust, using RetryOptions.nullable().safeParse along with proper error and version checks.
  • However, we did not find automated evidence (e.g., specific configuration keys like outOfMemory) validating that the retry configuration is parsed as expected.
  • I recommend manually verifying the retry configuration behavior (or adding targeted tests) to ensure that various configurations are correctly parsed and that fallback behaviors are triggered as intended.
packages/core/src/v3/types/tasks.ts (1)

205-219: Updated machine configuration documentation and type.

The machine configuration has been simplified to use presets, improving usability. The documentation link to machine specifications enhances clarity.

.changeset/forty-windows-shop.md (1)

1-6: LGTM! Clear and concise changeset.

The patch version bump is appropriate for this feature addition.

docs/machines.mdx (3)

8-16: Clear example of machine configuration.

The example demonstrates the simplified machine configuration using presets.


41-54: Comprehensive example of OOM retry configuration.

The example clearly demonstrates how to configure OOM retry with a larger machine.


56-59: Clear note about retry behavior.

The note effectively clarifies that OOM retry is temporary and doesn't permanently change the machine configuration.

@matt-aitken matt-aitken merged commit bb65b26 into main Feb 10, 2025
12 checks passed
@matt-aitken matt-aitken deleted the memory-retry-machine branch February 10, 2025 17:44
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