Skip to content

fix: prevent enqueuing into closed ReadableStream #1781

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

Conversation

CodeMan62
Copy link
Contributor

@CodeMan62 CodeMan62 commented Mar 10, 2025

Closes #1751

✅ Checklist

  • I have followed every step in the contributing guide
  • The PR title follows the convention.
  • I ran and tested the code works

Testing

  1. Ran package tests using:
pnpm run test --filter @trigger.dev/core
  1. Verified that the ReadableStream properly handles closure states
  2. Confirmed that the stream cleanup works as expected
  3. Tested the realtime runs functionality to ensure no errors after extended periods

Changelog

  • Added #isStreamClosed flag to track stream state
  • Added checks to prevent enqueueing data after stream closure
  • Improved stream cleanup in the cancel handler
  • Enhanced error handling to properly mark stream as closed
  • Added proper cleanup of resources in stop() method
  • Fixed the "Cannot enqueue a chunk into a closed readable stream" error that occurred after 5-15 minutes

Screenshots

N/A - This is a backend fix for stream handling, no UI changes.

💯

Summary by CodeRabbit

  • Bug Fixes

    • Improved streaming reliability by preventing data from being enqueued into a closed ReadableStream.
    • Enhanced error handling, resulting in a more stable and predictable streaming experience.
  • Refactor

    • Optimized stream lifecycle management for improved performance and consistency.

Sorry, something went wrong.

Copy link

changeset-bot bot commented Mar 10, 2025

🦋 Changeset detected

Latest commit: ae3425d

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

This PR includes changesets to release 17 packages
Name Type
@trigger.dev/core Patch
@trigger.dev/build Patch
trigger.dev Patch
@trigger.dev/python Patch
@trigger.dev/redis-worker Patch
@trigger.dev/sdk Patch
@internal/redis Patch
@internal/run-engine Patch
@internal/testcontainers Patch
@internal/tracing Patch
@internal/zod-worker Patch
references-d3-demo Patch
@trigger.dev/react-hooks Patch
@trigger.dev/rsc Patch
@trigger.dev/database Patch
@trigger.dev/otlp-importer Patch
references-nextjs-realtime 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 Mar 10, 2025

Walkthrough

The changes add a private boolean property #isStreamClosed to the ReadableShapeStream class to track the state of the stream. The stop, cancel, and transform methods have been modified to check or update this flag, ensuring no further message processing occurs when the stream is closed. Error handling in the transform method now wraps processing logic in a try-catch block, logging errors and calling an error handler that also sets the stream to a closed state and unsubscribes from the stream.

Changes

File Path Change Summary
packages/core/.../apiClient/stream.ts Added a private boolean property #isStreamClosed. Modified the stop, cancel, and transform methods to check/update this flag, and enhanced error handling with a try-catch block that logs errors and unsubscribes via the error handler.
.changeset/smart-coins-hammer.md Added a changelog entry for a patch release addressing real-time streams by preventing data enqueuing into a closed ReadableStream.

Assessment against linked issues

Objective Addressed Explanation
Prevent enqueuing data into a closed ReadableStream (#1751)

Poem

I'm a rabbit with a happy beat,
In code streams, I'm light on my feet.
When the stream is closed, I hop away,
Unsubscribing troubles, safe and gray.
Errors caught keep my trail so neat!
🐰✨


📜 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 e56bc39 and ae3425d.

📒 Files selected for processing (1)
  • .changeset/smart-coins-hammer.md (1 hunks)
🔇 Additional comments (2)
.changeset/smart-coins-hammer.md (2)

1-3: Changeset Header is Properly Formatted
The front matter is correctly defined for a changeset file, indicating that @trigger.dev/core should receive a patch version bump. This conforms to the expected changeset conventions.


5-6: Clear and Concise Change Description
The fix description "fix: Realtime streams: prevent enqueuing into closed ReadableStream" clearly communicates the intent of the changes, aligning with the PR objectives. Ensure that any additional documentation (if needed) is linked elsewhere in the repository.


🪧 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.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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 bot commented Mar 12, 2025

🧩 Analysis chain

I'll review this PR for you. Let me gather more information about the changes first.


🏁 Script executed:

#!/bin/bash
# Get the PR diff to examine the changes
git diff HEAD^ HEAD

Length of output: 209


I need to first check out the PR to properly review the changes. Let me try again.


🏁 Script executed:

#!/bin/bash
# First, let's check if we can fetch the PR
git fetch origin pull/1781/head:pr-1781
git checkout pr-1781

# Let's look at the diff
git diff origin/main...pr-1781

Length of output: 272


🏁 Script executed:

#!/bin/bash
# Let's check the commit history on this PR branch to understand what changes were made
git log -n 5 --oneline

# Let's also check what files were changed in the PR
git diff --name-only HEAD~1 HEAD

# Now, let's look at the specific file mentioned in the summary
cat packages/core/src/v3/apiClient/stream.ts

Length of output: 6943


@CodeMan62: Yes, this PR looks excellent. The changes properly address the issue of enqueueing data into closed ReadableStreams by:

  1. Adding the #isStreamClosed flag to track stream state
  2. Adding appropriate checks before enqueueing data
  3. Ensuring the flag is set to true in all necessary places (stop(), cancel handler, error handler)
  4. Improving error handling with proper stream closure

These changes will effectively prevent the "Cannot enqueue a chunk into a closed readable stream" error that was occurring after 5-15 minutes of operation.

✅ Actions performed

Comments resolved.

@CodeMan62
Copy link
Contributor Author

@ericallam can you check this PR and tell me if there is any problem in it

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature.

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature.
@matt-aitken matt-aitken requested review from ericallam and Copilot April 1, 2025 10:15
Copy link

@Copilot Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

This PR fixes an issue where data was being enqueued into a closed ReadableStream, which caused errors after prolonged stream usage. The changes introduce a new #isStreamClosed flag to track stream state, update the stop() and cancel() handlers to set the flag, and add conditional checks before enqueueing messages and final rows.

Comments suppressed due to low confidence (2)

packages/core/src/v3/apiClient/stream.ts:158

  • [nitpick] Consider checking the stream closed state inside the loop when enqueuing each row to ensure that no final row is added after the stream is closed, even if the flag changes during iteration.
if (!this.#isStreamClosed) {

packages/core/src/v3/apiClient/stream.ts:114

  • [nitpick] The cancel handler duplicates cleanup logic already present in stop(); consider refactoring the shared cleanup into a separate method to reduce code duplication and potential maintenance issues.
cancel: () => {

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature.
@ericallam ericallam merged commit 2812124 into triggerdotdev:main Apr 1, 2025
1 check passed
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.

Realtime bug: Failed to execute 'enqueue' on ReadableStreamDefaultController
2 participants