Skip to content

realtime: fix streams missing chunks when streams are longer than 5 minutes and receive 408 Request Timeout errors. Also now support multiple client streams being sent to a single stream key #1993

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
Apr 29, 2025

Conversation

ericallam
Copy link
Member

@ericallam ericallam commented Apr 29, 2025

Summary by CodeRabbit

  • Bug Fixes

    • Resolved an issue where data chunks could be lost during timeouts and resumes in realtime streaming, ensuring complete data delivery.
    • Improved handling of stream end markers to prevent unwanted data from being enqueued and to ensure streams close correctly.
  • Refactor

    • Enhanced internal stream reader management for more reliable error handling and resource cleanup during streaming operations.

Copy link

changeset-bot bot commented Apr 29, 2025

🦋 Changeset detected

Latest commit: 9967dc3

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

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 Apr 29, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

This update addresses issues in the realtime streaming and metadata streaming functionalities. It refines how stream entries are processed and ensures that no data chunks are lost during timeout and resume events. The changes include adjustments to the handling of end-of-stream sentinels in Redis-based streams and a refactor of the MetadataStream class to improve the management of stream readers and error handling. No alterations were made to public APIs or exported types, but internal logic was updated to ensure more robust and reliable streaming behavior.

Changes

File(s) Change Summary
.changeset/gentle-waves-suffer.md Documents the patch to fix lost data chunks on stream timeout and resume, ensuring data integrity in realtime streaming.
apps/webapp/app/services/realtime/redisRealtimeStreams.server.ts Refactors stream entry iteration from for...of to indexed for loop; improves handling of END_SENTINEL so the stream closes only when the sentinel is the last entry, and prevents enqueuing the sentinel itself.
packages/core/src/v3/runMetadata/metadataStream.ts Refactors MetadataStream to use a locally scoped stream reader in makeRequest, removing the persistent reader property. Reader locks are now released on error, timeout, or HTTP 408, improving resource management and error propagation. Also updates error handling to reject promises directly instead of destroying the request.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant MetadataStream
    participant ServerStream

    Client->>MetadataStream: makeRequest()
    MetadataStream->>ServerStream: getReader()
    loop For each chunk
        ServerStream-->>MetadataStream: chunk
        MetadataStream-->>Client: process chunk
    end
    alt Error/Timeout/HTTP 408
        MetadataStream->>ServerStream: releaseReader()
        MetadataStream-->>Client: reject promise
    end
Loading

Possibly related PRs

  • triggerdotdev/trigger.dev#1952: Refactors the MetadataStream class to improve reader lifecycle management and error handling, overlapping with this PR's focus on stream handling and resource management.

Suggested reviewers

  • nicktrn

Poem

In the warren of code, a stream flows anew,
No chunks are lost, the data hops through.
Sentinels guard the end, as rabbits intend,
With readers released, and errors that mend.
Streaming with care, from start to the end—
A patch well-delivered, from your bunny friend! 🐇


📜 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 059c3a6 and 9967dc3.

📒 Files selected for processing (3)
  • .changeset/gentle-waves-suffer.md (1 hunks)
  • apps/webapp/app/services/realtime/redisRealtimeStreams.server.ts (1 hunks)
  • packages/core/src/v3/runMetadata/metadataStream.ts (6 hunks)
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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.

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

🔭 Outside diff range comments (1)
packages/core/src/v3/runMetadata/metadataStream.ts (1)

118-132: 🛠️ Refactor suggestion

Reader lock is never released on normal completion

When the source stream ends (done === true) we req.end() but do not releaseLock().
That leaves the lock held for the remainder of the process, leaking resources and preventing other readers.

 if (done) {
   req.end();
+  releaseReader();          // <-- ensure lock is freed
   break;
 }

(Assumes the helper releaseReader() from the previous comment.)

🧹 Nitpick comments (2)
apps/webapp/app/services/realtime/redisRealtimeStreams.server.ts (1)

53-66: Sentinel handling looks solid – minor readability tweak suggested

Great catch on ensuring the sentinel only closes the stream when it’s the final entry in the batch; this removes the “early-close” hazard when multiple writers reuse the same key.

For readability / maintainability consider destructuring the Redis field tuple so the intent is explicit:

-const [id, fields] = entries[i];
-
-if (fields && fields.length >= 2) {
-  if (fields[1] === END_SENTINEL && i === entries.length - 1) {
+const [id, [fieldName, fieldValue]] = entries[i]; // ["data", value]
+
+if (fieldName === "data") {
+  if (fieldValue === END_SENTINEL && i === entries.length - 1) {
     controller.close();
     return;
   }
-  if (fields[1] !== END_SENTINEL) {
-    controller.enqueue(fields[1]);
+  if (fieldValue !== END_SENTINEL) {
+    controller.enqueue(fieldValue);
   }
 }

This makes it obvious we’re always working with the "data" field and avoids the slightly magic fields[1] index.
Feel free to keep the current code if you prefer, but the destructure pattern reduces the chance of index mistakes when additional fields are added later.

.changeset/gentle-waves-suffer.md (1)

1-6: Polish changelog wording for clarity

-Fixed an issue with realtime streams that timeout and resume streaming dropping chunks
+Fixed an issue where realtime streams that timed out and then resumed were dropping chunks.

Adds past-tense consistency, clarifies subject, and inserts a missing comma.

🧰 Tools
🪛 LanguageTool

[style] ~4-~4: Consider using a different verb for a more formal wording.
Context: --- "@trigger.dev/sdk": patch --- Fixed an issue with realtime streams that tim...

(FIX_RESOLVE)


[uncategorized] ~5-~5: Possible missing comma found.
Context: ...ealtime streams that timeout and resume streaming dropping chunks

(AI_HYDRA_LEO_MISSING_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 f579afb and 059c3a6.

📒 Files selected for processing (3)
  • .changeset/gentle-waves-suffer.md (1 hunks)
  • apps/webapp/app/services/realtime/redisRealtimeStreams.server.ts (1 hunks)
  • packages/core/src/v3/runMetadata/metadataStream.ts (5 hunks)
🧰 Additional context used
🪛 LanguageTool
.changeset/gentle-waves-suffer.md

[style] ~4-~4: Consider using a different verb for a more formal wording.
Context: --- "@trigger.dev/sdk": patch --- Fixed an issue with realtime streams that tim...

(FIX_RESOLVE)


[uncategorized] ~5-~5: Possible missing comma found.
Context: ...ealtime streams that timeout and resume streaming dropping chunks

(AI_HYDRA_LEO_MISSING_COMMA)

⏰ 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 (1)
packages/core/src/v3/runMetadata/metadataStream.ts (1)

90-94: Potential race: processStream() may reject after promise already resolved

On a 408 retry path you resolve(this.makeRequest(...)) but processStream can still throw after the lock is released, invoking reject(error) on a promise that is already settled.
While silently ignored by Node, it surfaces as an unhandled-rejection warning in strict environments.

Consider cancelling the processStream loop once you decide to retry (e.g., by breaking the loop after releasing the reader or checking readerReleased), or move the retry logic outside the Promise constructor to avoid the resolve-then-reject scenario.

…inutes and receive 408 Request Timeout errors. Also now support multiple client streams being sent to a single stream key
@ericallam ericallam merged commit 07365cd into main Apr 29, 2025
5 of 12 checks passed
@ericallam ericallam deleted the ea-branch-53 branch April 29, 2025 11:42
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