Skip to content

Various fixes for run engine v1 #1643

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

Various fixes for run engine v1 #1643

merged 2 commits into from
Jan 27, 2025

Conversation

ericallam
Copy link
Member

@ericallam ericallam commented Jan 27, 2025

Summary by CodeRabbit

  • Logging Enhancements

    • Improved logging capabilities in shared queue consumer
    • Added structured error and message extraction for more detailed logging
  • Error Handling

    • Enhanced error tracking in queue processing
    • Improved handling of task run states and dependencies
  • Message Sending

    • Added ability to validate message sending capabilities
    • Introduced conditional message sending mechanism
  • Database Query Improvements

    • Updated task run and dependency retrieval methods
    • Refined database query flexibility

These changes focus on improving system reliability, logging, and message handling across various components.

- Make sure there are connected providers before sending a scheduled attempt message, nack and retry if there are not
- Fail runs that fail task heartbeats when pending and locked
- More and better logging around shared queue consumer
- Fix bug when failing a task run with no attempt
Copy link

changeset-bot bot commented Jan 27, 2025

⚠️ No Changeset found

Latest commit: 14d2ea9

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 27, 2025

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/failedTaskRun.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

This pull request introduces several modifications across multiple files in the Trigger.dev application, focusing on enhancing task run management, error handling, logging, and message sending capabilities. The changes span various services and components, including task run retry logic, queue consumers, socket connections, and logging mechanisms. The modifications aim to improve the robustness and flexibility of the system by refining data retrieval methods, adding conditional message sending, and improving error and message logging.

Changes

File Change Summary
apps/webapp/app/v3/failedTaskRun.server.ts Updated payload structure for task run attempts, replacing includeAttempts with FailedTaskRunRetryGetPayload
apps/webapp/app/v3/marqs/sharedQueueConsumer.server.ts Enhanced logging, error handling, and control flow in queue consumer
apps/webapp/app/v3/requeueTaskRun.server.ts Added logging and error handling for task runs in "PENDING" state
apps/webapp/app/v3/services/createTaskRunAttempt.server.ts Modified task run retrieval method from findUnique to findFirst
apps/webapp/app/v3/services/resumeTaskDependency.server.ts Changed dependency retrieval method from findUnique to findFirst
apps/webapp/app/v3/sharedSocketConnection.ts Added canSendMessage method to check socket connection status
packages/core/src/logger.ts Introduced new functions for extracting structured error and message information
packages/core/src/v3/zodMessageHandler.ts Added canSendMessage option and validation method for message sending

Sequence Diagram

sequenceDiagram
    participant MessageSender as ZodMessageSender
    participant Socket as SocketNamespace
    
    MessageSender->>Socket: Check socket connections
    Socket-->>MessageSender: Return connection status
    MessageSender->>MessageSender: Validate can send message
    alt Can send message
        MessageSender->>Socket: Send message
    else Cannot send message
        MessageSender-->>Caller: Prevent message sending
    end
Loading

Possibly related PRs

Suggested reviewers

  • matt-aitken

Poem

🐰 Hopping through code with glee,
Refactoring paths, setting logic free
Sockets connect, errors now clear
Task runs dance without any fear
CodeRabbit's magic spreads its cheer! 🚀

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

🧹 Nitpick comments (3)
apps/webapp/app/v3/services/resumeTaskDependency.server.ts (1)

9-9: Consider using findUnique instead of findFirst.

Since you're querying by id which is a unique identifier, using findUnique would be more appropriate as it:

  1. Leverages the unique constraint for better query performance
  2. Clearly communicates the intent to find exactly one record
  3. Prevents potential bugs if the uniqueness constraint is accidentally removed
