Skip to content

AI-3509: keep a statistic window's whole buckets, in UTC days - #2262

Merged
Loschcode merged 2 commits into
mainfrom
laurentschaffner/ai-3509-statistic-windows-drop-their-first
Nov 23, 2026
Merged

Loschcode merged 2 commits into
mainfrom
laurentschaffner/ai-3509-statistic-windows-drop-their-first

Conversation

@Loschcode

@Loschcode Loschcode commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

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

Overlap

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

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

Copy link
Copy Markdown
Contributor Author

/jeffery review

@getstream-metis

Copy link
Copy Markdown

Thanks for asking Jeffery for review. I'll stay on this PR until I can approve it.

How it works

  • Findings come as inline comments, each starting with [Must Fix], [Should Fix], nit: or consider:.
  • Push fixes whenever you're ready. Once the branch has been quiet for 10 minutes I review the new head and resolve the threads it fixes. To skip the wait, comment /jeffery review.
  • If you disagree or have a question, reply in the thread. I'll answer there, and resolve it if you're right.
  • I approve once every must-fix and should-fix is closed and nobody has requested changes. CI isn't part of that; branch protection still holds the merge until it's green. From round 3 on, open should-fix findings stop blocking.
  • I don't approve release/* branches or changes to protected paths, and I'll say so when that applies.
  • If a must-fix is still open after round 8, I stop and hand the PR to a human. Draft PRs wait until they're marked ready.

Commands (each as a whole comment)

Command What it does
/jeffery review Review the current head now
/jeffery rereview Start over at round 1 on the current head and withdraw my approval. This redoes the whole review and costs as much as the first one, so use it only when you don't trust the earlier rounds. If nothing changed since my last round I say so instead; add force to redo it anyway
/jeffery pause / /jeffery resume Stop or restart automatic reviews on this PR
/jeffery status What I last reviewed, and why I have or haven't approved
/jeffery help This list

/review-agent or a mention of me works in place of /jeffery.

getstream-metis[bot]
getstream-metis Bot previously approved these changes Nov 23, 2026

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

✅ Approved f81ebe3c6a8a after 1 round

…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
getstream-metis Bot dismissed their stale review November 23, 2026 19:12

Withdrawing approval until b0064f2 is reviewed.

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

✅ Approved b0064f272624 after 2 rounds

@Loschcode

Copy link
Copy Markdown
Contributor Author

/jeffery review

@getstream-metis

Copy link
Copy Markdown

/jeffery review

Nothing changed since round 2 on b0064f272624; comment /jeffery rereview force to redo the full review anyway.

@Loschcode
Loschcode merged commit 49e60f1 into main Nov 23, 2026
14 checks passed
@Loschcode
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>
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.

1 participant