Skip to content

Conversation

@medtaher123
Copy link
Contributor

@medtaher123 medtaher123 commented Feb 12, 2025

This PR introduces exponential backoff when checking for existing messages to prevent duplicate echo messages. Previously, echo messages could arrive before the original message was saved, causing them to be incorrectly treated as new messages.

Changes:

  • Implemented retry logic with exponential backoff in findMessageWithRetries().
  • Instead of immediately assuming an echo message is new, the system retries checking for its existence with increasing delay.

Behavior:

  1. When an echo message arrives, the system checks if the message exists.
  2. If not found, it waits and retries multiple times (default: 5 attempts, doubling the delay each time).
  3. If still not found after all retries, it is treated as an external echo.

serves Issue #746

Summary by CodeRabbit

  • Bug Fixes
    • Improved handling of echo messages to reduce the chance of duplicate messages appearing in chat by adding a retry mechanism before processing.
  • Chores
    • Enhanced internal reliability for message processing, resulting in a smoother chat experience.

@yassinedorbozgithub yassinedorbozgithub added the question Further information is requested label Jul 10, 2025
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 10, 2025

✨ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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

🧹 Nitpick comments (2)
api/src/chat/services/chat.service.ts (2)

226-227: Consider renaming the variable for clarity.

The variable message is misleading since findMessageWithRetries returns a boolean, not a message object. Consider renaming it to messageExists or found for better code readability.

-        const message = await this.findMessageWithRetries(mid);
+        const messageExists = await this.findMessageWithRetries(mid);

-        if (!message) {
+        if (!messageExists) {

Also applies to: 230-240


264-274: Consider adding bounds to prevent excessive delays.

While the exponential backoff implementation is correct, consider adding an upper bound to the delay to prevent excessively long waits in edge cases. With the current implementation, the maximum delay could reach 1.6 seconds (100ms * 2^4) which seems reasonable, but adding a max delay parameter would make the method more robust.

  async findMessageWithRetries(
    mid: string,
    maxRetries = 5,
    initialDelay = 100,
+   maxDelay = 1000,
  ) {
    let attempt = 0;
    let delay = initialDelay;

    while (attempt < maxRetries) {
      const exists = await this.messageService.count({ mid });

      if (exists > 0) {
        return true; // Message exists
      }

      attempt++;
      await new Promise((resolve) => setTimeout(resolve, delay));
-     delay *= 2; // Exponential backoff
+     delay = Math.min(delay * 2, maxDelay); // Exponential backoff with cap
    }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 457d49c and 2ddf516.

📒 Files selected for processing (1)
  • api/src/chat/services/chat.service.ts (1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
api/src/chat/services/chat.service.ts

[error] 228-228: This is an unexpected use of the debugger statement.

Unsafe fix: Remove debugger statement

(lint/suspicious/noDebugger)

🔇 Additional comments (1)
api/src/chat/services/chat.service.ts (1)

248-280: Well-implemented retry mechanism with exponential backoff.

The implementation correctly addresses the timing issue described in the PR objectives. The exponential backoff strategy is appropriate for this use case, and the default parameters (5 retries, 100ms initial delay) provide a good balance between reliability and performance.

Key strengths:

  • Uses count() for efficient existence checking
  • Implements proper exponential backoff (doubling delay)
  • Includes appropriate logging for debugging
  • Has reasonable default parameters
  • Clear JSDoc documentation

this.eventEmitter.emit('hook:chatbot:sent', sentMessage);
const mid = event.getId();
const message = await this.findMessageWithRetries(mid);
debugger;
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Remove the debugger statement.

The debugger statement should be removed before merging to production as it will cause the code to break in debugger mode unexpectedly.

-        debugger;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
debugger;
🧰 Tools
🪛 Biome (1.9.4)

[error] 228-228: This is an unexpected use of the debugger statement.

Unsafe fix: Remove debugger statement

(lint/suspicious/noDebugger)

🤖 Prompt for AI Agents
In api/src/chat/services/chat.service.ts at line 228, remove the debugger
statement to prevent the code from breaking unexpectedly in debugger mode when
running in production.

@medchedli medchedli removed the question Further information is requested label Sep 15, 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.

3 participants