Skip to content

Fix: Prevent hung worker process on flush exceptions #1501

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 3 commits into from
Nov 27, 2024

Conversation

nicktrn
Copy link
Collaborator

@nicktrn nicktrn commented Nov 27, 2024

The CLI logger uses a special esbuild formatting function that forces async code to become synchronous using worker threads. That approach is incompatible with deployed workers and could cause the worker process to hang, becoming completely unresponsive. Two affected log statements were found, both called if errors are thrown when flushing usage, tracing, and metadata.

This only affected two methods of the internal CLI logger, which is not called by any user-facing logging functions.

Summary by CodeRabbit

  • Bug Fixes

    • Resolved an issue where specific log statements could cause deployed worker processes to hang.
  • New Features

    • Introduced deprecation notices for warn and error methods in the Logger class, indicating their restricted use in deployed code to prevent process hangs.
  • Style

    • Updated method signatures in the Logger class to include deprecation comments.

Copy link

changeset-bot bot commented Nov 27, 2024

🦋 Changeset detected

Latest commit: 1e5b400

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 11 packages
Name Type
trigger.dev Patch
@trigger.dev/build Patch
@trigger.dev/core Patch
@trigger.dev/react-hooks Patch
@trigger.dev/rsc Patch
@trigger.dev/sdk Patch
@trigger.dev/database Patch
@trigger.dev/otlp-importer Patch
@internal/redis-worker Patch
@internal/zod-worker 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 Nov 27, 2024

Walkthrough

This pull request introduces several changes aimed at improving logging behavior in the application. A patch for "trigger.dev" is added to prevent specific log statements from causing worker processes to hang. Additionally, modifications are made to the TaskRunProcess class to change error logging from structured logging to console output. The Logger class is updated to include deprecation notices for its warn and error methods, indicating they should only be used in the CLI context to avoid process hanging.

Changes

File Path Change Summary
.changeset/ninety-teachers-fold.md Introduced a patch for "trigger.dev" to prevent log statements from hanging worker processes.
packages/cli-v3/src/executions/taskRunProcess.ts Replaced logger.error with console.error in cancel and cleanup methods for error logging.
packages/cli-v3/src/utilities/logger.ts Added deprecation notices to warn and error methods in Logger class, indicating CLI-only usage.

Possibly related PRs

Suggested reviewers

  • ericallam
  • matt-aitken

Poem

🐇 In the land of code where rabbits play,
Logs were hanging, causing dismay.
With a patch so clever, we’ve made it right,
Now worker processes run with delight!
Console errors shine, warnings now clear,
In the CLI only, let’s give a cheer! 🎉

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.

packages/cli-v3/src/executions/taskRunProcess.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.


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.

@nicktrn nicktrn changed the title Fix: Prevent hung worker process when throwing errors while flushing Fix: Prevent hung worker process on flush exceptions Nov 27, 2024
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

🧹 Outside diff range and nitpick comments (7)
.changeset/ninety-teachers-fold.md (1)

4-5: Consider enhancing the changeset description with more details.

While the current description captures the essence of the fix, it would be helpful to include:

  • Which specific log statements were affected (error logging during flush operations)
  • The root cause (esbuild formatting function forcing async code to run synchronously)
  • The scope of impact (internal CLI logger methods only, not user-facing logging functions)

Here's a suggested enhancement:

-Prevent certain log statements from hanging deployed worker processes
+Prevent worker process hangs when throwing errors during flush operations. This fixes an issue
+where the internal CLI logger's esbuild formatting function was forcing async code to run
+synchronously, affecting only internal error logging during usage/tracing/metadata flush operations.
packages/cli-v3/src/utilities/logger.ts (3)

61-64: Deprecation notices effectively prevent process hanging issues

The deprecation notices clearly communicate the risk of using these methods in deployed code. This aligns well with the PR's objective of preventing worker process hangs.

However, to further strengthen this implementation:

Consider:

  1. Adding runtime environment detection to throw errors if these methods are called outside CLI context
  2. Creating separate CLI-specific and worker-safe logger implementations

Example implementation:

+ const isCliEnvironment = () => process.env.TRIGGER_CLI === 'true';
+
  /** @deprecated **ONLY USE THIS IN THE CLI** - It will hang the process when used in deployed code (!) */
- warn = (...args: unknown[]) => this.doLog("warn", args);
+ warn = (...args: unknown[]) => {
+   if (!isCliEnvironment()) {
+     throw new Error('Logger.warn() can only be used in CLI environment');
+   }
+   this.doLog("warn", args);
+ };

  /** @deprecated **ONLY USE THIS IN THE CLI** - It will hang the process when used in deployed code (!) */
- error = (...args: unknown[]) => this.doLog("error", args);
+ error = (...args: unknown[]) => {
+   if (!isCliEnvironment()) {
+     throw new Error('Logger.error() can only be used in CLI environment');
+   }
+   this.doLog("error", args);
+ };

Line range hint 83-96: Consider refactoring formatMessage to avoid sync formatting in non-CLI contexts

The root cause of the hanging issue lies in the synchronous formatting using formatMessagesSync.

