Skip to content

The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu

53.0 KB
Raw Blame
package tokens

import (
	"testing"
	"time"

	"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"
)

func usageEventFixture(ts, harness, session, model string, mutate func(*schema.Event)) schema.Event {
	event := schema.Event{
		Timestamp: ts,
		Event:     schema.EventInfo{Kind: "agent_runtime", Action: "token.usage", Category: "metric"},
		Harness:   schema.HarnessInfo{Name: harness},
		Model:     model,
		GenAI:     &schema.GenAIInfo{Usage: &schema.GenAIUsageInfo{}},
	}
	if session != "" {
		event.Session = &schema.SessionInfo{ID: session}
	}
	if mutate != nil {
		mutate(&event)
	}
	return event
}

func int64Ptr(v int64) *int64       { return &v }
func float64Ptr(v float64) *float64 { return &v }

func TestAggregateSumsDeltaUsageAcrossGroups(t *testing.T) {
	events := []schema.Event{
		usageEventFixture("2026-06-11T10:00:00Z", "claude_code", "s1", "claude-sonnet-4-5", func(e *schema.Event) {
			e.GenAI.Usage.InputTokens = int64Ptr(100)
			e.Repository = "github.com/acme/app"
		}),
		usageEventFixture("2026-06-11T10:00:00Z", "claude_code", "s1", "claude-sonnet-4-5", func(e *schema.Event) {
			e.GenAI.Usage.OutputTokens = int64Ptr(40)
		}),
		usageEventFixture("2026-06-11T11:00:00Z", "asymptote_observe", "s2", "gpt-4o-mini", func(e *schema.Event) {
			e.GenAI.Usage.InputTokens = int64Ptr(60)
			e.GenAI.Usage.OutputTokens = int64Ptr(20)
			e.GenAI.Usage.Reasoning = &schema.GenAIUsageReasoningInfo{OutputTokens: int64Ptr(5)}
		}),
		usageEventFixture("2026-06-11T11:30:00Z", "claude_code", "s1", "claude-sonnet-4-5", func(e *schema.Event) {
			e.Event.Action = "cost.usage"
			e.GenAI.Usage.CostUSD = float64Ptr(0.25)
		}),
		// Event without usage is counted in TotalEvents only.
		{Timestamp: "2026-06-11T11:45:00Z", Event: schema.EventInfo{Action: "tool.invoked"}, Harness: schema.HarnessInfo{Name: "claude_code"}},
	}

	report := Aggregate(events, Options{BucketSize: time.Hour})
	if report.TotalEvents != 5 || report.EventsWithUsage != 4 {
		t.Fatalf("event counts = %d/%d, want 4/5", report.EventsWithUsage, report.TotalEvents)
	}
	if report.Totals.InputTokens != 160 || report.Totals.OutputTokens != 60 || report.Totals.ReasoningOutputTokens != 5 || report.Totals.CostUSD != 0.25 {
		t.Fatalf("totals = %#v", report.Totals)
	}
	if len(report.ByModel) != 2 || report.ByModel[0].Key != "claude-sonnet-4-5" || report.ByModel[0].Usage.InputTokens != 100 || report.ByModel[0].Usage.CostUSD != 0.25 {
		t.Fatalf("by_model = %#v", report.ByModel)
	}
	if len(report.BySession) != 2 || report.BySession[0].Key != "s1" {
		t.Fatalf("by_session = %#v", report.BySession)
	}
	if len(report.ByHarness) != 2 || report.ByHarness[0].Key != "claude_code" {
		t.Fatalf("by_harness = %#v", report.ByHarness)
	}
	if len(report.ByRepository) != 1 || report.ByRepository[0].Key != "github.com/acme/app" || report.ByRepository[0].Usage.InputTokens != 100 {
		t.Fatalf("by_repository = %#v", report.ByRepository)
	}
	if len(report.Series) != 2 || report.Series[0].Start != "2026-06-11T10:00:00Z" || report.Series[0].Usage.InputTokens != 100 || report.Series[1].Usage.CostUSD != 0.25 {
		t.Fatalf("series = %#v", report.Series)
	}
}

func TestAggregateAttributesUsageToSessionUserContext(t *testing.T) {
	contextEvent := func(host, user, uid string) schema.Event {
		return schema.Event{
			Timestamp: "2026-06-11T09:59:00Z",
			Event:     schema.EventInfo{Kind: "agent_runtime", Action: "session.context", Category: "session"},
			Endpoint:  schema.EndpointInfo{Hostname: host, OS: "darwin"},
			User:      schema.UserInfo{Name: user, UID: uid},
			Harness:   schema.HarnessInfo{Name: "codex_cli"},
			Session:   &schema.SessionInfo{ID: "shared-session"},
		}
	}
	usageEvent := func(host string, input int64) schema.Event {
		return usageEventFixture("2026-06-11T10:00:00Z", "codex_cli", "shared-session", "gpt-5.6-sol", func(e *schema.Event) {
			e.Endpoint = schema.EndpointInfo{Hostname: host, OS: "darwin"}
			e.User = schema.UserInfo{Name: "root", UID: "0"}
			e.GenAI.Usage.InputTokens = int64Ptr(input)
		})
	}

	report := Aggregate([]schema.Event{
		contextEvent("host-a", "alice", "501"),
		usageEvent("host-a", 10),
		contextEvent("host-b", "bob", "502"),
		usageEvent("host-b", 20),
	}, Options{})

	if len(report.ByUser) != 2 {
		t.Fatalf("by_user = %#v, want two endpoint-scoped users", report.ByUser)
	}
	users := map[string]Usage{}
	for _, group := range report.ByUser {
		users[group.Key] = group.Usage
	}
	if users["alice [501]"].InputTokens != 10 || users["bob [502]"].InputTokens != 20 {
		t.Fatalf("by_user = %#v, want session context to override collector identity", users)
	}
}

func TestAggregateAttributesAuxiliaryCodexSessionToUniqueEndpointUser(t *testing.T) {
	contextEvent := schema.Event{
		Timestamp: "2026-06-11T09:59:00Z",
		Event:     schema.EventInfo{Kind: "agent_runtime", Action: "session.context", Category: "session"},
		Endpoint:  schema.EndpointInfo{Hostname: "host-a", OS: "darwin"},
		User:      schema.UserInfo{Name: "shukan", UID: "501"},
		Harness:   schema.HarnessInfo{Name: "codex_cli"},
		Session:   &schema.SessionInfo{ID: "main-session"},
	}
	auxiliaryStarted := schema.Event{
		Timestamp: "2026-06-11T10:00:00Z",
		Event:     schema.EventInfo{Kind: "agent_runtime", Action: "session.started", Category: "session"},
		Endpoint:  schema.EndpointInfo{Hostname: "host-a", OS: "darwin"},
		User:      schema.UserInfo{Name: "shukan"},
		Harness:   schema.HarnessInfo{Name: "codex_cli"},
		Session:   &schema.SessionInfo{ID: "title-session"},
	}
	mainUsage := usageEventFixture("2026-06-11T10:00:05Z", "codex_cli", "main-session", "gpt-5.6-sol", func(e *schema.Event) {
		e.Endpoint = schema.EndpointInfo{Hostname: "host-a", OS: "darwin"}
		e.User = schema.UserInfo{Name: "shukan"}
		e.GenAI.Usage.InputTokens = int64Ptr(10)
	})
	auxiliaryUsage := usageEventFixture("2026-06-11T10:00:06Z", "codex_cli", "title-session", "gpt-5.6-sol", func(e *schema.Event) {
		e.Endpoint = schema.EndpointInfo{Hostname: "host-a", OS: "darwin"}
		e.User = schema.UserInfo{Name: "shukan"}
		e.GenAI.Usage.InputTokens = int64Ptr(20)
	})

	report := Aggregate([]schema.Event{contextEvent, auxiliaryStarted, mainUsage, auxiliaryUsage}, Options{})
	if len(report.ByUser) != 1 || report.ByUser[0].Key != "shukan [501]" || report.ByUser[0].Usage.InputTokens != 30 {
		t.Fatalf("by_user = %#v, want both Codex sessions attributed to the unique endpoint user", report.ByUser)
	}
	scoped := AggregateScoped(
		[]schema.Event{contextEvent, auxiliaryStarted, mainUsage, auxiliaryUsage},
		"",
		Options{SessionID: "title-session"},
	)
	if len(scoped.ByUser) != 1 || scoped.ByUser[0].Key != "shukan [501]" || scoped.ByUser[0].Usage.InputTokens != 20 {
		t.Fatalf("scoped by_user = %#v, want auxiliary session attributed from unfiltered context", scoped.ByUser)
	}
}

