metrics

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Oct 5, 2026 License: Apache-2.0 Imports: 5 Imported by: 1 module, 0 packages

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

Documentation

Overview

Package metrics turns component/run reports into telemetry. It provides concrete components.Emitter implementations; the pipeline depends only on the Emitter interface, so this package imports components and not vice versa.

v1 ships: Nop (in components), Slog (structured logs in OTel gen_ai.* vocabulary), and Aggregator (in-process rollups behind /stats). An OTel-SDK emitter and honest-metrics extras (bounce-adjusted savings, waste signals) land in P5. Each host surfaces these natively (proxy -> bifrost Prometheus/ OTel + /metrics; sidecar plugin -> StatsSource).

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ExtractionAvgLatencyMs added in v0.1.1

func ExtractionAvgLatencyMs(component string) (float64, int64)

ExtractionAvgLatencyMs returns the observed mean wall time per extraction call made by `component` and the number of calls it averages. The gate reads this to stop SPECULATIVE calls once they are observed to be slow — exploration spends wall clock as well as money, and an agent with a task deadline feels the former more (PR #37: 17.8s across 2 calls that saved 0 tokens).

func ExtractionP50LatencyMs added in v0.1.1

func ExtractionP50LatencyMs(component string) (float64, int64)

ExtractionP50LatencyMs returns the MEDIAN observed wall time per extraction call made by `component`, and the number of samples behind it. The gate reads this rather than the mean to decide whether speculative calls have become too slow to be worth their wall clock — see offload.tooSlowToExplore for the measurement that made the mean unusable here.

PER COMPONENT (#176): reading the process-global median made one component's brake fire on another component's latency. extract_llm's per-output cheap-model calls and the sweep's single frontier-model ask differ by more than an order of magnitude, so the pooled median is not a fact about either.

func RecordExtractionCacheLookup added in v0.1.1

func RecordExtractionCacheLookup(component string, hit bool)

RecordExtractionCacheLookup notes one global result-cache lookup and whether it hit. A hit is a call AVOIDED — the cheapest possible outcome, and the source of ~93% of the component's realized value in the Terminal-Bench measurement.

func RecordExtractionCall added in v0.1.1

func RecordExtractionCall(component string, latencyMs float64)

RecordExtractionCall notes one extraction LLM call and its wall time, for `component`.

func RecordExtractionReason added in v0.1.1

func RecordExtractionReason(component, reason string)

RecordExtractionReason counts one trigger/suppression reason.

func RecordExtractionSaving added in v0.1.1

func RecordExtractionSaving(component string, tokens int)

RecordExtractionSaving notes tokens removed by an accepted extraction (count each distinct compaction once — the caller dedups by content key).

func RecordExtractionSpend added in v0.1.1

func RecordExtractionSpend(component string, usd float64)

RecordExtractionSpend notes what ONE call cost, priced by the component that made it with the rates of the model it actually addressed. See xCounters.spendNano for why /stats cannot derive this from cheapmodel's process totals.

func RecordExtractionSuppressed added in v0.1.1

func RecordExtractionSuppressed(component, reason string)

RecordExtractionSuppressed notes that the economic gate declined a call, with its reason.

func RecordExtractionValue added in v0.1.1

func RecordExtractionValue(component string, usd float64)

RecordExtractionValue notes the dollars one removal was worth, priced by the component at the rate that removal was actually billed at — the cache-write rate on a cold turn for the first application, the cache-read rate for each later replay of the frozen result.

Called at BOTH sites deliberately: crediting only the first application under-reports by however much the replay is worth, and crediting the replays at the first application's rate over-reports it by 12.5x. The component is the only layer that knows which regime a request was in, so it is the layer that prices it.

Types

type Aggregator

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

Aggregator keeps process-wide and per-component rollups for /stats. Savings are token-weighted (SUM saved / SUM before), the honest aggregate — not a mean of per-request percentages (rtk's lesson).

func NewAggregator

func NewAggregator() *Aggregator

NewAggregator returns an empty aggregator.

func (*Aggregator) Component

func (a *Aggregator) Component(r components.Report)

func (*Aggregator) FilterAct added in v0.1.1

func (a *Aggregator) FilterAct(family, filter, contentKey string, saved int)

FilterAct implements components.FilterStatsSink: one applied cmdfilter filter.

func (*Aggregator) FilterMiss added in v0.1.1

func (a *Aggregator) FilterMiss(selector string)

FilterMiss implements components.FilterStatsSink: a selector that matched nothing.

func (*Aggregator) RecordAddedLatency

func (a *Aggregator) RecordAddedLatency(ms float64)

RecordAddedLatency notes the wall time (ms) context-guru added to one request (normalize + pipeline + writeback). Only meaningful on the active path.

func (*Aggregator) RecordEligibility added in v0.1.1

func (a *Aggregator) RecordEligibility(attempted, frozen int)

RecordEligibility notes how many tokens this request's offloaders were allowed to touch, and how many cache-awareness froze — the numerator's honest denominator, and the cost of our own safety mechanism.

func (*Aggregator) RecordExpand

func (a *Aggregator) RecordExpand(tokens int)

RecordExpand notes that `tokens` of previously-offloaded content had to be re-served (the model called expand). This is the bounce signal: it means an offload was premature, so the honest savings figure subtracts it (lean-ctx's adjusted savings).

func (*Aggregator) RecordSSE added in v0.1.1

func (a *Aggregator) RecordSSE(ttfbMs float64, buffered bool)

RecordSSE notes one streaming response: ms from issuing the upstream request to the first byte handed to the client, and whether the stream had to be fully buffered first (which turns TTFB into total-response time).

func (*Aggregator) RecordSSEExpandAfterStream added in v0.1.1

func (a *Aggregator) RecordSSEExpandAfterStream()

RecordSSEExpandAfterStream notes a response the bounded SSE peek streamed through that nevertheless named the expand tool — a call the continuation loop would have intercepted had the whole stream been buffered, so the client got the model's raw tool_use instead.

This is the peek's price, and it is measured rather than argued: the peek trades away interception of an expand call that arrives after the response's first content block, in exchange for not delaying ~33% of responses by ~21 seconds. If this counter is a meaningful fraction of sse_streamed, the trade is wrong and the fix is the SSE splice described in proxy/ssepeek.go. It is an UPPER bound: a model that writes the tool's name in prose is counted too.

func (*Aggregator) RecordUpstreamLatency

func (a *Aggregator) RecordUpstreamLatency(ms float64, bypassed bool)

RecordUpstreamLatency notes one provider round-trip (ms), split by whether the request bypassed context-guru — so a run can compare with-CG vs baseline latency.

func (*Aggregator) RecordUsage added in v0.1.1

func (a *Aggregator) RecordUsage(fresh, cacheRead, cacheWrite, output int64)

RecordUsage adds one response's provider-billed token tiers. Called with what the provider reported; a response that reports nothing contributes nothing (never a zero-filled row that would read as "free").

func (*Aggregator) Run

func (a *Aggregator) Run(r components.RunReport)

func (*Aggregator) SetMode added in v0.1.1

func (a *Aggregator) SetMode(m components.Mode)

SetMode records the configured operating mode so /stats can label itself — the observe-mode banner has to be unmistakable, and a consumer needs to know from the payload alone whether the numbers were enforced.

func (*Aggregator) Snapshot

func (a *Aggregator) Snapshot() Snapshot

Snapshot returns a point-in-time copy of the rollups.

type ExtractStats added in v0.1.1

type ExtractStats struct {
	Calls            int64 `json:"calls"`            // extraction LLM calls made
	CallsAvoided     int64 `json:"calls_avoided"`    // global result-cache hits
	CallsSuppressed  int64 `json:"calls_suppressed"` // declined by the economic gate
	CacheLookups     int64 `json:"cache_lookups"`    //
	GrossSavedTokens int64 `json:"gross_saved_tokens"`

	// CacheHitRate is calls_avoided / cache_lookups.
	CacheHitRate float64 `json:"cache_hit_rate"`
	// AvgLatencyMs is mean wall time per extraction call — the component's latency cost.
	AvgLatencyMs float64 `json:"avg_latency_ms"`

	// PromptCacheReadTokens is the evidence for issue #28 part A. If this stays 0 while
	// calls climbs, the preamble's cache_control breakpoint is being SILENTLY IGNORED
	// (the prefix is below the model's minimum cacheable length) and the split is buying
	// nothing. Do not infer a cache win from the fact that a breakpoint was placed.
	PromptCacheReadTokens  int64 `json:"prompt_cache_read_tokens"`
	PromptCacheWriteTokens int64 `json:"prompt_cache_write_tokens"`

	// ExtractionCostUSD is what the component SPENT; GrossValueUSD is what its saved
	// tokens are WORTH at the rate they would actually have been billed; NetValueUSD is
	// the honest headline. Negative means the component is underwater and should be off.
	ExtractionCostUSD float64 `json:"extraction_cost_usd"`
	GrossValueUSD     float64 `json:"gross_value_usd"`
	// NetValueUSD is nil — rendered as JSON `null` — when the spend behind it is NOT KNOWN.
	//
	// A pointer rather than a float because 0 dollars of spend and 0 evidence of spend are the
	// same number and the opposite claim, and this field is the one an operator acts on. A
	// component that made calls and priced none of them would otherwise publish
	// `net_value_usd: +grossValue` — "comfortably profitable" — on no cost information at all,
	// while the block enclosing it reported the component underwater from the host's figure. Two
	// figures for one quantity disagreeing by the whole spend is exactly the failure this change
	// exists to remove, so the unknown is rendered as unknown. Read CostSource for which case a
	// row is in.
	//
	// The AGGREGATE is never nil: it always has a determined spend, from the components, from the
	// host's figure, or from there being no spend at all.
	NetValueUSD *float64 `json:"net_value_usd"`
	// CostSource says where ExtractionCostUSD came from. Named values, because the number alone
	// cannot distinguish the cases and they call for different responses:
	//
	//	component   every call in this row priced itself, at the rates of the model it called.
	//	            The figure is this component's own arithmetic — trust it.
	//	host_total  the host's process-global cheap-model spend. A SUPERSET: it also carries
	//	            `summarize` and `agentdiet`, and prices everything through one rate card.
	//	            Aggregate only.
	//	partial     some calls priced themselves and some did not, and the host's figure was no
	//	            larger. The total is a FLOOR, not the bill. Aggregate only.
	//	unpriced    this row made calls and none of them priced itself, so nothing is known about
	//	            what it spent. ExtractionCostUSD is 0 because there is no evidence, NOT
	//	            because the component was free, and NetValueUSD is null.
	//	none        no calls and no spend. 0 is the true figure.
	CostSource string `json:"cost_source"`
	// UnpricedComponents NAMES the components whose calls priced nothing, sorted, so a
	// `cost_source` of `partial` or `host_total` says WHICH component the total is missing
	// rather than only that something is missing.
	//
	// Aggregate only, and omitted when every call priced itself. Without it the label is a
	// prompt to go and scan every by_component row for `cost_source: unpriced` — which is work
	// the snapshot already did, since it is the same test that set the aggregate's label. An
	// operator who has to re-derive the answer from the rows will read the label and stop, and
	// then the floor gets quoted as the bill.
	UnpricedComponents []string `json:"unpriced_components,omitempty"`

	// Reasons counts why extraction ran or was suppressed, most frequent first.
	Reasons map[string]int64 `json:"reasons,omitempty"`
	// TopReason is the single most common reason — the one-line operator answer.
	TopReason string `json:"top_reason,omitempty"`

	// ByComponent breaks every field above down by the component that recorded it (#176).
	//
	// The enclosing block stays the SUM — see the type comment for why those names are frozen,
	// and note it is /metrics rather than the harness that freezes them — but the sum is the
	// figure that misattributed a 59-second latency and a negative net value to a component
	// that made no calls, so it must never again be the only figure available. Nil inside each
	// nested entry: the breakdown does not nest.
	ByComponent map[string]*ExtractStats `json:"by_component,omitempty"`
}

ExtractStats is the extraction economics block served inside /stats. It is ADDITIVE: every pre-existing field keeps its name and meaning.

NOT because the benchmark harness parses it — that reason was carried here and in docs/components/extract_llm.md and it is FALSE. `deploy/` reads `runs`, `acted` and `saved_tokens` off the per-COMPONENT objects (measure.py does so by direct index, so removing one is a KeyError), and reads nothing at all out of this block; grepping deploy/ for gross_saved_tokens, calls_avoided, extraction_cost_usd or avg_latency_ms returns nothing.

The real reason these names are frozen is /metrics. proxy/promexport.go publishes them as cg_extract_calls_total, cg_extract_cost_usd, cg_extract_net_value_usd and cg_extract_latency_ms, and dash/metrics_export.go documents cg_extract_net_value_usd as the endpoint's only dollar figure. Those are what an operator's alert rule and dashboard query are written against, off-repo and unversioned, so a rename breaks monitoring silently — which is a worse failure than breaking the harness, because the harness would at least crash.

func ExtractSnapshot added in v0.1.1

func ExtractSnapshot(cost, perSavedTokenUSD float64, cacheWrite, cacheRead int64) ExtractStats

ExtractSnapshot builds the extraction stats.

cost is the host's fallback figure for extraction spend, used only for components that recorded none of their own (a library embedding that never fills ModelCall.CostUSD). perSavedTokenUSD is the value of ONE saved token at the rate it would actually have been billed (cache-read vs fresh — the caller knows the traffic's cache-awareness); the value side is computed HERE, against each component's own GrossSavedTokens.

Taking a RATE rather than a pre-computed total is deliberate. The obvious signature (grossValue float64) invites the caller to pass the pipeline-wide savings figure, which prices every other component's work (format, dedup, cmdfilter, extract, …) against extract_llm's cost and reports the component as POSITIVE when its own arithmetic says otherwise. That is the single number this whole issue exists to get right, so the signature makes the mistake impossible to express.

func (ExtractStats) Net added in v0.1.1

func (s ExtractStats) Net() (float64, bool)

Net returns the net value, and whether it is known. Consumers that must publish a number (a Prometheus gauge cannot say "unknown") use the bool to decide whether to publish at all rather than turning an unknown into a 0 that reads as break-even.

type QueueStats added in v0.1.1

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 modes.Stats. Declared here as a plain struct rather than importing modes because the dependency runs the other way (modes uses metrics, not vice versa).

type SelectorMiss added in v0.1.1

type SelectorMiss struct {
	Selector string `json:"selector"`
	Count    int64  `json:"count"`
}

SelectorMiss is one output shape that matched no filter, with how often it appeared.

type Slog

type Slog struct{ L *slog.Logger }

Slog logs each component and run in the GenAI semantic-convention vocabulary.

At DEBUG, not INFO. These are per-component records — several per request — so at INFO they buried the one line per request that describes the request, which is that level's whole job. The proxy no longer wires this emitter at all: apply logs the same decisions with the tenant, the session and the gate histogram attached (see apply.logDecisions). It stays exported for a library host that wants this vocabulary.

func (Slog) Component

func (s Slog) Component(r components.Report)

func (Slog) Run

func (s Slog) Run(r components.RunReport)

type Snapshot

type Snapshot struct {
	Requests      int64   `json:"requests"`
	TokensBefore  int64   `json:"tokens_before"`
	TokensAfter   int64   `json:"tokens_after"`
	SavedTokens   int64   `json:"saved_tokens"`
	SavingsPct    float64 `json:"savings_pct"`
	WastedTokens  int64   `json:"wasted_tokens"`  // re-served via expand
	Bounces       int64   `json:"bounces"`        // expand events
	AdjustedSaved int64   `json:"adjusted_saved"` // saved - wasted (may be negative)
	// Reversibility's two failure causes, split because they call for opposite responses.
	// Malformed = the model invented a marker id; nothing to do. Missing = an id this proxy could
	// have minted resolved to nothing, i.e. a cut advertised as reversible was not — a defect, and
	// the ALERTABLE one. Neither can be inferred from WastedTokens, which counts successful
	// re-serves and therefore reads identically whether a stash broke or expand was never called.
	ExpandUnresolvedMalformed int64 `json:"expand_unresolved_malformed"`
	ExpandUnresolvedMissing   int64 `json:"expand_unresolved_missing"`
	// AdjudicateStray counts tool_results rewritten because the AGENT called the proxy-injected
	// adjudication tool. The proxy advertises that tool on every request and tells the model not to
	// call it; this is the number that says whether the telling works (measured 0 across ~4,900
	// requests). Non-zero is a lost agent turn per count, not a correctness failure.
	AdjudicateStray int64 `json:"adjudicate_stray"`
	// ModelInfoUnresolved counts failed attempts to load the operator's model-window document, and
	// ModelInfoLastError says why the most recent one failed. Empty/zero is the healthy case.
	//
	// PUBLISHED HERE BECAUSE THIS IS THE ARTIFACT A RUN KEEPS. When the window cannot be resolved,
	// every fraction-based threshold in the pipeline is silently evaluated against a built-in default
	// instead: iteration 024 ran ten benchmark passes that way, resolved 1,000,000 on all 2,207
	// requests against a configured 64,000, and produced a complete set of healthy counters describing
	// a configuration that was never in effect — summarize's 0.78 trigger became 780,000 and never
	// fired once, and the econ trigger's turn horizon came out 16x too long. Nothing else in this
	// snapshot can go non-zero for that. A warning in a debug log was not enough, because nobody reads
	// a debug log for a run that looks fine.
	ModelInfoUnresolved int64  `json:"model_info_unresolved"`
	ModelInfoLastError  string `json:"model_info_last_error,omitempty"`

	Components map[string]compStat `json:"components"`
	// Pipeline is the CONFIGURED component order, and PipelineLen its length, so a reader can tell
	// "no components are configured" from "components ran and did nothing". Components alone cannot:
	// both are an empty map. That distinction stopped being academic when `off` became the plugin's
	// default preset - the common case is now an empty pipeline, and a dashboard that renders it as
	// a blank panel says "broken" about something working exactly as configured.
	//
	// NEITHER carries omitempty, and Pipeline's absence of it is the load-bearing part. With
	// `omitempty` an EMPTY slice is omitted exactly like a nil one - so single-tenant `off`, which is
	// now the plugin's default and the whole case these fields exist to describe, emitted no
	// `pipeline` key at all and was indistinguishable from the multi-tenant case that both comments
	// said absence meant. Without it the two are distinct on the wire: `[]` is "configured with no
	// components", `null` is "no single pipeline describes this endpoint". Caught in review.
	Pipeline    []string `json:"pipeline"`
	PipelineLen int      `json:"pipeline_len"`
	// TopPassthrough names components that ran but never saved a token — dead
	// weight in the pipeline, candidates to drop from the config.
	TopPassthrough []string `json:"top_passthrough"`
	// TopDiscarded names components whose changes the writeback layer threw away at
	// least once — they mutated the request but (for those changes) never reached the
	// wire. Any entry here needs investigating; see the per-component
	// `discarded_changes` for the count.
	TopDiscarded []string `json:"top_discarded"`
	// LLM* report the cheap (config-source) model usage the CONTEXT-GURU components
	// themselves incurred (e.g. extract:code's Starlark-writer calls) — the CG
	// components' OWN cost, separate from the agent. Priced externally.
	LLMCalls        int64 `json:"llm_calls"`
	LLMInputTokens  int64 `json:"llm_input_tokens"`
	LLMOutputTokens int64 `json:"llm_output_tokens"`
	// LLMTimeouts/LLMErrors make the FAIL-OPEN PATH VISIBLE. A component that
	// abandons its model call leaves the output verbatim (correct — compaction must
	// never break the agent's request) but reports nothing, so an arm that quietly
	// stops compacting under load looks like an arm that got faster. MEASURED on a
	// KV-pressured on-prem server: llm_calls fell 2,093 -> 255 at equal request
	// volume while per-request overhead ROSE 55%, and the resulting "42-point
	// improvement" was the treatment partially switching itself off.
	//
	// Read them together with LLMCallTimeoutMs: a non-zero timeout count means the
	// budget is too small for the server's current load, and this arm's savings are
	// an UNDERCOUNT rather than a measurement. Filled by the host at serve time
	// (offload owns the deadline and lives below metrics), same as the Frozen* fields.
	LLMTimeouts      int64 `json:"llm_timeouts"`
	LLMErrors        int64 `json:"llm_errors"`
	LLMCallTimeoutMs int64 `json:"llm_call_timeout_ms"`
	// LLMTruncated counts replies that stopped at the model's output cap. Its own figure
	// because it is the failure whose fix is a config change rather than a decision to stop
	// calling, and because it was previously invisible: a truncated program parses as
	// nothing, which is indistinguishable from a model that declined to compact. It is the
	// worst outcome available — full price, zero result — and it was happening.
	LLMTruncated int64 `json:"llm_truncated"`
	// Summarize* are the same three figures for `summarize`, which owns a SEPARATE
	// budget (its call is one big span, not one tool output, so the two cannot share a
	// ceiling). Reported separately rather than folded into LLM* above because the
	// components run in different arms: a summarize-only pipeline would otherwise
	// report llm_timeouts 0 with its own deadline expiring on every request.
	//
	// summarize's failure is already visible as a per-component `reverted`, but that
	// cannot distinguish "budget too small for this load" (savings are an undercount)
	// from "the model call is failing" (the arm is not measuring summarization at all).
	SummarizeTimeouts      int64 `json:"summarize_timeouts"`
	SummarizeErrors        int64 `json:"summarize_errors"`
	SummarizeCallTimeoutMs int64 `json:"summarize_call_timeout_ms"`
	// SummarizeAsync* are the health of the DETACHED summarizer path, and they exist because that
	// path removed every other way to see it. When the call was inline, a slow or failing summarizer
	// showed up as request latency, as a `reverted` component, and in that request's own row. Off
	// the hot path it shows up nowhere: the request has already been answered, and no row carries
	// the work until the session's next turn.
	//
	// The pair that matters is Started vs Committed. A growing gap means calls are being paid for
	// and lost — the only signal that exists for it. Refused counts what the GLOBAL bound turned
	// away (the deployment shedding compaction under load, distinct from the ordinary per-session
	// single-flight refusal, which is a gate). Unresolved is how many are outstanding right now.
	//
	// WaitedMs and WaitTimeouts are the other half: whether the wait cap is set anywhere near
	// right. A climbing timeout count means turns are paying the full cap and getting nothing,
	// which is the case for lowering it or for looking at the summarizer.
	SummarizeAsyncStarted    int64 `json:"summarize_async_started"`
	SummarizeAsyncCommitted  int64 `json:"summarize_async_committed"`
	SummarizeAsyncRefused    int64 `json:"summarize_async_refused"`
	SummarizeAsyncUnresolved int64 `json:"summarize_async_unresolved"`
	// SummarizeAsyncPanics counts recovered panics in the detached goroutine. Fail-open is right
	// there — a panic in a detached goroutine would otherwise take the process down — but the
	// recover() was silent, so a panicking summarizer showed up only as a growing started/committed
	// gap and nothing named the cause.
	SummarizeAsyncPanics      int64 `json:"summarize_async_panics"`
	SummarizeAwaitedMs        int64 `json:"summarize_awaited_ms"`
	SummarizeAwaitTimeouts    int64 `json:"summarize_await_timeouts"`
	SummarizeAsyncConcurrency int64 `json:"summarize_async_concurrency"`
	// AgentDiet* are the same three figures for the `agentdiet` baseline, which owns a
	// third budget: its prompt is a window of b+1+a serialized steps, so it sits
	// between extract_llm's single tool output and summarize's whole span. Reported
	// separately for the same reason as summarize — it runs in its own arm, so folding
	// it into LLM* would show llm_timeouts 0 while every reflection call expired.
	AgentDietTimeouts      int64 `json:"agentdiet_timeouts"`
	AgentDietErrors        int64 `json:"agentdiet_errors"`
	AgentDietCallTimeoutMs int64 `json:"agentdiet_call_timeout_ms"`
	// CacheAwareSummarizer* are cache_aware_summarizer's. That method's whole claim is WHERE the
	// summarization request is built — the conversation plus an appended instruction, so the
	// backend recognises a prefix it already has — which makes its cost profile different in
	// kind from the summarizers it is compared against. Folding it into theirs would report the
	// baseline's numbers for the treatment.
	//
	// ⭐ CacheAwareSummarizerDeclined IS THE LOAD-BEARING ONE. The component refuses to run when
	// no components.MessagesModel is available, because the alternative — flattening the
	// conversation into one prompt string — is precisely the prefix-destroying shape it exists to
	// avoid. A declining arm therefore compacts NOTHING and is byte-identical to `off` on every
	// other field in this struct. Non-zero means that arm measured nothing.
	CacheAwareSummarizerCalls         int64 `json:"cache_aware_summarizer_calls"`
	CacheAwareSummarizerTimeouts      int64 `json:"cache_aware_summarizer_timeouts"`
	CacheAwareSummarizerErrors        int64 `json:"cache_aware_summarizer_errors"`
	CacheAwareSummarizerDeclined      int64 `json:"cache_aware_summarizer_declined"`
	CacheAwareSummarizerCallTimeoutMs int64 `json:"cache_aware_summarizer_call_timeout_ms"`
	// a call was PAID FOR and returned nothing usable — the signature of an instruction the chat template dropped or hoisted, which is the silent failure the model registry exists to prevent
	CacheAwareSummarizerEmpty int64 `json:"cache_aware_summarizer_empty"`
	// declined because instruction_role was pinned to `system` for a model no registry profile verifies; the arm is configured for a silent failure and is refusing to take it
	CacheAwareSummarizerUnverifiedSystem int64 `json:"cache_aware_summarizer_unverified_system"`
	// a summary was abandoned because the store would not accept the span; a marker with no stash behind it would be a lossy Offload advertising reversibility it does not have
	CacheAwareSummarizerRefusedStash int64 `json:"cache_aware_summarizer_refused_stash"`
	// declined because the outbound request would exceed max_request_tokens; the session outgrew the method rather than anything failing
	CacheAwareSummarizerTooLarge int64 `json:"cache_aware_summarizer_too_large"`
	// the profiles_path override could not be read, so the EMBEDDED registry was used instead; the
	// instruction roles this arm resolved are not the ones the deployment pinned
	CacheAwareSummarizerProfileFallbacks int64 `json:"cache_aware_summarizer_profile_fallbacks"`
	// detached summaries commissioned
	CacheAwareSummarizerAsyncStarted int64 `json:"cache_aware_summarizer_async_started"`
	// detached summaries that reached a checkpoint. The PAIR is the signal: started without committed is a summary paid for and lost
	CacheAwareSummarizerAsyncCommitted int64 `json:"cache_aware_summarizer_async_committed"`

	// Extract is extract_llm's own economics (#28 part F), including NET savings after
	// its LLM cost — the honest headline for the one component that spends to save.
	// Purely ADDITIVE: no field above was renamed or removed, so deploy/harbor/*.py
	// keeps parsing /stats unchanged.
	Extract *ExtractStats `json:"extract,omitempty"`
	// End-to-end latency (W7): mean ms context-guru added per request, and mean
	// provider round-trip on the active vs bypassed (baseline) path — a with/without
	// context-guru session-latency comparison.
	AddedLatencyMsAvg     float64 `json:"cg_added_ms_avg"`
	UpstreamMsAvg         float64 `json:"upstream_ms_avg"`
	UpstreamMsAvgBypassed float64 `json:"upstream_ms_avg_bypassed"`
	// SSE streaming health (#26). SSEBuffered counts streams context-guru had to read
	// in full before the client saw a byte (to look for an expand tool call); those
	// requests lose streaming entirely, so their TTFB is reported separately. A high
	// buffered share on traffic that never expands is the regression to watch. All four
	// count once per CLIENT REQUEST, not per upstream round: a request that drove
	// several expand rounds waited for all of them.
	SSEStreamed  int64   `json:"sse_streamed"`
	SSEBuffered  int64   `json:"sse_buffered"`
	SSETTFBMsAvg float64 `json:"sse_ttfb_ms_avg"` // streamed-through requests: a real TTFB
	// SSETTFBMsAvgBuf is time-to-LAST-byte by construction, not a comparable TTFB: a
	// buffered response is read in full before the client is written to, so its first
	// byte cannot precede the buffer completing. Read it as "what buffering cost these
	// requests", not as a latency to compare against sse_ttfb_ms_avg.
	SSETTFBMsAvgBuf float64 `json:"sse_ttfb_ms_avg_buffered"`
	SSEBufferedPct  float64 `json:"sse_buffered_pct"`
	// SSEExpandAfterStream counts responses whose expand call reached the CLIENT anyway —
	// batched with a client tool, past the round cap, past the retain bound, or in a dialect
	// that cannot be reconstructed. See Aggregator.RecordSSEExpandAfterStream.
	SSEExpandAfterStream int64 `json:"sse_expand_after_stream"`
	// Freeze-replay health — the cache-WRITE cost line. A frozen decision replayed
	// (frozen_hits) keeps an already-cached message byte-identical. A decision the store
	// DROPS (frozen_dropped: TTL expiry / pin cap) would flip that message's
	// representation and force the provider to re-write the whole suffix at 11.5x the
	// read price — unless it is re-derived (frozen_repaired). frozen_flips =
	// dropped − repaired is the count that actually cost cache-writes; it should be 0.
	// frozen_misses counts every replay lookup that found nothing, which is dominated by
	// the normal "never frozen yet" case — read it beside frozen_dropped, not instead.
	// Filled by the host at serve time (offload + store live below metrics).
	FrozenHits     int64 `json:"frozen_hits"`
	FrozenMisses   int64 `json:"frozen_misses"`
	FrozenDropped  int64 `json:"frozen_dropped"`
	FrozenRepaired int64 `json:"frozen_repaired"`
	FrozenFlips    int64 `json:"frozen_flips"`
	// Rewind-reserve health — the REVERSIBILITY cost line, and the leading indicator for
	// expand_unresolved_missing. That counter can only move when the agent happens to ask
	// for removed content, so a run whose store could no longer hold payloads read as
	// perfectly healthy until it did (#187: 209 failed expands in one benchmark arm, 0 in
	// the arm where the sweep was inert).
	//
	// StashRefused counts removals DECLINED because the reserve was full: content left
	// verbatim, nothing became irreversible, and the fix is a larger max_entries (or
	// stash_max_bytes — read Bytes against MaxBytes to see which budget bound).
	//
	// StashMissing is the OPPOSITE outcome and must not be read as a refusal: a marker was
	// replayed with no payload behind it, so a dangling marker went out on the wire. It is the
	// one case here that genuinely breaks reversibility. The two shared a counter until the
	// #188 review, which meant the number an operator watches to confirm nothing broke was
	// being incremented by things breaking. It also grows with TURN COUNT rather than with
	// distinct broken markers — a missing payload cannot be restored, so every later turn
	// re-reports it for every affected message.
	//
	// StashExpired counts payloads the TTL reclaimed. Payloads have their OWN, shorter TTL
	// (stash_ttl_seconds) because a payload — unlike a frozen decision — is re-derivable from
	// the transcript: every turn's replay re-writes it, so a reclaimed one is re-created on the
	// request path before any expand could ask for it (see store.DefaultStashTTL, #190).
	//
	// StashRevived is that absorption, counted: a payload written again under a key the TTL had
	// taken. It is why StashExpired is not itself an alert — Expired without Revived is a
	// session that never came back, which is the reclamation working. What breaks the promise is
	// StashMissing, and the remedy for a rising StashMissing is stash_ttl_seconds (the payload
	// was reclaimed too eagerly) or a larger reserve (the re-stash was refused) — read Live
	// against Capacity and Bytes against MaxBytes to tell which.
	//
	// BOTH AT ZERO IS NOT EVIDENCE THAT THE HORIZON WORKS. It means the reserve never bound.
	// sweepExpired runs only from StashRoom, PutStash's pre-refusal path and evictOldest — i.e.
	// only once the reserve, the shared exempt budget or the entry cap is already binding — and
	// PutStash's refresh branch does not check expiry, so on an unsaturated run an
	// expired-but-unswept payload is resurrected in place and NEITHER counter moves. That is the
	// intended behaviour (a slot is released when a slot is wanted), but it means a run must
	// actually saturate the reserve before this pair says anything, which is the same precondition
	// iteration 024 failed to meet for stash_refused — and failing it is how #190 became
	// undecidable from data. What distinguishes "never bound" from "working" is StashRefused and
	// StashLive against StashCapacity.
	// Filled by the host at serve time (offload + store live below metrics).
	// UsageUnparsed and UsageUnreadable are the two ways this proxy failed to ACCOUNT a response
	// it otherwise served perfectly: the provider sent a usage block in a spelling the parser does
	// not recognise, or the bytes examined were not a whole document (a spliced sniffer window).
	// Either way fresh_input_tokens / cache_read_tokens / cache_write_tokens read 0 on a healthy
	// 200 with correct savings, correct latency and correct everything else — which ran for 4,015
	// of 4,015 requests in one benchmark iteration and was found two iterations later, in a
	// post-mortem chasing a different question (#200).
	//
	// Counted apart because the REMEDIES are opposite — add the dialect vs. stop truncating the
	// window — and kept out of the benign cases (a provider that genuinely reported no usage, and
	// a recognised block whose tiers are all zero), which are reported as `usage_miss` on the
	// lifecycle log line and are not alertable. Filled by the host at serve time.
	UsageUnparsed   int64 `json:"usage_unparsed"`
	UsageUnreadable int64 `json:"usage_unreadable"`
	StashRefused    int64 `json:"stash_refused"`
	StashMissing    int64 `json:"stash_missing"`
	StashExpired    int64 `json:"stash_expired"`
	StashRevived    int64 `json:"stash_revived"`
	StashLive       int   `json:"stash_live"`
	StashCapacity   int   `json:"stash_capacity"`
	StashBytes      int64 `json:"stash_bytes"`
	StashMaxBytes   int64 `json:"stash_max_bytes"`
	// ExpandPrefixFlips counts turns where an ESTABLISHED compaction was abandoned because the
	// agent had expanded that content: a frozen decision existed, so the provider holds the
	// compacted bytes, and the turn sends the original in full at the same position. That is a
	// cache-write of the whole suffix at ~11.5x a read — the cost the cache-tail gate exists to
	// avoid everywhere else — and until now no counter distinguished it from any other cache-write,
	// so an operator could not see it and a benchmark could not attribute it (#201).
	//
	// It is a DELIBERATE cost, not a defect: re-compacting would bounce the agent into another
	// expand, and one cache-write is cheaper than an unbounded loop. This makes the trade visible
	// rather than assumed.
	//
	// Per turn per message, not per distinct content — every later turn re-sends the same original
	// and re-observes the same abandonment, and only the FIRST is a real cache-write. Read it as
	// "expansion is churning cached prefixes here", not as a count of cache-writes. Filled by the
	// host at serve time (the counter lives in components/offload).
	//
	// IT COUNTS ONE EVENT, not every expand-induced cache-write: a REPLAY DECLINED because the
	// content was expanded (components/offload.reapplyFrozen, its only increment site). At least one
	// sibling is not counted — protecting expanded content shortens summarize's span, which can
	// invalidate a checkpoint whose boundary reached past it, and re-summarizing produces different
	// summary text at a fixed prefix position, i.e. another suffix cache-write. That is the correct
	// trade (content loss for one cache-write) and the same class of event, but a second increment
	// site would change what this number means, so it is deliberately left to its own decision. Do
	// not read a zero here as "expansion cost nothing".
	ExpandPrefixFlips int64 `json:"expand_prefix_flips"`
	// CompactionResets counts turns whose cached-prefix boundary restarted because the
	// AGENT compacted its own transcript (it shrank under a stable session id). The
	// session id deliberately survives that compaction so one conversation is one
	// session in the dashboard — which means the boundary is the only thing left that can
	// notice, and if it does not, every message of every later turn is treated as already
	// cached and no component can act for the rest of the session. So this is the counter
	// that says "these sessions restarted their prefix N times"; a long run with real
	// auto-compaction should be non-zero, and a run where it stays 0 while savings fall
	// off a cliff mid-session is the regression it exists to expose. Filled by the host at
	// serve time (the counter lives in `modes`, which metrics cannot import).
	CompactionResets int64 `json:"compaction_resets"`
	// cmdfilter attribution: which command FAMILIES pay off (builds/tests/iac/pkg/net),
	// which individual filters fire, and which output shapes matched no filter (the
	// backlog of filters worth writing). Additive fields — nothing above is renamed.
	CmdfilterFamilies map[string]filterStat `json:"cmdfilter_families,omitempty"`
	CmdfilterFilters  map[string]filterStat `json:"cmdfilter_filters,omitempty"`
	CmdfilterMisses   []SelectorMiss        `json:"cmdfilter_selector_misses,omitempty"`

	// Mode is the configured operating mode ("sync" | "observe").
	Mode string `json:"mode"`
	// SyncEnforced counts requests whose forwarded body context-guru actually shaped. In
	// observe mode it is 0 BY CONSTRUCTION — that is the machine-readable form of
	// "context-guru did not modify requests".
	SyncEnforced int64 `json:"sync_enforced"`

	// Observe mode: HYPOTHETICALS. Distinct keys (potential_* / projected_*) that never
	// share a name with an enforced metric, so a consumer cannot sum a hypothetical into a
	// real saving even by accident. All zero outside observe mode.
	ObserveNotice            string              `json:"observe_notice,omitempty"`
	ObserveRequests          int64               `json:"observe_hypothetical_requests"`
	ActualBaselineTokens     int64               `json:"actual_baseline_tokens"`     // what the agent really sent
	ProjectedOptimizedTokens int64               `json:"projected_optimized_tokens"` // what it would have sent
	PotentialSavedTokens     int64               `json:"potential_saved_tokens"`
	PotentialSavingsPct      float64             `json:"potential_savings_pct"`
	PotentialComponents      map[string]compStat `json:"potential_components,omitempty"`
	// PotentialOverheadMsAvg is the mean wall time a compaction WOULD have added to each
	// request had this mode been enforcing — measured off-path, so it is what sync would
	// cost, not what observe costs.
	PotentialOverheadMsAvg float64 `json:"potential_overhead_ms_avg"`
	// ObserveLLMNotice warns that context-guru's own model spend (llm_calls /
	// llm_input_tokens / llm_output_tokens, which feed cg_llm_cost in the harnesses) is
	// OFF-PATH measurement cost in observe mode, not the cost of an enforced compaction.
	// The tokens were really spent — the number is not hypothetical and must not be moved
	// into the potential_* namespace — but attributing it to enforcement would be wrong.
	// cg_added_ms_avg is likewise a real measurement of the enforced path, and in observe
	// mode it correctly reads ~0 because that path does no pipeline work. Zeroing either
	// would hide a true number rather than protect anyone.
	ObserveLLMNotice string `json:"observe_llm_notice,omitempty"`

	// ObserveQueue is the off-path worker pool's counter tuple, filled by the host at
	// serve time (the pool lives in `modes`, which sits above this package). All five
	// counters are exposed rather than just `queued` because `dropped` is the one that
	// changes a reader's conclusion: a drop is an observation silently given up, so a
	// rising `dropped` means the potential_*/projected_* figures UNDERSTATE what
	// compaction would have saved. Reporting the queue depth while hiding the drops is
	// exactly the gap noted in headroom's dashboard. Omitted when no pool is running, so
	// a sync-only deployment shows no phantom queue.
	ObserveQueue *QueueStats `json:"observe_queue,omitempty"`

	// KeepAlive is the idle prompt-cache keep-alive's ledger, filled by the host (the
	// mechanism lives in `proxy` because it acts between requests, which is above this
	// layer). Omitted entirely when nothing has opted in, so a deployment that does not use
	// it shows no field rather than a row of zeroes.
	KeepAlive any `json:"keepalive,omitempty"`

	// Savings is /stats' reconciled, DB-backed savings figure — dash.SavingsTotals summed
	// three ways (current session / live sessions / all-time), filled by the host (the
	// query lives in `dash`, which sits above this package). Omitted entirely on a hosted
	// deployment or a proxy with no dashboard, same reasoning as KeepAlive above.
	Savings any `json:"savings,omitempty"`

	// Provider-billed token tiers (W8), summed from response usage. ADDITIVE: the
	// benchmark harnesses parse this payload, so fields are only ever added here,
	// never renamed or removed (see the golden shape test).
	FreshInputTokens int64 `json:"fresh_input_tokens"`
	CacheReadTokens  int64 `json:"cache_read_tokens"`
	CacheWriteTokens int64 `json:"cache_write_tokens"`
	OutputTokens     int64 `json:"output_tokens"`
	// AttemptedTokens is what compaction was ALLOWED to touch; FrozenTokens is what
	// cache-awareness deliberately left alone. SavingsPctAttempted divides savings
	// by the former — the honest ratio, since SavingsPct's whole-request denominator
	// recounts the transcript every turn and trends to ~0% on a long session.
	AttemptedTokens int64 `json:"attempted_tokens"`
	FrozenTokens    int64 `json:"frozen_tokens"`
	// SavingsPctAttempted = saved / attempted. 0 when nothing was attempted.
	SavingsPctAttempted float64 `json:"savings_pct_attempted"`
	// SavingsPctNewInput = saved / (fresh + cache_write + saved): savings as a
	// fraction of what would have newly entered the provider. 0 (not 100) when the
	// provider reported no usage — savings must never be divided by themselves.
	SavingsPctNewInput float64 `json:"savings_pct_new_input"`
}

Snapshot is the JSON served at /stats. It reports both gross savings and the honest, bounce-adjusted figure, plus quality signals naming components that never earned their place (rtk's top_passthrough idea).

type Tee

type Tee []components.Emitter

Tee fans a report out to several emitters.

func (Tee) Component

func (t Tee) Component(r components.Report)

func (Tee) FilterAct added in v0.1.1

func (t Tee) FilterAct(family, filter, contentKey string, saved int)

FilterAct / FilterMiss forward cmdfilter's ledger to whichever tee'd emitters record it (so a Tee still satisfies components.FilterStatsSink).

func (Tee) FilterMiss added in v0.1.1

func (t Tee) FilterMiss(selector string)

func (Tee) Run

func (t Tee) Run(r components.RunReport)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL