Skip to content

AI-3373: unowned usage alert names each app - #2118

Merged
kanat merged 8 commits into
mainfrom
fix/ai-3373-unowned-alert-names-app
Nov 26, 2026
Merged

kanat merged 8 commits into
mainfrom
fix/ai-3373-unowned-alert-names-app

Conversation

@aliev

@aliev aliev commented Nov 19, 2026 •

Copy link
Copy Markdown
Member

Why

The router's unowned usage alert reaches Sentry as usage alert: unowned with only an increase and a value. It names no app, and the number counts every sweep that passed over a waiting row, not rows. Whoever opens it cannot tell which app waits, how much, since when, or what to check.

How it works

every router, each sweeper count (30 s)
  │
  ├─ shard PG:  requests WHERE to_ship AND shipped_at IS NULL
  │             AND organization_id = ''
  │             GROUP BY app, api_key, modality, provider, model
  │
  ├─ global PG: drop apps that have an app_organizations row
  │             (the next sweep ships their rows)
  │
  └─ Sweeper.unowned = []UnownedApp
          │
alerts loop (every 15 s)
  │
  └─ unowned (Items): one item per app whose oldest
     waiting row started >= 15 min ago
          │
          └─ Sentry event per app, fingerprint usage_unowned:<app>

Sentry event, before and after:

Before After
Message usage alert: unowned: usage rows of an app that has joined no organization keep waiting; ... usage alert: unowned app-123: the app has joined no organization, so its usage rows wait and are not billed until it joins one; check app_organizations for the app first, then what wrote the rows (written_by: api_key, modality, provider, model)
Fingerprint usage_alert:unowned (all apps, one issue) usage_unowned:app-123 (one issue per app)
Context increase, span, value (sweep skips) waiting_rows, cost_micros, oldest_started_at, oldest_waiting, written_by[] (top 10 groups by rows; the rest in other_groups, other_rows)
Level, hold warn, counter rising for 15 min warn, oldest waiting row started 15 min ago

Context of one event:

{
  "waiting_rows": 12,
  "cost_micros": 400,
  "oldest_started_at": "2026-11-18T10:00:00Z",
  "oldest_waiting": "26h0m0s",
  "written_by": [
    {"api_key": "job:crawler", "modality": "knowledge",
     "provider": "turbopuffer", "model": "write",
     "rows": 10, "cost_micros": 300},
    {"api_key": "key-1", "modality": "llm",
     "provider": "openai", "model": "gpt",
     "rows": 2, "cost_micros": 100}
  ]
}
Change Result Test
Store.UnownedUsage (internal/store/shipping.go) waiting rows with no organization, by app and by what wrote them; shipped, organized and joined apps left out TestUnownedUsageIsTheWaitingRowsOfAppsWithNoOrganization, TestUnownedUsageStartsAtTheOldestRowOfAnyGroup
Sweeper.count keeps it (internal/routing/sweeper.go) every router reads it each count; a failed count keeps the last TestTheUnownedAlertNamesTheAppWhoseRowsWaitUntilItJoinsOne, TestACountThatFailsKeepsTheAppsTheLastOneFound
unowned is an Items condition with Describe (internal/routing/alerts.go) one alert per app, rows not sweeps, gone once the app joins TestUnownedNamesEachAppWhoseRowsWaitedFifteenMinutes, TestUnownedWarnsFromTheFifteenthMinuteOn, TestUnownedReadsNothingFromASweeperNotYetCounted, TestUnownedSendsTheTenGroupsWithMostRowsAndSumsTheRest, TestUnownedSaysWhyTheRowsWaitAndWhatToCheck
router_usage_unowned_total help (internal/routing/metrics.go) name kept for dashboards; help says it counts skips n/a

Every router of a shard now sends the alert, as ship_stale already does; the per-app fingerprint keeps them one Sentry issue. The hourly log line naming the app is unchanged.

Validation

  • go vet (with and without -tags integration) on internal/store, internal/routing, internal/alerts.
  • Unit: go test ./internal/store ./internal/routing ./internal/alerts.
  • Integration: go test -tags integration ./internal/routing and the new store tests in TestStoreSuite and TestShardedStoreSuite; the new tests also under -race.
  • Red before the fix: the store test did not build (no UnownedUsage); the alert unit tests panicked on the old condition, which had no Items or Describe. The sweeper test asserts the same row counts once after two sweeps, which the old counter (2) fails.
  • Each later test fails under the defect it names: no nil guard (panic), <= at 15 minutes, no oldest update across groups, a failed membership read storing an empty list, no cap on written_by.

The unowned alert named no app and its number counted sweeps passing over
a waiting row. It is now one alert per app (usage_unowned:<app>), read
from Postgres at each sweeper count: waiting rows, their cost, when the
oldest started and the rows by api_key, modality, provider and model.
Apps that have joined an organization are left out. The skip counter
keeps its name; its help now says what it counts.
@coderabbitai

coderabbitai Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The store now aggregates unshipped usage rows for apps without organization membership. The sweeper stores these results, and the unowned alert reports apps whose oldest waiting row has reached the 15-minute threshold. Alert items include row counts, cost, timing, and writer groups. Tests cover aggregation, alert content, repeated sweeps, and removal of an app after it joins an organization.

Merge Risk: Minimal · up to 4bfe2

This change replaces the aggregate unowned-usage alert with one alert per app that has usage waiting without an organization. It appears well covered by tests and carries no identified merge-blocking risk.

- [ ] Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 7b8b5a1 and 4bfe270.

Files selected for processing: 3

  • CHANGELOG.md
  • acceleration/internal/routing/alerts.go
  • acceleration/internal/routing/alerts_test.go

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 5 remain after this review.

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

Nitpick comments: 1

acceleration/internal/store/shipping.go: 1

204-204: Trivial · Performance & Scalability · Quick win

Use a set for joined-app membership.

The group loop calls slices.Contains once per writer group. Each unsuccessful lookup scans every joined app. This makes membership filtering O(groups × joined apps) on every count.

Build a local set from joined, then use keyed lookups. This preserves the filter and reduces membership work to O(groups + joined apps).

Review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 0bacd97 and 6ce3f1d.

Files selected for processing: 8

  • CHANGELOG.md
  • acceleration/internal/routing/alerts.go
  • acceleration/internal/routing/alerts_test.go
  • acceleration/internal/routing/metrics.go
  • acceleration/internal/routing/shipper_test.go
  • acceleration/internal/routing/sweeper.go
  • acceleration/internal/store/shipping.go
  • acceleration/internal/store/shipping_test.go

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 6 remain after this review.

@kanat kanat left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Reviewed 6ce3f1d merged onto main at bb12cb4.

CI: all checks green.
Suites: the touched suites pass on the merged tree: unit tests for store, routing and alerts, plus the integration tests TestUnownedUsage* (unsharded and sharded) and the WriterSuite unowned/sweeper tests.

Checked and sound:

  • Query cost. The new query uses requests_to_ship_idx (partial, WHERE to_ship, 20261110135000_requests_usage_id.sql:50). I seeded 2.2M rows. With no backlog it is an index scan of 1.3 ms. With a 200k-row backlog it becomes a seq scan of 182 ms, the same plan as the existing Unshipped count (154 ms).
  • No N+1. The global-DB step is one batched IN query per count.
  • Shard and global split. requests is read on the shard and app_organizations on the global DB. ShardedStoreSuite kills both mutants that read from the wrong DB.
  • No secrets. api_key is a key id or an origin, never a secret (models.go:35).
  • Joined apps. An app is left out of the alert once it joins an organization: removing that filter fails the store test.
  • Other alerts, shipping and billing. Only the unowned entry changed, and the read is read-only.
  • CodeRabbit. The boundary thread is valid and is part of R1.1. The nitpick to use a set for joined apps is not needed: joined holds only apps that joined since their rows last shipped.

Verdict: request changes for R1.1: four surviving mutants, one of them an untested guard against a router crash.

Comment thread acceleration/internal/routing/alerts.go Resolved
Comment thread acceleration/internal/routing/alerts.go Resolved
Comment thread acceleration/internal/routing/alerts.go Resolved
Tests for the 15-minute boundary, a sweeper not yet counted, the oldest
row in a smaller group, and a failed count keeping the last apps. The
joined apps are a set.
@aliev