func TestAggregateDedupesDualChannelUsage(t *testing.T) {
	// Claude Code reports each request's usage on both a claude_code.api_request
	// log record (no metric_name) and the claude_code.token.usage metric, under
	// the base and 1M-context model names respectively. Counting both doubles
	// every token field; cost rides only on claude_code.cost.usage.
	metric := func(name string, mutate func(*schema.Event)) schema.Event {
		return usageEventFixture("2026-06-11T10:00:05Z", "claude_code", "s1", "claude-opus-4-6[1m]", func(e *schema.Event) {
			mutate(e)
			e.Raw = map[string]interface{}{"metric_name": name, "metric_temporality": "Delta"}
		})
	}
	events := []schema.Event{
		// Log/span channel: full per-request usage, base model name, no cost.
		usageEventFixture("2026-06-11T10:00:00Z", "claude_code", "s1", "claude-opus-4-6", func(e *schema.Event) {
			e.Event.Action = "tool.invoked"
			e.Message = "claude_code.api_request"
			e.GenAI.Usage.InputTokens = int64Ptr(11)
			e.GenAI.Usage.OutputTokens = int64Ptr(826)
			e.GenAI.Usage.CacheRead = &schema.GenAIUsageCacheReadInfo{InputTokens: int64Ptr(119393)}
			e.GenAI.Usage.CacheCreation = &schema.GenAIUsageCacheCreationInfo{InputTokens: int64Ptr(15751)}
		}),
		// Metric channel: same tokens, field-split (must be suppressed) plus cost (must survive).
		metric("claude_code.token.usage", func(e *schema.Event) { e.GenAI.Usage.InputTokens = int64Ptr(11) }),
		metric("claude_code.token.usage", func(e *schema.Event) { e.GenAI.Usage.OutputTokens = int64Ptr(826) }),
		metric("claude_code.token.usage", func(e *schema.Event) {
			e.GenAI.Usage.CacheRead = &schema.GenAIUsageCacheReadInfo{InputTokens: int64Ptr(119393)}
		}),
		metric("claude_code.token.usage", func(e *schema.Event) {
			e.GenAI.Usage.CacheCreation = &schema.GenAIUsageCacheCreationInfo{InputTokens: int64Ptr(15751)}
		}),
		metric("claude_code.cost.usage", func(e *schema.Event) { e.GenAI.Usage.CostUSD = float64Ptr(0.1788) }),
		// Metrics-only scope (no log/span channel): must be left untouched.
		usageEventFixture("2026-06-11T10:01:00Z", "codex", "s2", "gpt-5", func(e *schema.Event) {
			e.GenAI.Usage.InputTokens = int64Ptr(500)
			e.Raw = map[string]interface{}{"metric_name": "gen_ai.client.token.usage", "metric_temporality": "Delta"}
		}),
	}

	report := Aggregate(events, Options{})
	if got := report.Totals; got.InputTokens != 511 || got.OutputTokens != 826 ||
		got.CacheReadInputTokens != 119393 || got.CacheCreationInputTokens != 15751 || got.CostUSD != 0.1788 {
		t.Fatalf("totals double-counted or dropped: %#v", got)
	}
	// Base model name carries the deduped tokens; the [1m] metric name carries cost only.
	byModel := map[string]Usage{}
	for _, g := range report.ByModel {
		byModel[g.Key] = g.Usage
	}
	if base := byModel["claude-opus-4-6"]; base.InputTokens != 11 || base.OutputTokens != 826 || base.CacheReadInputTokens != 119393 {
		t.Fatalf("base model tokens = %#v", base)
	}
	if oneM := byModel["claude-opus-4-6[1m]"]; oneM.TotalTokens() != 0 || oneM.CostUSD != 0.1788 {
		t.Fatalf("[1m] model should carry cost only, got %#v", oneM)
	}
	if codex := byModel["gpt-5"]; codex.InputTokens != 500 {
		t.Fatalf("metrics-only scope was dropped: %#v", codex)
	}
}

// Gemini CLI reports each response on the gemini_cli.api_response log and again on the
// cumulative gemini_cli.token.usage counter, and puts its session.id on both, so the two land in
// one (harness, session) scope and the log channel wins. The events are shaped as the exporter
// writes them: the log already carries the disjoint reading (input = prompt - cached + tool,
// output = candidates + thoughts), and so does each metric line.
func TestAggregateCountsGeminiLogAndMetricChannelsOnce(t *testing.T) {
	const session = "8c4f0d2e-5b1a-4e7c-9f3d-2a6b8e1c7d40"
	response := func(ts string, input, output, cacheRead, reasoning int64) schema.Event {
		return usageEventFixture(ts, "gemini_cli", session, "gemini-2.5-pro", func(e *schema.Event) {
			e.Event.Action = "tool.invoked"
			e.Event.Category = "tool"
			e.Message = "API response from gemini-2.5-pro. Status: 200. Duration: 2311ms."
			e.GenAI.Usage.InputTokens = int64Ptr(input)
			e.GenAI.Usage.OutputTokens = int64Ptr(output)
			e.GenAI.Usage.CacheRead = &schema.GenAIUsageCacheReadInfo{InputTokens: int64Ptr(cacheRead)}
			e.GenAI.Usage.Reasoning = &schema.GenAIUsageReasoningInfo{OutputTokens: int64Ptr(reasoning)}
		})
	}
	counter := func(ts, tokenType string, mutate func(*schema.GenAIUsageInfo)) schema.Event {
		return usageEventFixture(ts, "gemini_cli", session, "gemini-2.5-pro", func(e *schema.Event) {
			e.Message = "gemini_cli.token.usage"
			e.GenAI.Token = &schema.GenAITokenInfo{Type: tokenType}
			mutate(e.GenAI.Usage)
			e.Raw = map[string]interface{}{"metric_name": "gemini_cli.token.usage", "metric_temporality": "Cumulative"}
		})
	}
	collection := func(ts string, input, output, cacheRead, reasoning int64) []schema.Event {
		return []schema.Event{
			counter(ts, "input", func(u *schema.GenAIUsageInfo) { u.InputTokens = int64Ptr(input) }),
			counter(ts, "output", func(u *schema.GenAIUsageInfo) { u.OutputTokens = int64Ptr(output) }),
			counter(ts, "cache", func(u *schema.GenAIUsageInfo) {
				u.CacheRead = &schema.GenAIUsageCacheReadInfo{InputTokens: int64Ptr(cacheRead)}
			}),
			counter(ts, "thought", func(u *schema.GenAIUsageInfo) {
				u.Reasoning = &schema.GenAIUsageReasoningInfo{OutputTokens: int64Ptr(reasoning)}
			}),
			counter(ts, "tool", func(u *schema.GenAIUsageInfo) {}),
		}
	}
	events := []schema.Event{
		// prompt 12000 (8000 cached), candidates 350, thoughts 420: total 12770.
		response("2026-10-05T09:30:00Z", 4000, 770, 8000, 420),
		// prompt 5000, tool-use prompt 600, candidates 100: total 5700.
		response("2026-10-05T09:30:40Z", 5600, 100, 0, 0),
	}
	events = append(events, collection("2026-10-05T09:31:00Z", 9600, 870, 8000, 420)...)
	events = append(events, collection("2026-10-05T09:32:00Z", 9600, 870, 8000, 420)...)

	report := Aggregate(events, Options{})
	got := report.Totals
	if got.InputTokens != 9600 || got.OutputTokens != 870 || got.CacheReadInputTokens != 8000 || got.ReasoningOutputTokens != 420 {
		t.Fatalf("totals = %#v, want the log channel once: input 9600, output 870, cache read 8000, reasoning 420", got)
	}
	if got.TotalTokens() != 12770+5700 {
		t.Fatalf("total tokens = %d, want Gemini's own totals 12770 + 5700", got.TotalTokens())
	}
	if got.Events != 2 {
		t.Fatalf("events = %d, want the two api_response lines only", got.Events)
	}
}

func TestAggregateDedupesCumulativeSeries(t *testing.T) {
	cumulative := func(ts string, value int64) schema.Event {
		return usageEventFixture(ts, "claude_code", "s1", "claude-sonnet-4-5", func(e *schema.Event) {
			e.GenAI.Usage.InputTokens = int64Ptr(value)
			e.Raw = map[string]interface{}{
				"metric_name":        "claude_code.token.usage",
				"metric_temporality": "Cumulative",
			}
		})
	}
	events := []schema.Event{
		cumulative("2026-06-11T10:00:00Z", 100),
		cumulative("2026-06-11T10:01:00Z", 250),
		cumulative("2026-06-11T10:02:00Z", 400),
		// Counter reset: raw value becomes the interval contribution.
		cumulative("2026-06-11T10:03:00Z", 50),
	}

	report := Aggregate(events, Options{})
	if report.Totals.InputTokens != 450 {
		t.Fatalf("cumulative input total = %d, want 450 (100+150+150+50)", report.Totals.InputTokens)
	}
}

func TestAggregateAttributesCIRuns(t *testing.T) {
	events := []schema.Event{
		usageEventFixture("2026-06-11T10:00:00Z", "claude_code", "ci-1", "claude-sonnet-4-5", func(e *schema.Event) {
			e.GenAI.Usage.InputTokens = int64Ptr(10)
			e.Run = &schema.RunInfo{Provider: "github_actions", RunID: "12345"}
		}),
		usageEventFixture("2026-06-11T10:05:00Z", "claude_code", "ci-1", "claude-sonnet-4-5", func(e *schema.Event) {
			e.GenAI.Usage.OutputTokens = int64Ptr(4)
			e.Run = &schema.RunInfo{Provider: "github_actions", RunID: "12345"}
		}),
	}
	report := Aggregate(events, Options{})
	if len(report.ByRun) != 1 || report.ByRun[0].Key != "github_actions/12345" {
		t.Fatalf("by_run = %#v", report.ByRun)
	}
	if report.ByRun[0].Usage.InputTokens != 10 || report.ByRun[0].Usage.OutputTokens != 4 {
		t.Fatalf("by_run usage = %#v", report.ByRun[0].Usage)
	}
}

func TestAggregateRunKeyWithoutProvider(t *testing.T) {
	events := []schema.Event{
		usageEventFixture("2026-06-11T10:00:00Z", "claude_code", "s1", "claude-sonnet-4-5", func(e *schema.Event) {
			e.GenAI.Usage.InputTokens = int64Ptr(7)
			e.Run = &schema.RunInfo{RunID: "run-abc"} // provider empty
		}),
	}
	report := Aggregate(events, Options{})
	if len(report.ByRun) != 1 || report.ByRun[0].Key != "run-abc" {
		t.Fatalf("by_run = %#v, want bare run id without leading slash", report.ByRun)
	}
}

func TestAggregateScopedFiltersSessionAndRun(t *testing.T) {
	events := []schema.Event{
		usageEventFixture("2026-06-11T10:00:00Z", "claude_code", "Session-1", "claude-sonnet-4-5", func(e *schema.Event) {
			e.GenAI.Usage.InputTokens = int64Ptr(100)
			e.Run = &schema.RunInfo{Provider: "github_actions", RunID: "777"}
		}),
		usageEventFixture("2026-06-11T10:01:00Z", "claude_code", "session-2", "claude-sonnet-4-5", func(e *schema.Event) {
			e.GenAI.Usage.InputTokens = int64Ptr(50)
			e.Run = &schema.RunInfo{Provider: "github_actions", RunID: "888"}
		}),
	}

	// Session match is exact but case-insensitive.
	report := AggregateScoped(events, "", Options{SessionID: "session-1"})
	if report.Totals.InputTokens != 100 || report.TotalEvents != 1 {
		t.Fatalf("session scope totals = %#v (events=%d), want only session-1", report.Totals, report.TotalEvents)
	}
	if report.SessionDetail == nil || report.SessionDetail.SessionID != "session-1" {
		t.Fatalf("session detail = %#v", report.SessionDetail)
	}

	// Run id accepts both the bare id and the composite provider/run_id key.
	for _, runID := range []string{"888", "github_actions/888"} {
		got := AggregateScoped(events, runID, Options{})
		if got.Totals.InputTokens != 50 || got.TotalEvents != 1 {
			t.Fatalf("run scope %q totals = %#v (events=%d), want only run 888", runID, got.Totals, got.TotalEvents)
		}
		if len(got.ByRun) != 1 || got.ByRun[0].Key != "github_actions/888" {
			t.Fatalf("run scope %q by_run = %#v", runID, got.ByRun)
		}
	}

	// No scope keeps every event.
	if all := AggregateScoped(events, "", Options{}); all.Totals.InputTokens != 150 || all.TotalEvents != 2 {
		t.Fatalf("unscoped totals = %#v (events=%d), want all events", all.Totals, all.TotalEvents)
	}
}

func TestAggregateBuildsSessionStepTree(t *testing.T) {
	spanEvent := func(ts, span, parent string, input int64) schema.Event {
		return usageEventFixture(ts, "asymptote_observe", "s1", "gpt-4o-mini", func(e *schema.Event) {
			e.Event.Action = "tool.invoked"
			e.Message = "step-" + span
			e.GenAI.Usage.InputTokens = int64Ptr(input)
			e.Trace = &schema.TraceInfo{ID: "trace-1", SpanID: span, ParentSpanID: parent}
		})
	}
	events := []schema.Event{
		spanEvent("2026-06-11T10:00:00Z", "root", "", 100),
		spanEvent("2026-06-11T10:00:05Z", "child-a", "root", 30),
		spanEvent("2026-06-11T10:00:10Z", "child-b", "root", 20),
		spanEvent("2026-06-11T10:00:15Z", "grandchild", "child-a", 10),
		// Step without span identity stays flat at the top level.
		usageEventFixture("2026-06-11T10:00:20Z", "claude_code", "s1", "claude-sonnet-4-5", func(e *schema.Event) {
			e.GenAI.Usage.OutputTokens = int64Ptr(7)
		}),
	}

	report := Aggregate(events, Options{SessionID: "s1"})
	detail := report.SessionDetail
	if detail == nil || detail.SessionID != "s1" {
		t.Fatalf("session detail = %#v", detail)
	}
	if detail.Usage.InputTokens != 160 || detail.Usage.OutputTokens != 7 {
		t.Fatalf("session usage = %#v", detail.Usage)
	}
	if len(detail.Steps) != 2 {
		t.Fatalf("top-level steps = %d, want 2 (root + flat step): %#v", len(detail.Steps), detail.Steps)
	}
	root := detail.Steps[0]
	if root.SpanID != "root" || len(root.Children) != 2 {
		t.Fatalf("root step = %#v", root)
	}
	if root.Children[0].SpanID != "child-a" || len(root.Children[0].Children) != 1 || root.Children[0].Children[0].SpanID != "grandchild" {
		t.Fatalf("child tree = %#v", root.Children)
	}
	if detail.Steps[1].SpanID != "" || detail.Steps[1].Usage.OutputTokens != 7 {
		t.Fatalf("flat step = %#v", detail.Steps[1])
	}
}

