From af0d796c5d9f588e7f48f4f14e2b0d408ec7c5f7 Mon Sep 17 00:00:00 2001 From: Laurent Schaffner Date: Mon, 23 Nov 2026 19:36:46 +0100 Subject: [PATCH 1/8] fix(store): keep a label valued "other" apart from the spend remainder Spend summed every group outside the biggest few into the value "other", so a cost label whose value is "other" was merged into it. The remainder row now carries other: true; a label of that value is a row of its own. The field is optional, so clients reading an older router still parse. Co-Authored-By: Claude Opus 5.5 --- .../skills/sdk/notes/2026-11-23-ai-3511.md | 1 + acceleration/api/openapi.yaml | 7 +++-- acceleration/internal/api/server.go | 10 ++++--- acceleration/internal/api/server_test.go | 21 ++++++++++++++ acceleration/internal/store/request.go | 11 ++++--- acceleration/internal/store/shard_merge.go | 29 ++++++++++++++----- .../_generated/api/default/get_spend.py | 20 ++++++++----- .../stream/_generated/models/spend_bucket.py | 18 ++++++++++-- sdks/go/acceleration/generated.go | 15 ++++++---- sdks/js/src/generated/api.ts | 6 ++-- 10 files changed, 101 insertions(+), 37 deletions(-) create mode 100644 .claude/skills/sdk/notes/2026-11-23-ai-3511.md diff --git a/.claude/skills/sdk/notes/2026-11-23-ai-3511.md b/.claude/skills/sdk/notes/2026-11-23-ai-3511.md new file mode 100644 index 0000000000..2d572d141c --- /dev/null +++ b/.claude/skills/sdk/notes/2026-11-23-ai-3511.md @@ -0,0 +1 @@ +`GET /v1/stats/spend` rows carry `other` (AI-3511): true on the row that sums every value outside the biggest few, whose `value` is still `"other"`, and left out on every other row. A cost label whose value is `"other"` is now a row of its own, no longer merged into the remainder. Go (`sdks/go/acceleration/generated.go`), Python (`plugins/stream` `_generated`) and JavaScript (`sdks/js/src/generated/api.ts`) are regenerated. Other SDKs that model `SpendBucket` by hand need the optional boolean, and any code that picks the remainder by `value == "other"` should read `other` instead. diff --git a/acceleration/api/openapi.yaml b/acceleration/api/openapi.yaml index d2e73d6681..615ab7085e 100644 --- a/acceleration/api/openapi.yaml +++ b/acceleration/api/openapi.yaml @@ -10147,11 +10147,14 @@ components: description: Millionths of a dollar, priced from the configured rates. format: int64 type: integer + other: + description: 'True on the row that is everything outside the biggest few, summed. Its value is "other", which a label can also have: a label of that value is a row of its own, without other.' + type: boolean request_count: format: int64 type: integer value: - description: The modality or label value this row is for. "other" is everything outside the biggest few, and the empty string is spend carrying no such label at all, so a customer that labels only part of its traffic can see which part. + description: The modality or label value this row is for. "other" with other true is everything outside the biggest few, and the empty string is spend carrying no such label at all, so a customer that labels only part of its traffic can see which part. example: support type: string required: @@ -26922,7 +26925,7 @@ paths: description: |- Spend across every modality at once, which is what a bill is. group_by decides what the series are: "modality" for where the money went, who asked for it ("who:app", "who:origin", "who:user", "who:team" or "who:category"), or a cost label for what it was spent on. "who:origin" groups by the key the work was started with, or the origin of work no key started, such as hook:chat. A label key holds no ':', so a label named app is still grouped by as group_by=app. "who:team" groups by the team the user's token named, work with none under the empty value; "who:category" by the other usage categories, and a request carrying several counts once in each, so those rows add up to more than the total. scope=organization counts every app of the caller's organization rather than the caller's app alone; grouped by "who:user" the value is then /, since a user id is only unique within its app. - Only the biggest values keep a series of their own, because a label such as customer_id has as many values as the customer has customers. The rest are summed into "other", and spend carrying no such label at all into the empty value, so the rows still add up to the total. + Only the biggest values keep a series of their own, because a label such as customer_id has as many values as the customer has customers. The rest are summed into a row marked other, whose value is "other", and spend carrying no such label at all into the empty value, so the rows still add up to the total. Reads the request rows rather than the rollups, so today's spend is there without a rollup having run. operationId: getSpend parameters: diff --git a/acceleration/internal/api/server.go b/acceleration/internal/api/server.go index 592571de59..220009eb80 100644 --- a/acceleration/internal/api/server.go +++ b/acceleration/internal/api/server.go @@ -2029,6 +2029,7 @@ func (s *Server) getSpend(ctx context.Context, request *getSpendRequest) (*getSp spend = append(spend, SpendBucket{ Bucket: bucket.Bucket, Value: bucket.Value, + Other: bucket.Other, CostMicrosTotal: bucket.CostMicrosTotal, RequestCount: bucket.RequestCount, }) @@ -2450,9 +2451,9 @@ func (s *Server) registerServer(api huma.API) { "app alone; grouped by \"who:user\" the value is then /, since a user id is " + "only unique within its app.\n" + "Only the biggest values keep a series of their own, because a label such as customer_id " + - "has as many values as the customer has customers. The rest are summed into \"other\", and " + - "spend carrying no such label at all into the empty value, so the rows still add up to " + - "the total.\n" + + "has as many values as the customer has customers. The rest are summed into a row marked " + + "other, whose value is \"other\", and spend carrying no such label at all into the empty " + + "value, so the rows still add up to the total.\n" + "Reads the request rows rather than the rollups, so today's spend is there without a " + "rollup having run.", // Declared rather than read off the input, so the default is documented without @@ -2823,8 +2824,9 @@ type RollupResult struct { type SpendBucket struct { Bucket time.Time `json:"bucket"` CostMicrosTotal int64 `json:"cost_micros_total" doc:"Millionths of a dollar, priced from the configured rates."` + Other bool `json:"other,omitempty" doc:"True on the row that is everything outside the biggest few, summed. Its value is \"other\", which a label can also have: a label of that value is a row of its own, without other."` RequestCount int64 `json:"request_count"` - Value string `json:"value" doc:"The modality or label value this row is for. \"other\" is everything outside the biggest few, and the empty string is spend carrying no such label at all, so a customer that labels only part of its traffic can see which part." example:"support"` + Value string `json:"value" doc:"The modality or label value this row is for. \"other\" with other true is everything outside the biggest few, and the empty string is spend carrying no such label at all, so a customer that labels only part of its traffic can see which part." example:"support"` } // StatsBucket is the StatsBucket schema. diff --git a/acceleration/internal/api/server_test.go b/acceleration/internal/api/server_test.go index 7f97a32955..2fffd084cd 100644 --- a/acceleration/internal/api/server_test.go +++ b/acceleration/internal/api/server_test.go @@ -509,6 +509,27 @@ func (s *ServerSuite) TestSpendByUserAcrossTheOrganization() { spentBy(s.spend("group_by=who%3Aorigin&granularity=daily&scope=organization"))) } +func (s *ServerSuite) TestALabelValuedOtherIsKeptApartFromTheRest() { + for value, cost := range map[string]int64{"other": 5_000, "a": 3_000, "b": 1_000, "c": 500} { + s.Require().NoError(s.store.Requests.Insert(context.Background(), &store.Request{ + Modality: "llm", CustomerID: s.customerID(), OrganizationID: s.app.organization.ID, APIKey: "key", + Provider: "stub", Model: "stub-llm", StartedAt: s.base.Add(5 * time.Minute), CostMicros: cost, + Billable: true, Success: true, Tags: map[string]string{"project": value}, + })) + } + + type row struct { + value string + other bool + } + spent := map[row]int64{} + for _, bucket := range s.spend("group_by=project&granularity=daily&limit=2") { + spent[row{bucket.Value, bucket.Other}] += bucket.CostMicrosTotal + } + + s.Equal(map[row]int64{{"other", false}: 5_000, {"a", false}: 3_000, {"other", true}: 1_500}, spent) +} + // who:origin groups by the key or origin that started the work (AI-2811). func (s *ServerSuite) TestSpendByOrigin() { organization := s.app.organization.ID diff --git a/acceleration/internal/store/request.go b/acceleration/internal/store/request.go index 20a7142cdc..82cc8891af 100644 --- a/acceleration/internal/store/request.go +++ b/acceleration/internal/store/request.go @@ -187,11 +187,13 @@ func measured(prefix string) string { const requestsPrimaryKey = "stt_requests_pkey" // SpendBucket is what one group cost in one bucket, across every modality. Value is a -// modality or a cost label value; "other" is everything outside the biggest few and the -// empty string is spend that carried no such label, so the rows still add up to the total. +// modality or a cost label value; the row with Other is everything outside the biggest few, +// with Value "other", and the empty string is spend that carried no such label, so the rows +// still add up to the total. A label whose value is "other" is a row of its own, without Other. type SpendBucket struct { Bucket time.Time `bun:"bucket"` Value string `bun:"value"` + Other bool `bun:"-"` CostMicrosTotal int64 `bun:"cost_micros_total"` RequestCount int64 `bun:"request_count"` } @@ -771,7 +773,8 @@ func spendGroups(groupBy string, acrossApps bool) (value, join string, ok bool) return "", "", false } -// spendOther is the value every group outside the biggest few is summed into. +// spendOther is the value of the row every group outside the biggest few is summed into, +// which SpendBucket.Other tells apart from a label of that value. const spendOther = "other" // Spend returns what one customer spent per bucket and group, oldest bucket first. It is the @@ -780,7 +783,7 @@ const spendOther = "other" // groupBy is "modality", who asked (SpendGroupByApp and the rest), or a cost label key. Only // the limit biggest values over the whole window keep a group of their own: a label such as // customer_id has as many values as the customer has customers, and a chart of all of them -// says nothing. The rest are summed into "other", and requests carrying no such label into +// says nothing. The rest are summed into a row marked Other, and requests carrying no such label into // the empty value, so the rows still add up to the total; grouped by category, a row counts // once in each of its categories. // diff --git a/acceleration/internal/store/shard_merge.go b/acceleration/internal/store/shard_merge.go index 77cdeb6744..248726acad 100644 --- a/acceleration/internal/store/shard_merge.go +++ b/acceleration/internal/store/shard_merge.go @@ -142,9 +142,9 @@ type spendRow struct { RequestCount int64 `bun:"request_count"` } -// foldSpend keeps the limit biggest groups over the whole window and sums the rest into -// spendOther, the way Requests.Spend's query does for one shard: rows with no value stay -// their own group. It reads every shard's unfolded rows, so the folding is exact. +// foldSpend keeps the limit biggest groups over the whole window and sums the rest into the +// row marked Other: rows with no value stay their own group. It reads every shard's unfolded +// rows, so the folding is exact. func foldSpend(lists [][]spendRow, limit int) []SpendBucket { type total struct { cost, requests int64 @@ -179,19 +179,20 @@ func foldSpend(lists [][]spendRow, limit int) []SpendBucket { type key struct { bucket time.Time value string + other bool } var order []key sums := map[key]*SpendBucket{} for _, list := range lists { for _, row := range list { - value := row.Value - if value != "" && !kept[value] { + value, other := row.Value, row.Value != "" && !kept[row.Value] + if other { value = spendOther } - k := key{row.Bucket.UTC(), value} + k := key{row.Bucket.UTC(), value, other} sum, seen := sums[k] if !seen { - sum = &SpendBucket{Bucket: row.Bucket, Value: value} + sum = &SpendBucket{Bucket: row.Bucket, Value: value, Other: other} sums[k] = sum order = append(order, k) } @@ -204,7 +205,19 @@ func foldSpend(lists [][]spendRow, limit int) []SpendBucket { out = append(out, *sums[k]) } slices.SortStableFunc(out, func(a, b SpendBucket) int { - return cmp.Or(a.Bucket.Compare(b.Bucket), cmp.Compare(b.CostMicrosTotal, a.CostMicrosTotal), strings.Compare(a.Value, b.Value)) + return cmp.Or(a.Bucket.Compare(b.Bucket), cmp.Compare(b.CostMicrosTotal, a.CostMicrosTotal), strings.Compare(a.Value, b.Value), + compareBool(a.Other, b.Other)) }) return out } + +// compareBool orders false before true. +func compareBool(a, b bool) int { + switch { + case a == b: + return 0 + case a: + return 1 + } + return -1 +} diff --git a/plugins/stream/vision_agents/plugins/stream/_generated/api/default/get_spend.py b/plugins/stream/vision_agents/plugins/stream/_generated/api/default/get_spend.py index bd3db6a05b..30abdfbce4 100644 --- a/plugins/stream/vision_agents/plugins/stream/_generated/api/default/get_spend.py +++ b/plugins/stream/vision_agents/plugins/stream/_generated/api/default/get_spend.py @@ -170,8 +170,9 @@ def sync_detailed( grouped by "who:user" the value is then /, since a user id is only unique within its app. Only the biggest values keep a series of their own, because a label such as customer_id has as many - values as the customer has customers. The rest are summed into "other", and spend carrying no such - label at all into the empty value, so the rows still add up to the total. + values as the customer has customers. The rest are summed into a row marked other, whose value is + "other", and spend carrying no such label at all into the empty value, so the rows still add up to + the total. Reads the request rows rather than the rollups, so today's spend is there without a rollup having run. @@ -251,8 +252,9 @@ def sync( grouped by "who:user" the value is then /, since a user id is only unique within its app. Only the biggest values keep a series of their own, because a label such as customer_id has as many - values as the customer has customers. The rest are summed into "other", and spend carrying no such - label at all into the empty value, so the rows still add up to the total. + values as the customer has customers. The rest are summed into a row marked other, whose value is + "other", and spend carrying no such label at all into the empty value, so the rows still add up to + the total. Reads the request rows rather than the rollups, so today's spend is there without a rollup having run. @@ -327,8 +329,9 @@ async def asyncio_detailed( grouped by "who:user" the value is then /, since a user id is only unique within its app. Only the biggest values keep a series of their own, because a label such as customer_id has as many - values as the customer has customers. The rest are summed into "other", and spend carrying no such - label at all into the empty value, so the rows still add up to the total. + values as the customer has customers. The rest are summed into a row marked other, whose value is + "other", and spend carrying no such label at all into the empty value, so the rows still add up to + the total. Reads the request rows rather than the rollups, so today's spend is there without a rollup having run. @@ -406,8 +409,9 @@ async def asyncio( grouped by "who:user" the value is then /, since a user id is only unique within its app. Only the biggest values keep a series of their own, because a label such as customer_id has as many - values as the customer has customers. The rest are summed into "other", and spend carrying no such - label at all into the empty value, so the rows still add up to the total. + values as the customer has customers. The rest are summed into a row marked other, whose value is + "other", and spend carrying no such label at all into the empty value, so the rows still add up to + the total. Reads the request rows rather than the rollups, so today's spend is there without a rollup having run. diff --git a/plugins/stream/vision_agents/plugins/stream/_generated/models/spend_bucket.py b/plugins/stream/vision_agents/plugins/stream/_generated/models/spend_bucket.py index 3241f96921..cb79a53b0e 100644 --- a/plugins/stream/vision_agents/plugins/stream/_generated/models/spend_bucket.py +++ b/plugins/stream/vision_agents/plugins/stream/_generated/models/spend_bucket.py @@ -8,6 +8,8 @@ from attrs import field as _attrs_field from typing_extensions import Self +from ..types import UNSET, Unset + T = TypeVar("T", bound="SpendBucket") @@ -18,15 +20,18 @@ class SpendBucket: bucket (datetime.datetime): cost_micros_total (int): Millionths of a dollar, priced from the configured rates. request_count (int): - value (str): The modality or label value this row is for. "other" is everything outside the biggest few, and the - empty string is spend carrying no such label at all, so a customer that labels only part of its traffic can see - which part. Example: support. + value (str): The modality or label value this row is for. "other" with other true is everything outside the + biggest few, and the empty string is spend carrying no such label at all, so a customer that labels only part of + its traffic can see which part. Example: support. + other (bool | Unset): True on the row that is everything outside the biggest few, summed. Its value is "other", + which a label can also have: a label of that value is a row of its own, without other. """ bucket: datetime.datetime cost_micros_total: int request_count: int value: str + other: bool | Unset = UNSET additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict) def to_dict(self) -> dict[str, Any]: @@ -38,6 +43,8 @@ def to_dict(self) -> dict[str, Any]: value = self.value + other = self.other + field_dict: dict[str, Any] = {} field_dict.update(self.additional_properties) field_dict.update( @@ -48,6 +55,8 @@ def to_dict(self) -> dict[str, Any]: "value": value, } ) + if other is not UNSET: + field_dict["other"] = other return field_dict @@ -62,11 +71,14 @@ def from_dict(cls, src_dict: Mapping[str, Any]) -> Self: value = d.pop("value") + other = d.pop("other", UNSET) + spend_bucket = cls( bucket=bucket, cost_micros_total=cost_micros_total, request_count=request_count, value=value, + other=other, ) spend_bucket.additional_properties = d diff --git a/sdks/go/acceleration/generated.go b/sdks/go/acceleration/generated.go index 6b37c23d60..8ea2211642 100644 --- a/sdks/go/acceleration/generated.go +++ b/sdks/go/acceleration/generated.go @@ -10054,9 +10054,12 @@ type SpendBucket struct { // CostMicrosTotal Millionths of a dollar, priced from the configured rates. CostMicrosTotal int64 `json:"cost_micros_total"` - RequestCount int64 `json:"request_count"` - // Value The modality or label value this row is for. "other" is everything outside the biggest few, and the empty string is spend carrying no such label at all, so a customer that labels only part of its traffic can see which part. + // Other True on the row that is everything outside the biggest few, summed. Its value is "other", which a label can also have: a label of that value is a row of its own, without other. + Other *bool `json:"other,omitempty"` + RequestCount int64 `json:"request_count"` + + // Value The modality or label value this row is for. "other" with other true is everything outside the biggest few, and the empty string is spend carrying no such label at all, so a customer that labels only part of its traffic can see which part. // // Example: support Value string `json:"value"` @@ -16441,7 +16444,7 @@ type ClientInterface interface { // // Spend across every modality at once, which is what a bill is. group_by decides what the series are: "modality" for where the money went, who asked for it ("who:app", "who:origin", "who:user", "who:team" or "who:category"), or a cost label for what it was spent on. "who:origin" groups by the key the work was started with, or the origin of work no key started, such as hook:chat. A label key holds no ':', so a label named app is still grouped by as group_by=app. "who:team" groups by the team the user's token named, work with none under the empty value; "who:category" by the other usage categories, and a request carrying several counts once in each, so those rows add up to more than the total. // scope=organization counts every app of the caller's organization rather than the caller's app alone; grouped by "who:user" the value is then /, since a user id is only unique within its app. - // Only the biggest values keep a series of their own, because a label such as customer_id has as many values as the customer has customers. The rest are summed into "other", and spend carrying no such label at all into the empty value, so the rows still add up to the total. + // Only the biggest values keep a series of their own, because a label such as customer_id has as many values as the customer has customers. The rest are summed into a row marked other, whose value is "other", and spend carrying no such label at all into the empty value, so the rows still add up to the total. // Reads the request rows rather than the rollups, so today's spend is there without a rollup having run. // // Corresponds with GET /v1/stats/spend (the `GetSpend` operationId). @@ -23159,7 +23162,7 @@ func (c *Client) GetAgentStats(ctx context.Context, params *GetAgentStatsParams, // // Spend across every modality at once, which is what a bill is. group_by decides what the series are: "modality" for where the money went, who asked for it ("who:app", "who:origin", "who:user", "who:team" or "who:category"), or a cost label for what it was spent on. "who:origin" groups by the key the work was started with, or the origin of work no key started, such as hook:chat. A label key holds no ':', so a label named app is still grouped by as group_by=app. "who:team" groups by the team the user's token named, work with none under the empty value; "who:category" by the other usage categories, and a request carrying several counts once in each, so those rows add up to more than the total. // scope=organization counts every app of the caller's organization rather than the caller's app alone; grouped by "who:user" the value is then /, since a user id is only unique within its app. -// Only the biggest values keep a series of their own, because a label such as customer_id has as many values as the customer has customers. The rest are summed into "other", and spend carrying no such label at all into the empty value, so the rows still add up to the total. +// Only the biggest values keep a series of their own, because a label such as customer_id has as many values as the customer has customers. The rest are summed into a row marked other, whose value is "other", and spend carrying no such label at all into the empty value, so the rows still add up to the total. // Reads the request rows rather than the rollups, so today's spend is there without a rollup having run. // // Corresponds with GET /v1/stats/spend (the `GetSpend` operationId). @@ -39785,7 +39788,7 @@ type ClientWithResponsesInterface interface { // // Spend across every modality at once, which is what a bill is. group_by decides what the series are: "modality" for where the money went, who asked for it ("who:app", "who:origin", "who:user", "who:team" or "who:category"), or a cost label for what it was spent on. "who:origin" groups by the key the work was started with, or the origin of work no key started, such as hook:chat. A label key holds no ':', so a label named app is still grouped by as group_by=app. "who:team" groups by the team the user's token named, work with none under the empty value; "who:category" by the other usage categories, and a request carrying several counts once in each, so those rows add up to more than the total. // scope=organization counts every app of the caller's organization rather than the caller's app alone; grouped by "who:user" the value is then /, since a user id is only unique within its app. - // Only the biggest values keep a series of their own, because a label such as customer_id has as many values as the customer has customers. The rest are summed into "other", and spend carrying no such label at all into the empty value, so the rows still add up to the total. + // Only the biggest values keep a series of their own, because a label such as customer_id has as many values as the customer has customers. The rest are summed into a row marked other, whose value is "other", and spend carrying no such label at all into the empty value, so the rows still add up to the total. // Reads the request rows rather than the rollups, so today's spend is there without a rollup having run. // // Returns a wrapper object for the known response body format(s). @@ -72856,7 +72859,7 @@ func (c *ClientWithResponses) GetAgentStatsWithResponse(ctx context.Context, par // // Spend across every modality at once, which is what a bill is. group_by decides what the series are: "modality" for where the money went, who asked for it ("who:app", "who:origin", "who:user", "who:team" or "who:category"), or a cost label for what it was spent on. "who:origin" groups by the key the work was started with, or the origin of work no key started, such as hook:chat. A label key holds no ':', so a label named app is still grouped by as group_by=app. "who:team" groups by the team the user's token named, work with none under the empty value; "who:category" by the other usage categories, and a request carrying several counts once in each, so those rows add up to more than the total. // scope=organization counts every app of the caller's organization rather than the caller's app alone; grouped by "who:user" the value is then /, since a user id is only unique within its app. -// Only the biggest values keep a series of their own, because a label such as customer_id has as many values as the customer has customers. The rest are summed into "other", and spend carrying no such label at all into the empty value, so the rows still add up to the total. +// Only the biggest values keep a series of their own, because a label such as customer_id has as many values as the customer has customers. The rest are summed into a row marked other, whose value is "other", and spend carrying no such label at all into the empty value, so the rows still add up to the total. // Reads the request rows rather than the rollups, so today's spend is there without a rollup having run. // // Returns a wrapper object for the known response body format(s). diff --git a/sdks/js/src/generated/api.ts b/sdks/js/src/generated/api.ts index d0269f2780..5c1cf9fec3 100644 --- a/sdks/js/src/generated/api.ts +++ b/sdks/js/src/generated/api.ts @@ -4373,7 +4373,7 @@ export type paths = { * What the calling customer spent, grouped * @description Spend across every modality at once, which is what a bill is. group_by decides what the series are: "modality" for where the money went, who asked for it ("who:app", "who:origin", "who:user", "who:team" or "who:category"), or a cost label for what it was spent on. "who:origin" groups by the key the work was started with, or the origin of work no key started, such as hook:chat. A label key holds no ':', so a label named app is still grouped by as group_by=app. "who:team" groups by the team the user's token named, work with none under the empty value; "who:category" by the other usage categories, and a request carrying several counts once in each, so those rows add up to more than the total. * scope=organization counts every app of the caller's organization rather than the caller's app alone; grouped by "who:user" the value is then /, since a user id is only unique within its app. - * Only the biggest values keep a series of their own, because a label such as customer_id has as many values as the customer has customers. The rest are summed into "other", and spend carrying no such label at all into the empty value, so the rows still add up to the total. + * Only the biggest values keep a series of their own, because a label such as customer_id has as many values as the customer has customers. The rest are summed into a row marked other, whose value is "other", and spend carrying no such label at all into the empty value, so the rows still add up to the total. * Reads the request rows rather than the rollups, so today's spend is there without a rollup having run. */ readonly get: operations["getSpend"]; @@ -10386,10 +10386,12 @@ export type components = { * @description Millionths of a dollar, priced from the configured rates. */ readonly cost_micros_total: number; + /** @description True on the row that is everything outside the biggest few, summed. Its value is "other", which a label can also have: a label of that value is a row of its own, without other. */ + readonly other?: boolean; /** Format: int64 */ readonly request_count: number; /** - * @description The modality or label value this row is for. "other" is everything outside the biggest few, and the empty string is spend carrying no such label at all, so a customer that labels only part of its traffic can see which part. + * @description The modality or label value this row is for. "other" with other true is everything outside the biggest few, and the empty string is spend carrying no such label at all, so a customer that labels only part of its traffic can see which part. * @example support */ readonly value: string; From 22e5bf9839e3b013b511ecfaa83fae683701703f Mon Sep 17 00:00:00 2001 From: Laurent Schaffner Date: Mon, 23 Nov 2026 19:38:06 +0100 Subject: [PATCH 2/8] fix(store): refuse a price cancel that waited past the change's time Cancel compared the change's effective time with now(), the start of its transaction, which is taken before the wait of up to 5 s for the price list's lock. A change that came into force during that wait could still be cancelled. It now reads clock_timestamp() once the lock is held. Co-Authored-By: Claude Opus 5.5 --- acceleration/internal/store/price_change.go | 6 +++-- .../internal/store/price_entry_test.go | 26 +++++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/acceleration/internal/store/price_change.go b/acceleration/internal/store/price_change.go index cfe75a2a2e..77bff67a03 100644 --- a/acceleration/internal/store/price_change.go +++ b/acceleration/internal/store/price_change.go @@ -705,8 +705,10 @@ func (r *PriceChanges) Cancel(ctx context.Context, name, reason, actorID, actorN if change.CancelledAt != nil { return nil } - now, err := databaseNow(ctx, tx) - if err != nil { + // The clock now, not the transaction's start: the cancel may have waited for the lock + // while the change came into force. + var now time.Time + if err := tx.QueryRowContext(ctx, "SELECT clock_timestamp()").Scan(&now); err != nil { return err } if change.Kind != PriceChangeAPI || !change.EffectiveAt.After(now) { diff --git a/acceleration/internal/store/price_entry_test.go b/acceleration/internal/store/price_entry_test.go index 37a43b96e8..08e1569eee 100644 --- a/acceleration/internal/store/price_entry_test.go +++ b/acceleration/internal/store/price_entry_test.go @@ -228,6 +228,32 @@ func (s *StoreSuite) TestAWriteThatWaitsOutThePriceListsLockIsBusy() { s.ErrorIs(err, ErrPriceListBusy) } +func (s *StoreSuite) TestACancelThatWaitedPastTheChangesTimeIsRefused() { + s.seeded(priced("a", 1)) + soon := time.Now().Add(1500 * time.Millisecond) + write := apiChange("soon", "key-soon", priced("a", 0.5)) + write.EffectiveAt = &soon + change, _, _, err := s.store.PriceChanges.Insert(s.ctx, write, accept) + s.Require().NoError(err) + held, err := s.store.GlobalDB().BeginTx(s.ctx, nil) + s.Require().NoError(err) + defer held.Rollback() //nolint:errcheck // the lock goes with the transaction + _, err = held.ExecContext(s.ctx, "SELECT pg_advisory_xact_lock(hashtextextended('router.prices', 0))") + s.Require().NoError(err) + + cancelled := make(chan error, 1) + go func() { + _, _, _, err := s.store.PriceChanges.Cancel(s.ctx, change.Name, "Late.", "staff:ada", "Ada") + cancelled <- err + }() + // The cancel's transaction starts before the change's time and waits for the lock past it. + time.Sleep(time.Until(soon) + 300*time.Millisecond) + s.Require().Empty(cancelled, "the cancel is still waiting for the lock") + s.Require().NoError(held.Rollback()) + + s.ErrorIs(<-cancelled, ErrPriceChangeInForce) +} + func (s *StoreSuite) TestThePriceSourceAnswersTheListInForceAndTheNextChange() { seed := s.seeded(priced("a", 1)) tomorrow := time.Now().Add(24 * time.Hour).UTC().Truncate(time.Microsecond) From ed71ec4b1a0c90e14c43746bf9687418c3acc9ce Mon Sep 17 00:00:00 2001 From: Laurent Schaffner Date: Mon, 23 Nov 2026 19:40:47 +0100 Subject: [PATCH 3/8] fix(store): leave work on the customer's own key out of prices drift A BYOK row is priced at the BYOK fee with no cost at the vendor's rates, since the vendor bills the customer, so drift read every such row as billed 100% under what the vendor reported. Co-Authored-By: Claude Opus 5.5 --- .../cmd/router/prices_integration_test.go | 20 +++++++++++++++++++ acceleration/internal/store/request.go | 5 +++-- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/acceleration/cmd/router/prices_integration_test.go b/acceleration/cmd/router/prices_integration_test.go index edad921e77..062ea0aa74 100644 --- a/acceleration/cmd/router/prices_integration_test.go +++ b/acceleration/cmd/router/prices_integration_test.go @@ -593,6 +593,26 @@ func (s *PriceSyncSuite) TestDriftNamesARowByItsUsageIDWhereItHasOne() { s.Contains(out.String(), "(usage "+usageID+")") } +func (s *PriceSyncSuite) TestDriftLeavesOutWorkOnTheCustomersOwnKey() { + pgStore := s.started() + s.recordWithVendorCost(pgStore, "grok-4.7", 1_000, 1_000) + // Priced at the BYOK fee, at no cost at the vendor's rates: the vendor bills the customer. + s.Require().NoError(pgStore.Requests.Insert(s.ctx, &store.Request{ + Modality: "llm", CustomerID: "app", Provider: "grok", Model: "grok-4.7", StartedAt: time.Now(), + CostMicros: 200, BaseCostMicros: 0, PriceVersion: "byok", BYOK: true, Billable: true, Success: true, + Attributes: map[string]string{store.VendorCostAttribute: "1000"}, + })) + var out bytes.Buffer + + s.Require().NoError(runPricesDrift(s.ctx, []string{"--json"}, s.settings, &out)) + + var models []driftedModel + s.Require().NoError(json.Unmarshal(out.Bytes(), &models)) + s.Require().Len(models, 1) + s.Equal(1, models[0].Rows, "only the row on the operator's key") + s.Equal("ok", models[0].Status) +} + // recordWithVendorCost records an LLM row the list priced at cost, of work the vendor said // cost vendorCost. func (s *PriceSyncSuite) recordWithVendorCost(router *store.Store, model string, cost, vendorCost int64) { diff --git a/acceleration/internal/store/request.go b/acceleration/internal/store/request.go index 82cc8891af..f13c78bb72 100644 --- a/acceleration/internal/store/request.go +++ b/acceleration/internal/store/request.go @@ -1047,7 +1047,8 @@ func (r *Requests) CountByModel(ctx context.Context, modality string, since time // vendorCosts is every row since a time whose vendor reported what it charged, with the list's // cost at the vendor's rates: base_cost_micros once something writes it, else cost_micros, // which is the same figure for a row priced before either was written. A malformed figure is skipped, -// never cast, so one bad row cannot fail the read. +// never cast, so one bad row cannot fail the read. A row on the customer's own key is left out: +// its vendor bills the customer, so the list puts no cost at the vendor's rates on it. const vendorCosts = ` SELECT id, usage_id, modality, provider, model, started_at, vendor, base FROM ( @@ -1056,7 +1057,7 @@ FROM ( THEN (attributes->>'vendor_cost_micros')::bigint END AS vendor, CASE WHEN price_version = '' THEN cost_micros ELSE base_cost_micros END AS base FROM requests - WHERE started_at >= ? AND attributes->>'vendor_cost_micros' IS NOT NULL + WHERE started_at >= ? AND attributes->>'vendor_cost_micros' IS NOT NULL AND NOT byok ) AS reported WHERE vendor > 0` From a1a1f967794b2d260cd881c2d9eb6b8d73d0dbf9 Mon Sep 17 00:00:00 2001 From: Laurent Schaffner Date: Mon, 23 Nov 2026 19:44:18 +0100 Subject: [PATCH 4/8] fix(store): bill a caller from the arrival whichever event comes first An inbound leg opens started at the call's arrival. A join delivered after it kept that start (Connect), but a join delivered before it was taken as the leg opened and moved the start to the join, so the same call billed a second more or less by delivery order. The kept join now starts only a leg not started yet. Co-Authored-By: Claude Opus 5.5 --- .../phone/metering_integration_test.go | 29 +++++++++++++++++++ acceleration/internal/store/call_leg.go | 13 +++++---- 2 files changed, 36 insertions(+), 6 deletions(-) diff --git a/acceleration/internal/phone/metering_integration_test.go b/acceleration/internal/phone/metering_integration_test.go index df2f027e0d..ce2bdf9154 100644 --- a/acceleration/internal/phone/metering_integration_test.go +++ b/acceleration/internal/phone/metering_integration_test.go @@ -305,6 +305,35 @@ func (s *MeteringSuite) TestACallersJoinBeforeSessionStartedIsTakenByTheInboundL s.Zero(s.kept(callID)) } +// A caller's join made after the call arrived but delivered before it bills the caller from the +// arrival, as the same join delivered after it does. +func (s *MeteringSuite) TestACallerIsBilledFromTheArrivalWhicheverEventIsDeliveredFirst() { + arrival := s.clock.now() + s.clock.advance(2 * time.Second) + joined := func(callID string) { + s.Require().NoError(s.service.Connect(s.ctx, everyApp, defaultCallType, callID, "session-1", "caller-1", "15125550199", + arrival.Add(time.Second))) + } + arrived := func(callID string) { + s.service.OpenLeg(s.ctx, routing.Owner{CustomerID: s.customer, Attribution: routing.Attribution{APIKey: routing.OriginPhoneInbound}}, + store.CallLeg{CallType: defaultCallType, CallID: callID, StreamSessionID: "session-1", Vendor: s.vendor.vendor, + Direction: store.Inbound, LocalNumber: s.e164, Country: "US", DialedAt: arrival}, true) + } + joinFirst, arrivalFirst := "call-"+uuid.NewString(), "call-"+uuid.NewString() + joined(joinFirst) + arrived(joinFirst) + arrived(arrivalFirst) + joined(arrivalFirst) + s.clock.set(arrival.Add(time.Minute)) + + s.left(defaultCallType, joinFirst, "caller-1") + s.left(defaultCallType, arrivalFirst, "caller-1") + + minutes := s.rowsWhen(ModelCallMinutes, 2) + s.Equal(pricing.Quantities{pricing.CallSeconds: 60}, minutes[0].Meters, "from the arrival") + s.Equal(minutes[0].Meters, minutes[1].Meters) +} + // A leave kept between Connect reading the phone's leaves and connecting its leg ends the leg // at it, rather than being forgotten with the leg left open, and billed, until the call ends. func (s *MeteringSuite) TestALeaveRacingItsJoinEndsTheLeg() { diff --git a/acceleration/internal/store/call_leg.go b/acceleration/internal/store/call_leg.go index e7c51862b0..25b3ca3f4e 100644 --- a/acceleration/internal/store/call_leg.go +++ b/acceleration/internal/store/call_leg.go @@ -189,8 +189,8 @@ func (r *CallLegs) Open(ctx context.Context, leg *CallLeg) (bool, error) { // takeParticipant gives a leg that just opened the join of its phone kept from before it // (CallParticipants.Record): by the leg's remote number, then, for an outbound leg, the number it // was placed from, then its participant session, then, for a leg that knows none of them, the -// call's first phone to join. The leg starts when that phone joined, or when the leg opened if -// that is later, and ends when the phone left if its leave was kept too. +// call's first phone to join. A leg not started yet starts when that phone joined, or when the +// leg opened if that is later, and the leg ends when the phone left if its leave was kept too. func (r *CallLegs) takeParticipant(ctx context.Context, leg *CallLeg) error { var matches []func(*bun.SelectQuery) *bun.SelectQuery byNumber := func(number string) func(*bun.SelectQuery) *bun.SelectQuery { @@ -280,13 +280,14 @@ func (r *CallLegs) takeFrom(ctx context.Context, db bun.IDB, leg *CallLeg, match } // joinTaken starts a leg, which legs holds, from the kept join of its phone, no earlier than the -// leg opened, and ends it if the phone's leave was kept too. A leg given another phone -// meanwhile keeps it, and its start (errLegGone), and so does a phone given another leg -// (errPhoneHasLeg). +// leg opened, and ends it if the phone's leave was kept too. A leg opened started, as a call that +// arrived is, keeps its start, as it does when the join is delivered after it (Connect). A leg +// given another phone meanwhile keeps it, and its start (errLegGone), and so does a phone given +// another leg (errPhoneHasLeg). func joinTaken(ctx context.Context, legs bun.IDB, leg CallLeg, taken CallParticipant) (CallLeg, error) { update := legs.NewUpdate().Model((*CallLeg)(nil)). Set("participant_session = ?", taken.ParticipantSession). - Set("started_at = GREATEST(?::timestamptz, dialed_at)", *taken.JoinedAt) + Set("started_at = COALESCE(started_at, GREATEST(?::timestamptz, dialed_at))", *taken.JoinedAt) if taken.LeftAt != nil { update = update.Set("ended_at = GREATEST(?::timestamptz, ?::timestamptz, dialed_at)", *taken.LeftAt, *taken.JoinedAt). Set("end_reason = ?", LegLeft) From 749f97602f8e078c1483672d88e64119ff32cd85 Mon Sep 17 00:00:00 2001 From: Laurent Schaffner Date: Mon, 23 Nov 2026 19:46:06 +0100 Subject: [PATCH 5/8] fix(activity): drop a write whose commit failed rather than count it twice The activity upsert adds each write's counts to the stored ones, and the recorder kept a failed write's deltas for the next. A commit whose answer was lost may have landed, so writing it again counted it twice. A write that failed in its commit is now ErrActivityUnsure, and the recorder drops and logs it: an ambiguous commit undercounts rather than double counts. A write that failed before its commit is still written again. Co-Authored-By: Claude Opus 5.5 --- acceleration/internal/activity/activity.go | 9 +++- .../internal/activity/activity_test.go | 42 +++++++++++++++++++ acceleration/internal/store/activity.go | 15 ++++++- 3 files changed, 63 insertions(+), 3 deletions(-) diff --git a/acceleration/internal/activity/activity.go b/acceleration/internal/activity/activity.go index fa8c17e1e4..6ea22715f3 100644 --- a/acceleration/internal/activity/activity.go +++ b/acceleration/internal/activity/activity.go @@ -282,7 +282,14 @@ func (r *Recorder) write() bool { } ctx, cancel := context.WithTimeout(context.Background(), writeTimeout) defer cancel() - if err := r.db.Activities.Add(ctx, deltas); err != nil { + err := r.db.Activities.Add(ctx, deltas) + if errors.Is(err, store.ErrActivityUnsure) { + // Kept for the next write, rows the database did record would be counted twice: a count + // lost reads better than one doubled. + r.logger.Error("could not tell whether the activity record was written; dropped it", "rows", len(deltas), "error", err) + return false + } + if err != nil { r.logger.Error("could not write the activity record", "rows", len(deltas), "error", err) r.mu.Lock() defer r.mu.Unlock() diff --git a/acceleration/internal/activity/activity_test.go b/acceleration/internal/activity/activity_test.go index 886db89a02..669fc9584b 100644 --- a/acceleration/internal/activity/activity_test.go +++ b/acceleration/internal/activity/activity_test.go @@ -10,6 +10,7 @@ import ( "log/slog" "math" "os" + "strings" "sync" "sync/atomic" "testing" @@ -227,6 +228,47 @@ func (s *ActivitySuite) TestAFailedWriteIsWrittenByTheNextOne() { settleFor, 10*time.Millisecond, "what the failed write held was not written again") } +// Defect: a write whose commit failed written again by the next one, which counts its rows +// twice when the commit did land and only its answer was lost. +func (s *ActivitySuite) TestAWriteThatFailedInItsCommitIsNotWrittenAgain() { + stuck := s.app() + // A deferred constraint that refuses the app's row fails the write in its commit, as a lost + // answer to the commit does, after every statement was accepted. + trigger := "refuse_" + strings.ToLower(rand.Text()) + _, err := s.db.GlobalDB().ExecContext(s.ctx, `CREATE FUNCTION `+trigger+`() RETURNS trigger LANGUAGE plpgsql AS +$$ BEGIN RAISE EXCEPTION 'refused at commit'; END $$`) + s.Require().NoError(err) + _, err = s.db.GlobalDB().ExecContext(s.ctx, `CREATE CONSTRAINT TRIGGER `+trigger+` AFTER INSERT OR UPDATE ON customer_activity +DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN (NEW.app_id = '`+stuck+`') EXECUTE FUNCTION `+trigger+`()`) + s.Require().NoError(err) + dropped := false + drop := func() { + if dropped { + return + } + dropped = true + _, err := s.db.GlobalDB().ExecContext(s.ctx, "DROP TRIGGER "+trigger+" ON customer_activity; DROP FUNCTION "+trigger+"()") + s.Require().NoError(err) + } + s.T().Cleanup(drop) + + err = s.db.Activities.Add(s.ctx, []store.ActivityDelta{{ + OrganizationID: "org", AppID: stuck, Area: AreaAgentSetup, Client: store.AuditSourceCLI, Day: day, Requests: 1, FirstAt: day, LastAt: day, + }}) + s.Require().ErrorIs(err, store.ErrActivityUnsure) + + recorder := s.recorder(time.Hour, 0) + recorder.Record(request(stuck)) + s.Require().False(recorder.write()) + drop() + other := s.app() + recorder.Record(request(other)) + + s.Require().True(recorder.write()) + s.EqualValues(1, s.requests(other)) + s.Zero(s.requests(stuck), "the write that failed in its commit was dropped, not written again") +} + // Defect: a day cut from the request's own zone, not UTC: 23:30 in UTC-8 on 1 March is counted // on 1 March, though it is 2 March everywhere the router stores a day. func (s *ActivitySuite) TestARequestIsCountedOnItsUTCDay() { diff --git a/acceleration/internal/store/activity.go b/acceleration/internal/store/activity.go index 16c19457f1..da480eeb22 100644 --- a/acceleration/internal/store/activity.go +++ b/acceleration/internal/store/activity.go @@ -3,6 +3,7 @@ package store import ( "cmp" "context" + "errors" "fmt" "slices" "time" @@ -91,22 +92,32 @@ func (r *Activities) Add(ctx context.Context, deltas []ActivityDelta) error { cmp.Compare(a.client, b.client), cmp.Compare(a.day, b.day)) }) - // One transaction, so a failed write wrote nothing and the caller can keep the deltas - // for its next try without counting any of them twice. + // One transaction, so a write that failed before its commit wrote nothing and the caller can + // keep the deltas for its next try without counting any of them twice. One that failed in + // its commit may have been written, a reply lost on the way back: that is ErrActivityUnsure. + committing := false err := r.store.global.RunInTx(ctx, nil, func(ctx context.Context, tx bun.Tx) error { for start := 0; start < len(order); start += activityBatch { if err := writeActivity(ctx, tx, folded, order[start:min(start+activityBatch, len(order))]); err != nil { return err } } + committing = true return nil }) + if err != nil && committing { + return stack.Wrap(fmt.Errorf("store: record activity: %w: %w", ErrActivityUnsure, err)) + } if err != nil { return stack.Wrap(fmt.Errorf("store: record activity: %w", err)) } return nil } +// ErrActivityUnsure is a write of activity whose commit failed, which may have been written all +// the same: written again, its counts would be counted twice. +var ErrActivityUnsure = errors.New("store: the activity may have been recorded") + // activityUpsert is one customer_activity row as writeActivity upserts it. type activityUpsert struct { bun.BaseModel `bun:"table:customer_activity,alias:act"` From f76a9c82c94bcdc71244e018e19f32122dbd8284 Mon Sep 17 00:00:00 2001 From: Laurent Schaffner Date: Mon, 23 Nov 2026 20:05:55 +0100 Subject: [PATCH 6/8] chore(sdks): regenerate the .NET, PHP, Ruby and Rust types for spend's other Co-Authored-By: Claude Opus 5.5 --- .../dotnet/src/GetStream.VisionAgents/Generated/Models.cs | 8 +++++++- sdks/php/src/Generated/SpendBucket.php | 8 +++++++- sdks/ruby/lib/getstream/vision_agents/generated/spec.rb | 2 +- sdks/rust/src/types.rs | 5 ++++- 4 files changed, 19 insertions(+), 4 deletions(-) diff --git a/sdks/dotnet/src/GetStream.VisionAgents/Generated/Models.cs b/sdks/dotnet/src/GetStream.VisionAgents/Generated/Models.cs index b1926a216f..8641d9370c 100644 --- a/sdks/dotnet/src/GetStream.VisionAgents/Generated/Models.cs +++ b/sdks/dotnet/src/GetStream.VisionAgents/Generated/Models.cs @@ -14995,11 +14995,17 @@ public partial class SpendBucket [System.Text.Json.Serialization.JsonPropertyName("cost_micros_total")] public long CostMicrosTotal { get; set; } = default!; + /// + /// True on the row that is everything outside the biggest few, summed. Its value is "other", which a label can also have: a label of that value is a row of its own, without other. + /// + [System.Text.Json.Serialization.JsonPropertyName("other")] + public bool? Other { get; set; } = default!; + [System.Text.Json.Serialization.JsonPropertyName("request_count")] public long RequestCount { get; set; } = default!; /// - /// The modality or label value this row is for. "other" is everything outside the biggest few, and the empty string is spend carrying no such label at all, so a customer that labels only part of its traffic can see which part. + /// The modality or label value this row is for. "other" with other true is everything outside the biggest few, and the empty string is spend carrying no such label at all, so a customer that labels only part of its traffic can see which part. /// [System.Text.Json.Serialization.JsonPropertyName("value")] public string Value { get; set; } = default!; diff --git a/sdks/php/src/Generated/SpendBucket.php b/sdks/php/src/Generated/SpendBucket.php index 9b1836a22f..3e175dff03 100644 --- a/sdks/php/src/Generated/SpendBucket.php +++ b/sdks/php/src/Generated/SpendBucket.php @@ -15,8 +15,10 @@ public function __construct( // Millionths of a dollar, priced from the configured rates. public int $costMicrosTotal, public int $requestCount, - // The modality or label value this row is for. "other" is everything outside the biggest few, and the empty s... + // The modality or label value this row is for. "other" with other true is everything outside the biggest few,... public string $value, + // True on the row that is everything outside the biggest few, summed. Its value is "other", which a label can... + public ?bool $other = null, ) { } @@ -30,6 +32,7 @@ public static function fromArray(array $data): self costMicrosTotal: Json::int($data, 'cost_micros_total'), requestCount: Json::int($data, 'request_count'), value: Json::string($data, 'value'), + other: array_key_exists('other', $data) && $data['other'] !== null ? Json::bool($data, 'other') : null, ); } @@ -45,6 +48,9 @@ public function toArray(): array $out['cost_micros_total'] = $this->costMicrosTotal; $out['request_count'] = $this->requestCount; $out['value'] = $this->value; + if ($this->other !== null) { + $out['other'] = $this->other; + } return $out; } } diff --git a/sdks/ruby/lib/getstream/vision_agents/generated/spec.rb b/sdks/ruby/lib/getstream/vision_agents/generated/spec.rb index 9302f6ca02..0be442417c 100644 --- a/sdks/ruby/lib/getstream/vision_agents/generated/spec.rb +++ b/sdks/ruby/lib/getstream/vision_agents/generated/spec.rb @@ -3134,7 +3134,7 @@ module Generated required: %w[text].freeze, open: false }.freeze, "SpendBucket" => { - properties: %w[bucket cost_micros_total request_count value].freeze, + properties: %w[bucket cost_micros_total other request_count value].freeze, required: %w[bucket cost_micros_total request_count value].freeze, open: false }.freeze, "SpendHardLimit" => { diff --git a/sdks/rust/src/types.rs b/sdks/rust/src/types.rs index 84aed57078..bb15d1933b 100644 --- a/sdks/rust/src/types.rs +++ b/sdks/rust/src/types.rs @@ -12797,8 +12797,11 @@ pub struct SpendBucket { pub bucket: ::std::string::String, ///Millionths of a dollar, priced from the configured rates. pub cost_micros_total: i64, + ///True on the row that is everything outside the biggest few, summed. Its value is "other", which a label can also have: a label of that value is a row of its own, without other. + #[serde(skip_serializing_if = "::std::option::Option::is_none")] + pub other: ::std::option::Option, pub request_count: i64, - ///The modality or label value this row is for. "other" is everything outside the biggest few, and the empty string is spend carrying no such label at all, so a customer that labels only part of its traffic can see which part. + ///The modality or label value this row is for. "other" with other true is everything outside the biggest few, and the empty string is spend carrying no such label at all, so a customer that labels only part of its traffic can see which part. pub value: ::std::string::String, } ///`SpendHardLimit` From 9c45d9ae259653587c259bcffe36c0ebd1aaefc0 Mon Sep 17 00:00:00 2001 From: Laurent Schaffner Date: Mon, 23 Nov 2026 20:42:19 +0100 Subject: [PATCH 7/8] fix(activity): retry a write whose commit was never sent database/sql answers a context that ended before the commit with ErrTxDone or the context's error, without sending COMMIT, and pgdriver sends COMMIT on a context of its own. Those, and an error the server answered, are a commit that did not land, so the write is kept and written again. Only another failure, such as a connection cut after COMMIT was sent, is ErrActivityUnsure. A dropped write holds nothing back, so write reports true and a full record is written again at once. Co-Authored-By: Claude Opus 5.5 --- acceleration/internal/activity/activity.go | 9 +- .../internal/activity/activity_test.go | 175 +++++++++++++++--- acceleration/internal/store/activity.go | 26 ++- 3 files changed, 175 insertions(+), 35 deletions(-) diff --git a/acceleration/internal/activity/activity.go b/acceleration/internal/activity/activity.go index 6ea22715f3..1266777789 100644 --- a/acceleration/internal/activity/activity.go +++ b/acceleration/internal/activity/activity.go @@ -260,9 +260,9 @@ func (r *Recorder) run() { } } -// write writes what is held and reports whether it did. What a failed write held is kept for -// the next one, as far as there is room: a database that did not answer this minute may next -// minute. +// write writes what is held and reports whether it holds nothing back for the next write. What +// a failed write held is kept for the next one, as far as there is room: a database that did not +// answer this minute may next minute. A write whose commit may have landed is dropped instead. func (r *Recorder) write() bool { r.mu.Lock() pending, dropped := r.pending, r.dropped @@ -287,7 +287,8 @@ func (r *Recorder) write() bool { // Kept for the next write, rows the database did record would be counted twice: a count // lost reads better than one doubled. r.logger.Error("could not tell whether the activity record was written; dropped it", "rows", len(deltas), "error", err) - return false + // Nothing is held for the next write, so a full record is written again at once. + return true } if err != nil { r.logger.Error("could not write the activity record", "rows", len(deltas), "error", err) diff --git a/acceleration/internal/activity/activity_test.go b/acceleration/internal/activity/activity_test.go index 669fc9584b..b634a4916c 100644 --- a/acceleration/internal/activity/activity_test.go +++ b/acceleration/internal/activity/activity_test.go @@ -3,12 +3,16 @@ package activity import ( + "bytes" "context" "crypto/rand" "database/sql" "errors" + "io" "log/slog" "math" + "net" + "net/url" "os" "strings" "sync" @@ -17,6 +21,7 @@ import ( "time" "github.com/stretchr/testify/suite" + "github.com/uptrace/bun" "github.com/GetStream/Vision-Agents/acceleration/internal/store" _ "github.com/GetStream/Vision-Agents/acceleration/internal/testenv" @@ -228,45 +233,163 @@ func (s *ActivitySuite) TestAFailedWriteIsWrittenByTheNextOne() { settleFor, 10*time.Millisecond, "what the failed write held was not written again") } -// Defect: a write whose commit failed written again by the next one, which counts its rows -// twice when the commit did land and only its answer was lost. -func (s *ActivitySuite) TestAWriteThatFailedInItsCommitIsNotWrittenAgain() { - stuck := s.app() - // A deferred constraint that refuses the app's row fails the write in its commit, as a lost - // answer to the commit does, after every statement was accepted. +// Defect: a write whose commit landed but whose answer was lost written again by the next one, +// which counts its rows twice. +func (s *ActivitySuite) TestAWriteWhoseCommitAnswerWasLostIsNotWrittenAgain() { + cut := newCommitCutter(s.T()) + db, err := store.Open(cut.dsn(os.Getenv("ROUTER_POSTGRES_DSN"))) + s.Require().NoError(err) + s.T().Cleanup(func() { s.Require().NoError(db.Close()) }) + recorder, err := New(Options{Store: db, Interval: time.Hour, Logger: slog.New(slog.DiscardHandler)}) + s.Require().NoError(err) + s.T().Cleanup(recorder.Close) + landed, other := s.app(), s.app() + + cut.arm() + recorder.Record(request(landed)) + s.True(recorder.write(), "a write that may have landed is dropped, and nothing is held back") + s.Require().True(cut.fired(), "the connection was cut after COMMIT was sent") + recorder.Record(request(other)) + s.Require().True(recorder.write()) + + s.EqualValues(1, s.requests(landed), "the commit landed once and was not written again") + s.EqualValues(1, s.requests(other)) +} + +// Defect: a write whose context ended before its commit was sent read as one that may have +// landed and dropped, though nothing of it was written. +func (s *ActivitySuite) TestAWriteWhoseContextEndedBeforeItsCommitIsWrittenAgain() { + db, err := store.Open(os.Getenv("ROUTER_POSTGRES_DSN")) + s.Require().NoError(err) + s.T().Cleanup(func() { s.Require().NoError(db.Close()) }) + ctx, cancel := context.WithCancel(s.ctx) + defer cancel() + // Ends the write's context once its upsert has run, before the commit. + db.GlobalDB().AddQueryHook(cancelAfter{prefix: `INSERT INTO "customer_activity"`, cancel: cancel}) + app := s.app() + delta := store.ActivityDelta{OrganizationID: "org", AppID: app, Area: AreaAgentSetup, Client: store.AuditSourceCLI, + Day: day, Requests: 1, FirstAt: day, LastAt: day} + + err = db.Activities.Add(ctx, []store.ActivityDelta{delta}) + s.Require().Error(err) + s.NotErrorIs(err, store.ErrActivityUnsure) + s.Zero(s.requests(app), "nothing was committed") + + s.Require().NoError(s.db.Activities.Add(s.ctx, []store.ActivityDelta{delta})) + s.EqualValues(1, s.requests(app)) +} + +// Defect: a commit the database refused read as one that may have landed and dropped. +func (s *ActivitySuite) TestACommitTheDatabaseRefusedIsNotUnsure() { + refused := s.app() + // A deferred constraint refusing the app's row fails the write in its commit, with an answer. trigger := "refuse_" + strings.ToLower(rand.Text()) _, err := s.db.GlobalDB().ExecContext(s.ctx, `CREATE FUNCTION `+trigger+`() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'refused at commit'; END $$`) s.Require().NoError(err) _, err = s.db.GlobalDB().ExecContext(s.ctx, `CREATE CONSTRAINT TRIGGER `+trigger+` AFTER INSERT OR UPDATE ON customer_activity -DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN (NEW.app_id = '`+stuck+`') EXECUTE FUNCTION `+trigger+`()`) +DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN (NEW.app_id = '`+refused+`') EXECUTE FUNCTION `+trigger+`()`) s.Require().NoError(err) - dropped := false - drop := func() { - if dropped { - return - } - dropped = true + s.T().Cleanup(func() { _, err := s.db.GlobalDB().ExecContext(s.ctx, "DROP TRIGGER "+trigger+" ON customer_activity; DROP FUNCTION "+trigger+"()") s.Require().NoError(err) - } - s.T().Cleanup(drop) + }) err = s.db.Activities.Add(s.ctx, []store.ActivityDelta{{ - OrganizationID: "org", AppID: stuck, Area: AreaAgentSetup, Client: store.AuditSourceCLI, Day: day, Requests: 1, FirstAt: day, LastAt: day, + OrganizationID: "org", AppID: refused, Area: AreaAgentSetup, Client: store.AuditSourceCLI, Day: day, Requests: 1, FirstAt: day, LastAt: day, }}) - s.Require().ErrorIs(err, store.ErrActivityUnsure) - recorder := s.recorder(time.Hour, 0) - recorder.Record(request(stuck)) - s.Require().False(recorder.write()) - drop() - other := s.app() - recorder.Record(request(other)) + s.Require().ErrorContains(err, "refused at commit") + s.NotErrorIs(err, store.ErrActivityUnsure) +} - s.Require().True(recorder.write()) - s.EqualValues(1, s.requests(other)) - s.Zero(s.requests(stuck), "the write that failed in its commit was dropped, not written again") +// cancelAfter is a query hook that calls cancel once a query starting with prefix has run. +type cancelAfter struct { + prefix string + cancel context.CancelFunc +} + +func (h cancelAfter) BeforeQuery(ctx context.Context, _ *bun.QueryEvent) context.Context { return ctx } + +func (h cancelAfter) AfterQuery(_ context.Context, event *bun.QueryEvent) { + if strings.HasPrefix(event.Query, h.prefix) { + h.cancel() + } +} + +// commitCutter is a TCP proxy to the suite's Postgres that, once armed, passes the next COMMIT +// on and then cuts the client's connection before the answer comes back: a commit that landed +// with its answer lost. +type commitCutter struct { + listener net.Listener + upstream string + armed atomic.Bool + cut atomic.Bool +} + +func newCommitCutter(t *testing.T) *commitCutter { + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + c := &commitCutter{listener: listener} + t.Cleanup(func() { _ = listener.Close() }) // closing ends serve + go c.serve() + return c +} + +// dsn is dsn reached through the proxy, which forwards to dsn's own host. +func (c *commitCutter) dsn(dsn string) string { + parsed, err := url.Parse(dsn) + if err != nil { + panic(err) + } + c.upstream = parsed.Host + parsed.Host = c.listener.Addr().String() + return parsed.String() +} + +func (c *commitCutter) arm() { c.armed.Store(true) } +func (c *commitCutter) fired() bool { return c.cut.Load() } + +func (c *commitCutter) serve() { + for { + client, err := c.listener.Accept() + if err != nil { + return + } + server, err := net.Dial("tcp", c.upstream) + if err != nil { + _ = client.Close() // the client sees the refusal as a closed connection + continue + } + go func() { + defer client.Close() + _, _ = io.Copy(client, server) // ends when either side closes + }() + go func() { + defer server.Close() + buffer := make([]byte, 32*1024) + for { + n, err := client.Read(buffer) + if n > 0 { + if _, werr := server.Write(buffer[:n]); werr != nil { + return + } + if c.armed.Load() && bytes.Contains(buffer[:n], []byte("COMMIT")) && c.armed.CompareAndSwap(true, false) { + c.cut.Store(true) + _ = client.Close() // the answer to COMMIT never reaches the client + // Postgres finishes a COMMIT it has read before it notices the client is gone. + time.Sleep(200 * time.Millisecond) + return + } + } + if err != nil { + return + } + } + }() + } } // Defect: a day cut from the request's own zone, not UTC: 23:30 in UTC-8 on 1 March is counted diff --git a/acceleration/internal/store/activity.go b/acceleration/internal/store/activity.go index da480eeb22..8d46a9a92d 100644 --- a/acceleration/internal/store/activity.go +++ b/acceleration/internal/store/activity.go @@ -3,12 +3,14 @@ package store import ( "cmp" "context" + "database/sql" "errors" "fmt" "slices" "time" "github.com/uptrace/bun" + "github.com/uptrace/bun/driver/pgdriver" "github.com/uptrace/bun/schema" "github.com/GetStream/Vision-Agents/acceleration/internal/stack" @@ -93,8 +95,9 @@ func (r *Activities) Add(ctx context.Context, deltas []ActivityDelta) error { }) // One transaction, so a write that failed before its commit wrote nothing and the caller can - // keep the deltas for its next try without counting any of them twice. One that failed in - // its commit may have been written, a reply lost on the way back: that is ErrActivityUnsure. + // keep the deltas for its next try without counting any of them twice. One whose commit was + // sent and got no answer may have been written, a reply lost on the way back: that is + // ErrActivityUnsure (commitUnsure). committing := false err := r.store.global.RunInTx(ctx, nil, func(ctx context.Context, tx bun.Tx) error { for start := 0; start < len(order); start += activityBatch { @@ -105,7 +108,7 @@ func (r *Activities) Add(ctx context.Context, deltas []ActivityDelta) error { committing = true return nil }) - if err != nil && committing { + if committing && commitUnsure(err) { return stack.Wrap(fmt.Errorf("store: record activity: %w: %w", ErrActivityUnsure, err)) } if err != nil { @@ -114,10 +117,23 @@ func (r *Activities) Add(ctx context.Context, deltas []ActivityDelta) error { return nil } -// ErrActivityUnsure is a write of activity whose commit failed, which may have been written all -// the same: written again, its counts would be counted twice. +// ErrActivityUnsure is a write of activity whose commit was sent and got no answer, which may +// have been written all the same: written again, its counts would be counted twice. var ErrActivityUnsure = errors.New("store: the activity may have been recorded") +// commitUnsure reports whether err, a commit's failure, leaves it unknown whether the commit +// landed. database/sql answers a context that ended before the commit with ErrTxDone or the +// context's error and sends nothing, and pgdriver sends COMMIT on a context of its own, so +// neither comes from a COMMIT on the wire; an error the server answered is a commit it refused. +// Anything else, such as a connection cut after COMMIT was sent, may have landed. +func commitUnsure(err error) bool { + if err == nil || errors.Is(err, sql.ErrTxDone) || errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { + return false + } + var refused pgdriver.Error + return !errors.As(err, &refused) +} + // activityUpsert is one customer_activity row as writeActivity upserts it. type activityUpsert struct { bun.BaseModel `bun:"table:customer_activity,alias:act"` From eab22633c65819345d713879fac577facc4b1e08 Mon Sep 17 00:00:00 2001 From: Laurent Schaffner Date: Mon, 23 Nov 2026 20:42:57 +0100 Subject: [PATCH 8/8] test(store): time the late price cancel off the database's clock The cancel is checked against clock_timestamp(), so the change's time and the wait past it are read off the database's clock too. The SDK note lists every SDK regenerated for spend's other. Co-Authored-By: Claude Opus 5.5 --- .claude/skills/sdk/notes/2026-11-23-ai-3511.md | 2 +- acceleration/internal/store/price_entry_test.go | 9 +++++++-- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/.claude/skills/sdk/notes/2026-11-23-ai-3511.md b/.claude/skills/sdk/notes/2026-11-23-ai-3511.md index 2d572d141c..136a1e18ae 100644 --- a/.claude/skills/sdk/notes/2026-11-23-ai-3511.md +++ b/.claude/skills/sdk/notes/2026-11-23-ai-3511.md @@ -1 +1 @@ -`GET /v1/stats/spend` rows carry `other` (AI-3511): true on the row that sums every value outside the biggest few, whose `value` is still `"other"`, and left out on every other row. A cost label whose value is `"other"` is now a row of its own, no longer merged into the remainder. Go (`sdks/go/acceleration/generated.go`), Python (`plugins/stream` `_generated`) and JavaScript (`sdks/js/src/generated/api.ts`) are regenerated. Other SDKs that model `SpendBucket` by hand need the optional boolean, and any code that picks the remainder by `value == "other"` should read `other` instead. +`GET /v1/stats/spend` rows carry `other` (AI-3511): true on the row that sums every value outside the biggest few, whose `value` is still `"other"`, and left out on every other row. A cost label whose value is `"other"` is now a row of its own, no longer merged into the remainder. The field is optional, so a client reading an older router still parses its rows. Seven SDKs are regenerated in the same change: Go (`sdks/go/acceleration/generated.go`), Python (`plugins/stream` `_generated`), JavaScript (`sdks/js/src/generated/api.ts`), .NET (`sdks/dotnet` `Generated/Models.cs`), PHP (`sdks/php/src/Generated/SpendBucket.php`), Ruby (`sdks/ruby` `generated/spec.rb`) and Rust (`sdks/rust/src/types.rs`). Swift, Kotlin and Dart have no `SpendBucket`, so nothing is owed there. Code that picks the remainder by `value == "other"` should read `other` instead. diff --git a/acceleration/internal/store/price_entry_test.go b/acceleration/internal/store/price_entry_test.go index 08e1569eee..ea2b86cdbb 100644 --- a/acceleration/internal/store/price_entry_test.go +++ b/acceleration/internal/store/price_entry_test.go @@ -230,7 +230,12 @@ func (s *StoreSuite) TestAWriteThatWaitsOutThePriceListsLockIsBusy() { func (s *StoreSuite) TestACancelThatWaitedPastTheChangesTimeIsRefused() { s.seeded(priced("a", 1)) - soon := time.Now().Add(1500 * time.Millisecond) + // The change's time is read off the database's clock, which Cancel checks it against; read + // is the router's clock at that moment, to wait from. + const lead = 1500 * time.Millisecond + var soon time.Time + s.Require().NoError(s.store.GlobalDB().QueryRowContext(s.ctx, "SELECT clock_timestamp() + ?::interval", lead.String()).Scan(&soon)) + read := time.Now() write := apiChange("soon", "key-soon", priced("a", 0.5)) write.EffectiveAt = &soon change, _, _, err := s.store.PriceChanges.Insert(s.ctx, write, accept) @@ -247,7 +252,7 @@ func (s *StoreSuite) TestACancelThatWaitedPastTheChangesTimeIsRefused() { cancelled <- err }() // The cancel's transaction starts before the change's time and waits for the lock past it. - time.Sleep(time.Until(soon) + 300*time.Millisecond) + time.Sleep(time.Until(read.Add(lead + 300*time.Millisecond))) s.Require().Empty(cancelled, "the cancel is still waiting for the lock") s.Require().NoError(held.Rollback())