Skip to content

ROB-2005: improve error handling for streaming (slackbot) - #935

Merged
nherment merged 3 commits into
masterfrom
ROB-2005_holmes_slackbot_streaming
Sep 11, 2025
Merged

nherment merged 3 commits into
masterfrom
ROB-2005_holmes_slackbot_streaming

Conversation

@nherment

@nherment nherment commented Sep 4, 2025

Copy link
Copy Markdown
Contributor

No description provided.

@coderabbitai

coderabbitai Bot commented Sep 4, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Adds logging and a catch-all except Exception as e to stream_chat_formatter in holmes/utils/stream.py; it logs the exception, maps Bedrock's "Model is getting throttled" message to a rate-limit SSE error, and otherwise yields a generic SSE error payload (error_code=1). Existing RateLimitError handling remains.

Changes

Cohort / File(s) Summary of Changes
Streaming error handling
holmes/utils/stream.py
Imported logging and added a broad except Exception as e in stream_chat_formatter. The new handler logs the exception; if the exception text contains Model is getting throttled it yields a rate-limit SSE message (Bedrock case); otherwise yields a generic SSE error with description/msg set from the exception and error_code=1. Preserves existing RateLimitError branch; no public API/signature changes.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant C as Client
  participant S as stream_chat_formatter
  participant P as LLM Provider

  C->>S: Start stream
  S->>P: Send request / stream tokens
  alt Success
    P-->>S: Token chunks
    S-->>C: SSE data chunks
  else RateLimitError
    P--xS: Raise RateLimitError
    S-->>C: SSE error (rate_limit)
  else Other Exception
    P--xS: Raise Exception
    S->>S: log.exception(e)
    alt Message contains "Model is getting throttled"
      S-->>C: SSE error (rate_limit via Bedrock throttle)
    else Any other exception
      S-->>C: SSE error (description=msg=exception, error_code=1)
    end
  end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Pre-merge checks (1 passed, 1 warning, 1 inconclusive)

❌ Failed checks (1 warning, 1 inconclusive)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
Description Check ❓ Inconclusive The supplied context does not include the PR's current description field (<current_description> is missing) so I cannot verify the actual GitHub description; the provided raw_summary is relevant to the changeset but is not guaranteed to match the PR description on the platform. Please provide the PR description text or ensure the GitHub PR description briefly states what changed, why, and any testing notes (and links to ROB-2005); I will re-evaluate once the actual description is available.
✅ Passed checks (1 passed)
Check name Status Explanation
Title Check ✅ Passed The title "ROB-2005: improve error handling for streaming (slackbot)" accurately reflects the main change shown in the diff (broadened error handling and logging in streaming code under holmes/utils/stream.py) and is concise with a ticket reference, so a reviewer can quickly grasp the primary intent.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch ROB-2005_holmes_slackbot_streaming

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

Comment @coderabbitai help to get the list of available commands and usage tips.

@nherment nherment changed the title ROB-2005: improve error handling for streaming ROB-2005: improve error handling for streaming (slackbot) Sep 4, 2025

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
holmes/utils/stream.py (2)

72-75: Add return type for the generator (coding guideline: type hints required).

Both formatters yield SSE strings; annotate the return type to keep mypy happy.

 def stream_chat_formatter(
     call_stream: Generator[StreamMessage, None, None],
     followups: Optional[List[dict]] = None,
-):
+) -> Generator[str, None, None]:

48-51: Add return type to stream_investigate_formatter as well.

Matches behavior (yields SSE strings).

 def stream_investigate_formatter(
     call_stream: Generator[StreamMessage, None, None], runbooks
-):
+) -> Generator[str, None, None]:
🧹 Nitpick comments (2)
holmes/utils/stream.py (2)

89-100: Consider logging the exception with traceback for observability.

Today the error is only surfaced to the client; add structured logging to aid triage.

Add near the imports:

import logging
logger = logging.getLogger(__name__)

Then inside the catch-all block before yielding:

logger.exception("stream_chat_formatter failed")

48-70: Consistency: mirror the generic error handling in investigate formatter (optional).

Only stream_chat_formatter has the catch-all path; stream_investigate_formatter will still drop non-rate-limit errors. Consider mirroring the same behavior to provide consistent SSE error semantics.

If you want, I can draft the mirrored try/except for stream_investigate_formatter.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between f8cd1c2 and 987c693.

