Documentation
¶
Overview ¶
Package rollup is the single write path for events: it stores the event, upserts the session, prices assistant turns, and maintains session_stats / daily_stats / session_files in one transaction, then publishes live frames. Every producer (hookd, ingest, harness) goes through Recorder.Record.
Index ¶
- Constants
- type Batch
- func (b *Batch) Abort()
- func (b *Batch) Due() bool
- func (b *Batch) Exec(fn func(ctx context.Context, q store.Querier) error) error
- func (b *Batch) Flush() (stored, deduped int, err error)
- func (b *Batch) Open() bool
- func (b *Batch) Record(ctx context.Context, ev *event.Event, info SessionInfo) (Result, error)
- type Recorder
- func (r *Recorder) ApplyCorrections(ctx context.Context) (corrected int, err error)
- func (r *Recorder) Batch(ctx context.Context) *Batch
- func (r *Recorder) Exclusive() (release func())
- func (r *Recorder) MarkIdle(ctx context.Context, idleAfter, endAfter time.Duration) error
- func (r *Recorder) PriceUnpriced(ctx context.Context) (priced int, err error)
- func (r *Recorder) RebuildCodexDaily(ctx context.Context, keepFrom time.Time) (rows int, err error)
- func (r *Recorder) Record(ctx context.Context, ev *event.Event, info SessionInfo) (Result, error)
- func (r *Recorder) RefreshCompactionStats(ctx context.Context) (written int, err error)
- func (r *Recorder) RepairForkedTurns(ctx context.Context) (repaired int, err error)
- func (r *Recorder) RepairSessionModels(ctx context.Context) (int, error)
- type Result
- type SessionFrame
- type SessionInfo
Constants ¶
const ( BatchMaxEvents = 512 BatchMaxAge = 50 * time.Millisecond )
Batch limits. A first import of 181k events spent half the daemon's CPU on one transaction per event (F7 in docs/resource-usage-audit-2026-10-18.md); these bound how long one batch holds the write lock, and with it how long a live writer can wait behind it.
const MetaPriceCorrections = "price_corrections"
MetaPriceCorrections records the pricing-table version whose corrections have been applied, so they run once per version rather than on every start.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Batch ¶ added in v0.136.0
type Batch struct {
// MaxEvents and MaxAge override BatchMaxEvents and BatchMaxAge.
MaxEvents int
MaxAge time.Duration
// contains filtered or unexported fields
}
Batch writes many events in one transaction, for importers reading history (the transcript tailer, the Codex importer). Live hook events never go through a batch: they use Record, and an open batch commits and steps aside as soon as one is waiting (Due).
Each event is written under its own savepoint, so an event that fails is undone alone and the batch goes on, exactly as a failed Record would leave the events before it. Nothing is published, and no OnPriced runs, until Flush commits: a rolled-back batch has announced nothing, counted nothing and moved no offset that the caller writes through Exec.
A Batch belongs to one goroutine, and while it is open (between the first write and Flush or Abort) that goroutine must not call Record, which would wait on the lock the batch holds.
func (*Batch) Abort ¶ added in v0.136.0
func (b *Batch) Abort()
Abort rolls back whatever the batch holds. It is safe to call at any time, and after Flush it does nothing.
func (*Batch) Due ¶ added in v0.136.0
Due reports whether the batch should be committed now: it is full, it has held the write lock long enough, or a live writer is waiting for it. Callers check it between units they can resume from (a transcript line).
func (*Batch) Exec ¶ added in v0.136.0
Exec runs fn inside the batch's transaction under its own savepoint, for a write that must commit with the events: a transcript's offset, its title.
func (*Batch) Flush ¶ added in v0.136.0
Flush commits the batch and then publishes what it stored. It returns how many events the commit stored and how many were already there. After a failed commit nothing was stored and nothing is published. The batch can be used again after Flush.
type Recorder ¶
type Recorder struct {
Store *store.Store
Table *cost.Table
Bus *bus.Bus
Log *slog.Logger
// Now is overridable in tests.
Now func() time.Time
// Location decides which calendar day a turn belongs to (daily_stats).
Location *time.Location
// OnPriced is called after a turn has been priced and stored, with the
// daily spend cap as its only caller today.
//
// A hook rather than a direct dependency: the recorder is the write path
// for every event on the machine, and it must not grow a reason to know
// what a spend cap is. It is also called *after* the transaction commits —
// a cap that paused sessions from inside the write path would hold the
// database open while signalling processes.
OnPriced func(ctx context.Context)
// SubscriptionOf names the subscription a transcript path belongs to
// (ADR-048): Claude Code writes a session's transcript under the
// configuration directory it runs with, so a hook or a transcript line
// from under <data dir>/profiles/<id>/ is that subscription's. Nil, or
// "", leaves the session on the Default sign-in.
SubscriptionOf func(transcriptPath string) string
// OnWrite is called as Record begins, before it waits for the database.
// The daemon's idle-time VACUUM holds the write lock for its whole run
// and stands down the moment something is to be recorded, and its
// background steps yield the same way (daemon/compact.go,
// daemon/maintain.go). Set once, before the first Record; must not block.
OnWrite func()
// OnClear is told, after the commit, that session next took over the
// process session prev ran in (a /clear): the terminal Caprock holds
// for prev now serves next (agents.Manager.Follow). Must not block.
OnClear func(next, prev string)
// contains filtered or unexported fields
}
Recorder wires store + pricing + bus.
func (*Recorder) ApplyCorrections ¶ added in v0.64.0
ApplyCorrections reprices the turns the table's `corrections` name, and moves the session and daily totals by the difference in the same transaction.
This is the one place a stored cost changes after the fact, and only for a mistake in our own table (see cost.Correction): a price that really changed keeps the figure it was given when the turn ran. Each turn is priced at the row in force at its own timestamp, as Record would have priced it had the table been right.
Idempotent: a turn already at the corrected figure moves by nothing, so an interrupted pass is finished by the next start.
func (*Recorder) Batch ¶ added in v0.136.0
Batch starts a batch. Nothing is written until the first Record or Exec.
func (*Recorder) Exclusive ¶ added in v0.175.0
func (r *Recorder) Exclusive() (release func())
Exclusive holds every write the recorder makes until release is called: the user-started pack of the database (daemon/pack.go) takes it for its VACUUM. It waits for the write in flight, and an open Batch commits at its next unit because a writer is waiting. Meanwhile each Record and Batch waits here, in memory and on a context nothing cancels, so an event that arrives during the pack is written when it ends rather than failing in SQLite's busy handler after busy_timeout. release must be called once.
func (*Recorder) MarkIdle ¶
MarkIdle flips sessions silent for longer than idleAfter to idle, and sessions silent for longer than endAfter (when > 0) to ended, publishing their new state. Called periodically by the daemon.
func (*Recorder) PriceUnpriced ¶ added in v0.59.0
PriceUnpriced prices the turns stored with no cost because their model was missing from the pricing table, now that the table has a row for it.
This is not repricing. A turn that was priced keeps the figure it was given when it ran — a bump never restates history. A turn with no cost was never given a figure at all; it sat outside every total as "unpriced", and adding the model's row fixed only the turns after it. 5,788 Codex turns on the owner's machine (gpt-6-sol and gpt-6-luna) were in that state. Each is priced at the row in force at its own timestamp, exactly as it would have been had the row existed then, and the session and daily totals take the same amount in the same transaction, so every screen stays consistent with the events.
func (*Recorder) RebuildCodexDaily ¶ added in v0.59.0
RebuildCodexDaily recomputes daily_stats' Codex rows from the Codex events.
Migrations 0022 and 0023 deleted every Codex event and zeroed the per-session totals so the importer could write them again correctly — but left daily_stats alone. The re-import then added each re-read turn to the day it was already in. On the owner's machine that put five days $3.68 and 7.9M tokens above what the events add up to (2025-10-16/17 on gpt-5-codex, three days in August and September on gpt-5.6-sol), in every screen that reads the daily table.
daily_stats cannot simply be rebuilt from events in general: it outlives events that retention has pruned, and its project is the one the turn's own cwd resolved to at the time. For Codex both are knowable — the importer passes the session's cwd, so the project is the session's — which is why this is scoped to Codex, and within Codex:
- a (day, model) that another source also used on that day is skipped, because its row mixes usage this cannot separate;
- a day before keepFrom is skipped, because retention may have pruned its events and rebuilding it would erase real history.
Tokens and cost are rewritten; the session count is left as it is, because daily_sessions never double-counted. Runs once (store.MetaCodexDailyRebuilt).
func (*Recorder) Record ¶
Record stores one event and updates every rollup. It is safe to call from multiple goroutines; the recorder serializes its writers.
The transaction runs on a context that cannot be cancelled, once ctx has been checked (F15 in docs/resource-usage-audit-2026-10-18.md). The SQLite driver starts a goroutine for every statement whose context can be cancelled, so that cancelling can interrupt it; for a write of a few milliseconds that cost more CPU than the statement, and an interrupted write was only ever a lost one. The wait for the lock is still bounded by busy_timeout.
func (*Recorder) RefreshCompactionStats ¶ added in v0.168.0
RefreshCompactionStats keeps compaction_stats current (migration 0077; 03-contracts.md § Compaction stats DDL): a row for every new main-thread boundary, its figures made again under a new pricing table, its cost made when what it needs is known, and the calls since its last pass counted into its saving. Incremental: a row whose session made no call since its last pass costs one index seek, and a row closed by the session's next boundary is settled once it has counted up to it. Run at start (the backfill) and on the daemon's minute tick. It returns how many rows it wrote.
func (*Recorder) RepairForkedTurns ¶ added in v0.68.0
RepairForkedTurns takes the usage and cost of copied assistant turns back out of every total, leaving one row per message id that pays.
`claude --resume <id> --fork-session` writes the parent's history since its last compaction into the fork's transcript under the fork's session id, with the original message ids and usage. Turns are deduped per session, so each copy was stored as a new turn and priced again. On the owner's database one fork held 827 copies, $212.93 counted twice. Record now stores a copy with no usage (store.TurnPaidElsewhere); this repairs what was stored before.
Within each message id the payer is the row with the most tokens — Claude Code zeroes the scalars of the first messages it preserves across a compaction, so a copy can hold less than the original, never more — and the earliest stored on a tie. Every other row keeps its place in its session's timeline with zero tokens and zero cost, and session_stats and daily_stats move by exactly what was taken off, in the same transaction. The turn count is left alone: the row is still a turn in the fork's history.
Idempotent by construction (a second pass finds one row with usage per message id) and run once (store.MetaForkedTurnsRepaired).
func (*Recorder) RepairSessionModels ¶ added in v0.65.0
RepairSessionModels sets each session's model to the one its main thread last ran on, where the stored value says otherwise.
Earlier versions let a subagent's turn overwrite sessions.model, so a session run on Opus whose last subagent ran on Haiku is stored as Haiku — on its card, in the session lists and in the window its context fill is measured against. Recording now keeps the main thread's model (store.SessionPatch.SubagentModel), which repairs nothing already written; this does.
Only sessions with a main-thread turn naming a model are touched. One whose every turn is a subagent's (an OpenCode child session) has nothing better to say than what it holds. Internal turns (a Codex review) are left out, as the write path leaves them out. Runs once (store.MetaSessionModelRepaired).
type Result ¶
type Result struct {
Stored bool // false when the event was a duplicate
Event event.Event
Session store.Session
Stats store.Stats
Priced bool // cost computed for this event
NewFiles int // files touched for the first time by this event
// Replaced is the session a /clear in the same process replaced, when
// this event is the SessionStart that did it; "" otherwise.
Replaced string
}
Result reports what Record did, for callers that need to fan out further.
type SessionFrame ¶
type SessionFrame struct {
Session store.Session `json:"session"`
Stats store.Stats `json:"stats"`
}
SessionFrame is the payload of a "session" live frame.
type SessionInfo ¶
type SessionInfo struct {
Cwd, TranscriptPath, GitBranch, Version, Model string
// PID is the process the session belongs to, when it is known: the shim
// reports its parent, which is Claude Code. Zero means unknown, and an
// unknown pid is why the staleness sweep still exists.
PID int
// Agent names the coding agent this session belongs to. Empty means Claude
// Code, which is what every session was before OpenCode support, and what
// the column defaults to.
Agent string
// ReplacesPID is set when this event starts a session that takes over a
// process already running one — a `SessionStart` whose source is `clear`.
// The sibling it replaces cannot be found by the staleness sweep, because
// they share the live process the sweep uses to judge liveness.
ReplacesPID bool
// Title is the agent's own name for the session, when its source carries
// one (OpenCode). Empty leaves a stored title alone.
Title string
// Subscription is the sign-in the session runs on, when the source knows
// it (a Codex profile's importer); empty asks Recorder.SubscriptionOf.
Subscription string
// Effort is the reasoning effort a main-thread hook named, a known level
// only (hookd.EffortLevel); empty leaves the stored one alone.
Effort string
}
SessionInfo is what a producer knows about the session an event belongs to. Empty fields are "unknown", never overwrite.