Skip to content

ref(crons): Reorganize incident creation / issue occurrence logic#8

Open
everettbu wants to merge 1 commit into
monitor-incident-refactor-beforefrom
monitor-incident-refactor-after
Open

ref(crons): Reorganize incident creation / issue occurrence logic#8
everettbu wants to merge 1 commit into
monitor-incident-refactor-beforefrom
monitor-incident-refactor-after

Conversation

@everettbu

@everettbu everettbu commented Jul 26, 2025

Copy link
Copy Markdown

Test 8

Summary by CodeRabbit

  • New Features

    • Improved handling and reporting of monitor failures, including more detailed incident occurrences with context such as failure reasons, environment, and last successful check-in time.
    • Enhanced incident processing logic to better determine when incidents should be created or updated based on recent check-in history and failure thresholds.
  • Refactor

    • Streamlined internal logic for marking monitor failures, resulting in more efficient and maintainable processing of incidents.

…0528)

Since we'll be doing more with issue occurrences split out the concept
of incidents into it's own logic module, as well as incident_occurrence
into it's own module

Part of GH-80527
@coderabbitai

coderabbitai Bot commented Jul 26, 2025

Copy link
Copy Markdown

Walkthrough

This change refactors the incident and failure handling logic for monitor check-ins. It introduces new modules to encapsulate incident occurrence creation and threshold logic, moves helper functions and types, and simplifies the mark_failed function to delegate incident processing to the new logic. A new SimpleCheckIn type is also added.

Changes

Cohort / File(s) Change Summary
Incident Occurrence Logic
src/sentry/monitors/logic/incident_occurrence.py
New module for generating incident occurrences when monitor check-ins fail. Adds functions for creating occurrences, formatting failure reasons, and extracting monitor environment context.
Incident Threshold Logic
src/sentry/monitors/logic/incidents.py
New module implementing try_incident_threshold, which processes failed check-ins against a failure threshold to determine incident creation or updates, and emits signals accordingly.
Mark Failed Refactor
src/sentry/monitors/logic/mark_failed.py
Refactors mark_failed to delegate all incident and issue logic to try_incident_threshold, removing all internal logic for incident/issue creation and related helpers.
Type Definitions
src/sentry/monitors/types.py
Adds a new SimpleCheckIn TypedDict for representing simplified check-in data.

Sequence Diagram(s)

sequenceDiagram
    participant MonitorCheckIn
    participant mark_failed
    participant try_incident_threshold
    participant incident_occurrence
    participant Kafka

    MonitorCheckIn->>mark_failed: Failed check-in triggers mark_failed
    mark_failed->>try_incident_threshold: Delegate incident/issue logic
    try_incident_threshold->>incident_occurrence: If incident needed, create occurrence(s)
    incident_occurrence->>Kafka: Send IssueOccurrence event
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~18 minutes

Poem

A monitor checked in, but alas, it failed,
New logic now tracks where errors have trailed.
Incidents pop up when thresholds are crossed,
With context and reasons for what has been lost.
The code’s more modular, clean as can be—
A hop and a skip for observability!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch monitor-incident-refactor-after

🪧 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 generate unit tests to generate unit tests for 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.

@coderabbitai

coderabbitai Bot commented Jul 28, 2025

Copy link
Copy Markdown
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@everettbu

Copy link
Copy Markdown
Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 28, 2025

Copy link
Copy Markdown
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (3)
src/sentry/monitors/logic/incidents.py (1)

37-45: Consider adding type validation for the QuerySet values cast.

The cast to list[SimpleCheckIn] on line 37 assumes Django's values() returns the exact TypedDict structure. While this typically works, consider adding runtime validation or using a more explicit conversion to ensure type safety.

src/sentry/monitors/logic/incident_occurrence.py (2)

133-133: Fix typo in docstring.

-    Builds a humam readible string from a list of failed check-ins.
+    Builds a human readable string from a list of failed check-ins.

83-86: Apply style improvements suggested by static analysis.

The static analysis correctly identified two style improvements that would make the code more Pythonic.

-    if failed_checkin.trace_id:
-        trace_id = failed_checkin.trace_id.hex
-    else:
-        trace_id = None
+    trace_id = failed_checkin.trace_id.hex if failed_checkin.trace_id else None
-        if checkin["status"] in HUMAN_FAILURE_STATUS_MAP.keys()
+        if checkin["status"] in HUMAN_FAILURE_STATUS_MAP

Also applies to: 142-142

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5fc9f67 and c3b32a7.

📒 Files selected for processing (4)
  • src/sentry/monitors/logic/incident_occurrence.py (1 hunks)
  • src/sentry/monitors/logic/incidents.py (1 hunks)
  • src/sentry/monitors/logic/mark_failed.py (2 hunks)
  • src/sentry/monitors/types.py (1 hunks)
🧰 Additional context used
🪛 Ruff (0.12.2)
src/sentry/monitors/logic/incident_occurrence.py

83-86: Use ternary operator trace_id = failed_checkin.trace_id.hex if failed_checkin.trace_id else None instead of if-else-block

Replace if-else-block with trace_id = failed_checkin.trace_id.hex if failed_checkin.trace_id else None

(SIM108)


142-142: Use key in dict instead of key in dict.keys()

Remove .keys()

(SIM118)

🔇 Additional comments (2)
src/sentry/monitors/types.py (1)

105-113: LGTM! Clean type definition for simplified check-in representation.

The SimpleCheckIn TypedDict provides a well-structured, minimal representation of check-in data needed for incident processing. The field types are appropriate and the docstring clearly indicates its purpose.

src/sentry/monitors/logic/mark_failed.py (1)

1-79: Excellent refactoring! Clean separation of concerns.

The mark_failed function has been simplified to focus solely on updating monitor environment state, while delegating incident threshold logic to the new try_incident_threshold function. This improves modularity and makes the code more maintainable.

The conditional update pattern (lines 52-73) correctly prevents race conditions by ensuring newer check-ins aren't overwritten.

Comment on lines +159 to +171
def get_monitor_environment_context(monitor_environment: MonitorEnvironment):
config = monitor_environment.monitor.config.copy()
if "schedule_type" in config:
config["schedule_type"] = monitor_environment.monitor.get_schedule_type_display()

return {
"id": str(monitor_environment.monitor.guid),
"slug": str(monitor_environment.monitor.slug),
"name": monitor_environment.monitor.name,
"config": monitor_environment.monitor.config,
"status": monitor_environment.get_status_display(),
"type": monitor_environment.monitor.get_type_display(),
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue

Use the modified config variable instead of the original.

The function modifies the config variable to include display values but then returns the original monitor.config instead of the modified version.

 def get_monitor_environment_context(monitor_environment: MonitorEnvironment):
     config = monitor_environment.monitor.config.copy()
     if "schedule_type" in config:
         config["schedule_type"] = monitor_environment.monitor.get_schedule_type_display()
 
     return {
         "id": str(monitor_environment.monitor.guid),
         "slug": str(monitor_environment.monitor.slug),
         "name": monitor_environment.monitor.name,
-        "config": monitor_environment.monitor.config,
+        "config": config,
         "status": monitor_environment.get_status_display(),
         "type": monitor_environment.monitor.get_type_display(),
     }
📝 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
def get_monitor_environment_context(monitor_environment: MonitorEnvironment):
config = monitor_environment.monitor.config.copy()
if "schedule_type" in config:
config["schedule_type"] = monitor_environment.monitor.get_schedule_type_display()
return {
"id": str(monitor_environment.monitor.guid),
"slug": str(monitor_environment.monitor.slug),
"name": monitor_environment.monitor.name,
"config": monitor_environment.monitor.config,
"status": monitor_environment.get_status_display(),
"type": monitor_environment.monitor.get_type_display(),
}
def get_monitor_environment_context(monitor_environment: MonitorEnvironment):
config = monitor_environment.monitor.config.copy()
if "schedule_type" in config:
config["schedule_type"] = monitor_environment.monitor.get_schedule_type_display()
return {
"id": str(monitor_environment.monitor.guid),
"slug": str(monitor_environment.monitor.slug),
"name": monitor_environment.monitor.name,
"config": config,
"status": monitor_environment.get_status_display(),
"type": monitor_environment.monitor.get_type_display(),
}
🤖 Prompt for AI Agents
In src/sentry/monitors/logic/incident_occurrence.py around lines 159 to 171, the
function modifies the local variable config but returns the original
monitor_environment.monitor.config instead of the updated config. Fix this by
returning the modified config variable in the returned dictionary under the
"config" key.

Comment on lines +93 to +100
checkins = MonitorCheckIn.objects.filter(id__in=[c["id"] for c in previous_checkins])
for checkin in checkins:
create_incident_occurrence(
previous_checkins,
checkin,
incident,
received=received,
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Optimize database queries by avoiding redundant fetches.

The code fetches MonitorCheckIn objects by ID when the required data already exists in previous_checkins. This creates an unnecessary database query.

Consider passing the check-in data directly to create_incident_occurrence or modifying it to accept SimpleCheckIn objects:

-        checkins = MonitorCheckIn.objects.filter(id__in=[c["id"] for c in previous_checkins])
-        for checkin in checkins:
-            create_incident_occurrence(
-                previous_checkins,
-                checkin,
-                incident,
-                received=received,
-            )
+        for checkin_data in previous_checkins:
+            # If create_incident_occurrence needs the full MonitorCheckIn object,
+            # consider fetching only the required fields or modifying the function
+            # to work with SimpleCheckIn data
+            if checkin_data["id"] == failed_checkin.id:
+                create_incident_occurrence(
+                    previous_checkins,
+                    failed_checkin,
+                    incident,
+                    received=received,
+                )
+            else:
+                # Handle other check-ins if needed
+                pass

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In src/sentry/monitors/logic/incidents.py around lines 93 to 100, the code
fetches MonitorCheckIn objects from the database using IDs already present in
previous_checkins, causing an unnecessary query. To fix this, refactor the code
to pass the existing check-in data from previous_checkins directly to
create_incident_occurrence, or update create_incident_occurrence to accept
SimpleCheckIn objects, thereby eliminating the redundant database fetch.

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