Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -885,6 +885,9 @@ A `recipient` that is neither an E.164 number nor, for channel `imessage` or `al

## Bug Fixes

### The `unowned` usage alert is sent once a day, not once a minute

The router's `unowned` alert holds for as long as usage rows wait for an app to join an organization, which can be days, and was sent again every minute it held. It is now sent again at most once a day while it holds; it is still sent as soon as it starts holding, including when it holds again after it stopped. Every other usage alert is unchanged (#2115).
### The JavaScript SDK's channel stops the agent's reply from the default stop button

The default stop button of stream-chat-react's composer, `StopAIGenerationButton`, calls the channel's `stopAIResponse()`, as React Native's composer does, which only sent `ai_indicator.stop`, an event the agent does not act on, so the reply went on and apps replaced the button with one calling `session.interrupt()`. On the channel `session.chat()` opens, `stopAIResponse()` now interrupts the session's reply first and still sends the event, so the default button works and the override can go. The channel gets Stream Chat's own back when the session is closed.
Expand Down
55 changes: 42 additions & 13 deletions acceleration/internal/alerts/alerts.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
// Package alerts checks named conditions in the process that can see them, and sends one
// Sentry event per condition that holds at most once per interval, which Sentry's alert rules
// route by the usage_alert tag. Without a Sentry DSN an alert is only logged, at ERROR, which
// it always is too. Every check also adds to the counter router_alert_holds_total{alert,level}
// what the condition holds at that check (1, or the number of items), whatever the limit
// sends, so a monitor outside Sentry can page on an increase of the level page ones. A hold at
// the last check, on shutdown, or during a drain reaches Sentry only: by then /metrics is closed
// or handed over.
// Sentry event per condition that holds at most once per interval (the loop's Limit, or the
// condition's own Repeat), which Sentry's alert rules route by the usage_alert tag. Without a
// Sentry DSN an alert is only logged, at ERROR, which it always is too. Every check also adds to
// the counter router_alert_holds_total{alert,level} what the condition holds at that check (1, or
// the number of items), whatever the limit sends, so a monitor outside Sentry can page on an
// increase of the level page ones. A hold at the last check, on shutdown, or during a drain
// reaches Sentry only: by then /metrics is closed or handed over.
package alerts

import (
Expand All @@ -15,6 +15,7 @@ import (
"os"
"path/filepath"
"slices"
"strings"
"time"

"github.com/getsentry/sentry-go"
Expand Down Expand Up @@ -78,6 +79,12 @@ type Condition struct {
// whoever reads it in Slack. It follows the name in the alert's message; the fingerprint and
// the tags do not have it, so a new summary keeps the alert's Sentry issue.
Summary string
// Repeat is the least time between two events of the condition, or of one of its items,
// while it keeps holding, in place of the loop's Limit; zero keeps the Limit. Once it stops
// holding, the next time it holds is sent at once. A check that is given the loop's limit
// (IncreasedSinceAlert, IncreasedPer) must be given the Repeat instead, or it loses every
// increase the Repeat holds back.
Repeat time.Duration
Comment thread
kanat marked this conversation as resolved.
Resolved
}

// Options configure a Loop.
Expand All @@ -91,7 +98,8 @@ type Options struct {
Tags map[string]string
// Every is how often the conditions are checked; defaults to 15 s.
Every time.Duration
// Limit is the least time between two events of one condition; defaults to a minute.
// Limit is the least time between two events of one condition without a Repeat of its
// own; defaults to a minute.
Limit time.Duration
// Now is the loop's clock; nil is time.Now.
Now func() time.Time
Expand Down Expand Up @@ -146,7 +154,7 @@ func (l *Loop) Run(ctx context.Context) {
}

// check counts what each condition holds and sends each condition that holds and was not sent
// within the limit.
// within its repeat interval.
func (l *Loop) check() {
now := l.options.Now()
for _, condition := range l.conditions {
Expand All @@ -157,10 +165,13 @@ func (l *Loop) check() {
held, extra := condition.Check(now)
counter := holds.WithLabelValues(condition.Name, string(condition.Level))
if !held {
if condition.Repeat != 0 {
delete(l.sent, condition.Name)
}
continue
}
counter.Inc()
if last, ok := l.sent[condition.Name]; ok && now.Sub(last) < l.options.Limit {
if last, ok := l.sent[condition.Name]; ok && now.Sub(last) < l.repeat(condition) {
Comment thread
kanat marked this conversation as resolved.
Resolved
continue
}
l.sent[condition.Name] = now
Expand All @@ -169,14 +180,24 @@ func (l *Loop) check() {
}

// checkItems adds the number of items the condition holds for to its counter, and sends each
// item that was not sent within the limit, in order so the events of one check go out the
// same way every time.
// item that was not sent within its repeat interval, in order so the events of one check go out
// the same way every time.
func (l *Loop) checkItems(now time.Time, condition Condition) {
held := condition.Items(now)
holds.WithLabelValues(condition.Name, string(condition.Level)).Add(float64(len(held)))
if condition.Repeat != 0 {
prefix := condition.Name + ":"
for key := range l.sent {
if item, ok := strings.CutPrefix(key, prefix); ok {
if _, still := held[item]; !still {
delete(l.sent, key)
}
}
}
}
for _, item := range slices.Sorted(maps.Keys(held)) {
key := condition.Name + ":" + item
if last, ok := l.sent[key]; ok && now.Sub(last) < l.options.Limit {
if last, ok := l.sent[key]; ok && now.Sub(last) < l.repeat(condition) {
continue
}
l.sent[key] = now
Expand All @@ -188,6 +209,14 @@ func (l *Loop) checkItems(now time.Time, condition Condition) {
}
}

// repeat is the least time between two events of condition, or of one of its items.
func (l *Loop) repeat(condition Condition) time.Duration {
if condition.Repeat != 0 {
return condition.Repeat
}
return l.options.Limit
}

// Send sends one alert now, for a short-lived process (a job) that has no loop. It goes to
// the current hub, tagged with the binary's name; the caller flushes Sentry before it exits.
func Send(name string, level Level, extra map[string]any) {
Expand Down
101 changes: 101 additions & 0 deletions acceleration/internal/alerts/alerts_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,107 @@ func (s *AlertsSuite) TestAConditionHeldPastTheLimitIsSentAgain() {
s.Equal(sentry.LevelError, s.sent()[0].Level)
}

func (s *AlertsSuite) TestAConditionWithItsOwnRepeatIsSentAgainOnlyAfterIt() {
start := time.Now()
now := start
loop := New(Options{
Hub: s.hub, Logger: slog.New(slog.NewTextHandler(s.logs, nil)), Every: 15 * time.Second, Limit: time.Minute,
Now: func() time.Time { return now },
}, Condition{Name: "unowned", Level: Warn, Repeat: 24 * time.Hour,
Check: func(time.Time) (bool, map[string]any) { return true, nil }})

s.ticks(loop, &now, start, 0)
s.Require().Len(s.sent(), 1, "the first event goes out as soon as the condition holds")
s.ticks(loop, &now, start, time.Minute, 2*time.Minute, time.Hour, 24*time.Hour-time.Second)
s.Len(s.sent(), 1, "the loop's one-minute limit does not apply to it")
s.ticks(loop, &now, start, 24*time.Hour)
s.Len(s.sent(), 2)
}

func (s *AlertsSuite) TestAnItemOfAConditionWithItsOwnRepeatIsSentAgainOnlyAfterIt() {
start := time.Now()
now := start
loop := New(Options{
Hub: s.hub, Logger: slog.New(slog.NewTextHandler(s.logs, nil)), Every: 15 * time.Second, Limit: time.Minute,
Now: func() time.Time { return now },
}, Condition{Name: "unowned", Level: Warn, Repeat: 24 * time.Hour,
Items: func(time.Time) map[string]map[string]any { return map[string]map[string]any{"a": nil} }})

s.ticks(loop, &now, start, 0, time.Minute, 2*time.Minute, 24*time.Hour-time.Second)
s.Len(s.sent(), 1)
s.ticks(loop, &now, start, 24*time.Hour)
s.Len(s.sent(), 2)
}

func (s *AlertsSuite) TestANewSpellOfAConditionWithItsOwnRepeatIsSentAtOnce() {
start := time.Now()
now := start
holds := func(now time.Time) bool { at := now.Sub(start); return at < 2*time.Hour || at >= 3*time.Hour }
loop := New(Options{
Hub: s.hub, Logger: slog.New(slog.NewTextHandler(s.logs, nil)), Every: 15 * time.Second, Limit: time.Minute,
Now: func() time.Time { return now },
}, Condition{Name: "unowned", Level: Warn, Repeat: 24 * time.Hour,
Check: func(now time.Time) (bool, map[string]any) { return holds(now), nil }})

s.ticks(loop, &now, start, 0, time.Hour, 2*time.Hour, 3*time.Hour, 4*time.Hour)

s.Len(s.sent(), 2, "the condition stopped holding at 2 h, so 3 h starts a new spell")
}

func (s *AlertsSuite) TestAnItemThatComesBackIsSentAtOnce() {
start := time.Now()
now := start
loop := New(Options{
Hub: s.hub, Logger: slog.New(slog.NewTextHandler(s.logs, nil)), Every: 15 * time.Second, Limit: time.Minute,
Now: func() time.Time { return now },
}, Condition{Name: "unowned", Level: Warn, Repeat: 24 * time.Hour,
Items: func(now time.Time) map[string]map[string]any {
if at := now.Sub(start); at >= time.Hour && at < 2*time.Hour {
return map[string]map[string]any{"b": nil}
}
return map[string]map[string]any{"a": nil, "b": nil}
}})

s.ticks(loop, &now, start, 0, time.Hour, 2*time.Hour, 3*time.Hour)

events := s.sent()
s.Require().Len(events, 3, "a went away at 1 h and came back at 2 h; b never went away")
s.Equal("a", events[2].Tags["item"])
}

func (s *AlertsSuite) TestAConditionWithoutARepeatKeepsTheLimitAcrossSpells() {
start := time.Now()
now := start
loop := New(Options{
Hub: s.hub, Logger: slog.New(slog.NewTextHandler(s.logs, nil)), Every: 15 * time.Second, Limit: time.Minute,
Now: func() time.Time { return now },
}, Condition{Name: "rejected", Level: Page,
Check: func(now time.Time) (bool, map[string]any) { return now.Sub(start) != 15*time.Second, nil }})

s.ticks(loop, &now, start, 0, 15*time.Second, 30*time.Second)

s.Len(s.sent(), 1, "a condition with no Repeat is held back for the Limit even after it stopped holding")
Comment thread
kanat marked this conversation as resolved.
Resolved
}

func (s *AlertsSuite) TestAnItemOfAConditionWithoutARepeatKeepsTheLimitAcrossSpells() {
start := time.Now()
now := start
loop := New(Options{
Hub: s.hub, Logger: slog.New(slog.NewTextHandler(s.logs, nil)), Every: 15 * time.Second, Limit: time.Minute,
Now: func() time.Time { return now },
}, Condition{Name: "rejected", Level: Page,
Items: func(now time.Time) map[string]map[string]any {
if now.Sub(start) == 15*time.Second {
return map[string]map[string]any{}
}
return map[string]map[string]any{"a": nil}
}})

s.ticks(loop, &now, start, 0, 15*time.Second, 30*time.Second)

s.Len(s.sent(), 1, "an item with no Repeat is held back for the Limit even after it went away")
}

func (s *AlertsSuite) TestWithNoDSNAnAlertIsLogged() {
held := Condition{Name: "ingest_failing", Level: Page, Check: func(time.Time) (bool, map[string]any) {
return true, map[string]any{"increase": 4}
Expand Down
8 changes: 4 additions & 4 deletions acceleration/internal/routing/alerts.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,9 @@ func unflushedHoldsSeconds() float64 {
}

// Alerts are the router's usage conditions, for the one alerts loop of a process, which sends
// one event of a condition at most every limit. A row lost or refused while the limit holds the
// alert back is sent once the limit has passed, and each row is sent once. The names are the
// alerts' everywhere they are routed.
// one event of a condition at most every limit, or its Repeat. A row lost or refused while the
// limit holds the alert back is sent once the limit has passed, and each row is sent once. The
// names are the alerts' everywhere they are routed.
func Alerts(limit time.Duration) []alerts.Condition {
return []alerts.Condition{
// Every lost row is revenue, so there is no hold.
Expand All @@ -63,7 +63,7 @@ func Alerts(limit time.Duration) []alerts.Condition {
Summary: "spend holds are not reaching the other routers, so billable requests are refused with 503 spend_check_unavailable"},
{Name: "ship_stale", Level: alerts.Page, Check: aboveFor(unshippedOldest, shipStaleSeconds, shipStaleFor, "oldest_unshipped_started_seconds_ago"),
Summary: "usage rows are not reaching the usage service, so the balances it keeps are stale"},
{Name: "unowned", Level: alerts.Warn, Check: alerts.IncreasingFor(func() float64 { return alerts.Total(usageUnowned) }, unownedFor),
{Name: "unowned", Level: alerts.Warn, Repeat: 24 * time.Hour, Check: alerts.IncreasingFor(func() float64 { return alerts.Total(usageUnowned) }, unownedFor),
Summary: "usage rows of an app that has joined no organization keep waiting; they are not billed until the app joins one"},
{Name: "pending_slow", Level: alerts.Warn, Check: aboveFor(oldestPending, pendingSlowSeconds, 0, "oldest_pending_seconds"),
Summary: fmt.Sprintf("a usage row has waited over %d seconds to be written: Postgres is slow, or writes are failing and retried", pendingSlowSeconds)},
Expand Down
13 changes: 13 additions & 0 deletions acceleration/internal/routing/alerts_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,19 @@ func (s *UsageAlertsSuite) TestTheRouterHasItsEightConditions() {
}, levels)
}

// unowned holds for days while one row waits, so a per-minute event floods Sentry.
func (s *UsageAlertsSuite) TestOnlyUnownedRepeatsOnceADay() {
repeats := map[string]time.Duration{}
for _, condition := range Alerts(time.Minute) {
repeats[condition.Name] = condition.Repeat
}

s.Equal(map[string]time.Duration{
"lost": 0, "rejected": 0, "write_failing": 0, "ship_stale": 0,
"holds_flush_failing": 0, "unowned": 24 * time.Hour, "pending_slow": 0, "unattributed": 0,
}, repeats)
}

// The Slack message of an alert is its Sentry title: without a summary it names only the alert.
func (s *UsageAlertsSuite) TestEveryConditionSaysWhatItMeans() {
for _, condition := range Alerts(time.Minute) {
Expand Down
Loading