func TestAggregateUtilizationCombinesPerIntervalDataPoints(t *testing.T) {
	// Claude Code reports one datapoint per token type at the same timestamp;
	// utilization must recombine them into one context-size sample.
	at := "2026-06-11T10:00:00Z"
	events := []schema.Event{
		usageEventFixture(at, "claude_code", "s1", "claude-sonnet-4-5", func(e *schema.Event) {
			e.GenAI.Usage.InputTokens = int64Ptr(1000)
		}),
		usageEventFixture(at, "claude_code", "s1", "claude-sonnet-4-5", func(e *schema.Event) {
			e.GenAI.Usage.CacheRead = &schema.GenAIUsageCacheReadInfo{InputTokens: int64Ptr(179000)}
		}),
		usageEventFixture(at, "claude_code", "s1", "claude-sonnet-4-5", func(e *schema.Event) {
			e.GenAI.Usage.CacheCreation = &schema.GenAIUsageCacheCreationInfo{InputTokens: int64Ptr(5000)}
		}),
		usageEventFixture("2026-06-11T11:00:00Z", "asymptote_observe", "s2", "experimental-model", func(e *schema.Event) {
			e.GenAI.Usage.InputTokens = int64Ptr(123)
		}),
	}

	report := Aggregate(events, Options{})
	if len(report.Utilization) != 2 {
		t.Fatalf("utilization = %#v", report.Utilization)
	}
	claude := report.Utilization[0]
	if claude.Model != "claude-sonnet-4-5" || claude.ContextWindow != 200000 || claude.Calls != 1 {
		t.Fatalf("claude utilization = %#v", claude)
	}
	if claude.MaxInputTokens != 185000 || claude.MaxRatio != 0.925 || claude.NearLimitCalls != 1 {
		t.Fatalf("claude utilization sample = %#v", claude)
	}
	unknown := report.Utilization[1]
	if unknown.Model != "experimental-model" || unknown.ContextWindow != 0 || unknown.MaxRatio != 0 || unknown.MaxInputTokens != 123 {
		t.Fatalf("unknown model utilization = %#v", unknown)
	}
}

func TestAggregateTopLimitCapsGroups(t *testing.T) {
	events := []schema.Event{
		usageEventFixture("2026-06-11T10:00:00Z", "claude_code", "s1", "model-a", func(e *schema.Event) {
			e.GenAI.Usage.InputTokens = int64Ptr(300)
		}),
		usageEventFixture("2026-06-11T10:01:00Z", "claude_code", "s2", "model-b", func(e *schema.Event) {
			e.GenAI.Usage.InputTokens = int64Ptr(200)
		}),
		usageEventFixture("2026-06-11T10:02:00Z", "claude_code", "s3", "model-c", func(e *schema.Event) {
			e.GenAI.Usage.InputTokens = int64Ptr(100)
		}),
	}
	report := Aggregate(events, Options{TopLimit: 2})
	if len(report.ByModel) != 2 || report.ByModel[0].Key != "model-a" || report.ByModel[1].Key != "model-b" {
		t.Fatalf("by_model = %#v", report.ByModel)
	}
}

// Context is a level, not spend. A context-only event must not add anything a report sums, or a
// Qwen session's cost would grow with the square of its length.
//
// "Anything" is the whole shape, not just the token and cost fields. An earlier version of this
// test checked only those two and passed while the event was still incrementing the event counts
// and creating zero-token rows under every grouping -- which reads as a runtime that spent nothing
// but was nonetheless active in a spend report, and which the coverage report in beacon
// token-usage --coverage would have read as "this runtime is reporting its spend".
func TestContextOnlyEventsAddNothingToTotals(t *testing.T) {
	events := []schema.Event{
		usageEventFixture("2026-06-11T10:00:00Z", "qwen_code", "s1", "qwen3-coder-plus", func(e *schema.Event) {
			e.GenAI.Usage = nil
			e.GenAI.Context = &schema.GenAIContextInfo{
				UsedTokens:  int64Ptr(110100),
				LimitTokens: int64Ptr(262144),
			}
		}),
	}
	report := Aggregate(events, Options{BucketSize: time.Hour, SessionID: "s1"})
	if got := report.Totals.TotalTokens(); got != 0 {
		t.Errorf("totals = %d tokens, want 0 -- context occupancy is not spend", got)
	}
	if report.Totals.CostUSD != 0 {
		t.Errorf("totals cost = %v, want 0", report.Totals.CostUSD)
	}
	if report.Totals.Events != 0 {
		t.Errorf("totals events = %d, want 0 -- the event carries no usage to have counted", report.Totals.Events)
	}
	if report.EventsWithUsage != 0 {
		t.Errorf("events_with_usage = %d, want 0", report.EventsWithUsage)
	}
	for name, group := range map[string][]Group{
		"by_model": report.ByModel, "by_session": report.BySession,
		"by_harness": report.ByHarness, "by_user": report.ByUser,
		"by_repository": report.ByRepository, "by_run": report.ByRun,
	} {
		if len(group) != 0 {
			t.Errorf("%s = %+v, want no rows -- a zero-token row reads as a runtime that spent nothing but was active", name, group)
		}
	}
	if len(report.Series) != 0 {
		t.Errorf("series = %+v, want no buckets", report.Series)
	}
	if report.SessionDetail != nil && len(report.SessionDetail.Steps) != 0 {
		t.Errorf("session steps = %+v, want none", report.SessionDetail.Steps)
	}
	// The one thing it must still do.
	if len(report.Utilization) != 1 {
		t.Fatalf("utilization = %+v, want the context-only event to still be measured", report.Utilization)
	}
}

// An event reporting both spend and context is not context-only: its usage counts normally and its
// context still feeds utilization.
func TestEventsWithBothUsageAndContextCountAsSpend(t *testing.T) {
	events := []schema.Event{
		usageEventFixture("2026-06-11T10:00:00Z", "some_runtime", "s1", "some-model", func(e *schema.Event) {
			e.GenAI.Usage.InputTokens = int64Ptr(900)
			e.GenAI.Usage.OutputTokens = int64Ptr(100)
			e.GenAI.Context = &schema.GenAIContextInfo{
				UsedTokens:  int64Ptr(50000),
				LimitTokens: int64Ptr(200000),
			}
		}),
	}
	report := Aggregate(events, Options{})
	if got := report.Totals.TotalTokens(); got != 1000 {
		t.Errorf("totals = %d, want the reported 1000 spend tokens", got)
	}
	if report.EventsWithUsage != 1 {
		t.Errorf("events_with_usage = %d, want 1", report.EventsWithUsage)
	}
	if len(report.Utilization) != 1 || report.Utilization[0].MaxInputTokens != 50000 {
		t.Errorf("utilization = %+v, want the reported 50000 occupancy, not the 900 input", report.Utilization)
	}
}