aliev commented Nov 19, 2026

Copy link
Copy Markdown
Member Author

@coderabbitai the nitpick on shipping.go (set for joined apps) is fixed in 7b8b5a1: the memberships are a map now.

@coderabbitai

coderabbitai Bot commented Nov 19, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

Analysis chain

Script executed:

#!/bin/bash
set -u
fd -t f -F 'shipping.go' . | while IFS= read -r file; do
  printf '\n--- Outline: %s ---\n' "$file"
  ast-grep outline "$file" --items all
  printf '\n--- Contents: %s ---\n' "$file"
  cat -n "$file"
done
printf '\n--- Commit changes ---\n'
git show --format=fuller --stat 7b8b5a159 --
printf '\n--- Commit diff for shipping.go ---\n'
git show --format= -- acceleration/internal/store/shipping.go 7b8b5a159 2>/dev/null || true
git show 7b8b5a159 -- acceleration/internal/store/shipping.go

Length of output: 20653


@aliev Confirmed. UnownedUsage now uses a map to check joined apps in acceleration/internal/store/shipping.go, Line 202.


If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

You are interacting with an AI system.

@kanat kanat left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Delta round 2. Verdict: GO. Reviewed 4bfe270 merged onto main 9edddca (clean). go test ./internal/store ./internal/routing ./internal/alerts and the integration subset (store TestUnownedUsage* in both suites; routing Writer/UsageAlerts Unowned|NoOrganization|ACountThatFails|Condition) pass, also with -shuffle=on and -race. gh pr checks shows all checks green on this head at read time.

