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

Add sequence number for ai stream objects #1597

Merged
merged 1 commit into from
Nov 21, 2024
Merged

Conversation

michaeljguarino
Copy link
Member

@michaeljguarino michaeljguarino commented Nov 21, 2024

needed to handle out of order

Test Plan

n/a

Checklist

  • If required, I have updated the Plural documentation accordingly.
  • I have added tests to cover my changes.
  • I have added a meaningful title and summary to convey the impact of this PR to a user.

Summary by CodeRabbit

  • New Features

    • Introduced sequence tracking for AI-related data and chat messages, enhancing message order management.
    • Added a new seq field to the ai_delta object in the GraphQL schema for better tracking of AI-generated messages.
  • Bug Fixes

    • Improved error handling in the exec function to ensure robust message publishing.
  • Tests

    • Updated subscription tests to accommodate the new data structure for published messages.

needed to handle out of order
@michaeljguarino michaeljguarino added the enhancement New feature or request label Nov 21, 2024
@michaeljguarino michaeljguarino requested a review from a team November 21, 2024 00:13
Copy link
Contributor

coderabbitai bot commented Nov 21, 2024

Walkthrough

The changes introduce enhancements to the data models related to AI interactions by adding a sequence field to the AiDelta and Chat structs in models_gen.go. The publish function in the Console.AI.Stream module has been updated to reflect a semantic change in parameter naming, while the exec function in Console.AI.Stream.Exec has improved its data structure and error handling. Additionally, the GraphQL schema and related tests have been modified to accommodate the new sequence field, ensuring consistency across the application.

Changes

File Change Summary
go/client/models_gen.go Added AiDelta struct with Seq field; updated Chat struct to include Seq. Added IsKubernetesData method to Deployment and StatefulSet.
lib/console/ai/stream.ex Updated publish function parameter from chunk to delta and changed the published message structure.
lib/console/ai/stream/exec.ex Modified exec function to include sequence number in published messages and refined error handling.
lib/console/graphql/ai.ex Added seq field to ai_delta object as a non-null integer.
schema/schema.graphql Added seq field of type Int! to AiDelta type in GraphQL schema.
test/console_web/channels/graphql/ai_subscription_test.exs Updated aiStream subscription test to publish a map with content and seq.

Possibly related PRs

  • fix streaming api #1596: The changes in this PR involve modifications to the publish function in the Console.AI.Stream module, which is relevant because the main PR also updates the structure of data being published, specifically adding a sequence field to the message format.

Suggested reviewers

  • jsladerman

Poem

In the meadow where data flows,
A sequence hops and gently grows.
With every chat and delta's cheer,
We track the tales that bring us near.
So let’s celebrate this change so bright,
For every message, there's a guiding light! 🐇✨


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.

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 (8)
lib/console/ai/stream.ex (1)

12-17: Consider adding type specs and validation

Since this function is critical for message ordering, consider:

  1. Adding a type spec to document the expected delta structure
  2. Adding runtime validation for the required fields
+ @type delta :: %{required(:content) :: String.t(), required(:seq) :: integer()}
+ @spec publish(%__MODULE__{topic: String.t()}, delta()) :: :ok

  def publish(%__MODULE__{topic: topic}, delta) when is_binary(topic) do
+   unless is_map(delta) and is_integer(delta[:seq]) and is_binary(delta[:content]) do
+     raise ArgumentError, "delta must contain :content (string) and :seq (integer)"
+   end
    Absinthe.Subscription.publish(
      ConsoleWeb.Endpoint,
      delta,
      [ai_stream: topic]
    )
  end
test/console_web/channels/graphql/ai_subscription_test.exs (2)

20-21: LGTM, but test coverage could be improved.

While the change correctly updates the Stream.publish call to include the sequence number, the test doesn't verify that this field is properly transmitted. Consider updating the GraphQL subscription query to include the seq field and verify it in the assertion.

-  subscription AI($threadId: ID) {
-    aiStream(threadId: $threadId) { content }
-  }
+  subscription AI($threadId: ID) {
+    aiStream(threadId: $threadId) { 
+      content
+      seq 
+    }
+  }

-assert_push("subscription:data", %{result: %{data: %{"aiStream" => %{"content" => "something"}}}})
+assert_push("subscription:data", %{result: %{data: %{"aiStream" => %{"content" => "something", "seq" => 1}}}})

Line range hint 1-24: Add test cases for out-of-order message handling.

Given that the PR's main objective is to handle out-of-order processing, it would be valuable to add test cases that verify this functionality. Consider adding tests that:

  1. Send messages with non-sequential sequence numbers
  2. Verify correct ordering on the receiving end
  3. Test edge cases like duplicate sequence numbers or gaps

Here's a suggested test case structure:

test "handles out-of-order messages correctly" do
  user = insert(:user)
  thread = insert(:chat_thread)
  {:ok, socket} = establish_socket(user)
  
  ref = push_doc(socket, """
    subscription AI($threadId: ID) {
      aiStream(threadId: $threadId) { 
        content
        seq 
      }
    }
  """, variables: %{"threadId" => thread.id})
  
  assert_reply(ref, :ok, %{subscriptionId: _})
  stream = %Stream{topic: Stream.topic(:thread, thread.id, user)}
  
  # Send messages out of order
  Stream.publish(stream, %{content: "second", seq: 2})
  Stream.publish(stream, %{content: "first", seq: 1})
  Stream.publish(stream, %{content: "third", seq: 3})
  
  # Verify they are received in correct order
  assert_push("subscription:data", %{result: %{data: %{"aiStream" => %{"content" => "first", "seq" => 1}}}})
  assert_push("subscription:data", %{result: %{data: %{"aiStream" => %{"content" => "second", "seq" => 2}}}})
  assert_push("subscription:data", %{result: %{data: %{"aiStream" => %{"content" => "third", "seq" => 3}}}})
end
lib/console/ai/stream/exec.ex (3)

14-21: Consider adding type specs for better documentation

The implementation correctly includes sequence numbers in the published messages. Consider adding a type spec for better documentation and compile-time checks:

@type event_acc :: list(String.t())
@spec exec(fun(), AIStream.t(), (map() -> String.t() | :pass)) :: 
  {:ok, String.t()} | {:error, String.t()}

22-22: Consider adding error logging

The error handling correctly matches the new indexed structure. Consider adding error logging for better debugging capabilities:

-      {{:error, error}, _}, _ -> {:halt, {:error, "ai service error: #{inspect(error)}"}}
+      {{:error, error}, _}, _ ->
+        Logger.error("AI service error: #{inspect(error)}")
+        {:halt, {:error, "ai service error: #{inspect(error)}"}}

11-22: Well-designed solution for handling message ordering

The implementation elegantly solves the out-of-order processing problem by:

  1. Using Elixir's built-in Stream.with_index() for efficient sequence number generation
  2. Maintaining the stream's lazy evaluation properties
  3. Seamlessly integrating sequence numbers into the existing message structure

This approach ensures message ordering can be tracked without compromising the system's performance or complexity.

lib/console/graphql/ai.ex (1)

119-119: LGTM! The sequence field addition looks good.

The non-null integer field for sequence numbers is appropriate for handling message ordering in AI streams.

Since this sequence number is crucial for handling out-of-order processing:

  1. Ensure the client-side code buffers and reorders messages based on this sequence number
  2. Consider implementing a window-based approach for handling severely delayed messages (e.g., dropping messages that are too old)
  3. Think about error handling when sequence gaps are detected
go/client/models_gen.go (1)

Line range hint 1-1: Note: This is a generated file

As indicated by the filename suffix _gen.go and the header comment, this is a generated file. Any changes should be made to the generator rather than manually editing this file.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between adffee2 and 8bbd14f.

⛔ Files ignored due to path filters (1)
  • assets/src/generated/graphql.ts is excluded by !**/generated/**
📒 Files selected for processing (6)
  • go/client/models_gen.go (1 hunks)
  • lib/console/ai/stream.ex (1 hunks)
  • lib/console/ai/stream/exec.ex (1 hunks)
  • lib/console/graphql/ai.ex (1 hunks)
  • schema/schema.graphql (1 hunks)
  • test/console_web/channels/graphql/ai_subscription_test.exs (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • schema/schema.graphql
🔇 Additional comments (5)
lib/console/ai/stream.ex (1)

12-12: LGTM: Improved parameter naming

The rename from chunk to delta better reflects the nature of the data being handled, especially now that it includes sequence information for ordering.

lib/console/ai/stream/exec.ex (1)

11-13: LGTM: Stream indexing implementation is correct

The addition of Stream.with_index() provides a clean way to generate sequence numbers while maintaining the stream's lazy evaluation properties.

lib/console/graphql/ai.ex (1)

Line range hint 258-271: Verify subscription handling with sequence numbers.

The subscription configuration looks good, but we should verify that the Stream module correctly handles sequence numbers when publishing messages.

go/client/models_gen.go (2)

131-134: LGTM! Well-structured AiDelta type

The AiDelta struct is well-designed with appropriate field types and JSON tags. The int64 type for Seq will handle large sequence numbers effectively.


Line range hint 1002-1010: LGTM! Consistent sequence field addition

The Seq field addition to the Chat struct maintains consistency with AiDelta and follows proper Go struct field conventions.

@michaeljguarino michaeljguarino merged commit 6a410d7 into master Nov 21, 2024
12 checks passed
@michaeljguarino michaeljguarino deleted the add-stream-seq branch November 21, 2024 01:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request hotfix
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant