Skip to content

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

Recover the session model for context-only events

Claude81e456fb00ac
diff --git a/cli/beacon-hooks/cmd/qwen_event_test.go b/cli/beacon-hooks/cmd/qwen_event_test.go
index 6feed1b7..58d545a5 100644
--- a/cli/beacon-hooks/cmd/qwen_event_test.go
+++ b/cli/beacon-hooks/cmd/qwen_event_test.go
@@ -625,3 +625,29 @@ func TestQwenNotebookEditRecordsThePathWithoutClaimingADiff(t *testing.T) {
"asserting content Beacon never saw", diff)
}
}
+
+// Why the model for Qwen occupancy has to be resolved when the log is read rather than when it is
+// written. Qwen names its model on session start and never again: the Stop payload -- the only one
+// carrying the context trio -- has no model field, so the emitted event has none either. Anything
+// keyed on the model, the token-usage utilization report included, has to recover it from the
+// session. Recording that here means a future change to this hook cannot quietly remove the reason
+// the reader does that work.
+func TestQwenStopEventCarriesNoModel(t *testing.T) {
+ logPath := setupQwenHook(t)
+
+ input := readQwenFixture(t, "stop.json")
+ if _, ok := input["model"]; ok {
+ t.Fatalf("stop fixture now has a model; the reader-side session lookup may no longer be needed: %#v", input)
+ }
+ sessionID, _ := resolveSessionIDWithTranscript(input, platformFlag)
+ logger := newHookLogger("stop", platformFlag, sessionID)
+ emitHookEvent(logger, "tool.completed", "tool", "info", "Agent response completed", input, sessionFields(sessionID, input))
+
+ event := lastEndpointEvent(t, logPath)
+ if model, ok := event["model"]; ok && fmt.Sprint(model) != "" {
+ t.Errorf("event.model = %v, want absent -- Qwen's Stop payload has no model to read", model)
+ }
+ if session, ok := event["session"].(map[string]interface{}); !ok || fmt.Sprint(session["id"]) == "" {
+ t.Errorf("event has no session id (%#v); without one the reader cannot recover the model", event["session"])
+ }
+}
diff --git a/cli/beacon/internal/tokens/tokens.go b/cli/beacon/internal/tokens/tokens.go
index 23a5b0e1..68b07c3b 100644
--- a/cli/beacon/internal/tokens/tokens.go
+++ b/cli/beacon/internal/tokens/tokens.go
@@ -358,7 +358,51 @@ func userKey(user schema.UserInfo) string {
}
}
+// modelDeclaration is one point at which a session named its model, kept with the position it was
+// seen at so a later lookup can ask what was in force rather than what was in force last.
+type modelDeclaration struct {
+ order int
+ model string
+}
+
+// sessionModelIndex records every model a session named, in event order. Qwen Code is why it
+// exists: it declares its model on session start and never again, so its Stop payload -- the only
+// event carrying gen_ai.context -- has a session id and no model. Utilization keys its rows on the
+// model, so without this the occupancy Beacon just learned how to record is dropped before the
+// report that wanted it.
+type sessionModelIndex map[sessionContextKey][]modelDeclaration
+
+func sessionModelDeclarations(events []schema.Event) sessionModelIndex {
+ index := sessionModelIndex{}
+ for i, event := range events {
+ model := strings.TrimSpace(event.Model)
+ if model == "" || event.Session == nil || strings.TrimSpace(event.Session.ID) == "" {
+ continue
+ }
+ key := sessionKey(event)
+ if declarations := index[key]; len(declarations) > 0 && declarations[len(declarations)-1].model == model {
+ continue
+ }
+ index[key] = append(index[key], modelDeclaration{order: i, model: model})
+ }
+ return index
+}
+
+// modelAt returns the model the session had named by the given position. Scanning back to the last
+// declaration at or before the event, rather than taking the session's newest one, keeps a session
+// that switched models from having its earlier occupancy attributed to the later one.
+func (index sessionModelIndex) modelAt(key sessionContextKey, order int) string {
+ declarations := index[key]
+ for i := len(declarations) - 1; i >= 0; i-- {
+ if declarations[i].order <= order {
+ return declarations[i].model
+ }
+ }
+ return ""
+}
+
func collectUsageEvents(events []schema.Event, sessionUsers sessionUserIndex) []*usageEvent {
+ sessionModels := sessionModelDeclarations(events)
var out []*usageEvent
for i, event := range events {
// Context-only events count too. A runtime can report how full the window was without
@@ -450,6 +494,14 @@ func collectUsageEvents(events []schema.Event, sessionUsers sessionUserIndex) []
// added to a total by some later path that does not know to check the flag.
ue.contextOnly = true
ue.usage.Events = 0
+ if ue.model == "" && event.Session != nil {
+ // Attribution only, and only here. An event reporting real spend without a model
+ // of its own stays unattributed as it always has: relabelling that would move
+ // other runtimes' spend between models on the strength of a guess. Occupancy has
+ // no such risk -- it is never summed -- and without a model it is not reportable
+ // at all.
+ ue.model = sessionModels.modelAt(sessionKey(event), i)
+ }
}
if event.Raw != nil {
if temporality, _ := event.Raw["metric_temporality"].(string); strings.EqualFold(temporality, "cumulative") {
diff --git a/cli/beacon/internal/tokens/tokens_test.go b/cli/beacon/internal/tokens/tokens_test.go
index 4b3003e0..ef930c5b 100644
--- a/cli/beacon/internal/tokens/tokens_test.go
+++ b/cli/beacon/internal/tokens/tokens_test.go
@@ -567,3 +567,80 @@ func TestUtilizationStillInfersWhenNoContextIsReported(t *testing.T) {
t.Fatalf("utilization = %+v, want the summed 1500", 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)
+ }
+ }
+}