// The real Qwen payload, not the fixture shape the other utilization tests use. Qwen declares its
// model on session start and never again: its Stop hook -- the only producer of gen_ai.context --
// carries session_id, context_usage, context_limit and input_tokens, and no model at all. Since
// buildUtilization keys rows on the model and skips events without one, occupancy was recorded on
// the event and then dropped before reaching the report this change exists to fill. The session's
// model is the right attribution because the events belong to one session that declared it.
func TestUtilizationAttributesContextToTheSessionModelWhenTheEventCarriesNone(t *testing.T) {
	events := []schema.Event{
		{
			Timestamp: "2026-06-11T10:00:00Z",
			Event:     schema.EventInfo{Kind: "agent_runtime", Action: "session.start", Category: "session"},
			Harness:   schema.HarnessInfo{Name: "qwen_code"},
			Session:   &schema.SessionInfo{ID: "qwen-8f21c4a0"},
			Model:     "qwen3-coder-plus",
		},
		{
			Timestamp: "2026-06-11T10:01:00Z",
			Event:     schema.EventInfo{Kind: "agent_runtime", Action: "tool.completed", Category: "tool"},
			Harness:   schema.HarnessInfo{Name: "qwen_code"},
			Session:   &schema.SessionInfo{ID: "qwen-8f21c4a0"},
			GenAI: &schema.GenAIInfo{Context: &schema.GenAIContextInfo{
				UsedTokens:  int64Ptr(110100),
				LimitTokens: int64Ptr(262144),
			}},
		},
	}
	report := Aggregate(events, Options{})
	if len(report.Utilization) != 1 {
		t.Fatalf("utilization = %+v, want one row attributed to the session model", report.Utilization)
	}
	row := report.Utilization[0]
	if row.Model != "qwen3-coder-plus" {
		t.Errorf("model = %q, want the model the session declared", row.Model)
	}
	if row.MaxInputTokens != 110100 {
		t.Errorf("max input tokens = %d, want the reported 110100", row.MaxInputTokens)
	}
	if row.ContextWindow != 262144 {
		t.Errorf("context window = %d, want the reported 262144", row.ContextWindow)
	}
	// The carry-forward is for attribution only. Nothing about it makes occupancy spend.
	if report.Totals.TotalTokens() != 0 {
		t.Errorf("totals = %d, want 0", report.Totals.TotalTokens())
	}
	if report.EventsWithUsage != 0 {
		t.Errorf("events with usage = %d, want 0", report.EventsWithUsage)
	}
}

// The carry-forward must not reach spend. An event reporting real usage with no model of its own
// is attributed as it always was -- summed into the totals, absent from the per-model rows -- and
// changing that would silently move other runtimes' spend between models.
func TestSessionModelCarryForwardDoesNotRelabelSpend(t *testing.T) {
	events := []schema.Event{
		{
			Timestamp: "2026-06-11T10:00:00Z",
			Event:     schema.EventInfo{Kind: "agent_runtime", Action: "session.start", Category: "session"},
			Harness:   schema.HarnessInfo{Name: "claude_code"},
			Session:   &schema.SessionInfo{ID: "s1"},
			Model:     "claude-opus-5",
		},
		usageEventFixture("2026-06-11T10:01:00Z", "claude_code", "s1", "", func(e *schema.Event) {
			e.GenAI.Usage.InputTokens = int64Ptr(100)
			e.GenAI.Usage.OutputTokens = int64Ptr(20)
		}),
	}
	report := Aggregate(events, Options{})
	if report.Totals.TotalTokens() != 120 {
		t.Fatalf("totals = %d, want 120", report.Totals.TotalTokens())
	}
	for _, group := range report.ByModel {
		if group.Key == "claude-opus-5" {
			t.Errorf("by-model has a claude-opus-5 row (%+v); spend with no model of its own must not be relabelled", group)
		}
	}
}

// Every path that writes an event now canonicalizes the model name, so a log Beacon wrote after
// that landed cannot split. This is about the logs where that does not hold: everything written
// before the rule existed, which the runtime log retains and a --since window spans, and any JSONL
// Beacon reads without having written -- a customer's own file, or events forwarded in from a
// producer with its own conventions.
//
// Reading is where a report can still be made whole for those, and grouping is the only place it
// matters: three spellings of one model are three rows, each holding a third of the bill, with
// nothing on the report saying so. A split row is not obviously wrong to a reader, which is what
// makes it worth closing rather than tolerating.
func TestAggregateGroupsOneModelReportedUnderSeveralSpellings(t *testing.T) {
	mk := func(model string) schema.Event {
		return usageEventFixture("2026-06-11T10:00:00Z", "claude_code", "s1", model, func(e *schema.Event) {
			e.GenAI.Usage.InputTokens = int64Ptr(10)
		})
	}
	report := Aggregate([]schema.Event{
		mk("claude-opus-5"),
		mk("anthropic/claude-opus-5"),
		mk("Claude-Opus-5"),
		mk("  openrouter/anthropic/Claude-Opus-5  "),
	}, Options{})

	if len(report.ByModel) != 1 {
		keys := make([]string, 0, len(report.ByModel))
		for _, group := range report.ByModel {
			keys = append(keys, group.Key)
		}
		t.Fatalf("by-model rows = %v, want one row for one model", keys)
	}
	row := report.ByModel[0]
	if row.Key != "claude-opus-5" {
		t.Errorf("by-model key = %q, want the canonical spelling", row.Key)
	}
	if row.Usage.TotalTokens() != 40 {
		t.Errorf("by-model tokens = %d, want all 40 under the one row", row.Usage.TotalTokens())
	}
	if len(report.Utilization) != 1 {
		t.Errorf("utilization rows = %d, want one -- it keys on the model too", len(report.Utilization))
	}
	// The totals never split, so they are the control: they were right before this change and must
	// be unchanged by it.
	if report.Totals.TotalTokens() != 40 {
		t.Errorf("totals = %d, want 40", report.Totals.TotalTokens())
	}
}

// The normalization is the shared one, so what it declines to do it declines to do here. Folding
// the dot in "claude-sonnet-4.6" would merge it with Anthropic's "claude-sonnet-4-6", and the same
// rule turns "gpt-4.1" into a model that exists under no name. A visible split beats an invented
// id, so these stay two rows.
func TestAggregateDoesNotMergeModelsThatOnlyLookAlike(t *testing.T) {
	mk := func(model string) schema.Event {
		return usageEventFixture("2026-06-11T10:00:00Z", "claude_code", "s1", model, func(e *schema.Event) {
			e.GenAI.Usage.InputTokens = int64Ptr(10)
		})
	}
	report := Aggregate([]schema.Event{mk("claude-sonnet-4.6"), mk("claude-sonnet-4-6")}, Options{})
	if len(report.ByModel) != 2 {
		t.Fatalf("by-model rows = %d, want 2 -- these are different ids and merging them needs a catalog", len(report.ByModel))
	}
}