Prior findings

  • R1.1 (Should fix): fixed. I reran all four mutants, each now fails a test:
    • nil guard removed: TestUnownedReadsNothingFromASweeperNotYetCounted.
    • < to <=: TestUnownedWarnsFromTheFifteenthMinuteOn. Also settles the CodeRabbit thread (4629528187): fixed.
    • earliest-row update in shipping.go removed: TestUnownedUsageStartsAtTheOldestRowOfAnyGroup.
    • failed read ignored, and failed read storing an empty list: TestACountThatFailsKeepsTheAppsTheLastOneFound.
  • R1.3 (Nit): done. The top-10 order comes from the store's ORDER BY customer_id, rows DESC, api_key, modality, provider, model, so the largest groups come first and ties are deterministic. I mutated the cap: constant 10 to 11 or 9, last 10 instead of first 10, += to =, skipping the first of the rest, other_groups off by one, other_rows summing cost, cap removed, keys always emitted. All fail TestUnownedSendsTheTenGroupsWithMostRowsAndSumsTheRest or an existing test. cost_micros stays the app total. An app with 1 group is unchanged (the keys-always mutant fails two existing tests).
  • Joined-apps map in shipping.go: map never filled, inverted filter and wrong key all fail TestUnownedUsageIsTheWaitingRowsOfAppsWithNoOrganization (both suites).
  • R1.2 (merge order with #2115): decided, reviewed in a later round.

New finding

  • [Nit] alerts.go:121: > to >= survives. With exactly 10 groups the event gets other_groups: 0 and other_rows: 0. Harmless. To pin it, add to UsageAlertsSuite: 10 groups (rows 20..11), app ten, oldest an hour ago; s.Equal(groups, held["written_by"]), s.NotContains(held, "other_groups"), s.NotContains(held, "other_rows"). I checked it passes on this head and fails under the mutant.

Details: reviewer-2.md in the ticket ledger.

kanat and others added 3 commits November 25, 2026 17:04
UnownedUsage moves to the Requests repository (main split Store); the
unowned condition keeps per-item names and the 24 h Repeat of #2115.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SWVEMob5wtaNHdUCC1msgG
@kanat

kanat commented Nov 25, 2026

Copy link
Copy Markdown
Collaborator

Taken over per Kanat (Ali's branch idle since 11-20). Main (with #2115, e75990b) is merged in b4f1d5b; no history rewritten.

What changed:

  • Merge conflicts: main split store.Store into repositories, so UnownedUsage, UnownedApp and UnownedGroup now live on Requests (store/request.go), and the sweeper calls s.store.Requests.UnownedUsage. The unowned condition keeps per-app naming and has Repeat: 24 * time.Hour from AI-3373: send the unowned usage alert at most once a day #2115.
  • New test TestUnownedNamesAnAppOnceADayWhileItWaits: a second send for the same app within 24 h is held, and after 24 h it is sent. Dropping the Repeat fails it (and TestOnlyUnownedRepeatsOnceADay).
  • New test TestUnownedWithExactlyTenGroupsSendsThemAllAndCountsNoRest, the remaining Nit of R1.3 (> to >= now fails it).
  • Ali's sweeper tests ported to the new Store API.

Checked: go vet with and without the integration tag, ./internal/routing, ./internal/alerts and ./internal/store unit and integration. Only TestEveryHotTableIsReadByIndex fails in store (planner, known base failure, none of its failing cases touch unowned usage). Still a draft.

@kanat kanat left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

VERDICT: GO

Delta round 3. Reviewed b4f1d5b merged onto main f58ff6e: the merge is clean, and go vet ./... and go vet -tags integration ./... pass in acceleration/ on the merged tree. Checks on the head are CodeQL, GitGuardian and labeler (pass); go and integration are skipped because the PR is a draft.

Prior findings

  • R1.1 (Should fix): fixed, as ruled before; its four tests still pass and the merge did not touch them.
  • R1.2 (Question, composing with #2115): answered by this merge. routing/alerts.go keeps the per-app Items and Describe and adds Repeat: 24 * time.Hour. Mutants: dropping Repeat, or changing it to 23 h, fails TestOnlyUnownedRepeatsOnceADay and TestUnownedNamesAnAppOnceADayWhileItWaits.
  • R1.3 (Nit, 10 groups): fixed. Changing > to >= at alerts.go:121 fails TestUnownedWithExactlyTenGroupsSendsThemAllAndCountsNoRest.

Merge resolutions (git show --remerge-diff on the merge)

  • routing/alerts.go: the unowned condition is the PR's Items form plus main's Repeat. Main's old Check line is gone and nothing from #2115's repeat handling is lost.
  • routing/alerts_test.go: main's TestOnlyUnownedRepeatsOnceADay is kept, and so is the PR's comment on the Slack message.
  • store/shipping.go, shipping_test.go: the removed block is main's old Store methods, which main moved to Requests. Against the old merge base the PR added only UnownedApp, UnownedGroup and UnownedUsage there, so nothing else of the PR was dropped.
  • store/request.go: UnownedUsage is ported as it was. Requests are read from r.store.shard and app_organizations from r.store.global, as AppOrganizations.Get does. The tests moved to request_test.go and use AppOrganizations.Upsert. Reading app_organizations from the shard instead of global fails both TestUnownedUsage* tests in ShardedStoreSuite. Skipping the joined-app check fails the main test in both suites.
  • sweeper.go calls s.store.Requests.UnownedUsage. shipper_test.go uses AppOrganizations.Upsert and GlobalDB().

Suites (whole packages, merged tree, own test DB)

  • Unit tests for store, routing and alerts pass.
  • Integration tests for routing and alerts pass.
  • Integration store (whole package, -timeout 30m): only TestEveryHotTableIsReadByIndex fails, in both suites, on Requests.CountByUser, RenameUser, forgetUserHere, ExportCustomer and Sandboxes.Usage. This is the known planner failure, and none of the failing subtests concerns unowned usage. TestUnownedUsage* pass in StoreSuite and ShardedStoreSuite.

No new findings. Review threads R1.1 to R1.3 are left unresolved for the author to close.

@kanat
kanat marked this pull request as ready for review November 26, 2026 04:08

@kanat kanat left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Approving on the delta reviewer's GO (#2118 (review)).

@kanat
kanat merged commit cc8c7f5 into main Nov 26, 2026
18 of 19 checks passed
@kanat
kanat deleted the fix/ai-3373-unowned-alert-names-app branch November 26, 2026 05:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants