Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .claude/skills/sdk/notes/2026-11-23-ai-3511.md
Original file line number Diff line number Diff line change
@@ -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. 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.
7 changes: 5 additions & 2 deletions acceleration/api/openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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 <app_id>/<user_id>, 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:
Expand Down
20 changes: 20 additions & 0 deletions acceleration/cmd/router/prices_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
16 changes: 12 additions & 4 deletions acceleration/internal/activity/activity.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -282,7 +282,15 @@ 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)
// 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)
r.mu.Lock()
defer r.mu.Unlock()
Expand Down
165 changes: 165 additions & 0 deletions acceleration/internal/activity/activity_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,25 @@
package activity

import (
"bytes"
"context"
"crypto/rand"
"database/sql"
"errors"
"io"
"log/slog"
"math"
"net"
"net/url"
"os"
"strings"
"sync"
"sync/atomic"
"testing"
"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"
Expand Down Expand Up @@ -227,6 +233,165 @@ func (s *ActivitySuite) TestAFailedWriteIsWrittenByTheNextOne() {
settleFor, 10*time.Millisecond, "what the failed write held was not written again")
}

// 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 = '`+refused+`') EXECUTE FUNCTION `+trigger+`()`)
s.Require().NoError(err)
s.T().Cleanup(func() {
_, err := s.db.GlobalDB().ExecContext(s.ctx, "DROP TRIGGER "+trigger+" ON customer_activity; DROP FUNCTION "+trigger+"()")
s.Require().NoError(err)
})

err = s.db.Activities.Add(s.ctx, []store.ActivityDelta{{
OrganizationID: "org", AppID: refused, Area: AreaAgentSetup, Client: store.AuditSourceCLI, Day: day, Requests: 1, FirstAt: day, LastAt: day,
}})

s.Require().ErrorContains(err, "refused at commit")
s.NotErrorIs(err, store.ErrActivityUnsure)
}

// 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
// on 1 March, though it is 2 March everywhere the router stores a day.
func (s *ActivitySuite) TestARequestIsCountedOnItsUTCDay() {
Expand Down
10 changes: 6 additions & 4 deletions acceleration/internal/api/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
})
Expand Down Expand Up @@ -2450,9 +2451,9 @@ func (s *Server) registerServer(api huma.API) {
"app alone; grouped by \"who:user\" the value is then <app_id>/<user_id>, 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
Expand Down Expand Up @@ -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.
Expand Down
21 changes: 21 additions & 0 deletions acceleration/internal/api/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
29 changes: 29 additions & 0 deletions acceleration/internal/phone/metering_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down
Loading
Loading