Repository navigation
AI-3498: count the right rows in statistics - #2258
Merged
Loschcode merged 7 commits intoNov 23, 2026
Merged
Conversation
…t a rollup Turns per session and turns before a tool's first use count every response that was not rewound, since every response but a session's first has a parent. Calls and voice minutes skip the calls rows a text session writes. A session carried on in another shard is counted once in turns, tool usage and the concurrency peak. Tag statistics read the request rows, as the provider breakdown does, so they no longer wait for a manual rollup. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Contributor
Author
|
/jeffery review |
|
Thanks for asking Jeffery for review. I'll stay on this PR until I can approve it. How it works
Commands (each as a whole comment)
|
…wrong-rows Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Turns before a tool's first use are counted across every shard, so a session carried on in another shard no longer restarts its turns at 0. Activity counts a carried session once, in its earliest bucket. Session sets cross shards as bigint hashes rather than text ids, and only when there are peers. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
getstream-metis
Bot
dismissed
their stale review
November 23, 2026 19:26
Withdrawing approval until e33be9f is reviewed.
Contributor
Author
|
/jeffery review |
Nothing changed since round 2 on |
Loschcode
added a commit
that referenced
this pull request
Nov 23, 2026
## Why https://linear.app/stream/issue/AI-3509/statistic-windows-drop-their-first-bucket-and-days-follow-the Tag and turn statistics compared bucket start times with the window's ends. A window from 10:30 to 12:30 dropped the 10:00 bucket and returned the 12:00 bucket whole. Every `date_trunc` also ran without a zone, so a day was the database session's day. That is right only while the session's zone is UTC. ## What changed - **Whole buckets**: - `TagBuckets.Select` (rollup tables) filters with `wholeBuckets`, which the rollups already use, and returns every bucket the window touches. - `TurnBuckets.Select` filters its hourly rows with `wholeBuckets(Hourly, ...)` at either granularity. A daily turn read is the hours the window touches, grouped by UTC day. That matches how the request and spend statistics keep their window, and the API's "from inclusive, to exclusive". A daily window starting at midday does not count that day's morning. - **Fixed-length buckets in `wholeBuckets`**: its upper bound used to add `interval '1 day'`. That is a calendar day in the session's zone, an hour short or long across a DST change (in Denver, the day ending 2026-03-09 00:00Z ended at 03-08 23:00Z). It now adds `'24 hours'` or `'1 hour'`. - **UTC days, in SQL**: every `date_trunc` in `internal/store` now passes `'UTC'` as its third argument. The places are: - `wholeBuckets`, both bounds - the provider and tag rollups - `Buckets.Select` - `Requests.Spend` - `TurnBuckets.Select` - every bucket in `CustomerActivity` `grep "date_trunc(" internal/store/*.go` finds none without a zone. - **UTC on the connection (skipped here)**: setting `timezone = UTC` in `connect` belongs to AI-3494 / #2230, which changes the same line. With this PR's fixed-length intervals and named zones, the statistics no longer depend on the session's zone, even before #2230 lands. - **Bound on the turn statistics range (skipped: does not reproduce)**: the ticket says to bound it "as the other statistics are". On `main`, and at `ed5c656b9`, no statistics endpoint bounds its range. `getStats`, `getTagStats`, `getSpend`, `getTagKeys`, `getActivity` and `getAgentStats` all check only `to > from`. The only limit in `internal/api` is the organization activity's 90 days. Turn statistics are unpaginated and load every hourly bin in range, so a multi-year hourly read is unbounded. That is filed as [AI-3645](https://linear.app/stream/issue/AI-3645/turn-statistics-accept-any-date-range-and-load-every-hourly-bin-in-it). ## Overlap - **#2258 (AI-3498)** rewrites `TagBuckets.Select` to read the raw `requests` rows with an exact `[from, to)` window, as `Buckets.Select` does. #2258 merges first, and this PR is then rebased onto it: - `TagBuckets.Select` keeps #2258's exact raw-row window, not `wholeBuckets`. Only its `date_trunc` gains `'UTC'`. - `TestATagWindowInsideItsHoursReturnsEveryHourItTouches` is rewritten for that window. It will neither call `Rollup` nor expect the 12:45 row. - **#2230 (AI-3494)** owns `connect`. This PR does not touch it. The time zone test sets its zone as a startup parameter of its own DSNs (`?timezone=America/Denver`, which pgdriver passes on). #2230's session defaults let a DSN parameter win, so the test keeps working once #2230 lands. ## Tests `go test -tags integration -p 1 ./internal/store/` (StoreSuite and ShardedStoreSuite): - **`TestATurnWindowInsideItsHoursReturnsEveryHourItTouches` and `TestATagWindowInsideItsHoursReturnsEveryHourItTouches`**: a window from 10:30 to 12:30 with rows at 10:45 and 12:45. - **`TestADailyTurnWindowStartingMidDayCountsOnlyTheHoursInIt`.** - **`TestADayIsAUTCDayWhateverTheDatabasesTimeZone`**: a router whose connections are in `America/Denver`, with rows at 03:00 UTC (the evening before, in Denver) and 10:00 UTC. Each of these gives one bucket at 00:00 UTC: - `Buckets.Select` - `Requests.Spend` - `TurnBuckets.Select` - `CustomerActivity` (sessions, messages, calls, people) - a daily `Rollup` - a `stats_tags_daily` read - **`TestADailyRollupOnTheDayTheClocksChangeKeepsTheWholeUTCDay`**: Denver, 2026-03-08, with a row at 23:30Z that is kept and a row the midday before that is not touched. I checked the tests by mutation. Taking `'UTC'` out of any one site, or putting back `+ interval '1 day'` or the per-granularity turn filter, fails at least one of these tests. That covers all 14 mutations. Locally, against Postgres 16 (`va-test-pg`, postgres:16-alpine) and a Redis of its own: - The new tests fail on `main` and pass here. The exception is `TestADailyTurnWindowStartingMidDayCountsOnlyTheHoursInIt`, which pins behaviour `main` already has and which this PR's first commit had broken. - The whole `./internal/store` package passes in CI's `integration (store)` job. On the local Postgres 16, five plan assertions in `TestEveryHotTableIsReadByIndex` that this PR does not touch fail the same way on an untouched `main` checkout. - `go vet` and `gofmt` are clean. - CI's `integration (api)` fails in `TestChannelsSuite` the same way on `main` (ce41c39). 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Laurent Schaffner <laurentschaffner@Laurents-MacBook-Pro-Stream.local> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
…wrong-rows TagBuckets.Select keeps the exact raw-row window, with its date_trunc in UTC. The tag window test now checks the window's own requests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
getstream-metis
Bot
dismissed
their stale review
November 23, 2026 20:08
Withdrawing approval until f842724 is reviewed.
A shard tells it carries a session on from a response whose parent is not on it, since a reopened session answers after the newest response on any shard. Activity leaves those rows out, so a session counts by the row it began in whatever the window, and a day holding only such a row is not listed. A tool's first use is numbered locally and asked of every shard only when the session was carried on to the shard that saw it, with turns ordered by time and then id as bytes on both sides. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Contributor
Author
|
/jeffery review |
Nothing changed since round 3 on |
Loschcode
deleted the
laurentschaffner/ai-3498-statistics-count-the-wrong-rows
branch
November 23, 2026 20:44
martinmitrevski
added a commit
that referenced
this pull request
Nov 23, 2026
#2258 added shard tests that call Sessions.Close without the time the closing router opened the session, and a second carriedOn helper. Both merged cleanly as text but did not compile: pass each row's open time and name #2258's helper carriedOnAt. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
martinmitrevski
added a commit
that referenced
this pull request
Nov 23, 2026
#2258 added shard tests that call Sessions.Close without the time the closing router opened the session, and a second carriedOn helper. Both merged cleanly as text but did not compile: pass each row's open time and name #2258's helper carriedOnAt. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Why
https://linear.app/stream/issue/AI-3498/statistics-count-the-wrong-rows-turns-per-session-is-always-about-1
Some statistics count the wrong rows. Average turns per session reads about 1. A text chat counts as a call, and its open time counts as voice minutes. A session continued on another shard counts twice. Tag statistics only change when somebody calls the rollup endpoint by hand.
What changed
Turns per session (
CustomerTurns): a turn is now every response that was not rewound. The old conditionparent_response_id IS NULLmatched only a session's first response, because every response's parent is the one before it (internal/session/session.go:2155,ParentResponseID: s.leaf).Turns before a tool's first use (
CustomerToolUsage): it numbers every response that was not rewound and joins ona.id.session.go:2155is the only place a response row is built.continueTurn,session.go:2226). When it comes back later, it opens a turn of its own.TestTurnsBeforeAToolIsUsedAreTheConversationsOwnmodelled the old reading, so it now chains parents the way production does. The doc comments say what a turn is.API doc for
avg_turns: it said a turn excludes "a delegated task's". It now says what is counted. I regeneratedapi/openapi.yamland the clients built from it: Go, JS, the Python plugin, PHP, Rust and .NET.Calls and voice minutes (
CustomerActivity):call_countskeeps onlycallsrows withcall_id <> '', asCalls.LastVoiceddoes. A text session's stretches add nothing.Sessions continued on another shard are counted once. Each statistic handles it differently:
How a shard tells it carries a session on: when a session reopens on another shard, its first response there answers after the newest response on any shard (
Responses.ActiveLeaf, read from every shard inmanager.go). So the response's parent is not on this shard.answersAfterAnotherShardtests for such a response.carriedInadds that none of the session's responses here is a first turn (a response with no parent). Both are per-shard SQL conditions, so nothing about the session crosses shards to decide this.CustomerTurnsand the tool usage sessions: each shard also returnsarray_agg(DISTINCT hashtextextended(session_id, 0))(a bigint per session), and the hashes are unioned in Go.CustomerActivity: each shard leaves out of its session count, and out of the people it saw open a session, the rows that only carry a session on (carriedIn). A session counts in the bucket of the row it began in.CustomerConcurrencyPeak, sharded path: the spans carry the session id. Spans of one session that overlap are joined before their edges are walked. They are joined as a union of intervals, not min/max, so a gap between the two rows stays a gap.Turns before a tool's first use: a carried session's turns on another shard used to restart at 0.
answersAfterAnotherShardholds for that session on that shard.COLLATE "C"in SQL, plain string comparison in Go).turnsBeforeFirstUse). That is the only second round, and it carries only those sessions.With turns 1 and 2 on shard A and the first use on turn 3 on shard B, the answer is 2. It used to be 0. A turn in another shard counts whatever the window's agent config, since it is the same session's.
Cost with one shard: none of this runs. The SQL
COUNT(DISTINCT)and averages stay, and the per-session columns areNULL.Cost with peers: no extra query for activity, one query for tool usage (counts unchanged), and a second round only when a carried session used a tool.
Known limits:
ActiveLeafskips rewound ones). Such a session still counts twice in activity. Deciding it needs the session's origin shard, which no row records (AI-3515).Tag statistics freshness (
TagBuckets.Select): it now reads therequestsrows directly, asBuckets.Selectalready does for the provider breakdown ("so recent activity is visible before rollups run"). I chose this over a scheduled rollup for three reasons:Details of the new read:
uptimeis computed in the SQL, so a deployment of one shard still gets it.Buckets.Select's (started_at >= from AND started_at < to).tags ? keysorequests_tags_idxcould help. On the seeded explain data the planner still picksrequests_customer_started_idxand applies?as a filter, so the read keepstags->>key IS NOT NULL.store_explain_test.gopinsrequests_customer_started_idx.POST /v1/ops/stats/rollupand the export are unchanged, and no migration is needed.stats_tags_hourlyandstats_tags_dailyare now written and never read. Removing them is AI-3647.origin/mainis merged in twice, with merge commits (no rebase). The second merge brings in AI-3509: keep a statistic window's whole buckets, in UTC days #2262 (AI-3509):TagBuckets.Selectkeeps this PR's exact[from, to)raw-row window, with itsdate_truncin'UTC'.TestATagWindowInsideItsHoursKeepsOnlyTheRequestsInIt.date_trunc(has no zone-less call left ininternal/store, AI-3509: keep a statistic window's whole buckets, in UTC days #2262's Denver tests pass here, and the generated clients are still in step with the spec.Overlap and dependencies
getTagStats'sinvalidRequest(err.Error())(server.go). A store error in the new raw read reaches a caller through that line until AI-3483: errors sent to callers name no internals #2248 lands, so this PR leaves it alone.store.goonly in theStorestruct fields, which are already onmain.mainand merged in here.Tests
go test -tags integration -p 1 ./internal/store/(StoreSuite and ShardedStoreSuite):TestASessionOfFiveTurnsIsFiveTurnsPerSession: five chained turns give{Sessions: 1, Turns: 5}.TestAToolUsedOnTheFourthTurnHadThreeTurnsBeforeIt.TestTurnsBeforeAToolIsUsedAreTheConversationsOwn, rewritten with production-shaped parents.TestATextSessionAddsNothingToCallsOrVoiceMinutes: a textcallsrow with no call id adds nothing, and a voice one still counts.TestATaggedRequestIsInTheTagStatisticsWithoutARollupandTestTagStatisticsAreOnlyTheCallingCustomers. The existing tag tests no longer run a rollup first.TestASessionOpenInTwoShardsAtOnceIsOneInThePeak.TestASessionAwayFromOneShardWhileAnotherRanIsNotOpenThroughTheGap: A at 0–10m, B at 20–30m and another session at 12–18m give a peak of 1. It passes with or without the span merge (no two spans overlap), so it only guards against a min/max merge coming back.TestASessionCarriedOnInAnotherShardIsOneSessionOfItsTurnsAndTools: one session, three turns.lookup_order, first used on turn 2, gives 1.refund, first used on turn 3 on the other shard, gives 2.TestATurnRewoundInTheOtherShardIsNotCountedBeforeAToolsFirstUse: 2, not 3.TestTurnsAtTheSameInstantInTwoShardsAreOrderedById: four turns at one instant across two shards give 3.TestASessionCarriedOnInAnotherShardIsOneSessionOfItsActivity.TestASessionCarriedOnIsCountedOnTheDayItBeganWhateverTheWindow: day 2 counts 0 and day 1 counts 1.TestADayHoldingOnlyACarriedOnRowIsNotListed.Which tests catch what:
main: the new tests fail.store.go(f8427248e):TestASessionCarriedOnIsCountedOnTheDayItBeganWhateverTheWindowandTestADayHoldingOnlyACarriedOnRowIsNotListedfail. The rewound and tie tests pass there, because the previous round counted every tool-using session exactly. They guard the bounded design.rewound_at IS NULLfrom the second round (rewound test);Locally, against Postgres 16 (
va-test-pg) and a Redis of its own:./internal/storepackage passes in CI'sintegration (store)job. On the local Postgres 16, five plan assertions ofTestEveryHotTableIsReadByIndexthat this PR does not touch fail the same way on an untouchedmaincheckout.TestServerSuite(internal/api, which includes/v1/llm/stats/tags) passes.go vetandgofmtare clean.🤖 Generated with Claude Code