Repository navigation
AI-3509: keep a statistic window's whole buckets, in UTC days - #2262
Merged
Loschcode merged 2 commits intoNov 23, 2026
Merged
Conversation
Tag and turn statistics read every bucket the window touches, as the rollups do, instead of comparing bucket starts with the window's ends. Every date_trunc names UTC, so a day does not follow the server's zone. 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)
|
…eps its window wholeBuckets added '1 day' in the session's zone, so across a DST change the day it read was an hour short or long; it now adds 24 hours. A daily turn read groups the hours the window touches by UTC day, as the request and spend statistics keep their window, instead of widening to whole days. The time zone test sets the zone as a startup parameter of its own DSNs rather than on the database, and now covers spend, activity and the label rollup as well as the day clocks change. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
getstream-metis
Bot
dismissed
their stale review
November 23, 2026 19:12
Withdrawing approval until b0064f2 is reviewed.
Contributor
Author
|
/jeffery review |
Nothing changed since round 2 on |
Loschcode
deleted the
laurentschaffner/ai-3509-statistic-windows-drop-their-first
branch
November 23, 2026 20:03
Loschcode
added a commit
that referenced
this pull request
Nov 23, 2026
## 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 condition `parent_response_id IS NULL` matched 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 on `a.id`. - Production never writes a response whose parent means "delegated task". `session.go:2155` is the only place a response row is built. - Delegated work that comes back while its turn is open is recorded on that turn's response (`continueTurn`, `session.go:2226`). When it comes back later, it opens a turn of its own. - `TestTurnsBeforeAToolIsUsedAreTheConversationsOwn` modelled 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 regenerated `api/openapi.yaml` and the clients built from it: Go, JS, the Python plugin, PHP, Rust and .NET. - **Calls and voice minutes** (`CustomerActivity`): `call_counts` keeps only `calls` rows with `call_id <> ''`, as `Calls.LastVoiced` does. 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 in `manager.go`). So the response's parent is not on this shard. `answersAfterAnotherShard` tests for such a response. `carriedIn` adds 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. - **`CustomerTurns` and the tool usage sessions**: each shard also returns `array_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. - That holds whatever the window. A session opened on day 1 and carried on on day 2 counts 0 on day 2. - A row left out makes no bucket, so a day that holds only a carried-on row is not listed. - What was said in the carried row still counts as messages. - **`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. - Each shard returns, per tool, every session's first use with its local count of turns before it, the turn's time and id, and the session's hash. It also returns the session id when `answersAfterAnotherShard` holds for that session on that shard. - The earliest first use across shards wins, ordered by time and then by id as bytes (`COLLATE "C"` in SQL, plain string comparison in Go). - When that use is on a shard holding all the session's earlier turns, its local count is the answer. - Only when the session was carried on to that shard does every shard count its unrewound turns before the use (`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 are `NULL`. - **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**: - A carried row cannot be told from the one the session began in when the session's first turn there has no parent: nothing said there yet, or every earlier response rewound before the reopen (`ActiveLeaf` skips rewound ones). Such a session still counts twice in activity. Deciding it needs the session's origin shard, which no row records (AI-3515). - A first turn regenerated in the shard the session was carried to has no parent, which makes that shard look like the origin. - **Tag statistics freshness** (`TagBuckets.Select`): it now reads the `requests` rows directly, as `Buckets.Select` already does for the provider breakdown ("so recent activity is visible before rollups run"). I chose this over a scheduled rollup for three reasons: - It is what the other statistics do. - A scheduled rollup runs on every replica, so it needs a lock or a leader. - It would still lag by its interval. Details of the new read: - `uptime` is computed in the SQL, so a deployment of one shard still gets it. - The window predicate is `Buckets.Select`'s (`started_at >= from AND started_at < to`). - I tried `tags ? key` so `requests_tags_idx` could help. On the seeded explain data the planner still picks `requests_customer_started_idx` and applies `?` as a filter, so the read keeps `tags->>key IS NOT NULL`. `store_explain_test.go` pins `requests_customer_started_idx`. - The rollup tables, `POST /v1/ops/stats/rollup` and the export are unchanged, and no migration is needed. `stats_tags_hourly` and `stats_tags_daily` are now written and never read. Removing them is [AI-3647](https://linear.app/stream/issue/AI-3647/stats-tags-hourly-and-stats-tags-daily-are-written-and-never-read). - `origin/main` is merged in twice, with merge commits (no rebase). The second merge brings in #2262 (AI-3509): - `TagBuckets.Select` keeps this PR's exact `[from, to)` raw-row window, with its `date_trunc` in `'UTC'`. - The tag window test is now `TestATagWindowInsideItsHoursKeepsOnlyTheRequestsInIt`. - `date_trunc(` has no zone-less call left in `internal/store`, #2262's Denver tests pass here, and the generated clients are still in step with the spec. ## Overlap and dependencies - **#2248** (AI-3483) owns `getTagStats`'s `invalidRequest(err.Error())` (`server.go`). A store error in the new raw read reaches a caller through that line until #2248 lands, so this PR leaves it alone. - **#2177** touches `store.go` only in the `Store` struct fields, which are already on `main`. - **AI-3515** covers the wider problem that a carried-on session has a row in each shard. This PR only counts distinct sessions in the statistics. - **#2262** (AI-3509) is on `main` and 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 text `calls` row with no call id adds nothing, and a voice one still counts. - `TestATaggedRequestIsInTheTagStatisticsWithoutARollup` and `TestTagStatisticsAreOnlyTheCallingCustomers`. The existing tag tests no longer run a rollup first. - Sharded: - `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: - **On `main`**: the new tests fail. - **On the previous head's `store.go`** (`f8427248e`): `TestASessionCarriedOnIsCountedOnTheDayItBeganWhateverTheWindow` and `TestADayHoldingOnlyACarriedOnRowIsNotListed` fail. The rewound and tie tests pass there, because the previous round counted every tool-using session exactly. They guard the bounded design. - **Each of these one-line breaks makes at least one named test fail**: - drop `rewound_at IS NULL` from the second round (rewound test); - ignore the id at a tie, in SQL or in Go (tie test); - never flag a carrier (turns-and-tools, rewound and tie tests); - count carried rows in activity (all three activity tests). Locally, against Postgres 16 (`va-test-pg`) and a Redis of its own: - The whole `./internal/store` package passes in CI's `integration (store)` job. On the local Postgres 16, five plan assertions of `TestEveryHotTableIsReadByIndex` that this PR does not touch fail the same way on an untouched `main` checkout. - `TestServerSuite` (`internal/api`, which includes `/v1/llm/stats/tags`) passes. - `go vet` and `gofmt` are clean. 🤖 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>
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-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_truncalso 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 withwholeBuckets, which the rollups already use, and returns every bucket the window touches.TurnBuckets.Selectfilters its hourly rows withwholeBuckets(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 addinterval '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_truncininternal/storenow passes'UTC'as its third argument. The places are:wholeBuckets, both boundsBuckets.SelectRequests.SpendTurnBuckets.SelectCustomerActivitygrep "date_trunc(" internal/store/*.gofinds none without a zone.UTC on the connection (skipped here): setting
timezone = UTCinconnectbelongs to AI-3494 / fix(store): bound every serving statement on the server, and a cached read's wait on Redis #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 fix(store): bound every serving statement on the server, and a cached read's wait on Redis #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 ated5c656b9, no statistics endpoint bounds its range.getStats,getTagStats,getSpend,getTagKeys,getActivityandgetAgentStatsall check onlyto > from. The only limit ininternal/apiis 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.Overlap
TagBuckets.Selectto read the rawrequestsrows with an exact[from, to)window, asBuckets.Selectdoes. AI-3498: count the right rows in statistics #2258 merges first, and this PR is then rebased onto it:TagBuckets.Selectkeeps AI-3498: count the right rows in statistics #2258's exact raw-row window, notwholeBuckets. Only itsdate_truncgains'UTC'.TestATagWindowInsideItsHoursReturnsEveryHourItTouchesis rewritten for that window. It will neither callRollupnor expect the 12:45 row.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). fix(store): bound every serving statement on the server, and a cached read's wait on Redis #2230's session defaults let a DSN parameter win, so the test keeps working once fix(store): bound every serving statement on the server, and a cached read's wait on Redis #2230 lands.Tests
go test -tags integration -p 1 ./internal/store/(StoreSuite and ShardedStoreSuite):TestATurnWindowInsideItsHoursReturnsEveryHourItTouchesandTestATagWindowInsideItsHoursReturnsEveryHourItTouches: a window from 10:30 to 12:30 with rows at 10:45 and 12:45.TestADailyTurnWindowStartingMidDayCountsOnlyTheHoursInIt.TestADayIsAUTCDayWhateverTheDatabasesTimeZone: a router whose connections are inAmerica/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.SelectRequests.SpendTurnBuckets.SelectCustomerActivity(sessions, messages, calls, people)Rollupstats_tags_dailyreadTestADailyRollupOnTheDayTheClocksChangeKeepsTheWholeUTCDay: 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:mainand pass here. The exception isTestADailyTurnWindowStartingMidDayCountsOnlyTheHoursInIt, which pins behaviourmainalready has and which this PR's first commit had broken../internal/storepackage passes in CI'sintegration (store)job. On the local Postgres 16, five plan assertions inTestEveryHotTableIsReadByIndexthat this PR does not touch fail the same way on an untouchedmaincheckout.go vetandgofmtare clean.integration (api)fails inTestChannelsSuitethe same way onmain(ce41c39).🤖 Generated with Claude Code