Skip to content

feat: Alert Policies for Quiet Hours and Rate Limits - #80

Merged
maxjb-xyz merged 17 commits into
mainfrom
feature/alert-policy
Jun 3, 2026
Merged

maxjb-xyz merged 17 commits into
mainfrom
feature/alert-policy

Conversation

@maxjb-xyz

@maxjb-xyz maxjb-xyz commented Jun 2, 2026 •

Copy link
Copy Markdown
Owner

What it does: Every notification destination (ntfy/Discord/Slack) now has two independent, opt-in controls:

  • Quiet hours — a daily window (server timezone, wraps midnight). Per-destination mode: Drop (silently skip) or Defer & digest (hold overnight, send one rollup when the window ends; survives restarts via a startup flush).

  • Rate limit — max N per hour or day (sliding window). Overflow is dropped, and the next allowed notification carries a (+N suppressed) note.

Summary by CodeRabbit

  • New Features

    • Per-destination Quiet Hours (enable toggle, timezone-aware, midnight-wrap, "drop" or "defer")
    • Per-destination Rate Limits (hour/day sliding window, max count, "(+N suppressed)" note)
    • Digest delivery for deferred destinations when Quiet Hours end
    • Delivery decision logging for visibility and pruning of old logs
  • Documentation

    • Guides for configuring Quiet Hours and Rate Limiting; both default to off and existing destinations unchanged until enabled
  • UI

    • Admin form now supports configuring and validating these policies

maxjb-xyz and others added 13 commits June 2, 2026 01:29
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
…afety

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@maxjb-xyz maxjb-xyz self-assigned this Jun 2, 2026
@coderabbitai

coderabbitai Bot commented Jun 2, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: e8bd3fd1-0b9e-4db1-b726-594157aa764f

📥 Commits

Reviewing files that changed from the base of the PR and between caf5818 and 6133d9d.

📒 Files selected for processing (1)
  • server/internal/notify/notify.go

📝 Walkthrough

Walkthrough

Adds per-destination Quiet Hours (drop or defer+digest) and Rate Limiting (hour/day sliding windows): DB models and migration, admin API validation/persistence, dispatcher decisioning and logging, background digest flusher, sender note plumbing, frontend types/UI/validation, tests, and documentation.

Changes

Notification Quiet Hours and Rate Limiting

Layer / File(s) Summary
Data models, migrations, and sweeper
server/internal/models/notification_dest.go, server/internal/models/notification_dest_test.go, server/internal/models/notification_log.go, server/internal/models/notification_log_test.go, server/internal/db/db.go, server/internal/db/db_test.go
Adds quiet-hours and rate-limit fields to NotificationDest, introduces NotificationLog model with indexes, auto-migrates schemas at startup, and adds an hourly sweeper that prunes old logs while preserving unflushed held rows; tests cover migration and sweeper behavior.
Admin API policy configuration & tests
server/internal/handlers/admin_notifications.go, server/internal/handlers/admin_notifications_test.go
Adds policyInput, HH:MM regex and validatePolicy, validates mode and rate-limit constraints on create/update, persists policy fields on create and update; tests cover validation, successful create/update, and invalid input paths.
Quiet-window and note helpers
server/internal/notify/window.go, server/internal/notify/window_test.go
Adds parseHHMM, inWindowMinutes (supports wrap-past-midnight), inQuietWindow, rateWindow, decision constants, and appendNote helper with unit tests.
Policy decision logic & tests
server/internal/notify/policy.go, server/internal/notify/policy_test.go
Dispatcher helpers to log decisions, count sent events in sliding windows, count dropped-rate after last send, and decide() implementing quiet-hours vs rate-limit outcomes and suppression-note generation; tests validate counting and decision matrix.
Dispatcher refactor & concurrency tests
server/internal/notify/notify.go, server/internal/notify/notify_clock_test.go, server/internal/notify/notify_test.go, server/internal/notify/send_test.go
Dispatcher gains injectable clock, refactors concurrent send to evaluateAndSend which calls decide, records decisions, reserves rate slots via NotificationLog, and routes notes through sendTo; tests assert clock behavior, routing, decision recording, and rate-limit hard-cap under concurrency.
Background digest flusher & tests
server/internal/notify/digest.go, server/internal/notify/digest_test.go
Flusher emits synthetic digest notifications for defer-mode destinations when they exit quiet window, marks held logs as flushed, creates digest log entry, and runs on a ticker; tests exercise on-window and off-window behavior.
Provider sender updates & tests
server/internal/notify/discord.go, server/internal/notify/discord_test.go, server/internal/notify/slack.go, server/internal/notify/slack_test.go, server/internal/notify/ntfy.go, server/internal/notify/ntfy_test.go
Discord/Slack/ntfy senders accept an extra note parameter and append suppression info when present; test call sites updated and new tests verify suppressed note content in payloads.
Frontend types, validation, and admin UI
web/src/api/client.ts, web/src/pages/notificationPolicy.ts, web/tests/admin-notifications-policy.test.ts, web/src/pages/AdminPage.tsx
Adds NotificationPolicy type; extends NotificationDest and NotificationDestInput; normalizes policy fields; adds validatePolicyForm with HH:MM/mode/count/unit checks and tests; Admin UI gains controls for quiet hours and rate limits and validates on save.
Documentation
docs/site/docs/integrations/notifications.md
New documentation section explains quiet hours (server timezone, midnight-wrap), drop vs defer+digest behavior, rate-limiting semantics (hour/day sliding windows), suppressed-count notes, and that controls default to off.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~75 minutes