// TestAggregatePrefersLiveCaptureOverPollBackfill covers runtimes Beacon reads twice: once live
// (an OTLP export, a hook, a Beacon-managed plugin) and once after the fact from the session store
// the runtime commits to disk (`beacon endpoint <runtime> sync`, collection_method=poll). Both
// paths report the same requests' usage under the same session id, and nothing at write time
// collapses them: usage events carry no tool-call id, so each path's event.id is a digest of its
// own line. Live is authoritative from the moment its channel was capturing the session; poll
// usage before that is the only record of those turns and stays.
func TestAggregatePrefersLiveCaptureOverPollBackfill(t *testing.T) {
	type tokens struct {
		input, output, cacheRead, cacheCreation, reasoning int64
		cost                                               float64
	}
	event := func(ts, harness, method, session, action string, usage *tokens, mutate func(*schema.Event)) schema.Event {
		e := schema.Event{
			Timestamp: ts,
			Endpoint:  schema.EndpointInfo{Hostname: "host-a", OS: "darwin"},
			Event:     schema.EventInfo{Kind: "agent_runtime", Action: action},
			Harness:   schema.HarnessInfo{Name: harness, CollectionMethod: method},
		}
		if session != "" {
			e.Session = &schema.SessionInfo{ID: session}
		}
		if usage != nil {
			info := &schema.GenAIUsageInfo{}
			if usage.input != 0 {
				info.InputTokens = int64Ptr(usage.input)
			}
			if usage.output != 0 {
				info.OutputTokens = int64Ptr(usage.output)
			}
			if usage.cacheRead != 0 {
				info.CacheRead = &schema.GenAIUsageCacheReadInfo{InputTokens: int64Ptr(usage.cacheRead)}
			}
			if usage.cacheCreation != 0 {
				info.CacheCreation = &schema.GenAIUsageCacheCreationInfo{InputTokens: int64Ptr(usage.cacheCreation)}
			}
			if usage.reasoning != 0 {
				info.Reasoning = &schema.GenAIUsageReasoningInfo{OutputTokens: int64Ptr(usage.reasoning)}
			}
			if usage.cost != 0 {
				info.CostUSD = float64Ptr(usage.cost)
			}
			e.GenAI = &schema.GenAIInfo{Usage: info}
		}
		if mutate != nil {
			mutate(&e)
		}
		return e
	}
	model := func(name string) func(*schema.Event) { return func(e *schema.Event) { e.Model = name } }
	metric := func(name string) func(*schema.Event) {
		return func(e *schema.Event) {
			e.Model = "claude-opus-4-6"
			e.Raw = map[string]interface{}{"metric_name": name, "metric_temporality": "Delta"}
		}
	}
	const (
		otlp   = schema.CollectionMethodOTLP
		plugin = schema.CollectionMethodPlugin
		hook   = schema.CollectionMethodHook
		poll   = schema.CollectionMethodPoll
		gw     = schema.CollectionMethodGateway
	)

	cases := []struct {
		name       string
		events     []schema.Event
		want       tokens
		wantEvents int
		suppressed int
	}{
		{
			// Claude Code's OTLP api_request log is written when a request completes; the
			// transcript line `claude sync` reads for the same request is written as the
			// response streams, so it lands a second or two earlier. The cutover is the session's
			// first OTLP record (the user_prompt log), not its first usage record, or the first
			// request of every session would be counted twice.
			name: "claude otlp api_request log and claude sync",
			events: []schema.Event{
				event("2026-06-11T10:00:00.100Z", "claude_code", otlp, "c1", "prompt.submitted", nil, nil),
				event("2026-06-11T10:00:03.900Z", "claude_code", poll, "c1", "agent.response", &tokens{input: 6, output: 410, cacheRead: 21000, cacheCreation: 3100}, model("claude-opus-4-6")),
				event("2026-06-11T10:00:05.200Z", "claude_code", otlp, "c1", "tool.invoked", &tokens{input: 6, output: 410, cacheRead: 21000, cacheCreation: 3100, cost: 0.0421}, model("claude-opus-4-6")),
				event("2026-06-11T10:00:41.000Z", "claude_code", poll, "c1", "agent.response", &tokens{input: 3, output: 95, cacheRead: 24100}, model("claude-opus-4-6")),
				event("2026-06-11T10:00:42.500Z", "claude_code", otlp, "c1", "tool.invoked", &tokens{input: 3, output: 95, cacheRead: 24100, cost: 0.0153}, model("claude-opus-4-6")),
			},
			want:       tokens{input: 9, output: 505, cacheRead: 45100, cacheCreation: 3100, cost: 0.0574},
			wantEvents: 2,
			suppressed: 2,
		},
		{
			// Three channels for one session: the api_request log, the token.usage/cost.usage
			// metrics, and the transcript. The log wins over the metric for tokens (the existing
			// channel dedupe), cost survives once on the metric, and the poll copy goes.
			name: "claude log, metric and claude sync counted once",
			events: []schema.Event{
				event("2026-06-11T10:00:00Z", "claude_code", otlp, "c2", "prompt.submitted", nil, nil),
				event("2026-06-11T10:00:04Z", "claude_code", poll, "c2", "agent.response", &tokens{input: 11, output: 826, cacheRead: 119393, cacheCreation: 15751}, model("claude-opus-4-6")),
				event("2026-06-11T10:00:05Z", "claude_code", otlp, "c2", "tool.invoked", &tokens{input: 11, output: 826, cacheRead: 119393, cacheCreation: 15751}, model("claude-opus-4-6")),
				event("2026-06-11T10:00:06Z", "claude_code", otlp, "c2", "token.usage", &tokens{input: 11}, metric("claude_code.token.usage")),
				event("2026-06-11T10:00:06Z", "claude_code", otlp, "c2", "token.usage", &tokens{output: 826}, metric("claude_code.token.usage")),
				event("2026-06-11T10:00:06Z", "claude_code", otlp, "c2", "token.usage", &tokens{cacheRead: 119393}, metric("claude_code.token.usage")),
				event("2026-06-11T10:00:06Z", "claude_code", otlp, "c2", "token.usage", &tokens{cacheCreation: 15751}, metric("claude_code.token.usage")),
				event("2026-06-11T10:00:06Z", "claude_code", otlp, "c2", "cost.usage", &tokens{cost: 0.1788}, metric("claude_code.cost.usage")),
			},
			want:       tokens{input: 11, output: 826, cacheRead: 119393, cacheCreation: 15751, cost: 0.1788},
			wantEvents: 2,
			suppressed: 1,
		},
		{
			// Metrics exporter only, no logs: the metric is the live channel. The transcript's
			// pre-cutover turn must not zero the metric's tokens for the whole session, which is
			// what the log/metric dedupe would do if it read a poll event as the log channel.
			name: "claude metric only and claude sync",
			events: []schema.Event{
				event("2026-06-11T09:30:00Z", "claude_code", poll, "c3", "agent.response", &tokens{input: 40, output: 7}, model("claude-opus-4-6")),
				event("2026-06-11T10:00:04Z", "claude_code", poll, "c3", "agent.response", &tokens{input: 11, output: 826}, model("claude-opus-4-6")),
				event("2026-06-11T10:00:00Z", "claude_code", otlp, "c3", "token.usage", &tokens{input: 11}, metric("claude_code.token.usage")),
				event("2026-06-11T10:00:00Z", "claude_code", otlp, "c3", "token.usage", &tokens{output: 826}, metric("claude_code.token.usage")),
			},
			want:       tokens{input: 51, output: 833},
			wantEvents: 3,
			suppressed: 1,
		},
		{
			// Codex's turn span carries its own start, which precedes the span's timestamp by the
			// whole turn; `codex sync` stamps token_count at each request inside the turn. The
			// turn from before Beacon's collector was running survives from the backfill alone.
			name: "codex otlp turn span and codex sync",
			events: []schema.Event{
				event("2026-06-11T09:50:00Z", "codex_cli", poll, "019a-thread", "token.usage", &tokens{input: 3000, cacheRead: 1200, output: 80}, model("gpt-5.6-sol")),
				event("2026-06-11T10:00:00Z", "codex_cli", hook, "019a-thread", "session.started", nil, nil),
				event("2026-06-11T10:00:20Z", "codex_cli", poll, "019a-thread", "token.usage", &tokens{input: 13347, cacheCreation: 13344, output: 512, reasoning: 64}, model("gpt-5.6-sol")),
				event("2026-06-11T10:00:30Z", "codex_cli", otlp, "019a-thread", "token.usage", &tokens{input: 13347, cacheCreation: 13344, output: 512, reasoning: 64}, func(e *schema.Event) {
					e.Model = "gpt-5.6-sol"
					e.Raw = map[string]interface{}{"source": "codex_turn_span", "turn_id": "turn-2", "turn_start_timestamp": "2026-06-11T10:00:01Z"}
				}),
			},
			want:       tokens{input: 16347, cacheRead: 1200, cacheCreation: 13344, output: 592, reasoning: 64},
			wantEvents: 2,
			suppressed: 1,
		},
		{
			// Codex's legacy turn metric has no session id, so it cannot claim a session and
			// leaves the backfill alone; the turn span does claim one, and the span preference
			// still drops the overlapping metric.
			name: "codex legacy metric, turn span and codex sync",
			events: []schema.Event{
				event("2026-06-11T09:00:00Z", "codex_cli", otlp, "", "token.usage", &tokens{input: 10}, func(e *schema.Event) {
					e.Model = "gpt-5.6-sol"
					e.Raw = map[string]interface{}{"metric_name": "codex.turn.token_usage", "metric_temporality": "Delta"}
				}),
				event("2026-06-11T09:59:59Z", "codex_cli", otlp, "", "token.usage", &tokens{input: 20}, func(e *schema.Event) {
					e.Model = "gpt-5.6-sol"
					e.Raw = map[string]interface{}{"metric_name": "codex.turn.token_usage", "metric_temporality": "Delta"}
				}),
				event("2026-06-11T09:59:58Z", "codex_cli", poll, "t2", "token.usage", &tokens{input: 20}, model("gpt-5.6-sol")),
				event("2026-06-11T10:00:00Z", "codex_cli", otlp, "t2", "token.usage", &tokens{input: 20}, func(e *schema.Event) {
					e.Model = "gpt-5.6-sol"
					e.Raw = map[string]interface{}{"source": "codex_turn_span", "turn_start_timestamp": "2026-06-11T09:59:55Z"}
				}),
			},
			want:       tokens{input: 30},
			wantEvents: 2,
			suppressed: 1,
		},
		{
			// Codex tags its legacy metric with the session's originator, so the exporter names it
			// codex_desktop like the Desktop turn span over the same turns, which drops it.
			name: "codex desktop turn span and the desktop's legacy metric",
			events: []schema.Event{
				event("2026-06-11T10:00:30Z", "codex_desktop", otlp, "", "token.usage", &tokens{input: 20}, func(e *schema.Event) {
					e.Model = "gpt-5.6-sol"
					e.Raw = map[string]interface{}{"metric_name": "codex.turn.token_usage", "metric_temporality": "Delta",
						"attributes": map[string]interface{}{"service.name": "codex-app-server", "originator": "Codex_Desktop", "session_source": "vscode"}}
				}),
				event("2026-06-11T10:00:30Z", "codex_desktop", otlp, "019a-desktop", "token.usage", &tokens{input: 20}, func(e *schema.Event) {
					e.Model = "gpt-5.6-sol"
					e.Raw = map[string]interface{}{"source": "codex_turn_span", "turn_start_timestamp": "2026-06-11T10:00:01Z"}
				}),
			},
			want:       tokens{input: 20},
			wantEvents: 1,
			suppressed: 0,
		},
		{
			// An older CLI exports only the legacy metric, under its own service name; Desktop's
			// turn spans on the same machine and model cover none of its turns.
			name: "codex desktop turn span and an older CLI's legacy metric",
			events: []schema.Event{
				event("2026-06-11T10:00:00Z", "codex_desktop", otlp, "019a-desktop", "token.usage", &tokens{input: 20}, func(e *schema.Event) {
					e.Model = "gpt-5.6-sol"
					e.Raw = map[string]interface{}{"source": "codex_turn_span", "turn_start_timestamp": "2026-06-11T09:59:50Z"}
				}),
				event("2026-06-11T10:05:00Z", "codex_cli", otlp, "", "token.usage", &tokens{input: 7}, func(e *schema.Event) {
					e.Model = "gpt-5.6-sol"
					e.Raw = map[string]interface{}{"metric_name": "codex.turn.token_usage", "metric_temporality": "Delta",
						"attributes": map[string]interface{}{"service.name": "codex_cli_rs"}}
				}),
			},
			want:       tokens{input: 27},
			wantEvents: 2,
			suppressed: 0,
		},
		{
			// `codex sync` reads the same conversation from its rollout. Here both name it
			// codex_desktop, from the originator; one session, so the backfill goes.
			name: "codex desktop live capture and codex sync",
			events: []schema.Event{
				event("2026-06-11T10:00:00Z", "codex_desktop", otlp, "019a-desktop", "session.started", nil, nil),
				event("2026-06-11T10:00:20Z", "codex_desktop", poll, "019a-desktop", "token.usage", &tokens{input: 500, output: 40}, model("gpt-5.6-sol")),
				event("2026-06-11T10:00:30Z", "codex_desktop", otlp, "019a-desktop", "token.usage", &tokens{input: 500, output: 40}, func(e *schema.Event) {
					e.Model = "gpt-5.6-sol"
					e.Raw = map[string]interface{}{"source": "codex_turn_span", "turn_start_timestamp": "2026-06-11T10:00:01Z"}
				}),
			},
			want:       tokens{input: 500, output: 40},
			wantEvents: 1,
			suppressed: 1,
		},
		{
			// Logs written before the originator decided name one session twice: `codex sync`
			// wrote Desktop rollouts as codex_cli, and the collector wrote every app-server
			// session, CLI ones too, as codex_desktop.
			name: "codex live capture and codex sync under the names logs already hold",
			events: []schema.Event{
				event("2026-06-11T10:00:00Z", "codex_desktop", otlp, "019a-desktop", "session.started", nil, nil),
				event("2026-06-11T10:00:20Z", "codex_cli", poll, "019a-desktop", "token.usage", &tokens{input: 500, output: 40}, model("gpt-5.6-sol")),
				event("2026-06-11T10:00:30Z", "codex_desktop", otlp, "019a-desktop", "token.usage", &tokens{input: 500, output: 40}, func(e *schema.Event) {
					e.Model = "gpt-5.6-sol"
					e.Raw = map[string]interface{}{"source": "codex_turn_span", "turn_start_timestamp": "2026-06-11T10:00:01Z"}
				}),
			},
			want:       tokens{input: 500, output: 40},
			wantEvents: 1,
			suppressed: 1,
		},
		{
			// Cline's plugin reports usage once, on the run result at task end; `cline sync`
			// reports it per API request from the task's ui_messages. The task-end total covers
			// every request after the plugin's first event, so all of those poll rows go.
			name: "cline plugin task end and cline sync",
			events: []schema.Event{
				event("2026-06-11T10:00:00Z", "cline", plugin, "1749636000000", "session.started", nil, nil),
				event("2026-06-11T10:00:10Z", "cline", poll, "1749636000000", "agent.response", &tokens{input: 1200, output: 150, cacheRead: 9000, cost: 0.011}, model("claude-sonnet-4-5")),
				event("2026-06-11T10:00:40Z", "cline", poll, "1749636000000", "agent.response", &tokens{input: 800, output: 90, cacheRead: 10200, cost: 0.009}, model("claude-sonnet-4-5")),
				event("2026-06-11T10:01:00Z", "cline", plugin, "1749636000000", "session.ended", &tokens{input: 2000, output: 240, cacheRead: 19200, cost: 0.02}, nil),
			},
			want:       tokens{input: 2000, output: 240, cacheRead: 19200, cost: 0.02},
			wantEvents: 1,
			suppressed: 2,
		},
		{
			// The Pi extension reports usage on message_end; the session file stamps the assistant
			// message when it was created, before it streamed.
			name: "pi extension and pi sync",
			events: []schema.Event{
				event("2026-06-11T10:00:00Z", "pi_cli", plugin, "pi-0197", "session.started", nil, nil),
				event("2026-06-11T10:00:02Z", "pi_cli", poll, "pi-0197", "agent.response", &tokens{input: 2400, output: 610, cacheRead: 300, cost: 0.0102}, model("claude-sonnet-4-5")),
				event("2026-06-11T10:00:19Z", "pi_cli", plugin, "pi-0197", "agent.response", &tokens{input: 2400, output: 610, cacheRead: 300, cost: 0.0102}, model("claude-sonnet-4-5")),
			},
			want:       tokens{input: 2400, output: 610, cacheRead: 300, cost: 0.0102},
			wantEvents: 1,
			suppressed: 1,
		},
		{
			// A harness or session spelling difference must not split one session into two scopes.
			name: "harness spellings normalize to one session",
			events: []schema.Event{
				event("2026-06-11T10:00:00Z", "Claude Code", otlp, "c4", "prompt.submitted", nil, nil),
				event("2026-06-11T10:00:04Z", "claude_code", poll, "C4", "agent.response", &tokens{input: 5, output: 50}, nil),
				event("2026-06-11T10:00:05Z", "claude-code", otlp, "c4", "tool.invoked", &tokens{input: 5, output: 50}, nil),
			},
			want:       tokens{input: 5, output: 50},
			wantEvents: 1,
			suppressed: 1,
		},
		{
			// Beacon installed mid-session: the backfill is the only record of what came before.
			name: "poll before the live cutover is kept",
			events: []schema.Event{
				event("2026-06-11T09:10:00Z", "claude_code", poll, "c5", "agent.response", &tokens{input: 100, output: 10}, nil),
				event("2026-06-11T09:20:00Z", "claude_code", poll, "c5", "agent.response", &tokens{input: 200, output: 20}, nil),
				event("2026-06-11T10:00:00Z", "claude_code", otlp, "c5", "prompt.submitted", nil, nil),
				event("2026-06-11T10:00:04Z", "claude_code", poll, "c5", "agent.response", &tokens{input: 300, output: 30}, nil),
				event("2026-06-11T10:00:05Z", "claude_code", otlp, "c5", "tool.invoked", &tokens{input: 300, output: 30}, nil),
			},
			want:       tokens{input: 600, output: 60},
			wantEvents: 3,
			suppressed: 1,
		},
		{
			// Without a session id there is no evidence the two reports are the same turn.
			name: "no session id is never deduplicated",
			events: []schema.Event{
				event("2026-06-11T10:00:00Z", "claude_code", otlp, "", "tool.invoked", &tokens{input: 7}, nil),
				event("2026-06-11T10:00:01Z", "claude_code", poll, "", "agent.response", &tokens{input: 7}, nil),
			},
			want:       tokens{input: 14},
			wantEvents: 2,
		},
		{
			// Each session decides for itself: one with live capture does not suppress another's
			// backfill, and the same session id on another endpoint is another session.
			name: "sessions and endpoints are independent",
			events: []schema.Event{
				event("2026-06-11T10:00:00Z", "pi_cli", plugin, "pi-a", "session.started", nil, nil),
				event("2026-06-11T10:00:02Z", "pi_cli", poll, "pi-a", "agent.response", &tokens{input: 100}, nil),
				event("2026-06-11T10:00:03Z", "pi_cli", plugin, "pi-a", "agent.response", &tokens{input: 100}, nil),
				event("2026-06-11T10:00:04Z", "pi_cli", poll, "pi-b", "agent.response", &tokens{input: 40}, nil),
				event("2026-06-11T10:00:05Z", "pi_cli", poll, "pi-a", "agent.response", &tokens{input: 9}, func(e *schema.Event) {
					e.Endpoint.Hostname = "host-b"
				}),
			},
			want:       tokens{input: 149},
			wantEvents: 3,
			suppressed: 1,
		},
		{
			// A live channel that reports how full the window is, and nothing spent, is no
			// authority on spend: it must not suppress the backfill.
			name: "context-only live capture does not suppress poll",
			events: []schema.Event{
				event("2026-06-11T10:00:00Z", "pi_cli", plugin, "pi-c", "session.context", nil, func(e *schema.Event) {
					e.Model = "claude-sonnet-4-5"
					e.GenAI = &schema.GenAIInfo{Context: &schema.GenAIContextInfo{UsedTokens: int64Ptr(52000), LimitTokens: int64Ptr(200000)}}
				}),
				event("2026-06-11T10:00:05Z", "pi_cli", poll, "pi-c", "agent.response", &tokens{input: 52000, output: 100}, model("claude-sonnet-4-5")),
			},
			want:       tokens{input: 52000, output: 100},
			wantEvents: 1,
		},
		{
			// A live channel that reports cost only claims cost only: the backfill's tokens
			// stay, and its cost does not count twice.
			name: "live fields are suppressed field by field",
			events: []schema.Event{
				event("2026-06-11T10:00:00Z", "claude_code", otlp, "c6", "cost.usage", &tokens{cost: 0.05}, metric("claude_code.cost.usage")),
				event("2026-06-11T10:00:04Z", "claude_code", poll, "c6", "agent.response", &tokens{input: 30, output: 3, cost: 0.05}, nil),
			},
			want:       tokens{input: 30, output: 3, cost: 0.05},
			wantEvents: 2,
		},
		{
			// A record with no usable timestamp cannot be placed against the cutover, and a live
			// channel with no usable timestamp cannot set one; both stay, as in the Codex span
			// preference.
			name: "zero timestamps are kept",
			events: []schema.Event{
				event("2026-06-11T10:00:00Z", "opencode", plugin, "ses_z", "agent.response", &tokens{input: 10}, nil),
				event("", "opencode", poll, "ses_z", "token.usage", &tokens{input: 10}, nil),
				event("", "cline", plugin, "task-z", "session.ended", &tokens{input: 5}, nil),
				event("2026-06-11T10:00:00Z", "cline", poll, "task-z", "agent.response", &tokens{input: 5}, nil),
			},
			want:       tokens{input: 30},
			wantEvents: 4,
		},
		{
			// An event with no collection method (a log written before provenance existed) is
			// not evidence of live capture.
			name: "unmarked events are not live",
			events: []schema.Event{
				event("2026-06-11T10:00:00Z", "claude_code", "", "c7", "tool.invoked", &tokens{input: 8}, nil),
				event("2026-06-11T10:00:01Z", "claude_code", poll, "c7", "agent.response", &tokens{input: 8}, nil),
			},
			want:       tokens{input: 16},
			wantEvents: 2,
		},
		{
			// A gateway sees each model call live, so it is authoritative over a poll copy of
			// the same session from the same endpoint, like any other live channel.
			name: "gateway is a live channel",
			events: []schema.Event{
				event("2026-06-11T10:00:00Z", "claude_code", gw, "g1", "prompt.submitted", nil, nil),
				event("2026-06-11T10:00:04Z", "claude_code", poll, "g1", "agent.response", &tokens{input: 12, output: 40}, model("claude-opus-4-6")),
				event("2026-06-11T10:00:05Z", "claude_code", gw, "g1", "agent.message", &tokens{input: 12, output: 40}, model("claude-opus-4-6")),
			},
			want:       tokens{input: 12, output: 40},
			wantEvents: 1,
			suppressed: 1,
		},
	}
	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			report := Aggregate(tc.events, Options{})
			got := report.Totals
			if got.InputTokens != tc.want.input || got.OutputTokens != tc.want.output ||
				got.CacheReadInputTokens != tc.want.cacheRead || got.CacheCreationInputTokens != tc.want.cacheCreation ||
				got.ReasoningOutputTokens != tc.want.reasoning || !closeTo(got.CostUSD, tc.want.cost) {
				t.Fatalf("totals = %+v, want %+v", got, tc.want)
			}
			if report.EventsWithUsage != tc.wantEvents {
				t.Fatalf("events_with_usage = %d, want %d", report.EventsWithUsage, tc.wantEvents)
			}
			if report.SuppressedPollEvents != tc.suppressed {
				t.Fatalf("suppressed_poll_events = %d, want %d", report.SuppressedPollEvents, tc.suppressed)
			}
		})
	}
}