📒 Files selected for processing (1)
  • holmes/utils/stream.py (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.py

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.py: Always place Python imports at the top of the file, not inside functions or methods
Type hints are required (mypy is configured in pyproject.toml)

Files:

  • holmes/utils/stream.py
🪛 Ruff (0.12.2)
holmes/utils/stream.py

91-91: Do not catch blind exception: Exception

(BLE001)

🪛 GitHub Actions: Build and test HolmesGPT
holmes/utils/stream.py

[error] 89-100: ruff-format failed: 1 file reformatted by this hook during pre-commit. 1 file reformatted, 326 files left unchanged. Command: 'pre-commit run --show-diff-on-failure --color=always --all-files'.

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: llm_evals
  • GitHub Check: Pre-commit checks
🔇 Additional comments (2)
holmes/utils/stream.py (2)

91-100: Run pre-commit (ruff‐format) locally to fix formatting
CI indicates formatting errors in holmes/utils/stream.py (likely inline comment spacing or trailing whitespace). Install pre-commit if needed and run pre-commit run --all-files, then commit the fixes.


95-99: Standardize error_code usage: Generic errors use 1 (holmes/utils/stream.py:97) while rate-limit errors use 5204 (holmes/utils/stream.py:43), and there’s no central ErrorCode enum or constants. Please verify any existing conventions or introduce a shared enumeration/constants for consistency.

Comment thread holmes/utils/stream.py
Comment thread holmes/utils/stream.py Outdated

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
holmes/utils/stream.py (1)

49-51: Add return type hints to the streaming formatters.

Mypy is enabled; these should declare they yield strings.

-def stream_investigate_formatter(
-    call_stream: Generator[StreamMessage, None, None], runbooks
-):
+def stream_investigate_formatter(
+    call_stream: Generator[StreamMessage, None, None], runbooks
+) -> Generator[str, None, None]:
@@
-def stream_chat_formatter(
-    call_stream: Generator[StreamMessage, None, None],
-    followups: Optional[List[dict]] = None,
-):
+def stream_chat_formatter(
+    call_stream: Generator[StreamMessage, None, None],
+    followups: Optional[List[dict]] = None,
+) -> Generator[str, None, None]:

Also applies to: 73-76

♻️ Duplicate comments (2)
holmes/utils/stream.py (2)

92-97: Harden catch-all: noqa BLE001, log traceback, normalize Bedrock check, and avoid exposing internals.

At a streaming boundary a broad except is fine; annotate it, log with traceback, make the Bedrock check case-insensitive and broader, and don’t send raw exception text in the user-facing msg.

-    except Exception as e:
-        logging.error(e)
-        if "Model is getting throttled" in str(e):  # happens for bedrock
-            yield create_rate_limit_error_message(str(e))
-        else:
-            yield create_sse_error_message(description=str(e), error_code=1, msg=str(e))
+    except Exception as e:  # noqa: BLE001 - streaming boundary: convert any failure to SSE
+        err = str(e)
+        # include traceback for diagnostics
+        logger.exception("stream_chat_formatter failed")
+        # Bedrock throttling (make robust to provider/case variants)
+        if any(s in err.lower() for s in (
+            "model is getting throttled",
+            "throttlingexception",
+            "too many requests",
+            "rate exceeded",
+        )):
+            yield create_rate_limit_error_message(err)
+        else:
+            yield create_sse_error_message(
+                description=err,
+                error_code=1,
+                msg="Unexpected error"
+            )

90-95: Use logger.exception instead of logging.error to keep traceback.

Also satisfies TRY400. This is covered in the diff above.

🧹 Nitpick comments (1)
holmes/utils/stream.py (1)

8-8: Prefer a module-level logger over the root logger.

Define logger = logging.getLogger(__name__) and use it (keeps logs scoped and configurable).

-import logging
+import logging
+logger = logging.getLogger(__name__)
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 987c693 and 6d5c131.

📒 Files selected for processing (1)
  • holmes/utils/stream.py (2 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.py

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.py: Always place Python imports at the top of the file, not inside functions or methods
Type hints are required (mypy is configured in pyproject.toml)

Files:

  • holmes/utils/stream.py
🪛 Ruff (0.12.2)
holmes/utils/stream.py

92-92: Do not catch blind exception: Exception

(BLE001)


93-93: Use logging.exception instead of logging.error

Replace with exception

(TRY400)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: llm_evals
  • GitHub Check: Pre-commit checks
  • GitHub Check: Pre-commit checks

@nherment
nherment requested a review from moshemorad September 11, 2025 10:56

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

♻️ Duplicate comments (1)
holmes/utils/stream.py (1)

94-99: Catch-all: justify BLE001, log with traceback, and normalize Bedrock throttling check; avoid leaking raw errors to clients.

Add # noqa: BLE001 with rationale, use logger.exception for stack, do a case-insensitive throttling match, and return a generic msg to the client to prevent information leakage.

-    except Exception as e:
-        logging.error(e)
-        if "Model is getting throttled" in str(e):  # happens for bedrock
-            yield create_rate_limit_error_message(str(e))
-        else:
-            yield create_sse_error_message(description=str(e), error_code=1, msg=str(e))
+    except Exception as e:  # noqa: BLE001 - streaming boundary: convert any failure to SSE
+        err = str(e)
+        logger.exception("stream_chat_formatter failed")
+        if "model is getting throttled" in err.lower():  # bedrock throttling
+            yield create_rate_limit_error_message(err)
+        else:
+            yield create_sse_error_message(description=err, error_code=1, msg="Unexpected error")
🧹 Nitpick comments (1)
holmes/utils/stream.py (1)

8-8: Define a module-level logger; prefer stack-trace logging.

Add a named logger and use logger.exception(...) in the catch-all below to capture traceback (TRY400).

 import logging
+logger = logging.getLogger(__name__)
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6d5c131 and 9acedfc.

📒 Files selected for processing (1)
  • holmes/utils/stream.py (2 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.py

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.py: Use Ruff for formatting and linting
Type hints are required (checked by mypy)
Always place Python imports at the top of the file, not inside functions or methods

Files:

  • holmes/utils/stream.py
🪛 Ruff (0.12.2)
holmes/utils/stream.py

94-94: Do not catch blind exception: Exception

(BLE001)


95-95: Use logging.exception instead of logging.error

Replace with exception

(TRY400)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: llm_evals
  • GitHub Check: Pre-commit checks

@github-actions

Copy link
Copy Markdown
Contributor

Results of HolmesGPT evals

  • ask_holmes: 28/37 test cases were successful, 1 regressions, 2 skipped, 5 setup failures
Test suite Test case Status
ask 01_how_many_pods ✅
ask 02_what_is_wrong_with_pod ✅
ask 04_related_k8s_events ↪️
ask 05_image_version ✅
ask 09_crashpod ✅
ask 10_image_pull_backoff ✅
ask 110_k8s_events_image_pull ✅
ask 11_init_containers ✅
ask 13a_pending_node_selector_basic ✅
ask 14_pending_resources ✅
ask 15_failed_readiness_probe ✅
ask 17_oom_kill ✅
ask 18_crash_looping_v2 🚧
ask 19_detect_missing_app_details ✅
ask 20_long_log_file_search ✅
ask 24_misconfigured_pvc ✅
ask 24a_misconfigured_pvc_basic ✅
ask 28_permissions_error 🚧
ask 29_events_from_alert_manager ↪️
ask 39_failed_toolset ✅
ask 41_setup_argo ✅
ask 42_dns_issues_steps_new_tools ⚠️
ask 43_current_datetime_from_prompt ✅
ask 45_fetch_deployment_logs_simple ✅
ask 51_logs_summarize_errors 🚧
ask 53_logs_find_term 🚧
ask 54_not_truncated_when_getting_pods ❌
ask 59_label_based_counting ✅
ask 60_count_less_than 🚧
ask 61_exact_match_counting ✅
ask 63_fetch_error_logs_no_errors ✅
ask 79_configmap_mount_issue ✅
ask 83_secret_not_found ✅
ask 86_configmap_like_but_secret ✅
ask 93_calling_datadog[0] ✅
ask 93_calling_datadog[1] ✅
ask 93_calling_datadog[2] ✅

Legend

  • ✅ the test was successful
  • ↪️ the test was skipped
  • ⚠️ the test failed but is known to be flaky or known to fail
  • 🚧 the test had a setup failure (not a code regression)
  • 🔧 the test failed due to mock data issues (not a code regression)
  • ❌ the test failed and should be fixed before merging the PR

@nherment
nherment merged commit 6157f8e into master Sep 11, 2025
7 checks passed
@nherment
nherment deleted the ROB-2005_holmes_slackbot_streaming branch September 11, 2025 11:12
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