Possibly related PRs

  • maxjb-xyz/blackbox#42: Extends admin notification destination CRUD flows and notification dispatch plumbing; likely closely related to policy persistence and sender changes.

Poem

🔔 Quiet hours hum, alerts take their rest,
Suppressed counts tally each unruly guest,
When windows open, digests gently sing,
Rate limits steady the notifying spring,
Midnight wraps keep the silence blessed.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 13.24% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat: Alert Policies for Quiet Hours and Rate Limits' clearly and concisely describes the main feature addition across the changeset.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/alert-policy

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.

@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: 9

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@server/internal/handlers/admin_notifications_test.go`:
- Around line 259-343: Add a new test TestUpdateNotificationDest_WithPolicy that
seeds a notification via newNotificationTestDB, then issues a PUT to
UpdateNotificationDest using adminNotificationRequest with a JSON body
containing the full quiet_hours_* and rate_limit_* fields (e.g.
quiet_hours_enabled/start/end/mode and rate_limit_enabled/count/unit) to
exercise the Updates map path, then fetch/decode the updated
models.NotificationDest and assert that QuietHoursEnabled, QuietHoursStart,
QuietHoursEnd, QuietHoursMode, RateLimitEnabled, RateLimitCount and
RateLimitUnit match the sent values; use the same helpers as other tests
(newNotificationTestDB, adminNotificationRequest) and mirror the pattern from
TestCreateNotificationDest_WithPolicy for status code and field assertions.

In `@server/internal/models/notification_log.go`:
- Around line 5-20: NotificationLog grows without retention; implement a sweeper
similar to StartOIDCStateSweeper that periodically deletes old NotificationLog
rows beyond the retention horizon (e.g. >24h) while preserving pending held
entries (NotificationLog where Decision == "held" and FlushedAt == nil); add a
StartNotificationLogSweeper function in db.go that runs on a ticker, executes a
single DELETE query filtering by CreatedAt < now - retention AND NOT
(Decision="held" AND FlushedAt IS NULL), logs errors, and hook it into startup
alongside StartOIDCStateSweeper.

In `@server/internal/notify/digest_test.go`:
- Around line 32-33: The two test calls to d.logDecision currently ignore the
returned error; capture the error from each call (e.g., err :=
d.logDecision(...)) and handle it—in tests this should be a fatal assertion like
if err != nil { t.Fatalf("logDecision failed: %v", err) } (or use
require.NoError(t, err) if testify is already used). Update both d.logDecision
invocations (the ones with ids "i1" and "i2") to check the error and fail the
test on non-nil error.
- Line 60: The call to d.logDecision in the test is ignoring its error return;
update the invocation of d.logDecision (the helper under test) to capture and
assert the error (e.g., err := d.logDecision(...); fail the test if err != nil)
so the test consistently checks and fails on unexpected errors; apply the same
pattern used elsewhere in the test suite for error assertions to keep CI linters
happy.

In `@server/internal/notify/digest.go`:
- Around line 78-85: The digest currently computes ids from held and builds a
note using len(held) but then lists the fetched incidents (variable incidents)
which can be fewer if some Incident rows were deleted; update the note to use
len(incidents) (the actual fetched slice) instead of len(held) so the count
matches the listed items, or explicitly handle missing incidents by filtering
held and adjusting the message to reflect "X of Y held" using both
len(incidents) and len(held) in the digest generation (refer to variables held,
ids, incidents and the DB lookup via f.db and models.Incident).

In `@server/internal/notify/discord_test.go`:
- Line 118: The test currently calls ExportedSendDiscord with empty note strings
so the new Suppressed branch in sendDiscord is never exercised; add a targeted
test that passes a non-empty note string and asserts the produced Discord embed
contains a "Suppressed" field and the note text. Update or add a test (e.g.,
TestSendDiscord_AppendsSuppressedNote) that starts an httptest.Server capturing
request body, calls ExportedSendDiscord with a models.Incident and the note "(+2
suppressed in the last hour)", checks no error, and asserts the captured body
contains both "Suppressed" and the note text to cover the Suppressed branch in
sendDiscord.

In `@server/internal/notify/notify.go`:
- Around line 86-90: When d.decide(d.db, dest) returns an error, don’t return
early; instead log the error, set the decision to a persistent failure marker
(e.g., DecisionFailed or a new constant) and append the error text to note, then
continue the normal send/audit path so a NotificationLog row is always written;
update the code around d.decide to use the DecisionFailed symbol (or create it)
and ensure the existing NotificationLog writer (e.g., writeNotificationLog /
whatever function writes NotificationLog rows) is invoked with the decision and
note even on decide errors, and if desired still attempt sending for critical
alerts based on dest/priority.

In `@server/internal/notify/policy.go`:
- Around line 70-88: The current rate check in decide (which calls
sentCountSince and droppedRateSinceLastSent and returns decisionSent) is racy
under concurrent Send/evaluateAndSend calls; to enforce a hard cap either
serialize per-destination decisions or push the check+write into the DB:
implement a per-destination keyed mutex (map[id]mutex or sync.Map of mutexes)
and acquire that lock at the start of decide and hold it until after the code
that logs the decisionSent row in evaluateAndSend, or refactor so the
rateWindow/count check and insertion of the decisionSent row occur inside a
single DB transaction/atomic conditional insert (e.g., SELECT COUNT... FOR
UPDATE then INSERT if count < limit). Ensure the lock or transaction surrounds
the sentCountSince check and the eventual write of decisionSent to prevent
in-flight overshoot.

In `@web/src/api/client.ts`:
- Line 746: The normalization sets const rateCount = typeof
data.rate_limit_count === 'number' ? data.rate_limit_count : 0 which can produce
0 while notificationPolicy.ts requires count >= 1 when rate_limit_enabled is
true; change the fallback to 1 (or otherwise coerce to Math.max(1,
providedValue)) so that rateCount aligns with the validation, and ensure any
usages that rely on rate_limit_enabled and rateCount (look for references to
rate_limit_enabled and rateCount in this module) will receive a valid minimum
value.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 94ba39c5-84b8-49ab-bea0-4a93cb5619fb

📥 Commits

Reviewing files that changed from the base of the PR and between b27bd7f and 2fb1f9d.

📒 Files selected for processing (29)
  • docs/site/docs/integrations/notifications.md
  • server/internal/db/db.go
  • server/internal/handlers/admin_notifications.go
  • server/internal/handlers/admin_notifications_test.go
  • server/internal/models/notification_dest.go
  • server/internal/models/notification_dest_test.go
  • server/internal/models/notification_log.go
  • server/internal/models/notification_log_test.go
  • server/internal/notify/digest.go
  • server/internal/notify/digest_test.go
  • server/internal/notify/discord.go
  • server/internal/notify/discord_test.go
  • server/internal/notify/notify.go
  • server/internal/notify/notify_clock_test.go
  • server/internal/notify/notify_test.go
  • server/internal/notify/ntfy.go
  • server/internal/notify/ntfy_test.go
  • server/internal/notify/policy.go
  • server/internal/notify/policy_test.go
  • server/internal/notify/send_test.go
  • server/internal/notify/slack.go
  • server/internal/notify/slack_test.go
  • server/internal/notify/window.go
  • server/internal/notify/window_test.go
  • server/main.go
  • web/src/api/client.ts
  • web/src/pages/AdminPage.tsx
  • web/src/pages/notificationPolicy.ts
  • web/tests/admin-notifications-policy.test.ts

Comment on lines +5 to +20
// NotificationLog records every per-destination send decision made by the
// dispatcher. It powers sliding-window rate counting, the suppressed-count
// note, the deferred-digest hold queue, and "why was/wasn't I paged?"
// observability.
type NotificationLog struct {
ID string `gorm:"primaryKey" json:"id"`
DestID string `gorm:"index:idx_notiflog_dest_created;index:idx_notiflog_dest_decision" json:"dest_id"`
IncidentID string `json:"incident_id"`
Event string `json:"event"`
// Decision is one of: sent, held, dropped_rate, dropped_quiet, failed, digest.
Decision string `gorm:"index:idx_notiflog_dest_decision" json:"decision"`
Note string `json:"note"`
CreatedAt time.Time `gorm:"index:idx_notiflog_dest_created" json:"created_at"`
// FlushedAt is set on held rows when they are rolled into a digest.
FlushedAt *time.Time `gorm:"index:idx_notiflog_dest_decision" json:"flushed_at,omitempty"`
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick | 🔵 Trivial

Heads up: this log table has no purge protocol.

NotificationLog records every dispatch decision (sent/held/dropped/digest) with no retention or pruning. On a busy deployment this grows without bound — and unlike OIDCState, there's no sweeper to keep it trimmed. I'd recommend a periodic cleanup goroutine that deletes rows older than your rate-limit/digest horizon (e.g. anything older than a day that isn't a pending held row), mirroring the existing StartOIDCStateSweeper pattern in db.go.

Want me to draft a StartNotificationLogSweeper modeled on the OIDC sweeper?

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@server/internal/models/notification_log.go` around lines 5 - 20,
NotificationLog grows without retention; implement a sweeper similar to
StartOIDCStateSweeper that periodically deletes old NotificationLog rows beyond
the retention horizon (e.g. >24h) while preserving pending held entries
(NotificationLog where Decision == "held" and FlushedAt == nil); add a
StartNotificationLogSweeper function in db.go that runs on a ticker, executes a
single DELETE query filtering by CreatedAt < now - retention AND NOT
(Decision="held" AND FlushedAt IS NULL), logs errors, and hook it into startup
alongside StartOIDCStateSweeper.

Comment thread server/internal/notify/digest_test.go Resolved
Comment thread server/internal/notify/digest_test.go Resolved
Comment on lines +78 to +85
ids := make([]string, 0, len(held))
for _, h := range held {
ids = append(ids, h.IncidentID)
}
var incidents []models.Incident
if err := f.db.Where("id IN ?", ids).Find(&incidents).Error; err != nil {
return err
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick | 🔵 Trivial | 💤 Low value

Incident-to-held-log count mismatch possible if incidents are deleted.

Chief, if an Incident row is deleted after its notification was held but before this digest runs, incidents will have fewer entries than held. The digest note (line 98) will say "digest of N held" but the message body will list fewer incidents. This is a minor inconsistency but won't cause failures.

Consider using len(incidents) in the note for accuracy, or documenting this edge case as acceptable behavior.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@server/internal/notify/digest.go` around lines 78 - 85, The digest currently
computes ids from held and builds a note using len(held) but then lists the
fetched incidents (variable incidents) which can be fewer if some Incident rows
were deleted; update the note to use len(incidents) (the actual fetched slice)
instead of len(held) so the count matches the listed items, or explicitly handle
missing incidents by filtering held and adjusting the message to reflect "X of Y
held" using both len(incidents) and len(held) in the digest generation (refer to
variables held, ids, incidents and the DB lookup via f.db and models.Incident).

Comment thread server/internal/notify/discord_test.go Resolved
Comment thread server/internal/notify/notify.go Resolved
Comment on lines +70 to +88
if dest.RateLimitEnabled && dest.RateLimitCount > 0 {
window := rateWindow(dest.RateLimitUnit)
count, err := d.sentCountSince(db, dest.ID, now.Add(-window))
if err != nil {
return "", "", err
}
if count >= int64(dest.RateLimitCount) {
return decisionDroppedRate, "", nil
}
suppressed, err := d.droppedRateSinceLastSent(db, dest.ID)
if err != nil {
return "", "", err
}
if suppressed > 0 {
note = fmt.Sprintf("(+%d suppressed in the last %s)", suppressed, dest.RateLimitUnit)
}
}

return decisionSent, note, nil

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick | 🔵 Trivial

Heads up, Chief — the rate limiter is a soft limit under concurrent bursts.

decide reads sentCountSince here, but the corresponding decisionSent row isn't written until evaluateAndSend finishes the outbound send. Since Send fans out per destination across goroutines (and multiple incidents can fire near-simultaneously), several dispatches for the same destination can each observe count < RateLimitCount and all proceed before any of them logs a sent row. Net effect: the cap can be exceeded by roughly the number of in-flight sends.

For an alerting system a small overshoot is usually tolerable, so this isn't a blocker — but if you need a hard cap, serialize per-destination decisions (e.g., a per-dest mutex/keyed lock around decide→log) or enforce it at the DB layer within a transaction.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@server/internal/notify/policy.go` around lines 70 - 88, The current rate
check in decide (which calls sentCountSince and droppedRateSinceLastSent and
returns decisionSent) is racy under concurrent Send/evaluateAndSend calls; to
enforce a hard cap either serialize per-destination decisions or push the
check+write into the DB: implement a per-destination keyed mutex (map[id]mutex
or sync.Map of mutexes) and acquire that lock at the start of decide and hold it
until after the code that logs the decisionSent row in evaluateAndSend, or
refactor so the rateWindow/count check and insertion of the decisionSent row
occur inside a single DB transaction/atomic conditional insert (e.g., SELECT
COUNT... FOR UPDATE then INSERT if count < limit). Ensure the lock or
transaction surrounds the sentCountSince check and the eventual write of
decisionSent to prevent in-flight overshoot.

Comment thread web/src/api/client.ts Resolved
maxjb-xyz and others added 3 commits June 2, 2026 02:22
Reserve the rate slot under a per-destination lock (decide + sent-row insert
held together) so concurrent sends cannot both pass the cap; HTTP delivery
stays outside the lock. On a decide() error, deliver best-effort instead of
silently dropping the notification.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Adds StartNotificationLogSweeper (mirrors StartOIDCStateSweeper): hourly DELETE
of rows older than 48h, preserving pending held rows awaiting a deferred digest.
Wired into startup alongside the OIDC sweeper.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
… fixes

- TestUpdateNotificationDest_WithPolicy exercises the Updates-map path
- TestSendDiscord_AppendsSuppressedNote covers the Suppressed embed field
- digest_test now asserts logDecision errors
- normalizeNotificationDest rate count fallback aligns with the >=1 minimum

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

@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.

♻️ Duplicate comments (1)
server/internal/notify/notify.go (1)

135-138: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Keep the alert path fail-open when the reservation write breaks.

Line 135 still turns a transient notification_logs insert failure into a dropped notification. The send never happens, and there’s no fallback audit row. After unlocking, fall back to d.deliver(dest, inc, event, incURL, note) so a DB hiccup degrades rate enforcement instead of swallowing the alert.

Proposed fix
 	if err := d.db.Create(row).Error; err != nil {
 		mu.Unlock()
-		log.Printf("notify: reserve sent for %q: %v", dest.Name, err)
+		log.Printf("notify: reserve sent for %q: %v (sending anyway)", dest.Name, err)
+		d.deliver(dest, inc, event, incURL, note)
 		return
 	}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@server/internal/notify/notify.go` around lines 135 - 138, The reservation
insert failure currently unlocks the mutex and returns early, dropping the
notification; instead, after mu.Unlock() call d.deliver(dest, inc, event,
incURL, note) so the alert still sends when the DB write fails (failing open).
Locate the block where d.db.Create(row).Error is checked in notify.go, keep the
mu.Unlock(), then invoke d.deliver(dest, inc, event, incURL, note) and return
its result (or ignore its error if the surrounding function expects no error) so
rate enforcement degrades but the notification is still delivered.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Duplicate comments:
In `@server/internal/notify/notify.go`:
- Around line 135-138: The reservation insert failure currently unlocks the
mutex and returns early, dropping the notification; instead, after mu.Unlock()
call d.deliver(dest, inc, event, incURL, note) so the alert still sends when the
DB write fails (failing open). Locate the block where d.db.Create(row).Error is
checked in notify.go, keep the mu.Unlock(), then invoke d.deliver(dest, inc,
event, incURL, note) and return its result (or ignore its error if the
surrounding function expects no error) so rate enforcement degrades but the
notification is still delivered.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 76169cbb-e2fd-4206-8b03-5d3002385929

📥 Commits

Reviewing files that changed from the base of the PR and between 2fb1f9d and caf5818.

📒 Files selected for processing (9)
  • server/internal/db/db.go
  • server/internal/db/db_test.go
  • server/internal/handlers/admin_notifications_test.go
  • server/internal/notify/digest_test.go
  • server/internal/notify/discord_test.go
  • server/internal/notify/notify.go
  • server/internal/notify/send_test.go
  • server/main.go
  • web/src/api/client.ts

A failed reservation insert previously dropped the notification; now it falls
through to deliver() so the alert still sends (rate enforcement degrades),
matching the decide()-error fail-open path.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@maxjb-xyz
maxjb-xyz merged commit 8a786db into main Jun 3, 2026
7 of 8 checks passed
@maxjb-xyz
maxjb-xyz deleted the feature/alert-policy branch June 3, 2026 06:03
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.

1 participant