-    const dependency = await this._prisma.taskRunDependency.findFirst({
+    const dependency = await this._prisma.taskRunDependency.findUnique({
apps/webapp/app/v3/failedTaskRun.server.ts (1)

17-29: Consider improving the constant name and adding documentation.

While the implementation is correct, consider:

  1. Renaming to TaskRunRetryPayloadSelect to better reflect its purpose
  2. Adding JSDoc comments to document the purpose and structure
+/**
+ * Defines the fields to select when retrieving a task run for retry processing.
+ * @property {boolean} id - The task run ID
+ * @property {Object} attempts - The most recent attempt
+ * @property {string} lockedById - The ID of the task that locked this run
+ * @property {string} lockedToVersionId - The ID of the worker version that locked this run
+ */
-const FailedTaskRunRetryGetPayload = {
+const TaskRunRetryPayloadSelect = {
packages/core/src/logger.ts (1)

126-162: Add type annotations and defensive coding.

The functions work correctly but could benefit from:

  1. TypeScript type annotations for better type safety
  2. Defensive coding for edge cases

Consider this implementation:

-function extractStructuredErrorFromArgs(...args: Array<Record<string, unknown> | undefined>) {
+function extractStructuredErrorFromArgs(...args: Array<Record<string, unknown> | undefined>): { message: string; stack?: string; name: string; } | undefined {
   const error = args.find((arg) => arg instanceof Error) as Error | undefined;

   if (error) {
     return {
       message: error.message,
-      stack: error.stack,
+      stack: error.stack ?? undefined,
       name: error.name,
     };
   }

-  const structuredError = args.find((arg) => arg?.error);
+  const structuredError = args.find((arg): arg is { error: Error } => 
+    arg?.error instanceof Error
+  );

   if (structuredError && structuredError.error instanceof Error) {
     return {
       message: structuredError.error.message,
-      stack: structuredError.error.stack,
+      stack: structuredError.error.stack ?? undefined,
       name: structuredError.error.name,
     };
   }

   return;
 }

-function extractStructuredMessageFromArgs(...args: Array<Record<string, unknown> | undefined>) {
+function extractStructuredMessageFromArgs(...args: Array<Record<string, unknown> | undefined>): string | undefined {
   // Check to see if there is a `message` key in the args, and if so, return it
-  const structuredMessage = args.find((arg) => arg?.message);
+  const structuredMessage = args.find((arg): arg is { message: string } => 
+    typeof arg?.message === 'string'
+  );

   if (structuredMessage) {
     return structuredMessage.message;
   }

   return;
 }

The changes:

  1. Add explicit return type annotations
  2. Use type predicates for better type inference
  3. Add null checks for error stack traces
  4. Add type checking for message property
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 75753ec and 14d2ea9.

📒 Files selected for processing (8)
  • apps/webapp/app/v3/failedTaskRun.server.ts (2 hunks)
  • apps/webapp/app/v3/marqs/sharedQueueConsumer.server.ts (7 hunks)
  • apps/webapp/app/v3/requeueTaskRun.server.ts (2 hunks)
  • apps/webapp/app/v3/services/createTaskRunAttempt.server.ts (1 hunks)
  • apps/webapp/app/v3/services/resumeTaskDependency.server.ts (1 hunks)
  • apps/webapp/app/v3/sharedSocketConnection.ts (1 hunks)
  • packages/core/src/logger.ts (2 hunks)
  • packages/core/src/v3/zodMessageHandler.ts (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: e2e / 🧪 CLI v3 tests (windows-latest - pnpm)
  • GitHub Check: e2e / 🧪 CLI v3 tests (windows-latest - npm)
  • GitHub Check: typecheck / typecheck
  • GitHub Check: e2e / 🧪 CLI v3 tests (ubuntu-latest - npm)
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (15)
apps/webapp/app/v3/sharedSocketConnection.ts (1)

83-90: LGTM! Well-implemented socket connection check.

The canSendMessage implementation correctly verifies socket connectivity by:

  1. First checking if there are any sockets in the namespace
  2. Then verifying if at least one socket is connected
apps/webapp/app/v3/requeueTaskRun.server.ts (1)

46-68: LGTM! Robust handling of locked PENDING tasks.

The implementation correctly:

  1. Detects locked PENDING tasks
  2. Fails them with appropriate error code (TASK_RUN_HEARTBEAT_TIMEOUT)
  3. Nacks unlocked tasks
  4. Includes detailed logging for better observability
apps/webapp/app/v3/failedTaskRun.server.ts (1)

31-31: LGTM! Type-safe and optimized query implementation.

The changes improve type safety and query optimization by:

  1. Using a const assertion for better type inference
  2. Selecting only necessary fields
  3. Using direct ID references instead of related records

Also applies to: 96-96

packages/core/src/logger.ts (2)

99-100: LGTM! Clean extraction of structured data.

The function calls are well-organized and use appropriate variable names for clarity.


105-105: LGTM! Clean conditional inclusion of structured data.

Good use of the spread operator and conditional object spread pattern. The $message prefix helps distinguish the structured message from the regular message field.

Also applies to: 109-109

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

257-262: LGTM! Improved query flexibility.

The changes from findUnique to findFirst with conditional where clause provide better flexibility in searching by either id or friendlyId. The implementation correctly handles the prefix check for determining the search field.

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

242-242: LGTM! Clean implementation of conditional message sending.

Good addition of the optional canSendMessage function with proper typing and initialization.

Also applies to: 248-248, 253-253


256-260: LGTM! Simple and effective validation method.

The validateCanSendMessage method is well-implemented with:

  1. Proper handling of undefined callback
  2. Correct async/await usage
  3. Clear boolean return type
apps/webapp/app/v3/marqs/sharedQueueConsumer.server.ts (7)

37-37: LGTM! Added required imports.

Clean addition of queue-related utility imports.


324-331: LGTM! Enhanced debug logging.

Good addition of structured logging with relevant statistics for better observability.


360-363: LGTM! Improved logging conditionals.

Smart optimization to skip logging for common "no_message_dequeued" cases while ensuring other results are logged.


384-386: LGTM! Enhanced error handling.

Good improvement to propagate errors to the current span for better tracing.


771-771: LGTM! Clearer log message.

Updated log message better reflects the action being taken.


892-934: LGTM! Robust attempt scheduling implementation.

The implementation correctly:

  1. Uses span for tracing
  2. Validates message sending capability
  3. Handles provider disconnection gracefully
  4. Includes comprehensive attempt scheduling data

961-962: LGTM! Consistent retry interval.

Good addition of next tick interval for consistent retry behavior.

Copy link

pkg-pr-new bot commented Jan 27, 2025

@trigger.dev/build

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

trigger.dev

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

@trigger.dev/react-hooks

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

@trigger.dev/rsc

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

@trigger.dev/sdk

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

@trigger.dev/core

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

commit: 14d2ea9

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