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
- Variables
- func AgentFor(ua string) string
- func BreakdownDims() []string
- func CoverageSeconds(idleSeconds float64, maxPings int) float64
- func IsBuiltinTool(kind, name string) bool
- func PingsPerSpan(gap, idleSeconds float64, maxPings int) int
- func RedactConfig(v any) any
- func RedactContent(s string, cap int) string
- func SplitMCPName(name string) (server, tool string, ok bool)
- type API
- func (a *API) Mount(m *http.ServeMux)
- func (a *API) MountTools(m *http.ServeMux)
- func (a *API) SetAuth(fn Authenticator)
- func (a *API) SetPricer(p modelinfo.Pricer)
- func (a *API) SetTenantCapture(fn func(tenantID string) bool)
- func (a *API) SetToolFilterState(fn func(tenantID string) ToolFilterState)
- func (a *API) SetUIPath(prefix string)
- func (a *API) SetWhoami(fn func(*http.Request) any)
- func (a *API) SetWindows(r modelinfo.Resolver)
- func (a *API) ToolFilterDocument(r *http.Request) (*ToolFilterDoc, error)
- type AccountGaps
- type ArchivedSession
- type Authenticator
- type Band
- type BenchArm
- type BenchRun
- type BenchTask
- type BreakpointTotals
- type Bucket
- type CachesplitHistorical
- type CalcRow
- type CampaignSavingCell
- type ClientCeilingUsed
- type CompRow
- type CompactionAssumptions
- type CompactionCoverage
- type CompactionEpisode
- type CompactionEpisodeGroup
- type CompactionEpisodes
- type ComponentRow
- type ContentRow
- type DB
- func (d *DB) AccountMedianPrefix(f Filter) (int64, string, error)
- func (d *DB) ArchivedSessionByID(sessionID string) (ArchivedSession, error)
- func (d *DB) ArchivedSessions(f Filter, limit int) ([]ArchivedSession, error)
- func (d *DB) BenchRuns() ([]*BenchRun, error)
- func (d *DB) BenchTasks(runID int64, arm string) ([]*BenchTask, error)
- func (d *DB) Breakdown(f Filter, dim string) ([]*GroupRow, error)
- func (d *DB) CachesplitHistoricalUSD(f Filter, p modelinfo.Pricer) (CachesplitHistorical, error)
- func (d *DB) CachesplitHistoricalUSDByTenant(since int64, p modelinfo.Pricer) (map[string]CachesplitHistorical, error)
- func (d *DB) CachesplitSizeSpread() (map[string][2]int, error)
- func (d *DB) CampaignRealSavings(strategyIDs, tenantIDs []string, since int64) ([]CampaignSavingCell, error)
- func (d *DB) Close() error
- func (d *DB) CompactionEpisodesFor(f Filter, windows modelinfo.Resolver, p modelinfo.Pricer, cfg KVCacheSimConfig, ...) (*CompactionEpisodes, error)
- func (d *DB) Components(f Filter) ([]*ComponentRow, error)
- func (d *DB) DeclCreditFor(f Filter, price func(string) (modelinfo.Price, bool), removed []string) (*DeclCredit, error)
- func (d *DB) DeclFilterSavings(f Filter, price func(string) (modelinfo.Price, bool)) (*DeclFilterSaving, error)
- func (d *DB) DeclFilterSavingsByTenant(since int64, price func(string) (modelinfo.Price, bool)) (map[string]*DeclFilterSaving, error)
- func (d *DB) DecomposeComponentSavedUSD(f Filter, p modelinfo.Pricer, out []*ComponentRow) error
- func (d *DB) DropOldestSessions(n int) (int64, error)
- func (d *DB) DropOldestSessionsOfTenant(tenant string, targetRows int64) (int64, error)
- func (d *DB) EstimateComponentSavedUSD(f Filter, p modelinfo.Pricer, out []*ComponentRow) error
- func (d *DB) Facets(f Filter) (map[string][]string, error)
- func (d *DB) IngestBenchDir(dir string) (tasks int, err error)
- func (d *DB) IngestBenchRoots(roots []string) (runs, tasks int)
- func (d *DB) KVCacheAnalyze(f Filter, o KVCacheOptions, p modelinfo.Pricer, cfg KVCacheSimConfig) (*KVCacheAnalysis, error)
- func (d *DB) KVCacheDataset(f Filter, o KVCacheOptions) ([]*kvcache.Request, int64, error)
- func (d *DB) KVCacheMedianPrefix(f Filter, o KVCacheOptions) (int64, error)
- func (d *DB) KVCacheModels(f Filter) ([]string, error)
- func (d *DB) KVCacheRows(f Filter, o KVCacheOptions) (*KVCacheRowPage, error)
- func (d *DB) KVCacheSimulate(f Filter, o KVCacheOptions, p modelinfo.Pricer, cfg KVCacheSimConfig) (*KVCacheSimulation, error)
- func (d *DB) KVCacheSuggest(f Filter, o KVCacheOptions, p modelinfo.Pricer, cfg KVCacheSimConfig) (*KVCacheSuggestions, error)
- func (d *DB) KVCacheSuggestHoldout(f Filter, o KVCacheOptions, p modelinfo.Pricer, cfg KVCacheSimConfig, ...) (*KVCacheHoldout, error)
- func (d *DB) KeepAliveBehaviour(f Filter, coverageSeconds float64) (*KeepAliveBehaviour, error)
- func (d *DB) KeepAliveCalc(f Filter, idleSeconds float64, prefix int64, model string, ...) (*KeepAliveCalc, error)
- func (d *DB) KeepAliveLatencyDiagnostic(f Filter) (kvcache.Latency, error)
- func (d *DB) KeepAliveLedger(f Filter) (*KeepAliveLedger, error)
- func (d *DB) KeepAliveLive(f Filter, now int64, idleSeconds float64, maxPings int, ...) (*KeepAliveLive, error)
- func (d *DB) KeepAliveNetUSDByTenant(since int64) (map[string]float64, error)
- func (d *DB) KeepAliveRecommend(f Filter) (*KeepAliveRecommendation, error)
- func (d *DB) KeepAliveSessions(f Filter, limit int) ([]*KeepAliveSessionRow, error)
- func (d *DB) LastBilledPrefix(f Filter, session string) (int64, string, error)
- func (d *DB) MonthToDateUSD(tenantID string) (float64, error)
- func (d *DB) OrphanRows() (components, content int64, err error)
- func (d *DB) Overview(f Filter) (*Overview, error)
- func (d *DB) Path() string
- func (d *DB) PromptViewFor(f Filter) (*PromptView, error)
- func (d *DB) Prune(now time.Time, maxAge time.Duration, maxBytes int64) (int64, error)
- func (d *DB) Request(id int64, withContent bool) (*Event, error)
- func (d *DB) Requests(f Filter, before int64, limit int) (*Page, error)
- func (d *DB) SavingsTotals(f Filter) (*SavingsTotals, error)
- func (d *DB) SelfRemovals(f Filter, price func(string) (modelinfo.Price, bool), removed []string) ([]SelfRemoval, error)
- func (d *DB) Series(f Filter, bucketMs int64) ([]*Bucket, error)
- func (d *DB) SessionEvents(f Filter, sessionID string, withContent bool) ([]*Event, error)
- func (d *DB) SessionEventsPage(f Filter, sessionID string, withContent bool, after string, limit int) (*TranscriptPage, error)
- func (d *DB) Sessions(f Filter, limit, offset int) ([]*SessionRow, int64, error)
- func (d *DB) StrategyLedger(strategyID string) (*StrategyLedgerView, error)
- func (d *DB) TenantHasRows(tenantID string) (bool, error)
- func (d *DB) TenantMetrics(since int64) ([]TenantMetricRow, error)
- func (d *DB) TenantRowCounts() (map[string]int64, error)
- func (d *DB) TierCosts(f Filter, p modelinfo.Pricer) (*TierCosts, error)
- func (d *DB) ToolFilterDocFor(f Filter, price func(string) (modelinfo.Price, bool), state ToolFilterState) (*ToolFilterDoc, error)
- func (d *DB) ToolReportFor(f Filter, price func(string) (modelinfo.Price, bool)) (*ToolReport, error)
- func (d *DB) WithContext(ctx context.Context) *DB
- type DayPoint
- type Decl
- type DeclCredit
- type DeclFilterSaving
- type Denominator
- type Event
- func (e *Event) AttributeCache(seenSession, seenModel bool, sinceLastMs int64, ttlMs int64, ...)
- func (e *Event) CachePrefixChangeReason()
- func (e *Event) FromTrace(tr apply.Trace, uniqueSaved map[string]int)
- func (e *Event) Price(p modelinfo.Price, accountingComplete bool)
- func (e *Event) Redact()
- func (e *Event) Saved() int
- type ExcludedDecl
- type ExtractionRow
- type Filter
- type GroupRow
- type Hub
- type Inventory
- type KVCacheAnalysis
- type KVCacheArm
- type KVCacheAssumptions
- type KVCacheCards
- type KVCacheCoverage
- type KVCacheCustom
- type KVCacheFeatureImportance
- type KVCacheFeatureRank
- type KVCacheFormula
- type KVCacheGroup
- type KVCacheHoldout
- type KVCacheHoldoutArm
- type KVCacheHoldoutCell
- type KVCacheOptions
- type KVCachePriceCost
- type KVCachePriceView
- type KVCacheRow
- type KVCacheRowPage
- type KVCacheSchedule
- type KVCacheSimConfig
- type KVCacheSimulation
- type KVCacheSuggestion
- type KVCacheSuggestions
- type KeepAliveBehaviour
- type KeepAliveCalc
- type KeepAliveCoverage
- type KeepAliveLedger
- type KeepAliveLive
- type KeepAliveLiveRow
- type KeepAliveRecommendation
- type KeepAliveSessionRow
- type Meta
- type ModelRate
- type Options
- type Overview
- type Page
- type Principal
- type PromptPart
- type PromptRegion
- type PromptStat
- type PromptView
- type PurgeResult
- type QueueStats
- type Rclone
- func (r *Rclone) Check(ctx context.Context) error
- func (r *Rclone) Delete(ctx context.Context, path string) error
- func (r *Rclone) Describe() string
- func (r *Rclone) Get(ctx context.Context, path string) ([]byte, error)
- func (r *Rclone) Put(ctx context.Context, path string, data []byte) error
- func (r *Rclone) Size(ctx context.Context, path string) (int64, error)
- type Recorder
- func (r *Recorder) ArchiveSessionContent(ctx context.Context, c coldCandidate) (int64, error)
- func (r *Recorder) ArchiveSessionFull(ctx context.Context, c coldCandidate) (int64, error)
- func (r *Recorder) ArchivedBytes() int64
- func (r *Recorder) ArchivedSessionCount() int64
- func (r *Recorder) Close() error
- func (r *Recorder) DB() *DB
- func (r *Recorder) DBSizeBytes() int64
- func (r *Recorder) DiskUsedFraction() (float64, bool)
- func (r *Recorder) FetchArchived(ctx context.Context, sessionID string) ([]*Event, error)
- func (r *Recorder) FetchArchivedContent(ctx context.Context, sessionID string, requestID int64) ([]ContentRow, error)
- func (r *Recorder) Hub() *Hub
- func (r *Recorder) MarkUnique(tenant, component string, keys []string, saved int) int
- func (r *Recorder) Observe(tenant, session, model string, now int64) (seenSession, seenModel bool, sinceLastMs int64)
- func (r *Recorder) ObserveSplit(tenant, session, model string, now int64, tailHash uint64) (seenSession, seenModel bool, sinceLastMs int64, tailChanged bool)
- func (r *Recorder) Opts() Options
- func (r *Recorder) PurgeTenant(ctx context.Context, tenantID string) (PurgeResult, error)
- func (r *Recorder) Record(e *Event)
- func (r *Recorder) RecordInventory(tenant, session string, ts int64, inv *Inventory, text bool)
- func (r *Recorder) RemoteName() string
- func (r *Recorder) RemoteReachable() bool
- func (r *Recorder) SeedSessions(now int64) (int, error)
- func (r *Recorder) SetObserveQueue(fn func() QueueStats)
- func (r *Recorder) SetTenantQuota(fn func(tenantID string) int64)
- func (r *Recorder) Stats() Stats
- func (r *Recorder) ValueMetrics(since int64) (ValueMetrics, error)
- type Remote
- type Removal
- type SafetyCost
- type SavingsTotals
- type SelfRemoval
- type ServerStat
- type SessionRow
- type SkillStat
- type Stats
- type StrategyLedgerRow
- type StrategyLedgerView
- type Suggestion
- type SurvivalPoint
- type SystemPrompt
- type TenantMetricRow
- type TierCosts
- type ToolCoverage
- type ToolFilterDoc
- type ToolFilterState
- type ToolReport
- type ToolStat
- type ToolTotals
- type TranscriptPage
- type Used
- type ValueMetrics
- type WaterfallStep
- type Window
Constants ¶
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.
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.
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.
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. EpisodeVoided = "voided_client_compaction" )
Episode states. A closed episode is the only one that contributes to a total.
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.
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.
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.
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.
const ( ModeActive = "active" ModeBypass = "bypass" ModeObserve = "observe" )
Operating modes, as rendered in the UI.
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 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.
const ( // KindTool is a plain client-side tool (Claude Code's built-ins, an agent's own). KindTool = "tool" // 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 = "mcp_tool" // 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 = "server_tool" // KindSkill is one skill from the Skill tool's prose listing. KindSkill = "skill" // 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 = "skill_listing" // 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" )
Declaration kinds. They are stored as text because they are read back as labels and grouped on, exactly like `kind` on request_components.
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.
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.
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.
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.
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".
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 ¶
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.
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.
var KVCacheDefaultStrategies = []string{KVStrategyNoCache, KVStrategyFixed5m, KVStrategyFixed1h, KVStrategyKeepAlive5m, KVStrategyKeepAlive5mOnce, KVStrategyKeepAlive1hOnce, KVStrategyObserved, KVStrategyHistorical, KVStrategyStopReasonGated, KVStrategyOptimal}
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.
Functions ¶
func AgentFor ¶
AgentFor classifies a client User-Agent into an agent family so the dashboard can filter by application.
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 ¶
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.
func IsBuiltinTool ¶
IsBuiltinTool reports whether a KindTool declaration is one of Claude Code's own.
func PingsPerSpan ¶
PingsPerSpan is how many pings one idle span of `gap` seconds attracts under (X, K).
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 RedactConfig ¶
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 ¶
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 SplitMCPName ¶
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 ¶
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) Mount ¶
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 ¶
MountTools registers the inventory routes. Separate from Mount only to keep this feature additive to the API surface; a caller mounts both.
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) SetPricer ¶
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 ¶
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
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) SetWindows ¶ added in v0.2.0
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 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 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 ¶
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"`
// 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 BenchArm ¶
type BenchArm struct {
Arm string `json:"arm"`
Tasks int64 `json:"tasks"`
Scored int64 `json:"scored"`
Solved int64 `json:"solved"`
SolveRate float64 `json:"solve_rate"`
MeanReward float64 `json:"mean_reward"`
MeanSteps float64 `json:"mean_steps"`
TotalCostUSD float64 `json:"total_cost_usd"`
MeanCostUSD float64 `json:"mean_cost_usd"`
TotalNormCostUSD float64 `json:"total_norm_cost_usd"`
CacheRead int64 `json:"cache_read"`
CacheWrite int64 `json:"cache_write"`
FreshInput int64 `json:"fresh_input"`
Completion int64 `json:"completion_tokens"`
CacheHitRate float64 `json:"cache_hit_rate"`
MeanWallS float64 `json:"mean_wall_s"`
Exceptions int64 `json:"exceptions"`
// CostRows is how many of this arm's tasks carry a non-zero cost, and it exists so the UI
// can tell "this arm was free" apart from "the ingester could not find a cost in the file".
//
// harborRow.AgentCost binds to `agent_cost`. A rows file that names its cost anything else
// unmarshals to the zero value silently, every task lands at 0, and the arm then renders
// $0 / $0 / $0 and sorts as the CHEAPEST — a flattering lie with no way for a reader to see
// it. A float64 cannot express absence, and making the column nullable would spread that
// through five call sites; counting the rows that priced is the same information one join
// cheaper. An arm that ran tasks and cost exactly nothing on every one of them is not a
// measurement either, so `n/a` is the honest render in both cases.
CostRows int64 `json:"cost_rows"`
}
BenchArm aggregates one arm (baseline / context-guru / headroom / rtk) of a run. This is the cost-vs-reward view: an arm that saves money by failing tasks is not saving money, so reward sits beside cost in the same row.
type BenchRun ¶
type BenchRun struct {
ID int64 `json:"id"`
Name string `json:"name"`
TS int64 `json:"ts"`
Dataset string `json:"dataset"`
Model string `json:"model"`
Summary json.RawMessage `json:"summary"`
Arms []BenchArm `json:"arms"`
}
BenchRun is one ingested run as served to the UI.
type BenchTask ¶
type BenchTask struct {
Arm string `json:"arm"`
Task string `json:"task"`
Reward float64 `json:"reward"`
Steps int64 `json:"steps"`
CacheRead int64 `json:"cache_read"`
CacheWrite int64 `json:"cache_write"`
FreshInput int64 `json:"fresh_input"`
Completion int64 `json:"completion_tokens"`
CostUSD float64 `json:"cost_usd"`
NormCostUSD float64 `json:"norm_cost_usd"`
WallS float64 `json:"wall_s"`
Exception bool `json:"exception"`
}
BenchTask is one task row for the per-task drill-down.
type BreakpointTotals ¶
type BreakpointTotals struct {
System int64 `json:"system"`
Tools int64 `json:"tools"`
Messages int64 `json:"messages"`
Blocks int64 `json:"blocks"`
// 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 four 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. CachesplitSavedUSD is the part that is ours (see Overview).
CacheSavedUSD float64 `json:"cache_saved_usd"`
CachesplitSavedUSD float64 `json:"cachesplit_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"`
}
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 CachesplitHistorical ¶
type CachesplitHistorical struct {
// USD is the value, and Requests the number of session-first requests behind it.
USD float64 `json:"usd"`
Requests int64 `json:"requests"`
// Models is how many models contributed. Zero means nothing could be valued — no model has
// a measured stable half yet, none has a CONSTANT one, or none is priced.
Models int `json:"models"`
// Uncovered counts pre-instrumentation session-first requests that could NOT be valued —
// their model has no measured stable half, or the one it has is not a single number
// (recorded min != max, so there is nothing constant to retro-apply). Reported so the
// figure is never mistaken for complete.
Uncovered int64 `json:"uncovered"`
}
CachesplitHistorical is what the split earned before it was instrumented, and how much of the window that covers.
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"`
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"`
}
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 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" or "default". A measured ceiling came from watching a real
// client compact, in billed tokens; the other two 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 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"`
// 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 — the same rule and the same rates as baselineDeltaUSD, so the per-component
// figures sum to the request-level saving. 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"`
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 this query actually measured, because the ceiling is a
// fact about the CLIENT's behaviour on that model and 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"`
// OtherCreditUSD is cold_start and unknown turns. Reported apart rather than folded into
// either: a session's first turn had no entry to preserve, and "unknown" is not a verdict.
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"`
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"`
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 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 cachesplit (it moves a
// cache breakpoint) or cacheinject (it places one). Reported apart because one number
// could not carry both: cachesplit mutated 1,805 requests on production traffic and
// "acted" 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"`
// 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"`
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 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 ¶
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 (*DB) AccountMedianPrefix ¶
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) ArchivedSessionByID ¶
func (d *DB) ArchivedSessionByID(sessionID string) (ArchivedSession, error)
ArchivedSessionByID reads one 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) BenchTasks ¶
BenchTasks returns a run's task rows, optionally restricted to one arm.
func (*DB) Breakdown ¶
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) CachesplitHistoricalUSD ¶
CachesplitHistoricalUSD values the pre-instrumentation window. Read-only.
func (*DB) CachesplitHistoricalUSDByTenant ¶
func (d *DB) CachesplitHistoricalUSDByTenant(since int64, p modelinfo.Pricer) (map[string]CachesplitHistorical, error)
CachesplitHistoricalUSDByTenant is CachesplitHistoricalUSD for every tenant since a given time, in one pass instead of one call per tenant.
The Prometheus exporter used to call CachesplitHistoricalUSD once per tenant. Each call's ROW_NUMBER ranks the WHOLE unfiltered requests table (that's what makes it correct — see CachesplitHistoricalUSD's comment), so calling it N times re-sorted that same table N times over: on this deployment, 19 tenants at ~0.8s a sort, every single scrape. Tenant is only ever the outer filter here, never part of the session-first ranking itself, so it is safe to compute the ranking once and group the qualifying rows by tenant afterward.
func (*DB) CachesplitSizeSpread ¶
CachesplitSizeSpread reports the recorded minimum and maximum stable half per model. The estimate above credits a model only where those are equal; this is where that gets checked instead of assumed, and it is what decides the refusal rather than merely reporting on it.
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) 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) DeclCreditFor ¶
func (d *DB) DeclCreditFor(f Filter, price func(string) (modelinfo.Price, bool), removed []string) (*DeclCredit, error)
DeclCreditFor totals both halves over one scope.
removed is the account's own server-side removal list, VERBATIM as the configuration stores it, used ONLY to drop overlapping rows out of the modelled half. It is passed in rather than read here for the reason dash reads no tenant configuration anywhere: the host owns it (see API.SetToolFilterState). Raw rather than pre-keyed, because the config's vocabulary and the report's differ and doing that translation per caller is what made the exclusion silently inert — see declFilteredSet.
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 — see CachesplitHistoricalUSDByTenant (dash/cachehistory.go) for why a query per tenant re-pays the same table scan N times over.
func (*DB) DecomposeComponentSavedUSD ¶
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 ¶
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.
func (*DB) DropOldestSessionsOfTenant ¶
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.
func (*DB) EstimateComponentSavedUSD ¶
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 ¶
Facets returns the distinct values available for each filter dimension, so the UI's dropdowns show only what the data actually contains.
func (*DB) IngestBenchDir ¶
IngestBenchDir ingests one run directory (summary.json + rows-*.json). A directory with neither is skipped without error — scanning a jobs root full of in-progress runs must not fail.
func (*DB) IngestBenchRoots ¶
IngestBenchRoots scans each root one level deep for run directories and ingests every one it finds. Errors are collected per-directory and do not abort the scan.
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 ¶
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 ¶
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) 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 860 s.
func (*DB) KeepAliveCalc ¶
func (d *DB) KeepAliveCalc(f Filter, idleSeconds float64, prefix int64, model string, price func(string) (modelinfo.Price, bool), currentPings int) (*KeepAliveCalc, error)
KeepAliveCalc replays the account's own gaps against the K ladder at one idle interval.
Everything is priced from the ROW'S OWN MODEL rates, per the operator's price list. The one number that is not the account's own is the prefix, which the caller supplies — because per-ping cost is bimodal (p50 $0.0004, p99 $0.2275) and there is no honest average of it.
func (*DB) KeepAliveLatencyDiagnostic ¶
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 ¶
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, and CachesplitHistoricalUSDByTenant (dash/cachehistory.go) is why that gets paid for once instead of N times over.
func (*DB) KeepAliveRecommend ¶
func (d *DB) KeepAliveRecommend(f Filter) (*KeepAliveRecommendation, error)
KeepAliveRecommend answers "what should I set?" — or refuses.
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 ¶
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) MonthToDateUSD ¶
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) OrphanRows ¶
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) 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 ¶
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.
func (*DB) Request ¶
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 ¶
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) 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) 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) SessionEvents ¶
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 ¶
Sessions returns the session list, most-recently-active first, filtered and paginated server-side.
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) TenantHasRows ¶
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 ¶
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) 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)
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.
func (*DB) WithContext ¶
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"`
Requests int64 `json:"requests"`
AllUSD float64 `json:"all_usd"`
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"`
}
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"`
// The MODELLED half: what the account stopped declaring on its own. Items is how many
// names, Overlap how many were dropped because the filter is already credited for them.
SelfReads int64 `json:"self_reads"`
SelfUSD float64 `json:"self_usd"`
SelfItems int `json:"self_items"`
SelfOverlap int `json:"self_overlap"`
// 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 no longer sent, split by whose it is.
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"`
}
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"`
Model string `json:"model"`
Provider string `json:"provider"`
Agent string `json:"agent"`
Preset string `json:"preset"`
Mode string `json:"mode"`
Route string `json:"route"`
Status int `json:"status"`
Bypassed bool `json:"bypassed"`
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"`
CostUSD float64 `json:"cost_usd"`
BaselineCostUSD float64 `json:"baseline_cost_usd"`
CGLLMCostUSD float64 `json:"cg_llm_cost_usd"`
// 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"`
// CachesplitSavedUSD is what the volatile-tail split saved, and it is the only cache
// figure this project claims. See Price.
CachesplitSavedUSD float64 `json:"cachesplit_saved_usd"`
// SplitStableTokens is the size of the prefix half cachesplit moved the breakpoint
// onto — the tokens it moved out of the cache-creation tier, and the numerator of the
// figure above. Persisted so the dollar number can be checked against a token count
// instead of taken on trust.
SplitStableTokens int `json:"split_stable_tokens"`
// SplitTailHash identifies the volatile half on this request. Persisted for two reasons:
// it seeds the per-session comparison across a restart, and it lets the whole figure be
// recomputed from the table rather than trusted.
SplitTailHash uint64 `json:"split_tail_hash"`
// 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"`
// 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 transport error on send. All three
// bump skipped/failed and leave this count already raised. 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: it is the numerator's
// CEILING, and what gets stored is the credited dollars beside the cache_read they were
// computed from. See keepaliveSavedUSD for why the credit is the smaller of the two.
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"`
// 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"`
TokenAccounting string `json:"token_accounting"`
CacheMissReason string `json:"cache_miss_reason"`
UncompressedReason string `json:"uncompressed_reason"`
// 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"`
// TailChanged says the volatile tail differs from this session's previous request (or that
// this is its first). It is the condition that makes a cache hit attributable to the
// split: only on such a turn would the unsplit block have been re-created.
//
// It replaced "the session's first request", which was the wrong test on real traffic.
// Measured on this deployment: 1,105 of 1,127 session starts were COLD — the previous
// session's cache had expired before the next began — so a figure gated on the session's
// first request was structurally near zero while the component was in fact serving the
// system prompt from cache on hundreds of mid-session turns.
TailChanged bool `json:"-"`
// SessionFirst marks the first request captured for this session, which is what makes a
// cache hit attributable (see Price). Not persisted because it does not need to be: a
// nonzero cachesplit_saved_usd identifies exactly the rows that qualified, and
// split_stable_tokens, cache_read and cache_write are all stored beside it, so the
// figure can be recomputed from the row. (It is NOT recoverable from
// cache_miss_reason, which reads "hit" on every qualifying row — AttributeCache
// short-circuits on cache_read > 0 before it ever considers a cold start.)
SessionFirst bool `json:"-"`
// 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:"-"`
}
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 ¶
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) AttributeCache ¶
func (e *Event) AttributeCache(seenSession, seenModel bool, sinceLastMs int64, ttlMs int64, prefixChanged bool)
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.
func (*Event) CachePrefixChangeReason ¶
func (e *Event) CachePrefixChangeReason()
CachePrefixChangeReason marks the miss as caused by a changed prefix.
func (*Event) FromTrace ¶
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) Price ¶
Price fills the cost columns AT WRITE TIME, from this request's four billed token tiers plus a baseline counterfactual.
The baseline is what the SAME request would have cost had context-guru not removed anything. Getting this right is the whole point of the dashboard, and there are two ways to get it wrong, both of which inflate it:
- Pricing GROSS savings. `Saved()` is tokens_before − tokens_after for THIS turn, and the agent re-sends its whole transcript every turn, so the same compaction is re-counted once per remaining turn. On a real 63-request window that is a 13.1x overcount — a factor this dashboard computes and displays as `overcount_ratio` right beside the dollar figure. Only SavedUnique is content that genuinely never reached the provider.
- Pricing everything at the cache-WRITE rate. That rate (12.5x a read) is right for content entering the prompt for the first time. The re-sent remainder, on a turn whose cache HIT, would have been served from the provider's cache, so the most it could have been billed at is the cache-READ rate. Pricing it as a write multiplies the overcount by ~12.5.
So: unique savings at the write rate, and the re-sent remainder at the rate the request itself actually paid — see repeatRate, which is where "whose cache hit" stopped being an assumption. Restored (expanded) content is content we removed and then had to serve back, so it is added to the ACTUAL cost side, never subtracted from baseline.
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) 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.
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 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
Model string
Provider string
Agent string
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.
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);
// CachesplitSavedUSD is ours, and TotalSavedUSD is compaction's plus ours. 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"`
CachesplitSavedUSD float64 `json:"cachesplit_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 (*Hub) Publish ¶
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 ¶
ServeScoped streams only one tenant's events (or everything, for a manager).
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 ¶
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.
provider selects the dialect: Anthropic names tools at `tools.#.name` and calls them in `tool_use` content blocks; OpenAI nests both a level deeper (`tools.#.function.name`, `tool_calls.#.function.name`).
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
}
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 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 the shipped `prefix >= 20k` gate
// costs almost nothing, and the panel says so.
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"`
// 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 — see Event.keepaliveSavedUSD — 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"`
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"`
// 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"`
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: 3600 when this session's most recent write landed in
// the one-hour tier, 300 otherwise. 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"`
}
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 KeepAliveRecommendation ¶
type KeepAliveRecommendation struct {
// Refused is the reason, when there is one. Its presence is the branch.
Refused string `json:"refused,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"`
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"`
}
KeepAliveSessionRow is one row of panel 3f / panel 5: a session, what its expiries cost, and whether an override is armed on it.
type Meta ¶
type Meta struct {
// ReasoningEffort is Anthropic's `output_config.effort` or OpenAI's
// `reasoning_effort` — low|medium|high|xhigh|max, "" when unset. NOT a synonym for
// thinking: on current Anthropic models effort is the depth control and
// thinking.budget_tokens is the removed predecessor, so both are recorded.
ReasoningEffort string `json:"reasoning_effort"`
// ThinkingMode is Anthropic `thinking.type` — adaptive|enabled|disabled, "" absent.
ThinkingMode string `json:"thinking_mode"`
// ThinkingBudget is `thinking.budget_tokens` (pre-4.6 models only; 0 = unset).
ThinkingBudget int `json:"thinking_budget"`
// Temperature and TopP are POINTERS, and the column is NULLABLE, because "the client
// did not set it" and "the client set it to 0" are different facts and 0 is a
// legitimate value for both. A sentinel would make a deterministic request
// indistinguishable from an unspecified one.
Temperature *float64 `json:"temperature"`
TopP *float64 `json:"top_p"`
// MaxTokens is the client's output cap (`max_tokens`, or OpenAI's
// `max_completion_tokens`); 0 = unset.
MaxTokens int `json:"max_tokens"`
Stream bool `json:"stream"`
// ToolChoice is the normalized forcing mode: auto|any|none|required|tool for the
// object form, or the bare string OpenAI sends. The forced tool's NAME is
// deliberately not stored — it is unbounded client text with no aggregate use.
ToolChoice string `json:"tool_choice"`
// Tools is how many tools the request declared; SystemBlocks how many blocks the
// top-level `system` array carried (1 for a bare string).
Tools int `json:"tools"`
SystemBlocks int `json:"system_blocks"`
// The prompt-cache breakpoints ON ARRIVAL, by location: `tools` and `system` render
// ahead of `messages`, so location decides how much prefix a breakpoint protects.
// Zero on a request the pipeline never inspected (observe mode), like every other
// pipeline-derived field on such a row.
CacheBPSystem int `json:"cache_bp_system"`
CacheBPTools int `json:"cache_bp_tools"`
CacheBPMessages int `json:"cache_bp_messages"`
CacheBPBlocks int `json:"cache_bp_blocks"`
// StopReason is the provider's own terminal reason, normalized across dialects:
// Anthropic `stop_reason` (end_turn|max_tokens|tool_use|stop_sequence|pause_turn|
// refusal|model_context_window_exceeded) or OpenAI `choices.0.finish_reason`
// (stop|length|tool_calls|content_filter). "" when the response carried none.
StopReason string `json:"stop_reason"`
}
Meta is the request's own metadata — the knobs the CLIENT chose, plus the stop reason the provider answered with. Captured because they are the levers that explain a cost: reasoning effort and thinking budget buy output tokens, and where the cache_control breakpoints sit decides how much of the prefix was billed as a read rather than a write, which is the whole subject of this project.
Real columns rather than a JSON blob, deliberately. Every field here is either GROUPED BY in an aggregate (effort, thinking mode, stop reason, tool_choice, the breakpoint counts) or a scalar rendered on the request row; a JSON column would put json_extract() in the middle of every one of those queries and give the free-text tail somewhere to hide from the redactor. There is no long tail to justify one.
Anthropic and OpenAI spell the same knobs differently; capture normalizes them (see proxy.metaFromBody) so one column means one thing across dialects.
func (Meta) CacheBreakpoints ¶
CacheBreakpoints is the total the provider's cap of four applies to.
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 Options ¶
type Options struct {
// 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-OUT: it is the headline feature, so it defaults on. 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
// 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
// BenchDirs are directories scanned for harbor benchmark runs (summary.json +
// rows-*.json) at startup and on demand.
BenchDirs []string
// 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
// 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
}
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"`
// 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"`
// CachesplitSavedUSD is the cache saving that IS ours: summed over requests where the
// volatile-tail split ran, the snapshot had MOVED since the session's previous request,
// and the provider then read at least the stable half from cache while writing less than
// it. Priced against a cache miss. A floor. See Event.cachesplitSavedUSD.
CachesplitSavedUSD float64 `json:"cachesplit_saved_usd"`
// The three counts behind that figure, so a small number is explicable rather than
// mysterious. This mattered: when the credit was gated on the session's FIRST REQUEST the
// figure read ~$0 on real traffic, and the reason was visible only in these counts —
// 1,105 of 1,127 session starts had no cache to hit, because the previous session's had
// expired. That gate is gone (it is TailChanged now, see Event.cachesplitSavedUSD); the
// counts stay, because the replacement gate also fires rarely and for its own reason.
//
// SplitRequests is requests the split ran on; SplitTailMoved is the subset whose snapshot
// had moved (the turns it can earn on); SplitCredited is the subset that also read the
// stable half from cache instead of re-creating it (the turns it did earn on).
// CachesplitHistorical is what the split earned on requests that predate the
// instrumentation for it, valued at read time and never stored. nil when it could not be
// priced — absent, not zero. See DB.CachesplitHistoricalUSD.
CachesplitHistorical *CachesplitHistorical `json:"cachesplit_historical,omitempty"`
// 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"`
// 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"`
// ONE definition of "moved", used here and at the write site (Recorder.ObserveSplit): the
// tail moved if this request's tail hash differs from the most recent PREVIOUS tail hash
// recorded for the session, and a session with no previously recorded tail counts as moved
// because there was nothing there to match. The read-time recomputation used to compare
// against the previous ROW's hash including 0 — and 0 means "nothing was split on that
// turn", not "the tail was zero" — while the write-time map only ever remembered non-zero
// hashes. The two therefore counted different things and the page showed 844 acted / 314
// moved / 3 credited, which reads as broken arithmetic. Under the single definition the
// same corpus is 844 / 16 / 3.
//
// SplitCreditedMoved is the reconciliation: the credited requests that the recomputation
// also calls moved. It is 0 on the stored corpus, and that is a finding rather than a
// rounding difference — the write-time map is process-scoped, so a proxy restart or a
// session-eviction made three mid-session turns look like first sightings and they were
// credited for a snapshot that had not moved. The write path no longer does that (a
// session we have SEEN but whose tail we have forgotten is not a move), so from here on
// the two counts agree by construction. The stored $0.03 is left exactly as recorded.
SplitRequests int64 `json:"split_requests"`
SplitTailMoved int64 `json:"split_tail_moved"`
SplitCredited int64 `json:"split_credited"`
SplitCreditedMoved int64 `json:"split_credited_moved"`
// The declarations no longer sent. TWO figures, because they are two different claims about
// the same kind of tokens and adding them together would either overstate what this product
// did or refuse a number a reader has asked for. See dash/declcredit.go for the argument.
//
// DeclFilterUSD is 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.
//
// SelfRemovedUSD is MODELLED and the USER's: the account stopped declaring something and no
// component of ours was involved. It is NOT in TotalSavedUSD, which states that its addends
// are all ours. SelfRemovedOverlap is how many candidate rows were dropped because the filter
// is already credited for the same tokens.
DeclFilterUSD float64 `json:"decl_filter_usd"`
DeclFilterReads int64 `json:"decl_filter_reads"`
DeclFilterRequests int64 `json:"decl_filter_requests"`
SelfRemovedUSD float64 `json:"self_removed_usd"`
SelfRemovedReads int64 `json:"self_removed_reads"`
SelfRemovedItems int64 `json:"self_removed_items"`
SelfRemovedOverlap int64 `json:"self_removed_overlap"`
// 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"`
// TotalReducedUSD is TotalSavedUSD plus what the ACCOUNT removed itself. It answers "how much
// smaller did this account's bill get", where TotalSavedUSD answers "how much of that did
// context-guru do". A reader wants both and they are not the same question; printing one
// under the other's label is how a dashboard takes credit for its user's work.
TotalReducedUSD float64 `json:"total_reduced_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. These four columns
// have existed since the placement work and 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
// unaffected: they come from the provider's own reported usage.
//
// 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"`
// 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"`
// 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) SetDeclCredit ¶
func (o *Overview) SetDeclCredit(c *DeclCredit)
SetDeclCredit attaches the declarations-no-longer-sent credit and folds each half into the total it belongs in: the filter's measured saving into TotalSavedUSD (it is ours), the account's own removals into TotalReducedUSD only (they are not). Called by the API layer, which holds the rates, for the same reason SetTiers is — DB.Overview deliberately cannot price anything.
func (*Overview) SetTiers ¶
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 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"`
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"`
// 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 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"`
}
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 ¶
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) Put ¶
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.
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 ¶
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 ¶
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 ¶
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 ¶
ArchivedBytes is how much is stored in cold storage, both kinds of object counted.
func (*Recorder) ArchivedSessionCount ¶
ArchivedSessionCount is how many sessions are in cold storage.
func (*Recorder) DBSizeBytes ¶
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 ¶
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 ¶
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, 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) MarkUnique ¶
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) ObserveSplit ¶
func (r *Recorder) ObserveSplit(tenant, session, model string, now int64, tailHash uint64) (seenSession, seenModel bool, sinceLastMs int64, tailChanged bool)
ObserveSplit is Observe plus the volatile-tail comparison: tailChanged reports whether this request's tail differs from the previous request's in the same session, which is the turn on which the split is worth money (see dash.Event.cachesplitSavedUSD). A session's FIRST request counts as changed — there was nothing there to match.
tailHash 0 means nothing split, and then tailChanged is false: there is no split to credit.
func (*Recorder) PurgeTenant ¶
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 ¶
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 ¶
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) RemoteName ¶
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 ¶
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) SeedSessions ¶
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.
One indexed group-by at startup, 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 ¶
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) 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 ¶
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 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 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"`
CachesplitSavedUSD float64 `json:"cachesplit_saved_usd"`
KeepAlivePingUSD float64 `json:"keepalive_ping_usd"`
KeepAliveSavedUSD float64 `json:"keepalive_saved_usd"`
KeepAliveNetUSD float64 `json:"keepalive_net_usd"`
TotalSavedUSD float64 `json:"total_saved_usd"`
}
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.
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.
This is a saving the product caused and it was being thrown away. Once somebody removes an MCP server, the declaration is simply absent from later sessions: no component ran, no filter fired, and every measurement on this dashboard is about content we removed, so the reduction registered nowhere. Crediting it needs no new capture, only the observation that the inventory is a time series and this name is present in the early part and absent from the late part.
It is kept SEPARATE from the tool-filter's realized savings and never added to them, because the two can describe the same tokens: an account that removed a server locally AND has it in its server-side filter list would otherwise be credited twice for one reduction. Overlap is reported rather than resolved silently — see Overlap.
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"`
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 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"`
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"`
}
SessionRow is one row of the session list — the view neither reference implementation has at all, despite both having sessions internally.
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 Stats ¶
type Stats struct {
Captured int64 `json:"captured"`
Written int64 `json:"written"`
Dropped int64 `json:"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"`
// 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 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 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
// CachesplitSavedUSD is the prefix-cache saving that is ours (see Overview).
CachesplitSavedUSD float64
// CachesplitHistoricalUSD is the same saving on requests written before it could be
// measured per request, valued on read. Filled by the host, which holds the rates —
// TenantMetrics itself cannot price anything.
CachesplitHistoricalUSD 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 the same way
// CachesplitHistoricalUSD is (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 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 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 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"`
// 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"`
// SelfRemoved is what the account stopped declaring partway through the window — savings
// the user made themselves, which no other measurement on this dashboard could see.
SelfRemoved []SelfRemoval `json:"self_removed,omitempty"`
// Prompt is the system prompt's weight and how much of the prefix can be shown as text.
Prompt PromptStat `json:"prompt"`
}
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"`
// 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"`
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"`
// 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"`
// 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 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"`
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 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 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.
Source Files
¶
- api.go
- archive.go
- bench.go
- cachehistory.go
- campaignsavings.go
- capture.go
- compactepisode.go
- declcredit.go
- dedupetext.go
- diskfree_unix.go
- event.go
- janitor.go
- keepalive.go
- keepaliveapi.go
- keepalivestrategy.go
- keepalivestrategybackfill.go
- kvcache.go
- kvcacheapi.go
- kvcacheholdout.go
- kvcachesim.go
- kvcachesuggest.go
- metrics_export.go
- mountpath.go
- overview.go
- promptapi.go
- promptparts.go
- purge.go
- query.go
- readvalue.go
- redact.go
- remote.go
- savings.go
- schema.go
- spend.go
- sse.go
- store.go
- toolapi.go
- toolinventory.go
- toolremoval.go
- toolsuggest.go
- ui.go