Skip to content

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

fix(tokens): read the live cutover from the production readers' context set

Claude4ad1eb58f1f6
diff --git a/cli/beacon/internal/endpoint/dashboard/events.go b/cli/beacon/internal/endpoint/dashboard/events.go
index 3f0ab6eb..c21bab5a 100644
--- a/cli/beacon/internal/endpoint/dashboard/events.go
+++ b/cli/beacon/internal/endpoint/dashboard/events.go
@@ -13,6 +13,7 @@ import (
"time"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/tokens"
"github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
)
@@ -116,10 +117,16 @@ func ReadEventsAppendOrder(path string, query EventQuery) ([]schema.Event, error
return events, nil
}
-// ReadTokenEventsAppendOrder returns query-matched events plus every
-// session.context event in one pass over the log. Session context is kept
-// separate so token totals and TotalEvents still describe only the requested
-// time/model/session slice while user attribution can reach back to SessionStart.
+// ReadTokenEventsAppendOrder returns query-matched events plus the session context
+// the token report reads outside the query, in one pass over the log. Context is
+// kept separate so token totals and TotalEvents still describe only the requested
+// time/model/session slice while session-level facts can reach back past it:
+//
+// - every session.context event, so user attribution reaches back to SessionStart;
+// - for each session and live collection method, the earliest event that arrived
+// over that method (tokens.LiveCaptureKey), so the live/poll cutover is where the
+// live channel started capturing the session rather than where the window starts
+// or where its first usage record landed.
func ReadTokenEventsAppendOrder(path string, query EventQuery) ([]schema.Event, []schema.Event, error) {
result, err := ReadEvents(path, EventQuery{NoLimit: true})
if err != nil {
@@ -128,14 +135,30 @@ func ReadTokenEventsAppendOrder(path string, query EventQuery) ([]schema.Event,
SortRecordsAppendOrder(result.Events)
events := make([]schema.Event, 0, len(result.Events))
contexts := make([]schema.Event, 0)
+ type liveStart struct {
+ ts time.Time
+ event schema.Event
+ }
+ liveStarts := map[string]liveStart{}
+ var liveOrder []string
for _, record := range result.Events {
if record.Event.Event.Action == "session.context" {
contexts = append(contexts, record.Event)
+ } else if key, ts, ok := tokens.LiveCaptureKey(record.Event); ok {
+ if current, seen := liveStarts[key]; !seen {
+ liveStarts[key] = liveStart{ts: ts, event: record.Event}
+ liveOrder = append(liveOrder, key)
+ } else if ts.Before(current.ts) {
+ liveStarts[key] = liveStart{ts: ts, event: record.Event}
+ }
}
if matchesQuery(record, query) {
events = append(events, record.Event)
}
}
+ for _, key := range liveOrder {
+ contexts = append(contexts, liveStarts[key].event)
+ }
return events, contexts, nil
}
diff --git a/cli/beacon/internal/endpoint/dashboard/server_test.go b/cli/beacon/internal/endpoint/dashboard/server_test.go
index 8e66afce..2b5e230e 100644
--- a/cli/beacon/internal/endpoint/dashboard/server_test.go
+++ b/cli/beacon/internal/endpoint/dashboard/server_test.go
@@ -9,6 +9,7 @@ import (
"strconv"
"strings"
"testing"
+ "time"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/diagnostics"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/lifecycle"
@@ -688,3 +689,73 @@ func TestRequireLoopbackHostRejectsRebindingHosts(t *testing.T) {
}
}
}
+
+// TestTokensEndpointCountsALiveAndBackfilledRequestOnce reads a Claude Code session the way the
+// production readers hand it to the token report: matched events plus a reduced context set. The
+// live OTLP channel's first event is the user_prompt log; the transcript stamps the request as it
+// streamed, before the api_request log that reports the same usage lands. The cutover has to come
+// from that first live event, which is neither a session.context row nor a usage record, or the
+// backfilled copy of the session's first request is counted beside the live one.
+func TestTokensEndpointCountsALiveAndBackfilledRequestOnce(t *testing.T) {
+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")
+ line := func(ts, method, action, usage string) string {
+ genAI := ""
+ if usage != "" {
+ genAI = `,"gen_ai":{"usage":` + usage + `}`
+ }
+ return `{"timestamp":"` + ts + `","vendor":"beacon","product":"endpoint-agent","schema_version":"1.0","event":{"kind":"agent_runtime","action":"` + action + `","category":"session"},"severity":"info","endpoint":{"os":"linux","hostname":"devbox"},"harness":{"name":"claude_code","collection_method":"` + method + `"},"session":{"id":"sess-live-poll"},"model":"claude-opus-4-6"` + genAI + `,"message":"` + action + `"}`
+ }
+ lines := []string{
+ line("2026-06-11T10:00:00Z", "otlp", "prompt.submitted", ""),
+ line("2026-06-11T10:00:02Z", "poll", "token.usage", `{"input_tokens":6,"output_tokens":120,"cache_read":{"input_tokens":40000}}`),
+ line("2026-06-11T10:00:06Z", "otlp", "token.usage", `{"input_tokens":6,"output_tokens":120,"cache_read":{"input_tokens":40000}}`),
+ }
+ if err := os.WriteFile(logPath, []byte(strings.Join(lines, "\n")+"\n"), 0644); err != nil {
+ t.Fatalf("write fixture log: %v", err)
+ }
+
+ events, contexts, err := ReadTokenEventsAppendOrder(logPath, EventQuery{NoLimit: true})
+ if err != nil {
+ t.Fatal(err)
+ }
+ report := tokens.AggregateScopedWithContexts(events, contexts, "", tokens.Options{})
+ if report.Totals.OutputTokens != 120 || report.Totals.CacheReadInputTokens != 40000 || report.SuppressedPollEvents != 1 {
+ t.Fatalf("totals = %+v suppressed = %d, want one request (output 120, cache read 40000) and the backfill copy suppressed", report.Totals, report.SuppressedPollEvents)
+ }
+
+ // A window that starts after the live channel's first event must not move the cutover.
+ windowed, windowContexts, err := ReadTokenEventsAppendOrder(logPath, EventQuery{NoLimit: true, Since: mustParseTime(t, "2026-06-11T10:00:01Z")})
+ if err != nil {
+ t.Fatal(err)
+ }
+ report = tokens.AggregateScopedWithContexts(windowed, windowContexts, "", tokens.Options{})
+ if report.Totals.OutputTokens != 120 || report.SuppressedPollEvents != 1 {
+ t.Fatalf("windowed totals = %+v suppressed = %d, want one request", report.Totals, report.SuppressedPollEvents)
+ }
+
+ handler, err := Handler(Options{UserMode: true, LogPath: logPath})
+ if err != nil {
+ t.Fatalf("Handler returned error: %v", err)
+ }
+ rec := httptest.NewRecorder()
+ handler.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/api/tokens", nil))
+ if rec.Code != http.StatusOK {
+ t.Fatalf("status code = %d, body = %s", rec.Code, rec.Body.String())
+ }
+ var served tokens.Report
+ if err := json.Unmarshal(rec.Body.Bytes(), &served); err != nil {
+ t.Fatalf("unmarshal tokens report: %v", err)
+ }
+ if served.Totals.OutputTokens != 120 {
+ t.Fatalf("/api/tokens output = %d, want 120 (the backfill copy counted twice gives 240)", served.Totals.OutputTokens)
+ }
+}
+
+func mustParseTime(t *testing.T, value string) time.Time {
+ t.Helper()
+ parsed, err := time.Parse(time.RFC3339, value)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return parsed
+}
diff --git a/cli/beacon/internal/tokens/tokens.go b/cli/beacon/internal/tokens/tokens.go
index df5ba072..d6660837 100644
--- a/cli/beacon/internal/tokens/tokens.go
+++ b/cli/beacon/internal/tokens/tokens.go
@@ -177,7 +177,7 @@ func aggregate(events []schema.Event, opts Options, contextEvents []schema.Event
opts.NearLimitRatio = defaultNearLimitRatio
}
report := Report{TotalEvents: len(events)}
- usageEvents, suppressed := resolveUsageEvents(events, sessionUserContexts(contextEvents), liveCaptureStarts(contextEvents))
+ usageEvents, suppressed := resolveUsageEvents(events, sessionUserContexts(contextEvents), liveCaptureStarts(contextEvents, events))
report.SuppressedPollEvents = suppressed
byModel := map[string]*Usage{}
@@ -645,26 +645,46 @@ func isLiveCollectionMethod(method string) bool {
// any event arrived over that method -- whether or not the event carried usage.
type liveCaptureIndex map[liveScope]map[string]time.Time
-func liveCaptureStarts(events []schema.Event) liveCaptureIndex {
+// LiveCaptureKey names the (endpoint, harness, session, live collection method) an event marks the
+// start of, and reports false for an event that marks none: one without a session, a parseable
+// timestamp, or a live collection method. The live/poll cutover is the earliest such event per
+// key, so a reader that hands the aggregator a reduced context set (see
+// dashboard.ReadTokenEventsAppendOrder) needs to keep only the earliest event per key, not every
+// live event in the log.
+func LiveCaptureKey(event schema.Event) (string, time.Time, bool) {
+ method := strings.ToLower(strings.TrimSpace(event.Harness.CollectionMethod))
+ if !isLiveCollectionMethod(method) || event.Session == nil {
+ return "", time.Time{}, false
+ }
+ scope, ok := liveScopeFor(event.Endpoint.Hostname, event.Harness.Name, event.Session.ID)
+ if !ok {
+ return "", time.Time{}, false
+ }
+ ts, err := schema.ParseTimestamp(event.Timestamp)
+ if err != nil || ts.IsZero() {
+ return "", time.Time{}, false
+ }
+ return strings.Join([]string{scope.endpoint, scope.harness, scope.session, method}, "\x00"), ts, true
+}
+
+// liveCaptureStarts reads the cutover inputs from every source it is given. aggregate passes both
+// the report's own events and its context events: the context set alone is not enough, because
+// a caller may hand over only session.context rows, and the matched events alone are not enough
+// either, because a time window can start after a session's first live event.
+func liveCaptureStarts(sources ...[]schema.Event) liveCaptureIndex {
index := liveCaptureIndex{}
- for _, event := range events {
- method := strings.ToLower(strings.TrimSpace(event.Harness.CollectionMethod))
- if !isLiveCollectionMethod(method) || event.Session == nil {
- continue
- }
- scope, ok := liveScopeFor(event.Endpoint.Hostname, event.Harness.Name, event.Session.ID)
- if !ok {
- continue
- }
- ts, err := schema.ParseTimestamp(event.Timestamp)
- if err != nil || ts.IsZero() {
- continue
- }
- if index[scope] == nil {
- index[scope] = map[string]time.Time{}
- }
- if current, seen := index[scope][method]; !seen || ts.Before(current) {
- index[scope][method] = ts
+ for _, events := range sources {
+ for _, event := range events {
+ if _, ts, ok := LiveCaptureKey(event); ok {
+ scope, _ := liveScopeFor(event.Endpoint.Hostname, event.Harness.Name, event.Session.ID)
+ method := strings.ToLower(strings.TrimSpace(event.Harness.CollectionMethod))
+ if index[scope] == nil {
+ index[scope] = map[string]time.Time{}
+ }
+ if current, seen := index[scope][method]; !seen || ts.Before(current) {
+ index[scope][method] = ts
+ }
+ }
}
}
return index