// TestAggregateScopedKeepsTheLiveCutoverOutsideTheWindow checks that a time window that starts
// after a session's first live record does not move the cutover to the first record inside the
// window, which would let the backfill's copy of the window's first request count twice.
func TestAggregateScopedKeepsTheLiveCutoverOutsideTheWindow(t *testing.T) {
	mk := func(ts, method string, input int64) schema.Event {
		e := usageEventFixture(ts, "claude_code", "c8", "claude-opus-4-6", func(e *schema.Event) {
			e.Harness.CollectionMethod = method
		})
		if input == 0 {
			e.GenAI = nil
			e.Event.Action = "prompt.submitted"
		} else {
			e.GenAI.Usage.InputTokens = int64Ptr(input)
		}
		return e
	}
	all := []schema.Event{
		mk("2026-06-11T09:00:00Z", schema.CollectionMethodOTLP, 0),
		mk("2026-06-11T09:00:05Z", schema.CollectionMethodOTLP, 10),
		mk("2026-06-11T10:00:04Z", schema.CollectionMethodPoll, 20),
		mk("2026-06-11T10:00:05Z", schema.CollectionMethodOTLP, 20),
	}
	window := all[2:]
	report := AggregateScopedWithContexts(window, all, "", Options{})
	if report.Totals.InputTokens != 20 || report.SuppressedPollEvents != 1 {
		t.Fatalf("totals = %+v suppressed = %d, want the window's request once", report.Totals, report.SuppressedPollEvents)
	}
}

func closeTo(a, b float64) bool {
	d := a - b
	return d < 1e-9 && d > -1e-9
}