Consider refactoring to:

  1. Use async formatting in worker contexts
  2. Implement a simpler formatting strategy for non-CLI environments
  private formatMessage(level: Exclude<LoggerLevel, "none">, message: string): string {
    const kind = LOGGER_LEVEL_FORMAT_TYPE_MAP[level];
-   if (kind) {
+   if (kind && isCliEnvironment()) {
      // Format the message using the esbuild formatter.
      const [firstLine, ...otherLines] = message.split("\n");
      const notes = otherLines.length > 0 ? otherLines.map((text) => ({ text })) : undefined;
      return formatMessagesSync([{ text: firstLine, notes }], {
        color: true,
        kind,
        terminalWidth: this.columns,
      })[0]!;
    } else {
-     return message;
+     // Simple formatting for non-CLI environments
+     return `[${level.toUpperCase()}] ${message}`;
    }
  }

Line range hint 1-1: Update source attribution comment

The current comment references wrangler repo as the source, but given the significant divergence in functionality (CLI-specific limitations), this might be misleading.

- // This is a copy of the logger utility from the wrangler repo: https://github.com/cloudflare/workers-sdk/blob/main/packages/wrangler/src/logger.ts
+ // Initially based on wrangler's logger utility, but modified for CLI-specific use:
+ // https://github.com/cloudflare/workers-sdk/blob/main/packages/wrangler/src/logger.ts
packages/cli-v3/src/executions/taskRunProcess.ts (3)

87-87: LGTM! Consider enhancing error details

The change from logger.error to console.error helps prevent worker process hangs during error flushing, which aligns with the PR objectives.

Consider destructuring the error to log more specific details:

-console.error("Error flushing task run process", { err });
+console.error("Error flushing task run process", { 
+  error: err instanceof Error ? err.message : String(err),
+  stack: err instanceof Error ? err.stack : undefined 
+});

97-97: LGTM! Consider refactoring error handling

The change from logger.error to console.error helps prevent worker process hangs during error flushing, which aligns with the PR objectives.

Consider extracting the flush error handling into a private method to reduce code duplication between cancel and cleanup:

+  async #handleFlushError(err: unknown) {
+    console.error("Error flushing task run process", { 
+      error: err instanceof Error ? err.message : String(err),
+      stack: err instanceof Error ? err.stack : undefined 
+    });
+  }
+
   async cancel() {
     this._isBeingCancelled = true;
 
     try {
       await this.#flush();
     } catch (err) {
-      console.error("Error flushing task run process", { err });
+      await this.#handleFlushError(err);
     }
 
     await this.kill();
   }
 
   async cleanup(kill = true) {
     try {
       await this.#flush();
     } catch (err) {
-      console.error("Error flushing task run process", { err });
+      await this.#handleFlushError(err);
     }
 
     if (kill) {
       await this.kill("SIGKILL");
     }
   }

Line range hint 192-196: Consider enhancing flush timeout handling

The flush operation uses timeouts, but could be made more robust to prevent hangs.

Consider these improvements:

  1. Make timeouts configurable through constructor options
  2. Add a cleanup mechanism if IPC connection is broken
  3. Add logging for timeout occurrences
   async #flush(timeoutInMs: number = 5_000) {
     logger.debug("flushing task run process", { pid: this.pid });
 
-    await this._ipc?.sendWithAck("FLUSH", { timeoutInMs }, timeoutInMs + 1_000);
+    try {
+      if (!this._ipc) {
+        logger.debug("No IPC connection available for flush");
+        return;
+      }
+      
+      await Promise.race([
+        this._ipc.sendWithAck("FLUSH", { timeoutInMs }, timeoutInMs + 1_000),
+        new Promise((_, reject) => 
+          setTimeout(() => reject(new Error("Flush timeout")), timeoutInMs + 2_000)
+        )
+      ]);
+    } catch (err) {
+      if (err.message === "Flush timeout") {
+        logger.debug("Flush operation timed out");
+      }
+      throw err;
+    }
   }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 7e209e0 and 1e5b400.

📒 Files selected for processing (3)
  • .changeset/ninety-teachers-fold.md (1 hunks)
  • packages/cli-v3/src/executions/taskRunProcess.ts (2 hunks)
  • packages/cli-v3/src/utilities/logger.ts (1 hunks)
🔇 Additional comments (2)
.changeset/ninety-teachers-fold.md (1)

1-3: LGTM on the version bump!

Using a patch version is appropriate as this fixes a bug without introducing breaking changes.

packages/cli-v3/src/utilities/logger.ts (1)

61-64: Verify logger usage across the codebase

Let's ensure all current usages of these methods are in CLI-safe contexts.

Copy link

pkg-pr-new bot commented Nov 27, 2024

@trigger.dev/build

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

@trigger.dev/core

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

@trigger.dev/react-hooks

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

trigger.dev

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

@trigger.dev/rsc

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

@trigger.dev/sdk

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

commit: 1e5b400

@nicktrn nicktrn merged commit 9046ea4 into main Nov 27, 2024
9 checks passed
@nicktrn nicktrn deleted the fix/hung-worker-process branch November 27, 2024 16:22
@coderabbitai coderabbitai bot mentioned this pull request Apr 16, 2025
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