dash

package
v0.7.11 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 30, 2026 License: Apache-2.0 Imports: 69 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package dash is context-guru's persistent observability layer: the durable per-request store behind the dashboard, the off-hot-path capture pipeline that fills it, the JSON/SSE API the UI reads, and the embedded single-file UI.

Layering, and why it is boring on purpose:

  • metrics.Aggregator stays the fast in-process counter behind /stats. dash never replaces it and never changes its shape — the benchmark harnesses (deploy/harbor/*.py) parse that payload.
  • Capture is strictly out of band. A request handler builds one Event and hands it to a buffered channel; when the channel is full the event is DROPPED and counted. Observability can never add latency to, or fail, a request — the property gateway gets right and the one worth keeping.
  • One writer goroutine owns the database. It batches inserts in a transaction and fans a summary row out to SSE clients. Nothing else writes.
  • Percentages are derived at read time; COST is computed at write time, so history does not silently reprice when a model's published rate changes.
  • No rollup tables. Time series are bucketed in SQL at query time (ts/bucket*bucket GROUP BY 1). SQLite handles millions of rows; a pre-aggregation layer is the speculative complexity to skip until a query is measurably slow.

The driver is modernc.org/sqlite (pure Go), so a dashboard build needs no C toolchain beyond the one tree-sitter already forces.

Index

Constants

View Source
const (
	FallbackNoResult           = "no_result"                   // no Result attached (no usage, skipped, expand rounds)
	FallbackOpsDropped         = accrec.GateOpsDropped         // a change could not be placed as an operation
	FallbackObserve            = accrec.GateObserve            // the run was observe mode
	FallbackUnpriced           = accrec.GateUnpriced           // no usage or no price for the model, or an operation or effect is unpriced
	FallbackCheckSum           = accrec.GateCheckSum           // the library's sum check failed
	FallbackCheckUniqueChange  = accrec.GateCheckUniqueChange  // two operations share a ChangeID
	FallbackCheckSpans         = accrec.GateCheckSpans         // an operation's spans do not add up to its sizes
	FallbackCheckOther         = accrec.GateCheckOther         // a fatal library check this host has no name for
	FallbackImplausibleSize    = accrec.GateImplausibleSize    // the library saved more message tokens than the request had
	FallbackFigureWithoutRow   = accrec.GateFigureWithoutRow   // a library figure for a component with no row
	FallbackDuplicateName      = accrec.GateDuplicateName      // two rows share a component name
	FallbackActedWithoutFigure = accrec.GateActedWithoutFigure // a component acted and the library has no figure for it
	FallbackServerHeldHistory  = "server_held_history"         // an OpenAI Responses request with server-held history (previous_response_id, conversation, item_reference): the provider holds the history
)

Fallback reasons: why PriceMode booked no saving on an event. AccountantFallback returns one of them ("" when the override applied).

View Source
const (
	UnpricedNoUsage = "no_usage" // the request has no billed token counts (accounting is not complete)
	UnpricedNoPrice = "no_price" // the model has no price
)

Causes behind FallbackUnpriced. They are for the log line only: no stored column and no API field carries them, so a new cause here changes nothing a client can read.

View Source
const (
	// CaptureBlockedByOperator: capture is off service-wide. Nothing the reader can do
	// — telling them to enable their own setting is the bug this field exists to fix.
	CaptureBlockedByOperator = "operator"
	// CaptureBlockedByTenant: the operator allows capture and this account has not
	// opted in. Their own setting, and the one message that should say "turn it on".
	CaptureBlockedByTenant = "tenant"
)

Who has to act when there is no transcript to show. This is a SEPARATE axis from the transcript state, deliberately: the state answers "why is this panel empty" and the answer is the same either way (nothing was captured), while this names the party who can change that. Folding it into the state vocabulary would multiply every empty-panel state by every cause, and the UI needs both facts anyway.

View Source
const (
	TranscriptHot           = "hot"             // content is local; served in this response
	TranscriptCold          = "cold"            // archived — metrics only until a human asks
	TranscriptFetched       = "fetched"         // pulled back from cold storage on this request
	TranscriptNothing       = "nothing_changed" // capture is on and nothing was rewritten
	TranscriptNotCaptured   = "not_captured"    // capture is off, so there is nothing to show
	TranscriptNotPermitted  = "not_permitted"   // someone else's transcript, or an untrusted address
	TranscriptNeverArchived = "never_archived"  // asked for it; it was never uploaded
	TranscriptUnreachable   = "unreachable"     // cold storage is down — the data is safe, try later
	// TranscriptUnknownSession accompanies the 404: no such session for this caller. It
	// carries a state like every other answer so a client has ONE branch on `state`
	// rather than a state machine plus a special case for one status code. It is
	// deliberately the same answer for "never existed" and "belongs to someone else" —
	// a distinguishable 404 confirms other people's session ids.
	TranscriptUnknownSession = "unknown_session"
)

Transcript states. Three of them are the "why is this panel empty" answers, and they are kept apart because they are not the same fact and only one of them is something the person reading can act on: capture is a setting they own, permission is not theirs to change, and cold storage is a button away.

View Source
const (
	// ArchiveContent moved a session's transcripts out. Its metric rows stay local
	// and stay queryable — only the diff view has to reach for cold storage.
	ArchiveContent = "content"
	// ArchiveFull moved the whole session out. Its rows are gone locally; the
	// dashboard shows it from the archive index and fetches on demand.
	ArchiveFull = "full"
)

ArchiveKind names what left the local database.

View Source
const (
	// NextInputWindow is how many of a session's last billed requests set its next-request size.
	NextInputWindow = 10
	// DefaultNextInputTokens is the new input of a next request when the session has no history.
	// It is a user turn plus a tool result, not a ping. The value, 1,000 tokens, is the rounded
	// median of fresh_input + cache_write over a local dashboard sample of billed requests (pings
	// excluded), mostly Anthropic. No OpenAI sample yet.
	DefaultNextInputTokens = 1000
)
View Source
const (
	// EpisodeClosed: the span completed — the session was billed the full 10% more.
	EpisodeClosed = "closed"
	// EpisodeOpen: the window has not closed inside the queried range. Reported so a short
	// query window is distinguishable from a session that stopped.
	EpisodeOpen = "open"
	// EpisodeVoided: the client compacted its own transcript inside the span. The client did the
	// very thing the trigger exists to get ahead of, so the remainder is not comparable to a
	// world where we had not compacted. Counted, never averaged in.
	//
	// No longer produced. A client compaction ends the attribution span, and the credit earned up
	// to it counts (EpisodeClientCompacted). The constant and the group fields stay so the JSON
	// shape does not change under a reader.
	EpisodeVoided = "voided_client_compaction"
	// EpisodeClientCompacted: the client compacted its own transcript inside the span. From that
	// turn on both worlds carry a summarized transcript, so nothing later is ours. What the summary
	// earned BEFORE that turn is real and counts, exactly like a closed span.
	EpisodeClientCompacted = "closed_client_compaction"
)

Episode states. A closed episode is the only one that contributes to a total.

View Source
const (
	// EpisodeRecorded: t0 carried offload.EventSummaryStarted (it commissioned a summary) or
	// offload.EventFreshSummary (the inline path committed one). A fact about that turn.
	EpisodeRecorded = "recorded"
	// EpisodeInferred: t0 acted and carried none of summarize's replay event names, so it must
	// have been a fresh summary. Sound, but it is an inference from an absence, and it is the
	// only way to see episodes from BEFORE the event existed — which is the whole history of the
	// old size-only trigger, and therefore the only available comparison.
	EpisodeInferred = "inferred"
)

Episode provenance. Kept apart and NEVER summed, the same discipline declcredit.go keeps between a measured saving and a modelled one.

View Source
const (
	AccountingComplete = "complete"
	AccountingPartial  = "partial"
	AccountingMissing  = "missing"
)

Token-accounting honesty levels. A request is only `complete` when the provider told us all four token tiers; `partial` means we have content-token counts but no billed usage (so cost is an estimate at best); `missing` means we have neither. The UI must never render a partial row as exact — that is how a dashboard becomes unfalsifiable.

View Source
const (
	CacheHit          = "hit"
	CacheColdStart    = "cold_start"
	CacheTTLExpiry    = "ttl_expiry"
	CachePrefixChange = "prefix_change"
	CacheUnknown      = "unknown"
)

Cache-miss attribution buckets. cold_start is NOT a failure: the first request of a session, or the first for a given model, has nothing to hit. TTL wins ties against prefix_change — a prefix that changed after the cache had already expired was not the cause.

View Source
const (
	// CauseModelChanged: the thread switched model. Each model has its own cache.
	CauseModelChanged = "model_changed"
	// CauseCompactionAfterRewrite: the agent sent an unmodified request (bypass) after
	// context-guru had rewritten earlier turns of the thread. The cache holds the rewritten
	// history. The bypass forwards the original, so the prefix differs.
	CauseCompactionAfterRewrite = "compaction_after_rewrite"
	// CauseBypassFlip: bypass turned on or off with no earlier rewrite to explain it.
	CauseBypassFlip = "bypass_flip"
	// CauseToolsChanged: the tool declarations differ (digest, or count when no digest).
	CauseToolsChanged = "tools_changed"
	// CauseSystemChanged: the system prompt differs (hash, or block count when no hash).
	CauseSystemChanged = "system_changed"
	// CauseEffortChanged: reasoning effort, thinking mode or thinking budget differs.
	CauseEffortChanged = "effort_changed"
	// CauseConcurrent: nothing measured changed and the previous request began less than
	// concurrentGapMs ago. A cache entry is readable only after the first response starts,
	// so parallel sub-agent requests miss. The reason is "unknown", not "prefix_change".
	CauseConcurrent = "concurrent"
	// CauseFirstOnModel: no successful earlier request of the thread ran this model, and the
	// request is short or an earlier one failed. It is not stored as a cause: the reason is
	// cold_start. ObservePrefix returns it so AttributeCache agrees with the thread facts.
	CauseFirstOnModel = "first_on_model"
)

Cache-miss causes (requests.cache_miss_cause). cache_miss_reason keeps its five values for old readers. The cause says WHAT changed, and it comes from a comparison with the previous request of the same thread (see PrefixFacts), never from a guess. Only the first cause that applies is stored, in this order.

View Source
const (
	ReasonBypassed   = "bypassed"      // x-context-guru-bypass on this request
	ReasonNoMessages = "no_messages"   // nothing to operate on
	ReasonAllFrozen  = "cache_frozen"  // eligible tail was empty (cache safety)
	ReasonNoSavings  = "found_nothing" // components ran, found nothing to remove
	ReasonReverted   = "reverted"      // components acted but were all reverted
	// No component mutated anything. These two replace ReasonBelowTrigger, which named a
	// mechanism that was not the cause and cost a whole investigation to disprove:
	// components.Trigger is not consulted in this decision at all, and of the eight
	// components in the default preset only extract_llm ever calls Trigger.Fires. The label
	// nonetheless read "every component's trigger declined", which was reported upward as
	// "$744.62 of spend was gated by the trigger" and sent an agent off tuning triggers whose
	// measured counterfactual on interactive traffic was $0.00.
	//
	// What actually happens, measured over the 7,660 affected requests on the production
	// corpus: every deployed offloader and both JSON reformatters gate on `role == tool`, so a
	// request carrying no tool output has nothing any of them can rewrite, whatever any
	// trigger says. 4,199 of those requests (206.9M tokens, 54.3% of the gated total) carry
	// four messages or fewer and therefore hold no tool_result block at all — the largest
	// single group being 734 claude-cli requests averaging 120,245 tokens with ONE message and
	// ZERO tools, which is Claude Code's own summarisation call flattening a transcript into a
	// single user text block. The rest are long transcripts 65–89% frozen whose eligible tail
	// holds no recognised candidate.
	//
	// So the reason splits in two, on a fact the row already carries:
	ReasonNoToolOutput = "no_tool_output" // the request declared no tools: no tool_result to rewrite
	ReasonNoCandidate  = "no_candidate"   // tools present, nothing any component recognised
	// ReasonBelowTrigger is retained for READING rows written before the rename. Never emitted.
	// The UI labels it with the same words as ReasonNoCandidate so one history does not read as
	// two mechanisms.
	ReasonBelowTrigger = "below_trigger"
)

"Why didn't you compact this?" — a first-class reason bucket, not an absence of data. An empty string means we DID compact.

View Source
const (
	ModeActive  = "active"
	ModeBypass  = "bypass"
	ModeObserve = "observe"
)

Operating modes, as rendered in the UI.

View Source
const (
	// ScopeItem — removable on its own: a standalone skill, a client tool, one MCP tool by name.
	ScopeItem = "item"
	// ScopeServer — the MCP server is the unit. Denying one tool leaves the rest declared.
	ScopeServer = "server"
	// ScopePlugin — the PLUGIN is the unit. `skillOverrides` has no effect on a plugin's skills,
	// verified on real request traffic: the entry was still sent with the override set, while the
	// same override removed a standalone skill entirely. A per-skill instruction here is a line
	// the user pastes that changes nothing, which is worse than no instruction.
	ScopePlugin = "plugin"
	// ScopeNone — not offered at any scope. Claude Code's own built-ins: the weight is real and
	// removing one takes away a capability the model is expected to have.
	ScopeNone = "none"
)

The scope at which a capability can actually be removed. Not a grouping label: these are four different commands with four different blast radii, and picking the wrong one produces an instruction that silently does nothing.

View Source
const (
	// VerdictRemove — unused, removable, and observed long enough to be sure.
	VerdictRemove = "remove"
	// VerdictConsider — unused and removable, but not yet observed long enough. Listed, because
	// the floor gates ADVICE and not disclosure; refusing to recommend is honest, refusing to say
	// what is there is merely unhelpful.
	VerdictConsider = "consider"
	// VerdictKeep — in use, or a built-in. Two different facts, worded apart.
	VerdictKeep = "keep"
	// VerdictStale — it WAS used, it is not any more, and it is still carried on every request.
	//
	// The state the report could not express. A user working three months in one project —
	// planning, then development, now research — has planning skills used heavily in month one
	// and dead since month two. `calls > 0` filed them under keep, alongside a tool invoked a
	// minute ago, so the report never mentioned them.
	//
	// Deliberately NOT solved with a session window. A session is not a unit of time: measured on
	// one real store, spans were 0.0h, 1.1h and 99.1h, with a single session covering four days,
	// so "the last N sessions" is anywhere from minutes to weeks and "the last N days" anywhere
	// from two sessions to sixty. The gap between last-used and last-carried is a property of the
	// item instead, independent of how anybody structures their work, and it is evidence a reader
	// can check against their own memory.
	VerdictStale = "stale"
)

What the reader may be told to do about an item.

View Source
const (
	// PlanWait is the live per-wait plan (keepalive.Policy.WaitPings and the no-tool rule).
	PlanWait = "wait_plan"
	// PlanFixed is one K for every wait: the policy with keepalive_wait_plan off.
	PlanFixed = "fixed_k"
)

The two models a ladder or a recommendation can use for the ping count (#868).

View Source
const (
	KVStrategyNoCache         = kvcache.StrategyNoCache
	KVStrategyFixed5m         = kvcache.StrategyFixed5m
	KVStrategyFixed1h         = kvcache.StrategyFixed1h
	KVStrategyKeepAlive5m     = kvcache.StrategyKeepAlive5m
	KVStrategyKeepAlive5mOnce = kvcache.StrategyKeepAlive5mOnce
	KVStrategyKeepAlive1h     = kvcache.StrategyKeepAlive1h
	KVStrategyKeepAlive1hOnce = kvcache.StrategyKeepAlive1hOnce
	KVStrategyExtend1h        = kvcache.StrategyExtend1h
	KVStrategyObserved        = kvcache.StrategyObserved
	KVStrategyHistorical      = kvcache.StrategyHistorical
	KVStrategyStopReasonGated = kvcache.StrategyStopReasonGated
	KVStrategyStickySession1h = kvcache.StrategyStickySession1h
	KVStrategyKeepAliveBudget = kvcache.StrategyKeepAliveBudget
	KVStrategyOptimal         = kvcache.StrategyOptimal
	// KVStrategyCustom is the one arm that is NOT in kvcache's registry, because it cannot be
	// built from a name: it carries the page's own thresholds and the in-process Predictor
	// seam. It is offered beside the registry's arms and scored identically.
	KVStrategyCustom = "custom"
)

The strategy names the page may ask for.

Every one of them is kvcache's own constant rather than a second spelling of it. The name arrives from a query string and is resolved through kvcache.NewStrategy, so a typo selects nothing rather than something — and there is exactly one list of arms in the process, which is the point: dash used to carry a closed six-name list of its own, and the four arms the domain had gained since (the two keep-alive arms, the extend-to-1h arm and the exact ceiling) were unreachable from the dashboard while looking perfectly present in the code.

View Source
const (
	StateLoaded       = "loaded"
	StateDeferredCG   = "deferred_cg"     // Context Guru's history rule defers it
	StateDeferredCC   = "deferred_client" // Claude Code sends it in its deferred-tools list
	StateRemoved      = "removed"         // on the account's removal list
	SaveMoreToolsKind = "save_more_tools"
)

Tool states on a save-more tools row.

View Source
const (
	CauseColdStart    = "cold_start"      // first request of the session
	CauseIdleExpiry   = "idle_expiry"     // gap since the previous request exceeded the cache TTL
	CauseNewThread    = "new_thread"      // same session, a thread not seen before (subagent, side request, other model, or config change)
	CauseHistory      = "history_rewrite" // message count fell: compaction, rewind or edit
	CausePrefixChange = "prefix_change"   // warm, longer history, still rewritten: tools/system/MCP changed
)

Rewrite causes, ordered roughly by how avoidable they are.

View Source
const (
	// KindTool is a plain client-side tool (Claude Code's built-ins, an agent's own).
	KindTool = config.KindTool
	// KindMCPTool is one tool of an MCP server, named `mcp__<server>__<tool>`; Server
	// carries the server half so a per-server rollup needs no string work at read time.
	KindMCPTool = config.KindMCPTool
	// KindServerTool is a provider-side tool (`web_search_*`, `code_execution_*`,
	// `memory_*`, the `mcp_toolset` connector): declared with a `type` and usually no
	// input_schema, and not removable the way a client tool is.
	KindServerTool = config.KindServerTool
	// KindSkill is one skill from the Skill tool's prose listing.
	KindSkill = config.KindSkill
	// KindSkillListing is ONE marker row per declaration set carrying the listing's own
	// token cost and the PARSE STATE in Server (SkillsOK | SkillsUnknown). It is what
	// keeps a failed parse from reading as "this session declared no skills": with
	// state=unknown there are no KindSkill rows and the reader must say so.
	KindSkillListing = config.KindSkillListing
	// KindSystemPrompt is ONE marker row per distinct system prompt a session carried: name
	// is a hash of the text, tokens is its measured BPE cost, and text_gz holds the prompt
	// itself when consent allows. It is not a declaration, and it lives in this table
	// anyway because it is the same THING as far as every consumer is concerned — a region
	// of the prefix every request re-reads, keyed by session, evicted by the same trigger,
	// scoped by the same tenant_id. A second table would have bought a second eviction path
	// to forget about.
	KindSystemPrompt = "system_prompt"
	// KindDeferredListing is ONE marker row per declaration set whose body carried a deferred
	// tools list that this scan did not read (today: a Responses body, whose transcript is in
	// `input`). Its Server is SkillsUnknown. Like the skills marker, it keeps "not read" from
	// reading as "no deferred tools". It has no name and no weight, and it is not a declaration.
	KindDeferredListing = "deferred_listing"
)

Declaration kinds. They are stored as text because they are read back as labels and grouped on, exactly like `kind` on request_components.

View Source
const (
	// SkillsOK: the header was found and at least one entry parsed.
	SkillsOK = "ok"
	// SkillsUnknown: a listing is present but nothing parsed out of it — a Claude Code
	// version whose format moved. The size is still honest; the inventory is not known.
	SkillsUnknown = "unknown"
)

Skill-listing parse states, stored in the marker row's Server column.

View Source
const (
	// ActiveThreadsWindow is how far back a thread counts as active for Event.ActiveThreads. Ten
	// minutes is two 5-minute cache lifetimes: a subagent that has run longer than that without a
	// request is no longer likely to be what the main thread waits for, and a longer window would
	// count threads that finished long ago. Fixed, so rows stay comparable across installs.
	ActiveThreadsWindow = 10 * time.Minute
)
View Source
const AdaptOfferTTL = 30 * time.Minute

AdaptOfferTTL is how long a report's options can be applied by id.

View Source
const CurrencyMixed = "mixed"

CurrencyMixed is the unit of a view whose priced rows are in more than one currency. Such a view has no money total: Bobcoins and dollars do not add. The UI shows no money figure for it.

View Source
const DayMs int64 = 24 * 60 * 60 * 1000

DayMs is one day of buckets. Per-DAY usage bars are Series with this bucket — the bucketing is done in SQL from the raw ts (see the package comment), so a day-wide bucket needs no new query, no rollup table and no migration, and the "selectable time range" is the Since/Until the filter already carries.

Buckets are UTC days, matching the tenant_spend month key, rather than the viewer's local day. That is a deliberate limitation and not a rounding error: a local-day bucket would make the same row land in different bars for two people reading the same dashboard. ponytail: UTC days; take an offset parameter here if per-viewer local days ever matter.

View Source
const DefaultRemoteTimeout = 5 * time.Minute

DefaultRemoteTimeout bounds a single object transfer. Generous: a large session archive over a slow link is normal, and a spurious timeout means either a retry storm or, worse, a local delete that never had a confirmed upload behind it.

View Source
const DefaultUIPath = "/dashboard/"

DefaultUIPath is where the dashboard UI mounts when a host does not choose otherwise.

Unchanged, and it has to be: it is in this project's README, in every existing bookmark, and in the refusal messages the API already emits. A deployment that never calls SetUIPath sees exactly what it saw before this existed.

View Source
const DeferComponent = accwire.OpToolDefer

DeferComponent is the library's component name for tool deferral: the operator context-guru.tooldefer, which the proxy reports from the bodies (accountant R56). Its figure is the deferral's saving.

View Source
const EndedChangeComponent = accrec.EndedChangeComponent

EndedChangeComponent is the row that carries the break an ended change left behind.

View Source
const FallbackUnrecorded = "unrecorded"

FallbackUnrecorded is requests.acc_fallback on a row written before the column existed whose components say it fell back (backfillAccFallback). Its real reason was not stored. PriceMode never returns it.

View Source
const InteractionComponent = accrec.InteractionComponent

InteractionComponent is the row that carries the interaction on a rescued request (AccFigure.InteractionUSD): counted, and owned by no component.

View Source
const KindEnvelope = "envelope"

KindEnvelope is the CompRow.Kind of a row the accountant override adds: an envelope operator, the ended-change break or the interaction, none of which is a pipeline component.

View Source
const KindMCPServer = "mcp_server"

KindMCPServer is a whole MCP server as one adapt item: every tool of it, none ever called.

View Source
const PricedByAccountant = "accountant"

PricedByAccountant is CompRow.PricedBy on a row the accountant library priced.

View Source
const PricedByNone = "none"

PricedByNone is CompRow.PricedBy on a row of a request the accountant path handled but could not price (a fallback): it books no saving, and the read-time passes must not value it with the legacy rule. Any non-empty PricedBy means the stored split stands as written; only a row written before the switch has it empty.

View Source
const Redacted = redact.Redacted

Redacted is the placeholder written in place of any redacted value. It is deliberately visible: a blank would read as "the field was empty".

View Source
const SourceImported = "imported"

SourceImported marks a row recovered from a Claude Code transcript rather than measured by the proxy. A measured row stores "" — see Event.Source for why.

View Source
const StaleAfter = 14 * 24 * time.Hour

StaleAfter is how long a capability must go unused, while still being carried, before this report will call it abandoned.

Fourteen days, and the number is a judgement rather than a measurement — so it is one constant with its reasoning attached rather than a threshold scattered through the code. Shorter would catch a fortnight's holiday or a two-week spell on one part of a codebase, both of which are normal and neither of which means a tool is finished with. Much longer and a project that changed phase a month ago still shows its old tooling as current, which is the complaint this exists to answer.

It is a floor on the EVIDENCE, not a window on the data: every use is counted however old, and this only decides when a gap is long enough to report.

View Source
const StopTimeoutEstimated = "timeout_estimated"

StopTimeoutEstimated is the stop_reason of a keep-alive ping row that ran to the keeper's ping timeout with no answer (#754). The provider probably billed it, so the row books the keeper's projected cost of one ping, with every token column 0. It counts as keep-alive spend. It is not a refresh (its cache_read is 0, so no refresh probe matches it) and not a cache miss either: nobody knows what the provider did with it.

View Source
const SweepComponent = "extract_llm_sweep"

SweepComponent is the pipeline name of the component this ledger is about.

View Source
const TTLUnrecorded = "unrecorded"

TTLUnrecorded is the filter value and the group key for requests that cached something at a tier NOBODY WROTE DOWN.

It is a fourth group rather than a footnote on the five-minute one, and that is the whole honesty rule of this page applied to its own grouped table. Those rows are REPLAYED as five minutes so a simulation has something to run, but they are not evidence of a five-minute policy — and folding them in said "3,106 of your requests used the 5-minute tier" about a window where 295 of them recorded no tier at all, under a heading that called the group "configured". The coverage banner above it was reporting the same 295 as not recorded, so the page contradicted itself in two panels.

Variables

View Source
var AdaptCompactionCandidates = config.AdaptCandidates()

AdaptCompactionCandidates are the components the search may add, drop, reorder or tune: the shipped deterministic compaction components, in the default pipeline's order. Everything else in an account's pipeline (toolfilter, the LLM components) keeps its place in the applied config and is not run by the replay.

View Source
var CostlyChecks = []CostlyCheck{
	{
		ID: "disable-experimental-betas",
		Shapes: []CostlyShape{

			{ID: "classifier", ModelContains: "sonnet", Tools: ip(0), MaxTokens: ip(64), Stream: ip(0)},
		},
		Also: []CostlyShape{
			{ID: "classifier-stage-2", Tools: ip(0), SystemBlocks: ip(3), MaxTokens: ip(2112), Messages: ip(2)},
		},
	},

	{ID: "session-recap"},
	{
		ID: "small-model-rejects-server-check",

		Shapes: []CostlyShape{
			{ID: "classifier-after-haiku-400", ModelContains: "sonnet", Tools: ip(0), MaxTokens: ip(64), Stream: ip(0),
				SessionHas: &CostlyShape{ModelContains: "haiku", Status: ip(400)}},
		},
	},
}

CostlyChecks is the price side of the plugin's list.

View Source
var ErrPurgeNoTenant = errors.New("dash: refusing to purge with no tenant id")

ErrPurgeNoTenant refuses a purge with no tenant named.

"" is a LEGITIMATE tenant id in this schema — it is what every single-tenant and pre-tenancy row carries — so an empty argument would not be a no-op, it would erase the deployment's own history. A caller reaching here with "" has a bug, and the bug should not be destructive.

View Source
var ErrRemoteMissing = errors.New("dash: object not found in cold storage")

ErrRemoteMissing means the object is not there — distinguishable from a transport failure, because "this session was never archived" and "Box is down" call for very different responses.

KVCacheDefaultStrategies is what the page runs when the caller names none.

Ten arms, and each earns its place: the two bounds (no-cache below, optimal above), the two fixed tiers, the repeated 5-minute keep-alive arm alongside both single-ping counterparts (see KeepAlive.Once), the policy already in force, the one arm that learns from the account's own history, and the stop_reason gate — measured (docs/results/kv-ttl-predictor-arms.md) as the single best-justified change to the shipped mechanism: statistically indistinguishable from a trained model, with no training step at all. `optimal` is in the DEFAULT set on purpose — it is the only figure that says how much headroom exists at all, and an arm nobody sees by default is one nobody compares against — and it is marked Unreachable so no surface can present it as a result.

`keepalive-budget` is the eleventh, and it is in the DEFAULT set rather than merely on the picker because the comparison it belongs in is the one this list already draws: it is the only arm here that spends a DIFFERENT number of pings per conversation, and against the flat keep-alive arms beside it that is the whole question. Measured on 18.4 days of the hosted capture it takes 2.07% off the bill where the best flat arm takes 1.86%, and does it with 8,790 pings against 59,139 — a figure that only means anything read next to those arms, which is what a default set is for. `Config.MaxPings` still bounds it like every other arm: at the page's default of 2 it is capped well below the 8 sweeps it reasons over, and docs/how-to/kv-cache-keepalive-budget.md says what that costs.

View Source
var SummarizerComponents = []string{"summarize", "cache_aware_summarizer"}

SummarizerComponents is THE list of pipeline components whose removals are EARLIER transcript: a summary replaces turns the provider has already been sent. Every place that treats a component as a summarizer (the first-removal rate, the baseline split, the ledger, the cost attribution, the SQL) reads this list and no other. The default preset runs "summarize"; the medium, high and xhigh presets run "cache_aware_summarizer". Add a new summarizer here and nowhere else.

Functions

func AdaptCompactionKnobAllowed added in v0.5.2

func AdaptCompactionKnobAllowed(comp, key string, v int) bool

AdaptCompactionKnobAllowed reports whether comp.key=v is a setting the apply route may store.

func AdaptCompactionMerge added in v0.5.2

func AdaptCompactionMerge(cur, cands []string) []string

AdaptCompactionMerge returns the pipeline to store: cands in their new order, and every other component of cur kept right after the candidate it followed in cur (walking back past candidates the new order drops), so an LLM component stays where its owner put it relative to what remains.

func AdaptConfigHash added in v0.5.2

func AdaptConfigHash(doc string) string

AdaptConfigHash identifies a configuration document; an apply against a document that has changed since the report is refused, because the recommendation was for one that is gone.

func AdaptPresetDoc added in v0.5.2

func AdaptPresetDoc(doc, name string) (string, error)

AdaptPresetDoc is doc switched to a shipped preset: `preset: name` with no explicit pipeline, so the preset decides what runs; every other key is kept. Component blocks the account had stay and win over the preset's own, which is what a stated block means — and why the report prices a preset option on THIS document rather than on the bare preset.

func AdaptPresetDocWith added in v0.5.2

func AdaptPresetDocWith(doc, name string, dropOverrides bool) (string, []string, error)

AdaptPresetDocWith is AdaptPresetDoc, optionally WITHOUT the account's overrides: its own blocks for the preset's compaction components are dropped, so the preset's tuning decides. overrides names the blocks that differ from the preset — the ones dropOverrides removes, and the ones whose presence makes the two documents price differently. Blocks for anything else (the tool removal list, a model component, a component the preset does not run) are kept either way: they are not the preset's to decide.

func ApplySweepLedgerToRow added in v0.6.0

func ApplySweepLedgerToRow(c *ComponentRow, l *SweepLedger)

ApplySweepLedgerToRow puts the ledger on the sweep's component row: the expands charged to it come off its credit and its net, the answer cost sits beside them, and the quality counts are carried. A row that is not the sweep's, or a nil ledger, is left as it was.

func BreakdownDims

func BreakdownDims() []string

BreakdownDims lists the valid dimensions, sorted, for the API's error message and the UI's dimension picker.

func CoverageSeconds

func CoverageSeconds(idleSeconds float64, maxPings int) float64

CoverageSeconds is the window one idle span's pings keep a cache entry alive for.

K*X + TTL, and the trailing TTL is LOAD-BEARING: the last ping is itself a cache READ, and a read refreshes the entry for the provider's full lifetime. Writing K*X instead is the single error that made an earlier analysis of this mechanism wrong by a factor of 4.4, so TestCoverageIncludesTheFinalPingsTTL exists to fail if anyone reintroduces it.

CoverageSeconds is the ACCOUNT-WIDE policy figure and has no row, so it uses the Anthropic default ttlTTL. A figure for one row, whose provider and model are known, is CoverageSecondsFor.

func CoverageSecondsFor added in v0.6.5

func CoverageSecondsFor(idleSeconds float64, maxPings int, ttl time.Duration) float64

CoverageSecondsFor is K*X + ttl for a given cache lifetime. Pass modelinfo.CacheLifetime of the row's provider and model, so a GPT-5.6+ entry is credited its 30 minutes and not 5.

func DefaultWaitPolicy added in v0.6.6

func DefaultWaitPolicy(base int) keepalive.Policy

DefaultWaitPolicy is the shipped keep-alive policy for the replay: the per-wait plan on, with `base` as the base ping count. A host that knows the account's own policy supplies that instead.

func IsBuiltinTool

func IsBuiltinTool(kind, name string) bool

IsBuiltinTool reports whether a KindTool declaration is one of Claude Code's own.

func IsSummarizer added in v0.5.2

func IsSummarizer(component string) bool

IsSummarizer reports whether a component name is on SummarizerComponents.

func NextRequestUSD added in v0.5.3

func NextRequestUSD(p modelinfo.Price, model string, tokens, nextIn, ttlS int64) (warm, cold float64)

NextRequestUSD prices a cached prefix of `tokens` for the NEXT real request: warm is a cache read, cold is a rewrite at the write rate of the tier the cache was written at (2.0x input on the 1h tier; same derivation as accountant.RequestCost). nextIn is the new input that request adds to the prefix (NextInputTokens); it picks the price tier. The dashboard's cache-state view (/api/cachestate) shows both figures, so the "kept warm" figure and the cold figure agree.

The accountant owns the arithmetic: warm is the read of the prefix (PingCost with no fresh input), cold is warm plus the miss (MissCost). The size is the prefix plus the next request's own input, not the size of a ping (keepalive.PingPrompt): it prices the next request, which is what this is. The tier is the entry's own, by its lifetime (ttlS), as the keeper's miss uses the entry's tier.

func PingsPerSpan

func PingsPerSpan(gap, idleSeconds float64, maxPings int) int

PingsPerSpan is how many pings one idle span of `gap` seconds attracts under (X, K). It is kvcache.PingsPerSpan, the one schedule rule, with seconds as the unit.

The first ping fires at X, each subsequent one X after the last, and K caps the count. A gap no wider than X attracts none.

func ProjectPath added in v0.5.4

func ProjectPath(s string) string

ProjectPath sanitizes an agent's launch directory for storage.

THE TRUST BOUNDARY FOR THE PROJECT DIMENSION. A launch directory is a value the CLIENT chose, so it is attacker-influenced in exactly the way redactMeta describes: a request whose working directory happens to be named after a token would otherwise write that token into the requests table and onto the SSE feed, permanently and unredactably.

Same composition as metaEnum — scan for credential shapes, then insist on a shape — against a different shape, since a path is neither short nor an identifier and so cannot reuse metaEnumShape. The order matters and is the same as there: RedactContent first, because a credential embedded in an otherwise path-shaped string must be caught before the shape test passes it.

Returns Redacted rather than "" for a value it refuses. "" already means "this request did not state a project", and a refusal silently collapsing into that would be indistinguishable from the dimension not working — the same reasoning metaEnumShape's comment gives for preferring a visible placeholder.

func PurgeToolDefer added in v0.6.6

func PurgeToolDefer(ctx context.Context, db *sql.DB, tenantID string) (int64, error)

PurgeToolDefer deletes tool deferral's rows for tenant from db: the tool history, and the tenant's thread records and opt-outs in session_state (their keys start with the tenant-scoped session id, "<tenant>:"). A table that does not exist is skipped. Exported for the host, which runs it on tool deferral's own file too.

func RedactConfig

func RedactConfig(v any) any

RedactConfig walks a decoded configuration tree and returns a copy in which only allowlisted keys survive with their values; everything else is replaced by the placeholder. Maps and slices are walked; scalars are passed through.

func RedactContent

func RedactContent(s string, cap int) string

RedactContent scrubs credential-shaped substrings from captured transcript text and caps its length. cap<=0 means no cap. The cap is applied AFTER scrubbing so a secret near the end cannot survive by being truncated into place.

func SetKVCacheMaxRows added in v0.5.2

func SetKVCacheMaxRows(n int) (restore func())

SetKVCacheMaxRows lowers the row cap for a test in another package and returns the restore. It changes a global: not for parallel tests.

func SplitMCPName

func SplitMCPName(name string) (server, tool string, ok bool)

SplitMCPName splits an MCP tool name into its server and tool halves. `mcp__<server>__<tool>`, non-greedy on the server: real tool names contain `__` (mcp__plugin_context7_context7__resolve-library-id), and there is no escape for a server whose own name does — that case splits at the first delimiter and is reported as the server it looks like, which is the only choice the convention leaves.

Types

type API

type API struct {
	// contains filtered or unexported fields
}

API serves the dashboard: the JSON endpoints, the SSE stream, and the embedded UI. It holds only read access to the store plus the recorder's counters — it never writes a request row.

func NewAPI

func NewAPI(rec *Recorder) *API

NewAPI builds the HTTP surface for a recorder. Malformed CIDRs are skipped with no error: a typo in a trust list must not stop the proxy, and the failure mode (loopback-only) is the safe one.

func (*API) AdaptOffer added in v0.5.2

func (a *API) AdaptOffer(kind, tenantID, basis, id string) (any, bool)

AdaptOffer returns option id of the report basis offered this account, while it is fresh.

func (*API) InvalidateStateCaches added in v0.5.3

func (a *API) InvalidateStateCaches(kind string)

cachedRoute puts the stale-while-revalidate response cache (serveJSON) in front of a handler that does not have one of its own. The handler is unchanged: it runs once per key against a recorder, under serveJSON's detached, separately bounded context, and its 200 body is what is cached and shared. Anything else it answers (a 400, a 500) is passed through and not cached.

Every route wrapped this way was a cold 2-60 s read of the whole window that the UI re-issues on each tab switch and on its five-minute refresh; none of them existed in a cache before, so a reader paid the full price every time. The key is the caller's principal plus the full query string (cacheKey), so two accounts never share a body, and the path, so two routes never do. InvalidateStateCaches drops cached reads that include state a user can edit, so a change shows on the next load instead of after the stale window. kind is the tenant package's ChangeAccount (an account's configuration, which holds the tool and skill removal list) or ChangeStrategy (keep-alive strategies and campaigns). Read-only aggregates (stats, series, sessions) are left to the stale-while- revalidate path: nothing a user can edit appears in them.

func (*API) Mount

func (a *API) Mount(m *http.ServeMux)

Mount registers every dashboard route on a mux under the given prefix (typically "/dashboard" for the UI and "/api" for the data).

func (*API) MountTools

func (a *API) MountTools(m *http.ServeMux)

MountTools registers the inventory routes. Separate from Mount only to keep this feature additive to the API surface; a caller mounts both.

func (*API) OfferAdapt added in v0.5.2

func (a *API) OfferAdapt(kind, tenantID string, opts map[string]any) string

OfferAdapt records a report's options for one account under a fresh basis id, which it returns for the report's basis_id. It replaces that account's previous report of the same kind. Shared by every /api/adapt/* kind: an apply may only name an option a report just offered.

func (*API) SetAdaptCompactionConfig added in v0.5.2

func (a *API) SetAdaptCompactionConfig(fn AdaptCompactionConfigFunc)

SetAdaptCompactionConfig wires the config read the adapt report needs; dash holds no tenant config.

func (*API) SetAuth

func (a *API) SetAuth(fn Authenticator)

SetAuth turns on hosted-mode scoping. Once set, every data route requires a principal and every query is scoped to it.

func (*API) SetKeepAlivePlans added in v0.5.1

func (a *API) SetKeepAlivePlans(fn func(tenantID string, allTenants bool, session string) map[string]KeepAlivePlan)

SetKeepAlivePlans supplies the keeper's per-thread plan for one session, keyed by thread id. dash holds no keep-alive state of its own; nil means no plan is ever shown.

func (*API) SetOneHourTouches added in v0.7.5

func (a *API) SetOneHourTouches(fn func(tenantID string, allTenants bool, session string) map[string]OneHourTouch)

SetOneHourTouches supplies the keeper's per-thread 1-hour-ping facts for one session, keyed by thread id. dash keeps none of its own; nil means the clock is never lengthened.

func (*API) SetPingStates added in v0.5.4

func (a *API) SetPingStates(fn func(tenantID string, allTenants bool, session string) map[string]PingState)

SetPingStates supplies, per thread of one session, whether the keeper holds what a manual ping needs and why not when it does not. dash keeps no keep-alive state; nil means it is never stated.

func (*API) SetPricer

func (a *API) SetPricer(p modelinfo.Pricer)

SetPricer supplies the model rates, which the DB layer deliberately does not hold: the pre-instrumentation split figure is the one number that has to be priced at READ time, because the rows it values were written before there was anything to price. nil leaves that figure absent rather than zero — an unpriced number must not read as "nothing was saved".

func (*API) SetTenantCapture

func (a *API) SetTenantCapture(fn func(tenantID string) bool)

SetTenantCapture supplies the per-tenant half of the content-capture decision, read fresh on every request because a tenant can toggle its consent at any time.

Without it the dashboard reported the PROCESS-GLOBAL flag as if it were the answer: "captured" to an account that never consented, and "not captured" — phrased as a setting the reader should go and turn on — when the operator's service-wide gate was the thing that was off. Left nil in single-tenant mode, where there is no second gate.

func (*API) SetToolFilterState

func (a *API) SetToolFilterState(fn func(tenantID string) ToolFilterState)

SetToolFilterState supplies the caller's removal configuration. dash holds no tenant configuration of its own — the host owns it, validates it and audits changes to it — so this is a read hook rather than a store. Unset means "no per-account configuration on this deployment": the analysis is still served and the control reports itself unavailable.

The WRITE path is deliberately not here. It is the compaction configuration, so it goes through the control plane's existing account-update path, where validation, the audit trail and manager gating already live; a second writer would be a second set of rules.

func (*API) SetUIPath added in v0.2.0

func (a *API) SetUIPath(prefix string)

SetUIPath serves the dashboard UI at a different prefix.

WHY A HOST NEEDS THIS. The prefix used to be written into the route table, the bare-path redirect and the sign-in refusal, so a deployment serving the dashboard anywhere else had to fork dash/api.go — and forking a file to change a string is how a deployment ends up maintaining a copy of the whole package.

IT MOVES THE MOUNT, IT DOES NOT ADD ONE. The default prefix stops existing: a host that chooses its own path gets exactly one, and the old one 404s. That is deliberate — two live prefixes for one page means a bookmark, a runbook and a link each naming a different URL, and no way to tell which is canonical. A host that wants the old path to redirect can register that itself in three lines; a host that wants it gone gets that by default.

It must be called BEFORE Mount, and it is not safe once serving: the route table is read at mount time, and a prefix that changed underneath a running mux would leave the redirect and the mount disagreeing. Panics on a path that is not rooted and slash-terminated, because a half-formed prefix produces a dashboard whose relative asset references resolve one directory up — a blank page with no error, materially harder to diagnose than a panic at startup.

The UI itself is prefix-agnostic by construction: index.html and the scripts reference siblings relatively, /api/* is a sibling of the mount rather than a child, and the asset-version rewriter matches bare quoted names. So moving the mount needs no change to any asset.

func (*API) SetWaitPolicy added in v0.6.6

func (a *API) SetWaitPolicy(fn func(tenantID string) keepalive.Policy)

SetWaitPolicy supplies an account's per-wait ping plan settings (keepalive_wait_plan and its three counts) for the calculator and the recommendation. dash holds no tenant configuration of its own, so the host answers. nil: the shipped plan, on.

func (*API) SetWhoami

func (a *API) SetWhoami(fn func(*http.Request) any)

SetWhoami supplies the body for /api/whoami, the UI's mode probe.

func (*API) SetWindows added in v0.2.0

func (a *API) SetWindows(r modelinfo.Resolver)

SetWindows supplies the context-window resolver, for the views that ask how FULL a context got rather than what it cost. Separate from SetPricer for the reason the fields are separate.

func (*API) ToolFilterDocument

func (a *API) ToolFilterDocument(r *http.Request) (*ToolFilterDoc, error)

ToolFilterDocument builds the removal control document for a request's own scope. Exported because the control plane's write route answers with it too: a switch must repaint from the same document it would have read, and two builders would drift.

type AccEffectTokens added in v0.7.2

type AccEffectTokens struct {
	KeepAlive  TokenFlow `json:"keepalive"`    // rescue effects (keepalive_saved_usd)
	TTL        TokenFlow `json:"ttl"`          // head-TTL premium and rescue (on the headttl row's dollars)
	EndedBreak TokenFlow `json:"ended_change"` // the ended-change break (on the ended_change row's dollars)
}

AccEffectTokens is a request's cache effects in tokens: the ones no component row carries.

type AccFigure added in v0.7.0

type AccFigure struct {
	ByComponent map[string]float64 // net of the break each component caused
	// ByComponentFirst and ByComponentReplay split each component's SAVED tokens by tier: the write
	// and input tiers (content the provider had not cached: a first removal) and the read tier (a
	// replay of content in the cached prefix). ByComponent minus both is its costs (Caused, breaks).
	ByComponentFirst, ByComponentReplay map[string]float64
	// DeltaUSD is the sum of ByComponent plus EndedBreakUSD and InteractionUSD. It excludes
	// UnattributedBreakUSD, KeepAliveSavedUSD and TTLUSD.
	DeltaUSD          float64
	KeepAliveSavedUSD float64 // rescue effects
	TTLUSD            float64 // headttl effects: premium (negative) plus rescue: the headttl row
	// EndedBreakUSD is the break a change left behind when it ended (accountant design §5.2 row 1,
	// Q12): it has no ChangeID, so no component owns it, but the client body would have read that
	// prefix, so it is part of the bill difference. Negative: a cost.
	EndedBreakUSD float64
	// InteractionUSD is the value of the tokens no operation owns on a rescued request (accountant
	// design §6.2): Result.Interaction minus Result.InteractionCaused, both at the size without
	// context-guru. A ping kept the cache warm and an operation changed the body, so the client body
	// would have written these tokens cold and the request read them. Neither the keeper nor the
	// operation owns them. Counted, owned by no component: the interaction row (InteractionComponent).
	// The metrics book the same figure as llm.savings.interaction.usd. Signed: positive saves.
	InteractionUSD float64
	// UnattributedBreakUSD is the breaks the client body has too (InBaseline: client edits, expired
	// caches, entries lost early): shown, never counted, never charged to a component.
	UnattributedBreakUSD float64
	Unpriced             []string // "opID:reason"; an unpriced operation is not a zero saving
	Estimated            bool     // any counted operation or effect is an estimate, or a rate the pricer used

	// Fig is the library's own figure, before the mapping above. The held floor reads it.
	Fig accountant.USDFigure

	// The same figures as tokens by tier, before any pricing (#998). TokByComponent follows exactly
	// the attribution of ByComponent: the counted operations and the breaks and mark legs each
	// component owns. It does NOT hold the head-TTL legs or the ended-change break, which accOverride
	// adds to the dollar rows afterwards: those are TokTTL and TokEndedBreak. So the component tokens
	// and the four effect figures never overlap. For each, the dollar figure is
	// tierUSD(Saved) - tierUSD(Caused).
	TokByComponent map[string]TokenFlow
	TokKeepAlive   TokenFlow // rescue effects
	TokTTL         TokenFlow // ttlPremium and ttlRescue effects
	TokEndedBreak  TokenFlow // the break an ended change left behind
}

AccFigure is the request's savings in dollars, from the library's tokens. Only dollars are summed; token tiers are never collapsed into one total.

type AccTokenStats added in v0.7.2

type AccTokenStats struct {
	// Saved and Caused are the sums over every feature below, by tier.
	Saved  TierTokens `json:"saved"`
	Caused TierTokens `json:"caused"`
	// ByFeature is one entry per compaction component (its request_components rows), plus the
	// request-level effects: keepalive (the rescue), ttl (the head-TTL legs) and ended_change (the break an
	// ended change left behind). Tool filter and deferral are components (toolfilter, tooldefer)
	// when the library prices them. Features with no tokens are left out. The lean read has no
	// by_feature at all (absent, not empty): only the full read has the breakdown.
	ByFeature map[string]TokenFlow `json:"by_feature,omitempty"`
}

AccTokenStats is /api/stats' `tokens` object: the accountant's figures in tokens, for the period.

type AccTokensRead added in v0.7.2

type AccTokensRead struct {
	Tokens AccTokenStats
	// Unmeasured is the agent requests the library did not price (acc_priced = 0).
	Unmeasured int64
	// Ping is what the cache strategy's keep-alive pings paid, in billed tokens by tier (the ping
	// rows' own usage, not a library figure), and PingOutput their output tokens. Not in Tokens: a
	// ping is not agent traffic. The keep-alive's net in tokens is ByFeature["keepalive"] less Ping.
	Ping       TierTokens
	PingOutput int64
}

AccTokensRead is DB.AccTokens' answer: the tokens object and the facts beside it.

type AccountGaps

type AccountGaps struct {
	Tenant   string  `json:"tenant"`
	N        int64   `json:"n"`
	MeanHrs  float64 `json:"mean_hours"`
	MedHrs   float64 `json:"median_hours"`
	MaxHrs   float64 `json:"max_hours"`
	Coverage bool    `json:"has_gaps"`
}

AccountGaps is panel 3d: how long between one account's own TTL expiries.

Reported PER ACCOUNT and never blended. There is no service-wide "usually": per-account means run 0.64 h to 6.56 h with maxima to 30 h, so a single mean across a 10x spread would be a number that describes nobody.

type AdaptCompactionChoice added in v0.5.2

type AdaptCompactionChoice struct {
	// Preset, when set, is a shipped preset to switch to; Candidates and Settings are then unused.
	// DropOverrides lists the account's own blocks the switch removes ("<preset> without your
	// overrides").
	Preset        string
	DropOverrides []string
	Candidates    []string
	Settings      map[string]map[string]int
	Label         string
	// ConfigHash is AdaptConfigHash of the document the report was computed against.
	ConfigHash string
}

AdaptCompactionChoice is what applying an option stores: the candidates in their order and the searched settings. The report hands these out under short ids, and the apply route takes only an id from a report the same account just fetched (see API.AdaptOffer).

type AdaptCompactionConfigFunc added in v0.5.2

type AdaptCompactionConfigFunc func(tenantID string) (current, def string, ok bool, reason string)

AdaptCompactionConfigFunc returns a tenant's stored config document and the service default. ok=false means the proxy cannot say (no accounts), and reason is shown.

type AdaptCompactionCoverage added in v0.5.2

type AdaptCompactionCoverage struct {
	Requests            int     `json:"requests"`
	Sessions            int     `json:"sessions"`
	BilledUSD           float64 `json:"billed_usd"`
	RequestsWithContent int     `json:"requests_with_content"`
	SessionsWithContent int     `json:"sessions_with_content"`
	// CoveredRequests are requests with content, complete token accounting and known rates:
	// the population every dollar figure is over. CoveredBilledUSD is what they cost.
	CoveredRequests  int     `json:"covered_requests"`
	CoveredBilledUSD float64 `json:"covered_billed_usd"`
	// Blocks are distinct stored blocks; ClippedBlocks could not be run and are modelled from
	// their stored sizes (see adaptBlock.modelled). The token
	// figures are the same split in original tokens.
	Blocks             int   `json:"blocks"`
	ClippedBlocks      int   `json:"clipped_blocks"`
	BlockTokens        int64 `json:"block_tokens"`
	ClippedBlockTokens int64 `json:"clipped_block_tokens"`
	RequestsOverCap    int   `json:"requests_over_cap"`
	TruncatedToRecent  bool  `json:"truncated_to_recent,omitempty"`
	SearchRequests     int   `json:"search_requests"`
	ArchivedSessions   int   `json:"archived_sessions"`
	FidelityBlocks     int   `json:"fidelity_blocks"`
	FidelityReproduced int   `json:"fidelity_reproduced"`
	ArmsEvaluated      int   `json:"arms_evaluated"`
	// ObservedUSD is the savings to date with the configuration the account ran: every priced
	// request in the window (stored content or not), each component's booked token counts
	// re-priced at the replay's rates. ObservedRequests is how many requests that is.
	ObservedUSD         float64            `json:"observed_usd"`
	ObservedRequests    int                `json:"observed_requests"`
	ObservedByComponent map[string]float64 `json:"observed_by_component,omitempty"`
	DurationMs          int64              `json:"duration_ms"`
}

AdaptCompactionCoverage says how much of the window the dollar figures stand on.

type AdaptCompactionMeasured added in v0.5.2

type AdaptCompactionMeasured struct {
	Component   string  `json:"component"`
	MeasuredUSD float64 `json:"measured_usd"`
	ReplayedUSD float64 `json:"replayed_usd"`
}

AdaptCompactionMeasured is one current component's saving, measured and replayed.

type AdaptCompactionOption added in v0.5.2

type AdaptCompactionOption struct {
	// ID is short ("current", "default", "none", "c1"...), so the plugin can put it on a command
	// line; Label and Pipeline say what it is.
	ID     string `json:"id"`
	Label  string `json:"label"`
	Detail string `json:"detail,omitempty"`
	// BilledUSD is the replayed cost of the covered requests under this option.
	BilledUSD float64  `json:"billed_usd"`
	SavedUSD  float64  `json:"saved_usd"`
	SpendUSD  float64  `json:"spend_usd"`
	NetUSD    *float64 `json:"net_usd"`
	// Unavailable says why NetUSD is null.
	Unavailable string `json:"unavailable,omitempty"`
	// Pipeline is the full pipeline that would be stored: the candidate components in the
	// option's order with the account's other components kept where they were.
	Pipeline []string `json:"pipeline"`
	// UnseenUSD is the part of BilledUSD charged for measured savings the replay cannot see,
	// from current components this option drops (see adaptPop).
	UnseenUSD float64 `json:"unseen_usd"`
	// Busts counts covered requests on which this option rewrote content it had already sent.
	Busts int `json:"busts"`
	// Preset names the shipped preset this option is, or is empty.
	Preset string `json:"preset,omitempty"`
	// RangeUSD brackets NetUSD where the replay is uncertain: the low end is NetUSD itself (every
	// conservative assumption kept), the high end credits what the replay is known to miss — the
	// charge for unseen savings refunded, and any gain over the current configuration scaled up
	// by the share of the current configuration's booked savings the replay reproduces.
	RangeUSD [2]float64 `json:"range_usd"`
	// NotReplayed are the option's model-calling components: excluded from its figure, which is
	// then Class "estimate" rather than "counterfactual", and Detail says what was left out.
	NotReplayed []string `json:"not_replayed,omitempty"`
	Class       string   `json:"class"`
	// DropsOverrides are the account's own component settings applying this option removes.
	DropsOverrides []string `json:"drops_overrides,omitempty"`
	// ExpandUSD is the expand round trips this option avoids (negative) by carrying no offloader.
	ExpandUSD float64 `json:"expand_usd,omitempty"`
	// contains filtered or unexported fields
}

AdaptCompactionOption is one priced configuration, in the plugin's adapt contract (docs/plugin/adapt.md): saved is versus no deterministic compaction at all, spend is the expand declaration the option carries on top of that, net = saved - spend.

type AdaptCompactionRecommendation added in v0.5.2

type AdaptCompactionRecommendation struct {
	Option      string  `json:"option"`
	Change      string  `json:"change"`
	NetDeltaUSD float64 `json:"net_delta_usd"`
	PerMonthUSD float64 `json:"per_month_usd"`
	PerWeekUSD  float64 `json:"per_week_usd"`
	Effective   string  `json:"effective"`
	Reason      string  `json:"reason"`
	// GainUSD is NetDeltaUSD's basis restated: the covered requests, the options' own pricing.
	// GainWindowUSDEst scales it to the whole window by the share of the observed savings those
	// requests carry — an estimate, and labelled one.
	GainUSD          float64    `json:"gain_usd"`
	GainWindowUSDEst float64    `json:"gain_window_usd_est"`
	GainRangeUSD     [2]float64 `json:"gain_range_usd"`
}

AdaptCompactionRecommendation is the change the report proposes, when there is one.

type AdaptCompactionReport added in v0.5.2

type AdaptCompactionReport struct {
	Kind    string `json:"kind"`
	Version int    `json:"version"`
	Summary string `json:"summary"`
	// Window's sessions and requests are the COVERED ones, the population every figure is over;
	// Coverage has the whole window.
	Window struct {
		Since    int64 `json:"since"`
		Until    int64 `json:"until"`
		Sessions int   `json:"sessions"`
		Requests int   `json:"requests"`
	} `json:"window"`
	Class          string                         `json:"class"`
	Method         string                         `json:"method"`
	BasisID        string                         `json:"basis_id"`
	Current        string                         `json:"current"`
	Default        string                         `json:"default"`
	Best           string                         `json:"best"`
	Options        []AdaptCompactionOption        `json:"options"`
	Recommendation *AdaptCompactionRecommendation `json:"recommendation"`
	Observed       AdaptObserved                  `json:"observed"`
	ToDate         AdaptToDate                    `json:"to_date"`
	Reproduction   AdaptReproduction              `json:"reproduction"`
	Warnings       []string                       `json:"warnings"`
	Coverage       AdaptCompactionCoverage        `json:"coverage"`
	Pricing        string                         `json:"pricing"`
	// Measured is each current candidate component's saving on the covered requests, as the
	// product's own accounting booked it and as the replay sees dropping it.
	Measured []AdaptCompactionMeasured `json:"measured"`
	// contains filtered or unexported fields
}

AdaptCompactionReport is GET /api/adapt/compaction's body: the plugin's adapt contract, plus the coverage and the per-component measurement it rests on.

type AdaptObserved added in v0.5.2

type AdaptObserved struct {
	USD         float64                   `json:"usd"`
	Requests    int                       `json:"requests"`
	ByComponent []AdaptCompactionMeasured `json:"by_component"`
	Basis       string                    `json:"basis"`
}

AdaptObserved is the savings to date with the configuration the account ran.

type AdaptReproduction added in v0.5.2

type AdaptReproduction struct {
	ReplayedUSD  float64 `json:"replayed_usd"`
	ObservedUSD  float64 `json:"observed_usd"`
	ErrorPct     float64 `json:"error_pct"`
	TolerancePct float64 `json:"tolerance_pct"`
	OK           bool    `json:"ok"`
	Requests     int     `json:"requests"`
	Note         string  `json:"note"`
}

AdaptReproduction is the accuracy check every recommendation stands on: the replay of the CURRENT configuration against what the account's own rows booked for it, on the same covered requests and the same pricing. A replay that does not reproduce the history is not trusted.

type AdaptToDate added in v0.5.2

type AdaptToDate struct {
	SavedUSD float64 `json:"saved_usd"`
	Since    int64   `json:"since"`
	Until    int64   `json:"until"`
	Class    string  `json:"class"`
	Label    string  `json:"label"`
}

AdaptToDate is the plugin's one-line "what your current config saved so far".

type AdaptToolsCoverage added in v0.5.2

type AdaptToolsCoverage struct {
	Sessions         int `json:"sessions"`           // sessions with a tools>0 request
	SessionsCaptured int `json:"sessions_captured"`  // ... of which have a stored inventory
	Requests         int `json:"requests"`           // tools>0 requests
	RequestsMapped   int `json:"requests_mapped"`    // ... matched to a declaration set
	RequestsExact    int `json:"requests_exact"`     // ... of which by their recorded digest
	RequestsGuessed  int `json:"requests_ambiguous"` // ... of which had 2+ same-count candidate sets
	RequestsUnpriced int `json:"requests_unpriced"`  // mapped, but incomplete token accounting
}

AdaptToolsCoverage says how much of the scope could answer the question.

type AdaptToolsDoc added in v0.5.2

type AdaptToolsDoc struct {
	Kind           string                    `json:"kind"`
	Version        int                       `json:"version"`
	Summary        string                    `json:"summary"`
	Window         AdaptToolsWindow          `json:"window"`
	Class          string                    `json:"class"`
	Method         string                    `json:"method"`
	MethodDetail   string                    `json:"method_detail"`
	BasisID        string                    `json:"basis_id"` // set by the handler: the offer id apply must send
	Current        string                    `json:"current"`
	Default        string                    `json:"default"`
	Best           string                    `json:"best"`
	Options        []AdaptToolsOption        `json:"options"`
	Recommendation *AdaptToolsRecommendation `json:"recommendation"`
	Warnings       []string                  `json:"warnings"`
	Coverage       AdaptToolsCoverage        `json:"coverage"`
	// SavedSoFar is what removals already made have saved (measured); WouldAddUSD what the
	// recommended change would add on top of it (estimated, net of its one-off rewrite).
	SavedSoFar  AdaptToolsSaved `json:"saved_so_far"`
	WouldAddUSD float64         `json:"would_add_usd"`
	// PaybackWeeks is how many weeks of saving the recommended-set removal's one-off cache rewrite
	// costs; null when there is no such set or no week of history to rate it by.
	PaybackWeeks *float64 `json:"payback_weeks"`
	// ToDate and Removed are SavedSoFar in the shared renderer's shape.
	ToDate  *AdaptToolsToDate      `json:"to_date"`
	Removed []AdaptToolsRemovedRow `json:"removed"`
	// RewriteUSD is the one-off cost of removing anything: the next request re-writes the
	// cached prefix instead of reading it. Priced on the latest priced request in scope (its
	// whole prompt, at write minus read), which is the most it can cost a session.
	RewriteUSD float64 `json:"rewrite_usd"`

	Items    []AdaptToolsItem `json:"items"`
	TotalUSD float64          `json:"total_usd"`
	TotalLow float64          `json:"total_usd_low"`
	TotalHi  float64          `json:"total_usd_high"`
	Excluded []string         `json:"excluded"`
	Filter   AdaptToolsFilter `json:"filter"`
	// contains filtered or unexported fields
}

AdaptToolsDoc is the /api/adapt/tools response.

type AdaptToolsFilter added in v0.5.2

type AdaptToolsFilter struct {
	Enabled bool     `json:"enabled"`
	Removed []string `json:"removed"`
	Reason  string   `json:"reason,omitempty"`
}

AdaptToolsFilter is the caller's current toolfilter removal list.

type AdaptToolsItem added in v0.5.2

type AdaptToolsItem struct {
	Kind   string `json:"kind"` // mcp_server | mcp_tool | skill
	Name   string `json:"name"`
	Server string `json:"server,omitempty"`
	// Tools is how many tools an mcp_server item declares (the most seen in one set).
	Tools int `json:"tools,omitempty"`
	// Tokens is the weight on ONE request that carried it (the largest seen).
	Tokens   int   `json:"tokens"`
	Sessions int   `json:"sessions"`
	Requests int   `json:"requests"`
	FirstTS  int64 `json:"first_ts"`
	LastTS   int64 `json:"last_ts"`
	// USD = USDCacheRead + USDCacheWrite + USDInput: the item's tokens at the tier each carrying
	// request was billed at. USDLow/USDHigh bound it over every same-count set an inferred
	// request could have carried; equal to USD when every request recorded its digest.
	USD           float64 `json:"usd"`
	USDLow        float64 `json:"usd_low"`
	USDHigh       float64 `json:"usd_high"`
	USDCacheRead  float64 `json:"usd_cache_read"`
	USDCacheWrite float64 `json:"usd_cache_write"`
	USDInput      float64 `json:"usd_input"`
	// Priced is false when some carrying request's model had no known rates.
	Priced bool `json:"priced"`
	// Sufficient: declared in at least suggestMinSessions sessions spanning suggestMinSpan, the
	// bar the declaration filter's own suggestions are held to.
	Sufficient bool   `json:"sufficient"`
	RemoveAs   string `json:"remove_as"` // the toolfilter `remove` entry; "" when ClientOnly
	// ClientOnly: a deferred MCP server or tool, which the proxy filter cannot remove. Listed with
	// its client change and left out of every filter option.
	ClientOnly bool   `json:"client_only,omitempty"`
	Suggest    string `json:"suggest"` // the client-side change that stops sending it
	// Remove is the same change for the shared /context-guru:adapt renderer, and LastUsedMS is
	// always null: every item here is unused in the window.
	Remove     string `json:"remove"`
	LastUsedMS *int64 `json:"last_used_ms"`
	// Basis states what "unused" rests on: the observed window, never a promise about later.
	Basis string `json:"basis"`
}

AdaptToolsItem is one removable declaration with what carrying it cost.

type AdaptToolsOption added in v0.5.2

type AdaptToolsOption struct {
	ID       string  `json:"id"`
	Label    string  `json:"label"`
	Detail   string  `json:"detail,omitempty"`
	SavedUSD float64 `json:"saved_usd"`
	SpendUSD float64 `json:"spend_usd"`
	NetUSD   float64 `json:"net_usd"`
	// Remove is the toolfilter entries the option adds (or, for "restore", takes out).
	Remove []string `json:"remove"`
}

AdaptToolsOption is one choice the report offers; Apply names it by ID.

type AdaptToolsRecommendation added in v0.5.2

type AdaptToolsRecommendation struct {
	Option      string  `json:"option"`
	Change      string  `json:"change"`
	NetDeltaUSD float64 `json:"net_delta_usd"`
	PerMonthUSD float64 `json:"per_month_usd"`
	Effective   string  `json:"effective"`
	Reason      string  `json:"reason"`
	// Question is the recommendation as one yes/no question, ready to ask as it stands.
	Question string `json:"question"`
	// Remove is the set the option removes; SavedToDateUSD what removing it would have saved over
	// the window, SavedPerWeekUSD the same per week; RewriteUSD the one-off cache rewrite it costs.
	Remove          []string `json:"remove"`
	SavedToDateUSD  float64  `json:"saved_to_date_usd"`
	SavedPerWeekUSD float64  `json:"saved_per_week_usd"`
	RewriteUSD      float64  `json:"rewrite_usd"`
	// For the shared renderer: ItemsN is len(Remove); PerWeekUSD the steady weekly saving (an
	// estimate, the same figure as SavedPerWeekUSD); RangePerWeekUSD its low/high bounds when the
	// declaration sets of older requests were inferred (bounds, not a confidence interval).
	ItemsN          int       `json:"items_n"`
	PerWeekUSD      float64   `json:"per_week_usd"`
	RangePerWeekUSD []float64 `json:"range_per_week_usd,omitempty"`
	PaybackWeeks    *float64  `json:"payback_weeks"`
}

AdaptToolsRecommendation is the one change the report proposes.

type AdaptToolsRemovedRow added in v0.5.2

type AdaptToolsRemovedRow struct {
	// Class is "observed" (filtered by the proxy, measured) or "estimated" (removed in the client).
	Class    string  `json:"class"`
	Kind     string  `json:"kind"`
	Name     string  `json:"name"`
	SinceMS  int64   `json:"since_ms"`
	SavedUSD float64 `json:"saved_usd"`
	Requests int     `json:"requests"`
}

AdaptToolsRemovedRow is one earlier removal's measured saving.

type AdaptToolsSaved added in v0.5.2

type AdaptToolsSaved struct {
	TotalUSD float64             `json:"total_usd"`
	Filter   AdaptToolsSavedPart `json:"filter"`
	Client   AdaptToolsSavedPart `json:"client"`
	Method   string              `json:"method"`
}

AdaptToolsSaved is what removals ALREADY made have saved, measured from the request rows rather than estimated. See adaptToolsSaved for the method.

type AdaptToolsSavedItem added in v0.5.2

type AdaptToolsSavedItem struct {
	Kind          string  `json:"kind"`
	Name          string  `json:"name"`
	RemoveAs      string  `json:"remove_as,omitempty"`
	USD           float64 `json:"usd"`
	Requests      int     `json:"requests,omitempty"`
	SessionsAfter int     `json:"sessions_after,omitempty"`
	Since         int64   `json:"since,omitempty"`
}

AdaptToolsSavedItem is one removed declaration's measured saving.

type AdaptToolsSavedPart added in v0.5.2

type AdaptToolsSavedPart struct {
	// Class is "observed" for the filter and "estimated" for client-side removals; Label says so
	// in words a page can print.
	Class    string                `json:"class"`
	Label    string                `json:"label"`
	USD      float64               `json:"usd"`
	Requests int                   `json:"requests,omitempty"`
	Since    int64                 `json:"since,omitempty"`
	Items    []AdaptToolsSavedItem `json:"items"`
}

AdaptToolsSavedPart is one route a removal took: the proxy filter, or the client itself.

type AdaptToolsToDate added in v0.5.2

type AdaptToolsToDate struct {
	SavedUSD float64 `json:"saved_usd"`
	Since    int64   `json:"since"`
	Until    int64   `json:"until"`
	Class    string  `json:"class"`
	Items    int     `json:"items"`
	Label    string  `json:"label"`
}

AdaptToolsToDate is what earlier removals saved, measured (class observed).

type AdaptToolsWindow added in v0.5.2

type AdaptToolsWindow struct {
	Since    int64 `json:"since"`
	Until    int64 `json:"until"`
	Sessions int   `json:"sessions"`
	Requests int   `json:"requests"`
}

AdaptToolsWindow is the span the report covers.

type ArchivedSession

type ArchivedSession struct {
	SessionID    string `json:"session_id"`
	TenantID     string `json:"tenant_id"`
	FirstTS      int64  `json:"first_ts"`
	LastTS       int64  `json:"last_ts"`
	Requests     int64  `json:"requests"`
	ContentPath  string `json:"content_path,omitempty"`
	ContentBytes int64  `json:"content_bytes,omitempty"`
	FullPath     string `json:"full_path,omitempty"`
	FullBytes    int64  `json:"full_bytes,omitempty"`
	ArchivedAt   int64  `json:"archived_at"`
	Remote       string `json:"remote,omitempty"`
}

ArchivedSession is one row of the cold-storage index.

func (ArchivedSession) Archived

func (a ArchivedSession) Archived() bool

Archived reports whether the whole session is in cold storage.

type Authenticator

type Authenticator func(*http.Request) (Principal, bool)

Authenticator resolves a request to a principal. Returning ok=false makes the request a 401. nil (the default) means SINGLE-TENANT: there is no second party to scope against, and the proxy shows its own numbers exactly as it always has.

type Band

type Band struct {
	Label string  `json:"label"`
	N     int64   `json:"n"`
	USD   float64 `json:"usd"`
	// Tokens is the token form of USD: the billed input tokens of those expiries, by tier (#1048).
	// Set by the Cache strategy tab only; nil (absent) on the KV-cache bands.
	Tokens *TierTokens `json:"tokens,omitempty"`
	// Beyond marks the bands the CURRENT policy's coverage cannot reach, which the chart draws
	// in the de-emphasis gray beyond the coverage rule.
	Beyond bool `json:"beyond,omitempty"`
}

Band is one bucket of an ORDERED histogram: idle-gap bands, prefix-size bands, hour bins.

Label carries the meaning and the order is the data — a bar chart of these must preserve it and must not sort by size, because the order IS what the reader is reading.

Deliberately NO since/until here. These bands bucket by GAP LENGTH, by PREFIX SIZE and by HOUR OF DAY — none of which is a time range, so a bar's drill-down is `reason=ttl_expiry` plus the window already on screen and nothing more. A pair of fields that no band could ever populate would be two zeroes on the wire that something eventually renders as a date.

type BreakpointTotals

type BreakpointTotals struct {
	System   int64 `json:"system"`
	Tools    int64 `json:"tools"`
	Messages int64 `json:"messages"`
	Blocks   int64 `json:"blocks"`
	// Root is the top-level cache_control (automatic caching), one breakpoint on the wire (#1283).
	Root int64 `json:"root"`
	// Requests is the denominator, so a total can be read as a per-request average rather
	// than as a raw sum whose size only reflects the window.
	Requests int64 `json:"requests"`
	// Modal is the single most common (system, tools, messages, blocks) placement in the
	// window, as a display string, with ModalRequests behind it. An average placement is
	// meaningless — 1.5 breakpoints in the system block is not a thing any request did —
	// so the typical case is reported as the mode, not the mean.
	Modal         string `json:"modal"`
	ModalRequests int64  `json:"modal_requests"`
}

BreakpointTotals is prompt-cache breakpoint placement summed by location, plus the number of requests behind it. The provider caps a request at four breakpoints and its automatic caching consumes one of the slots, so the interesting question is never "how many" but "where" — and only these five numbers together answer it.

type Bucket

type Bucket struct {
	TS              int64   `json:"ts"`
	Requests        int64   `json:"requests"`
	TokensBefore    int64   `json:"tokens_before"`
	TokensAfter     int64   `json:"tokens_after"`
	Saved           int64   `json:"saved"`
	SavedUnique     int64   `json:"saved_unique"`
	AttemptedTokens int64   `json:"attempted_tokens"`
	FrozenTokens    int64   `json:"frozen_tokens"`
	FreshInput      int64   `json:"fresh_input"`
	CacheRead       int64   `json:"cache_read"`
	CacheWrite      int64   `json:"cache_write"`
	OutputTokens    int64   `json:"output_tokens"`
	CostUSD         float64 `json:"cost_usd"`
	BaselineCostUSD float64 `json:"baseline_cost_usd"`
	CGLLMCostUSD    float64 `json:"cg_llm_cost_usd"`
	// SavedUSD is baseline − actual − our own spend: the "saved" half of a spent-vs-saved
	// bar, derived here so every caller subtracts the same three terms. Nothing new is
	// stored for it.
	SavedUSD float64 `json:"saved_usd"`
	// CacheSavedUSD is what the PROVIDER's prompt cache saved in this bucket — a
	// diagnostic series, the one that moves when compaction starts rewriting a live
	// prefix.
	CacheSavedUSD float64 `json:"cache_saved_usd"`
	CGLatencyMs   float64 `json:"cg_latency_ms_avg"`
	UpstreamMs    float64 `json:"upstream_ms_avg"`
	Expands       int64   `json:"expands"`
	ExpandTokens  int64   `json:"expand_tokens"`
	Misses        int64   `json:"cache_misses"`
	// DeferNetUSD is tool deferral's net saving in this bucket: its own series, left out of the
	// JSON when 0 so an account that never deferred has no deferral series.
	DeferNetUSD float64 `json:"defer_net_usd,omitempty"`
}

Bucket is one time bucket of the series. Bucketing is done in SQL at query time (ts/bucket*bucket), so there are no rollup tables to keep consistent and any bucket size works without a migration.

type CacheState added in v0.5.0

type CacheState struct {
	Session string `json:"session"`
	Model   string `json:"model"`
	LastTS  int64  `json:"last_ts"` // epoch ms of the last request that touched the cache (its START)
	// EndTS is when that request finished (LastTS + the upstream time). The provider's TTL clock
	// runs from the response, not from the send, so a long answer keeps the cache warm longer
	// than LastTS+TTL says. Equal to LastTS when the duration is unknown.
	EndTS      int64 `json:"end_ts"`
	NowMS      int64 `json:"now_ms"` // server clock, so a client with skew can still count down
	TTLSeconds int64 `json:"ttl_s"`  // 1800 on OpenAI GPT-5.6+, 3600 if the last cache write was billed at the 1h tier or the last touch was a free 1-hour ping (#1243), else 300
	// TTLUnproven is true while ttl_s is 3600 only because of a free 1-hour ping on a route not yet proven to
	// grant the tier. The clients draw the clock with a "1h?" mark. Omitted otherwise.
	TTLUnproven bool `json:"ttl_unproven,omitempty"`
	// FreeHourPing is true while ttl_s is 3600 because the last touch was a free 1-hour ping, proven or not.
	// A manual ping would move that entry back to 5 minutes, so the clients hide the Ping button. Omitted otherwise.
	FreeHourPing bool `json:"free_hour_ping,omitempty"`
	// PrefixTokens is what the last request sent: fresh + cache_read + cache_write. If the cache
	// is cold, this is what the next send rewrites.
	PrefixTokens int64 `json:"prefix_tokens"`
	CacheRead    int64 `json:"cache_read"`
	CacheWrite   int64 `json:"cache_write"`
	KeepAlive    bool  `json:"keepalive"` // the last touch was a context-guru ping
	// RewriteUSD prices PrefixTokens at the cache-write rate (x2.0/1.25 on the 1h tier). Omitted
	// (0 with Priced=false) when the model has no price: unknown, never free.
	RewriteUSD float64 `json:"rewrite_usd"`
	Priced     bool    `json:"priced"`
	// NextWarmUSD and NextColdUSD price the next request's cached prefix both ways: read from a
	// warm cache (PrefixTokens x the cache-read rate), or rewritten into a cold one (the same
	// as RewriteUSD). Both omitted when the model has no price. A client built before they
	// existed falls back to RewriteUSD for the cold case.
	NextWarmUSD *float64 `json:"next_warm_usd,omitempty"`
	NextColdUSD *float64 `json:"next_cold_usd,omitempty"`
	// Pingable is true when the proxy holds this session's main thread's body and key, so POST
	// /api/me/cache/ping can work (with keep-alive off and no opt-in it holds nothing and answers 409
	// "not held"). PingReason says why not, when it is false: "not opted in", "too large", "expired",
	// "over budget", "not worth it", "unsupported", "pings used", "stopped", "below limits", "done" or "no entry". Both are omitted when the host cannot say, so a client treats
	// absence as "unknown".
	Pingable   *bool  `json:"pingable,omitempty"`
	PingReason string `json:"ping_reason,omitempty"`
	// Window is the served context window for Model, Exact=false when it is a guess.
	Window      int  `json:"window"`
	WindowExact bool `json:"window_exact"`
	// PingsLeft and HeldUntilMS are the main thread's keep-alive plan (see ThreadCache).
	PingsLeft   int   `json:"pings_left,omitempty"`
	HeldUntilMS int64 `json:"held_until_ms,omitempty"`
	// NextPingMS is when the next planned ping fires (epoch ms). Omitted when no ping is planned.
	// The mod hides its Ping button while this is before the cache expires.
	NextPingMS int64 `json:"next_ping_ms,omitempty"`
	// Money is the session's `saved $x of $y`, main thread and the rest, over the whole session.
	Money *SessionMoney `json:"money,omitempty"`
	// Threads is the session's cache entries, one per thread (the main agent and each subagent
	// have separate provider caches), most recently used first. Only threads that touched the
	// cache within the last two hours are listed: older ones are finished work.
	Threads []ThreadCache `json:"threads,omitempty"`
}

CacheState is the SERVER's view of one session's prompt cache: what the provider last billed us for, not what the client guesses. The status line prefers this over Claude Code's own prompt_cache block because the proxy sees every request of the session (keep-alive pings included), after every rewrite.

Numbers and enum labels only - no content - so it is scopeTenant like the keep-alive reads.

type CalcRow

type CalcRow struct {
	MaxPings int     `json:"max_pings"`
	Coverage float64 `json:"coverage_seconds"`
	// Convertible is the account's OWN addressable expiries whose idle gap falls inside
	// coverage — a replay of its history, not a forecast, which the panel states in words.
	Convertible    int64   `json:"convertible_misses"`
	ConvertibleUSD float64 `json:"convertible_usd"`
	SharePct       float64 `json:"share_of_addressable_pct"`
	Pings          int64   `json:"pings"`
	// omitempty on the three dollar fields, so an unpriced ladder puts no `0` on the wire at all.
	// "A field that exists gets rendered" is this project's own rule, and a 0 that means "no rate
	// on the operator's list" is the shape every zero-as-a-measurement defect on this dashboard has
	// had. The UI gates on `priced` as well; both, because either alone has failed before.
	PingUSD  float64 `json:"ping_usd,omitempty"`
	SavedUSD float64 `json:"saved_usd,omitempty"`
	NetUSD   float64 `json:"net_usd,omitempty"`
	Current  bool    `json:"current,omitempty"`
	// Plan says which model this rung uses: "wait_plan" (the live per-wait plan, with MaxPings as
	// its base) or "fixed_k" (MaxPings pings for every wait).
	Plan string `json:"plan"`
}

CalcRow is one rung of the K ladder.

type CampaignSavingCell

type CampaignSavingCell struct {
	TenantID string `json:"tenant_id"`
	HourUTC  int    `json:"hour_utc"`
	// Requests is real (non-ping) traffic in this cell since `since` — the denominator
	// for a $-per-1k-requests normalization, deliberately NOT the ping count, since a
	// ping is housekeeping this service issued, not traffic the tenant sent.
	Requests int64 `json:"requests"`
	// ActiveDays is how many distinct calendar days (UTC) this cell saw any real
	// request since `since` — the denominator for a $-per-active-day normalization.
	ActiveDays int64 `json:"active_days"`
	// Pings and PingUSD are EXACT, the same guarantee StrategyLedgerRow makes: every
	// ping row one of this campaign's own strategies caused carries that strategy's id.
	Pings   int64   `json:"pings"`
	PingUSD float64 `json:"ping_usd"`
	// SavedUSD is EXACT too, as of the strategy-id scoping described in the file doc
	// comment: only credit a ping from one of THIS campaign's own strategies rescued,
	// never the tenant's whole keep-alive credit in the cell.
	SavedUSD float64 `json:"saved_usd"`
	NetUSD   float64 `json:"net_usd"`
}

CampaignSavingCell is one (tenant, hour-of-day) cell's real economics since a campaign went live.

type CapResult added in v0.7.2

type CapResult struct {
	// CorrectionUSD is the sum of the corrections of the ledgers that ran: negative or zero.
	CorrectionUSD float64
	// NotApplied is true when at least one ledger did not run (no price table or window resolver,
	// or its scan failed). CorrectionUSD then holds only the part that did.
	NotApplied bool
}

CapResult is the cap's correction for one filter and whether it is complete.

type ClientCeilingUsed added in v0.2.0

type ClientCeilingUsed struct {
	Model string `json:"model"`
	// Frac is the fraction of the context window, in PROVIDER-BILLED input, at which the client is
	// taken to compact its own transcript. Not the figure the client's own indicator displays.
	Frac float64 `json:"frac"`
	// SpanFrac is what that ceiling produced for this model: `frac - fill_frac`.
	SpanFrac float64 `json:"span_frac"`
	// Provenance is "measured", "assumed", "configured", "client_default", "operator" or "window_fallback". A measured ceiling came
	// from watching a real client compact, in billed tokens. A configured one is the user's own client
	// setting (#948), taken as billed tokens at a factor of 1.0 that is not measured. The others did not, and an assumed ceiling that is too high
	// makes the span too wide and OVER-reports.
	Provenance string `json:"provenance"`
	// Note is why this value, in enough detail to tell whether it still holds.
	Note string `json:"note"`
}

ClientCeilingUsed is the ceiling one model's conversations were measured against.

type ClientSignal added in v0.7.4

type ClientSignal struct {
	TS       int64 // epoch ms
	TenantID string
	Session  string // the tenant-scoped session id the client's hook named
	Event    string // SessionEnd | SessionStart | Notification
	Reason   string // the reason, source or notification type; from a closed set
	// PermissionMode is the client's permission mode from its hook input (allow-listed by the host); "" when unsent.
	PermissionMode string
}

ClientSignal is one accepted client lifecycle event (proxy/clientsignal.go).

type CompRow

type CompRow struct {
	Component   string `json:"component"`
	Kind        string `json:"kind"`
	Acted       bool   `json:"acted"`
	Mutated     bool   `json:"mutated"`
	Reverted    bool   `json:"reverted"`
	Skipped     bool   `json:"skipped"`
	SavedGross  int    `json:"saved_gross"`
	SavedUnique int    `json:"saved_unique"`
	// SavedBytes is the same removal as SavedGross in bytes (#1533): the sum of the component's changes, before minus
	// after. A count. 0 is unknown.
	SavedBytes int `json:"saved_bytes,omitempty"`
	// SavedUSD is this component's share of the request's baseline delta, in dollars,
	// priced at write time from the request's OWN model and the tier the request itself
	// paid. Set by the accountant library (PriceMode); the per-component figures sum to the
	// request-level saving, except that on a request the accountant priced the tooldefer row's
	// dollars sit in the deferral lever (DeferNetUSD) and not in the baseline delta. It exists because the components view had
	// only a bare COST for the components that spend, and a dollar value improvised
	// client-side from hardcoded rates is wrong by whatever the deployment's model
	// actually charges.
	SavedUSD float64 `json:"saved_usd"`
	// SavedFirstUSD and SavedReplayUSD split SavedUSD by the tier the accountant library priced the
	// saved tokens at: the write or input tier (a first removal) and the read tier (a replay of
	// content in the cached prefix). SavedUSD minus both is the costs. PricedBy is "accountant" when
	// the library priced the row; "" on a row priced before it (see the request_components schema).
	SavedFirstUSD  float64 `json:"saved_first_usd"`
	SavedReplayUSD float64 `json:"saved_replay_usd"`
	PricedBy       string  `json:"priced_by,omitempty"`
	// Tokens is the accountant library's figure for this component in tokens by tier: what it
	// saved and what it caused (#998). Its dollars are SavedUSD. Stored (request_components.tok_*);
	// zero on a row the library did not price (PricedBy not "accountant"), on a held estimate, and
	// on the headttl and ended_change rows' effect legs, which are Event.AccTokens.
	Tokens     TokenFlow `json:"tokens,omitzero"`
	DurationMs float64   `json:"duration_ms"`
	Err        string    `json:"err,omitempty"`
	// Gates counts, per named gate, the candidates this component turned away. It is the
	// only answer to "why did nothing happen?", and it never left the pipeline before:
	// /stats had it service-wide, the log line had it per request, and the dashboard —
	// the thing a user actually opens — had a table of zeros with no explanation. On a
	// Bob session almost every row is a gate name, because the offload heuristics were
	// tuned on Claude Code's tool-output shapes.
	// Not omitempty: an EMPTY map means "gated nothing" and a MISSING field means "this row
	// predates the column". The UI renders the first as a dash and the second as "unknown",
	// and omitempty made every healthy component look like the second.
	Gates map[string]int `json:"gates"`
	// Events counts what this component DID — a replay served, an output removed, an inventory
	// offered, a candidate reached past the cached boundary. The counterpart to Gates, and carried
	// separately for the reason the two metrics series are separate: they answer opposite questions.
	//
	// Without it this row was blind in proportion to how well a component was working, because the
	// names a component raises when it SUCCEEDS are the ones that moved. Observed live: the turn
	// that adjudicated twelve outputs and removed twelve showed an empty gates cell, while a turn
	// that refused everything showed a full one.
	//
	// Same omitempty reasoning as Gates, and it is load-bearing here too: an EMPTY map means "did
	// nothing counted", a MISSING field means "this row predates the column".
	Events map[string]int `json:"events"`
}

CompRow is one component's accounting on one request.

type CompactionAssumptions added in v0.2.0

type CompactionAssumptions struct {
	// SpanFrac is the explicit `?span=` override, or 0 meaning the span was DERIVED per model from
	// that model's client ceiling. The spans actually used are in ClientCeilings, one per model,
	// because the ceiling is a per-model fact and one number here would average things that are not
	// comparable.
	SpanFrac     float64 `json:"span_frac"`
	FillFrac     float64 `json:"fill_frac"`
	SpanMeasure  string  `json:"span_measure"`
	CreditSource string  `json:"credit_source"`
	// CreditQuantityNote names the known error in the credit's QUANTITY, which is a different thing
	// from its rate: the tokens are counted on our own ruler. See issue #240.
	CreditQuantityNote string `json:"credit_quantity_note"`
	ColdLabel          string `json:"cold_label"`
	ReadLabel          string `json:"read_label"`
	DebitBound         string `json:"debit_bound"`
	VoidRule           string `json:"void_rule"`
	WindowRule         string `json:"window_rule"`
	KnownOmission      string `json:"known_omission"`
	OpenRule           string `json:"open_rule"`
	SpanMeasureNote    string `json:"span_measure_note"`
	// SpanRule says WHY the span is the width it is: it is an attribution boundary derived from the
	// fill threshold, not a tuning knob. See spanFor.
	SpanRule string `json:"span_rule"`
	// ClientCeilings is one entry per model and source this query actually measured (noteCeiling),
	// because the ceiling is a fact about the CLIENT's behaviour on that model, and a model can have
	// both a table conversation and a configured one. A single number would be an average of
	// things that are not comparable. Each carries its provenance, so a reader can tell which
	// published figures rest on a measurement and which on an assumption.
	ClientCeilings []ClientCeilingUsed `json:"client_ceilings"`
}

CompactionAssumptions is the server stating its own arithmetic, so the page prints it rather than restating it in a template nothing tests — the rule the KV-cache page already keeps.

type CompactionCoverage added in v0.2.0

type CompactionCoverage struct {
	// NoAttributableSpan counts conversations excluded because the fill threshold sits at or above
	// the CLIENT's compaction ceiling for that model: the client compacts before we would ever fire,
	// so there is no window in which anything is attributable to us and this component cannot help
	// there. A configuration to change, not an empty dataset — and a COUNT rather than a flag,
	// because the ceiling is per model and a query can span one model where this holds and another
	// where it does not.
	NoAttributableSpan int `json:"no_attributable_span"`
	// FillFrac is the threshold a conversation had to reach to qualify, as a fraction of its
	// window, measured in billed input. Reported because it is a parameter, not a law.
	FillFrac float64 `json:"fill_frac"`
	// Conversations reached FillFrac and had an exact window.
	Conversations int64 `json:"conversations"`
	WithEpisode   int64 `json:"with_episode"`
	NoEpisode     int64 `json:"no_episode"`
	// NoEpisodeColdUSD is what the ttl_expiry turns of those conversations actually paid in
	// cache creation — the money an episode there might have reduced. Not a claim that it would
	// have: it is the size of the opportunity, which is why it is named for the population and
	// not for a saving.
	NoEpisodeColdUSD float64 `json:"no_episode_cold_usd"`
	// WindowUnknown is conversations excluded because their model's window is a guess or
	// unknown. Counted so the population is never silently narrowed.
	WindowUnknown int64 `json:"window_unknown"`
	// Unpriced is qualifying conversations on a model with no rates.
	Unpriced int64 `json:"unpriced"`
}

CompactionCoverage is the other half of the question, and the panel is dishonest without it.

An episode only exists where a summary was made. Reporting episodes alone answers "when we helped, how much did we help" — which is survivorship, and always positive. The number that decides whether the trigger is worth its default is how many qualifying conversations produced NO episode at all, and what the cold rewrites cost them.

type CompactionEpisode added in v0.2.0

type CompactionEpisode struct {
	TenantID   string `json:"tenant_id"`
	SessionID  string `json:"session_id"`
	Model      string `json:"model"`
	Provenance string `json:"provenance"`
	State      string `json:"state"`
	StartTS    int64  `json:"start_ts"`
	EndTS      int64  `json:"end_ts"`
	// Window is the model's context window, always exact (see the file comment), and Span is
	// the billed input the episode covered — StartBilled to EndBilled.
	Window      int   `json:"window"`
	StartBilled int64 `json:"start_billed"`
	EndBilled   int64 `json:"end_billed"`
	// NewContentBilled is the provider-billed NEW content since t0 — fresh input plus the
	// newly-written tail on turns whose cache hit. It is the axis the span closes on: monotone by
	// construction, in the window's own units, and excluding both the re-sent prefix and the
	// re-creation of an expired one. See the derivation in conversationEpisodes for why the two
	// obvious axes (per-turn size, cumulative spend) each fail.
	NewContentBilled int64 `json:"new_content_billed"`
	Turns            int64 `json:"turns"`
	// The credit, split by the cache state of the turn that earned it. ColdCreditUSD is the
	// headline: turns whose entry had lapsed, where an uncompacted prefix would have been
	// re-written in full. ReadCreditUSD is every warm turn's re-sent remainder at 0.1x, which is
	// usually the larger of the two simply because warm turns are far more numerous.
	ColdCreditUSD float64 `json:"cold_credit_usd"`
	ReadCreditUSD float64 `json:"read_credit_usd"`
	// FirstRemovalCreditUSD is the saving on the turn that made a summary: the removed content
	// priced at the rate the turn before it paid for that content (a read when its cache was
	// live). Kept apart from the replay buckets because it is a different claim: one turn, no
	// replay multiple.
	FirstRemovalCreditUSD float64 `json:"first_removal_credit_usd"`
	// OtherCreditUSD is turns with no cache verdict at all. A cold_start turn is not credited
	// (#611): it had no entry to preserve. Neither is an unknown turn.
	OtherCreditUSD float64 `json:"other_credit_usd"`
	// InvalidationDebitUSD is what THIS component's own rewrite cost on t0: the cache-creation
	// tokens that turn wrote, at that model's write rates. An UPPER BOUND, deliberately — some
	// of that write was transcript growth that would have been paid anyway, and no column says
	// how much. Overstating our own cost is the conservative direction for a savings figure.
	InvalidationDebitUSD float64 `json:"invalidation_debit_usd"`
	// SummarizerCostUSD is context-guru's own model spend inside the episode: t0's summary and
	// any roll-forward that happened before the span closed.
	SummarizerCostUSD float64 `json:"summarizer_cost_usd"`
	// NetUSD is credits − debits. Negative is a real outcome and is reported as one.
	NetUSD float64 `json:"net_usd"`
	// Priced is false when this model has no rates. Then every dollar here is absent rather
	// than zero — an unpriced model is not a free one.
	Priced bool `json:"priced"`
}

CompactionEpisode is one summary and the span of work after it.

type CompactionEpisodeGroup added in v0.2.0

type CompactionEpisodeGroup struct {
	Provenance string `json:"provenance"`
	Episodes   int64  `json:"episodes"`
	Closed     int64  `json:"closed"`
	Open       int64  `json:"open"`
	Voided     int64  `json:"voided"`
	// ClientCompacted counts episodes the client's own compaction ended inside the span. They
	// are totalled like closed ones: the credit up to that turn is real.
	ClientCompacted       int64   `json:"client_compacted"`
	FirstRemovalCreditUSD float64 `json:"first_removal_credit_usd"`
	Turns                 int64   `json:"turns"`
	ColdCreditUSD         float64 `json:"cold_credit_usd"`
	ReadCreditUSD         float64 `json:"read_credit_usd"`
	OtherCreditUSD        float64 `json:"other_credit_usd"`
	InvalidationDebitUSD  float64 `json:"invalidation_debit_usd"`
	SummarizerCostUSD     float64 `json:"summarizer_cost_usd"`
	NetUSD                float64 `json:"net_usd"`
	// UnpricedEpisodes are closed episodes on a model with no rates: counted, never valued.
	UnpricedEpisodes int64 `json:"unpriced_episodes"`
	// OpenNetUSD is the net of spans that have NOT finished — money committed whose payoff is
	// still accruing. Reported apart from NetUSD rather than excluded.
	//
	// Excluding it was survivorship one level below the coverage line: an unfinished span is
	// exactly the case where we paid for a summary and have not yet recouped it, so dropping
	// those made the panel systematically optimistic. It is kept OUT of NetUSD because a partial
	// figure grows as the time range widens, which would make the settled total depend on when
	// you looked.
	//
	// It is not automatically a loss, and that is why it is computed rather than assumed: we are
	// behind only when 1.25xC > 0.1xF, i.e. when the compacted prefix exceeds ~8% of the full
	// one. At better than roughly 12.5:1 compression the compaction turn is already cheaper on
	// its own turn, before any later read saves anything.
	OpenNetUSD   float64 `json:"open_net_usd"`
	OpenTurns    int64   `json:"open_turns"`
	VoidedNetUSD float64 `json:"voided_net_usd"`
}

CompactionEpisodeGroup is one provenance's totals.

type CompactionEpisodes added in v0.2.0

type CompactionEpisodes struct {
	ByProvenance []CompactionEpisodeGroup `json:"by_provenance"`
	// Episodes is the drill-down list, newest first, capped. The groups above are computed over
	// everything, not over this slice.
	Episodes    []CompactionEpisode   `json:"episodes"`
	Coverage    CompactionCoverage    `json:"coverage"`
	Assumptions CompactionAssumptions `json:"assumptions"`
	// Ledger is summarize's credit, row by row, split into what counts and what does not. The
	// headline and /api/components read the same ledger, so the three figures agree.
	Ledger SummarizeLedger `json:"ledger"`
	// ReplayLedger is the same ledger for every other replaying component (see replaycap.go).
	ReplayLedger *ReplayLedger      `json:"replay_ledger,omitempty"`
	Pricing      *kvcache.PriceList `json:"pricing"`
	FirstTS      int64              `json:"first_ts"`
	LastTS       int64              `json:"last_ts"`
	Scanned      int64              `json:"scanned"`
}

CompactionEpisodes is the whole view.

type ComponentLedger added in v0.5.2

type ComponentLedger struct {
	// StoredUSD is request_components.saved_usd on the rows the walk saw.
	StoredUSD float64 `json:"stored_usd"`
	// CountedUSD is the part inside the cap; FirstRemovalUSD + ReplayUSD add up to it.
	CountedUSD      float64 `json:"counted_usd"`
	FirstRemovalUSD float64 `json:"first_removal_usd"`
	ReplayUSD       float64 `json:"replay_usd"`
	// PastCapUSD is the stored credit after the cap closed, with the reason that closed it.
	PastCapUSD         float64 `json:"past_cap_usd"`
	PastCapFirstUSD    float64 `json:"past_cap_first_usd"`
	PastCounterfactual float64 `json:"past_counterfactual_usd"`
	PastClientCompact  float64 `json:"past_client_compaction_usd"`
	Rows               int64   `json:"rows"`
	PastRows           int64   `json:"past_rows"`
	// WindowAssumedUSD is the stored credit of conversations whose model window was not exactly
	// known, capped against assumedWindow instead.
	WindowAssumedUSD float64 `json:"window_assumed_usd"`
}

ComponentLedger is one component's credit, sorted into what counts and what does not.

func (*ComponentLedger) DeltaUSD added in v0.5.2

func (l *ComponentLedger) DeltaUSD() float64

DeltaUSD is the correction to apply to a figure built from the stored credit.

type ComponentRow

type ComponentRow struct {
	Component string `json:"component"`
	Kind      string `json:"kind"`
	Runs      int64  `json:"runs"`
	Acted     int64  `json:"acted"`
	// Acted is the stored `acted` flag: mutated AND removed at least one token
	// (Event.FromTrace). ActedTokens is the same figure under a name that says so, and
	// ActedStructural is the rest of `mutated` — runs that changed the request without
	// removing anything, which is the whole point of a component like cacheinject (it places a
	// cache breakpoint). Reported apart because one number
	// could not carry both: such a component can mutate requests and
	// "act" on 0 of them, so its act rate was permanently 0% and painted red, which is the
	// same class of bug that was already fixed for the Prometheus counters.
	ActedTokens     int64   `json:"acted_tokens"`
	ActedStructural int64   `json:"acted_structural"`
	Mutated         int64   `json:"mutated"`
	Reverted        int64   `json:"reverted"`
	Skipped         int64   `json:"skipped"`
	SavedGross      int64   `json:"saved_gross"`
	SavedUnique     int64   `json:"saved_unique"`
	OvercountRatio  float64 `json:"overcount_ratio"`
	// SavedUSD is what this component's removals were worth over the window, in dollars,
	// summed from the per-request figures priced at write time (CompRow.SavedUSD). The sum
	// over turns IS the amortization: value realized turn by turn as a frozen reduction
	// replays, not a projection from one turn.
	SavedUSD float64 `json:"saved_usd"`
	// SavedUSDEstimated is the same figure for rows written BEFORE saved_usd existed, valued
	// on read from the tokens and tiers those rows do carry (DB.EstimateComponentSavedUSD).
	// Kept apart from SavedUSD so a stored dollar and an estimated one are never added
	// silently; the view adds them and says it did. EstimatedRows is how many component rows
	// are behind it, UnpricedRows how many removed tokens but could not be valued at all
	// (no rate for the model, or the request's own accounting was incomplete) — counted
	// rather than valued at zero, because "unknown" and "worthless" are different claims.
	SavedUSDEstimated     float64 `json:"saved_usd_estimated"`
	SavedUSDEstimatedRows int64   `json:"saved_usd_estimated_rows"`
	SavedUSDUnpricedRows  int64   `json:"saved_usd_unpriced_rows"`
	// NetUSD is SavedUSD − LLMCostUSD: the honest verdict on this component, and the number
	// the view must render instead of a bare cost. Negative is a real outcome and is shown
	// as one — a component underwater over the window says so here.
	//
	// NetUSDWithEstimate is the same verdict once the pre-column history is valued. It equals
	// NetUSD exactly when nothing needed estimating, and it is the figure the view shows —
	// judging extract_llm on its full spend against six rows of its saving is not a verdict.
	NetUSD             float64 `json:"net_usd"`
	NetUSDWithEstimate float64 `json:"net_usd_with_estimate"`
	// The two halves the dollar figure above is made of, valued on read over every priced
	// row — see DB.DecomposeComponentSavedUSD for why this is not decoration.
	//
	// SavedUSDFirstRemoval is each piece of content priced ONCE, at the cache-write rate it
	// would have entered the prompt at. SavedUSDReplay is every later turn that same content
	// stayed absent for, at the tier those turns actually paid. NetUSDFirstRemoval is the
	// first figure less this component's own LLM spend, and it is the verdict the proxy's
	// /stats endpoint reports — the one that reads NEGATIVE for extract_llm while the
	// amortized verdict reads positive. ReplayMultiple is the factor between them, i.e. the
	// single number that explains the sign flip.
	//
	// SavedUSDDecomposed is their sum, and it exists to be COMPARED with
	// SavedUSD+SavedUSDEstimated: the two are computed by different code from the same rows,
	// so a gap between them is a bug in one of them and the UI says so rather than picking a
	// winner silently.
	SavedUSDFirstRemoval float64 `json:"saved_usd_first_removal"`
	SavedUSDReplay       float64 `json:"saved_usd_replay"`
	SavedUSDDecomposed   float64 `json:"saved_usd_decomposed"`
	NetUSDFirstRemoval   float64 `json:"net_usd_first_removal"`
	ReplayMultiple       float64 `json:"replay_multiple"`
	// SavedUSDDecomposedStored is the decomposition restricted to rows that carry a STORED
	// saved_usd. It is the only part of the figure above that cross-checks against anything:
	// for a row with saved_usd = 0 the stored side comes from EstimateComponentSavedUSD, which
	// runs the identical formula, so agreement is arithmetic. The UI prints the covered
	// fraction rather than presenting the whole comparison as evidence.
	SavedUSDDecomposedStored float64 `json:"saved_usd_decomposed_stored"`
	// SavedUSDCosts is the costs the accountant library netted into saved_usd on the rows it
	// priced: added tokens and the breaks a component caused. Negative. It is the third term of
	// SavedUSDDecomposed on those rows (first removal + replay + costs = saved_usd); 0 before them.
	SavedUSDCosts float64 `json:"saved_usd_costs,omitempty"`
	// UniqueUnkeyed marks a component whose saved_unique is not a dedup measurement, because
	// it reports no content keys and MarkUnique therefore returns its saving in full every
	// turn. True for every reformatter. See DecomposeComponentSavedUSD for why this is
	// flagged rather than repriced.
	// UniqueRows / UniqueDiffRows are the evidence behind the flag, and they exist because the
	// boolean cannot express two states that matter. Below the row floor "nothing deduped" is
	// not a finding — and 98.2% of per-session windows are below it, so a session drawer
	// rendered a fabricated figure identically to a measured one. And a MIXED population reads
	// as fully measured through the boolean while part of its dollars are still fabricated,
	// which is the state the reformatter fix passes through.
	UniqueUnkeyed   bool    `json:"unique_unkeyed"`
	UniqueRows      int64   `json:"unique_rows"`
	UniqueDiffRows  int64   `json:"unique_diff_rows"`
	DurationMsTotal float64 `json:"duration_ms_total"`
	DurationMsAvg   float64 `json:"duration_ms_avg"`
	Errors          int64   `json:"errors"`
	// ActRate is acted/runs: how often the component removes anything. ActRateStructural is
	// the structural half over the same denominator — see ActedStructural for why a single
	// rate was a lie for the placement components.
	ActRate           float64 `json:"act_rate"`
	ActRateStructural float64 `json:"act_rate_structural"`
	// LLM-call economics, from the recorded per-call rows. Zero for every deterministic
	// component, which is the point: only the components that SPEND can be net-negative,
	// and until now the components view had no dollars in it at all, so it judged an
	// expensive component on tokens and latency and could never say "underwater".
	LLMCalls int64 `json:"llm_calls"`
	// SummarizeCreditPastSpanUSD / SummarizeCreditPrefixChangeUSD are stored summarize credit the
	// attribution ledger took out of SavedUSD (see SummarizeLedger). Set on the summarize row only.
	SummarizeCreditPastSpanUSD     float64 `json:"summarize_credit_past_span_usd,omitempty"`
	SummarizeCreditPrefixChangeUSD float64 `json:"summarize_credit_prefix_change_usd,omitempty"`
	// The sweep's ledger (#404 PR C), set on the extract_llm_sweep row only. SweepExpandChargeUSD is the
	// cost of the sweep's expands, already taken off SavedUSD and NetUSD. SweepAnswerUSD is what the
	// answers cost beyond the pings' own reads: its own column, NOT subtracted again (the component's
	// model spend already carries it). The false-drop rate is the number to pull the sweep on.
	SweepApplied         int64   `json:"sweep_applied,omitempty"`
	SweepFalseDrops      int64   `json:"sweep_false_drops,omitempty"`
	SweepFalseDropRate   float64 `json:"sweep_false_drop_rate,omitempty"`
	SweepExpands         int64   `json:"sweep_expands,omitempty"`
	SweepExpandTokens    int64   `json:"sweep_expand_tokens,omitempty"`
	SweepExpandChargeUSD float64 `json:"sweep_expand_charge_usd,omitempty"`
	SweepAnswerUSD       float64 `json:"sweep_answer_usd,omitempty"`
	// L1: the sweep's net saving by the provider's usage (credit - expand charge - answer cost). C2: the
	// provider's cache tiers on the cold-apply requests, and on the first warm request after each.
	SweepNetUSD              float64 `json:"sweep_net_usd,omitempty"`
	SweepColdApplyRequests   int64   `json:"sweep_cold_apply_requests,omitempty"`
	SweepColdApplyCacheRead  int64   `json:"sweep_cold_apply_cache_read,omitempty"`
	SweepColdApplyCacheWrite int64   `json:"sweep_cold_apply_cache_write,omitempty"`
	SweepNextWarmRequests    int64   `json:"sweep_next_warm_requests,omitempty"`
	SweepNextWarmCacheRead   int64   `json:"sweep_next_warm_cache_read,omitempty"`
	// ReplayCreditPastCapUSD is stored credit the replay ledger took out of SavedUSD: turns after
	// the counterfactual (or a real) client compaction. Set on the capped components' rows.
	ReplayCreditPastCapUSD float64 `json:"replay_credit_past_cap_usd,omitempty"`
	// ReplayWindowAssumed marks a row whose cap used an assumed context window for some
	// conversations (the model's window is not exactly published).
	ReplayWindowAssumed bool  `json:"replay_window_assumed,omitempty"`
	LLMCallsCold        int64 `json:"llm_calls_cold"`
	LLMCallsAcc         int64 `json:"llm_calls_accepted"`
	// LLMCostUSD is the figure every verdict on this row is computed from, and it is the
	// GATEWAY-priced one — see the query for why the dashboard used to carry two.
	// LLMCostGatewayUSD and LLMCostReportedUSD are the two sources kept separable so the UI
	// can show the gap rather than quietly pick a side.
	LLMCostUSD         float64 `json:"llm_cost_usd"`
	LLMCostGatewayUSD  float64 `json:"llm_cost_gateway_usd"`
	LLMCostReportedUSD float64 `json:"llm_cost_reported_usd"`
	LLMLatencyMsAvg    float64 `json:"llm_latency_ms_avg"`
	// LLMSavedTokens is what the CALLS removed, which is not the same as SavedUnique: the
	// component's savings also include frozen results replayed with no call at all, and on
	// measured traffic that replay is ~93% of its realized value.
	LLMSavedTokens int64 `json:"llm_saved_tokens"`
	// Gates totals the named reasons this component turned candidates away over the
	// window. For a component with act_rate 0 it is the whole story, and it used to be
	// visible only in /stats (service-wide) and the log line (per request) — never in the
	// dashboard, which is what a user opens when they ask why nothing was compacted.
	// Not omitempty - see CompRow.Gates. Over a window an absent map means no row in it
	// carried gate data at all.
	Gates map[string]int64 `json:"gates"`
	// Events is the counterpart total over the window: what this component DID. Same
	// empty-versus-absent contract as Gates above — an absent map means no row in the window
	// carried event data at all, which is not the same as a component that did nothing.
	Events map[string]int64 `json:"events"`
}

ComponentRow is one component's economics across the filtered window — the view that makes "which components earn their place" obvious without reading a doc.

type ContentRow

type ContentRow struct {
	Path         string `json:"path"`
	BeforeTokens int    `json:"before_tokens"`
	AfterTokens  int    `json:"after_tokens"`
	Before       string `json:"before,omitempty"`
	After        string `json:"after,omitempty"`
	// Components names which components rewrote this message, in the order they touched
	// it — EXACT attribution for the diff view, so it never has to infer the author from
	// whether the after-text carries a `<<cg:HASH>>` marker. A reverted component is
	// absent. Empty on rows written before this field existed, which the UI must read as
	// "unknown", not as "nothing".
	Components []string `json:"components,omitempty"`
}

ContentRow is one rewritten message's before/after text (already redacted and size-capped by the caller).

type CostlyCheck added in v0.5.4

type CostlyCheck struct {
	ID     string
	Shapes []CostlyShape // summed into the main figure
	Also   []CostlyShape // reported apart, never added to the main figure
}

CostlyCheck is one check the route prices. Shapes is empty when the shape is not known yet.

type CostlyDoc added in v0.5.4

type CostlyDoc struct {
	Kind    string      `json:"kind"`
	Version int         `json:"version"`
	Class   string      `json:"class"`
	Window  CostlyWin   `json:"window"`
	Checks  []CostlyRow `json:"checks"`
}

CostlyDoc is the document of GET /api/adapt/settings.

type CostlyPart added in v0.5.4

type CostlyPart struct {
	ID       string   `json:"id"`
	Requests int      `json:"requests"`
	CostUSD  *float64 `json:"cost_usd"`
}

CostlyPart is the count and cost of one shape.

type CostlyRow added in v0.5.4

type CostlyRow struct {
	ID       string       `json:"id"`
	Measured bool         `json:"measured"`
	Requests int          `json:"requests"`
	CostUSD  *float64     `json:"cost_usd"`
	Also     []CostlyPart `json:"also"`
}

CostlyRow is one check in the document. CostUSD is null when the check has no known shape.

type CostlyShape added in v0.5.4

type CostlyShape struct {
	ID            string
	ModelContains string // lower case; "" = any model
	Tools         *int
	SystemBlocks  *int
	MaxTokens     *int
	Stream        *int
	Messages      *int // the dashboard's count: the system prompt counts as one
	Status        *int // upstream HTTP status
	// SessionHas, when set, keeps only rows whose session also has a row of that shape. The inner row
	// must be in the same tenant and the same time window as the outer one.
	SessionHas *CostlyShape
}

CostlyShape is one request shape. A nil pointer means "any".

type CostlyWin added in v0.5.4

type CostlyWin struct {
	Since int64 `json:"since"`
	Until int64 `json:"until"`
}

CostlyWin is the window the figures cover.

type DB

type DB struct {
	// contains filtered or unexported fields
}

DB is the dashboard's durable store. All writes go through one goroutine (see capture.go), so the only concurrency here is reads racing that writer, which SQLite in WAL mode handles.

func Open

func Open(path string) (*DB, error)

Open opens (creating if needed) the dashboard database at path. path ":memory:" or "" yields an ephemeral in-memory database, which is also the fallback the proxy uses when the configured path is unwritable — the proxy must keep serving traffic whatever the disk says.

On a schema-version mismatch the existing file is renamed aside (<path>.v<old>.bak) and a fresh database is created: the METRICS in it are a derived view, so discarding them beats refusing to boot, and renaming beats deleting.

The file is NOT purely derived any more, and that is the part to keep in mind before extending this path: archived_sessions and tenant_spend are the only copies of their facts (the cold-storage index and the monthly spend rollup), so the fresh database CARRIES THEM ACROSS from the renamed file — see carryNonDerived. Anything else added here that cannot be recomputed from traffic has to join that list.

func OpenReadOnly added in v0.5.3

func OpenReadOnly(path string) (*DB, error)

OpenReadOnly opens an EXISTING dashboard database for reading only — for analysis tools that run beside a live proxy, which owns the file.

Open is not safe for that: it migrates the schema (additive DDL, new columns), stamps the version, checkpoints the WAL, and on a version mismatch RENAMES the file aside. Any of those against a database a serving process holds is a write the operator never asked for. This opens with SQLite's mode=ro and query_only, runs none of them, and REFUSES a database whose schema version is not this build's: a reader cannot migrate, and a query written for one schema read against another returns wrong numbers rather than an error.

mode=ro still reads the -wal, so rows the live writer has committed but not yet checkpointed are visible. A missing file is an error, not a fresh database. With NO live writer, SQLite still creates an empty -wal and the -shm index beside a WAL database to read it, so the directory must be writable; the database file itself is never modified.

func (*DB) AccTokens added in v0.7.2

func (d *DB) AccTokens(f Filter) (*AccTokensRead, error)

AccTokens answers the `tokens` object, tokens_unmeasured_requests and the pings' tokens for the filter, for the FULL /api/stats. The lean read has the same totals and count from its one scan (accTokenLeanTerms), and no by_feature and no ping tokens.

func (*DB) AccountMedianPrefix

func (d *DB) AccountMedianPrefix(f Filter) (int64, string, error)

AccountMedianPrefix is the account's own median billed prefix at a lapsed entry, and the model most of those lapses were on. What the calculator prefills when no session is selected.

The MODEL matters as much as the size: a rate belongs to a model, and without one the panel reported "not priced" on a deployment whose price list was perfectly good. The modal model of this account's own expiries is an honest answer to "what would this cost me"; a blended average across models is not, and is the defect class this project has hit five times. Returns 0 and "" when the account has no addressable expiry.

func (*DB) AdaptCompaction added in v0.5.2

func (d *DB) AdaptCompaction(ctx context.Context, f Filter, p modelinfo.Pricer, curDoc, defDoc string, custom bool) (*AdaptCompactionReport, error)

AdaptCompaction builds the report for one tenant. curDoc is the account's stored config, defDoc the service default. custom=false prices every shipped preset; custom=true searches which deterministic components run, their order and two thresholds.

func (*DB) AdaptTools added in v0.5.2

func (d *DB) AdaptTools(f Filter, price func(string) (modelinfo.Price, bool), state ToolFilterState) (*AdaptToolsDoc, error)

AdaptTools builds the document for one scope.

func (*DB) ArchivedSessionByID

func (d *DB) ArchivedSessionByID(sessionID string) (ArchivedSession, error)

ArchivedSessionByID reads one index row of ANY tenant, the most recently archived when two tenants share the id (#1069). It is for a caller with no tenant in view: a manager's service-wide scope. A caller that has a tenant uses ArchivedSessionOf.

func (*DB) ArchivedSessionOf added in v0.7.3

func (d *DB) ArchivedSessionOf(tenant, sessionID string) (ArchivedSession, error)

ArchivedSessionOf reads one tenant's index row.

func (*DB) ArchivedSessions

func (d *DB) ArchivedSessions(f Filter, limit int) ([]ArchivedSession, error)

ArchivedSessions lists the cold-storage index for a tenant, newest first. Served from the LOCAL index, so browsing history costs nothing and works even when the remote is unreachable.

func (*DB) BackfillProjects added in v0.5.4

func (d *DB) BackfillProjects(home string, apply bool) (*ProjectBackfill, error)

BackfillProjects fills the project column on rows that have none, reading each session's working directory out of the agent's transcripts.

`home` overrides the home directory, for tests. `apply` false reports what would change without writing, which is the mode worth running first: this rewrites historical rows.

func (*DB) Breakdown

func (d *DB) Breakdown(f Filter, dim string) ([]*GroupRow, error)

Breakdown aggregates the filtered window by one dimension: requests, tokens, and SPENT VS SAVED for each value. One query rather than one per dimension — per-model cost, cost by reasoning effort, and cost by cache_control breakpoint count are the same GROUP BY over the same columns, and three near-identical functions is three places for the savings arithmetic to drift.

An unknown dimension is an error rather than a silent fallback: a caller that mistypes the dimension must not be handed a chart of some other dimension's numbers.

func (*DB) CacheStateFor added in v0.5.0

func (d *DB) CacheStateFor(f Filter) (*CacheState, error)

CacheStateFor reads the session's most recent cache-touching request. nil, nil = none yet.

func (*DB) CampaignRealSavings

func (d *DB) CampaignRealSavings(strategyIDs, tenantIDs []string, since int64) ([]CampaignSavingCell, error)

CampaignRealSavings computes real, time-bounded economics per (tenant, hour-of-day) cell for a set of strategies (this campaign's own, so the cost half is exact) and the tenants they target (so the saving half's ceiling is at least scoped to the right accounts). since is a campaign's own activated_at, in epoch milliseconds — never 0 meaning "no bound", because that would silently fold in pre-campaign history.

Returns one cell per (tenant, hour) that had ANY ping or any real credited request since `since` — a cell absent from the result had neither, not a cell this query forgot to report.

func (*DB) CapCorrection added in v0.7.2

func (d *DB) CapCorrection(f Filter, windows modelinfo.Resolver, p modelinfo.Pricer) CapResult

CapCorrection is the correction the headline applies for the capped credit of one filter. The two ledgers run on their own, as they do for the headline: one that fails leaves the other's correction in place and sets NotApplied, so a reader lands where the headline lands. It is the one place the two are added, so a reader that cannot take a ledger row by row still agrees with the headline. Both ledgers stream the rows f selects, so the cost follows f: give it a session or a window, not the whole table (#502).

func (*DB) Close

func (d *DB) Close() error

Close releases the database.

func (*DB) CompactionEpisodesFor added in v0.2.0

func (d *DB) CompactionEpisodesFor(f Filter, windows modelinfo.Resolver, p modelinfo.Pricer,
	cfg KVCacheSimConfig, spanFrac, fillFrac, ceilingFrac float64) (*CompactionEpisodes, error)

CompactionEpisodesFor measures every episode one filter selects.

windows is read through modelinfo.Exact, so a resolver that cannot say whether its answer is published is treated as inexact and its conversations are excluded rather than measured against a guess.

func (*DB) Components

func (d *DB) Components(f Filter) ([]*ComponentRow, error)

Components aggregates per-component accounting over the filtered window.

func (*DB) CostlySettings added in v0.5.4

func (d *DB) CostlySettings(f Filter) (*CostlyDoc, error)

CostlySettings builds the document for one scope.

func (*DB) Currency added in v0.7.4

func (d *DB) Currency(f Filter) (string, error)

Currency is the one unit of the priced rows in the filter: USD when there are none, CurrencyMixed when there are two or more. Only priced rows count. An unpriced row costs nothing in any unit, and it would otherwise make every Bob view mixed with the USD default it is stored with.

func (*DB) DeclCreditFor

func (d *DB) DeclCreditFor(f Filter, price func(string) (modelinfo.Price, bool)) (*DeclCredit, error)

DeclCreditFor totals the filter's saving over one scope.

func (*DB) DeclFilterSavings

func (d *DB) DeclFilterSavings(f Filter, price func(string) (modelinfo.Price, bool)) (*DeclFilterSaving, error)

DeclFilterSavings totals the realized saving over a scope.

One row at a time rather than one SUM, for the same reason the inventory report is built in Go: each row's tokens are priced at ITS model's rates and ITS cache tier, and no aggregate can express that without either picking one model or blending rates that belong to none.

func (*DB) DeclFilterSavingsByTenant

func (d *DB) DeclFilterSavingsByTenant(since int64, price func(string) (modelinfo.Price, bool)) (map[string]*DeclFilterSaving, error)

DeclFilterSavingsByTenant is DeclFilterSavings for every tenant since a given time, in one pass instead of one call per tenant, which would re-pay the same table scan N times over.

func (*DB) DecomposeComponentSavedUSD

func (d *DB) DecomposeComponentSavedUSD(f Filter, p modelinfo.Pricer, out []*ComponentRow) error

DecomposeComponentSavedUSD splits each component's dollar value into the two halves it is made of — the FIRST removal of a piece of content, and every later turn that same removal was re-earned on — and prices each at the tier the requests behind it actually paid.

WHY THIS EXISTS. This dashboard and the proxy's own /stats endpoint report opposite signs for the same component. On measured traffic extract_llm reads +$1.40 saved here and −$0.82 there, and until now nothing on either surface acknowledged the other existed. The gap is not a disagreement about facts; it is one arithmetic step:

  • /stats prices each piece of removed content ONCE. That answers "did this turn's call pay for itself?"
  • This dashboard prices it on every turn it stayed removed for, because the agent re-sends its whole transcript each turn and content we removed at turn k is still absent at turns k+1…N. That answers "has this component paid for itself across the sessions it ran in?"

Both are defensible and they differ by the replay multiple — 51.9x for extract_llm. A reader cannot check either number, or understand why a component is green here and red in an operator's terminal, unless both halves are on screen. So both are.

It needs no new column: request_components already stores saved_gross and saved_unique per component per request, which is exactly the decomposition, and the tiers are on the request. Everything here is valued at READ time from those, over every priced row rather than only the un-backfilled ones, which is also what makes it a cross-check on the stored figure — see ComponentRow.SavedUSDDecomposed.

func (*DB) DropOldestSessions

func (d *DB) DropOldestSessions(n int) (int64, error)

DropOldestSessions deletes the n least-recently-active SESSIONS and returns how many request rows went with them. Component and content rows follow via ON DELETE CASCADE.

Session granularity, not row granularity, and that is the whole point: evicting the oldest individual requests tears conversations in half, so the dashboard shows a session whose first turns have vanished and whose totals no longer add up. A session is the unit a user reasons about, so it is the unit that disappears.

"Oldest" is MAX(ts) per session — last activity, not first. A long-running session that is still in use must not be evicted because it started a week ago.

The victims are picked ONCE, and the delete removes exactly that set (#772). The delete used to re-run the ordering subquery itself, so a request landing between the pick and the delete could change the order: the rows it removed were then not the rows the state cleanup acted on, and a session that stayed lost its state to one that went. The delete runs in chunks of sqlChunk ids, each chunk one statement and so one transaction. A failed chunk returns before the state cleanup, so victims the earlier chunks already removed keep their state until retention — the safe direction. The pick stays outside the deletes, like every other read here (ArchiveSessionFull reads its events outside its delete too): a read-then-write transaction on this shared pool can fail to upgrade its WAL snapshot when the session-state flush commits in between.

func (*DB) DropOldestSessionsOfTenant

func (d *DB) DropOldestSessionsOfTenant(tenant string, targetRows int64) (int64, error)

DropOldestSessionsOfTenant trims one tenant back toward its quota, oldest session first, and returns the rows deleted. DESTRUCTIVE, and only correct when there is no cold storage to migrate to — Recorder.trimTenantToQuota picks between the two. The dropped sessions' state rows go with them, exactly as in DropOldestSessions (#772).

func (*DB) EstimateComponentSavedUSD

func (d *DB) EstimateComponentSavedUSD(f Filter, p modelinfo.Pricer, out []*ComponentRow) error

EstimateComponentSavedUSD fills SavedUSDEstimated on component rows whose stored saved_usd predates the column, and recomputes NetUSDWithEstimate. Rows that already carry a stored figure are untouched, so the estimate can only ever ADD to history and never restate the present. Nothing happens without a Pricer — an unpriced deployment keeps reading 0.00, which is the honest answer there.

func (*DB) Facets

func (d *DB) Facets(f Filter) (map[string][]string, error)

Facets returns the distinct values available for each filter dimension, so the UI's dropdowns show only what the data actually contains.

func (*DB) FacetsFor added in v0.5.4

func (d *DB) FacetsFor(f Filter, home string) (map[string][]string, error)

FacetsFor is Facets with the project dimension rolled up to project roots.

WHY A SEPARATE ENTRY POINT. Facets reads raw columns, and the project column holds every working directory a session was launched in: on a real machine, 40 folders for six projects, the rest being subdirectories of the same repositories and eighteen throwaway /private/tmp directories. Reported as "I don't understand why I saw so many projects".

`home` overrides the home directory, for tests. An empty transcript directory -- the normal state of a hosted proxy, which cannot see the user's disk -- leaves the list unrolled, which degrades to the raw folders rather than to an empty picker.

func (*DB) FiveHourRows added in v0.7.3

func (d *DB) FiveHourRows(f Filter, sinceMs int64) ([]FiveHourRow, error)

FiveHourRows reads the rows for the fit: the newest rows since sinceMs that carry a 5-hour share and reset, for the filter's tenant (every tenant when f.TenantAll). Numbers and the model name only. Pings and the requests sent in place of a ping count too: they used the limit as well. A row carries the share only when the user's own credential sent it (#984), so a row sent with another credential is never in the fit.

func (*DB) InsertEvents added in v0.5.2

func (d *DB) InsertEvents(evs []*Event) error

InsertEvents writes events straight to the store in one transaction, without the recorder's queue. For test fixtures in other packages.

func (*DB) IsDeferredDecl added in v0.6.1

func (d *DB) IsDeferredDecl(tenant, name string) (bool, error)

IsDeferredDecl reports whether tenant has carried name as a deferred MCP tool: the exact tool, or, for the whole-server form `mcp__<server>`, any tool of that server.

func (*DB) KVCacheAnalyze

func (d *DB) KVCacheAnalyze(f Filter, o KVCacheOptions, p modelinfo.Pricer,
	cfg KVCacheSimConfig) (*KVCacheAnalysis, error)

KVCacheAnalyze reads the dataset and aggregates it.

func (*DB) KVCacheDataset

func (d *DB) KVCacheDataset(f Filter, o KVCacheOptions) ([]*kvcache.Request, int64, error)

KVCacheDataset reads the derived dataset for one filter, CHRONOLOGICALLY, and reports how many rows matched.

Chronological regardless of the table's own sort, because the replay walks it in wall-clock order and the table's sort is a view of the same rows. Over the cap the NEWEST rows are kept: an analysis of the recent past is useful, and one that silently stopped at some point in the middle of the window is not.

func (*DB) KVCacheMedianPrefix

func (d *DB) KVCacheMedianPrefix(f Filter, o KVCacheOptions) (int64, error)

KVCacheMedianPrefix is the median billed prefix (cache_read + cache_write) of the requests that CACHED SOMETHING, over the same rows the analysis describes.

Three things had to line up here and none of them did. It took only a Filter, so the page's own narrowings (time-of-day band, tier, has-a-successor) never reached it and the pricing panel printed a median 2.5x away from the card directly above it — both labelled "this window's own median". It had no LIMIT, so it was the one read on the page the stated 200,000-row ceiling did not apply to: it materialised a float64 per matching row and sorted the lot, scaling with the tenant rather than with the cap. And it medianed over EVERY request, including the ones that cached nothing, which is the population bias described on KVCacheCards.CachedContextP50.

So it now takes the options too, is built through kvCacheQuery like every other read on this page, excludes zero-prefix rows, and is bounded by the same ceiling — newest first, so the rows it medians are the rows the analysis kept.

NOT tokens_before, which is message text only and runs a median 3.4x low — the same correction the keep-alive tab's calculator applies. Exact rather than interpolated, for the reason pctlF is: an estimate here is a number nobody can reproduce.

func (*DB) KVCacheModels

func (d *DB) KVCacheModels(f Filter) ([]string, error)

KVCacheModels is the distinct models in one window, so the pricing panel has a row for every model the reader could be pricing — including the ones with no rates.

func (*DB) KVCacheRows

func (d *DB) KVCacheRows(f Filter, o KVCacheOptions) (*KVCacheRowPage, error)

KVCacheRows reads one page of the sortable detail table.

Offset paging, not keyset, because this table is SORTABLE on thirteen columns: a keyset cursor is a value in the sort order, so every re-sort would invalidate it. The page is bounded and the derivation is unaffected by the boundary — the window function runs over the whole scoped window inside the CTE and only the outer SELECT is paged, so a row on page 7 carries the same successor it would on page 1.

func (*DB) KVCacheSimulate

func (d *DB) KVCacheSimulate(f Filter, o KVCacheOptions, p modelinfo.Pricer,
	cfg KVCacheSimConfig) (*KVCacheSimulation, error)

KVCacheSimulate replays one window under every requested strategy.

func (*DB) KVCacheSuggest

func (d *DB) KVCacheSuggest(f Filter, o KVCacheOptions, p modelinfo.Pricer,
	cfg KVCacheSimConfig) (*KVCacheSuggestions, error)

KVCacheSuggest builds the per-user, per-hour strategy suggestion.

func (*DB) KVCacheSuggestBy added in v0.5.3

func (d *DB) KVCacheSuggestBy(f Filter, o KVCacheOptions, p modelinfo.Pricer, cfg KVCacheSimConfig,
	seg Segmenter) (*KVCacheSegments, error)

KVCacheSuggestBy is KVCacheSuggest with one more key on every cell: (user, hour, segment) instead of (user, hour), and seg instead of the Sunday-Thursday filter.

It answers "would a policy that ALSO knew the weekday (or the model, or the agent) have done better?" with the SAME per-cell decision KVCacheSuggest makes — kvSuggestCell, unchanged — so the two are comparable cell for cell. The campaign upload format has no segment field; this is for analysis, not for enforcement.

func (*DB) KVCacheSuggestHoldout

func (d *DB) KVCacheSuggestHoldout(f Filter, o KVCacheOptions, p modelinfo.Pricer,
	cfg KVCacheSimConfig, train, test Window) (*KVCacheHoldout, error)

KVCacheSuggestHoldout runs the suggester over a train window and a disjoint test window, and joins them per (user, hour): the arm train chose, and what that same arm actually saved on rows it was not chosen on.

f carries the scope (tenant, model, agent…) and is applied to BOTH windows — only the time bounds differ between them, so the two populations are the same slice of traffic observed over two periods rather than two different slices.

func (*DB) KeepAliveBehaviour

func (d *DB) KeepAliveBehaviour(f Filter, coverageSeconds float64) (*KeepAliveBehaviour, error)

KeepAliveBehaviour computes the behavioural panels for one window.

coverageSeconds is the policy the gap bands are marked against (K*X + TTL); 0 falls back to the shipped default's 840 s.

func (*DB) KeepAliveCalc

func (d *DB) KeepAliveCalc(f Filter, idleSeconds float64, prefix int64, model string,
	price func(string) (modelinfo.Price, bool), k int, wait keepalive.Policy) (*KeepAliveCalc, error)

KeepAliveCalc replays the account's own gaps against the K ladder at one idle interval.

Pricing rests on TWO caller-supplied representatives, not per-row values: the prefix and the model. One modelinfo.Price is resolved from the model argument up front and reused for every row and every K, so an account that runs several models is priced at its representative's rates, not each row's own. The prefix is supplied for the same reason: per-ping cost is bimodal (p50 $0.0004, p99 $0.2275) and there is no honest average of it. The rates themselves are the operator's price list; a model missing from it leaves every dollar field omitted (Priced above).

wait is the account's policy for the per-wait plan (#868): WaitPlan on gives the ladder a "wait_plan" rung, the live plan with base k, marked current, above the fixed-K rungs it is compared with. WaitPlan off (the account's keepalive_wait_plan: false) gives fixed-K rungs only, the one with K = k marked current. Only the tuning fields of wait are read; its MaxPings is replaced by k.

func (*DB) KeepAliveLatencyDiagnostic

func (d *DB) KeepAliveLatencyDiagnostic(f Filter) (kvcache.Latency, error)

KeepAliveLatencyDiagnostic reports the window's own measured hit-vs-write latency differential for large-context requests, reusing kvcache.MeasureLatency's shape (mean per cohort, gated at N>=20 — Known=false below that rather than a difference of two noisy means). A diagnostic about the MECHANISM — a cache hit is faster than a cache write — not a per-request or per-dollar claim: see kvcache.Latency's own comment for why, and why no per-request counterfactual is computed anywhere in this codebase.

func (*DB) KeepAliveLedger

func (d *DB) KeepAliveLedger(f Filter) (*KeepAliveLedger, error)

KeepAliveLedger computes the ledger for one filtered window.

func (*DB) KeepAliveLive

func (d *DB) KeepAliveLive(f Filter, now int64, idleSeconds float64, maxPings int,
	price func(string) (modelinfo.Price, bool)) (*KeepAliveLive, error)

KeepAliveLive lists the sessions whose provider cache entry has not yet lapsed.

`now` is passed in rather than read, for the same reason the keeper's clock is: a function that reads the wall clock cannot be tested against a fixture.

func (*DB) KeepAliveNetUSDByTenant

func (d *DB) KeepAliveNetUSDByTenant(since int64) (map[string]float64, error)

KeepAliveNetUSDByTenant is the keep-alive net (credit minus ping spend) for every tenant since a given time, in one pass — the exporter's per-tenant series otherwise needs one query per tenant.

func (*DB) KeepAliveRecommend

func (d *DB) KeepAliveRecommend(f Filter, wait keepalive.Policy) (*KeepAliveRecommendation, error)

KeepAliveRecommend answers "what should I set?" — or refuses.

wait is the account's policy (#868). With WaitPlan on the interval is the live plan's (base recMaxPings) and the fixed-K interval comes beside it; with WaitPlan off the interval is the fixed-K one, as before #858.

func (*DB) KeepAliveRecommendLearned added in v0.7.3

func (d *DB) KeepAliveRecommendLearned(f Filter, wait keepalive.Policy, fit FiveHourFit) (*KeepAliveRecommendation, error)

KeepAliveRecommendLearned is KeepAliveRecommend plus the forecast at the learned 5-hour weights (Learned), from a fit that passed the gate.

func (*DB) KeepAliveSessions

func (d *DB) KeepAliveSessions(f Filter, limit int) ([]*KeepAliveSessionRow, error)

KeepAliveSessions lists the sessions this window's addressable expiries are concentrated in, costliest first, with each one's own keep-alive ledger.

The concentration is real and it does NOT transfer forward: the top 8 sessions hold $431 of $734.75, and a list fitted on one half of the week earned $5.27 in the next half where the plain account-wide rule earned $53.32. The panel says that above the table.

func (*DB) LastBilledPrefix

func (d *DB) LastBilledPrefix(f Filter, session string) (int64, string, error)

LastBilledPrefix is one session's most recent billed prefix and model, from AGENT rows only. The number a person is shown before authorizing an override on that session.

func (*DB) LastBilledProvider added in v0.7.10

func (d *DB) LastBilledProvider(f Filter, session string) (string, error)

LastBilledProvider is the provider of the session's most recent request, as the request path stored it ("anthropic", "openai", ...). Empty when the session has no row.

func (*DB) LatestAuthSubscription added in v0.7.2

func (d *DB) LatestAuthSubscription(f Filter) (bool, error)

LatestAuthSubscription reports the auth kind of the account's newest Anthropic request: true when the client sent a Claude subscription (OAuth) token. Keep-alive pings are left out: the proxy sends them, so they carry no client auth kind. false when there is no such request.

func (*DB) LatestLimits added in v0.7.2

func (d *DB) LatestLimits(f Filter) (*Limits, int64, error)

LatestLimits is the newest row's limit values for the filter's tenant (or every tenant when f.TenantAll), and the row's time in epoch ms. nil when no row has any.

func (*DB) Lifecycles added in v0.5.0

func (d *DB) Lifecycles(tenant string) ([]LifecycleRow, error)

Lifecycles returns the stored lifecycle rows of one tenant, oldest request first. It is the read side for analysis and tests; nothing in the UI uses it, and it takes the tenant so an endpoint built on it cannot leak across tenants.

func (*DB) MonthToDateUSD

func (d *DB) MonthToDateUSD(tenantID string) (float64, error)

MonthToDateUSD returns a tenant's billed cost since the start of the current calendar month, for display.

Calendar month rather than a rolling 30 days, because a budget is something a person reconciles against a monthly invoice — a rolling window means the number a user sees never matches the number finance sees.

Includes cg_llm_cost_usd: context-guru's compaction calls go out on the same credential the request carried, so a tenant that enables extract_llm is spending their own money through us and the figure has to show it.

It reads the tenant_spend ROLLUP, not a SUM over the requests table, and that is the whole point. Retention — the age rule, the byte budget, the per-tenant row quota, the disk rule — deletes request rows, so a sum over them is a spend figure that silently shrinks as history is evicted: 120k requests worth $50 against a 100k-row quota loses the oldest 20k rows and under-reports the month. The rollup is incremented in the insert transaction and nothing ever deletes from it.

New failure modes, stated plainly:

  • It is MONOTONIC within a month. Deleting rows by hand, or restoring a database, does not refund spend; only the calendar turning over resets it.
  • It counts what the recorder WROTE. Events dropped by a full capture queue are not billed — the same under-count the old SUM had, and /api/capture reports it.
  • It lives in the dashboard database. The in-memory fallback (an unwritable path) starts the month's total at zero, so the figure under-counts for the rest of that month; it logs loudly. A schema-version bump no longer does this — Open carries this table across from the preserved file (see carryNonDerived).
  • A missing row means zero, not an error: a tenant that has not spent yet and a tenant whose month just turned over are the same fact.

A lookup error returns an error, and every caller treats it as cosmetic: a settings page with no spend figure on it is a nuisance, and failing a request over it would not be.

func (*DB) NextInputTokens added in v0.7.10

func (d *DB) NextInputTokens(f Filter, model string) int64

NextInputTokens is the new input to expect on the next real request of a model in the session: the median of fresh_input + cache_write (the tokens not read from the cache; on Anthropic a new turn is billed as cache write) of the last NextInputWindow billed requests of that model (pings and non-2xx rows excluded). With none, the same median over the whole session. With none either, or on a read error, DefaultNextInputTokens. It reads token counts only. DefaultNextInputTokens lives here because only the dashboard's own database can measure it.

func (*DB) OrphanRows

func (d *DB) OrphanRows() (components, content int64, err error)

OrphanRows counts child rows whose request is gone — component rows and content rows with no parent. It is a WHOLE-TABLE check, not per tenant, because that is the failure it exists to catch: a delete that took the parents and left the children belonging to nobody, which no tenant-scoped query can see.

func (*DB) Overview

func (d *DB) Overview(f Filter) (*Overview, error)

Overview computes the headline aggregates for the filtered window.

func (*DB) OverviewLean added in v0.5.0

func (d *DB) OverviewLean(f Filter, priceFn func(string) (modelinfo.Price, bool)) (*Overview, error)

OverviewLean answers /api/stats?lean=1 (dash/api.go's statsLean branch) — see #502.

For a SESSION or a concrete time window (anything but true lifetime), it runs 1 bounded aggregate (overviewLeanWindow), which also carries the `tokens` object's terms (#998), instead of Overview()'s 16 queries, because lean reads only a handful of their outputs: confirmed against context-guru-plugin/scripts/statusline.py and scripts/cg.py, lean needs total_saved_usd, keepalive_net_usd, keepalive_misses_avoided, upstream_ms_avg, cg_latency_ms_avg, cost_usd, baseline_cost_usd, cache_saved_usd, and the waterfall rows keyed "compaction", "keepalive_saved", "keepalive_ping", "decl_filter_saved", "cg_llm", plus the saved token counts saved_unique, saved_gross and replay_tokens (the status line's `rd / wr`, #990) — every one a plain SUM/AVG of a `requests` column or arithmetic on them, bounded by the session or the time window, same index Overview()'s own main aggregate already uses. The 7 goroutines Overview() runs beyond that aggregate (the replay ceiling, its keep-alive correction, CompactionResets, the TTL/accounting breakdown, 2 invalid-config counts, the estimator-divergence query, the p95-latency query) feed none of those fields, and the replay ceiling and CompactionResets among them are exactly the per-session window queries #492 measured as slow. OverviewLean never runs any of them.

TRUE lifetime (`since=0`, no session, no window) is not answered here: dash/api.go sends a lean call with neither bound to the full handler, which is exact. The status line stopped reading lifetime (#510), so lean is only ever a bounded read.

The read-time-priced credit (DeclFilterSavings) is included for SESSION and DAY scope: its SELECT is a plain filtered scan, bounded by the same index as the main aggregate for a session OR a time window.

func (*DB) Path

func (d *DB) Path() string

Path returns the on-disk path ("" when in-memory).

func (*DB) PingTokensSince added in v0.7.3

func (d *DB) PingTokensSince(f Filter, sinceMs int64) (FiveHourPing, error)

PingTokensSince is what the cache strategy's automatic pings billed since sinceMs, by tier, for the 5-hour estimate: the pings used the limit too, and the dollar estimate nets their cost.

func (*DB) PromptViewFor

func (d *DB) PromptViewFor(f Filter) (*PromptView, error)

PromptViewFor returns the most recently captured prefix in scope whose text was stored, falling back to the most recent one at all so the caller still learns the WEIGHTS when the text is absent.

One session's rows, chosen by the newest ts. The alternative — the union of every name ever declared — would be a prompt no request ever carried, with two versions of the same tool's schema in it.

func (*DB) Prune

func (d *DB) Prune(now time.Time, maxAge time.Duration, maxBytes int64) (int64, error)

Prune enforces retention by BOTH age and size, in that order: drop everything older than maxAge, then — if the file is still over maxBytes — drop the oldest requests until it fits. Age alone cannot bound a burst; size alone silently erases a quiet week. Content rows and component rows go with their request via ON DELETE CASCADE. Returns how many request rows were deleted.

maxAge <= 0 disables the age rule; maxBytes <= 0 disables the size rule.

This form has no size floor, no backup hook and no eviction hook; the janitor calls PruneWith. The size rule keeps every session whose last request is newer than defaultActiveSessionWindow (1 hour): it deletes rows of such a session only when that one session is over maxBytes by itself. It deletes whole idle sessions, oldest last activity first, not single rows.

func (*DB) PruneWith added in v0.7.4

func (d *DB) PruneWith(now time.Time, o PruneOptions) (int64, error)

PruneWith is Prune with the full set of options. See PruneOptions.

func (*DB) RecentSessions added in v0.5.4

func (d *DB) RecentSessions(f Filter, n int) ([]string, error)

ToolReportFor builds the report for one filter scope. price resolves a model's rates and may be nil, in which case nothing is priced and the report says so.

Aggregation happens in Go rather than in one SQL statement on purpose: the rows are per session (a few tens per session, a few thousand in a scope), and the pricing step needs each session's own model and cache tiers — which is a join no aggregate SUM can express honestly. RecentSessions returns the ids of the `n` most recently ACTIVE sessions the filter selects, newest first, for a caller that wants to window a report to "the last N sessions".

WHY RECENCY IS LAST ACTIVITY AND NOT FIRST. A session opened on Monday and still being worked in on Friday is a current session. Ordered by its first request it ranks behind every session opened since, so a "last 10" window would exclude the one the user is sitting in. MAX(ts) is therefore the key, not MIN(ts).

WHY THIS EXISTS AT ALL. A folder worked in for three months, with a plugin installed three weeks ago, has an inventory dominated by the ninety days before that plugin existed — the aggregate averages its skills over sessions that never declared them and reports them as nearly free. Windowing to recent sessions is what makes a newly installed, barely used plugin visible.

Asking for more sessions than exist returns what exists: a fresh install has one session, and a selector offering "last 10" has to work there too.

func (*DB) ReplayLedgerFor added in v0.5.2

func (d *DB) ReplayLedgerFor(f Filter, windows modelinfo.Resolver, p modelinfo.Pricer) (*ReplayLedger, error)

ReplayLedgerFor streams the rows one filter selects and runs the cap session by session. A model whose window is not exactly known is capped against an assumed window.

Memory is bounded by the largest single session in the scope (about 120 bytes per request plus its credit rows), not by the scope: the ledger itself is a few counters per component.

func (*DB) ReplayLedgerForCtx added in v0.5.2

func (d *DB) ReplayLedgerForCtx(ctx context.Context, f Filter, windows modelinfo.Resolver, p modelinfo.Pricer) (*ReplayLedger, error)

ReplayLedgerForCtx is ReplayLedgerFor under a caller's context, so a caller that no longer needs the answer can stop the scan.

func (*DB) Request

func (d *DB) Request(id int64, withContent bool) (*Event, error)

Request returns one request with its component rows and, when content was captured, its before/after blobs. withContent=false omits the content entirely (the caller decides, based on the access gate).

func (*DB) Requests

func (d *DB) Requests(f Filter, before int64, limit int) (*Page, error)

Requests returns a page of requests newest-first, using KEYSET pagination: `before` is the last id seen, not an OFFSET. Offset pagination re-scans the skipped rows, so page 500 of a busy proxy's history costs 500 pages of work; keyset is O(limit) at any depth and cannot skip or duplicate a row when new requests arrive mid-browse.

func (*DB) SQL added in v0.6.4

func (d *DB) SQL() *sql.DB

SQL returns the underlying handle, for a host that keeps a table of its own in this database. The session state store (package store) does: it shares this pool, so one pool serializes every writer in the process. The caller must not close it.

func (*DB) SaveMoreTools added in v0.6.7

func (d *DB) SaveMoreTools(f Filter, price func(string) (modelinfo.Price, bool), host SaveMoreToolsHost) (*SaveMoreToolsDoc, error)

SaveMoreTools builds the report for f, one account's scope.

func (*DB) SavingsTotals added in v0.2.0

func (d *DB) SavingsTotals(f Filter) (*SavingsTotals, error)

SavingsTotals computes the combined savings figure for the filtered window: two queries (agent traffic, then ping cost — see Filter.WithKeepAlive for why those cannot be one query) rather than Overview's sixteen. Cheap enough to run synchronously per request on a single-tenant deployment's own DB, which is the shape proxy.Handler.stats() runs against. A caller summing several sessions (e.g. every live keep-alive session) should pass Filter.SessionIn rather than looping — the two queries above already aggregate across however many session ids the IN-clause names.

func (*DB) SavingsTotalsCapped added in v0.7.2

func (d *DB) SavingsTotalsCapped(f Filter, windows modelinfo.Resolver, p modelinfo.Pricer) (*SavingsTotals, error)

SavingsTotalsCapped is SavingsTotals with the cap applied, so a scope agrees with the headline for the same rows. The baseline, net and total agree with the lean headline; the full headline adds a historical split figure and a declaration-filter credit to its total that SavingsTotals has never carried. When the cap cannot be computed in full the figure keeps the part that ran and CapNotApplied is set: a reader gets a labelled figure and not an error.

Use it for a scope that one session or one window bounds. A lifetime read (an empty filter) streams every row through the ledgers: use SavingsTotals there and say so.

func (*DB) SelfRemovals

func (d *DB) SelfRemovals(f Filter, price func(string) (modelinfo.Price, bool), removed []string) ([]SelfRemoval, error)

SelfRemovals finds declarations the account STOPPED carrying partway through the window.

This is the one saving this dashboard causes and could not see. Every other measurement here is about content a component removed; when a user reads this page, runs `claude mcp remove` and stops carrying 4,000 tokens on every request, no component ran and no filter fired, so the reduction landed in no figure anywhere. The product got no credit for the outcome it most wants to cause.

The method needs no new capture, only the observation that tool_declarations is a TIME SERIES keyed by session: a name that appears in the early sessions of a window and in none of the late ones stopped being declared. What makes that a claim rather than a guess is the number of sessions that ran AFTERWARDS without it — one proves nothing (a session may simply not have needed it), a dozen is strong. That count is returned on every row and the UI shows it, rather than a threshold being applied here and the weak rows silently dropped.

Deliberately NOT netted into the declaration filter's realized savings: an account that both removed a server locally and has it on its server-side filter list would otherwise be credited twice for one reduction. Rows in that position are marked Overlap and left for the reader.

func (*DB) Series

func (d *DB) Series(f Filter, bucketMs int64) ([]*Bucket, error)

Series buckets the filtered window into fixed-width buckets of bucketMs.

func (*DB) SeriesBucketFor added in v0.5.0

func (d *DB) SeriesBucketFor(f Filter, bucketMs int64) int64

SeriesBucketFor returns the bucket width Series should use for a request of bucketMs over the window f selects: bucketMs itself when it yields at most seriesMaxBuckets buckets, else the smallest whole multiple of it that does. A multiple, so every coarse bucket is a union of the fine ones the caller asked for and sums stay comparable.

func (*DB) SessionEvents

func (d *DB) SessionEvents(f Filter, sessionID string, withContent bool) ([]*Event, error)

SessionEvents returns ALL of one session's requests oldest-first, scoped by f. It is the ARCHIVE path's read: an upload has to carry the whole session, or the object it writes misreports what was captured. Anything user-facing wants SessionEventsPage — one session in this corpus reaches 31,425 diff blocks and ~78 MB of JSON, which is a browser crash rather than a page.

func (*DB) SessionEventsPage

func (d *DB) SessionEventsPage(f Filter, sessionID string, withContent bool, after string, limit int) (*TranscriptPage, error)

SessionEventsPage returns one page of a session's requests oldest-first, scoped by f — so a hosted caller can only ever name a session that is theirs, and a session id belonging to somebody else comes back as zero rows rather than as a 403 that confirms it exists.

Pagination is KEYSET, the same shape Requests already uses: `after` is the last (ts, id) seen, not an OFFSET, so page 50 of a long session costs what page 1 costs and no turn is skipped or repeated while the session is still being written to. limit <= 0 means unlimited, and is for the archive path only.

func (*DB) Sessions

func (d *DB) Sessions(f Filter, limit, offset int) ([]*SessionRow, int64, error)

Sessions returns the session list, most-recently-active first, filtered and paginated server-side.

func (*DB) SessionsOrdered added in v0.5.0

func (d *DB) SessionsOrdered(f Filter, limit, offset int, byCost bool) ([]*SessionRow, int64, error)

SessionsOrdered is Sessions with a choice of order: newest first, or costliest first (the five-page dashboard's "where did the money go" list).

func (*DB) SpendExplainFor added in v0.5.0

func (d *DB) SpendExplainFor(f Filter, price func(string) (modelinfo.Price, bool), tzMin int, now int64, top int) (*SpendExplain, error)

SpendExplainFor runs the pass. tzMin is the caller's UTC offset in minutes, for day buckets.

func (*DB) StrategyLedger

func (d *DB) StrategyLedger(strategyID string) (*StrategyLedgerView, error)

StrategyLedger computes one strategy's economics, built the same way KeepAliveSessions already is (dash/keepalive.go), filtered by keepalive_strategy_id instead of by Filter.Tenant.

Pings, PingUSD, and now SavedUSD are all EXACT: every ping row this strategy caused carries its id (proxy's record1), and every REAL row a ping later rescued carries the same id (keeper.arrive, threaded through capture — see dash/schema.go's keepalive_strategy_id comment). A tenant running more than one strategy over time no longer has its whole lifetime credit repeated under each one — a credited request is attributed to whichever strategy's ping(s) actually preceded it, once.

func (*DB) SummarizeLedgerFor added in v0.5.2

func (d *DB) SummarizeLedgerFor(f Filter, windows modelinfo.Resolver, p modelinfo.Pricer) (*SummarizeLedger, error)

SummarizeLedgerFor runs the walk over the sessions in which summarize ever acted and returns its ledger. A conversation whose model window is not exactly known contributes nothing, so its credit stays as stored: the same rule the episode view uses for the same reason.

It walks each summarizer component on its own and returns the sum, so the headline is the sum of the per-component figures SummarizeLedgersFor gives the Components tab.

func (*DB) SummarizeLedgersFor added in v0.5.2

func (d *DB) SummarizeLedgersFor(f Filter, windows modelinfo.Resolver, p modelinfo.Pricer) (map[string]*SummarizeLedger, error)

SummarizeLedgersFor is one ledger per summarizer component, keyed by component name.

func (*DB) SweepLedgerFor added in v0.6.0

func (d *DB) SweepLedgerFor(ctx context.Context, f Filter, p modelinfo.Pricer) (*SweepLedger, error)

SweepLedgerFor reads the ledger for the filtered window. p prices the expand charge; with nil p the charge is 0 and everything else is exact.

func (*DB) TenantHasRows

func (d *DB) TenantHasRows(tenantID string) (bool, error)

TenantHasRows reports whether any local row still names this tenant. Used by the deletion path's own check, and by its test: "no orphans left" is the property, and a caller that cannot ask cannot assert it.

func (*DB) TenantMetrics

func (d *DB) TenantMetrics(since int64) ([]TenantMetricRow, error)

TenantMetrics rolls up per-tenant traffic since `since` (epoch ms), for the Prometheus exporter.

One query with a LEFT JOIN onto the archive index rather than two and a merge in Go: a tenant that has ONLY archived data still needs a row, or its history would vanish from Grafana the moment its last live session was archived.

func (*DB) TenantRowCounts

func (d *DB) TenantRowCounts() (map[string]int64, error)

TenantRowCounts reports how many request rows each tenant holds. The caller compares each against that tenant's own quota, which is why this does not filter: the quota is per tenant now (a manager sets it), so there is no single threshold to push into the query.

Fairness before scarcity: without this, the global disk rule lets one heavy user's traffic evict everyone else's history, which is the shared-service failure where the person causing the problem is the last to notice it.

func (*DB) ThreadsFor added in v0.5.0

func (d *DB) ThreadsFor(f Filter, sinceMS int64) ([]ThreadCache, *SessionMoney, error)

ThreadsFor lists the session's per-thread cache entries touched since sinceMS (at most 16, most recent first) and the session's money split into the main thread and every other one. Two indexed reads of the session's rows (cacheThreadsQuery, cacheTTLQuery), whatever the number of threads.

func (*DB) TierCosts

func (d *DB) TierCosts(f Filter, p modelinfo.Pricer) (*TierCosts, error)

TierCosts prices the window by tier. Read-only, one row per model.

func (*DB) ToolDeferReportFor added in v0.6.7

func (d *DB) ToolDeferReportFor(f Filter) (*ToolDeferReport, error)

ToolDeferReportFor reads deferral's per-day ledger over f. A request deferral did not change has defer_tokens = 0 and is not read.

func (*DB) ToolFilterDocFor

func (d *DB) ToolFilterDocFor(f Filter, price func(string) (modelinfo.Price, bool), state ToolFilterState) (*ToolFilterDoc, error)

ToolFilterDocFor builds the control document for one scope. state may be the zero value, which is a deployment with no per-account configuration: the analysis is served and the control is reported unavailable.

func (*DB) ToolReportFor

func (d *DB) ToolReportFor(f Filter, price func(string) (modelinfo.Price, bool)) (*ToolReport, error)

func (*DB) ToolTimeline added in v0.5.4

func (d *DB) ToolTimeline(f Filter, days int) (*ToolTimeline, error)

ToolTimeline builds the per-item series. `days` of 0 means every day the store holds; a positive value keeps only that many most recent days, so a three-month history does not force ninety bars into a sparkline.

The default is deliberately unbounded: the value of this view is seeing a phase CHANGE, and a default window would hide the phase before it — which is the exact question the reader came with.

func (*DB) ToolsLastUsed added in v0.5.0

func (d *DB) ToolsLastUsed(f Filter) ([]toolLastUsed, error)

func (*DB) WithContext

func (d *DB) WithContext(ctx context.Context) *DB

WithContext returns a handle whose reads are cancellable, for a caller that has one.

The KV-cache analysis reads up to kvCacheMaxRows rows and builds a Request per row, which is ~135 MB and several seconds at the ceiling. Without a context that work continued after the client had gone: a request killed 1.5 s in still burned 7.1 s of CPU and allocated to completion, so a reader who hits refresh five times commits five times the memory and gets none of it back. Reads made through this handle stop when the request does.

type DayPoint

type DayPoint struct {
	Day    string  `json:"day"`
	TS     int64   `json:"ts"`
	Misses int64   `json:"misses"`
	USD    float64 `json:"usd"`
	// Tokens is the token form of USD: the billed input tokens of the day's expiries, by tier (#1048).
	Tokens     TierTokens `json:"tokens"`
	Requests   int64      `json:"requests"`
	AllUSD     float64    `json:"all_usd"`
	SharePct   float64    `json:"share_pct"`
	MissRatePc float64    `json:"miss_rate_pct"`
}

DayPoint is one day of the "how often, and what did it cost" series.

type Decl

type Decl struct {
	Kind   string `json:"kind"`
	Name   string `json:"name"`
	Server string `json:"server,omitempty"`
	Tokens int    `json:"tokens"`
	// Text is the declaration's OWN slice of the prompt: a tool's whole JSON element, a
	// skill's listing entry, the listing itself for the marker row. It is what the reader
	// has to see to judge a token weight — "4,723 tokens" is not a fact anybody can act on
	// until they can read the 4,723 tokens.
	//
	// It is the one field here that is CONTENT rather than an identifier, so it is the one
	// field gated on transcript-capture consent. The gate is NOT applied in this file: the
	// text is read on the request path (it is already in the body) and dropped by the
	// WRITER when consent is absent, exactly as extraction_calls drops its before/after
	// while keeping its metrics. Applying it here instead would poison declCache, whose
	// entries are shared by every tenant that declares the same set.
	Text string `json:"text,omitempty"`
	// Deferred marks a tool read from the deferred-tools list, not from `tools`: an MCP tool, or a
	// built-in that Claude Code defers (#866 N9). The proxy filter removes only `tools` elements,
	// so it cannot remove this one: only the user's own change (claude mcp remove,
	// permissions.deny) can.
	Deferred bool `json:"deferred,omitempty"`
}

Decl is one declaration: its name, its classification, and what carrying it costs in tokens (the whole JSON element for a tool, the listing entry for a skill).

type DeclCredit

type DeclCredit struct {
	// The MEASURED half: what the declaration filter actually stopped sending.
	FilterReads    int64   `json:"filter_reads"`
	FilterUSD      float64 `json:"filter_usd"`
	FilterRequests int     `json:"filter_requests"`
	FilterSince    int64   `json:"filter_since,omitempty"`
	// FilterFallbackUSD is the part of FilterUSD on requests the accountant could not price (#1004).
	FilterFallbackUSD float64 `json:"filter_fallback_usd,omitempty"`
	// Priced is false when any contributing model had no rates, in which case the dollar
	// figures are the priced subset only and a consumer must show the token counts instead.
	Priced bool `json:"priced"`
}

DeclCredit is the reduction from declarations the filter stopped sending.

type DeclFilterSaving

type DeclFilterSaving struct {
	// Requests and Sessions are how much traffic the filter acted on.
	Requests int `json:"requests"`
	Sessions int `json:"sessions"`
	// Reads is the billed tokens avoided: the declarations' weight on every request that did
	// not carry them. Named for what it is on the wire — re-reads of a cached prefix are
	// where almost all of it lives.
	Reads int64 `json:"reads"`
	// Since is the first request the filter acted on in this scope, so the figure has a
	// start date rather than an implied "ever".
	Since int64 `json:"since"`
	// Tokens split by the tier the request carrying them was billed at. A prefix that was
	// read from cache would have re-read these at 0.1x; the turn that CREATED the prefix
	// would have written them at 1.25x; a request with no cache at all at 1.0x. Reported
	// split because one blended number cannot be checked.
	CacheReadTokens  int64 `json:"cache_read_tokens"`
	CacheWriteTokens int64 `json:"cache_write_tokens"`
	FreshTokens      int64 `json:"fresh_tokens"`
	// USD is the sum over rows of tokens x that row's tier rate. Priced is false when any
	// contributing model had no known rates, in which case USD is the priced subset only
	// and must not be read as the total — a consumer renders the token count and an
	// "unpriced" mark rather than a dollar.
	USD    float64 `json:"usd"`
	Priced bool    `json:"priced"`
	// FallbackUSD is the part of USD on requests the accountant could not price (requests.acc_fallback).
	// The Overview share leaves those requests out, their saving with them (#1004).
	FallbackUSD float64 `json:"fallback_usd,omitempty"`
}

DeclFilterSaving is the REALIZED accounting: what the filter actually stopped sending, at the tier actually billed.

It is returned as a POINTER and OMITTED when nothing was measured, never rendered as a zero: the page that shows it prints "nothing realized" for an absent figure and would otherwise have to decide for itself whether a zero means "no saving" or "no data". An estimate in this field would silently become a lie on that page, so there is no path that puts one here — the only source is requests.filtered_decl_tokens.

type Denominator

type Denominator struct {
	Key         string  `json:"key"`
	Label       string  `json:"label"`
	Numerator   int64   `json:"numerator"`
	Denominator int64   `json:"denominator"`
	Percent     float64 `json:"percent"`
	// Description states exactly what this ratio divides by and when to trust it.
	Description string `json:"description"`
	// Available is false when the inputs were missing; the UI must then show "n/a"
	// rather than 0%, and never a ratio computed by dividing savings by themselves.
	Available bool `json:"available"`
}

Denominator is one labelled savings ratio. Shipping a single "savings %" is the mistake both reference implementations make in different ways: a whole-request ratio recounts the transcript every turn, so a 200-turn session reads ~0% no matter how well compaction performed, while a compressible-only ratio flatters by excluding everything we chose not to touch. Both are true. Neither is "the" number. So each ratio ships with the denominator it divides by, in words.

type Event

type Event struct {
	ID int64 `json:"id"`
	TS int64 `json:"ts"` // epoch ms
	// TenantID owns this row; "" in single-tenant deployments.
	TenantID  string `json:"tenant_id"`
	SessionID string `json:"session_id"`
	// ThreadID names the thread of the session this request belongs to: "" for the session's
	// primary thread — the main agent, told apart as the first thread without an agent header
	// that declares tools (see package thread) — "a:<agent id>" for a subagent that named itself
	// in a header, and "p:<fingerprint>" for a thread told apart by prefix continuity. Each thread
	// has its own provider cache entry, so recency and miss attribution are per thread; reporting
	// stays per session. See package thread and issue #423.
	//
	// A row keeps the id it was written with. A tool-less request that spoke before the main agent
	// held "" at the time, so its row reads "" although the tracker later moved that thread to a
	// "p:" id.
	ThreadID string `json:"thread_id"`
	// SessionAlias is the session's content-derived alias id (session.Scoped over the
	// normalized head), stored so the restart grace's seed can reload the warmth a request
	// under an EXPLICIT header id also left under the alias id: a later headerless turn
	// derives exactly that alias and asks for it alone (#766). ” on a row with no separate
	// alias — a headerless request's own id IS the alias, and a keep-alive ping carries no
	// body to derive one from — and on every row written before the column existed, which is
	// the documented limit of the seed: the alias warmth of history is gone.
	SessionAlias string `json:"session_alias,omitempty"`
	// AliasFn fills SessionAlias and touches the grace clock under the alias key, on the
	// WRITER goroutine (Recorder.run's write(), beside WaitCause) — never on the request
	// path: the derivation transforms and normalizes the whole body, the same scans the
	// enforced path pays, and finish() runs on the handler's own defer. It derives the id
	// the pipeline's own turn will ask under, through the envelope transform — see
	// apply.EnforcedSessionIDFor. nil on a row with no session id.
	AliasFn func() string `json:"-"`
	// Issue #424's RECORD half: why this thread is about to wait, and why it woke up — read
	// from the request body and the response's own tool calls/stop reason, by string match
	// and structural tool_use reads, no LLM. See waitcause, which defines every
	// value and never guesses: a signal this proxy's client (Claude Code) does not send, or
	// another agent/provider entirely, reads "unknown" rather than a label chosen for it.
	// This package NEVER reads these columns to choose a keep-alive ping budget or change
	// compaction behaviour — it only writes them, so a later change can.
	//
	// WaitingFor is set on the row whose OWN response ends a turn with nothing more to do
	// right now (own_tool|human|background|teammate|retry|done|unknown); WaitTool is the LAST
	// tool_use name on that response, filled only when WaitingFor is "own_tool". WakeCause
	// is set on the row that ENDS a wait (tool_result|background|teammate|human|system|
	// retry|unknown), read off its own last message. OpenBackground/OpenTeammate are the
	// open-task/open-teammate counts as of THIS request's body (the "waiting_on" detail);
	// MonitorExpiryMs is the latest known absolute Monitor expiry (epoch ms) among them, 0
	// when none is open or none stated one. All six are "" / 0 on a row written before this
	// column existed (see dash/schema.go's additiveColumns: nullable, no default, so an old
	// row reads SQL NULL rather than a value this package never computed for it).
	WaitingFor      string `json:"waiting_for"`
	WaitTool        string `json:"wait_tool"`
	WakeCause       string `json:"wake_cause"`
	OpenBackground  int    `json:"open_background"`
	OpenTeammate    int    `json:"open_teammate"`
	MonitorExpiryMs int64  `json:"monitor_expiry_ms"`
	// WaitCause, when set, is invoked by the WRITER goroutine (Recorder.run's write(),
	// right beside e.Redact() and for the identical reason) to fill the six fields above —
	// never on the request path. The actual body rescan this runs
	// (waitcause.Tracker.Observe) measured ~11ms on a 783 KB body; called from finish()
	// (which runs on the handler's own defer, BEFORE the handler returns) that delayed the
	// NEXT request on a keep-alive connection by the same amount, which is exactly what
	// this repo's own TestDashboardAddsNoRequestLatencyWithContentCapture-style tests exist
	// to catch. nil on any row this does not apply to — a keep-alive ping's row never sets
	// it at all, which is also how a ping is guaranteed to carry no wait-cause label (issue
	// #424 requirement). Never serialized (there is nothing to marshal); the SIX FIELDS it
	// fills are what reaches JSON and the database.
	WaitCause func() WaitCauseResult `json:"-"`
	// The metadata that predicts when a user returns (#1198). Each is NULL in the database when it was
	// not computed (the zero value here): absent means unknown, never a guess.
	//
	// WaitToolTimeoutMs / WaitToolBackground are the `timeout` and `run_in_background` of the tool
	// call the thread waits for (WaitTool); no other part of the call's input is read.
	// WaitPrompt is none|permission|question|other: whether the turn ends on a prompt a person must
	// answer. TZOffsetMin is the host's UTC offset in minutes (local proxy only; 0 is UTC and is a
	// real value). Turn counts the thread's real requests from 1; ActiveThreads counts the session's
	// threads with a real request in the last ActiveThreadsWindow, this one included. The KA*
	// fields are the ping plan in force for the wait the response starts. UserHash is a keyed hash of
	// the person's id; the raw id is never kept.
	WaitToolTimeoutMs  *int64 `json:"wait_tool_timeout_ms,omitempty"`
	WaitToolBackground *bool  `json:"wait_tool_background,omitempty"`
	WaitPrompt         string `json:"wait_prompt,omitempty"`
	TZOffsetMin        *int   `json:"tz_offset_min,omitempty"`
	Turn               int    `json:"turn,omitempty"`
	ActiveThreads      int    `json:"active_threads,omitempty"`
	KAPlannedPings     *int   `json:"ka_planned_pings,omitempty"`
	KAMinPrefixTokens  *int   `json:"ka_min_prefix_tokens,omitempty"`
	KAIdleS            *int   `json:"ka_idle_s,omitempty"`
	// UserHash stays out of the API and the live feed: it is a pseudonymous id, for analysis scans of
	// the database only.
	UserHash string `json:"-"`
	// ClientEntrypoint and PermissionMode describe the session's mode: an unattended run (headless or
	// bypassPermissions) has no person who waits. SubagentType and ParentFanout describe the subagent
	// calls THIS response made: the type of the last one and their count.
	ClientEntrypoint string `json:"client_entrypoint,omitempty"`
	PermissionMode   string `json:"permission_mode,omitempty"`
	SubagentType     string `json:"subagent_type,omitempty"`
	ParentFanout     int    `json:"parent_fanout,omitempty"`

	// Lifecycle is the opt-in lifecycle-signals row (dash/lifecycle.go), nil when the flag is
	// off; LifecycleFn fills it on the writer goroutine, for the same reason WaitCause runs
	// there (it rescans the request body). Neither is part of the JSON event.
	Lifecycle   *LifecycleRow        `json:"-"`
	LifecycleFn func() *LifecycleRow `json:"-"`
	Model       string               `json:"model"`
	// BypassCount, when set, fills tokens_before/after, attempted_tokens and frozen_tokens of a
	// BYPASSED request, which the pipeline does not count on the request path (counting a large
	// transcript took ~0.35 s per MiB). It runs on the recorder's count worker, never on the
	// writer or the request path, after the row is inserted. nil on every other row.
	BypassCount func() (before, attempted int) `json:"-"`
	// BypassBytes is the size of the bypassed request body BypassCount will tokenize; the count
	// queue is bounded by the total of it (see countMaxBytes).
	BypassBytes int `json:"-"`
	// BilledTokenFactor is the tokenizer correction applied to this row's COUNTERFACTUAL
	// dollars — baseline_cost_usd's delta and every request_components.saved_usd. It is
	// tokens.LegacyFactor(Model), resolved once in Price.
	//
	// It is published rather than folded in silently: this factor is the whole difference
	// between what the dashboard reported before #240 and after it, and a reader who sees a
	// savings figure move needs to be able to see, and divide out, the thing that moved it.
	// 1.0 with BilledTokenFactorMeasured=false means this model's family was never measured
	// and the figure is exactly what it always was.
	BilledTokenFactor float64 `json:"billed_token_factor"`
	// BilledTokenFactorMeasured distinguishes "corrected by a measured factor" from
	// "uncorrected because nobody has measured this family" — 1.0 means both otherwise.
	BilledTokenFactorMeasured bool   `json:"billed_token_factor_measured"`
	Provider                  string `json:"provider"`
	Agent                     string `json:"agent"`
	// Source says how this row came to exist: "" for a request the proxy MEASURED as it passed,
	// SourceImported for one recovered from a Claude Code transcript after the fact.
	//
	// The two can answer different questions and the difference is not recoverable from anything
	// else on the row. A measured row saw the request, so it knows what was declared on it and
	// can say "you carried this and never called it". An imported row knows only what the
	// provider billed, because a transcript does not record the declaration list — so it can
	// report spend and must never produce a waste verdict.
	//
	// "" rather than a word for measured, because every row written before this column existed
	// is measured and cannot be back-filled.
	Source string `json:"source,omitempty"`
	// Project is the directory the agent was started in — what a user means by "project". Read
	// from the request body, since nothing else in a request identifies one: the session id is a
	// hash of the conversation head, and one session can span directories (measured: 8 of 48 do).
	// "" means unattributed, which is what a client that does not state a working directory gets.
	Project string `json:"project,omitempty"`
	Preset  string `json:"preset"`
	Mode    string `json:"mode"`
	Route   string `json:"route"`
	Status  int    `json:"status"`

	Bypassed bool `json:"bypassed"`
	// AgentCompaction marks the agent's own compaction request. It is usually not bypassed, but it
	// can be: a request with the bypass header, or a body over the size ceiling, carries both
	// flags. The replay cap reads either one as the evidence that a drop in tokens_before is the
	// client compacting.
	AgentCompaction bool `json:"agent_compaction"`
	CacheAware      bool `json:"cache_aware"`
	Messages        int  `json:"messages"`

	TokensBefore    int `json:"tokens_before"`
	TokensAfter     int `json:"tokens_after"`
	AttemptedTokens int `json:"attempted_tokens"`
	FrozenTokens    int `json:"frozen_tokens"`
	SavedUnique     int `json:"saved_unique"`

	FreshInput   int64 `json:"fresh_input"`
	CacheRead    int64 `json:"cache_read"`
	CacheWrite   int64 `json:"cache_write"`
	OutputTokens int64 `json:"output_tokens"`
	// CacheWrite1h is the part of CacheWrite the provider billed at the ONE-HOUR tier. A
	// SUBSET of CacheWrite, never an addition to it.
	//
	// It exists because pricing a 1h write as a 5m one understates that request by 0.75x of
	// its whole written prefix, and a cost that is wrong in the flattering direction is the
	// dangerous direction — it argues for spending. Measured live on this gateway: a request
	// asking for the 1h head on aws/claude-haiku-4-5 came back with 36,251 of 36,574 written
	// tokens on the 1h tier, and without this column the row priced at $0.0348 against a real
	// $0.0554.
	//
	// It is also the ONLY signal that a requested `ttl: "1h"` was honoured. The same request
	// on aws/claude-sonnet-5 returned ephemeral_1h_input_tokens = 0 with an otherwise normal
	// 200 — Bedrock's 1h support covers the Claude 4.5 family and not Sonnet 5 — so a silently
	// downgraded request is indistinguishable from a granted one without this number.
	CacheWrite1h int64 `json:"cache_write_1h"`

	// Every *_usd figure on the row is in Currency, the unit of the price that costed it: US dollars,
	// unless the operator's price file names another unit (Bob's says Bobcoins). The field names keep
	// "usd" so no reader breaks. Empty until priced; an unpriced row is stored as USD, the default.
	Currency        string  `json:"currency"`
	CostUSD         float64 `json:"cost_usd"`
	BaselineCostUSD float64 `json:"baseline_cost_usd"`
	CGLLMCostUSD    float64 `json:"cg_llm_cost_usd"`
	// FallbackRateCostUSD is the part of CostUSD priced from a fallback rate: a cache-read rate no
	// source stated, filled from a default multiple (modelinfo.Price.FallbackCost, #1248). It is not
	// the accountant fallback of Overview.FallbackCostUSD. The metrics read it from the live event.
	// Not stored.
	FallbackRateCostUSD float64 `json:"-"`
	// CGCostUnpriced is set by PriceCG when the request made compaction calls that could not be
	// priced, so CGLLMCostUSD is an unknown 0 and not a free one. Not stored: the reprice pass
	// prices such a row on both halves once the price map loads (issues #920, #1033).
	CGCostUnpriced bool `json:"-"`
	// CGModel and the four CG token counts are what the request's compaction calls billed, the
	// input PriceCG prices. Not stored: the reprice pass needs them only for a row written by this
	// process, and it keeps them on its in-memory copy (issue #1033).
	CGModel                                      string `json:"-"`
	CGFresh, CGCacheRead, CGCacheWrite, CGOutput int64  `json:"-"`
	// CacheSavedUSD is what the provider's prompt cache saved on this request: its
	// cache-read tokens priced at the fresh rate they would have cost with no cache,
	// minus what they actually cost. A measurement of the PROVIDER's mechanism, kept
	// because it is the number that falls when a compaction pipeline destroys a prefix —
	// and reported nowhere as a saving of ours, because it is not one.
	CacheSavedUSD float64 `json:"cache_saved_usd"`
	// CacheTTL is the prompt-cache lifetime tier this request ASKED for — "ephemeral_5m",
	// "ephemeral_1h", or "" for a body that carried no cache_control at all. The pipeline has
	// always computed this (it is an input to cold-cache attribution) and then discarded it,
	// so nothing downstream could say which tier a prompt used: the strings did not appear in
	// the source at all, and a 1h prompt was priced at the 5m write rate because there was
	// nothing to price it differently by. Where a breakpoint SITS is already recorded
	// (CacheBP*); how long it was meant to live was the missing half.
	CacheTTL string `json:"cache_ttl"`
	// SSEBuffered and TTFBMs are the response-side latency the dashboard could not see.
	//
	// A third of streamed responses on measured traffic are BUFFERED rather than streamed
	// through — the client sees nothing until the whole response has arrived — and those wait
	// about 21 seconds longer for their first byte (29.0 s against 7.9 s). That is two orders
	// of magnitude more user-visible delay than anything the pipeline itself adds, and it was
	// visible only as a process-lifetime counter on /stats: unfilterable, unattributable to a
	// model or an account, and gone on restart. Persisting the pair makes it a fact about a
	// request like every other on this row.
	//
	// TTFBMs is 0 on a non-streamed response. On a BUFFERED one it is the total response time,
	// not a first-byte time: proxy.go leaves the first-byte instant zero and msSince falls back
	// to time.Now(). That is the right number for a buffered response — nothing is written to
	// the client until the whole response has arrived, so the client's first byte and its last
	// byte are the same moment — but it is a different measurement from the streamed figure,
	// which is why the flag is stored beside it and the two are never averaged together.
	SSEBuffered bool    `json:"sse_buffered"`
	TTFBMs      float64 `json:"ttfb_ms"`
	// FilteredDeclTokens is what the declaration filter stopped carrying on this request —
	// the token weight of the `tools` elements it removed under the account's opt-in list.
	//
	// It is a TOKEN count and not a dollar figure on purpose: what those tokens would have
	// cost depends on the tier this same row was billed at (cache_read 0.1x, cache creation
	// 1.25x, fresh 1.0x), and those columns are right here — so the price is computed by the
	// query that reads them together rather than frozen into a second column that could
	// disagree with them. See DB.DeclFilterSavings.
	FilteredDeclTokens int `json:"filtered_decl_tokens"`
	// FilteredDeclBytes is the bytes the declaration filter removed (#1533): the same removal as
	// FilteredDeclTokens, in the unit the accountant's request ratio converts. A count. 0 is unknown.
	FilteredDeclBytes int `json:"filtered_decl_bytes,omitempty"`
	// SweepExpandBytes is the bytes the sweep's expands restored: SweepExpandTokens, in bytes (#1533). 0 is unknown.
	SweepExpandBytes int `json:"sweep_expand_bytes,omitempty"`
	// Ratio is the request's own ratio, as the accountant built it (Result.Ratio): the provider's billed tokens
	// over the bytes of the forwarded text, and whether the media price was cut to the bill. Three counts, no text
	// (#1533). Known is false when the request has no Result. Not serialized: the store writes it.
	Ratio accrec.RatioCounts `json:"-"`
	// DeclDigest is the declaration set this request carried (tool_declarations.digest).
	DeclDigest string `json:"decl_digest,omitempty"`

	// KeepAlive marks a row that IS a keep-alive ping rather than agent traffic: a request
	// context-guru sent on its own initiative, to re-read an idle session's cached prefix so
	// the provider refreshes its lifetime. Its cost is real and lands in CostUSD like any
	// other row's, which is the point — a mechanism that spends the caller's money while
	// they are away from the keyboard has to be auditable to the cent, and a ping that did
	// not appear as a row would be spend with no owner.
	KeepAlive bool `json:"keepalive"`
	// KeepAlivePings is, on a REAL request, how many pings the keeper DECIDED to send during the
	// idle span it just ended — which is not the same as how many were sent, and the difference is
	// why dash.kaSaved does not trust this column.
	//
	// proxy/keepalive.go increments it under the sweep's lock, before dispatch. Three paths then
	// return without a request reaching the provider and without writing a ping row: the tenant
	// limiter refusing spare headroom, an unusable body, and a fast transport error on send. All
	// three bump skipped/failed and leave this count already raised. (A ping that runs to its
	// timeout does write a row since #754, marked StopTimeoutEstimated, with status 0.) Measured consequence on a
	// 133,064-row production corpus: 7 of 105 credited rows carry KeepAlivePings >= 1 with no ping
	// row anywhere in the span, two with none within 16.7 hours.
	//
	// So this is dispatch intent, and only a stored ping row (keepalive = 1, status = 200) is
	// evidence that a ping happened. The credit is gated on the latter at read time. Not fixed
	// here: the counter is in proxy/ and the figure it feeds is already protected.
	//
	// It is still what makes the saving below attributable rather than assumed: a
	// request that hits after a twenty-minute gap could have been rescued by our ping or by
	// any other session that happened to send byte-identical content, and only this
	// distinguishes them.
	KeepAlivePings int `json:"keepalive_pings"`
	// KeepAliveRefreshed is what the last ping on this session actually read from cache —
	// the tokens our ping demonstrably refreshed. Not persisted. The legacy credit rule capped
	// the credit with it; the credit is now the accountant library's rescue.
	KeepAliveRefreshed int64 `json:"-"`
	// KeepAliveSavedUSD is the cache re-creation this request avoided because a ping kept
	// its prefix alive.
	KeepAliveSavedUSD float64 `json:"keepalive_saved_usd"`
	// KeepAliveStrategyID is which manager-controlled strategy resolved the policy behind
	// this row (see proxy/keepalivestrategy.go) — "" when none matched (account config or a
	// session override supplied the policy instead). Set on a ping row for the strategy
	// that sent it, AND on the real request that followed it (whenever KeepAlivePings>0),
	// regardless of whether that request ended up credited — captured at keeper.arrive, the
	// one moment the idle span's strategy is still in scope (proxy/keepalive.go). Harmless
	// on an uncredited row: every reader of this column also filters on
	// KeepAliveSavedUSD>0. Written as SQL NULL, not ”, when empty — see dash/schema.go's
	// keepalive_strategy_id column — so a row from before this feature existed is
	// distinguishable from one deliberately attributed to nothing.
	KeepAliveStrategyID string `json:"keepalive_strategy_id,omitempty"`
	// ManualPing marks a keep-alive row the USER asked for (POST /api/me/cache/ping). It stays a
	// KeepAlive row — real spend, a real refresh of the provider's entry — and carries strategy id
	// "manual"; this flag is what every strategy ledger filters on, so a button press never lands
	// in a strategy's net. ManualSavedUSD is an ESTIMATE of the cache write it avoided (gross). Only a row
	// written before #1460 holds one; a newer row holds 0, because the accountant credits the rescue on the
	// thread's next real request. Its cost is CostUSD, as for any ping.
	ManualPing     bool    `json:"manual_ping,omitempty"`
	ManualSavedUSD float64 `json:"manual_saved_usd,omitempty"`
	// SinceLastMs is the gap from this session's previous REAL request, in milliseconds.
	// Not persisted — AttributeCache already turns it into cache_miss_reason — but the
	// keep-alive credit needs the raw number: the whole claim is that the gap exceeded the
	// provider's lifetime and the request hit anyway.
	SinceLastMs int64 `json:"-"`

	CGLatencyMs float64 `json:"cg_latency_ms"`
	UpstreamMs  float64 `json:"upstream_ms"`

	Expands      int `json:"expands"`
	ExpandTokens int `json:"expand_tokens"`
	Reverts      int `json:"reverts"`
	// SweepExpands and SweepExpandTokens are the part of Expands and ExpandTokens that restored a
	// marker the extract_llm_sweep made (#404 point 7). The sweep's credit has them taken off; the
	// totals above still carry them, so SavedAdjusted is unchanged.
	SweepExpands      int `json:"sweep_expands"`
	SweepExpandTokens int `json:"sweep_expand_tokens"`
	// SweepFalseExpands is how many drops were expanded back for the FIRST time on this request and
	// were not already counted as referenced: the expand half of the false-drop count, exact per drop.
	SweepFalseExpands int `json:"sweep_false_expands"`
	// SweepFalseExpandsWarm is the part of SweepFalseExpands whose drop was applied on a WARM request
	// (#491), so the warm false-drop rate counts expands as well as references.
	SweepFalseExpandsWarm int `json:"sweep_false_expands_warm"`
	// RestoredTokens is what the restored copies this request carried added to it
	// (expand.fixed_restore, #481). Every later turn of a session carries them again, and the
	// pipeline's TokensAfter counts them.
	RestoredTokens int `json:"restored_tokens"`
	// SweepAnswerUSD is, on a keep-alive ping row the sweep's question replaced, what the answer cost
	// beyond the read the ping would have paid anyway (#404 point 9). Booked once, on the ping row, as
	// the summary's call is (#458). It is part of CostUSD, not added to it, and it is a separate
	// column so the sweep's credit and its answer cost are never one number.
	SweepAnswerUSD float64 `json:"sweep_answer_usd,omitempty"`
	// Tool deferral's facts for this request (#485, #869), from the proxy's own deferral ledger:
	// set only on a request deferral changed and the provider answered with usage. DeferTokens is
	// the weight of the definitions it deferred (less those a search had already loaded), and
	// DeferListTokens the names list's weight, in our tokenizer's units. DeferSearches is the
	// server-side searches the response ran, DeferDroppedSearches the ones with no result (the
	// client drops a search sent beside another tool call, and the model searches again),
	// DeferLoaded the distinct tools they loaded, and DeferWrongGuesses the wrong guesses as
	// tooldefer.WrongGuesses counts them: a tool this request deferred that a search loaded and no
	// earlier message had loaded. DeferGrossUSD, DeferCostUSD and DeferNetUSD are the accountant's
	// figure for the tooldefer component (#1441), set by PriceMode: net is the figure (the definitions left out, the
	// tier re-rate, less the names list and the search turns), gross is its saved side, cost is gross less net. All 0
	// when the request has no accountant figure (an unpriced model, a held estimate).
	DeferTokens          int `json:"defer_tokens,omitempty"`
	DeferListTokens      int `json:"defer_list_tokens,omitempty"`
	DeferSearches        int `json:"defer_searches,omitempty"`
	DeferDroppedSearches int `json:"defer_dropped_searches,omitempty"`
	// CompactionPoint and CompactionPointSource are C in billed tokens and its source, written
	// ONLY when the client set it: the user's own setting or the client's own default (#948, #963; compactionpoint.Configured, ClientDefault). 0 and ""
	// on every other row: the table value is read back from the table. A number from a config
	// file, never content.
	CompactionPoint       int     `json:"compaction_point,omitempty"`
	CompactionPointSource string  `json:"compaction_point_source,omitempty"`
	DeferLoaded           int     `json:"defer_loaded,omitempty"`
	DeferWrongGuesses     int     `json:"defer_wrong_guesses,omitempty"`
	DeferGrossUSD         float64 `json:"defer_gross_usd,omitempty"`
	DeferCostUSD          float64 `json:"defer_cost_usd,omitempty"`
	DeferNetUSD           float64 `json:"defer_net_usd,omitempty"`
	// Backend is which of Bob's backends answered: "A", "B", "other" (the reply's marks match
	// neither) or "" (not Bob's model route, or no id and no usage). A short label made from the
	// reply's id shape and usage fields. The id itself is never stored.
	Backend string `json:"backend,omitempty"`
	// ClientCompaction is the client compaction verdict (#947): "unknown" on the first request after
	// the agent's own compaction (thread.Result.AfterCompaction), "" on any other request. The
	// proxy sends the same verdict to the accountant (RequestMeta.Compaction). The replay cap
	// closes an epoch on a row that carries one.
	ClientCompaction string `json:"client_compaction,omitempty"`
	// ClientCompactionKnown says the thread tracker judged this request (by prefix or by header), so
	// ClientCompaction is a verdict and "" means "no compaction". When false the row stores NULL: no
	// verdict. That includes the tracker's session fallback: no session id, no message list, a panic.
	ClientCompactionKnown bool `json:"-"`
	// AccFallback is why the accountant library could not price this request (a Fallback* reason, or
	// FallbackUnrecorded on a back-filled row). "" when it priced the request, or never ran on it. Set by
	// RecordAccountantFallback. A row with a reason books its cost and no saving, so the Overview counts it
	// and leaves it out of the saving share (#1004).
	AccFallback string `json:"acc_fallback,omitempty"`

	// Limits are the subscription limit values the provider's answer carried in its
	// anthropic-ratelimit-unified-* headers (#984), read by the host off the response headers.
	// nil when it carried none (an API key, Bedrock, Vertex) and on every earlier row. Numbers and
	// status words only.
	Limits *Limits `json:"limits,omitempty"`
	// AuthSubscription is true when the client authenticated this Anthropic request with a Claude
	// subscription token (an OAuth bearer token), false for an API key or anything else. The host
	// decides it from the credential's fixed prefix; only this flag is kept, never the token.
	AuthSubscription bool `json:"auth_subscription,omitempty"`

	TokenAccounting string `json:"token_accounting"`
	// PriceEstimated is true when the accountant library priced this request without knowing whether a
	// change broke the cache (penalty_unknown): the gross saving is right and the net may be too
	// high. It is stored, so the dashboard marks such a figure after a restart. False on an exact
	// figure, on an event that books no saving, and on a row from before the column existed.
	PriceEstimated bool `json:"price_estimated,omitempty"`
	// AccountantPriced is true when the accountant override applied to this request, so its
	// keepalive_saved_usd is the library's own rescue decision. Stored (requests.acc_priced), so the
	// keep-alive reachability gate trusts that decision with no component row and no ping probe. False
	// on a request the library did not price and on every row from before the column existed, which
	// keep the SQL gate (context-guru#912, #919).
	AccountantPriced bool `json:"acc_priced,omitempty"`
	// EstimatedSavedUSD is the saving the library priced on an estimated request, held apart from
	// the books (issue #915). With no history the library prices every removal as if the provider
	// would have written it, so after a restart that lost the state, or on a session that began on a
	// cache the proxy never saw, the figure can be about 2x too high. Such a request books
	// BaselineCostUSD == CostUSD and every component SavedUSD 0, so every total, the components table
	// and the keep-alive tab agree without a filter. This field keeps the figure that was not booked.
	// 0 on an exact request and on a row from before the column existed.
	EstimatedSavedUSD float64 `json:"estimated_saved_usd,omitempty"`
	// EstimatedSavedLowUSD is the floor of that held figure (#915): every removed token priced at the read
	// rate instead of the write rate. A client token never costs less than a read, so the true saving lies
	// in [EstimatedSavedLowUSD, EstimatedSavedUSD]. The size of the unseen warm prefix is not in the usage,
	// so the proxy cannot narrow it further. Never booked. 0 when not held and on an older row.
	EstimatedSavedLowUSD float64 `json:"estimated_saved_low_usd,omitempty"`
	// EstimateHeld is true when the hold-out above applied to this row: the request is estimated AND its
	// removal figure was kept out of every total. It is the marker readers use for "not counted". It is
	// not the same as PriceEstimated: a row written before #915 has price_estimated = 1 and DID book its
	// figure, and it reads here as false (the column defaults to 0, as acc_priced does). Stored.
	EstimateHeld bool `json:"estimate_held,omitempty"`
	// AccTokens is the accountant library's cache effects in tokens by tier: the keep-alive rescue,
	// the split, the head-TTL legs and the ended-change break (#998). The component figures are
	// CompRow.Tokens. Stored (requests.tok_*). Zero when AccountantPriced is false.
	AccTokens          AccEffectTokens `json:"acc_tokens,omitzero"`
	CacheMissReason    string          `json:"cache_miss_reason"`
	UncompressedReason string          `json:"uncompressed_reason"`
	// CacheMissCause says what changed on a miss that is not hit, cold_start or ttl_expiry.
	// Set only from a measured comparison (Cause* constants). "" when nothing was measured.
	CacheMissCause string `json:"cache_miss_cause,omitempty"`
	// PrefixCompared says that the thread had an earlier request to compare this one with, so an
	// empty CacheMissCause means "nothing differed", not "nothing to compare with" (for example,
	// the first request of a live thread after a restart). Not persisted: only the live metric
	// llm_cache_misses_total reads it.
	PrefixCompared bool `json:"-"`
	// SystemHash is the system prompt's hash, for the prefix comparison only. Not persisted.
	SystemHash string `json:"-"`

	// Meta is the request's own knobs, embedded so the JSON stays flat.
	Meta

	Components []CompRow    `json:"components,omitempty"`
	Content    []ContentRow `json:"content,omitempty"`
	// Extractions is one row per LLM call an expensive component made on this request.
	Extractions []ExtractionRow `json:"extractions,omitempty"`

	// ContentCap is the per-blob byte cap Redact applies. Set at the capture site and
	// consumed by the writer goroutine; not persisted (a knob, not a fact about the
	// request).
	ContentCap int `json:"-"`
	// contains filtered or unexported fields
}

Event is one captured request, as handed to the capture channel. It is built on the request goroutine from values the request path already computed (no extra token counting, no extra allocation of the transcript) and is then owned entirely by the writer goroutine.

func DecodeArchive

func DecodeArchive(gz []byte) ([]*Event, error)

DecodeArchive parses a gzipped JSONL archive. Exported so an operator can read an object back with a few lines of Go, or so a future importer does not have to reverse-engineer the format.

func (*Event) AccountantEstimated added in v0.7.0

func (e *Event) AccountantEstimated() bool

AccountantEstimated reports whether the applied figure is an estimate: the library could not rule out a break (penalty_unknown, accountant design §6.4). It is false when the override did not apply. It reads PriceEstimated, the stored field the dashboard marks the figure by.

func (*Event) AccountantFallback added in v0.7.0

func (e *Event) AccountantFallback() string

AccountantFallback is the reason PriceMode booked no saving, or "" when the override applied. It is "" too on an event priced with Price alone, which never tries the override. An event with no usage or no price books no saving too, and its reason is FallbackUnpriced.

func (*Event) AccountantFigure added in v0.7.0

func (e *Event) AccountantFigure(p modelinfo.Price) AccFigure

AccountantFigure is the attached Result in dollars. The dollars come from accountant.Figure, priced with the host's rates at the prompt size of each side (modelinfo.OneModel). This function only maps the library's figure to the dashboard's rows and columns, and takes the tokens of each row from the Result.

It reads a DryRun operation as the library does: computed, never counted. A spend (Call != nil) is a separate bill. Result.Interaction is attributed to nobody: it goes to InteractionUSD, the interaction row.

Where the library has a figure the dashboard had no row for:

  • UnownedMarkUSD (a mark premium or payback no counted operation owns) goes to the tail breakpoint row, the same row as before: that component adds the mark in every default preset.
  • UnownedReRateUSD (a guard: it is 0 today) goes to EndedBreakUSD, the ended_change row, as before.

func (*Event) AccountantResult added in v0.7.0

func (e *Event) AccountantResult() (accountant.Result, bool)

AccountantResult returns a copy of the attached Result and whether one is attached. It is how a test or a host reads what the store does not keep.

func (*Event) AttributeCache

func (e *Event) AttributeCache(seenSession, seenModel bool, sinceLastMs int64, ttlMs int64, cause string, prevPromptTokens int64)

AttributeCache buckets this request's cache behavior. seenSession/seenModel say whether we have already seen a request for this session / this model — the first of either is a COLD START, which is not a failure and must never be reported as a bust (headroom's model-aware rule). TTL wins ties: a prefix that changed after the entry had already expired was not the cause.

cause is the measured difference from the thread's previous request (Recorder.ObservePrefix): "" when nothing differed. A miss with no measured difference is "unknown", not "prefix_change".

prevPromptTokens is that previous same-model request's whole prompt (fresh input + cache read + cache write), 0 when none is known. A read alone is not a hit (#496): Claude Code keeps the system prompt and tools under a separate breakpoint, so a request that re-wrote the rest of the prompt still reads 35k-51k tokens. A PARTIAL read — under half the previous prompt, with more written than read — re-wrote most of the prompt, so it is a miss and takes the chain below like any other. Old rows are not migrated; they keep the label they got.

func (*Event) CachePrefixChangeReason

func (e *Event) CachePrefixChangeReason()

CachePrefixChangeReason marks the miss as caused by a changed prefix.

func (*Event) ComponentSavedUSD added in v0.5.2

func (e *Event) ComponentSavedUSD(p modelinfo.Price, component string, gross, unique int) float64

ComponentSavedUSD is the LEGACY per-component rule: a removal priced from a row's own token counts. Nothing stores it any more; the accountant library prices every new row (PriceMode). It stays for rows written before the switch (priced_by ”), which the read-time passes value with it (readvalue.go, summarizeattr.go, replaycap.go), because a stored row has no thread history for the library to price from. A row the library priced is never re-priced with it.

The first (unique) removal is priced by uniqueRate, the re-sent remainder by repeatRate.

func (*Event) DropUnbilledSavings added in v0.7.0

func (e *Event) DropUnbilledSavings()

DropUnbilledSavings removes the token saving from a request the provider rejected (issue #914). The provider billed none of its tokens, so cost and baseline are 0, and a token saving booked beside them would disagree with the dollar saving. It sets TokensAfter to TokensBefore, zeroes SavedUnique, and zeroes SavedGross and SavedUnique on every component row. A row keeps Mutated (the proxy did rewrite the body) but is no longer Acted. A status of 0 is a request that never reached a provider (/compact, an upstream that did not answer), and a 2xx was billed, so neither is touched. AttemptedTokens goes to 0 too: Overview divides the gross saving by it over the rows that have it, and a rejected row must leave both sides. FrozenTokens describes the cache freeze, not a saving, and stays.

func (*Event) FromTrace

func (e *Event) FromTrace(tr apply.Trace, uniqueSaved map[string]int)

FromTrace fills the pipeline-derived half of an Event from an apply.Trace. Usage/cost/latency come from the response and are filled by the caller.

func (*Event) HasAccountant added in v0.7.0

func (e *Event) HasAccountant() bool

HasAccountant reports whether a Result is attached.

func (*Event) Price

func (e *Event) Price(p modelinfo.Price, accountingComplete bool)

Price fills the cost columns AT WRITE TIME, from this request's four billed token tiers: CostUSD, the provider's own cache saving (CacheSavedUSD, a measurement, never ours), and the accounting fields. It books NO saving of ours: BaselineCostUSD equals CostUSD, and every component's SavedUSD, KeepAliveSavedUSD are 0. The savings are the accountant library's, applied by PriceMode. An event the library cannot price (AccountantFallback) keeps these zeros: a saving nothing measured is not shown.

accountingComplete=false leaves every cost at zero and the row is marked partial/missing: a cost we cannot compute must read as unknown, not as free.

func (*Event) PriceCG added in v0.7.4

func (e *Event) PriceCG(prices modelinfo.Pricer, main modelinfo.Price, mainPriced bool)

PriceCG prices the request's compaction calls into CGLLMCostUSD. main is the agent model's price and mainPriced whether it is known. The compaction model's own rate is used when it differs from the agent's model and prices knows it; otherwise the agent's rate, as it always was. With no rate, CGCostUnpriced is set and CGLLMCostUSD stays 0. A request with no compaction tokens is left alone.

The capture site and the reprice pass both call it, so one request gets one figure either way.

func (*Event) PriceMode added in v0.7.0

func (e *Event) PriceMode(p modelinfo.Price, accountingComplete bool)

PriceMode is Price, then an override of each component's SavedUSD, of BaselineCostUSD, of KeepAliveSavedUSD from the library's figure. CacheSavedUSD (the provider's own cache, a measurement), CostUSD and CGLLMCostUSD always stay as Price set them.

The override is all-or-nothing per event, because a partial list would show an unmeasured component as a $0 saving. It applies only when: a Result is attached; no change was dropped from the operation list; the run was not observe mode; no operation or effect is unpriced; no gated library check failed; the figure is plausible; and every component that acted has a library figure. Otherwise the event books no saving (Price set every saving to 0) and AccountantFallback says why: a figure nothing measured is not shown.

func (*Event) RecordAccountantFallback added in v0.7.4

func (e *Event) RecordAccountantFallback()

RecordAccountantFallback stores AccountantFallback in AccFallback, so the Overview can count the request and leave its cost out of the saving share (#1004). The host calls it only for a request the accountant ran on, or one whose history the provider holds (server_held_history): the same requests it logs as acc_fallback. A request with no record (no session, or the pipeline did not run) has nothing to price, so it is not a fallback, and AccFallback stays "".

A bypassed request is not a fallback either. The client asked for no context-guru, so its $0 saving is a measured $0, and its cost belongs in the share. Stored, a fallback would take bypassed spend out of the share and raise it.

func (*Event) Redact

func (e *Event) Redact()

Redact scrubs credential shapes from captured content and applies the size cap. The WRITER goroutine calls it immediately before the INSERT — never the request goroutine, where nine regexes over dozens of 16 KiB blobs cost ~53 ms, paid by the next request on a keep-alive connection.

The placement is the whole security property: redaction happens before anything reaches the database, so a secret is never on disk and there is no redact-on-read filter to forget. Running it here rather than at the capture site changes WHICH GOROUTINE pays, not whether it runs.

Idempotent, so a double call cannot corrupt a row.

func (*Event) Saved

func (e *Event) Saved() int

Saved is this request's gross content-token saving.

func (*Event) SetAccountant added in v0.7.0

func (e *Event) SetAccountant(r accountant.Result)

SetAccountant attaches the library's Result to the event.

func (*Event) SetAccountantContext added in v0.7.0

func (e *Event) SetAccountantContext(opsDropped int, observe bool)

SetAccountantContext records what qualifies the attached Result: how many of the request's changes the trace could not place as operations, and whether the run was observe mode. Both gate the accountant override in PriceMode.

func (*Event) SetAccountantServerHeldHistory added in v0.7.4

func (e *Event) SetAccountantServerHeldHistory()

SetAccountantServerHeldHistory marks an OpenAI Responses request with server-held history (previous_response_id, conversation or item_reference): the provider holds the earlier turns, so the body is only this turn and the proxy cannot see the prefix the provider reads. PriceMode then books no saving and says why (fallback server_held_history), where it would have said no_result, which reads as a request that was merely skipped (context-guru#899).

func (*Event) UnpricedWhy added in v0.7.0

func (e *Event) UnpricedWhy() string

UnpricedWhy names the cause when AccountantFallback is FallbackUnpriced, and is "" for any other reason. It is UnpricedNoUsage or UnpricedNoPrice when the event itself cannot be priced, or the library's "opID:reason" for the first operation or effect it could not price.

type ExcludedDecl

type ExcludedDecl struct {
	Kind   string `json:"kind"`
	Name   string `json:"name"`
	Server string `json:"server,omitempty"`
	// Since is when the filter first acted for this account, NOT a per-item audit date: the
	// configuration stores names, not timestamps, and the per-item history is in the audit
	// log where the change was recorded. Zero when the filter has not acted yet.
	Since int64 `json:"since,omitempty"`
}

ExcludedDecl is one declaration the account has opted out of, in the shape the inventory reports it (kind and name, so a page can match it against a row of GET /api/tools).

type ExtractionRow

type ExtractionRow struct {
	Component       string  `json:"component"`
	Model           string  `json:"model,omitempty"`
	Strategy        string  `json:"strategy,omitempty"`
	Aggressiveness  string  `json:"aggressiveness,omitempty"`
	Cold            bool    `json:"cold"`
	Escalated       bool    `json:"escalated,omitempty"`
	CandidateTokens int     `json:"candidate_tokens"`
	SavedTokens     int     `json:"saved_tokens"`
	PromptTokens    int64   `json:"prompt_tokens"`
	CompletionTok   int64   `json:"completion_tokens"`
	CacheRead       int64   `json:"cache_read"`
	CacheWrite      int64   `json:"cache_write"`
	CostUSD         float64 `json:"cost_usd"`
	LatencyMs       float64 `json:"latency_ms"`
	Accepted        bool    `json:"accepted"`
	GateReason      string  `json:"gate_reason,omitempty"`
	Rejection       string  `json:"rejection,omitempty"`
	Summary         string  `json:"summary,omitempty"`
	// Before/After are transcript content: persisted and served only under the same
	// per-account capture consent as the diff view.
	Before string `json:"before,omitempty"`
	After  string `json:"after,omitempty"`
}

ExtractionRow is one recorded LLM call an expensive component made. See the extraction_calls table for why this is not folded into CompRow.

func (ExtractionRow) NetUSD

func (r ExtractionRow) NetUSD(perSavedTokenUSD float64) float64

NetUSD is what this call was worth: the value of the tokens it removed, minus what the call cost. The whole point of recording calls individually — a component can be ahead overall while a particular kind of call is underwater.

type FallbackSaving added in v0.7.4

type FallbackSaving struct {
	CompactionUSD float64 `json:"compaction_usd"` // baseline - cost - cg_llm: the net_saved_usd part
	DeferUSD      float64 `json:"defer_usd"`      // tool deferral's figure: the defer_net_usd part
	KeepAliveUSD  float64 `json:"keepalive_usd"`  // the keep-alive credit: the keepalive_saved_usd part
	FilterUSD     float64 `json:"filter_usd"`     // the measured filter credit: the decl_filter_usd part
}

FallbackSaving is the saving the fallback requests booked, by the Overview part it lands in. The filter part is a read-time credit; SetDeclCredit (full read) and OverviewLean fill it.

type Filter

type Filter struct {
	Since int64 // epoch ms, inclusive; 0 = unbounded
	Until int64 // epoch ms, exclusive; 0 = unbounded
	// Tenant scopes every query to one tenant. In a hosted deployment the API layer
	// OVERWRITES this from the authenticated principal after parsing the request —
	// set, never merged — so a crafted ?tenant= cannot widen a view. A manager may
	// pass one explicitly. TenantAll opts out, and only a manager may reach it.
	Tenant string
	// TenantAll disables tenant scoping for a service-wide view. Separate from an
	// empty Tenant because "" is a legitimate tenant id (every single-tenant row),
	// so absence could not mean "everything" without making the unscoped case the
	// default — which is the wrong default for a filter that guards other people's data.
	TenantAll bool
	Session   string
	// SessionIn selects rows whose session id is any of these, for a grouped multi-session
	// query (e.g. every currently-live keep-alive session) in one round trip rather than one
	// query per session. Mutually exclusive with Session in practice; if both are set, both
	// apply (AND), which is never useful, so callers should pick one.
	SessionIn []string
	// ProjectIn selects rows in ANY of these folders, which is how a project root is scoped.
	//
	// A PROJECT IS SEVERAL FOLDERS. Claude Code records a working directory per request, and one
	// project produces many -- measured, one produced 14 -- so matching the root path alone would
	// return a fraction of its traffic and selecting a project would show LESS than the pooled
	// view. Set by ExpandProjectFilter from Project; callers set Project and let that expand it.
	ProjectIn []string
	// PerSession asks the tool inventory to keep its per-session cost attribution instead of
	// collapsing it to totals. Not a row predicate — it changes the SHAPE of the response, not
	// which rows are in it — and off by default because the breakdown is a per-row array that
	// most readers of /api/tools do not use.
	PerSession bool
	Model      string
	Provider   string
	Agent      string
	// Project scopes to one launch directory. Unset means EVERY project, which is the view the
	// dashboard opens on — not "the unattributed ones", since absence is not a value.
	Project string
	// ProjectNone selects the rows that state NO project. Separate from an empty Project for the
	// same reason TenantAll is separate from an empty Tenant: "" is a legitimate stored value
	// here (it is what every pre-migration row and every client that does not state a directory
	// records), so absence could not also mean "only those" without making one of the two
	// meanings unreachable.
	ProjectNone bool
	Preset      string
	Mode        string
	// Component selects requests on which this component RAN.
	Component string
	// Reason selects requests by their uncompressed reason bucket; the sentinel
	// "compacted" selects rows where we did compact.
	Reason string
	// Accounting selects by token_accounting (complete|partial|missing).
	Accounting string
	// Effort, Thinking and StopReason select on captured request metadata — the
	// drill-down from a breakdown chart into the rows behind one of its bars.
	Effort     string
	Thinking   string
	StopReason string
	// WithKeepAlive includes keep-alive PING rows. Off by default, and that default is the
	// point: a ping is a request context-guru sent on the user's behalf while they were away,
	// not traffic their agent produced. Counted in an aggregate it silently inflates the
	// request count, drags every per-request average towards a ~1-token response, and makes an
	// account's own traffic statistics wrong.
	//
	// Set it only where a ping IS the subject: the request LIST (the rows are the audit trail
	// and must be visible, badged by the `keepalive` column) and the keep-alive ledger itself.
	// Money is a deliberate exception handled elsewhere — a ping is real spend on the caller's
	// key, so DB.TenantSpend and the Prometheus cost series include it; the exclusion here is
	// about counts and averages, not about pretending the money was not spent.
	WithKeepAlive bool
	// Q is a free-text match against session id and model.
	Q string
}

Filter is the server-side filter set every list/aggregate query accepts. Every dimension the issue names is here, and filtering happens in SQL — pushing it to the client is the gap that makes headroom's request log unusable past a few hundred rows.

func ExpandProjectFilter added in v0.5.4

func ExpandProjectFilter(f Filter, g *ProjectGroup) Filter

ExpandProjectFilter turns a selected project ROOT into the set of folders that roll up to it.

A project is several folders -- Claude Code records a working directory per request and one project produced 14 of them on a measured machine -- so a query matching the root path alone returns a fraction of its traffic. The picker folds subdirectories into the root, and without this the query would not, which means selecting a project shows LESS than the pooled view did.

A root the transcripts do not recognise expands to itself, so a folder with no transcript is still reachable rather than silently empty.

type FiveHourFit added in v0.7.3

type FiveHourFit struct {
	// OK is true when the fit passed the gate. Every other screen reads the weights only then.
	OK bool `json:"ok"`
	// Reason says why the gate failed. "" when OK.
	Reason string `json:"reason,omitempty"`
	// Weights is the share of the 5-hour limit (0..1) that one token of each tier uses. A tier the
	// fit could not learn (Learned false) carries the API price, scaled to the account's own spend.
	Weights map[string]float64 `json:"weights,omitempty"`
	// Learned says, by tier, whether the weight came from the fit.
	Learned map[string]bool `json:"learned,omitempty"`
	// RelSE is each learned weight's relative standard error.
	RelSE map[string]float64 `json:"rel_se,omitempty"`
	// Requests, Windows and Spans are what the fit used. DroppedSpans were dropped as traffic
	// that did not go through the proxy.
	Requests     int `json:"requests"`
	Windows      int `json:"windows"`
	Spans        int `json:"spans"`
	DroppedSpans int `json:"dropped_spans"`
	// FitError is the fit quality: the root mean square of the span errors over the mean span
	// change. 0.1 means the weights predict a span's change to within about 10%.
	FitError float64 `json:"fit_error"`
	// HeaderAfterRow is true when the fit found that a row's header counts the row itself.
	HeaderAfterRow bool `json:"header_after_row"`
	// Forecast is the cache strategy forecast's scale. nil without prices.
	Forecast *ForecastScale `json:"forecast_scale,omitempty"`
}

FiveHourFit is the fit's answer, served at GET /api/me/fivehour-weights.

func FitFiveHourWeights added in v0.7.3

func FitFiveHourWeights(rows []FiveHourRow, price func(model string) (TierPrice, bool)) FiveHourFit

FitFiveHourWeights fits the weights. price gives a model's API price per tier; nil, or a model it does not know, leaves the forecast scale and the fallback weights out.

type FiveHourPing added in v0.7.3

type FiveHourPing struct {
	TierTokens
	Output int64 `json:"output"`
}

FiveHourPing is the pings' billed tokens in the open 5-hour window.

type FiveHourRow added in v0.7.3

type FiveHourRow struct {
	// ID is the row id: the order of two rows in the same millisecond.
	ID    int64
	TsMs  int64
	Reset int64   // limit_5h_reset, unix seconds: the window's key
	Util  float64 // limit_5h_utilization, 0..1
	// Billed tokens. Write5m is cache_write less cache_write_1h.
	Input, CacheRead, Write5m, Write1h, Output int64
	Model                                      string
}

FiveHourRow is one request row for the fit: numbers only.

type ForecastScale added in v0.7.3

type ForecastScale struct {
	Save5m float64 `json:"save_5m"`
	Save1h float64 `json:"save_1h"`
	Ping   float64 `json:"ping"`
}

ForecastScale turns a dollar figure at API prices into one at the learned weights, for the cache strategy forecast (#1042). Each factor is the learned weight over the API price, both relative to the account's whole spend, so the total scale of the dollars does not change, only the mix:

  • Save5m, Save1h: a rescued expiry saves a write and pays a read of the same prefix;
  • Ping: a ping pays a read of the prefix.

1 is "the same as API prices".

type GapBand added in v0.5.0

type GapBand struct {
	Band string  `json:"band"`
	N    int     `json:"n"`
	USD  float64 `json:"usd"`
}

GapBand is how many idle-expiry rewrites followed a pause of a given length, and what they cost.

type GroupRow

type GroupRow struct {
	// Key is the dimension's value. "" means the request did not carry it (no effort set,
	// no stop reason reported) and the UI must label it as unset rather than hide it —
	// "most of my traffic sets no effort at all" is a finding, not a gap.
	Key             string  `json:"key"`
	Requests        int64   `json:"requests"`
	Sessions        int64   `json:"sessions"`
	TokensBefore    int64   `json:"tokens_before"`
	TokensAfter     int64   `json:"tokens_after"`
	Saved           int64   `json:"saved"`
	SavedUnique     int64   `json:"saved_unique"`
	FreshInput      int64   `json:"fresh_input"`
	CacheRead       int64   `json:"cache_read"`
	CacheWrite      int64   `json:"cache_write"`
	OutputTokens    int64   `json:"output_tokens"`
	CostUSD         float64 `json:"cost_usd"`
	BaselineCostUSD float64 `json:"baseline_cost_usd"`
	CGLLMCostUSD    float64 `json:"cg_llm_cost_usd"`
	// SpentUSD is what was actually paid (billed + our own spend); SavedUSD is baseline
	// minus that. The pair is the "spent vs saved" comparison, per group.
	SpentUSD float64 `json:"spent_usd"`
	SavedUSD float64 `json:"saved_usd"`
	// CacheSavedUSD is the PROVIDER's prompt-cache saving for this group (a diagnostic);
	// TotalSavedUSD is compaction's saving. Per MODEL
	// these are the numbers that were most wrong before: the rates now come from the
	// operator's price list, so a gateway that charges half the public API's rate is no
	// longer reported at the public rate.
	CacheSavedUSD float64 `json:"cache_saved_usd"`
	TotalSavedUSD float64 `json:"total_saved_usd"`
	// Incomplete counts rows whose accounting is not `complete`, i.e. rows whose cost
	// contribution is unknown rather than zero. A bar with Requests>0 and
	// Incomplete==Requests is a bar whose money figures mean nothing, and the UI has to
	// say so instead of drawing a zero.
	Incomplete int64 `json:"incomplete_rows"`
}

GroupRow is one bar of a breakdown: everything a spent-vs-saved comparison needs for one value of one dimension.

type Hub

type Hub struct {
	// contains filtered or unexported fields
}

Hub fans captured events out to SSE clients. Published events carry SUMMARY rows only — no before/after content, ever. The live feed is a monitoring surface; content is fetched deliberately, per request, through the access-gated detail route.

func NewHub

func NewHub() *Hub

NewHub returns an empty hub.

func (*Hub) Clients

func (h *Hub) Clients() int

Clients reports the current subscriber count.

func (*Hub) Close

func (h *Hub) Close()

Close disconnects every client.

func (*Hub) Publish

func (h *Hub) Publish(e *Event)

Publish sends one event to every live client, dropping (and evicting) any client whose buffer is full. Called only from the writer goroutine.

func (*Hub) ServeHTTP

func (h *Hub) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP streams events as SSE. It honors Last-Event-ID (header or the ?last_event_id= query param, for clients that cannot set headers), enforces a per-write timeout, and evicts itself on a stalled write. ServeHTTP serves the service-wide feed. Correct for a single-tenant proxy and for a manager; the hosted dashboard mounts ServeScoped instead.

func (*Hub) ServeScoped

func (h *Hub) ServeScoped(w http.ResponseWriter, r *http.Request, tenant string, all bool)

ServeScoped streams only one tenant's events (or everything, for a manager).

type InsightsDoc added in v0.5.4

type InsightsDoc struct {
	Items  []InsightsItem  `json:"items"`
	Owners []InsightsOwner `json:"owners"`
	// RemovableTokens / RemovableUSD are the per-request weight and the measured cost of the
	// items that can actually be removed. Deliberately NOT the inventory's headline figure, which
	// excludes built-ins entirely: this one excludes them from the OFFER and still lists them.
	RemovableTokens int     `json:"removable_tokens"`
	RemovableUSD    float64 `json:"removable_usd"`
	Basis           string  `json:"basis"`
	// Project is the folder this document describes, or "" for every project pooled. Echoed back
	// rather than left to the caller to remember: every figure below means something different
	// depending on it, and a narrowed document that looks identical to a pooled one is the
	// misreading this surface must not invite.
	Project string `json:"project,omitempty"`
	// Timeline is the per-item picture, present only when the caller asked for it. Attached rather
	// than merged into Items because the two series are aligned to ONE shared bucket list: a copy
	// of the axis on every row would be the same array sixty-eight times.
	Timeline     *ToolTimeline `json:"timeline,omitempty"`
	SelfExcluded SelfExclusion `json:"self_excluded"`
}

InsightsDoc is the shaped document a page renders.

func ShapeInsights added in v0.5.4

func ShapeInsights(rep *ToolReport, opt InsightsOptions) *InsightsDoc

ShapeInsights turns an inventory into the document a page renders.

type InsightsItem added in v0.5.4

type InsightsItem struct {
	Kind   string `json:"kind"`
	Name   string `json:"name"`
	Server string `json:"server,omitempty"`
	Plugin string `json:"plugin,omitempty"`
	Tokens int    `json:"tokens"`
	// Reads is billed tokens spent carrying it in sessions that never invoked it.
	Reads    int64   `json:"reads"`
	USD      float64 `json:"usd"`
	Priced   bool    `json:"priced"`
	Invoked  bool    `json:"invoked"`
	Calls    int     `json:"calls,omitempty"`
	Scope    string  `json:"scope"`
	Verdict  string  `json:"verdict"`
	Why      string  `json:"why"`
	Command  string  `json:"command,omitempty"`
	Settings string  `json:"settings,omitempty"`
	// LastUsedTS / DeadDays: when it was last reached for, and how long it has been carried since.
	// The evidence behind a stale verdict, and a figure a reader can check against their memory.
	LastUsedTS int64   `json:"last_used_ts,omitempty"`
	DeadDays   float64 `json:"dead_days,omitempty"`
	Desc       string  `json:"desc,omitempty"`
	DescFull   string  `json:"desc_full,omitempty"`
	DescKnown  bool    `json:"desc_known"`
}

InsightsItem is one declared capability, with what it cost and what removing it would mean.

type InsightsOptions added in v0.5.4

type InsightsOptions struct {
	// Qualified names the items the SERVER's own floor has cleared for removal, keyed by item
	// name. Supplied rather than recomputed because an inventory row carries no dates at all: a
	// local check could only test the session count, which passes for five sessions in one
	// afternoon — the exact case the seven-day span exists to reject.
	Qualified map[string]bool
	// Descriptions maps an item name to what it does, read from its own SKILL.md. Absent is
	// absent: a description this layer invented would be indistinguishable from one it read.
	Descriptions map[string]string
	// Project is the folder being reported on, or "" for every project pooled. It changes the
	// BASIS rather than any arithmetic — the rows are already scoped by the caller's filter — so
	// that a narrowed document says so instead of looking like an all-projects one.
	Project string
	// ProjectNone says the rows are the UNATTRIBUTED ones — requests that stated no directory,
	// plus every row written before the column existed. A separate flag for the same reason the
	// Filter needs one: the project being reported on is "", which as a value is indistinguishable
	// from "every project pooled", and the two need different wording.
	ProjectNone bool
}

InsightsOptions carries what shaping cannot derive from the inventory itself.

type InsightsOwner added in v0.5.4

type InsightsOwner struct {
	// Kind is "plugin" or "server". Kept apart rather than merged on the name, because
	// `mcp__giveinfo__info` and `giveinfo:blah` can share a word with no relationship at all.
	Kind     string  `json:"kind"`
	Name     string  `json:"name"`
	Items    int     `json:"items"`
	Skills   int     `json:"skills,omitempty"`
	MCPTools int     `json:"mcp_tools,omitempty"`
	Tokens   int     `json:"tokens"`
	USD      float64 `json:"usd"`
	// UnpricedItems counts children whose models have no known rate, so a subtotal short by an
	// unknown amount says so rather than being presented as complete.
	UnpricedItems int    `json:"unpriced_items,omitempty"`
	Command       string `json:"command,omitempty"`
}

InsightsOwner is the thing that removes a group of items, with its own subtotal.

A VIEW, NOT AN ADDEND. These subtotals re-count tokens already counted per item, one level up. Summing them double-counts; adding them to RemovableUSD double-counts differently. RemovableUSD is computed over items, each counted once, and nothing here contributes to it.

type Inventory

type Inventory struct {
	Digest string
	Decls  []Decl
	Used   []Used
	// System is the top-level system prompt this request carried, or nil when it had none.
	// Kept OFF Decls because it is not a declaration and, more importantly, because Decls is
	// memoized by a digest that does not cover the system prompt — a shared cache entry
	// holding one tenant's system text and served to another is a disclosure, not a bug to
	// find later.
	System *SystemPrompt
	// UseFingerprint identifies the turn Used came from. Claude Code resends the whole
	// transcript, so consecutive requests usually show the SAME last tool-using turn;
	// the writer skips a repeat rather than counting those calls again per resend.
	UseFingerprint uint64
}

Inventory is one request's contribution: the declaration set it carried (identified by Digest, so the writer stores each distinct set once per session) and the tool calls visible in its last tool-using turn.

func ScanInventory

func ScanInventory(wire string, body []byte) *Inventory

ScanInventory reads one request's declared inventory and used set off the raw body. Returns nil when the request declares no tools at all — an agent that uses none has no inventory, and a phantom row for it would make "nothing declared" and "nothing captured" the same number.

wire is the request's dialect, from schema.WireFor (the provider alone does not say):

  • Anthropic names tools at `tools.#.name` and calls them in `tool_use` content blocks.
  • OpenAI Chat nests both a level deeper (`tools.#.function.name`, `tool_calls.#.function.name`).
  • OpenAI Responses declares a function tool flat (`tools.#.name`, type "function") and calls it with a `function_call` item in `input`.

type KVCacheAnalysis

type KVCacheAnalysis struct {
	Cards     KVCacheCards    `json:"cards"`
	Coverage  KVCacheCoverage `json:"coverage"`
	IdleBands []Band          `json:"idle_bands"`
	Survival  []SurvivalPoint `json:"survival"`
	HourBins  []Band          `json:"hour_bins"`
	ByTTL     []KVCacheGroup  `json:"by_ttl"`
	ByBucket  []KVCacheGroup  `json:"by_bucket"`
	ByUser    []KVCacheGroup  `json:"by_user"`
	ByModel   []KVCacheGroup  `json:"by_model"`
	// Assumptions is the server's own statement of every formula and caveat, so the page prints
	// the arithmetic rather than restating it in a template nothing tests.
	Assumptions KVCacheAssumptions `json:"assumptions"`
	Pricing     *kvcache.PriceList `json:"pricing"`
	// FirstTS and LastTS are the span the rows actually cover, so a quiet window is
	// distinguishable from a narrow one.
	FirstTS int64 `json:"first_ts"`
	LastTS  int64 `json:"last_ts"`

	Scanned   int64 `json:"scanned"`
	Total     int64 `json:"total"`
	Truncated bool  `json:"truncated"`
}

KVCacheAnalysis is the whole analysis read: one request, one consistent set of denominators.

Deliberately ONE payload rather than a panel per endpoint. Every figure shares the dataset it came from, and the failure that avoids is two tiles on one page reporting different totals because two queries disagreed about which rows were in scope — which this repo has shipped.

type KVCacheArm

type KVCacheArm struct {
	kvcache.StrategySpec
	Selectable bool `json:"selectable"`
}

KVCacheArm is one selectable arm as the page presents it: the domain's own spec, plus whether this API can actually construct it.

Selectable is a real distinction rather than a filter. `replay` is a registry arm whose whole input is an action list supplied in-process, so no query string can ask for it — and dropping it from the payload would leave the page unable to explain why an arm the docs mention is not on the picker. It is listed, marked, and not offered as a checkbox.

func KVCacheArms

func KVCacheArms() []KVCacheArm

KVCacheArms is every arm the page may show, in the domain's presentation order, with the dash-only custom arm last.

The order is kvcache.Registry()'s and is deliberately not re-sorted here: it runs cheapest-to-reason-about first, so a reader meets the baseline before the policies scored against it. Sorting by cost or by hit rate would be the page choosing a winner.

type KVCacheAssumptions

type KVCacheAssumptions struct {
	// TimeZone is UTC, always, and it is a field rather than a constant in the page because the
	// claim has to travel with the data: the store carries no per-user timezone, so a local one
	// would be invented.
	TimeZone string `json:"time_zone"`
	TimeUnit string `json:"time_unit"`

	Horizon5mSeconds float64 `json:"horizon_5m_seconds"`
	Horizon1hSeconds float64 `json:"horizon_1h_seconds"`

	Multipliers kvcache.Multipliers `json:"multipliers"`
	Semantics   kvcache.Semantics   `json:"semantics"`
	Schedule    KVCacheSchedule     `json:"schedule"`

	Formulas []KVCacheFormula `json:"formulas"`
	Notes    []string         `json:"notes"`
}

KVCacheAssumptions is the server's own statement of what every figure on the page rests on: the units, the two horizons, the pricing multiples, the provider cache semantics, the keep-alive schedule, the cost formulas and the caveats.

It is on the wire so the page PRINTS it rather than restating it. Every number here is one the simulation actually used, echoed back — so a reader checking a figure against a formula is checking it against the arithmetic that produced it.

type KVCacheCards

type KVCacheCards struct {
	Requests      int64   `json:"requests"`
	Scanned       int64   `json:"scanned"`
	Conversations int64   `json:"conversations"`
	Users         int64   `json:"users"`
	Models        int64   `json:"models"`
	WithNext      int64   `json:"with_next"`
	FinalRequests int64   `json:"final_requests"`
	MedianIdleMs  float64 `json:"median_idle_ms"`
	MeanIdleMs    float64 `json:"mean_idle_ms"`
	P90IdleMs     float64 `json:"p90_idle_ms"`
	Within5m      int64   `json:"within_5m"`
	Within1h      int64   `json:"within_1h"`
	Within5mPct   float64 `json:"within_5m_pct"`
	Within1hPct   float64 `json:"within_1h_pct"`
	Hits          int64   `json:"hits"`
	// HitRatePct is the share the PROVIDER served from cache, as recorded. An observation of
	// what happened, never a simulated figure — the simulated ones live on kvcache.Result.
	HitRatePct  float64 `json:"hit_rate_pct"`
	CostUSD     float64 `json:"cost_usd"`
	CostUnknown int64   `json:"cost_unknown"`
	// CachedContextP50 is the median billed prefix in tokens, over the requests that CACHED
	// SOMETHING — rows with a zero prefix are excluded.
	//
	// The population is the whole point. This figure is what every cache-write, cache-read and
	// keep-alive dollar in the pricing panel is multiplied by, and a request that cached nothing
	// has no prefix to price. Including them does not add noise, it biases: 2,120 of the
	// production corpus's 14,407 rows have a zero prefix, which pulled the median from 147,550
	// down to 124,845 — 18% low on every cost derived from it. A tenant whose traffic is mostly
	// uncached got a median of ZERO, and then a whole table of $0.00 rates rendered as though
	// they were known, which is the failure Result.Valued exists to prevent one layer over.
	//
	// PrefixKnown on the pricing view is the flag that says whether this could be computed at
	// all; see TestTheMedianPrefixPricesOnlyRowsThatCached.
	CachedContextP50 int64 `json:"cached_context_p50"`
}

KVCacheCards is the summary band.

Every idle figure's denominator is WithNext, never Requests: a conversation's last request has no gap, and dividing by Requests would count it as a zero-second return.

type KVCacheCoverage

type KVCacheCoverage struct {
	// The three tier states, counted apart rather than blended. See observedTTL.
	TTLConfigured int64 `json:"ttl_configured"`
	TTLObserved   int64 `json:"ttl_observed"`
	TTLUnknown    int64 `json:"ttl_unknown"`
	// CostUnknown is rows whose accounting was incomplete: counted everywhere, valued nowhere.
	CostUnknown int64 `json:"cost_unknown"`
	// SingleRequestConversations is conversations with exactly one request in this window. On
	// the production corpus that is 1,551 of 1,772, so a page that did not say so would look
	// like it had thrown most of the traffic away.
	SingleRequestConversations int64 `json:"single_request_conversations"`
	// KeepAliveRows is the ping rows this dataset EXCLUDED. A ping is a request context-guru
	// sent while nobody was at the keyboard; counted, it would split one real idle gap into two
	// short ones and make every reuse probability wrong in the flattering direction.
	KeepAliveRows int64 `json:"keepalive_rows"`
}

KVCacheCoverage answers "is a zero here a measurement or an absence?".

Every field counts rows that could NOT answer something, and they are on the wire because three of them are routinely nonzero on real history: a snapshot written before the cache_ttl column records no tier, a row whose token accounting was incomplete has no cost, and a conversation with one request in the window contributes a final request and no gap at all. A page that rendered those as 5m, $0.00 and 0 s would fabricate three measurements at once.

type KVCacheCustom

type KVCacheCustom struct {
	// P5m and P1h are the reuse-probability thresholds, as fractions.
	P5m float64 `json:"p_5m"`
	P1h float64 `json:"p_1h"`
	// MinPrefix is the prefix below which nothing is cached at all, in tokens.
	MinPrefix int64 `json:"min_prefix"`
	// AlwaysPing forces the long hold onto the keep-alive path rather than the cheaper of the
	// two, for an operator measuring the ping path specifically.
	AlwaysPing bool `json:"always_ping"`
}

KVCacheCustom is the configurable arm's inputs, as the page sends them.

type KVCacheFeatureImportance

type KVCacheFeatureImportance struct {
	// LogisticRegression's Score is the standardized coefficient's magnitude.
	LogisticRegression []KVCacheFeatureRank `json:"logistic_regression"`
	// GradientBoosted's Score is the tree model's own importance. Same training data, same
	// label as LogisticRegression, fit purely for this comparison — never scored as a
	// policy (see docs/results/kv-ttl-predictor-arms.md).
	GradientBoosted []KVCacheFeatureRank `json:"gradient_boosted"`
}

KVCacheFeatureImportance holds each model's own top-5, from the offline predictor study — see kvCacheFeatureImportance for the source and why this is static data.

type KVCacheFeatureRank

type KVCacheFeatureRank struct {
	Rank    int     `json:"rank"`
	Feature string  `json:"feature"`
	Score   float64 `json:"score"`
}

KVCacheFeatureRank is one feature at one rank in ONE model's own top-5 — not a row scored by both models, which is the mistake this type exists to prevent: the two models agree on ranks 1-2 and diverge from rank 3 on, so a single table with one column per model would have to fabricate a score for a feature that model never ranked at all.

type KVCacheFormula

type KVCacheFormula struct {
	Name string `json:"name"`
	// Formula and Note are spelled the way the page reads them. Renaming either is a silent
	// break: the expression renders into an empty <code> element, so the panel lists eleven
	// formula NAMES with eleven blank boxes under them and looks like a styling glitch rather
	// than a contract mismatch. TestThePageReadsTheFormulaFieldsTheServerSends is the guard.
	Formula string `json:"formula"`
	Note    string `json:"note"`
}

KVCacheFormula is one cost formula: what it is called, the expression, and the sentence that says what it means and where it can mislead.

A struct rather than prose in the UI for one reason: a formula typed into a JavaScript template is a SECOND definition of the arithmetic, and nothing tests it against the first. These travel with the data and are asserted against the functions that implement them.

type KVCacheGroup

type KVCacheGroup struct {
	Key           string  `json:"key"`
	Requests      int64   `json:"requests"`
	Conversations int64   `json:"conversations"`
	WithNext      int64   `json:"with_next"`
	FinalRequests int64   `json:"final_requests"`
	MedianIdleMs  float64 `json:"median_idle_ms"`
	MeanIdleMs    float64 `json:"mean_idle_ms"`
	Within5mPct   float64 `json:"within_5m_pct"`
	Within1hPct   float64 `json:"within_1h_pct"`
	// Hits is the numerator of HitRatePct, and it is on the wire for two reasons. A rate without
	// its own count cannot be checked — a share accidentally expressed as a fraction stays inside
	// [0,100] and no range assertion can see it, so only recomputing it from its numerator and
	// denominator catches that — and the page can say "2,599 of 3,391" instead of a bare
	// percentage, which is the standard the rest of this dashboard already keeps.
	Hits        int64   `json:"hits"`
	HitRatePct  float64 `json:"hit_rate_pct"`
	CostUSD     float64 `json:"cost_usd"`
	CostUnknown int64   `json:"cost_unknown"`
	// Source is set only on the TTL groups, naming how that tier was known.
	Source string `json:"source,omitempty"`
}

KVCacheGroup is the OBSERVED dataset restricted to one user, model, tier or time-of-day band.

Not kvcache.Group, which is a SIMULATED result. The two deliberately do not share a type: with the same field names a reader would eventually compare a measurement with a projection.

type KVCacheHoldout

type KVCacheHoldout struct {
	Baseline    string   `json:"baseline"`
	Weekdays    []string `json:"weekdays_included"`
	TimeZone    string   `json:"time_zone"`
	MinRequests int      `json:"min_requests"`

	TrainSince int64 `json:"train_since"`
	TrainUntil int64 `json:"train_until"`
	TestSince  int64 `json:"test_since"`
	TestUntil  int64 `json:"test_until"`

	Users []string             `json:"users"`
	Cells []KVCacheHoldoutCell `json:"cells"`

	// Each window's own read coverage, carried straight from the KVCacheSuggest run that
	// produced it. KVCacheDataset caps one read at kvCacheMaxRows and the cap keeps the
	// NEWEST rows, so a window bigger than the cap is silently reduced to its own recent
	// tail — and the two windows here are read and capped INDEPENDENTLY.
	//
	// That matters more here than on the single-window page, which already declares it
	// (KVCacheSuggestions.Truncated, banner in dash/ui/kvcache.js). A clipped TRAIN window
	// means the arm was chosen on a slice of the period the reader asked for; a clipped
	// TEST window means it was scored on one; and RetentionPct can then divide two totals
	// whose populations cover very different fractions of their own windows. Every
	// per-cell request count reports only the rows that were read, so without these fields
	// nothing in the payload reveals any of it — the one silent data loss that would
	// undermine every other honesty flag in this file.
	TrainScanned   int64 `json:"train_scanned"`
	TrainTotal     int64 `json:"train_total"`
	TrainTruncated bool  `json:"train_truncated"`
	TestScanned    int64 `json:"test_scanned"`
	TestTotal      int64 `json:"test_total"`
	TestTruncated  bool  `json:"test_truncated"`

	// TotalTrainSavingUSD and TotalTestSavingUSD sum the CHOSEN arm over exactly the cells
	// where BOTH sides are known and neither side is below the request floor — the only
	// population where the two totals describe the same thing. ComparableCells is that
	// population's size, reported so the totals are never read as covering every cell.
	TotalTrainSavingUSD float64 `json:"total_train_saving_usd"`
	TotalTestSavingUSD  float64 `json:"total_test_saving_usd"`
	ComparableCells     int     `json:"comparable_cells"`
	// TotalCells is every cell the train window produced, comparable or not, so the gap
	// between it and ComparableCells is visible rather than inferred.
	TotalCells int `json:"total_cells"`
	// RetentionPct is TotalTestSavingUSD / TotalTrainSavingUSD × 100: how much of the
	// in-sample predicted saving survived contact with rows the arm was not chosen on.
	// Below 100 is the expected direction; it can be negative, when the chosen arms cost
	// more than the baseline out of sample, and that is reported rather than clamped for
	// the same reason kvcache.Savings.AbsoluteUSD is.
	//
	// Computed here rather than left to the caller because the two conditions that make it
	// undefined — no comparable cells at all, and a train total of exactly zero (a ratio
	// against nothing is not 0%, it is undefined, the same rule kvcache.Savings.Known
	// already encodes for percentages) — are properties of this data, not of whoever
	// renders it. A UI that divides these two totals itself has to rediscover both, and
	// dash/ui/campaigns.js deliberately does no arithmetic precisely so that it cannot get
	// this wrong.
	RetentionPct   float64 `json:"retention_pct"`
	RetentionKnown bool    `json:"retention_known"`

	Notes []string `json:"notes"`
}

KVCacheHoldout is the whole /api/kvcache/suggest/holdout payload.

type KVCacheHoldoutArm

type KVCacheHoldoutArm struct {
	Strategy string `json:"strategy"`
	// TrainSavingUSD/TestSavingUSD are this arm's saving over the SAME BASELINE in each
	// window (kvcache.Compare's AbsoluteUSD). Negative where the arm costs more than the
	// baseline, and reported that way — see kvcache.Savings.AbsoluteUSD on why a
	// comparison that clamps stops being one.
	TrainSavingUSD float64 `json:"train_saving_usd"`
	TrainKnown     bool    `json:"train_known"`
	TestSavingUSD  float64 `json:"test_saving_usd"`
	// TestKnown is false where this arm has no priced result in the test window at all —
	// the cell had no test traffic, or nothing in it could be priced. The field is then
	// meaningless and the UI must render "not enough data", never 0.00.
	TestKnown bool `json:"test_known"`
	// Chosen marks the arm the TRAIN window's own suggester picked as this cell's winner:
	// the one a campaign built from the train window would actually have enforced.
	Chosen bool `json:"chosen"`
}

KVCacheHoldoutArm is one arm's saving on the train window beside its saving on the test window, for one (user, hour) cell.

type KVCacheHoldoutCell

type KVCacheHoldoutCell struct {
	User    string `json:"user"`
	HourUTC int    `json:"hour_utc"`

	// TrainRequests/TestRequests are the two populations this cell was decided from and
	// scored on. Both are Sunday-Thursday only, the same filter KVCacheSuggest applies —
	// see its own doc comment on why the weekend is not read at all.
	TrainRequests int64 `json:"train_requests"`
	TestRequests  int64 `json:"test_requests"`
	// TrainInsufficientData/TestInsufficientData mirror KVCacheSuggestion.InsufficientData
	// on each side: below kvSuggestMinRequests the cell still reports every number, but
	// acting on it as a pattern is what the flag warns against.
	TrainInsufficientData bool `json:"train_insufficient_data"`
	TestInsufficientData  bool `json:"test_insufficient_data"`

	// Arm is the arm the train window chose — what a campaign created from that window
	// would have enforced for this cell.
	Arm string `json:"arm"`
	// TrainSavingUSD is that arm's IN-SAMPLE saving: chosen on these rows, scored on these
	// rows. This is the figure the live KV-cache page and a campaign's PredictedUSD both
	// show today.
	TrainSavingUSD float64 `json:"train_saving_usd"`
	TrainKnown     bool    `json:"train_known"`
	// TestSavingUSD is the same arm's saving on the test window's rows — out of sample,
	// the honest forecast. TestKnown is false where the test window has nothing to score
	// it on; the number is then absent, never a zero standing in for one.
	TestSavingUSD float64 `json:"test_saving_usd"`
	TestKnown     bool    `json:"test_known"`
	// TestNote says why TestKnown is false, so a blank cell is explained rather than just
	// blank. Empty when TestKnown is true.
	TestNote string `json:"test_note,omitempty"`

	// Arms is every candidate's train-and-test pair for this cell, the train-chosen one
	// among them and flagged — so a reader can see whether the arm that won on train was
	// anywhere near the best on test, which is the whole question this view exists for.
	Arms []KVCacheHoldoutArm `json:"arms"`
}

KVCacheHoldoutCell is one (user, hour-of-day) cell's train-chosen arm, scored on held-out rows.

type KVCacheOptions

type KVCacheOptions struct {
	Limit  int
	Offset int
	// Sort is a key of kvCacheSortKeys; Dir is "asc" or "desc".
	Sort string
	Dir  string
	// Bucket is a kvcache.Bucket name, or "" for every band. UTC.
	Bucket string
	// TTL is "none", string(kvcache.TTL5m), string(kvcache.TTL1h), or "" for every tier. It
	// selects on the RECONSTRUCTED tier, not on the raw column — see observedTTL.
	TTL string
	// HasNext is "yes" (requests followed by another in the same conversation), "no" (the last
	// request of a conversation), or "" for both.
	//
	// Its own dimension rather than a sentinel on some other field, because "the requests
	// nobody came back to" is a population an operator asks about directly — and it is the
	// population every average on this page has to exclude.
	HasNext string
	// ByThread links each request to the next one on its own THREAD (requests.thread_id) as well as its conversation: a subagent's
	// request is not the successor of the main thread's. Rows recorded before threads existed have thread_id ” and link as before.
	ByThread bool
}

KVCacheOptions are the narrowings that exist only on this page, plus the table's paging.

They are separate from Filter because all three narrowings are DERIVED — a reconstructed tier, a time-of-day band, and whether a successor exists at all — and none of them is a column any other view could filter on.

type KVCachePriceCost

type KVCachePriceCost struct {
	Model string `json:"model"`
	Known bool   `json:"known"`
	// Uncached is the prefix billed as fresh input — the no-cache alternative to all of it.
	Uncached float64 `json:"uncached_usd"`
	// Read is one cache hit on the prefix; Write5m and Write1h are one creation at each tier.
	Read    float64 `json:"read_usd"`
	Write5m float64 `json:"write_5m_usd"`
	Write1h float64 `json:"write_1h_usd"`
	// KeepAlive is ONE refresh, and Late is one refresh that arrived after the entry lapsed.
	KeepAlive float64 `json:"keep_alive_usd"`
	Late5m    float64 `json:"late_5m_usd"`
	Late1h    float64 `json:"late_1h_usd"`
	// Hold5m and Hold1h are the whole cost of holding the prefix at each tier through one idle
	// span: the creation plus MaxPings refreshes. The two numbers a strategy chooses between.
	Hold5m float64 `json:"hold_5m_usd"`
	Hold1h float64 `json:"hold_1h_usd"`
	// Raise5mTo1h is what the longer hold costs on the SAME write: Write1h − Write5m.
	Raise5mTo1h float64 `json:"raise_5m_to_1h_usd"`
	// SavedPerMiss is what one five-minute miss costs beyond a hit at the same tier: Late5m −
	// KeepAlive. The ping overhead is in both terms and cancels.
	SavedPerMiss float64 `json:"saved_per_miss_usd"`
	// SavedVs1hWrite is Late5m − Write1h, SIGNED: negative means paying for the 1-hour tier up
	// front costs more than the one 5-minute miss it would have prevented.
	SavedVs1hWrite float64 `json:"saved_vs_1h_write_usd"`
	// BreakevenMisses is how many prevented 5-minute misses pay for raising the TTL, or nil when
	// SavedPerMiss or Raise5mTo1h is not positive — undefined, not zero.
	BreakevenMisses *int64 `json:"breakeven_misses"`
}

KVCachePriceCost is one model's rates turned into DOLLARS on this window's own median prefix.

It exists because a per-token rate is not a number anybody can act on. "$0.0000060 per token at the one-hour tier" and "$0.75 to hold your median 124,845-token prompt for an hour" are the same fact, and only the second one answers the question the reader has. Both are shown: the rate, because it is what they can edit, and the cost, because it is what they are deciding about.

type KVCachePriceView

type KVCachePriceView struct {
	Pricing     *kvcache.PriceList `json:"pricing"`
	Assumptions KVCacheAssumptions `json:"assumptions"`
	// Arms is every arm that exists, so the page builds its picker from what the server can
	// actually run instead of from a list of its own. A hardcoded picker is how four shipped
	// arms stayed invisible for a day.
	Arms []KVCacheArm `json:"arms"`
	// Prefix is the window's own MEDIAN billed prefix, in tokens, and the size every cost
	// above is computed on. The median rather than the mean: per-request cache cost is
	// bimodal on real traffic, so a mean would describe no request.
	Prefix int64 `json:"prefix_tokens"`
	// PrefixKnown is false when no request in this window cached anything, so there is no prefix
	// to price on. Every cost below is then ZERO FOR WANT OF A SIZE, not because the tier is
	// free — and a table of $0.00 rates beside `known: true` is exactly the fabricated
	// measurement kvcache.Result.Valued exists to prevent one layer over. It was reachable: a
	// tenant whose traffic is mostly uncached is the tenant most likely to be reading this page.
	PrefixKnown bool               `json:"prefix_known"`
	Costs       []KVCachePriceCost `json:"costs"`
}

KVCachePriceView is /api/kvcache/pricing: the editable rates, the assumptions, and what those rates come to on this window's own prefix.

type KVCacheRow

type KVCacheRow struct {
	*kvcache.Request
	// RequestURL and ConversationURL are the links to the existing request drawer and session
	// diff. Built here rather than in the page because a session id is CLIENT-SUPPLIED text —
	// it can contain a slash, a space, a hash — and a link assembled by string concatenation in
	// JavaScript is where that becomes a broken URL or worse.
	RequestURL      string `json:"request_url"`
	ConversationURL string `json:"conversation_url"`
}

KVCacheRow is one dataset row plus the two ways back out of the analysis.

type KVCacheRowPage

type KVCacheRowPage struct {
	Rows []*KVCacheRow `json:"rows"`
	// Total is how many rows match the filter, so the pager can say "51–100 of 14,407".
	Total  int64 `json:"total"`
	Offset int   `json:"offset"`
	Limit  int   `json:"limit"`
	// Truncated says the ANALYSIS over this filter is capped, so the table's own total and the
	// figures above it describe different row counts. On the wire because the pager prints it.
	Truncated bool `json:"truncated"`
}

KVCacheRowPage is one page of the detail table.

type KVCacheSchedule

type KVCacheSchedule struct {
	IdleSeconds   float64 `json:"idle_seconds"`
	IdleSeconds1h float64 `json:"idle_seconds_1h"`
	MaxPings      int     `json:"max_pings"`
}

KVCacheSchedule is the keep-alive schedule a simulation ran with, in seconds.

Two intervals, because the interval is the whole cost difference between the two tiers: one ping costs the same either way (it is a cache read), but a five-minute entry has to be touched roughly twelve times as often as a one-hour one to be held for the same span.

type KVCacheSegmentCell added in v0.5.3

type KVCacheSegmentCell struct {
	Segment string `json:"segment"`
	KVCacheSuggestion
}

KVCacheSegmentCell is one (user, hour, segment) cell: the same decision KVCacheSuggest makes for a (user, hour) cell, over that segment's rows only.

type KVCacheSegments added in v0.5.3

type KVCacheSegments struct {
	Baseline  string               `json:"baseline"`
	Cells     []KVCacheSegmentCell `json:"cells"`
	Scanned   int64                `json:"scanned"`
	Total     int64                `json:"total"`
	Truncated bool                 `json:"truncated"`
}

KVCacheSegments is KVCacheSuggestBy's result.

type KVCacheSimConfig

type KVCacheSimConfig struct {
	// Multipliers and Overrides are the pricing experiment: the multiples used to fill in a
	// rate the price list does not state, and per-model rates typed in the page.
	Multipliers kvcache.Multipliers
	Overrides   map[string]kvcache.Override
	// Semantics is the provider cache behaviour.
	Semantics kvcache.Semantics
	// The keep-alive schedule.
	PingIdle   time.Duration
	PingIdle1h time.Duration
	MaxPings   int
	// Strategies names the arms to run, and Baseline the one the others are scored against.
	Strategies []string
	Baseline   string
	// Custom is the configurable arm's parameters.
	Custom KVCacheCustom
	// Predictor, when non-nil, is wired into the custom arm. There is no way to set this from
	// an HTTP request and that is deliberate: a predictor is code, not a query parameter. It
	// is here so an in-process caller — the proxy, a benchmark harness, a test — can score a
	// learned model against exactly the same baseline the page shows.
	Predictor kvcache.Predictor
}

KVCacheSimConfig is everything the page can change about a simulation.

type KVCacheSimulation

type KVCacheSimulation struct {
	// Baseline is the arm every saving below is measured against, by name.
	Baseline string `json:"baseline"`
	// Results is one entry per arm, in kvCacheStrategyOrder.
	Results []*kvcache.Result `json:"results"`
	// Savings is one entry per arm INCLUDING the baseline (whose own saving is exactly zero,
	// shown rather than omitted so the table has a row for every arm).
	Savings []kvcache.Savings `json:"savings"`

	Pricing     *kvcache.PriceList `json:"pricing"`
	Assumptions KVCacheAssumptions `json:"assumptions"`
	// Arms is every arm that exists, so the page builds its picker from what the server can
	// actually run instead of from a list of its own. A hardcoded picker is how four shipped
	// arms stayed invisible for a day.
	Arms []KVCacheArm `json:"arms"`

	// Unknown names any requested strategy that does not exist, rather than silently running
	// something else.
	Unknown []string `json:"unknown,omitempty"`

	// FeatureImportance is what predicts a keep-alive rescue, from the offline predictor
	// study — see kvCacheFeatureImportance for why this is STATIC data rather than
	// something this simulation computes.
	FeatureImportance KVCacheFeatureImportance `json:"feature_importance"`

	Scanned   int64 `json:"scanned"`
	Total     int64 `json:"total"`
	Truncated bool  `json:"truncated"`
	// WindowEnd is the instant an open idle span is bounded at, and it is on the wire because
	// PingsOnOpenSpans cannot be read without it.
	WindowEnd int64 `json:"window_end"`
}

KVCacheSimulation is the whole /api/kvcache/simulate payload.

type KVCacheSuggestion

type KVCacheSuggestion struct {
	User    string `json:"user"`
	HourUTC int    `json:"hour_utc"`
	// Requests is how many Sunday–Thursday requests fall in this cell. It is the population
	// every figure below was decided from — Friday and Saturday requests, if this account has
	// any in this hour, are not in it.
	Requests int64 `json:"requests"`
	// InsufficientData is true below kvSuggestMinRequests. Every candidate is still simulated
	// and reported — a floor on trusting the answer is not a reason to hide the arithmetic.
	InsufficientData bool `json:"insufficient_data"`

	// Baseline is the arm every saving below is measured against — the same honest denominator
	// the page-wide simulator uses, not a second definition of it.
	Baseline    string  `json:"baseline"`
	BaselineUSD float64 `json:"baseline_usd"`

	// BestStrategy is the argmax by absolute dollar saving against Baseline, over every valued
	// candidate. Baseline is itself always a candidate, so BestStrategy is never worse than
	// changing nothing: the floor of this field is "keep doing what you already do".
	BestStrategy    string  `json:"best_strategy"`
	BestDescription string  `json:"best_description,omitempty"`
	BestUSD         float64 `json:"best_usd"`
	// SavingUSD and SavingPct are Baseline's cost minus the winner's, absolute and as a share of
	// Baseline. Never negative — see BestStrategy — and never clamped either; a cell with no
	// arm beating the baseline simply reports 0.
	SavingUSD   float64 `json:"saving_usd"`
	SavingPct   float64 `json:"saving_pct"`
	SavingKnown bool    `json:"saving_known"`
	// Valued is false where neither the baseline nor the winner could be priced — every dollar
	// figure on this cell is then 0.00 for want of a rate, not because nothing was spent.
	//
	// It is a floor, not a coverage measure: kvcache.Result.Valued is `Unpriced < Requests`, so
	// ANY one priced request in the cell sets it. UnpricedRequests is the coverage — how many of
	// this cell's own Requests contributed nothing to SavingUSD because their model has no
	// rates. Nonzero means SavingUSD describes only part of this cell, which is why the
	// service-wide total refuses such a cell rather than adding it (see KVCacheSuggestions).
	Valued           bool  `json:"valued"`
	UnpricedRequests int64 `json:"unpriced_requests"`

	// OptimalUSD and OptimalSavingUSD are the exact ceiling's own cost on this cell's rows,
	// and its saving over Baseline — computed and frozen ALONGSIDE the winner, never as one
	// of the candidates a sweep could pick (see kvSuggestCandidates' own doc comment for why
	// `optimal` is excluded there: it reads the true next-request time). Reported so a reader
	// always sees how much headroom remains beyond what was actually recommended, not only
	// against the baseline.
	OptimalUSD       float64 `json:"optimal_usd"`
	OptimalSavingUSD float64 `json:"optimal_saving_usd"`
	OptimalKnown     bool    `json:"optimal_known"`

	// Candidates is every arm's own saving over this cell's own rows, baseline included, so the
	// winner is checkable rather than asserted.
	Candidates []kvcache.Savings `json:"candidates"`
}

KVCacheSuggestion is one (user, hour-of-day) cell's winner, decided from exactly that account's own Sunday–Thursday requests in that hour — nothing else.

type KVCacheSuggestions

type KVCacheSuggestions struct {
	Baseline string   `json:"baseline"`
	Weekdays []string `json:"weekdays_included"`
	TimeZone string   `json:"time_zone"`
	// MinRequests is kvSuggestMinRequests, echoed so a reader of the JSON does not have to find
	// it in the code that produced it.
	MinRequests int      `json:"min_requests"`
	Users       []string `json:"users"`
	// Cells is one entry per (user, hour) that had any Sunday–Thursday traffic at all, ordered
	// by user then hour so the same window renders the same list twice.
	Cells []KVCacheSuggestion `json:"cells"`
	// TotalSavingUSD sums SavingUSD over the cells that cleared MinRequests and were priced in
	// FULL — the aggregate this deployment would have kept had every cell run its own winner
	// instead of the baseline, over exactly the history read.
	//
	// In full, because a cell's own Valued flag is `Unpriced < Requests` (kvcache/simulate.go):
	// a cell with 99 of its 100 requests unpriced is Valued, and its SavingUSD is then measured
	// on the one priced request while being labelled with the whole cell.
	//
	// The dollars themselves are not inflated by this, and it matters that the comment says so:
	// an unpriced request contributes $0 to the baseline AND $0 to the winning arm, so a
	// partially-priced cell UNDERSTATES its own saving. What is actually damaged is the CHOICE.
	// BestStrategy is an argmax over the priced subset, and that ranking moves: pricing one
	// missing model was measured to flip keepalive-5m-once from -0.07% to +1.07% and
	// stop-reason-gated from -0.35% to +0.75%, reordering ranks 5 through 8 — and
	// stop-reason-gated buys 249 pings. So the defect is a total that claims coverage it does
	// not have, over cells whose winner was picked on a fraction of their own traffic.
	//
	// A cell therefore enters this total only when nothing in it went unpriced, which makes the
	// figure a floor over fully-covered cells rather than a blend of two populations.
	//
	// TotalSavingKnown is false when NO cell qualified. The figure is then n/a, not $0.00 — a
	// zero here would claim that switching every cell to its own winner saves nothing, which is
	// the opposite of "we could not price it". TotalSavingCells is how many cells are behind the
	// figure and TotalUnpricedRequests how many requests were left out of it for want of a rate,
	// so the coverage is on the payload rather than inferred from it. Before this field existed
	// `grep -n Unpriced dash/kvcachesuggest.go` returned nothing: no UI could disclose the
	// coverage because the payload did not carry it, while the sibling table on the same tab
	// does (kvcache.js:1136).
	TotalSavingUSD        float64 `json:"total_saving_usd"`
	TotalSavingKnown      bool    `json:"total_saving_known"`
	TotalSavingCells      int64   `json:"total_saving_cells"`
	TotalUnpricedRequests int64   `json:"total_unpriced_requests"`

	Scanned   int64 `json:"scanned"`
	Total     int64 `json:"total"`
	Truncated bool  `json:"truncated"`

	Notes []string `json:"notes"`
}

KVCacheSuggestions is the whole /api/kvcache/suggest payload.

type KeepAliveBehaviour

type KeepAliveBehaviour struct {
	Daily []DayPoint `json:"daily"`
	// GapBands is the idle-gap histogram with FIXED edges, so the shape is comparable between
	// accounts and between windows. The edge at 580 s is not arbitrary: it is the shipped
	// policy's own coverage at X=280, K=1.
	GapBands    []Band        `json:"gap_bands"`
	PrefixBands []Band        `json:"prefix_bands"`
	HourBins    []Band        `json:"hour_bins"`
	Gaps        []AccountGaps `json:"account_gaps"`
	// PrefixP10/P50/P90 in tokens, over the lapsed entries. p50 is 292,527 on the corpus and
	// 347 of 356 are past 20k — which is the measured reason a `prefix >= 20k` gate
	// costs almost nothing at 20k (the pre-#435 gate), and the panel says so. The shipped floors are 20k for a
	// tool wait, background work, a teammate or a subagent and 80k for a main thread that waits for a person or for an unknown cause (#858).
	PrefixP10 int64 `json:"prefix_p10"`
	PrefixP50 int64 `json:"prefix_p50"`
	PrefixP90 int64 `json:"prefix_p90"`
	// GapP10/P50/P90 in seconds.
	GapP10 float64 `json:"gap_p10"`
	GapP50 float64 `json:"gap_p50"`
	GapP90 float64 `json:"gap_p90"`
	// CoverageSeconds is K*X + TTL under the policy the bands are drawn against, which is what
	// the threshold rule on the chart marks.
	CoverageSeconds float64 `json:"coverage_seconds"`
	AboveTwentyK    int64   `json:"prefix_above_20k"`
	Addressable     int64   `json:"addressable_misses"`
	Phantom         int64   `json:"phantom_ttl_rows"`
	KeepAliveCoverage
}

KeepAliveBehaviour is panels 3a–3e.

type KeepAliveCalc

type KeepAliveCalc struct {
	IdleSeconds float64 `json:"idle_seconds"`
	Prefix      int64   `json:"prefix_tokens"`
	Model       string  `json:"model"`
	// Priced false means the model has no rate on the operator's list. Then EVERY dollar field
	// is omitted and the panel says "not priced". It does NOT fall back to a blended average:
	// that is the defect class this project has hit five times.
	Priced bool `json:"priced"`
	// PingUSDEach is the cost of one ping on this prefix: prefix at the cache-READ rate plus
	// the single output token. AvoidedUSDEach is what one converted miss is worth: the
	// avoidable WRITE PREMIUM, (cache_write - cache_read) x prefix — not the whole miss.
	PingUSDEach    float64   `json:"ping_usd_each,omitempty"`
	AvoidedUSDEach float64   `json:"avoided_usd_each,omitempty"`
	Addressable    int64     `json:"addressable_misses"`
	AddressableUSD float64   `json:"addressable_usd"`
	Rows           []CalcRow `json:"rows"`
	// Plan says which policy the account runs: "wait_plan", or "fixed_k" when its keepalive_wait_plan is
	// off (#858). With "wait_plan" the ladder carries a rung of the live plan, marked current, and the
	// fixed-K rungs are the comparison. Each rung also states its own model.
	Plan string `json:"plan"`
	// Counts are the account's plan counts, present with "wait_plan", so the page can state them.
	Counts *PlanCounts `json:"plan_counts,omitempty"`
	// PrefixSource says where the prefill came from, so nobody reads a number as measured when
	// it was typed: "session", "account_median" or "given".
	PrefixSource string `json:"prefix_source,omitempty"`
	KeepAliveCoverage
}

KeepAliveCalc is the calculator's whole answer.

type KeepAliveCoverage

type KeepAliveCoverage struct {
	// RecordedFrom is MIN(ts) of any row carrying a ping or a ping-derived credit. 0 means the
	// keep-alive has never run on this account, which is not the same as having saved nothing.
	RecordedFrom int64 `json:"keepalive_recorded_from"`
	// RecordedRows is the rows at or after that instant, and Requests the rows in the window.
	// RecordedRows < Requests is the partial state.
	RecordedRows int64 `json:"keepalive_recorded_rows"`
	Requests     int64 `json:"requests"`
}

KeepAliveCoverage is the "is this figure a measurement or an absence?" statement that accompanies every number on the tab.

It exists because `keepalive_pings` and `keepalive_saved_usd` arrived as ADDITIVE columns with DEFAULT 0. On a row written before PR #86 a zero means NOT RECORDED, and rendering that as "no pings" would be a fabricated measurement — the failure this project has hit repeatedly. Three distinct states, never conflated: never ran, partially recorded, or plain figures.

type KeepAliveLedger

type KeepAliveLedger struct {
	Pings         int64   `json:"pings"`
	PingUSD       float64 `json:"ping_usd"`
	MissesAvoided int64   `json:"misses_avoided"`
	// SavedUSD is a CEILING, and every tile that shows it says so. The credit itself is exact
	// arithmetic (the accountant library's rescue) — but the provider's cache is keyed on CONTENT,
	// so another session sending a byte-identical prefix would have refreshed the same entry
	// for nothing. That confound cannot be measured from our side; it can only be declared.
	SavedUSD float64 `json:"saved_usd"`
	NetUSD   float64 `json:"net_usd"`
	// The winner/loser split over the sessions the mechanism TOUCHED. 85 of 119 lose about a
	// third of a cent service-wide, funding a large rebate on 34 — the panel states that in
	// words, unconditionally, above the fold.
	Sessions     int64  `json:"sessions_touched"`
	Winners      int64  `json:"winners"`
	Losers       int64  `json:"losers"`
	WorstSession string `json:"worst_session"`
	// WorstSessionTenant says whose WorstSession it is: two tenants can hold the same session id.
	WorstSessionTenant string  `json:"worst_session_tenant,omitempty"`
	WorstNetUSD        float64 `json:"worst_net_usd"`
	Addressable        int64   `json:"addressable_misses"`
	AddressableUSD     float64 `json:"addressable_usd"`
	// PingsThatReadNothing is the operator's check on SavedUSD: a ping that read nothing
	// refreshed nothing. PingsThatWrote is worse — it CREATED an entry, which costs 12.5x a
	// read, and the keeper stops pinging that session.
	PingsThatReadNothing int64 `json:"pings_that_read_nothing"`
	PingsThatWrote       int64 `json:"pings_that_wrote"`
	// PingsTimedOut counts ping rows booked at an estimated cost because the ping ran to its
	// timeout (#754, StopTimeoutEstimated). They are in Pings and PingUSD, and not in
	// PingsThatReadNothing: a timeout says nothing about whether the cache was read.
	PingsTimedOut int64 `json:"pings_timed_out"`
	// PingTimedOutUSD is the part of PingUSD those rows carry: the keeper's projection, not a
	// billed figure. PingUSD minus this is the measured ping spend.
	PingTimedOutUSD float64 `json:"ping_timed_out_usd"`
	// BytesPerDay is what this account's own ping rows cost on disk, measured rather than
	// assumed: 294 B of row plus ~103 B of index per ping. Here because per-session overrides
	// are the mechanism by which somebody could raise it.
	PingsPerDay float64 `json:"pings_per_day"`
	BytesPerDay float64 `json:"bytes_per_day"`
	// Latency is the window's own measured hit-vs-write speed difference for large-context
	// requests — see KeepAliveLatencyDiagnostic. Known is false (and every figure zero) on
	// a window too small to measure it, never a fabricated number.
	Latency kvcache.Latency `json:"latency"`
	// The same two halves in tokens, by tier, for a Claude subscription (#1022). Tokens is the
	// rescue: the sum of the accountant's keep-alive figure (tok_ka_*), as /api/stats
	// tokens.by_feature.keepalive. PingTokens is what the pings paid, as /api/stats
	// keepalive_ping_tokens. The two are never netted: the tiers have no common unit.
	// TokensUnmeasured counts the agent requests with no token figure (acc_priced = 0).
	Tokens           TokenFlow  `json:"tokens"`
	PingTokens       TierTokens `json:"keepalive_ping_tokens"`
	TokensUnmeasured int64      `json:"tokens_unmeasured_requests"`
	KeepAliveCoverage
}

KeepAliveLedger is panel 1 and panel 2: the verdict, and the losing majority beside it.

type KeepAliveLive

type KeepAliveLive struct {
	// Now is the server's clock at read time. On the wire so the page can count down without
	// drifting against a browser clock that may be minutes out — a countdown computed from the
	// client's own clock is how a "2 minutes left" reads on a session that expired ten ago.
	Now int64 `json:"now"`
	// IdleSeconds and MaxPings are the policy the reach figures are computed at.
	IdleSeconds float64 `json:"idle_seconds"`
	MaxPings    int     `json:"max_pings"`
	// SoonSeconds is the threshold the page warns at.
	SoonSeconds float64 `json:"soon_seconds"`
	// Soon and SoonUSD are the expiry warning: how many rows are inside SoonSeconds of lapsing
	// and what they would pay to re-create what they are about to lose. PotentialUSD is the same
	// figure over every live row.
	//
	// Summed HERE and not in the browser. The tab's rule is that the server owns every dollar on
	// the page (see renderKACalcControls: "nothing below multiplies a dollar by anything"), and
	// a total assembled client-side is a figure with no test behind it — which is how a
	// denominator came to be the twenty rows a table happened to be showing.
	Soon         int64   `json:"soon"`
	SoonUSD      float64 `json:"soon_usd"`
	PotentialUSD float64 `json:"potential_usd"`
	// SoonUnpriced counts rows inside the warning whose model has no rate, so the page can say
	// the total excludes them rather than implying it covers everything.
	SoonUnpriced int64              `json:"soon_unpriced"`
	Rows         []KeepAliveLiveRow `json:"rows"`
}

KeepAliveLive is the live-session answer: the rows, and the clock they were computed against.

type KeepAliveLiveRow

type KeepAliveLiveRow struct {
	SessionID string `json:"session_id"`
	TenantID  string `json:"tenant_id"`
	Model     string `json:"model"`
	Turns     int64  `json:"turns"`
	// LastTS is the last real request's START, which is what the provider measures the lifetime
	// from — not the end of its response. A response that streamed for four minutes has already
	// spent four minutes of its own entry's life.
	LastTS int64 `json:"last_ts"`
	// Prefix is that request's billed prefix (cache_read + cache_write): the size of the entry
	// at risk, in the provider's own units. Never tokens_before, which is message text only and
	// runs a median 3.38x low.
	Prefix int64 `json:"prefix_tokens"`
	// TTLSeconds is the lifetime IN FORCE: 1800 on OpenAI GPT-5.6+, else 3600 when this session's
	// most recent write landed in the one-hour tier, 300 otherwise. It follows the head rule
	// (keepalive.HeadLifetimeOneHour), so a mixed write counts as 1 hour. Read off cache_write_1h rather than off configuration,
	// because a `ttl: "1h"` request that the model does not support is granted as a 5-minute
	// entry with a perfectly normal 200 — the tier billed is the only honest source.
	TTLSeconds int64 `json:"ttl_seconds"`
	// RemainingSeconds is what is left of it. Rows at or below zero are not returned: the entry
	// is gone and the page would be stating a lifetime that has already elapsed.
	RemainingSeconds float64 `json:"remaining_seconds"`
	// Pings/PingUSD/SavedUSD are this session's keep-alive history in the window. Whether it is
	// armed RIGHT NOW is not here: that lives in the proxy's control plane, which the dashboard
	// does not read — the page joins the two, from /api/me/keepalive/sessions.
	Pings    int64   `json:"pings"`
	PingUSD  float64 `json:"ping_usd"`
	SavedUSD float64 `json:"saved_usd"`
	// Priced false means this model has no rate on the operator's list, and then EVERY dollar
	// below is omitted rather than defaulted. A blended rate here is the defect class this
	// project has hit five times.
	Priced bool `json:"priced"`
	// PingUSDEach is one ping on this prefix: the prefix at the model's cache-READ rate plus the
	// single output token the ping asks for. MissUSD is what letting the entry lapse costs — the
	// avoidable WRITE PREMIUM, prefix x (cache_write - cache_read), and not the whole re-read,
	// because a resuming request pays to read its prefix either way.
	PingUSDEach float64 `json:"ping_usd_each,omitempty"`
	MissUSD     float64 `json:"miss_usd,omitempty"`
	// BreakevenPings is how many pings one lapse pays for: MissUSD / PingUSDEach, floored. It is
	// THE number that decides whether to arm, and it is nearly prefix-independent — both terms
	// scale with the prefix, so it collapses to a ratio of the model's own rates.
	// BreakevenMinutes is the idle time that many pings bridges at the current policy.
	BreakevenPings   int64   `json:"breakeven_pings,omitempty"`
	BreakevenMinutes float64 `json:"breakeven_minutes,omitempty"`
	// The same pair for a ONE-HOUR entry, which is strictly a "what it would be" on a deployment
	// whose models grant 5 minutes: a 1h write costs 2.0x base against 1.25x, so a lapse is
	// dearer and pays for more pings, and each ping buys an hour instead of five minutes.
	Breakeven1hPings   int64   `json:"breakeven_1h_pings,omitempty"`
	Breakeven1hMinutes float64 `json:"breakeven_1h_minutes,omitempty"`
	// The same history as Pings/PingUSD/SavedUSD in tokens, by tier, for a Claude subscription
	// (#1048). The per-ping and per-lapse figures above are a price what-if and have no token form.
	KeepAliveSessionTokens
}

KeepAliveLiveRow is one session that may still hold a provider cache entry RIGHT NOW: which lifetime is in force on it, how long that entry has left, and what one ping and one lapse would each cost on this session's own prefix at its own model's rates.

The economics are per SESSION and never blended, for the reason the calculator refuses to average a prefix: per-ping cost is bimodal (p50 $0.0004, p99 $0.2275), so a service-wide average is a number that describes no session on the list.

type KeepAlivePlan added in v0.5.1

type KeepAlivePlan struct {
	RefreshedMS int64 // when the provider's entry was last known refreshed (epoch ms)
	NextPingMS  int64 // when the next ping fires (epoch ms)
	PingsLeft   int   // pings still to send, the next one included
	IdleMS      int64 // the spacing between pings
}

KeepAlivePlan is one thread's scheduled keep-alive, as the proxy's keeper holds it in memory.

type KeepAliveRecommendation

type KeepAliveRecommendation struct {
	// Refused is the reason, when there is one. Its presence is the branch.
	Refused string `json:"refused,omitempty"`
	// Plan says which model the interval is for: "wait_plan" (the live per-wait plan, MaxPings is its
	// base) or "fixed_k" (the account's keepalive_wait_plan is off, or the old fixed policy).
	Plan string `json:"plan"`
	// FixedK is the same window replayed under a fixed K = MaxPings, for comparison with the plan.
	// Present only for a "wait_plan" recommendation. A range, like the main one.
	FixedK *RecInterval `json:"fixed_k,omitempty"`
	// IdleSeconds and MaxPings are the recommendation. K = 1 is NEVER returned, and the reason
	// is REACH, not a loss: coverage is K*X + TTL, so one ping reaches 580 s against two pings'
	// 860 s. The "4.7 minutes / -$71 service-wide" this comment used to give is the K*X coverage
	// error CoverageSeconds exists to refuse — under correct coverage K=1 is +$101.56 in the
	// adjudicated sweep and K=2 is +$170.08, so K=2 dominates on size and not on sign.
	IdleSeconds int `json:"idle_seconds,omitempty"`
	MaxPings    int `json:"max_pings,omitempty"`
	// LoUSD/HiUSD is the 90% interval over a window like this one. A RANGE, always, and the UI
	// renders it as "$lo – $hi" and never as a hero figure.
	LoUSD float64 `json:"lo_usd,omitempty"`
	HiUSD float64 `json:"hi_usd,omitempty"`
	// N is the addressable expiries the interval rests on and Sessions how many sessions they
	// came from. Shown beside the range, because a range without its n is not honest either.
	N        int64 `json:"n"`
	Sessions int64 `json:"sessions"`
	Requests int64 `json:"requests"`
	// AltMaxPings is offered only where the account's own convertible count rises by more than
	// its bootstrap's own noise between K=2 and K=3. On the production corpus that is nobody,
	// and the panel says K=2 and K=3 are a measured tie.
	AltMaxPings int `json:"alt_max_pings,omitempty"`
	// ServiceLoUSD/ServiceHiUSD is the service-wide interval, for scale in a refusal.
	ServiceLoUSD float64 `json:"service_lo_usd,omitempty"`
	ServiceHiUSD float64 `json:"service_hi_usd,omitempty"`
	// Learned is the same forecast at the learned 5-hour weights (#1047), on a Claude subscription
	// whose fit passed the gate. nil otherwise, and on a refusal for too little data, which no weight
	// changes. The dashboard shows it in place of the API-price forecast on a subscription.
	Learned *LearnedForecast `json:"learned,omitempty"`
	KeepAliveCoverage
}

KeepAliveRecommendation is either a recommendation with its interval and its n, or a refusal with the count that caused it. Never both, and there is no point estimate on the wire AT ALL.

The missing field is deliberate and it is the whole design of this payload. Every account in the production corpus has a 90% interval whose relative half-width is at least 62%, and 5 of 12 cross zero — the account with 89 addressable expiries cannot pin its own figure closer than [+$9, +$48]. A `point_estimate` field would be rendered as a number by somebody, some day, so it does not exist.

type KeepAliveSessionRow

type KeepAliveSessionRow struct {
	SessionID string `json:"session_id"`
	TenantID  string `json:"tenant_id"`
	Turns     int64  `json:"turns"`
	Last      int64  `json:"last"`
	Model     string `json:"model"`
	// LastPrefix is the last billed prefix (cache_read + cache_write) on this session — the
	// number the calculator prefills from, because per-ping cost is bimodal and a service-wide
	// average would answer a question nobody asked.
	LastPrefix int64   `json:"last_prefix"`
	Expiries   int64   `json:"expiries"`
	ExpiryUSD  float64 `json:"expiry_usd"`
	Pings      int64   `json:"pings"`
	PingUSD    float64 `json:"ping_usd"`
	SavedUSD   float64 `json:"saved_usd"`
	NetUSD     float64 `json:"net_usd"`
	// ExpiryTokens is the token form of ExpiryUSD: the billed input tokens of the session's
	// expiries, by tier (#1048).
	ExpiryTokens TierTokens `json:"expiry_tokens"`
	KeepAliveSessionTokens
}

KeepAliveSessionRow is one row of panel 3f / panel 5: a session, what its expiries cost, and whether an override is armed on it.

type KeepAliveSessionTokens added in v0.7.3

type KeepAliveSessionTokens struct {
	KeepAliveTokens     TokenFlow  `json:"keepalive_tokens"`
	KeepAlivePingTokens TierTokens `json:"keepalive_ping_tokens"`
	TokensUnmeasured    int64      `json:"tokens_unmeasured_requests"`
}

KeepAliveSessionTokens is one session's keep-alive figures in tokens, by tier, for a Claude subscription (#1048). They are the Sessions tab's own figures (sessionTokens, #1023), so the two tabs cannot disagree about a session:

  • KeepAliveTokens is the rescue: the accountant's keep-alive figure (tok_ka_*), the token form of saved_usd. It is a different measurement from saved_usd, which is the legacy credit gated on read.
  • KeepAlivePingTokens is what the pings paid, the token form of ping_usd. It is never netted against the rescue: the view shows it on its own line.
  • TokensUnmeasured counts the session's agent requests with no token figure.

type LearnedForecast added in v0.7.3

type LearnedForecast struct {
	Refused     string  `json:"refused,omitempty"`
	IdleSeconds int     `json:"idle_seconds,omitempty"`
	MaxPings    int     `json:"max_pings,omitempty"`
	LoUSD       float64 `json:"lo_usd,omitempty"`
	HiUSD       float64 `json:"hi_usd,omitempty"`
	// Requests and Windows are what the weight fit used: the label says "from N requests".
	Requests int `json:"requests"`
	Windows  int `json:"windows"`
}

LearnedForecast is the recommendation's yes or no and range at the learned 5-hour weights: the same replay, with the saving and the ping cost each scaled by ForecastScale. Dollars at API input prices, with the token kinds weighed as the 5-hour limit weighs them.

type LifecycleReq added in v0.5.0

type LifecycleReq = reqfacts.Lifecycle

LifecycleReq is what a request body says about the wait it ended. It is built by reqfacts.ScanLifecycle, with no thread knowledge.

type LifecycleRow added in v0.5.0

type LifecycleRow struct {
	// ResultCount/ResultBytes/ResultError describe the tool_results the request answers: how
	// many, their summed text length in bytes, and whether any is flagged is_error.
	ResultCount, ResultBytes int
	ResultError              bool
	// SincePrevEndMs is the time from the previous response's END on this thread to this
	// request's START. Both are read from the PROXY clock (the end is stamped when the proxy
	// finishes relaying the response), not the provider's, so a long stream's end is when the
	// last byte reached the proxy.
	SincePrevEndMs int64
	GrantedTTL     string // 5m | 1h | mixed | "" (no cache write to read a grant from)
	PingN          int    // >0 on a keep-alive ping row: its ordinal in the idle span
}

LifecycleRow is one request_lifecycle row. SincePrevEndMs is -1 when unknown ("missing is not zero"): the first request of a thread, or the first one after a proxy restart.

type LimitWindow added in v0.7.2

type LimitWindow struct {
	// Utilization is the used share of the window: a 0..1 fraction as the header gives it, in steps of 0.01.
	Utilization *float64 `json:"utilization,omitempty"`
	// ResetS is when the window resets, in unix seconds.
	ResetS *int64 `json:"reset_s,omitempty"`
	// Status is the provider's word for the window, such as "allowed" or "rejected".
	Status string `json:"status,omitempty"`
}

LimitWindow is one subscription limit window (5 hours or 7 days), as the provider's anthropic-ratelimit-unified-* response headers gave it on one answer (#984). A nil field and an empty Status mean the header was missing or did not parse: it is left out, never read as 0.

func (LimitWindow) Empty added in v0.7.2

func (w LimitWindow) Empty() bool

Empty is true when the window has no value.

type Limits added in v0.7.2

type Limits struct {
	FiveHour LimitWindow `json:"five_hour"`
	SevenDay LimitWindow `json:"seven_day"`
}

Limits are the subscription limit values of one upstream answer. Numbers and short status words only: metadata, the same at every storage level.

func (Limits) Empty added in v0.7.2

func (l Limits) Empty() bool

Empty is true when no header gave a value.

type LiveSession added in v0.5.0

type LiveSession struct {
	Session  string `json:"session"`
	Model    string `json:"model"`
	LastTS   int64  `json:"last_ts"`
	Context  int64  `json:"context"`
	TTLMs    int64  `json:"ttl_ms"`
	TTL1h    bool   `json:"ttl_1h"`
	Messages int    `json:"messages"`
}

type ManualPings added in v0.5.3

type ManualPings struct {
	Count         int64   `json:"count"`
	PingUSD       float64 `json:"ping_usd"`
	SavedUSD      float64 `json:"saved_usd"`
	WritesAvoided int64   `json:"writes_avoided"`
}

ManualPings is the "Manual pings" savings category: pings the USER asked for with the Ping button, kept apart from the cache strategy because a person pressing a button is not the strategy's decision and must not move its net.

SavedUSD is already NET of the pings' own cost: the cache write each ping avoided on the then-current context, minus what the ping cost (negative if a ping missed and paid for a write instead). So it is the figure that joins total_saved_usd, and PingUSD is shown beside it for the reader, not to be subtracted again.

WritesAvoided is how many of the pings found the cache still warm (read it). It counts pings, not later requests: two presses in one cache lifetime both count, so the Overview shows it as an upper bound, apart from the measured count of requests.

type Meta

type Meta = reqfacts.Meta

Meta is the request's own metadata and the stop reason. The type lives in reqfacts, which reads it off a request body. dash stores it.

type ModelRate

type ModelRate struct {
	Model string `json:"model"`
	// Requests and Sessions are the weight behind this model, so a rate that applies to four
	// requests is not read as though it applied to the whole scope.
	Requests int `json:"requests"`
	Sessions int `json:"sessions"`
	// CacheWriteUSDPerToken / CacheReadUSDPerToken are the two rates, per single token.
	CacheWriteUSDPerToken float64 `json:"cache_write_usd_per_token"`
	CacheReadUSDPerToken  float64 `json:"cache_read_usd_per_token"`
	Priced                bool    `json:"priced"`
}

ModelRate is one model this scope actually ran on, with the two rates that decide what removing a declaration is worth.

It is a LIST because the answer genuinely differs per model and the page was collapsing them: the same 4,000-token declaration is worth an order of magnitude more on an expensive model than a cheap one, and an account running both has no single answer. FirstRequestUSD per token is the cache-WRITE rate (the tier a declaration enters the prompt at); the per-session figure is dominated by the cache-READ rate, because that is what every later turn of the session pays to carry it again.

type OneHourTouch added in v0.7.5

type OneHourTouch struct {
	// AtMS is when the ping started (epoch ms). The fact ends an hour after it, and holds only while the thread's
	// last touch is within oneHourSlackMS of it.
	AtMS int64
	// Proven is true when the route is proven to grant the 1-hour tier. False: the clock is a belief the
	// thread's return will test, and the clients mark it ("1h?").
	Proven bool
}

OneHourTouch is the fact (read by the keeper from the store's one record, apply.LiveOneHourPing) that a thread's last touch was a FREE 1-hour ping: the keep-alive ping asked every cache marker at 1 hour and read the prefix without writing. The entry then lives an hour from the ping, so the clock counts an hour from it, until the thread's next real request. Metadata only.

type Options

type Options struct {
	// Tap, when non-nil, is called on the writer goroutine with each event once it is stored,
	// before the live feed gets its summary copy. It must not block or keep the event after
	// it returns. It is the SOLE test seam for the in-memory fields the store does not keep
	// (the accountant Result, read through Event.AccountantResult): the database drops them
	// and the Hub's subscribe is unexported, so no other route reaches them. No production
	// code sets it.
	Tap func(*Event)
	// DBPath is the SQLite file. "" or ":memory:" keeps everything in RAM (the
	// no-persistence mode), which is also the automatic fallback when the path
	// cannot be opened — the proxy must never fail to start over a dashboard.
	DBPath string
	// Retention bounds the store by age AND size. Zero values use the defaults
	// below; a negative value disables that rule.
	RetentionAge   time.Duration
	RetentionBytes int64
	// CaptureContent enables the before/after content capture the diff view needs.
	// Opt-IN: the zero value is off, and so is --dashboard-content, because capture writes
	// arbitrary agent output to disk through a best-effort redactor. ContentCap bounds each
	// captured blob (default 16 KiB); ContentMaxPerRequest bounds how many
	// rewritten messages are captured per request (default 24).
	CaptureContent       bool
	ContentCap           int
	ContentMaxPerRequest int
	// QueueSize is the capture channel's depth (default 4096). When it is full,
	// events are DROPPED and counted rather than blocking a request.
	QueueSize int
	// BatchSize / FlushInterval control how the writer batches inserts.
	BatchSize     int
	FlushInterval time.Duration
	// PromptGrace is how long a permission-prompt mark waits for the row it interrupted to reach the
	// writer before it marks the latest stored row. Default 2s.
	PromptGrace time.Duration
	// TrustedCIDRs are the networks allowed to see per-request CONTENT and the
	// effective configuration. Loopback is always allowed. Aggregates are open to
	// everyone (a proxy people bind to 0.0.0.0 still wants its numbers visible).
	TrustedCIDRs []string
	// Mode is the proxy's operating mode ("active" | "observe"), served on /api/capture
	// so the UI can render the observe banner. Empty means active.
	//
	// There is deliberately no Preset field here: per-row preset labelling comes from
	// proxy.Options.Preset at the capture site (proxy/dashcapture.go), and a second copy
	// of the same value in a second Options struct is a copy that goes stale.
	Mode string
	// Effective is the resolved, already-structured configuration to serve at
	// /api/config. It is redacted before serving; nothing sensitive should be in
	// here in the first place.
	Effective map[string]any

	// DiskHighWatermark is the fraction of the FILESYSTEM in use at which the
	// janitor starts evicting the oldest sessions; DiskLowWatermark is where it
	// stops. 0 uses the defaults (0.90 / 0.85); a negative high watermark disables
	// the rule.
	//
	// Two watermarks, not one. With a single threshold the janitor deletes and
	// reclaims on every pass forever once the host is full — and the host is usually
	// full for reasons that have nothing to do with us, so it would grind away
	// destroying history without ever fixing anything.
	DiskHighWatermark float64
	DiskLowWatermark  float64
	// MinKeepBytes floors how far the disk rule will shrink this database. Below it
	// the janitor stops and logs: if the filesystem is full because of something
	// else, deleting our last megabyte does not help anyone and the dashboard going
	// blank hides the problem instead of showing it.
	MinKeepBytes int64
	// RetentionFloorBytes is the floor of the SIZE rule (RetentionBytes): it never makes the
	// database smaller than this, even when the database is still over its limit. 0 = a quarter
	// of RetentionBytes. It is not MinKeepBytes: that floor (1 GiB) is above the default size
	// limit (512 MiB), so it cannot serve the size rule.
	RetentionFloorBytes int64
	// DisableBackup turns off the backup copy (`<db>.bak`) the janitor makes before the age,
	// size and quota rules delete rows. The zero value keeps the backup on.
	DisableBackup bool
	// MaxRowsPerTenant caps one tenant's retained request rows. Applied BEFORE the
	// disk rule, so a heavy user is trimmed to its own quota before anyone else's
	// history is touched. 0 = no per-tenant cap.
	MaxRowsPerTenant int64

	// Remote is cold storage (Box via rclone). When set, eviction becomes MIGRATION:
	// a session is uploaded and verified before its local rows are deleted, so
	// history is bounded by the remote's capacity rather than by this disk. nil
	// keeps the old behaviour, where eviction means deletion.
	Remote Remote
	// RemoteName is the CONFIGURED cold-storage name, set by the host even when the
	// boot reachability probe failed and Remote was therefore left nil. Without it the
	// dashboard cannot tell "no cold storage on this deployment" from "cold storage is
	// configured and currently unreachable" — and it reported the first while listing
	// archived sessions. Empty falls back to Remote.Describe().
	RemoteName string
	// ArchiveContentAfter moves a session's TRANSCRIPTS to cold storage once it has
	// been idle this long. Transcripts are the overwhelming majority of the bytes and
	// are read rarely, so moving them early is what keeps the local database small
	// enough that the disk rule never fires. 0 disables.
	ArchiveContentAfter time.Duration
	// ArchiveSessionAfter moves a WHOLE session out once it has been idle this long.
	// Should be well beyond ArchiveContentAfter: metric rows are small and worth
	// keeping locally queryable for as long as anyone might browse them. 0 disables.
	ArchiveSessionAfter time.Duration
	// ArchiveInterval is how often the archiver runs. 0 = defaultArchiveInterval.
	ArchiveInterval time.Duration
	// ArchiveBatch bounds sessions moved per pass, so one catch-up cycle cannot
	// spend an hour in rclone or exhaust the remote's API quota. 0 = default.
	ArchiveBatch int
	// ArchiveRequired refuses to delete a session under disk pressure unless it was
	// successfully archived first. Safer for data, dangerous for the host: with the
	// remote down and the disk full, nothing can be reclaimed and the filesystem
	// fills, which takes down every user's agent. Default false — reclaim and say
	// loudly what was lost.
	ArchiveRequired bool
	// LifecycleSignals records the per-request lifecycle signals into request_lifecycle
	// (dash/lifecycle.go). The zero value is off, but --dashboard-lifecycle-signals defaults
	// to on: the rows hold only counts and sizes, never content.
	LifecycleSignals bool
	// Prices, when set, lets the recorder price a request it booked at $0 because the host's price
	// map had not loaded yet (issue #920). Rows this process wrote with billed tokens and no price
	// are priced once Prices knows the model. nil turns the pass off.
	Prices modelinfo.Pricer
	// RepriceInterval is how often that pass runs. 0 = defaultRepriceInterval.
	RepriceInterval time.Duration
}

Options configures the dashboard. The zero value is usable: an in-memory database, content capture on, 7-day / 512 MiB retention, loopback-only access to per-request content and effective config.

type Overview

type Overview struct {
	Since    int64 `json:"since"`
	Until    int64 `json:"until"`
	Requests int64 `json:"requests"`
	Sessions int64 `json:"sessions"`

	// InvalidConfigRequests is how many of Requests ran with NO compaction because this
	// account's stored configuration failed to build — proxy/tenancy.go's build() fails open
	// on purpose (a bad config row must never take someone's agent offline) by forwarding
	// uncompacted and marking the row's preset "invalid", but until now that marker was only
	// ever visible in the proxy's own log, never on the page an account owner or a manager
	// actually looks at. A real incident (#118 removed a config key with no migration for the
	// accounts already using it) ran for hours as nine accounts' compaction silently went to
	// zero before anyone noticed from a log line rather than from here. Nonzero here means the
	// account's Settings page needs attention now, not "check the logs".
	InvalidConfigRequests int64 `json:"invalid_config_requests"`
	// InvalidConfigRecent is the same count over the last invalidConfigRecentWindow, scoped to
	// the account but NOT to the filter's time range or any of its facets. It exists because
	// InvalidConfigRequests alone cannot answer the question the banner above the headline asks,
	// which is "is compaction broken RIGHT NOW".
	//
	// The dashboard's default view has no time filter at all, so a window-scoped count keeps
	// reporting an incident forever after it is over: this deployment carried 1,752 such requests
	// from a single afternoon (a config key removed with no migration, since fixed), and the page
	// went on telling every viewer to "open Settings and fix the configuration" for days, about a
	// configuration that was already correct. An alarm that cannot switch itself off is one people
	// learn to scroll past, which costs exactly what it was built to buy.
	//
	// Facets are deliberately ignored, not just the time range: filtering to one model must not be
	// able to hide a live breakage that happens to be showing up on another.
	InvalidConfigRecent int64 `json:"invalid_config_recent"`

	TokensBefore int64 `json:"tokens_before"`
	TokensAfter  int64 `json:"tokens_after"`
	// SavedGross re-counts the same compaction every turn the agent re-sends the
	// transcript. SavedUnique counts each distinct compaction once. SavedAdjusted
	// subtracts content we offloaded and then had to serve back.
	SavedGross     int64   `json:"saved_gross"`
	SavedUnique    int64   `json:"saved_unique"`
	SavedAdjusted  int64   `json:"saved_adjusted"`
	OvercountRatio float64 `json:"overcount_ratio"`

	// The replay, named as what it is.
	//
	// ReplayTokens is SavedGross − SavedUnique: the reductions this window RE-EARNED, because
	// a reduction frozen at turn N is still absent from the transcript on every later turn the
	// agent re-sends it. It is the same quantity OvercountRatio expresses as a multiple, and
	// it was previously presented only that way — as an "overcount", i.e. as a discount
	// against us. It is the opposite: it is where most of the realized dollar value comes
	// from (~93% on measured traffic), and it is already priced into BaselineCostUSD and into
	// every component's saved_usd, per turn, at the tier that turn actually paid.
	//
	// ReplayProjectedTokens is the ceiling: every unique reduction multiplied by the number of
	// later turns in its OWN session, i.e. what the replay would have come to had each
	// reduction survived to the end of its session. ReplayRealizedPct is the fraction of that
	// ceiling actually collected — 5.4% on production traffic. The gap is not an accounting
	// error, it is the cache-safety freeze declining to compact the cached prefix, and it is
	// the largest single piece of headroom this dashboard can point at. It had no field.
	ReplayTokens          int64   `json:"replay_tokens"`
	ReplayProjectedTokens int64   `json:"replay_projected_tokens"`
	ReplayRealizedPct     float64 `json:"replay_realized_pct"`

	AttemptedTokens int64 `json:"attempted_tokens"`
	FrozenTokens    int64 `json:"frozen_tokens"`

	// SavedGrossAttempted is SavedGross counted over ONLY the requests that recorded a nonzero
	// attempted_tokens, and AttemptedRequests is how many those are. They exist because
	// AttemptedTokens is not a total over the same population as SavedGross: it is an additive
	// column, so every row written before it shipped reads 0, and cache-aware turns that were
	// allowed to touch nothing read 0 legitimately. Summing a numerator over all rows and a
	// denominator over that subset is the same basis mismatch the "attempted" denominator was
	// already repaired for once (see denominators()) — repaired on the numerator's DEFINITION
	// and not on its row population, which left the residual these two fields close.
	SavedGrossAttempted int64 `json:"saved_gross_attempted"`
	AttemptedRequests   int64 `json:"attempted_requests"`

	FreshInput   int64 `json:"fresh_input"`
	CacheRead    int64 `json:"cache_read"`
	CacheWrite   int64 `json:"cache_write"`
	OutputTokens int64 `json:"output_tokens"`

	CostUSD         float64 `json:"cost_usd"`
	BaselineCostUSD float64 `json:"baseline_cost_usd"`
	CGLLMCostUSD    float64 `json:"cg_llm_cost_usd"`
	NetSavedUSD     float64 `json:"net_saved_usd"`
	// SummarizeCorrectionUSD is what ApplySummarizeLedger moved the baseline by: summarize's
	// counted credit less the stored one. Negative when the stored figure over-credited (a first
	// removal priced as a write, or turns past the attribution span). Zero until the API layer,
	// which holds the rates and the window resolver, has applied it.
	SummarizeCorrectionUSD float64 `json:"summarize_correction_usd"`
	// ReplayCapCorrectionUSD is what ApplyReplayLedger moved the baseline by: the credit of the
	// replaying components (extract_llm, searchfold, ...) earned after the counterfactual client
	// compaction, or after a real one, for the removals made before that close. A removal first made
	// after a close earns again until the next one (#940). Zero or negative.
	ReplayCapCorrectionUSD float64 `json:"replay_cap_correction_usd"`
	// AvoidedCompactionUSD is the price of the compaction requests the world without context-guru paid at
	// its counterfactual closes and we did not. It is not a saving on any request and no total above
	// includes it. AvoidedCompactionAssumed is true when it rests on the assumed summary size.
	AvoidedCompactionUSD     float64 `json:"avoided_compaction_usd"`
	AvoidedCompactionAssumed bool    `json:"avoided_compaction_assumed"`
	// ReplayCapNotApplied is true when the cap could not be computed (it errored or timed out), so
	// the figures above carry the stored, uncapped replay credit. The page says so.
	ReplayCapNotApplied bool `json:"replay_cap_not_applied"`
	// CacheSavedUSD is what the PROVIDER's prompt cache saved over paying the fresh rate
	// for the same tokens. Context, not credit: the agent places most of the breakpoints
	// itself. It is here because it is the number that collapses when a pipeline rewrites
	// deep history — a diagnostic, and the API keeps it for that. The dashboard does not
	// show it as a saving, because it is not ours.
	CacheSavedUSD float64 `json:"cache_saved_usd"`
	// DeferNetUSD is tool deferral's NET saving, OURS and MEASURED: the sum of the per-request
	// `defer_net_usd`: the library's one deferral figure (the definitions left out, the tier re-rate, less the
	// names list and the search turns, #1441). A request with no accountant figure books none. It is in TotalSavedUSD
	// and is its own lever, and the library's figure is not also in the baseline. 0 for an account that never deferred.
	DeferNetUSD float64 `json:"defer_net_usd"`
	// The idle keep-alive's ledger. Four numbers, and they belong together: a mechanism that
	// spends the caller's money to avoid a larger charge is only defensible if both sides are
	// on the same page, and either alone is misleading. KeepAlivePings is how many pings were
	// sent, KeepAlivePingUSD what they cost, KeepAliveSavedUSD the re-creations they avoided,
	// and KeepAliveNetUSD the difference — which is the only one of the four worth a decision.
	//
	// KeepAliveMissesAvoided is the count behind the saving: real requests that resumed after
	// an idle gap wider than the provider's lifetime and were served from cache anyway. On
	// this traffic such a request would otherwise have cost 8.5x what it did.
	KeepAlivePings         int64   `json:"keepalive_pings"`
	KeepAlivePingUSD       float64 `json:"keepalive_ping_usd"`
	KeepAliveSavedUSD      float64 `json:"keepalive_saved_usd"`
	KeepAliveNetUSD        float64 `json:"keepalive_net_usd"`
	KeepAliveMissesAvoided int64   `json:"keepalive_misses_avoided"`
	// ManualPings is the user's own pings, apart from the cache strategy's four numbers above;
	// its net is one addend of TotalSavedUSD.
	ManualPings ManualPings `json:"manual_pings"`

	// CacheWrite1h is how many written tokens the provider billed at the ONE-HOUR tier. It is
	// the verification path for the mixed-TTL head: asking for `ttl: "1h"` on a model that does
	// not support it returns a normal 200 with the tokens on the 5-minute tier, so this is the
	// only thing that distinguishes granted from silently downgraded. Zero on this deployment,
	// and expected to be — see apply/headttl.go.
	CacheWrite1h int64 `json:"cache_write_1h"`

	// The declarations the filter stopped sending, MEASURED and OURS: `requests.filtered_decl_tokens`,
	// written by the filter on every request it acted on, priced at the tier those requests paid.
	// It is in TotalSavedUSD. It was in NO total before, and that was a bug rather than a policy —
	// the savings walk is built on tokens_before, which is message text only, and a tool
	// declaration is not in `messages`, so the biggest measured lever in the product moved none of
	// it. What an account stops declaring on its own is not shown (#583, #584); see
	// dash/declcredit.go.
	DeclFilterUSD      float64 `json:"decl_filter_usd"`
	DeclFilterReads    int64   `json:"decl_filter_reads"`
	DeclFilterRequests int64   `json:"decl_filter_requests"`
	// DeclCreditPriced is false when a contributing model had no rates: the token counts above
	// stand and the dollars are the priced subset, which a consumer must not read as the total.
	DeclCreditPriced bool `json:"decl_credit_priced"`

	// TotalSavedUSD is OUR savings together: compaction's, less our own spend; the prefix
	// components'; the keep-alive's NET, which is its saving minus what its pings cost; and the
	// declaration filter's realized saving. FOUR addends, all ours, over disjoint token sets.
	//
	// The fourth one's disjointness is the only one that needs an argument, because half of what
	// it removes (a skill's listing entry) lives in `messages`, which is exactly where
	// `tokens_before` is measured. It holds because BOTH halves of the filter run in apply BEFORE
	// the request is normalized (apply/apply.go:441) and therefore before the pipeline baselines it
	// (components/pipeline.go:35), so `tokens_before` is measured on the already-filtered body and
	// the removal is invisible to Saved() rather than counted twice. The boundary is NORMALIZE, not
	// the `msgsRaw` read above it — that one exists so a later rewrite cannot move a byte offset,
	// and a filter placed between the two would still be safe for this purpose. Confirmed by
	// mutation: moving the skill half past normalize reds the apply-side guard.
	// Measured on a live run: on every request where the filter dropped 561 tokens,
	// tokens_before == tokens_after, saved_gross == 0 and baseline_cost_usd − cost_usd == 0,
	// while tokens_before itself fell by exactly the skill entry's weight.
	// TestTheDeclarationFilterSavingIsDisjointFromCompactions holds it, because "disjoint" is a
	// claim that a later reordering in apply could quietly falsify.
	//
	// The keep-alive contributes its net rather than its gross because the ping spend is excluded
	// from CostUSD — a ping is not agent traffic — so it has nowhere else in this walk to appear.
	TotalSavedUSD float64 `json:"total_saved_usd"`
	// PrefixChangeCost is a DIAGNOSTIC, not a cost subtracted from net.
	//
	// It sums cost_usd over requests whose cache missed with reason prefix_change AND whose
	// PREVIOUS request in the same session had a component that mutated the transcript. That
	// is the population where "we rewrote history and the next turn re-billed the whole
	// prompt" is a live hypothesis, and it has to be visible: size-stratified it comes to
	// roughly $24 on the current corpus, and +$39 over transcripts past 60k tokens — larger
	// than every saving on this dashboard.
	//
	// It stays observational because mutation is NOT randomly assigned. Components act where
	// there is something to act on, which are also the long, churny turns most likely to break
	// a prefix for reasons of their own; and prefix_change already loses ties to ttl_expiry, so
	// this bucket is not even a clean partition of causes. Subtracting it from net would book a
	// correlation as a debt. Settling it needs the A/B, not a bigger query.
	//
	// PrefixChangeRequests is how many turns are behind it, which was missing — a dollar
	// figure with no denominator cannot be sized. PrefixChangeCostAll / RequestsAll are the
	// UNCONDITIONAL prefix_change bucket: every turn whose cache missed on a changed prefix,
	// whether or not we had just mutated anything. That is the whole exposure of the failure
	// mode this project exists to avoid — $156.55 over 214 requests on production, against
	// $7.10 of savings on the same page — and it was buried below the fold. It belongs at the
	// same altitude as the savings, and un-netted, for exactly the reason above.
	PrefixChangeCost        float64 `json:"prefix_change_cost_usd"`
	PrefixChangeRequests    int64   `json:"prefix_change_requests"`
	PrefixChangeCostAll     float64 `json:"prefix_change_cost_all_usd"`
	PrefixChangeRequestsAll int64   `json:"prefix_change_requests_all"`

	// The response-side latency, which is where the user-visible time actually goes.
	//
	// A third of streamed responses are BUFFERED — the client sees nothing until the whole
	// response has arrived — and those wait about 21 seconds longer for a first byte. That is
	// two orders of magnitude more delay than the pipeline itself adds (154 ms), and it was
	// reported nowhere on this dashboard: it existed only as a process-lifetime gauge on
	// /stats, which cannot be filtered by model, account or hour and resets on restart.
	//
	// Both averages are kept, never blended. TTFB is 0 by construction on a buffered response
	// (there is no first byte before the whole write), so one combined average would report
	// the healthiest number for exactly the requests having the worst experience.
	// SSERecorded and CacheTTLRecorded are the COVERAGE of the two newly captured facts: how
	// many requests in the window actually carry them. Both columns default to zero/"" on
	// every row written before they existed, so without these counts a five-day history reads
	// as "0% buffered, no request uses prompt caching" — which is not a measurement, it is the
	// absence of one, and it is the single easiest way for a new column to tell a lie.
	SSERecorded      int64 `json:"sse_recorded"`
	SSEStreamRows    int64 `json:"sse_stream_rows"`
	CacheTTLRecorded int64 `json:"cache_ttl_recorded"`

	// Both averages come from the SAME ttfb_ms column but they are NOT the same measurement,
	// and that is why they are named apart rather than blended.
	//
	// On a streamed response ttfb_ms is a real time-to-first-byte. On a buffered one
	// proxy.go leaves sseFirstByte zero and msSince falls back to time.Now(), so the value is
	// the TOTAL response time — which is also, for a buffered response, the moment the client
	// receives anything at all, because nothing is written until the whole response has
	// arrived. So the figure is the right one to show; calling it a "time to first byte"
	// alongside the streamed one is what would be wrong, and the UI names it as the total.
	SSEStreamed        int64   `json:"sse_streamed"`
	SSEBuffered        int64   `json:"sse_buffered"`
	SSEBufferedPct     float64 `json:"sse_buffered_pct"`
	TTFBMsAvgStreamed  float64 `json:"ttfb_ms_avg_streamed"`
	TotalMsAvgBuffered float64 `json:"total_ms_avg_buffered"`
	// CacheTTL buckets requests by the prompt-cache lifetime tier they ASKED for:
	// ephemeral_5m, ephemeral_1h, or "" for a body that carried no cache_control. Newly
	// captured — every row written before the column exists reads "", which is why the UI
	// must distinguish "no caching asked for" from "not recorded yet" by the coverage count
	// beside it rather than by the bucket alone.
	CacheTTL map[string]int64 `json:"cache_ttl"`
	// Breakpoints is the aggregate placement of prompt-cache breakpoints BY LOCATION. Where a
	// breakpoint sits decides how much prefix it protects, so a count alone cannot answer the
	// question: system=2/tools=0/messages=0/blocks=1 and system=0/tools=0/messages=3/blocks=0
	// are both "three breakpoints" and are not remotely the same prompt. (The fifth location is
	// top-level: the one cache_control of automatic caching.) The four
	// location columns have existed since the placement work; the fifth, cache_bp_root, came with
	// #1281. They were readable only one request at a time in the drawer.
	Breakpoints BreakpointTotals `json:"breakpoints"`
	// CompactionResets is how many turns arrived SMALLER than the previous turn of the same
	// session — a context-window reset, or the agent compacting its own transcript.
	//
	// DERIVED from the requests table rather than captured, because the proxy's own counter is
	// a process-lifetime number in the metrics aggregator and this question is per-window. It
	// belongs on this page because it BOUNDS the amortization: replay accrues only while the
	// removed content keeps being re-sent, and a reset is where that stops. 1,364 of them on
	// measured traffic against a replay ceiling built by assuming none.
	CompactionResets int64 `json:"compaction_resets"`
	// EstimatorDivergence is the MEDIAN per-request ratio of provider-billed input to our own
	// tokens_before, over the requests where nothing was compacted — i.e. where the two are
	// measuring the same prompt and should agree.
	//
	// It is here because the divergence is the central honesty problem with every token figure
	// on this page, and a ratio of sums hides it. Measured on 12,882 uncompacted production
	// rows: ratio-of-sums 2.87x, but the MEDIAN per-request ratio is 3.38x (p25 2.43, p75 4.64,
	// p90 6.80). The median is the right one to show, because the question a reader has is "how
	// wrong is the number in front of me", not "how wrong is the corpus in aggregate".
	//
	// The gap is mostly SCOPE rather than tokenizer error: tokens_before is
	// schema.MessagesTokens, which counts message TEXT only — no system prompt, no tool
	// declarations, no JSON envelope — while the provider bills all of it.
	//
	// DOLLARS ARE NOT UNAFFECTED. This comment used to end "Dollars are unaffected: they come
	// from the provider's own reported usage", which is true of cost_usd and false of every
	// savings figure beside it: baseline_cost_usd is cost_usd plus a delta that prices OUR
	// token counts at the provider's rate (the accountant library's bytes-to-tokens ratio). A reader
	// auditing exactly this was told not to look, which is how #240 survived. The correction
	// factor is NOT this ratio — see tokens.BilledDeltaFactor, which is a factor on a
	// DIFFERENCE, measured against real bills, where the fixed overhead above cancels.
	//
	// This ratio is also measured on the strict COMPLEMENT of the population it would
	// invalidate: ratioPop requires tokens_before = tokens_after, i.e. rows where nothing was
	// compacted, while saved_usd is nonzero exactly where they differ. Read it as "how far off
	// is a LEVEL on this page", never as a correction for a saving.
	//
	// EstimatorDivergenceRows is the population, so a ratio over four requests is not read as a
	// fact about the deployment. Zero rows leaves the ratio at 0 and the UI shows nothing.
	EstimatorDivergence     float64 `json:"estimator_divergence"`
	EstimatorDivergenceRows int64   `json:"estimator_divergence_rows"`
	// EstimatorDivergenceCompacted is the same median ratio over the rows where compaction
	// DID remove something — the population every saved_usd figure is computed on, and the
	// one EstimatorDivergence above deliberately excludes. Published beside it so nobody
	// reads one as a correction for the other; see the note on EstimatorDivergence.
	EstimatorDivergenceCompacted     float64 `json:"estimator_divergence_compacted"`
	EstimatorDivergenceCompactedRows int64   `json:"estimator_divergence_compacted_rows"`
	// PreCorrectionSavingRows / PreCorrectionSavedUSD / CorrectedSavingRows are the #240
	// boundary: how much of the savings on this page was computed by the arithmetic BEFORE the
	// tokenizer correction (requests.billed_token_factor = 0), and how much after.
	//
	// They exist because the fix is not backfilled. Re-pricing 281k historical rows would
	// rewrite measurements nobody re-measured, so old rows keep their old figures and the UI
	// says which is which. A single "total saved" spanning the boundary is a sum of two
	// different definitions, and this is what lets the page admit that instead of hiding it.
	PreCorrectionSavingRows int64   `json:"pre_correction_saving_rows"`
	PreCorrectionSavedUSD   float64 `json:"pre_correction_saved_usd"`
	CorrectedSavingRows     int64   `json:"corrected_saving_rows"`
	// EstimatedRequests counts the requests whose saving the accountant library priced without knowing whether
	// a component broke the cache AND that the proxy held out of the books (requests.estimate_held): the first
	// request of a thread, and the first one after a restart that lost the state. It does not count a row
	// written before #915, which has price_estimated = 1 but booked its figure. Overview.Requests is the denominator.
	EstimatedRequests int64 `json:"estimated_requests"`
	// Tokens is the accountant library's figures in tokens by tier, in total and by feature (#998).
	// Every accountant-measured saving has its token form here. The read-time credits (the declaration
	// filter, the split's historical credit), defer_net_usd and the manual pings' savings do not.
	// The tiers are never added into one number.
	// TokensUnmeasuredRequests counts the agent requests in the period the library did not price
	// (acc_priced = 0: rows from before the library, and rows it could not price): they have no
	// token figure, which is not a zero saving. A held estimate (EstimatedRequests) is measured
	// and its component tokens are held out, as its dollars are. Both reads come from DB.AccTokens,
	// so the full and the lean answer agree.
	Tokens                   AccTokenStats `json:"tokens"`
	TokensUnmeasuredRequests int64         `json:"tokens_unmeasured_requests"`
	// KeepAlivePingTokens is what the cache strategy's pings paid, in billed tokens by tier (the ping
	// rows' usage), and KeepAlivePingOutputTokens their output tokens: the token form of
	// KeepAlivePingUSD. Not in Tokens. The keep-alive's net in tokens is
	// Tokens.ByFeature["keepalive"] less these.
	KeepAlivePingTokens       TierTokens `json:"keepalive_ping_tokens"`
	KeepAlivePingOutputTokens int64      `json:"keepalive_ping_output_tokens"`
	// EstimatedSavedUSD is what those requests would have saved, held OUT of every total (#915):
	// NetSavedUSD, TotalSavedUSD, the components and the keep-alive tab never include it. It is
	// what the library priced without knowing whether the cache was already warm, and that can be
	// about 2x too high. Shown beside the totals, never added to them.
	EstimatedSavedUSD float64 `json:"estimated_saved_usd"`
	// EstimatedSavedLowUSD is the floor of EstimatedSavedUSD: the same removals priced at the read rate. The
	// true held saving is between the two (#915). Shown beside the ceiling, never added to any total.
	EstimatedSavedLowUSD float64 `json:"estimated_saved_low_usd"`
	// BilledInputTokens is fresh + cache reads + cache writes: the input the PROVIDER counted.
	// It is here to be compared with TokensBefore, which is what our own tokenizer counted
	// over message text only — a different unit, roughly a third the size, and the reason no
	// token figure on this page may be read as a billed-token figure. See the tile.
	BilledInputTokens int64 `json:"billed_input_tokens"`
	// TokensBeforeBilled and BilledInputRows are the DENOMINATOR and the POPULATION for
	// BilledInputTokens, and they exist because the browser was dividing by the wrong thing.
	//
	// BilledInputTokens is fresh + cache_read + cache_write, which is identically 0 on a row
	// where the provider reported no usage. TokensBefore is our own tokenizer and is non-zero on
	// every row. So `billed_input_tokens / tokens_before` is a ratio across two populations: a
	// numerator contributed only by rows with provider usage over a denominator summed across
	// all of them. It understates the ratio by exactly the share of unmeasured rows, and it
	// printed "the provider bills LESS than we count" 0 px above a tooltip saying the opposite.
	//
	// Restricting the DENOMINATOR to the same rows makes it one population, and BilledInputRows
	// is that population's size so the ratio can state its own denominator (DESIGN §3.4).
	TokensBeforeBilled int64 `json:"tokens_before_billed"`
	BilledInputRows    int64 `json:"billed_input_rows"`

	CGLatencyMsAvg float64 `json:"cg_latency_ms_avg"`
	UpstreamMsAvg  float64 `json:"upstream_ms_avg"`
	CGLatencyMsP95 float64 `json:"cg_latency_ms_p95"`
	UpstreamMsP95  float64 `json:"upstream_ms_p95"`

	Expands      int64   `json:"expands"`
	ExpandTokens int64   `json:"expand_tokens"`
	ExpandRate   float64 `json:"expand_rate"`
	Reverts      int64   `json:"reverts"`
	Passthroughs int64   `json:"passthroughs"`

	// Accounting counts rows by token_accounting so a viewer can see how much of
	// the window is exactly measured versus estimated.
	Accounting map[string]int64 `json:"accounting"`
	// FallbackRequests counts the requests the accountant library could not price (requests.acc_fallback).
	// Counted in the share, each would move it although no priced saving changed (#1004). FallbackCostUSD is
	// their cost_usd + cg_llm_cost_usd, and FallbackSaved the saving they still booked, by part (see
	// fallback.go). The UI takes both off, so the hero and its parts describe the priced requests only, and
	// it says what it left out. Fallback is the count by reason (full read only). All are over the non-ping
	// rows the main aggregate reads.
	FallbackRequests int64            `json:"fallback_requests"`
	FallbackCostUSD  float64          `json:"fallback_cost_usd"`
	FallbackSaved    FallbackSaving   `json:"fallback_saved"`
	Fallback         map[string]int64 `json:"fallback,omitempty"`
	// CacheMiss buckets requests by attribution, cold_start included as a
	// non-failure.
	CacheMiss map[string]int64 `json:"cache_miss"`
	// Uncompressed answers "why didn't you compact this?" — an empty-string key
	// means we did.
	Uncompressed map[string]int64 `json:"uncompressed"`

	// Tiers is the bill split by the tier the provider charged on, priced at read time
	// because nothing stores per-tier cost. It carries AddressableUSD — the input side, the
	// only part of a bill an input-side transformation can ever reach. Absent (nil) when no
	// rates were available; a percentage against a bill we could not split must not be shown.
	Tiers *TierCosts `json:"tier_costs,omitempty"`

	Denominators []Denominator   `json:"denominators"`
	Waterfall    []WaterfallStep `json:"waterfall"`
	// SafetyCost reports what our own safety mechanisms cost, beside what they
	// bought. A compaction proxy that only reports tokens removed is unfalsifiable.
	SafetyCost SafetyCost `json:"safety_cost"`
}

func (*Overview) ApplyReplayLedger added in v0.5.2

func (o *Overview) ApplyReplayLedger(l *ReplayLedger)

ApplyReplayLedger corrects the headline for the capped components' credit.

func (*Overview) ApplySummarizeLedger added in v0.5.2

func (o *Overview) ApplySummarizeLedger(l *SummarizeLedger)

ApplySummarizeLedger corrects the headline for summarize's credit: the baseline carried the stored figure, so the difference moves the baseline and every total built on it.

func (*Overview) SetDeclCredit

func (o *Overview) SetDeclCredit(c *DeclCredit)

SetDeclCredit attaches the declarations-no-longer-sent credit and folds the filter's measured saving into TotalSavedUSD. Called by the API layer, which holds the rates, for the same reason SetTiers is — DB.Overview deliberately cannot price anything.

func (*Overview) SetTiers

func (o *Overview) SetTiers(t *TierCosts)

SetTiers attaches the read-time per-tier costing and the two figures that depend on it: the safety panel's benefit half, which the panel has always described in prose and never had a number for. Called by the API layer, which holds the rates — DB.Overview deliberately cannot price anything, so that a rate change never rewrites a stored row.

type Page

type Page struct {
	Requests []*Event `json:"requests"`
	// NextCursor is the `before` value for the following page; 0 = no more rows.
	NextCursor int64 `json:"next_cursor"`
	Total      int64 `json:"total"`
}

Page is one page of requests plus the cursor for the next one.

type PingState added in v0.5.4

type PingState struct {
	Pingable bool
	Reason   string
}

PingState is one thread's answer to "can a manual ping work now": Pingable, or the Reason it cannot.

type PlanCounts added in v0.6.6

type PlanCounts struct {
	ToolWaitMax     int `json:"tool_wait_max"`
	BackgroundExtra int `json:"background_extra"`
	HumanExtra      int `json:"human_extra"`
	// MaxPings is the cap on any plan count: max(base, MaxWaitPings).
	MaxPings int `json:"max_pings"`
}

PlanCounts are the counts of the per-wait plan in force: a tool wait up to ToolWaitMax pings, background work base + BackgroundExtra, a person base + HumanExtra, none above MaxPings (or the base).

type PrefixFacts added in v0.5.3

type PrefixFacts struct {
	Model        string
	DeclDigest   string // tool_declarations.digest; "" when the inventory was not read
	Tools        int
	SystemHash   string // "" when the system prompt was not read
	SystemBlocks int
	Effort       string
	Thinking     string
	Budget       int
	Bypassed     bool
	// Messages is the message count of the request. 0 means it was not read.
	Messages int
	// PromptTokens is the request's whole prompt: fresh input + cache read + cache write.
	// A token count, so metadata only. 0 means the usage block was not read.
	PromptTokens int64
	// Rewrote says context-guru shortened this request (tokens_after < tokens_before).
	Rewrote bool
	// TS is the request time in epoch ms.
	TS int64
	// RewroteEarlier is sticky: some earlier, non-bypassed request of the thread was rewritten,
	// so the provider cache holds a history that differs from the original one.
	RewroteEarlier bool
	// OneHour says the provider BILLED the WHOLE write of this request at the one-hour tier
	// (cache_write_1h >= cache_write > 0), not that the request asked for it. A mixed write (a
	// 1h head over a 5m tail) is not one-hour: its tail dies in five minutes. This is the rule
	// of keepalive ResolveTier. A request that wrote nothing
	// keeps the tier of the previous same-model request (ObservePrefix fills that in). Metadata
	// only: a token count.
	OneHour bool
	// NoWrite says the request wrote no cache, so it read an existing entry and left its tier as is.
	NoWrite bool
}

PrefixFacts is what one request tells us about its cache prefix, as hashes, counts and flags. No request body is stored. Recorder.ObservePrefix keeps the latest one per thread and compares the next request with it on a miss.

func FactsOf added in v0.5.3

func FactsOf(e *Event) PrefixFacts

FactsOf reads the prefix facts off a captured event.

type Principal

type Principal struct {
	TenantID string
	Manager  bool
}

Principal is the authenticated dashboard viewer.

type ProjectBackfill added in v0.5.4

type ProjectBackfill struct {
	// Sessions the dashboard holds with unattributed rows, and how many of them had a transcript.
	Sessions        int
	SessionsMatched int
	// Rows considered and rows a directory could be found for.
	Rows      int
	RowsFound int
	// Updated is how many rows were actually written; 0 for a dry run.
	Updated int
	// ByProject counts the rows each directory gained, so the caller can show the result before
	// committing to it.
	ByProject map[string]int
	// Unmatched names the sessions with no transcript, because "3,002 of 3,003" needs the 1
	// explained rather than rounded away.
	Unmatched []string
}

ProjectBackfill is what a back-fill would do, or did.

type ProjectGroup added in v0.5.4

type ProjectGroup struct {
	// contains filtered or unexported fields
}

ProjectGroup maps recorded folders onto projects.

func CachedProjectGroups added in v0.5.4

func CachedProjectGroups(home string) *ProjectGroup

CachedProjectGroups is ProjectGroups behind a per-home TTL cache, shared by every call site.

func ProjectGroups added in v0.5.4

func ProjectGroups(home string) *ProjectGroup

ProjectGroups reads the transcript directories under `home` and builds the mapping.

`home` overrides the home directory, for tests. An empty result is the normal state of a machine with no transcripts, and of a HOSTED proxy, which cannot see the user's disk at all — the same limit skillDescriptions documents. Project() then returns each folder unchanged, which degrades to today's behaviour rather than to an empty page.

func (*ProjectGroup) FoldersOf added in v0.5.4

func (g *ProjectGroup) FoldersOf(project string) []string

FoldersOf is every recorded folder that rolls up to the given project, including the project itself.

WHAT A PER-PROJECT QUERY HAS TO MATCH. Invocations are stored against the folder they happened in, so a query matching only the project's own path would exclude the work done in its subdirectories — and selecting a project would then show LESS than the unscoped view. Measured shape: one real project folded in 14 subfolders.

A project nothing was recorded against returns just itself, so a caller always has at least one value to match and never builds an empty IN clause.

func (*ProjectGroup) Project added in v0.5.4

func (g *ProjectGroup) Project(folder string) string

Project resolves one recorded folder to its project.

A FOLDER NO TRANSCRIPT MENTIONS STAYS ITSELF. It is not dropped and not attached to a project that never saw it: a measured row whose session has no transcript on disk still describes traffic, and attributing it elsewhere would be a guess presented as a measurement.

func (*ProjectGroup) Projects added in v0.5.4

func (g *ProjectGroup) Projects() []string

Projects is the distinct set, sorted.

type PromptPart

type PromptPart struct {
	// Title is the heading text, or "Preamble" for the text ahead of the first heading. Level
	// is the heading depth (1 for `#`, 2 for `##`, 0 for the preamble) so a UI can indent
	// rather than present a flat list of forty equal-looking sections.
	Title string `json:"title"`
	Level int    `json:"level"`
	// Tokens is this part's own measured BPE weight and Share its percentage of the parts'
	// SUM — not of the region's stored total. The two differ, by a token or two per boundary:
	// BPE is not additive across a split, so measuring the pieces and measuring the whole are
	// different measurements of the same bytes. PromptRegion.PartsTokens carries the sum so a
	// UI can show both figures instead of implying they must agree.
	Tokens int     `json:"tokens"`
	Share  float64 `json:"share"`
	Text   string  `json:"text"`
}

PromptPart is one section of the system prompt, identified and measured.

type PromptRegion

type PromptRegion struct {
	// Kind is the declaration kind, or KindSystemPrompt for the system prompt itself.
	Kind   string `json:"kind"`
	Name   string `json:"name"`
	Server string `json:"server,omitempty"`
	// Tokens is this region's measured BPE weight, and Share its percentage of the whole
	// prefix below. Both are computed from the STORED weights, so they agree with the
	// figures on the Inventory report rather than being re-derived from the text.
	Tokens int     `json:"tokens"`
	Share  float64 `json:"share"`
	// Text is the region itself, or "" when it was not stored. HasText distinguishes the
	// two, because a tool CAN legitimately have a very short declaration and "" is not
	// the same answer as "we do not have it".
	Text    string `json:"text,omitempty"`
	HasText bool   `json:"has_text"`
	// Parts decomposes the SYSTEM PROMPT region into the sections it was assembled from, so
	// "your system prompt is 12,400 tokens" becomes a list of things a reader can act on
	// separately. Empty for every other region: a tool schema is one JSON object and a skills
	// listing is one block, so neither has parts to name. See splitSystemPrompt.
	Parts []PromptPart `json:"parts,omitempty"`
	// PartsTokens is the SUM of the parts' own measured weights, which is a few tokens off
	// Tokens above and must be shown as its own figure rather than reconciled: BPE is not
	// additive across a split point, so measuring the pieces and measuring the whole are two
	// measurements of the same bytes and neither is the error.
	PartsTokens int `json:"parts_tokens,omitempty"`
}

PromptRegion is one readable slice of the prefix every request carries.

type PromptStat

type PromptStat struct {
	// Tokens is the largest system prompt any captured session in scope carried, and
	// Sessions how many recorded one at all. The MAX rather than a mean: the question is
	// "how big is the thing I would be reading", and a mean over sessions with and without
	// a prompt answers nothing.
	Tokens   int `json:"tokens"`
	Sessions int `json:"sessions"`
	// Rows / TextRows is the coverage count, the pattern cache_ttl already uses: how many
	// DECLARATIONS are in scope — one per (session, kind, name), matching how scopedDecls
	// groups them — and how many of them stored their prompt text. PromptView counts the
	// same way, deliberately: the raw table has a row per declaration-set digest too, and the
	// two figures came out 13x apart when one counted rows and the other counted declarations. A row
	// written before the column existed and a row written without content consent are both
	// absent from TextRows, so a UI can say "not recorded yet" instead of showing a
	// capability whose text looks empty. NEVER a fabricated default.
	Rows     int `json:"rows"`
	TextRows int `json:"text_rows"`
}

PromptStat is the system prompt's own place in the prefix, plus how much of the prefix this scope can actually SHOW.

It exists because the Inventory page decomposes "what every request carries" and the system prompt is normally the largest single region of it. Leaving it out made the composition a composition of the tools array only, which reads as a complete answer and is not one.

type PromptView

type PromptView struct {
	// Captured is whether any text at all is available here. When false, BlockedBy names
	// the party who can change that (CaptureBlockedByOperator / CaptureBlockedByTenant), or
	// is "" when consent is fine and the rows simply predate the column.
	Captured  bool   `json:"captured"`
	BlockedBy string `json:"blocked_by,omitempty"`
	// Session / TS / Digest identify WHICH set this is. It is one session's, not an
	// aggregate: a prompt averaged over sessions is not a prompt anybody sent, and the
	// reader has to be able to tell which one they are reading.
	Session string `json:"session,omitempty"`
	TS      int64  `json:"ts,omitempty"`
	Digest  string `json:"digest,omitempty"`
	// Regions is the prefix, heaviest first. NOT wire order: the array order a client sent
	// its tools in is not stored, and ordering by weight is what the reader wants anyway —
	// but it means the UI must not describe this as "the order the model sees them in".
	Regions []PromptRegion `json:"regions"`
	// Tokens is the summed weight of every region here — the whole that Share is a part of.
	Tokens int `json:"tokens"`
	// Rows / TextRows is the scope-wide coverage count. Present even when this view has
	// text, because "you can read this session and not the other 300" is the fact a reader
	// needs before concluding anything about their history.
	Rows     int `json:"rows"`
	TextRows int `json:"text_rows"`
}

PromptView is one session's prefix, decomposed.

type PruneOptions added in v0.7.4

type PruneOptions struct {
	// MaxAge drops rows older than this. <= 0 disables the age rule.
	MaxAge time.Duration
	// MaxBytes is the size limit. <= 0 disables the size rule.
	MaxBytes int64
	// FloorBytes is the size at which the size rule stops, even if the database is still over
	// MaxBytes. 0 = no floor. It is the size rule's own `minKeepBytes`.
	FloorBytes int64
	// ActiveWindow marks a session as active when its last request is newer than now-ActiveWindow.
	// The size rule keeps the rows of an active session unless that one session is over MaxBytes by
	// itself. <= 0 means no session is active.
	ActiveWindow time.Duration
	// BeforeDelete runs before the first delete of the age rule and before the first delete of the
	// size rule. The janitor uses it to take the backup. For the size rule, a false result
	// means "do not delete in this pass". For the age rule the result is ignored: the age rule is a
	// policy the operator set, and a failed copy must not keep rows past it.
	BeforeDelete func() bool
	// Evict, when set, deletes whole idle sessions for the size rule instead of the plain delete.
	// The janitor sets it to its archive-then-delete migration when cold storage is configured, so
	// the size rule loses no history the remote could hold. It returns how many request rows left
	// the local database. nil means a plain delete.
	Evict func([]coldCandidate) (int64, error)
	// KeepActiveRows stops the size rule from trimming rows of an over-limit active session.
	// The janitor sets it with --archive-required: that option means "never lose a row".
	KeepActiveRows bool
}

PruneOptions holds the limits of one Prune pass.

type PurgeResult

type PurgeResult struct {
	Requests   int64 `json:"requests"`
	Components int64 `json:"components"`
	Content    int64 `json:"content"`
	// Archives is index rows removed; Objects is objects deleted from cold storage.
	Archives int64 `json:"archives"`
	Objects  int64 `json:"objects"`
	// ObjectErrors names the cold-storage objects that could NOT be deleted. Their index
	// rows are deliberately left behind so a later purge retries them, which is also why
	// this is a list of paths rather than a count: an operator has to be able to go and
	// look.
	ObjectErrors []string `json:"object_errors,omitempty"`
	// SpendRows is monthly rollup rows removed.
	SpendRows int64 `json:"spend_rows"`
	// ToolDefer is tool deferral's rows removed (#485): the tenant's tool history and its per-thread
	// records and opt-outs in the session state.
	ToolDefer int64 `json:"tool_defer"`
	// SessionState is the tenant's other session-state rows removed (#1104): the metadata a hosted
	// proxy keeps so a restart does not lose a warm thread's state.
	SessionState int64 `json:"session_state"`
}

PurgeResult counts what a purge removed, so the caller can report it and so a manager pressing an irreversible button sees what it did rather than a bare "ok".

func (PurgeResult) Removed

func (p PurgeResult) Removed() bool

Removed reports whether anything at all was deleted.

type QueueStats

type QueueStats struct {
	Queued    int64 `json:"queued"`
	Pending   int64 `json:"pending"`
	Processed int64 `json:"processed"`
	Dropped   int64 `json:"dropped"`
	Errors    int64 `json:"errors"`
}

QueueStats mirrors metrics.QueueStats / modes.Stats. Declared here rather than imported because the dependency runs the other way.

type Rclone

type Rclone struct {
	// Bin is the rclone executable ("rclone" by default).
	Bin string
	// Base is the remote root, e.g. "box:context-guru". The remote name and its
	// credentials live in rclone's config, not here.
	Base string
	// ConfigPath is rclone's config file. Set it explicitly for a service: under
	// systemd, $HOME is not what an interactive shell had, and a remote rclone
	// cannot find looks exactly like a remote that is empty.
	ConfigPath string
	// Timeout bounds one transfer. 0 = DefaultRemoteTimeout.
	Timeout time.Duration
	// BWLimit is passed to --bwlimit (e.g. "8M"). Empty = unlimited. Worth setting:
	// rclone will otherwise use all the upload bandwidth it can get, and this box is
	// also serving everybody's agent traffic.
	BWLimit string
	// contains filtered or unexported fields
}

Rclone drives the rclone binary. It holds no credential: rclone's own config file owns the OAuth token, which is also what lets a token refresh happen without this process knowing anything about it.

func (*Rclone) Check

func (r *Rclone) Check(ctx context.Context) error

Check verifies the remote is usable, at startup, so a misconfigured remote is a log line on boot rather than a surprise the first time the archiver runs — by which point it would be reported as "archiving failed" with no hint that the remote was never reachable at all.

func (*Rclone) Delete

func (r *Rclone) Delete(ctx context.Context, path string) error

func (*Rclone) Describe

func (r *Rclone) Describe() string

func (*Rclone) Get

func (r *Rclone) Get(ctx context.Context, path string) ([]byte, error)

func (*Rclone) Put

func (r *Rclone) Put(ctx context.Context, path string, data []byte) error

Put streams data to an object via `rclone rcat`, which takes the body on stdin — so nothing is staged in a temporary file that a crash could leave behind.

func (*Rclone) Size

func (r *Rclone) Size(ctx context.Context, path string) (int64, error)

Size confirms an object exists and how big it is. `lsjson --stat` is the one rclone subcommand that answers "is this exact object there" without listing a directory, which matters when a tenant's archive folder has thousands of entries.

type RecInterval added in v0.6.6

type RecInterval struct {
	LoUSD float64 `json:"lo_usd"`
	HiUSD float64 `json:"hi_usd"`
}

RecInterval is a 90% range in dollars. Never a point.

type Recorder

type Recorder struct {
	// contains filtered or unexported fields
}

Recorder is the capture pipeline: a buffered channel, one writer goroutine that batches inserts, and an SSE hub the writer fans summaries out to.

The contract that matters: Record NEVER blocks and never returns an error. A full queue drops the event and increments a counter that the dashboard itself displays — an observability layer that silently lies about its own coverage is worse than one that admits a gap. This is why the dashboard cannot add request latency: the hot path does one channel send with a default branch.

func NewRecorder

func NewRecorder(opts Options) (*Recorder, error)

NewRecorder opens the store and starts the writer goroutine. It never returns a fatal error for a bad path: an unopenable database degrades to in-memory, with a warning, because the proxy's job is to proxy.

func (*Recorder) ArchiveSessionContent

func (r *Recorder) ArchiveSessionContent(ctx context.Context, c coldCandidate) (int64, error)

ArchiveSessionContent moves one session's transcripts to cold storage and deletes them locally, leaving its metric rows queryable. This is the big win on disk: content is the overwhelming majority of the bytes and is read rarely.

func (*Recorder) ArchiveSessionFull

func (r *Recorder) ArchiveSessionFull(ctx context.Context, c coldCandidate) (int64, error)

ArchiveSessionFull moves a whole session to cold storage and deletes its local rows. Used by the age rule for genuinely old sessions and by the disk-pressure rule, where it replaces outright deletion — which is the point of this whole tier: eviction becomes migration.

func (*Recorder) ArchivedBytes

func (r *Recorder) ArchivedBytes() int64

ArchivedBytes is how much is stored in cold storage, both kinds of object counted.

func (*Recorder) ArchivedSessionCount

func (r *Recorder) ArchivedSessionCount() int64

ArchivedSessionCount is how many sessions are in cold storage.

func (*Recorder) Close

func (r *Recorder) Close() error

func (*Recorder) DB

func (r *Recorder) DB() *DB

DB exposes the store for queries (read-only use by the API).

func (*Recorder) DBSizeBytes

func (r *Recorder) DBSizeBytes() int64

DBSizeBytes is the local database's size, write-ahead log included. 0 on error — a metrics endpoint must not fail because one gauge could not be read.

func (*Recorder) DiskUsedFraction

func (r *Recorder) DiskUsedFraction() (float64, bool)

DiskUsedFraction is how full the filesystem holding the database is. The second return distinguishes "0% used" from "could not measure", which matters for an alert rule: a gauge that reads zero when the probe fails would suppress the alert exactly when the box is in trouble.

func (*Recorder) FetchArchived

func (r *Recorder) FetchArchived(ctx context.Context, tenant, sessionID string) ([]*Event, error)

FetchArchived reads a session back from cold storage WITHOUT reinserting it. A read-only restore: the dashboard can show an archived session without dragging it back into the hot tier and re-triggering the eviction that put it there.

func (*Recorder) FetchArchivedContent

func (r *Recorder) FetchArchivedContent(ctx context.Context, tenant, sessionID string, requestID int64) ([]ContentRow, error)

FetchArchivedContent returns the archived transcripts for one request, for the diff view of a session whose content has moved out.

func (*Recorder) Hub

func (r *Recorder) Hub() *Hub

Hub exposes the SSE fan-out.

func (*Recorder) LifecycleOn added in v0.5.0

func (r *Recorder) LifecycleOn() bool

LifecycleOn reports whether lifecycle signals are enabled.

func (*Recorder) MarkUnique

func (r *Recorder) MarkUnique(tenant, component string, keys []string, saved int) int

MarkUnique attributes a component's savings to NEW content only, deduping by the content keys the component stashed — the same rule metrics.Aggregator uses, so the dashboard's unique figure and /stats' agree. Returns saved tokens attributable to content not seen before. tenant namespaces the seen-key set, and it must. The keys are CONTENT hashes, so two tenants working on the same repository produce the same ones — unscoped, the second tenant's genuinely new saving is silently attributed as a repeat and reported as zero. Their dashboard would show the tool doing nothing.

func (*Recorder) Observe

func (r *Recorder) Observe(tenant, session, model string, now int64) (seenSession, seenModel bool, sinceLastMs int64)

Observe records the session/model facts needed for cache attribution and returns them. Called on the request path (one map lookup under a short mutex), before Record. tenant namespaces both maps. The session id already carries its tenant (see session.Scoped), but the MODEL name does not: model ids are shared vocabulary, so unscoped, one tenant's first-ever request for a model would be attributed as a warm cache because a DIFFERENT tenant had used it. That is both wrong and a small disclosure — it tells you which models other people are running.

func (*Recorder) ObserveLifecycle added in v0.5.0

func (r *Recorder) ObserveLifecycle(tenant, session, thread string, ts, endTS int64,
	q LifecycleReq, write5m, write1h int64) *LifecycleRow

ObserveLifecycle builds the row for one request. ts is its start and endTS its response end, epoch ms on the proxy clock; write5m/write1h are the cache-write tokens by tier. Stale threads (silent longer than staleSession) are dropped by age, at most once a minute, so the cost is amortised and a busy fleet never loses a live thread's state.

func (*Recorder) ObservePrefix added in v0.5.3

func (r *Recorder) ObservePrefix(session, threadID, fromThread string, hasFrom bool, cur PrefixFacts, commit bool) (cause string, gapMs int64, known, lastWasSame bool, prevPromptTokens int64, prevOneHour bool)

ObservePrefix compares cur with the thread's previous request of the SAME model, and returns:

  • cause: one of the Cause* constants, or "" when nothing differed or there is nothing to compare with. The caller uses it only on a miss.
  • gapMs: the time since that same-model request, the figure the TTL test must use. A cache entry belongs to one model, so a request on model B in between does not refresh model A's entry. -1 means the thread has no same-model request: the entry never existed, so no TTL can have expired it.
  • lastWasSame: the thread's latest committed request ran this model, so a keep-alive ping after it refreshed this model's entry (see entryAgeMs).
  • known: false when the thread has no facts at all. The caller then keeps the gap it measured itself (a restart forgets facts but not recency).
  • prevOneHour: the billed tier of that same-model previous request's entry (PrefixFacts.OneHour). false when unknown, which keeps the five-minute lifetime.
  • prevPromptTokens: that same-model previous request's whole prompt (fresh input + cache read + cache write), 0 when there is none. AttributeCache uses it to tell a hit that covers the prompt from a partial read (#496).

A thread whose earlier requests were all on another model reads CauseModelChanged, with two exceptions that read CauseFirstOnModel (stored as cold_start). Both are a first request on this model, and not a switch the user made:

  • the request is short (1 to shortFirstMessages messages). Claude Code sends small helper requests on another model; they are not a /model switch.
  • an earlier request on this model failed. A failed request writes no cache entry, so the next success starts cold. Only a 2xx request counts as "seen" for a model.

commit says whether cur becomes the thread's new baseline. A failed request must not: its tools or effort would then stand in for the last request that really reached the cache. It must run once per request, in request order, with the key ObserveThread uses. fromThread is the thread a new thread inherits from (hasFrom says there is one); it is read only when the thread has no facts yet.

func (*Recorder) ObserveThread added in v0.5.0

func (r *Recorder) ObserveThread(tenant, session, threadID, model string, now int64) (seenSession, seenModel bool, sinceLastMs int64)

ObserveThread is Observe for one THREAD of the session (#423). Recency and the cold-start test are both per thread, because each thread has its own provider cache entry: a subagent's request must not reset the main thread's idle gap, or the main thread's expiry reads as a prefix change; and a subagent's first request is a cold start, not a prefix change. seenSession is therefore "seen this thread". The primary thread keys on the session alone, exactly as before threads existed.

func (*Recorder) ObserveThreadFrom added in v0.5.0

func (r *Recorder) ObserveThreadFrom(tenant, session, threadID, fromThread, model string, now int64) (seenSession, seenModel bool, sinceLastMs int64)

ObserveThreadFrom is ObserveThread for the first request of a thread whose content is mostly thread fromThread's (thread.Result.Inherits): a rewind, an edited earlier turn, a fork. Such a request is that conversation's next turn with a changed prefix, not a cold start, so it is observed as seen, with its gap measured from fromThread's last request. A miss on it then reads prefix_change or ttl_expiry. Once the new thread has been seen, this is ObserveThread.

func (*Recorder) Opts

func (r *Recorder) Opts() Options

Opts exposes the effective options (read-only).

func (*Recorder) PingLifecycle added in v0.5.0

func (r *Recorder) PingLifecycle(pingN int) *LifecycleRow

PingLifecycle is the row of a keep-alive ping: only its ordinal. Its thread is the requests.thread_id of the ping's own row.

func (*Recorder) PurgeTenant

func (r *Recorder) PurgeTenant(ctx context.Context, tenantID string) (PurgeResult, error)

PurgeTenant deletes everything this database and its cold storage hold for one tenant. It does NOT touch the control database — the caller owns the account row.

Partial progress is real and intentional: every step reports what it removed even when a later one fails, so a caller can log what happened and retry. Retrying is safe; every statement here is idempotent.

func (*Recorder) Record

func (r *Recorder) Record(e *Event)

Record hands an event to the writer. It is safe from any goroutine, never blocks, and never fails: a full queue drops and counts. Callers must not touch the event afterwards — the writer owns it.

func (*Recorder) RecordInventory

func (r *Recorder) RecordInventory(tenant, session string, ts int64, inv *Inventory, text bool, project string)

RecordInventory hands one request's declared/used inventory to the inventory writer. Safe on a nil Recorder and from any goroutine, never blocks, never fails: a full queue drops and counts, exactly like Record. text says whether the prompt TEXT this inventory carries may be stored. False strips it and keeps every measurement: the token weights, the names and the usage counts are identifiers and operational metrics, and an account that declined transcript capture must not lose the whole inventory feature as the price of that choice.

func (*Recorder) RecordSignal added in v0.7.4

func (r *Recorder) RecordSignal(s ClientSignal)

RecordSignal hands a client lifecycle event to the writer. It never blocks and never fails: a full queue drops the event. Safe from any goroutine.

func (*Recorder) RemoteName

func (r *Recorder) RemoteName() string

RemoteName describes the CONFIGURED cold storage, or "" when none is configured.

"Configured" is the load-bearing word, and it is the fix for a payload that lied. The host disables archiving when the boot reachability probe fails (it leaves Options.Remote nil), so this used to return "" for a deployment that is fully configured and merely unreachable — and the dashboard rendered "cold storage is not configured on this deployment" directly above two archived sessions. Options.RemoteName carries the configured name past a failed probe so the two facts stay separate; see RemoteReachable for the other half.

func (*Recorder) RemoteReachable

func (r *Recorder) RemoteReachable() bool

RemoteReachable reports whether cold storage is USABLE right now — i.e. whether the host handed us a working Remote. False with a non-empty RemoteName means "configured but unreachable", which is a transient operational fact; false with an empty name means "no cold storage on this deployment", which is a permanent one. Rendering both as the same sentence is how an archive list ended up under "not configured".

func (*Recorder) SeedGrace added in v0.6.4

func (r *Recorder) SeedGrace(refresh map[string]int64)

SeedGrace merges per-thread refresh timestamps into the grace clock by hand. For hosts and tests that know the clock exactly and want the grace seeded without the database round trip. Like the runtime paths, a timestamp only ever moves a key forward.

func (*Recorder) SeedGraceSessions added in v0.6.4

func (r *Recorder) SeedGraceSessions(now int64) (int, error)

SeedGraceSessions primes the restart grace's clock (graceSeen) from the database, the same startup recovery SeedSessions gives cache attribution (#766). One grouped query: per thread, the newest row that refreshed the provider's cache entry — a real request (keepalive = 0, whatever it read, because it wrote the entry) or a keep-alive ping that READ or WROTE the cache (keepalive = 1 AND cache_read + cache_write > 0: a read kept the entry warm, a write re-created it, #580). Only rows the upstream accepted (2xx): a failed request wrote no cache entry, and counting it would protect a prefix nothing kept warm.

Each row seeds BOTH its own key and, when it stored one, its session's ALIAS key: a request under an explicit header id refreshed the one provider entry its conversation's headerless turns read, and after a restart those turns ask for the alias key alone (their own id IS the alias), so the header id's warmth alone cannot reach them. The alias is a column because the body it was derived from is not stored — metadata only, the same kind of id session_id is. Two limits, both documented in docs/design.md: a row written before the column existed has no alias to seed, and a keep-alive ping carries no body to derive one from, so a ping refreshes only the id it ran under.

A SEPARATE map from SeedSessions' recency, and a SEPARATE query, because the two clocks answer different questions and must not re-date each other: attribution asks "when was this thread's last real request?", where a ping must never win (see SeedSessions), while the grace asks "when was its cached prefix last refreshed?", where a cache-reading ping is exactly the fact.

Rows without a session id are skipped: an observe-mode row carries none, and the empty key would say one shared entry warmed every sessionless thread.

func (*Recorder) SeedSessions

func (r *Recorder) SeedSessions(now int64) (int, error)

SeedSessions primes the session-recency map from the database, so a RESTART does not make every live conversation's next turn look like the start of a new one.

It matters because seenSession is not just a label any more: it is one of the three conditions that decide whether a cache read is credited as our saving, so a proxy restart used to hand out one bonus credit per live session — small, but exactly the kind of quiet over-claim the prefix-cache figure exists to avoid. It also fixes cache_miss_reason, which reported a cold start for every session in flight across a restart.

Three queries at startup (recency, tiers, models), bounded to sessions young enough to still matter.

func (*Recorder) SetObserveQueue

func (r *Recorder) SetObserveQueue(fn func() QueueStats)

SetObserveQueue lets the host publish its off-path pool's counters. Safe from any goroutine and safe to call on a nil Recorder.

func (*Recorder) SetTenantQuota

func (r *Recorder) SetTenantQuota(fn func(tenantID string) int64)

SetTenantQuota supplies the per-tenant row quota a manager set in the control plane. Returning 0 means "this tenant has no quota of its own", which falls back to Options.MaxRowsPerTenant. Wired by the host after the control database is open (the recorder starts first), and left nil in single-tenant mode.

func (*Recorder) Stats

func (r *Recorder) Stats() Stats

Stats snapshots the pipeline counters.

func (*Recorder) ThreadRefreshedAt added in v0.6.4

func (r *Recorder) ThreadRefreshedAt(key string) (atMs int64, ok bool)

ThreadRefreshedAt answers the restart grace's question (modes.Tracker.SetLastSeen): when was this thread's cached prefix last refreshed, as far as this recorder knows? key is the shape SeedGraceSessions and ObserveThread use — thread.Key(session, thread) — which is also the key the tracker records its turns under, so the proxy can hand this method to the tracker verbatim.

Metadata only: a timestamp per thread, no content. After a restart it comes from SeedGraceSessions' reload of the requests table; in a live process ObserveThread (real requests) and Record (cache-reading pings) keep it current. A thread this recorder has never seen reads as unknown, which the grace treats as a new thread. Pruning runs only once the map passes 20,000 entries, and only by age (two silent hours — a thread that quiet has lost its provider cache anyway); if even that frees nothing, the last resort empties the map wholesale, and every thread then reads as new until its next request refreshes it again.

func (*Recorder) ValueMetrics

func (r *Recorder) ValueMetrics(since int64) (ValueMetrics, error)

ValueMetrics rolls up the value figures since `since` (epoch ms). Read-only.

type Remote

type Remote interface {
	// Put writes an object, overwriting any existing one.
	Put(ctx context.Context, path string, data []byte) error
	// Get reads an object whole.
	Get(ctx context.Context, path string) ([]byte, error)
	// Size reports an object's size, for confirming an upload landed before the
	// local copy is deleted.
	Size(ctx context.Context, path string) (int64, error)
	// Delete removes an object. Absent is not an error.
	Delete(ctx context.Context, path string) error
	// Describe names the destination, for logs and the dashboard.
	Describe() string
}

Remote is the cold-storage backend. Small on purpose: whole objects in and out, no partial reads, no seeking — because that is all archival needs, and anything richer would invite someone to try using it as a filesystem.

type Removal

type Removal struct {
	// Kind is the mechanism class, for the UI to group and style by:
	// mcp_server | mcp_tool | builtin | skill | plugin_skill | provider | unknown.
	Kind string `json:"kind"`
	// Command is a shell command to run, or "" when the change is a config edit only.
	Command string `json:"command,omitempty"`
	// Settings is a settings.json fragment to merge, or "" when a command is enough.
	Settings string `json:"settings,omitempty"`
	// SettingsPath is where that fragment goes.
	SettingsPath string `json:"settings_path,omitempty"`
	// Effect says whether doing this actually shrinks the prompt, which is the only reason
	// this page exists. Some perfectly valid ways to block a capability save nothing.
	Effect string `json:"effect"`
	// Note carries the caveat for this specific kind. Never empty for a kind that has one.
	Note string `json:"note,omitempty"`
	// Danger marks a capability whose removal will break the agent. Built-ins only.
	Danger bool `json:"danger,omitempty"`
}

Removal is how to stop carrying one declared capability, in the form the user can act on.

func RemovalFor

func RemovalFor(kind, name, server string) Removal

RemovalFor returns how to stop carrying one declared capability.

server is the MCP server half of an mcp__ name, already split out by the caller.

type ReplayLedger added in v0.5.2

type ReplayLedger struct {
	ByComponent map[string]*ComponentLedger `json:"by_component"`
	// Conversations walked, and how many closed by each cause.
	Conversations          int64 `json:"conversations"`
	ClosedCounterfactual   int64 `json:"closed_counterfactual"`
	ClosedClientCompaction int64 `json:"closed_client_compaction"`
	WindowUnknownCovered   int64 `json:"window_unknown_conversations"`
	// CeilingFrac is, per model, C as a fraction of the window for the conversations that used the
	// BOOTSTRAP TABLE. A model with only configured conversations is absent.
	CeilingFrac map[string]float64 `json:"ceiling_frac,omitempty"`
	// CeilingConfigured is, per model, the C in billed tokens the user's own client setting, or the
	// client's own default (#948, #963), gave, for the conversations that used it. When a setting changed between conversations, it
	// holds the LAST one walked. A model absent here used only the table.
	CeilingConfigured map[string]float64 `json:"ceiling_configured,omitempty"`
	// ReopenedEpochs counts the epochs that started after a close (#940): every close of either cause.
	ReopenedEpochs int64 `json:"reopened_epochs"`
	// AvoidedCompactionUSD is the price of the compaction requests the baseline paid at its
	// counterfactual closes and we did not: C input tokens at the cache-read rate plus the summary at the
	// output rate. A separate figure: it is not a saving on any request, and no total includes it.
	AvoidedCompactionUSD float64 `json:"avoided_compaction_usd"`
	// SummaryAssumed is true when AvoidedCompactionUSD and the baseline after a close rest on the fixed
	// summary size and not on a measured one.
	SummaryAssumed bool `json:"summary_assumed"`
	// contains filtered or unexported fields
}

ReplayLedger is the ledger of every capped component, keyed by component name.

func (*ReplayLedger) DeltaUSD added in v0.5.2

func (l *ReplayLedger) DeltaUSD() float64

DeltaUSD is the total correction across components.

type RewriteCause added in v0.5.0

type RewriteCause struct {
	N      int     `json:"n"`
	Tokens int64   `json:"tokens"`
	USD    float64 `json:"usd"` // excess over a cache hit on the same tokens
	// WriteUSD is the FULL price of those writes (what the rows were billed for them), so the
	// causes partition the cache-write line instead of overlapping it.
	WriteUSD float64 `json:"write_usd"`
}

type RewriteEvent added in v0.5.0

type RewriteEvent struct {
	TS      int64   `json:"ts"`
	Session string  `json:"session"`
	Model   string  `json:"model"`
	Context int64   `json:"context"`
	GapS    int64   `json:"gap_s"` // -1 when there was no previous request
	Cause   string  `json:"cause"`
	USD     float64 `json:"usd"`
}

type SafetyCost

type SafetyCost struct {
	// FrozenTokens is content cache-aware compaction deliberately left alone. Its
	// benefit is the cache reads it preserved; its cost is compaction not done.
	//
	// FrozenReadUSD and FrozenWriteRiskUSD are that benefit, in dollars, which this panel
	// promised in prose and never computed: what the frozen prefix was billed as at the
	// cache-READ rate, and what re-creating it at the write rate instead would have added.
	// Both are absent (0 with Priced false) when no rates were available. Until now the
	// 396.5M frozen tokens on production were displayed as a cost with no counterpart at all.
	FrozenTokens       int64   `json:"frozen_tokens"`
	FrozenReadUSD      float64 `json:"frozen_read_usd"`
	FrozenWriteRiskUSD float64 `json:"frozen_write_risk_usd"`
	// Priced is false when the frozen figures could not be valued, so the UI shows "—"
	// rather than a benefit of zero for a mechanism whose benefit is simply unpriced.
	Priced bool `json:"priced"`
	// RestoredTokens is content we offloaded and the model asked back for — a
	// premature offload, paid for twice.
	RestoredTokens int64 `json:"restored_tokens"`
	// RevertedRuns is components the never-worse guard rolled back.
	RevertedRuns int64 `json:"reverted_runs"`
	// CGLLMCostUSD is what context-guru's own model calls cost.
	CGLLMCostUSD float64 `json:"cg_llm_cost_usd"`
	// CGLatencyMsTotal is the wall time context-guru itself added.
	CGLatencyMsTotal float64 `json:"cg_latency_ms_total"`
	Description      string  `json:"description"`
}

SafetyCost is the price of context-guru's own protective mechanisms.

type SaveMoreToolsDoc added in v0.6.7

type SaveMoreToolsDoc struct {
	Kind     string   `json:"kind"`
	SearchOn bool     `json:"search_on"`
	Keep     []string `json:"keep"`
	// AlwaysDefer is the account's always-defer list (#878).
	AlwaysDefer []string              `json:"always_defer"`
	Writable    bool                  `json:"writable"`
	Reason      string                `json:"reason,omitempty"`
	Window      AdaptToolsWindow      `json:"window"`
	Rows        []SaveMoreToolsRow    `json:"rows"`
	Options     []SaveMoreToolsOption `json:"options"`
	// NotYet names the actions #485 D3 lists that this proxy does not offer yet, each with the
	// issue that builds it, so a reader sees them as missing rather than absent.
	NotYet []SaveMoreToolsNotYet `json:"not_yet"`
	// Truncated is how many rows were left out past the limit (the cheapest ones).
	Truncated int `json:"truncated,omitempty"`
	// BasisID names this report; an apply sends it back with the option id.
	BasisID string `json:"basis_id,omitempty"`
}

SaveMoreToolsDoc is the GET /api/save-more/tools response.

func (*SaveMoreToolsDoc) SaveMoreToolsOffers added in v0.6.7

func (doc *SaveMoreToolsDoc) SaveMoreToolsOffers() map[string]any

SaveMoreToolsOffers is the option map an apply may name, for OfferAdapt.

type SaveMoreToolsHost added in v0.6.7

type SaveMoreToolsHost struct {
	// SearchOn is whether tool deferral is on for the account (toolfilter `defer: auto`).
	SearchOn bool
	// Keep is the account's keep list, AlwaysDefer its always-defer list (#878), Removed its
	// removal list.
	Keep, AlwaysDefer, Removed []string
	// Explain says whether Context Guru's history rule would defer name, and why. nil when the host
	// has no history (deferral never ran in this process).
	Explain func(name string) (deferred bool, reason string)
	// Writable is false when the account's configuration cannot be edited here; Reason says why.
	Writable bool
	Reason   string
}

SaveMoreToolsHost is what the host knows about one account's tool deferral.

type SaveMoreToolsNotYet added in v0.6.7

type SaveMoreToolsNotYet struct {
	Action string `json:"action"`
	Label  string `json:"label"`
	Issue  int    `json:"issue"`
}

SaveMoreToolsNotYet is one action the design lists and this proxy does not offer yet.

type SaveMoreToolsOption added in v0.6.7

type SaveMoreToolsOption struct {
	ID    string `json:"id"`
	Label string `json:"label"`
	// Action is keep | unkeep | defer | undefer | search_on | search_off; Name the row it acts on, ""
	// for the account.
	Action string `json:"action"`
	Name   string `json:"name,omitempty"`
}

SaveMoreToolsOption is one change the report offers. Apply names it by ID.

type SaveMoreToolsRow added in v0.6.7

type SaveMoreToolsRow struct {
	Kind   string `json:"kind"` // tool | mcp_server | skill
	Name   string `json:"name"`
	Server string `json:"server,omitempty"`
	State  string `json:"state"`
	Reason string `json:"reason"`
	// Builtin marks one of Claude Code's own tools.
	Builtin bool `json:"builtin,omitempty"`
	// Kept is true when the row is on the account's keep list; AlwaysDeferred when it is on the
	// always-defer list (#878).
	Kept           bool `json:"kept,omitempty"`
	AlwaysDeferred bool `json:"always_deferred,omitempty"`
	// Tokens is the weight on one request; SessionsDeclared/SessionsUsed/Calls its use.
	Tokens           int   `json:"tokens"`
	SessionsDeclared int   `json:"sessions_declared"`
	SessionsUsed     int   `json:"sessions_used"`
	Calls            int   `json:"calls"`
	LastUsedTS       int64 `json:"last_used_ts,omitempty"`
	// CarryUSD is what carrying it cost over the window, used or not; CarryPriced false when some
	// request had no known rates.
	CarryUSD    float64 `json:"carry_usd"`
	CarryPriced bool    `json:"carry_priced"`
	// Actions are the option ids an apply may name for this row (see SaveMoreToolsDoc.Options).
	Actions []string `json:"actions"`
}

SaveMoreToolsRow is one tool, MCP server or skill.

type SavingsTotals added in v0.2.0

type SavingsTotals struct {
	CostUSD         float64 `json:"cost_usd"`
	BaselineCostUSD float64 `json:"baseline_cost_usd"`
	CGLLMCostUSD    float64 `json:"cg_llm_cost_usd"`
	NetSavedUSD     float64 `json:"net_saved_usd"`

	// DeferNetUSD is tool deferral's net saving (see deferNetSum).
	DeferNetUSD float64 `json:"defer_net_usd"`

	KeepAlivePingUSD  float64 `json:"keepalive_ping_usd"`
	KeepAliveSavedUSD float64 `json:"keepalive_saved_usd"`
	KeepAliveNetUSD   float64 `json:"keepalive_net_usd"`

	// ManualPings is the user's own pings, a category of its own (see ManualPings).
	ManualPings ManualPings `json:"manual_pings"`

	TotalSavedUSD float64 `json:"total_saved_usd"`

	// CapCorrectionUSD is what the summarize and replay ledgers moved the baseline by (a
	// negative number: the credit past the cap). Zero unless SavingsTotalsCapped ran and the
	// cap found something. The figures above already include it.
	CapCorrectionUSD float64 `json:"cap_correction_usd"`
	// CapNotApplied is true when the figures above hold the stored, uncapped credit in whole or in
	// part: plain SavingsTotals never applies the cap, and SavingsTotalsCapped sets it when a ledger
	// could not run. Such a figure can be higher than the headline for the same rows (#586).
	CapNotApplied bool `json:"cap_not_applied"`
}

SavingsTotals is the cost/savings arithmetic Overview() and /stats both need — one query, one definition, so the two can never disagree about what "total saved" means. See Overview's own KeepAlive*/TotalSavedUSD fields for what each addend means; this type carries only the subset a caller asking "did this save money" needs, none of the SSE/breakpoint/prefix-change columns Overview also computes.

func (*SavingsTotals) ApplyCap added in v0.7.2

func (s *SavingsTotals) ApplyCap(c CapResult)

ApplyCap moves the totals by the cap's correction, the way ApplySummarizeLedger and ApplyReplayLedger move the headline's.

type Segmenter added in v0.5.3

type Segmenter func(r *kvcache.Request) (segment string, ok bool)

Segmenter places one request in a segment for KVCacheSuggestBy. ok=false leaves the request out of the analysis entirely.

type SelfExclusion added in v0.5.4

type SelfExclusion struct {
	Plugin  string  `json:"plugin,omitempty"`
	Items   int     `json:"items"`
	Tokens  int     `json:"tokens"`
	USD     float64 `json:"usd"`
	Command string  `json:"command,omitempty"`
}

SelfExclusion is this feature's own weight, held out of the tables and reported separately.

type SelfRemoval

type SelfRemoval struct {
	Kind   string `json:"kind"`
	Name   string `json:"name"`
	Server string `json:"server,omitempty"`
	// Tokens is what it weighed on each request that still carried it.
	Tokens int `json:"tokens"`
	// LastSeen / SessionsBefore / SessionsAfter are the evidence. SessionsAfter is how many
	// sessions ran after the last one that declared it — the claim is only as strong as that
	// number, and one session proves nothing, so the UI shows it beside every row.
	LastSeen       int64 `json:"last_seen"`
	SessionsBefore int   `json:"sessions_before"`
	SessionsAfter  int   `json:"sessions_after"`
	// AvoidedReads is Tokens x the requests in the later sessions that would have re-read it.
	AvoidedReads int64   `json:"avoided_reads"`
	AvoidedUSD   float64 `json:"avoided_usd"`
	Priced       bool    `json:"priced"`
	// Overlap is true when this name is ALSO on the account's server-side filter list, so the
	// same reduction may already be counted as a realized filter saving. Reported, not netted.
	Overlap bool `json:"overlap"`
}

SelfRemoval is a capability that STOPPED being declared partway through the window — the user acted on it.

It is detected, not credited: what an account removes on its own is not a saving context-guru made (#583, #584), so no total, tile or report shows it as one. The only reader is the savings-since-removal estimate (adaptToolsSaved), which prices the removals a user made after following a recommendation and keeps them apart from the filter's measured saving.

Overlap marks a row whose name is also on the server-side filter list, so the same tokens are never counted by both.

type ServerStat

type ServerStat struct {
	Server           string  `json:"server"`
	Tools            int     `json:"tools"`
	ToolsUsed        int     `json:"tools_used"`
	Tokens           int     `json:"tokens"`
	SessionsDeclared int     `json:"sessions_declared"`
	SessionsUsed     int     `json:"sessions_used"`
	Calls            int     `json:"calls"`
	UnusedReads      int64   `json:"unused_reads"`
	UnusedUSD        float64 `json:"unused_usd"`
	CarryReads       int64   `json:"carry_reads"`
	CarryUSD         float64 `json:"carry_usd"`
	CarryPriced      bool    `json:"carry_priced"`
	Priced           bool    `json:"priced"`
}

ServerStat rolls a whole MCP server up: an MCP server is what a user adds or removes, so it is the unit the decision is actually made in.

type SessionCostRow added in v0.5.4

type SessionCostRow struct {
	Session  string `json:"session"`
	Requests int    `json:"requests"`
	// Model is the session's first priced model, matching the rule the price follows. A session
	// that used two models is valued at the first, so the row names which one.
	Model string `json:"model,omitempty"`
	// UnusedReads is Tokens x Requests: billed tokens spent carrying it for nothing.
	UnusedReads int `json:"unused_reads"`
	// UnusedUSD prices those reads at the tiers this session actually paid. Zero with
	// Priced=false means the rate is unknown, NOT that it was free — the token count stands.
	UnusedUSD float64 `json:"unused_usd"`
	Priced    bool    `json:"priced"`
}

sessionCost is one session's re-read multiplier, split by the tier each request was billed at, plus the price of the model that billed it. SessionCostRow is what one declaration cost in one session that never invoked it.

Requests is how many times that session re-read its declarations, which is the multiplier that turns a declaration's one-request weight into what it actually cost: a 500-token skill in an eleven-request session cost 5,500 billed tokens, and the same skill in a two-request session cost 1,000. Reporting only the per-request weight hides that entirely, and it is where the money is.

type SessionDay added in v0.5.0

type SessionDay struct {
	Session string  `json:"session"`
	Day     int64   `json:"day"`
	USD     float64 `json:"usd"`
}

type SessionMoney added in v0.5.1

type SessionMoney struct {
	Main   ThreadMoney `json:"main"`
	Others ThreadMoney `json:"others"`
}

SessionMoney is a session's `saved $x of $y` split into the main thread and the sum of every other thread (sub-agents, teammates, and side requests such as Claude Code's classifier).

type SessionRow

type SessionRow struct {
	SessionID string `json:"session_id"`
	// TenantID names the account. A session id is unique per account, so under a
	// manager's service-wide scope this is what makes the list attributable — and a
	// comma-joined value is the honest answer when two accounts share an id.
	TenantID string `json:"tenant_id"`
	Turns    int64  `json:"turns"`
	Start    int64  `json:"start"`
	End      int64  `json:"end"`
	Models   string `json:"models"`
	// PrimaryModel is the single model that did the most output work in this session —
	// the model with the highest summed output_tokens for this session_id — not just
	// whichever string GROUP_CONCAT(DISTINCT ...) happened to list first. A session
	// mixes the caller's main-agent model with the client's own small/fast-model
	// housekeeping calls (e.g. title generation), and those are indistinguishable in
	// the schema except by the volume of work each one did.
	PrimaryModel    string  `json:"primary_model"`
	Providers       string  `json:"providers"`
	Agents          string  `json:"agents"`
	Presets         string  `json:"presets"`
	TokensBefore    int64   `json:"tokens_before"`
	TokensAfter     int64   `json:"tokens_after"`
	Saved           int64   `json:"saved"`
	SavedUnique     int64   `json:"saved_unique"`
	AttemptedTokens int64   `json:"attempted_tokens"`
	FrozenTokens    int64   `json:"frozen_tokens"`
	CacheRead       int64   `json:"cache_read"`
	CacheWrite      int64   `json:"cache_write"`
	OutputTokens    int64   `json:"output_tokens"`
	FreshInput      int64   `json:"fresh_input"`
	CostUSD         float64 `json:"cost_usd"`
	BaselineCostUSD float64 `json:"baseline_cost_usd"`
	CGLLMCostUSD    float64 `json:"cg_llm_cost_usd"`
	SavedUSD        float64 `json:"saved_usd"`
	Expands         int64   `json:"expands"`
	ExpandTokens    int64   `json:"expand_tokens"`
	Reverts         int64   `json:"reverts"`
	CGLatencyMs     float64 `json:"cg_latency_ms_avg"`
	UpstreamMs      float64 `json:"upstream_ms_avg"`
	Incomplete      int64   `json:"incomplete_rows"` // rows whose accounting is not `complete`
	// InFlight is true when this session's last request is still inside one provider cache
	// TTL, i.e. the next turn may well replay the same reduction and add to its value. Such a
	// session's net is an INCOMPLETE amortization, not a verdict: a young session with one
	// extraction call has paid for the call and not yet collected the replay, so it reads
	// underwater and stops reading underwater as the turns come in. The UI has to be able to
	// say so instead of rendering a half-finished number as a result.
	//
	// Derived from MAX(ts), not stored: nothing about it is a fact about the request.
	InFlight bool `json:"in_flight"`
	// The idle keep-alive's ledger for this session. The count and the cost come from a SECOND
	// grouped query with withKeepAlive — the aggregate above deliberately cannot see ping rows,
	// because a ping counted as a turn inflates Turns and drags every average on the row towards
	// a one-token response. The credit half is on the agent row that benefited, so it is summed
	// by the first query. Net is the only one of the four worth a decision, and it is the one
	// the Sessions table shows.
	KeepAlivePings    int64   `json:"keepalive_pings"`
	KeepAlivePingUSD  float64 `json:"keepalive_ping_usd"`
	KeepAliveSavedUSD float64 `json:"keepalive_saved_usd"`
	KeepAliveNetUSD   float64 `json:"keepalive_net_usd"`
	// The same session in tokens, for a Claude subscription (#1023). See sessionTokens.
	SessionTokens
}

SessionRow is one row of the session list — the view neither reference implementation has at all, despite both having sessions internally.

type SessionTokens added in v0.7.2

type SessionTokens struct {
	Tokens              TokenFlow  `json:"tokens"`
	KeepAliveTokens     TokenFlow  `json:"keepalive_tokens"`
	KeepAlivePingTokens TierTokens `json:"keepalive_ping_tokens"`
	UsedTokens          TierTokens `json:"used_tokens"`
	TokensUnmeasured    int64      `json:"tokens_unmeasured_requests"`
}

SessionTokens is one session's figures in tokens, by tier (#1023). A subscription is limited in tokens, so the Sessions tab shows these there in place of the dollars. The tiers are never added.

  • Tokens is the accountant's figure for the session, less the keep-alive rescue: the token form of saved_usd. It also has the split, the 1-hour head and the ended-change break, which the dollar row has no column for.
  • KeepAliveTokens is the accountant's own keep-alive rescue figure (the tok_ka columns). It is a different measurement from keepalive_saved_usd, which is the legacy credit gated on read (kaSavedSince): the two can disagree on a row. Tokens and KeepAliveTokens add up to the tok_total columns.
  • KeepAlivePingTokens is what the cache strategy's pings paid, in billed tokens: the token form of keepalive_ping_usd. It is never added into a cost: the view shows it on its own line.
  • UsedTokens is the session's agent requests' billed input tokens: the token form of cost_usd. context-guru's own model calls (cg_llm_cost_usd) have no token form here.
  • TokensUnmeasured counts the agent requests the library did not price (acc_priced = 0).

type SkillStat

type SkillStat struct {
	// State is ok when the listing parsed, unknown when one was present and did not, and
	// absent when no session in scope carried one. A reader must not translate unknown
	// into "no skills": see dash/toolinventory.go.
	State string `json:"state"`
	// UnknownSessions is how many sessions carried a listing this parser could not read.
	UnknownSessions int `json:"unknown_sessions"`
	// ListingTokens is the prose listing's own cost per request, averaged over the
	// sessions that carried one.
	ListingTokens int `json:"listing_tokens"`
	Declared      int `json:"declared"`
	Invoked       int `json:"invoked"`
	Calls         int `json:"calls"`
	// UnusedListingReads / UnusedListingUSD are the listing's OWN weight in the sessions
	// that invoked no skill at all: the prose is one indivisible block, so it is waste only
	// when nothing in it was used.
	UnusedListingReads int64   `json:"unused_listing_reads"`
	UnusedListingUSD   float64 `json:"unused_listing_usd"`
	// Skills is the per-skill detail, same shape as a tool.
	Skills []ToolStat `json:"skills"`
}

SkillStat is the skills half. It is reported apart from tools because skills are declared as PROSE in a role:"system" message rather than as JSON — so the inventory can be unknown, which no tools inventory can be.

type SpendDay added in v0.5.0

type SpendDay struct {
	Day        int64              `json:"day"` // local midnight, epoch ms
	Requests   int                `json:"requests"`
	USD        SpendUSD           `json:"usd"`
	RewriteUSD float64            `json:"rewrite_usd"`
	Rewrites   int                `json:"rewrites"`
	ByModel    map[string]float64 `json:"by_model"`
}

type SpendExplain added in v0.5.0

type SpendExplain struct {
	Since, Until int64                         `json:"-"`
	Window       map[string]int64              `json:"window"`
	Requests     int                           `json:"requests"`
	Priced       int                           `json:"priced_requests"`
	Unpriced     int                           `json:"unpriced_requests"`
	USD          SpendUSD                      `json:"usd"`
	StoredUSD    float64                       `json:"stored_cost_usd"` // sum of cost_usd, to reconcile against usd.total
	Rewrites     map[string]*RewriteCause      `json:"rewrites"`
	IdleGaps     []GapBand                     `json:"idle_gaps"`
	TopRewrites  []RewriteEvent                `json:"top_rewrites"`
	Models       []*SpendModel                 `json:"models"`
	Sessions     []*SpendSession               `json:"sessions"`
	Daily        []*SpendDay                   `json:"daily"`
	SessionDays  []SessionDay                  `json:"session_days"`
	Live         []LiveSession                 `json:"live"`
	Rates        map[string]map[string]float64 `json:"rates"`
	Ledger       SpendLedger                   `json:"ledger"`
}

type SpendLedger added in v0.5.0

type SpendLedger struct {
	GrossSavedUSD float64 `json:"gross_saved_usd"` // sum(baseline - cost) over non-ping rows; MODELLED, session-accumulative
	CGLLMUSD      float64 `json:"cg_llm_usd"`      // context-guru's own model calls (summariser)
	PingUSD       float64 `json:"ping_usd"`        // the keeper's pings (autoPing; a manual ping is its own category), billed to the caller
	PingSavedUSD  float64 `json:"ping_saved_usd"`  // modelled; kaSaved over the agent rows the pings inside the window kept warm
}

SpendLedger is context-guru's own books for the window, so a client can print an honest net: the modelled gross saving minus what context-guru itself spent.

type SpendModel added in v0.5.0

type SpendModel struct {
	Model      string   `json:"model"`
	Requests   int      `json:"requests"`
	USD        SpendUSD `json:"usd"`
	RewriteUSD float64  `json:"rewrite_usd"`
}

type SpendRate added in v0.5.0

type SpendRate struct {
	Input, Output, CacheRead, CacheWrite, CacheWrite1h float64 // USD per token
}

type SpendSession added in v0.5.0

type SpendSession struct {
	Session    string   `json:"session"`
	Model      string   `json:"model"` // the model that cost most in this session
	First      int64    `json:"first"`
	Last       int64    `json:"last"`
	Turns      int      `json:"turns"`
	USD        SpendUSD `json:"usd"`
	Rewrites   int      `json:"rewrites"`
	RewriteUSD float64  `json:"rewrite_usd"`
	// contains filtered or unexported fields
}

type SpendUSD added in v0.5.0

type SpendUSD struct {
	Fresh      float64 `json:"fresh"`
	CacheRead  float64 `json:"cache_read"`
	CacheWrite float64 `json:"cache_write"`
	Output     float64 `json:"output"`
	Total      float64 `json:"total"`
}

type Stats

type Stats struct {
	Captured int64 `json:"captured"`
	Written  int64 `json:"written"`
	Dropped  int64 `json:"dropped"`
	// CountsDropped is the number of bypassed requests whose token count was skipped because the
	// count worker's queue was full; their rows keep tokens_before 0.
	CountsDropped int64  `json:"counts_dropped"`
	Errors        int64  `json:"errors"`
	Queued        int    `json:"queued"`
	QueueCap      int    `json:"queue_cap"`
	Clients       int    `json:"sse_clients"`
	DBPath        string `json:"db_path"`
	DBBytes       int64  `json:"db_bytes"`
	// Mode is the proxy's operating mode ("active" | "observe"). The UI renders an
	// unmissable banner in observe mode: every request was forwarded UNTOUCHED, so a
	// reader who mistakes these figures for enforced savings has drawn exactly the wrong
	// conclusion. That is worth a banner rather than a field on a detail tab.
	Mode string `json:"mode"`
	// ObserveQueue is the off-path measurement pool's counters, supplied by the host
	// (the pool lives in `modes`, above this package). Omitted when no pool is running,
	// so a sync deployment shows no phantom queue. Its `dropped` matters most: a drop is
	// an observation given up, so the projection UNDERSTATES what compaction would save.
	ObserveQueue *QueueStats `json:"observe_queue,omitempty"`
}

Stats reports the capture pipeline's own health — including its drops, which is the number that keeps every other number honest.

type StrategyLedgerRow

type StrategyLedgerRow struct {
	TenantID string  `json:"tenant_id"`
	Pings    int64   `json:"pings"`
	PingUSD  float64 `json:"ping_usd"`
	SavedUSD float64 `json:"saved_usd"`
	NetUSD   float64 `json:"net_usd"`
}

StrategyLedgerRow is one tenant's economics under a strategy.

type StrategyLedgerView

type StrategyLedgerView struct {
	StrategyID string              `json:"strategy_id"`
	Pings      int64               `json:"pings"`
	PingUSD    float64             `json:"ping_usd"`
	SavedUSD   float64             `json:"saved_usd"`
	NetUSD     float64             `json:"net_usd"`
	Tenants    []StrategyLedgerRow `json:"tenants"`
}

StrategyLedgerView is one strategy's whole answer: the totals, and the per-tenant breakdown behind them, costliest first.

type Suggestion

type Suggestion struct {
	Kind   string `json:"kind"`
	Name   string `json:"name"`
	Server string `json:"server,omitempty"`
	// RemoveAs is the exact string to put in toolfilter's `remove` list, which is NOT always
	// Name: an MCP tool goes in as its full `mcp__server__tool` name (the whole server is
	// `mcp__server`, offered separately by the servers list) and a skill as
	// `skill__<name>`, because the two are removed by different mechanisms and a bare name
	// cannot say which is meant. See internal/skills.RemovePrefix.
	RemoveAs string `json:"remove_as"`
	// ClientOnly: the proxy filter cannot remove it (a deferred MCP tool), so RemoveAs is empty
	// and only the user's own change applies.
	ClientOnly bool `json:"client_only,omitempty"`
	// Tokens is what carrying this costs on ONE request.
	Tokens int `json:"tokens"`
	// Sessions is how many captured sessions declared it; Days is the span they cover.
	Sessions int     `json:"sessions"`
	Days     float64 `json:"days"`
	// Since is the first of those sessions, so the basis has a date and not just a count.
	Since int64 `json:"since"`
	// UnusedReads is the billed tokens already spent carrying it for nothing, and
	// ProjectedUSD their price at the tiers those requests paid. A FORECAST of what removal
	// is worth, stated as what the past would have cost without it — never a realized
	// saving, which only DeclFilterSavings reports.
	UnusedReads  int64   `json:"unused_reads"`
	ProjectedUSD float64 `json:"projected_usd"`
	Priced       bool    `json:"priced"`
	// Basis is the offer's justification in one sentence, so a reader never has to infer it
	// from the numbers beside it.
	Basis string `json:"basis"`
}

Suggestion is one declaration an account could stop carrying, with the evidence behind the offer and the forecast of what it is worth.

type SummarizeLedger added in v0.5.2

type SummarizeLedger struct {
	// FirstRemovalUSD is the counted saving on the turns that made a summary.
	FirstRemovalUSD float64 `json:"first_removal_usd"`
	// ReplayUSD is the counted saving on later turns, inside the attribution span.
	ReplayUSD float64 `json:"replay_usd"`
	// StoredUSD is what request_components.saved_usd holds for the same rows. CountedUSD less
	// StoredUSD is the correction the headline and the component table apply.
	StoredUSD float64 `json:"stored_usd"`
	// PastSpanUSD is stored credit on turns after the span ended (it closed, or the client
	// compacted). Nothing there is ours.
	PastSpanUSD float64 `json:"past_span_usd"`
	// PrefixChangeUSD is stored credit on replay turns that missed because the prompt changed.
	// Inside a span we opened the thing that changed it is us, so it is not credited.
	PrefixChangeUSD float64 `json:"prefix_change_usd"`
	Rows            int64   `json:"rows"`
}

SummarizeLedger is every summarize credit row the walk saw, sorted into what counts and what does not. It is the ONE attribution rule: the episode view reads its episodes from it and the headline and the Components tab read its totals, so none of the three has a pricing or attribution path of its own.

Rows are credit rows when summarize removed something priceable (SavedUSD != 0).

func (SummarizeLedger) CountedUSD added in v0.5.2

func (l SummarizeLedger) CountedUSD() float64

CountedUSD is what the ledger credits to summarize.

func (SummarizeLedger) DeltaUSD added in v0.5.2

func (l SummarizeLedger) DeltaUSD() float64

DeltaUSD is the correction to apply to a figure built from the stored credit.

type SurvivalPoint

type SurvivalPoint struct {
	Seconds float64 `json:"seconds"`
	Label   string  `json:"label"`
	// Arrived is how many gaps had closed by then, out of N — which is the count of requests
	// WITH a successor, repeated on every point so a reader never has to hunt for the
	// denominator.
	Arrived    int64   `json:"arrived"`
	ArrivedPct float64 `json:"arrived_pct"`
	N          int64   `json:"n"`
	// TTL marks the rungs that are a provider tier rather than an arbitrary ladder step, so the
	// chart can draw them as the thresholds they are.
	TTL string `json:"ttl,omitempty"`
}

SurvivalPoint is one rung of "has the conversation come back yet".

The survival view answers the question a TTL is chosen against, which a histogram does not: a histogram says how many gaps were four to five minutes long, and a policy needs the CUMULATIVE share still inside a horizon. Both are on the page — the histogram shows the shape, this shows the decision.

type SweepLedger added in v0.6.0

type SweepLedger struct {
	Applied              int64 `json:"applied"`
	AppliedCold          int64 `json:"applied_cold"`
	AppliedChangedPrefix int64 `json:"applied_changed_prefix"`
	// AppliedWarm and ReferencedWarm are the warm path's share (#491), part of Applied and Referenced.
	// Warm expands are in FalseExpandsWarm below (a column on the request row), so the warm false-drop
	// rate here counts references and expands, as /stats does.
	AppliedWarm    int64 `json:"applied_warm"`
	ReferencedWarm int64 `json:"referenced_later_warm"`
	// Referenced: drops a later turn used something from, without expanding.
	Referenced int64 `json:"referenced_later"`
	// Expands and ExpandTokens: every expand of a sweep marker, and what it returned.
	Expands      int64 `json:"expands"`
	ExpandTokens int64 `json:"expand_tokens"`
	// FalseExpands: drops expanded back for the first time and not already counted as referenced.
	FalseExpands int64 `json:"false_expands"`
	// FalseExpandsWarm is the part of FalseExpands whose drop was applied warm (#491). FalseDropsWarm
	// and FalseDropRateWarm count references and expands, the same as /stats.
	FalseExpandsWarm  int64   `json:"false_expands_warm"`
	FalseDropsWarm    int64   `json:"false_drops_warm"`
	FalseDropRateWarm float64 `json:"false_drop_rate_warm"`
	FalseDrops        int64   `json:"false_drops"`
	FalseDropRate     float64 `json:"false_drop_rate"`
	// ExpandChargeUSD is what the sweep's expands cost, taken off its credit.
	ExpandChargeUSD float64 `json:"expand_charge_usd"`
	// AnswerUSD is what the answers cost beyond the pings' own reads: its own column, booked once on
	// the ping row the question replaced.
	AnswerUSD float64 `json:"answer_usd"`
	// Questions is how many ping rows carry an answer cost.
	Questions int64 `json:"questions"`
	// CreditUSD is the sweep's stored saving over the window, before the expand charge. NetUSD is what L1
	// asks for: that credit, minus the expand charge, minus the answer cost, in dollars from the
	// provider's own usage (the credit is priced from each row's billed tiers, the answer from the ping
	// row's billed output). Both are filled by SweepLedgerFor so /stats-style readers need no second query.
	CreditUSD float64 `json:"credit_usd"`
	NetUSD    float64 `json:"net_usd"`
	// Cold-apply request cache usage (C2): over requests where the sweep applied on a cold request, the
	// cache read, cache write and fresh input the provider billed. A cold request should read the same
	// cached part as with the sweep off (the system prompt and tools) and write the smaller prefix; the
	// NEXT warm request should read the whole new prefix. ColdReadTokens/ColdWriteTokens are the first,
	// NextWarmReadTokens the second (the first warm request after each such cold request, same thread).
	ColdApplyRequests   int64 `json:"cold_apply_requests"`
	ColdReadTokens      int64 `json:"cold_apply_cache_read"`
	ColdWriteTokens     int64 `json:"cold_apply_cache_write"`
	NextWarmRequests    int64 `json:"next_warm_requests"`
	NextWarmReadTokens  int64 `json:"next_warm_cache_read"`
	NextWarmWriteTokens int64 `json:"next_warm_cache_write"`
	// Threads: the busiest threads by drops applied, at most 20. Labels are hashes.
	Threads []SweepThread `json:"threads,omitempty"`
}

SweepLedger is the sweep's quality and money over a filtered window.

type SweepThread added in v0.6.0

type SweepThread struct {
	Thread        string  `json:"thread"`
	Applied       int64   `json:"applied"`
	FalseDrops    int64   `json:"false_drops"`
	FalseDropRate float64 `json:"false_drop_rate"`
}

SweepThread is one thread's quality under a label that is not the session id.

type SystemPrompt

type SystemPrompt struct {
	// Hash identifies the text, and is what the writer dedups on. Not a cryptographic
	// digest and not treated as one: it exists to answer "is this the text we already
	// stored for this session".
	Hash string
	// Tokens is the whole prompt's BPE cost, measured, not estimated.
	Tokens int
	// Text is the unescaped prompt. Content, and gated on consent by the writer — see
	// Decl.Text for why the gate is not applied on this side.
	Text string
}

SystemPrompt is the top-level system prompt one request carried.

It is here rather than in the request row for the same reason the declarations are: it is constant for a whole session and a per-request copy would be ~65 identical multi-kilobyte blobs saying the same thing. It is measured even when its TEXT may not be stored, because "your system prompt is 12,400 tokens" is an operational figure about the caller's own configuration, and the composition of the prompt is unreadable without it — a page that shows tool weights and omits the largest single region of the prefix is not showing the composition of anything.

type TenantMetricRow

type TenantMetricRow struct {
	TenantID      string
	Label         string
	Requests      int64
	TokensBefore  int64
	TokensAfter   int64
	SavedUnique   int64
	CacheRead     int64
	CacheWrite    int64
	FreshInput    int64
	OutputTokens  int64
	CostUSD       float64
	BaselineUSD   float64
	CGLLMCostUSD  float64
	CacheSavedUSD float64
	// KeepAliveNetUSD is this tenant's keep-alive credit minus its ping spend. Filled by the
	// host via DB.KeepAliveNetUSDByTenant, alongside the other per-tenant figures below that
	// need a second query — kept out of TenantMetrics' own query so that one stays untouched.
	KeepAliveNetUSD float64
	// DeclFilterUSD is this tenant's declaration-filter saving, valued on read
	// (DB.DeclFilterSavingsByTenant) — needs a pricer, so
	// TenantMetrics itself cannot fill it.
	DeclFilterUSD float64
	CGLatencyMs   float64
	UpstreamMs    float64
	Sessions      int64
	ArchivedCount int64
	ArchivedBytes int64
}

TenantMetricRow mirrors proxy.TenantMetricRow. Duplicated rather than imported because dash must not depend on proxy (proxy depends on dash), and a shared types package for one struct would be more indirection than the copy costs.

type ThreadCache added in v0.5.0

type ThreadCache struct {
	ID         string `json:"id"`
	Main       bool   `json:"main"`
	Model      string `json:"model"`
	LastTS     int64  `json:"last_ts"`
	EndTS      int64  `json:"end_ts"`
	TTLSeconds int64  `json:"ttl_s"`

	// TTLUnproven: see CacheState.
	TTLUnproven  bool    `json:"ttl_unproven,omitempty"`
	FreeHourPing bool    `json:"free_hour_ping,omitempty"` // see CacheState
	PrefixTokens int64   `json:"prefix_tokens"`
	RewriteUSD   float64 `json:"rewrite_usd"`
	Priced       bool    `json:"priced"`
	// NextWarmUSD and NextColdUSD: see CacheState.
	NextWarmUSD *float64 `json:"next_warm_usd,omitempty"`
	NextColdUSD *float64 `json:"next_cold_usd,omitempty"`
	// Pingable and PingReason: see CacheState.
	Pingable   *bool  `json:"pingable,omitempty"`
	PingReason string `json:"ping_reason,omitempty"`
	// PingsLeft is how many keep-alive pings the proxy still plans for this thread, and
	// HeldUntilMS when its cache goes cold if no real request arrives first: the last planned
	// ping's start plus the TTL. Both omitted when no ping is planned.
	PingsLeft   int   `json:"pings_left,omitempty"`
	HeldUntilMS int64 `json:"held_until_ms,omitempty"`
	// NextPingMS is when the next planned ping fires (epoch ms), omitted when none is planned.
	NextPingMS int64 `json:"next_ping_ms,omitempty"`
	// SavedUSD and BaselineUSD are this thread's `saved $x of $y` (see threadMoney).
	SavedUSD    float64 `json:"saved_usd"`
	BaselineUSD float64 `json:"baseline_usd"`
	// contains filtered or unexported fields
}

ThreadCache is one thread's cache entry. Main is the session's primary thread.

type ThreadMoney added in v0.5.1

type ThreadMoney struct {
	SavedUSD    float64 `json:"saved_usd"`
	BaselineUSD float64 `json:"baseline_usd"`
	Threads     int     `json:"threads"`
}

ThreadMoney is `saved $x of $y` for one or more threads; see threadMoney. Threads counts them.

type TierCosts

type TierCosts struct {
	FreshUSD      float64 `json:"fresh_usd"`
	CacheReadUSD  float64 `json:"cache_read_usd"`
	CacheWriteUSD float64 `json:"cache_write_usd"`
	OutputUSD     float64 `json:"output_usd"`
	// AddressableUSD is the INPUT side — fresh + cache read + cache write. It is the only
	// part of the bill a context transformation can act on, and so the only denominator a
	// compaction saving may honestly be expressed as a percentage of. Output tokens are the
	// model's own generation; removing transcript content does not shorten them.
	AddressableUSD float64 `json:"addressable_usd"`
	// TotalUSD is all four tiers at today's rates. StoredUSD is SUM(cost_usd) over the same
	// rows, priced when each request was served. They are shown together on purpose: the gap
	// between them is rate drift over the window, and a split that silently disagreed with
	// the billed total would be worse than no split at all.
	TotalUSD  float64 `json:"total_usd"`
	StoredUSD float64 `json:"stored_usd"`
	// FrozenReadUSD prices the tokens cache-aware compaction deliberately left alone at the
	// cache-READ rate they were actually billed at — per row, min(frozen_tokens, cache_read).
	// The clamp is load-bearing, not defensive: the frozen count is what compaction DECLINED to
	// touch and cache_read is what the provider actually served from cache, and the first is not
	// bounded by the second. On 4.0% of the rows that recorded a freeze (3,004 of 75,185) the
	// frozen count EXCEEDS that request's cache_read, by 73.2M tokens in total; those tokens were
	// billed fresh or written, so pricing them at the read rate prices a tier they were never
	// charged at. Clamped rather than dropped, which is the conservative direction this file
	// already errs in. This is the benefit half of SafetyCost, which the panel has always
	// promised ("its benefit is the cache reads it preserved") and never computed.
	// FrozenWriteRiskUSD is what re-creating that same prefix instead would have ADDED — the
	// spread between the write and read rates, i.e. what the freeze bought. It is built from the
	// same clamped count, so it inherits the clamp rather than the error.
	FrozenReadUSD      float64 `json:"frozen_read_usd"`
	FrozenWriteRiskUSD float64 `json:"frozen_write_risk_usd"`
	// Requests is how many priced requests are behind these figures; Uncovered is how many
	// were left out because their model has no rate or their accounting was incomplete.
	Requests  int64 `json:"requests"`
	Uncovered int64 `json:"uncovered_requests"`
}

TierCosts is the filtered window's bill split into the four tiers the provider charges on, priced on read. Absent (nil) rather than zeroed when no rates are available.

type TierPrice added in v0.7.3

type TierPrice [fhTiers]float64

TierPrice is one model's API price per token, by fit tier.

type TierTokens added in v0.7.2

type TierTokens struct {
	Input        int64 `json:"input"`
	CacheRead    int64 `json:"cache_read"`
	CacheWrite5m int64 `json:"cache_write_5m"`
	CacheWrite1h int64 `json:"cache_write_1h"`
}

TierTokens is a token count by billing tier: accountant.TierTokens with JSON names.

type TimelineBucket added in v0.5.4

type TimelineBucket int64

TimelineBucket is one day, by the epoch-ms of its start.

type TimelineItem added in v0.5.4

type TimelineItem struct {
	// Calls is invocations that fell in each bucket.
	Calls []int `json:"calls"`
	// Carried is how many requests in each bucket carried the declaration. The baseline the calls
	// are drawn against: where it runs on and the calls stop, the difference is the waste.
	Carried []int `json:"carried"`
	// FirstUsed / LastUsed bound the invocations, for a label that does not need the series read.
	FirstUsed int64 `json:"first_used_ts,omitempty"`
	LastUsed  int64 `json:"last_used_ts,omitempty"`
}

TimelineItem is one capability's two series, aligned to the shared bucket list: Calls[i] and Carried[i] describe the same day. Aligned here rather than left to the page, because joining two differently-bucketed series is the one job this endpoint exists to do.

type TokenFlow added in v0.7.2

type TokenFlow struct {
	Saved  TierTokens `json:"saved"`
	Caused TierTokens `json:"caused"`
}

TokenFlow is a figure in tokens: what it saved and what it caused, each by tier. Its dollar value is the library's figure for the same tokens (Saved minus Caused, each at its rate).

type ToolCoverage

type ToolCoverage struct {
	Sessions int `json:"sessions"`
	// Captured / NotCaptured: sessions with an inventory, and sessions whose requests
	// predate this capture (or were dropped). NotCaptured sessions contribute NOTHING to
	// any figure above — they are not counted as fully-used and not as fully-wasted.
	Captured    int `json:"captured"`
	NotCaptured int `json:"not_captured"`
	// UnpricedSessions carried an inventory but a model with no known rates, so their
	// tokens are in UnusedReads and their dollars are in nobody's total.
	UnpricedSessions int `json:"unpriced_sessions"`
	Requests         int `json:"requests"`
}

ToolCoverage is the honesty half of the report: which sessions in scope can answer the question at all.

type ToolDeferDay added in v0.6.7

type ToolDeferDay struct {
	// Day is the UTC midnight of the day, epoch ms.
	Day    int64  `json:"day"`
	Tenant string `json:"tenant"`
	// Requests is how many requests deferral changed.
	Requests int64 `json:"requests"`
	// TokensDeferred is the deferred definitions' weight summed over those requests: what they did
	// not carry. Our tokenizer's units, before the billed-token correction the dollars carry.
	TokensDeferred int64 `json:"tokens_deferred"`
	ListTokens     int64 `json:"list_tokens"`
	Searches       int64 `json:"searches"`
	// DroppedSearches is the searches with no result (#866 N8): the model searched again.
	DroppedSearches int64 `json:"dropped_searches"`
	// Loaded is the tools the searches loaded; WrongGuesses the part of them deferral had
	// deferred and no earlier search in the thread had loaded.
	Loaded       int64   `json:"loaded"`
	WrongGuesses int64   `json:"wrong_guesses"`
	GrossUSD     float64 `json:"gross_usd"`
	NetUSD       float64 `json:"net_usd"`
	// CostUSD is gross less net: the names list and the search turns. It is read from the request row.
	CostUSD float64 `json:"cost_usd"`
	// Unpriced is the changed requests with no accountant figure (no price, a held estimate, no result): their dollars read 0, not free.
	Unpriced int64 `json:"unpriced_requests"`
}

ToolDeferDay is one account's deferral on one UTC day.

type ToolDeferReport added in v0.6.7

type ToolDeferReport struct {
	Days  []ToolDeferDay `json:"days"`
	Total ToolDeferDay   `json:"total"`
}

ToolDeferReport is the /api/tool-defer response: the days, newest first, and their total.

type ToolFilterDoc

type ToolFilterDoc struct {
	// Enabled reports whether the removal list can be changed through this API. False is a
	// working state, not an error: the analysis below is still served, and Reason says why
	// the control is unavailable.
	Enabled bool   `json:"enabled"`
	Reason  string `json:"reason,omitempty"`
	// Excluded is what the account has opted out of. Never nil, so a consumer can count it
	// without a guard.
	Excluded []ExcludedDecl `json:"excluded"`
	// Realized is what the filter actually avoided, at the tier actually billed. OMITTED —
	// not zeroed — when nothing has been measured, so an absent figure reads as "nothing
	// realized" and can never be confused with the projection below.
	Realized *DeclFilterSaving `json:"realized,omitempty"`
	// Suggestions are candidates that pass the sufficiency rule, heaviest first. PROJECTIONS.
	Suggestions []Suggestion `json:"suggestions"`
	// MinSessions / MinDays are the sufficiency thresholds these suggestions were held to,
	// returned so the page can state them and so a reader can tell a changed threshold from
	// a changed corpus.
	MinSessions int     `json:"min_sessions"`
	MinDays     float64 `json:"min_days"`
	// Coverage is the inventory report's own honesty block, carried through unchanged: how
	// many sessions in scope could answer the question at all.
	Coverage ToolCoverage `json:"coverage"`
	// Withheld is how many never-used items did NOT reach the bar. Reported because a short
	// list of suggestions has two very different causes — nothing is wasted, or nothing is
	// yet known — and silence cannot distinguish them.
	Withheld int `json:"withheld"`
}

ToolFilterDoc is the whole opt-in surface for one scope: what is currently excluded, what excluding it has ACTUALLY saved, and what is safe to offer next.

Realized and Suggestions are separate fields and never merged, because they answer different questions and only one of them is a fact. See the file comment.

type ToolFilterState

type ToolFilterState struct {
	// Enabled is false when there is nothing for a switch to write to — no per-account
	// configuration on this deployment, a stored document that does not load, or toolfilter
	// absent from the effective pipeline. A consumer states Reason once and shows the
	// analysis without the control.
	Enabled bool
	Removed []string
	Reason  string
}

ToolFilterState is the caller's removal configuration, supplied by the host: dash holds no tenant configuration of its own, and inventing one here would be a second source of truth for what the proxy is actually sending.

type ToolReport

type ToolReport struct {
	Coverage ToolCoverage `json:"coverage"`
	Totals   ToolTotals   `json:"totals"`
	// Tools is the CONTROLLABLE set: MCP tools. Skills are the other half and are in Skills.
	//
	// It used to be every client-side declaration, which put Claude Code's own tools at the top
	// of a page whose whole purpose is to recommend removals. They are not a candidate for
	// removal, they are the largest group by weight, and they therefore dominated the headline,
	// the composition, the totals and the sortable table with a number no reader should act on.
	// They are in Aside instead.
	Tools   []ToolStat   `json:"tools"`
	Servers []ServerStat `json:"servers"`
	Skills  SkillStat    `json:"skills"`
	// DeferredState is "unknown" when a session in scope carried a deferred tools list this scan
	// did not read, so the MCP tools above may be missing deferred ones. Empty otherwise. A reader
	// must not translate unknown into "no deferred tools".
	DeferredState           string `json:"deferred_state,omitempty"`
	DeferredUnknownSessions int    `json:"deferred_unknown_sessions,omitempty"`
	// Aside is everything declared that is NOT the reader's to remove, in the same row shape:
	// Claude Code's own tools (Builtin true), a third-party agent's or SDK application's client
	// tools, and the provider's server-side tools.
	//
	// It is REPORTED and it is not in any figure in Totals. Both halves of that matter. Hiding
	// it would be a lie about what the prompt contains — it is the majority of it — and folding
	// it into the totals was the older lie, that a reader could act on the majority of it.
	// The three sub-groups are told apart by Builtin and Kind, not by their position here,
	// because the page shows them under different warnings: the built-ins break the agent, an
	// unknown client tool needs its declarer identified first, a provider tool cannot be
	// touched from Claude Code at all.
	Aside []ToolStat `json:"aside"`
	// Models is every model this scope ran on, with its cache-write and cache-read rates, so
	// "what would removing this save me" can be answered per model instead of at one blended
	// rate that describes none of them.
	Models []ModelRate `json:"models"`
	// Prompt is the system prompt's weight and how much of the prefix can be shown as text.
	Prompt PromptStat `json:"prompt"`
	// Carried is how the unused figures were priced: requests matched to the declaration set they
	// carried, by recorded digest or by tool count, and how many of those matches were ambiguous.
	Carried *AdaptToolsCoverage `json:"carried,omitempty"`
}

ToolReport is the whole answer for one scope.

type ToolStat

type ToolStat struct {
	Kind   string `json:"kind"`
	Name   string `json:"name"`
	Server string `json:"server,omitempty"`
	// Deferred: some session carried it as a deferred tool (MCP, or a built-in Claude Code
	// defers), which the proxy filter cannot remove (see Decl.Deferred).
	Deferred bool `json:"deferred,omitempty"`
	// Tokens is what carrying this declaration costs on ONE request.
	Tokens int `json:"tokens"`
	// SessionsDeclared / SessionsUsed / Calls: how often it was carried, how often it was
	// invoked at all, and how many calls it received.
	SessionsDeclared int `json:"sessions_declared"`
	SessionsUsed     int `json:"sessions_used"`
	Calls            int `json:"calls"`
	// UnusedReads is Tokens x the requests that re-read it in the sessions that never
	// invoked it: the actual number of billed tokens spent carrying it for nothing.
	UnusedReads int64 `json:"unused_reads"`
	// UnusedUSD prices UnusedReads at the tier each of those requests was billed at.
	// Omitted (with Priced=false) when the model's rates are unknown — an unpriced number
	// must not read as "this cost nothing".
	UnusedUSD float64 `json:"unused_usd"`
	// CarryReads and CarryUSD are the same measure over EVERY captured session that declared this,
	// used or not: Tokens x the requests that re-read it, and that priced at each request's tier.
	// UnusedUSD answers "what did carrying it for nothing cost"; these answer "what does carrying
	// it cost", so a declaration the user does use still shows its price. CarryUSD is 0 when
	// unpriced (see Priced).
	// CarryPriced is false when some request that carried it had no known rates, so CarryUSD is
	// short. Separate from Priced, which describes the unused figure.
	//
	// Skill rows are slices of the skills listing, so summing carry across them counts the
	// listing's prose more than once; there is no carry total for that reason.
	CarryReads  int64   `json:"carry_reads"`
	CarryUSD    float64 `json:"carry_usd"`
	CarryPriced bool    `json:"carry_priced"`
	// UnusedUSDLow/High bound UnusedUSD over the declaration sets a request without a recorded
	// one could have carried; equal to it when every request recorded its set.
	UnusedUSDLow  float64 `json:"unused_usd_low"`
	UnusedUSDHigh float64 `json:"unused_usd_high"`
	Priced        bool    `json:"priced"`
	// Builtin marks one of Claude Code's OWN tools. Derived on read from a name allowlist
	// (see IsBuiltinTool), because the stored taxonomy cannot tell them from a user's own
	// client-side tools — both are KindTool. It exists so the UI can put them in their own
	// section, behind an expand, with a warning: they are the one group here that must NOT
	// look like a tidy saving, because removing one breaks the agent rather than slimming it.
	Builtin bool `json:"builtin"`
	// SharePct is this declaration's share of everything the account declares per request —
	// the "who owns the system prompt" number, which is the question the page is really
	// answering and which no column carried.
	SharePct float64 `json:"share_pct"`
	// LastUsedTS / LastCarriedTS are what make abandonment answerable without a window.
	//
	// A capability used heavily three months ago and carried on every request since is neither
	// "never invoked" nor "in use", and the report had no way to say so: it fell into the same
	// bucket as a tool called a minute ago. The obvious fix — analyse only the last N sessions —
	// does not work, because a session is not a unit of time: measured on one real store, spans
	// were 0.0h, 1.1h and 99.1h, with a single session covering four days. N sessions is anywhere
	// from minutes to weeks.
	//
	// The gap between these two is a fact about the ITEM, independent of how anybody structures
	// their sessions, and it is evidence a reader can check against their own memory.
	// Zero means never: an item never invoked has no LastUsedTS, rather than one that reads as 1970.
	LastUsedTS    int64 `json:"last_used_ts,omitempty"`
	LastCarriedTS int64 `json:"last_carried_ts,omitempty"`
	// Sessions is the per-session breakdown of what carrying this cost, present only when the
	// filter asked for it (Filter.PerSession). Opt-in because /api/tools is read by the
	// dashboard UI, the status line and the plugin, and an array per row on a large inventory
	// is a materially bigger payload for readers that do not use it.
	//
	// It exists because "this skill cost you $X" is a figure nobody can check, while "in these
	// four sessions it cost $a, $b, $c, $d and you never called it" is one a user can audit
	// against their own memory of what they were doing.
	Sessions []SessionCostRow `json:"sessions,omitempty"`
	// Removal is how to stop carrying it, in the form the user can act on. See RemovalFor.
	Removal Removal `json:"removal"`
	// HasText is whether this capability's own slice of the prompt was STORED and can be
	// read (see /api/prompt). False is a third state, not an empty one: a row written
	// before the column existed and a row written by an account that has not opted in to
	// content capture both land here, and the UI must say which rather than showing a
	// capability whose text looks empty.
	HasText bool `json:"has_text"`
}

ToolStat is one declared capability, with what it costs and whether it earns it.

type ToolTimeline added in v0.5.4

type ToolTimeline struct {
	// Buckets are day starts in epoch ms, ascending and contiguous — including days with no
	// traffic at all, because a gap is the thing this view is for and a compacted axis would
	// close it up.
	Buckets []TimelineBucket         `json:"buckets"`
	Items   map[string]*TimelineItem `json:"items"`
	// Days is the window actually covered, so a caller can tell a short history from a narrow
	// request.
	Days int `json:"days"`
}

ToolTimeline is the whole picture: one bucket list, and one item per capability.

type ToolTotals

type ToolTotals struct {
	// DeclaredTokens / UnusedTokens are per-session averages over the CAPTURED sessions.
	DeclaredTokens int     `json:"declared_tokens"`
	UnusedTokens   int     `json:"unused_tokens"`
	UnusedPct      float64 `json:"unused_pct"`
	// UnusedReads and UnusedUSD are the totals over the whole scope: the billed tokens
	// spent carrying never-invoked declarations, and their price.
	UnusedReads int64   `json:"unused_reads"`
	UnusedUSD   float64 `json:"unused_usd"`
	// UnusedUSDLow/High bound UnusedUSD; see ToolStat.
	UnusedUSDLow  float64 `json:"unused_usd_low"`
	UnusedUSDHigh float64 `json:"unused_usd_high"`
	Priced        bool    `json:"priced"`
	// AsideTokens is the per-session mean weight of the declarations kept OUT of every figure
	// above: Claude Code's own tools, another agent's client tools, the provider's. Reported so
	// the page can state what it left out and how large it is, instead of leaving a reader to
	// discover that the composition bar below is bigger than the headline and wonder which lied.
	AsideTokens int `json:"aside_tokens"`
	// AsideSetTokens is that group's set total, the counterpart of DeclaredSetTokens.
	AsideSetTokens int `json:"aside_set_tokens"`
	// RequestsPerSession is a MEAN over every TOOL-BEARING session in scope, captured or not,
	// while Median and Typical below are over the CAPTURED ones only — a different and smaller
	// population. That is deliberate (this one answers "how many requests does a session make",
	// those answer "how long is a session we can price"), but it means the three must never be
	// printed together without naming which population each describes: on real traffic they read
	// 3.9, 1 and 150.6. Every UI site that quotes one says so.
	RequestsPerSession       float64 `json:"requests_per_session"`
	RequestsPerSessionMedian int     `json:"requests_per_session_median"`
	// RequestsPerSessionTypical is the REQUEST-WEIGHTED mean: how many turns the session that
	// a typical request belongs to actually runs for. This is the multiplier a "cost across a
	// full session" projection must use — see the comment where it is computed for why the
	// mean and the median both answer a different question and both understate it badly.
	RequestsPerSessionTypical float64 `json:"requests_per_session_typical"`
	// DeclaredSetTokens is the summed weight of everything declared, once — INCLUDING the
	// aside group, because it is the whole that every SharePct is a part of and a share has to
	// be a share of the actual prompt. DeclaredTokens above is a per-session MEAN over the
	// controllable set and is a different quantity twice over; the two were conflated once and
	// produced shares over 100%.
	DeclaredSetTokens int `json:"declared_set_tokens"`
}

ToolTotals is the summary line.

EVERY FIGURE HERE EXCEPT DeclaredSetTokens AND THE TWO Aside FIELDS COVERS THE CONTROLLABLE SET ONLY — MCP tools and skills. It used to cover everything declared, and that made the headline of this page a number nobody could act on: Claude Code's own tools are the largest group here by weight and removing one breaks the agent, so a "you never touch 82.7% of what you carry" assembled mostly out of Read, Bash and Grep was, in effect, advice to break your agent. The built-ins are still reported — in Aside, and in their own section at the end of the page — they are simply not inside the statistics a reader is invited to act on. See ToolReport.Aside.

type TranscriptPage

type TranscriptPage struct {
	Requests []*Event `json:"requests"`
	// NextCursor is the `after` value for the following page; "" = no more turns.
	NextCursor string `json:"next_cursor"`
	// Total is the turn count for the WHOLE session, so a page can say which slice of
	// what it is showing rather than presenting a page as if it were the session.
	Total int64 `json:"total"`
	// HasContent answers "does this session have stored before/after text ANYWHERE",
	// not "on this page". The state machine above this needs the session's answer: a
	// first page of unstored turns would otherwise render "transcript storage is off"
	// over a session whose later turns ARE stored, which is exactly the wrong answer
	// that sends a user to switch on a setting they already have on.
	HasContent bool `json:"has_content"`
}

TranscriptPage is one page of a session's turns plus the cursor for the next one.

type TranscriptTurn added in v0.5.4

type TranscriptTurn struct {
	TS        int64 // epoch ms
	SessionID string
	// MessageID is the provider's id for the response. Claude Code writes one transcript line per
	// content block of a streamed message, every one carrying the same usage, so the id is what
	// makes a billed request a single turn instead of one per block. Empty on an entry that has
	// none, which is then taken as its own turn.
	MessageID string
	Model     string
	// Project is the directory the agent was started in, sanitised exactly as a live request's is.
	Project string
	// The four usage counters, named as this package names them rather than as the transcript
	// does, so a caller does not have to know the other program's vocabulary.
	FreshInput int64
	CacheRead  int64
	CacheWrite int64
	// CacheWrite1h is the part of CacheWrite billed at the one-hour tier. A subset of CacheWrite.
	CacheWrite1h int64
	Output       int64
	// Called is every capability this turn invoked: tool names as sent, and SKILLS BY THEIR OWN
	// NAME rather than by the tool that ran them. See transcriptCalled.
	Called []string
	// Skills is the subset of Called that arrived through the `Skill` tool.
	//
	// CARRIED AS A FACT, not re-derived from the name. The obvious test is a colon —
	// `superpowers:brainstorming` has one — but a marketplace skill does not: `artifact-design`
	// and `dataviz` are both skills and both bare. Guessing from the shape of the name files them
	// as tools, which puts them in the wrong half of the inventory. The transcript already knows,
	// because the invocation came through one specific tool, so the answer is recorded rather
	// than inferred.
	Skills map[string]bool
}

TranscriptTurn is one billed request, as another program recorded it.

func ReadTranscript added in v0.5.4

func ReadTranscript(path string) ([]TranscriptTurn, error)

ReadTranscript returns every billed request in one session transcript.

Errors only when the file cannot be opened. A line that does not parse, an entry type it does not know, and a torn final line are all expected states of a log another program is still writing, so each is skipped and the rest is returned — a partial read of a live session is the correct answer, not a failure.

func ReadTranscriptChecked added in v0.5.4

func ReadTranscriptChecked(path string) (turns []TranscriptTurn, truncated bool, err error)

ReadTranscriptChecked is ReadTranscript plus whether the read stopped early. A line past transcriptMaxLine aborts the scanner, and everything after it is lost; returning that as a flag lets the importer say "this file was cut short" rather than quietly undercounting.

ONE TURN PER MESSAGE ID. Claude Code writes a line per content block of a streamed message (text, then each tool_use), all with the same message.id and the same usage, milliseconds apart. Counting each line billed one request several times: measured on a real transcript, 7,680 usage lines for 5,038 distinct ids, cache_read overstated by 52%. The last line of an id carries the final usage; Called is the union of the tool_use blocks across all of its lines.

Only a regular file is read. A symlink under the projects directory could point anywhere.

type Used

type Used struct {
	Name   string `json:"name"`
	Server string `json:"server,omitempty"`
	Skill  string `json:"skill,omitempty"`
	Calls  int    `json:"calls"`
}

Used is one invoked capability: a tool name, or the Skill tool plus the skill it ran (which is the only way a skill invocation is identifiable).

type ValueMetrics

type ValueMetrics struct {
	// SavedUSD is baseline − billed: what compaction avoided, before our own spend.
	// NetSavedUSD subtracts CGLLMCostUSD, so it goes NEGATIVE when we spend more than we
	// save, which is a real outcome and the series reports it as one.
	CostUSD      float64
	BaselineUSD  float64
	CGLLMCostUSD float64
	SavedUSD     float64
	NetSavedUSD  float64
	// FrozenTokens is content cache-aware compaction deliberately left alone — the
	// headroom, and the number that explains a small SavedUSD.
	FrozenTokens int64
}

ValueMetrics is the deployment-wide value of compaction, for Prometheus. Not per tenant: these four are the numbers an operator alerts and reports on, and there was no dollar series at all — /metrics exported tokens, ratios, latency, cache outcomes and one component's net value, so Grafana could plot everything about this proxy EXCEPT whether it was worth running. cg_extract_net_value_usd was the only dollar figure on the endpoint.

type WaitCauseResult added in v0.5.0

type WaitCauseResult struct {
	WaitingFor, WaitTool, WakeCause string
	OpenBackground, OpenTeammate    int
	MonitorExpiryMs                 int64
	// The strategy metadata of issue #1198 that is read off the same body and response. All are
	// "not computed" at their zero value: nil pointers and "".
	WaitToolTimeoutMs  *int64
	WaitToolBackground *bool
	WaitPrompt         string
	// UserKey is the person's id read off the request body (session.UserKey), still raw. The
	// writer hashes it into Event.UserHash and drops it; it is never stored or published.
	UserKey string
	// SpawnType is the raw subagent_type of the last subagent call (hashed by the writer unless it is a
	// built-in name); Fanout is how many subagent calls the response made.
	SpawnType string
	Fanout    int
}

WaitCauseResult is issue #424's RECORD half's output for one request — see Event.WaitCause, which runs the computation that fills this, off the request path.

type WaterfallStep

type WaterfallStep struct {
	Key         string  `json:"key"`
	Label       string  `json:"label"`
	DeltaUSD    float64 `json:"delta_usd"` // signed: negative reduces cost
	Description string  `json:"description"`
	// Total marks a resting point (baseline / final net) rather than a delta.
	Total bool `json:"total"`
}

WaterfallStep is one bar of the honest-savings waterfall: baseline cost, the savings that reduced it, the penalties that gave some back, and the net.

type Window

type Window struct {
	Since int64 `json:"since"`
	Until int64 `json:"until"`
}

Window is a closed-open time range in epoch milliseconds. Named separately from Filter's own Since/Until because a holdout takes TWO of them and passing four loose int64s in a row is how two of them end up swapped with no compiler complaint.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL