offload

package
v0.7.5-beta.2 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: Apache-2.0 Imports: 40 Imported by: 2 modules, 1 package

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 offload holds the lossy-but-reversible components (they drop bytes and stash the original for the expand tool loop). Each registers itself via init(); a binary blank-imports components/all to pull them in.

Index

Constants

View Source
const (
	RefreshCostExtra = "extra"
	RefreshCostFull  = "full"
)

Values of the cache_aware_summarizer option refresh_cost.

View Source
const (
	// RecheckConversationShorter: the request has fewer messages than when the question was asked.
	// The agent rewound, ran /compact or /clear. Every verdict is void.
	RecheckConversationShorter = "conversation_shorter"
	// RecheckOutputGone: no tool message with the judged id is in the request any more.
	RecheckOutputGone = "output_gone"
	// RecheckContentChanged: the message with that id is there but its bytes differ from the ones
	// that were judged.
	RecheckContentChanged = "content_changed"
	// RecheckReferenced: a turn AFTER the question was asked reused something the output introduced.
	// The model judged before that turn existed.
	RecheckReferenced = "referenced_later"
	// RecheckExpanded: the agent asked for this content back (it is marked kept-verbatim, or a fixed
	// restore anchors it). Dropping it again would only trigger another expansion.
	RecheckExpanded = "expanded"
)

Why a drop verdict was dropped. These are the suffixes of the sweep_shadow_dropped_* events.

View Source
const (
	// GateAlreadyMarked: this content already carries an offload marker, so reducing again would
	// double-compact and can orphan the earlier stash. Benign — nothing flips.
	GateAlreadyMarked = "already_marked"
	// GateKeptVerbatim: the agent expanded this content, so it must not be re-compacted (that
	// would bounce it straight into another expand). The turn this first appears is the turn the
	// message reverts to its full form inside the cached prefix — see ExpandPrefixFlips.
	GateKeptVerbatim = "kept_verbatim_after_expand"
)

The two gate labels skipReduce distinguishes, named constants because eleven offloaders raise them and a typo in one would silently split a counter in two.

View Source
const (
	// EventFreshSummary marks a turn that PAID for a summary: a model call was made, a
	// checkpoint was written, and the transcript was restructured around new bytes. It is the
	// t0 of a compaction episode.
	EventFreshSummary = "fresh_summary"
	// The three replay names — a turn that re-emitted an existing checkpoint for free. Each
	// says WHY the replay happened, which is the operator-facing distinction: the trigger
	// permitted this turn and the tail had not grown (reused), the trigger declined it
	// (gated), or the store's rewind reserve refused a new stash (reserve exhausted).
	EventReusedCheckpoint                   = "reused_checkpoint"
	EventGatedReplayedCheckpoint            = "gated_replayed_checkpoint"
	EventReserveExhaustedReplayedCheckpoint = "reserve_exhausted_replayed_checkpoint"
	// EventSummaryStarted marks a turn that COMMISSIONED a summary without waiting for it. The
	// spend is committed here; the summary lands (or does not) on its own, and EventFreshSummary
	// is filed by the goroutine that commits it. Two names because a started-and-lost call is a
	// real outcome that must not read as a delivered summary.
	EventSummaryStarted = "summary_started"
	// EventSummaryDeferredToStash marks a cache_aware_summarizer prefix-ask commission held until
	// the host has stashed this turn's body, then started from the host's hook (#722).
	EventSummaryDeferredToStash = "summary_deferred_to_stash"
	// EventAwaitedCheckpoint marks a turn that WAITED for a summary an earlier turn started and
	// then spliced it. Distinct from EventReusedCheckpoint because this one cost latency: it is
	// the turn that paid for the async design, and the pair (awaited, summary_wait_timeout) is
	// what says whether the wait cap is set anywhere near right.
	EventAwaitedCheckpoint = "awaited_checkpoint"
)

The four names summarize files on Report.Events. Promoted to constants because a SECOND package now keys on them: the dashboard's compaction-episode walk (dash/compactepisode.go) identifies a fresh summary as an act carrying EventFreshSummary and a replay as one carrying any of the other three. A renamed string here would leave that walk matching nothing and reporting zero episodes — a silent zero, which is the failure mode this repo has already paid for twice (see Report.Replays on #176).

Variables

View Source
var ErrSummaryDidNotLand = errors.New("no summary landed within the deadline")

ErrSummaryDidNotLand is what a test helper returns when a summary never arrived, so a failure message can say that rather than reporting a confusing downstream symptom.

Functions

func AgentDietCallTimeout added in v0.1.1

func AgentDietCallTimeout() time.Duration

AgentDietCallTimeout exposes the resolved per-call budget, so /stats can report it beside the counters (a timeout count means nothing without the budget it hit).

func AgentDietErrors added in v0.1.1

func AgentDietErrors() int64

AgentDietErrors returns non-timeout reflection failures (transport, HTTP status, unparseable reply, cancelled parent request).

func AgentDietTimeouts added in v0.1.1

func AgentDietTimeouts() int64

AgentDietTimeouts returns the reflection calls abandoned on the per-call deadline. Non-zero means CONTEXT_GURU_AGENTDIET_TIMEOUT is too small for the server's load, and this arm's savings are an undercount rather than a measurement.

func AsyncSummaryStats added in v0.2.0

func AsyncSummaryStats() (started, committed, waitedMs, waitTimeouts, refused, unresolved, panics int64)

AsyncSummaryStats reports the async path's counters for /stats.

func CacheAwareAsyncStats added in v0.2.0

func CacheAwareAsyncStats() (started, committed, refused, panics int64)

CacheAwareAsyncStats returns (started, committed, refused, panics). The PAIR is the signal: started without committed is a summary that was paid for and lost, which no other counter here would reveal. Refused is the global bound shedding compaction under load rather than queueing a call nobody is waiting for.

func CacheAwareColdDeferralStats added in v0.5.0

func CacheAwareColdDeferralStats() (started, resolved, fallbackFired, dropped int64)

CacheAwareColdDeferralStats reports the cold-deferral registry's counters for /stats.

func CacheAwareSummarizerCacheTokens added in v0.5.0

func CacheAwareSummarizerCacheTokens() (read, write int64)

CacheAwareSummarizerCacheTokens returns the cumulative cache-read/cache-write tokens of every commission call this component has made, across every trigger and path.

func CacheAwareSummarizerCallTimeout added in v0.2.0

func CacheAwareSummarizerCallTimeout() time.Duration

func CacheAwareSummarizerCalls added in v0.2.0

func CacheAwareSummarizerCalls() int64

func CacheAwareSummarizerCoordsShifted added in v0.6.2

func CacheAwareSummarizerCoordsShifted() int64

func CacheAwareSummarizerDeclined added in v0.2.0

func CacheAwareSummarizerDeclined() int64

CacheAwareSummarizerDeclined counts turns that reached the model step and stopped because NEITHER a components.MessagesModel NOR a components.PrefixAsker was available. A role the backend rejects returns an error and lands in Errors, not here. Non-zero means this arm is not measuring cache-reuse compaction on those turns; it is measuring `off` — though a deployment may still be compacting plenty of OTHER turns via PrefixAsk (CacheAwareSummarizerPrefixAskUsed) at the same time, which this counter alone cannot distinguish from total inertness.

func CacheAwareSummarizerEmpty added in v0.2.0

func CacheAwareSummarizerEmpty() int64

CacheAwareSummarizerEmpty counts calls that were PAID FOR and returned nothing usable. It is the signature of the silent failure the profile registry guards against: an instruction the template dropped or hoisted, so the model answered the conversation instead of the request.

func CacheAwareSummarizerErrors added in v0.2.0

func CacheAwareSummarizerErrors() int64

func CacheAwareSummarizerNoPrefix added in v0.5.0

func CacheAwareSummarizerNoPrefix() int64

func CacheAwareSummarizerPrefixAskUsed added in v0.5.0

func CacheAwareSummarizerPrefixAskUsed() int64

func CacheAwareSummarizerProfileFallbacks added in v0.2.0

func CacheAwareSummarizerProfileFallbacks() int64

CacheAwareSummarizerProfileFallbacks counts turns that fell back to the embedded registry because profiles_path was unreadable or unparseable.

func CacheAwareSummarizerRefusedStash added in v0.2.0

func CacheAwareSummarizerRefusedStash() int64

CacheAwareSummarizerRefusedStash counts summaries abandoned because the store would not accept the span. The splice is skipped rather than completed, because a marker promising a span the store never took is a lossy Offload advertising reversibility it does not have.

func CacheAwareSummarizerStalePrefix added in v0.5.0

func CacheAwareSummarizerStalePrefix() int64

func CacheAwareSummarizerThinkingWouldStrip added in v0.5.0

func CacheAwareSummarizerThinkingWouldStrip() int64

func CacheAwareSummarizerTimeouts added in v0.2.0

func CacheAwareSummarizerTimeouts() int64

func CacheAwareSummarizerTooLarge added in v0.2.0

func CacheAwareSummarizerTooLarge() int64

CacheAwareSummarizerTooLarge counts turns declined because the outbound request would have exceeded max_request_tokens. Non-zero means this session outgrew the method rather than that anything failed.

func CacheAwareSummarizerTruncated added in v0.5.0

func CacheAwareSummarizerTruncated() int64

func CacheAwareSummarizerUnverifiedSystem added in v0.2.0

func CacheAwareSummarizerUnverifiedSystem() int64

CacheAwareSummarizerUnverifiedSystem counts turns declined because instruction_role was pinned to `system` for a model no registry profile marks as accepting a trailing system message. Non-zero means the arm is configured for a silent failure and is refusing to take it.

func CacheAwareWarmDeferralStats added in v0.6.0

func CacheAwareWarmDeferralStats() (started, resolved, replaced, fallback, full, refused, skippedDup int64)

CacheAwareWarmDeferralStats reports the warm-deferral counters, in the order of the vars above.

func ClaimThread added in v0.7.2

func ClaimThread(threadKey string) (release func(), ok bool)

ClaimThread takes the thread's ping guard and nothing else: the warm path's question (#491) runs under it, so a warm question and a ping substitute of one thread never run together. ok=false means another call holds the thread (counted as sweep_ping_thread_busy by the ping side; the warm side counts its own). release must be called when the question ends.

func ClearKeepAliveCandidate added in v0.5.0

func ClearKeepAliveCandidate(session string)

ClearKeepAliveCandidate drops a session's registered substitute material unconditionally. Test-only: a real caller on the request path must use ClearStaleKeepAliveCandidate instead — see that function's own comment for why an unconditional clear on every real request made keep-alive substitution impossible in practice (every request cleared the very candidate its own pipeline run had just registered, a few lines earlier in the same call).

func ClearStaleKeepAliveCandidate added in v0.5.0

func ClearStaleKeepAliveCandidate(session string, requestStartedAt time.Time)

ClearStaleKeepAliveCandidate drops session's registered substitute material ONLY IF it was registered before requestStartedAt — i.e. by an EARLIER request's pipeline run, not by this one. The proxy calls this once a real request's own pipeline has run (so cache_aware_summarizer has already had its chance to register this turn's material) and tr.Session is known, passing the wall-clock instant it captured BEFORE running the pipeline.

WHY TIMESTAMP-BASED, NOT CALL-ORDER-BASED. The proxy cannot call this BEFORE the pipeline runs: the pipeline is what resolves tr.Session (session.Scoped, off the request's own tenant/header/ body), so the key this function would need to clear by is not known yet at that point. Calling it AFTER the pipeline with an unconditional delete (the bug this function replaces) deletes whatever the pipeline's own run just wrote, a few lines earlier in the exact same request — cache_aware_summarizer's registration and the "drop a superseded one" cleanup were racing each other within a single, synchronous call stack, and the cleanup always won. A timestamp comparison needs no key resolved in advance: requestStartedAt is captured the instant this request began, trivially available before the pipeline runs, and a candidate's own registeredAt field (set the moment registerKeepAliveCandidate writes it) answers "was this written by code that ran before or after that instant" without the caller ever needing to name the session before now.

A registration from a CONCURRENT request for the same session (two requests on one session racing each other) can register after requestStartedAt was captured but before this call runs — that candidate's registeredAt is then >= requestStartedAt and survives, which is correct: it is not stale, it is simply newer than the request now doing the clearing.

func ColdApplyPhase added in v0.6.0

func ColdApplyPhase(p components.CachePhase) bool

ColdApplyPhase is the shared answer to "may a held result be applied to this request?" (#404). The summary reserve graduates on it (cacheAwareApplyPhase), and the sweep's cold apply must use the same test: a cold or untracked cache, where the rewrite is already paid for. PR C calls this.

func DropRecordsForTest added in v0.7.2

func DropRecordsForTest(st store.Store, threadKey string) int

DropRecordsForTest is how many drop records the sweep has written for a thread, from its own drop index.

func ExpandPrefixFlips added in v0.2.0

func ExpandPrefixFlips() int64

ExpandPrefixFlips returns how many times a replay declined because the agent had expanded content that WAS compacted before. Non-zero means expansion is re-writing cached prefixes; see expandFlips for why it is per turn per message rather than per distinct content.

func FrozenStats added in v0.1.1

func FrozenStats() (hits, misses int64)

FrozenStats returns the cumulative freeze-replay hits and misses since process start. Exported for the host's /stats, which pairs them with the store's drop/repair counts.

func HasSweepPingCandidate added in v0.6.4

func HasSweepPingCandidate(threadKey string) bool

HasSweepPingCandidate reports whether the sweep holds a registration for threadKey. The keeper reads it before an extra sweep question (#776), which goes out only when there is something to ask.

func HeldSweepAnswerForTest added in v0.6.0

func HeldSweepAnswerForTest(st store.Store, threadKey string) (asked, proposed int, waitingFor string, ok bool)

HeldSweepAnswerForTest reports a thread's held answer in the shape a test can assert on, without exporting the record: how many outputs the question judged, how many it proposed to drop, and the wait cause stored with it.

func KeepAliveCandidateState added in v0.6.4

func KeepAliveCandidateState(threadKey string) (cacheState string, preExpirySeconds int, ok bool)

KeepAliveCandidateState reports the cache_state and pre_expiry_seconds of the summarizer's keep-alive candidate for threadKey, and whether one is registered. It reads the registration only: no checkpoint, no content. The keeper uses it to place the summary's extra request (#776).

func KeepAliveSubstitute added in v0.5.0

func KeepAliveSubstitute(session string) (dispatch func(timeout time.Duration) KeepAliveSummaryResult, info KeepAliveCandidateInfo, reason KeepAliveSubstituteReason, ok bool)

KeepAliveSubstitute reports whether a session has commission material the idle keep-alive may use instead of a bare ping, and a Dispatch function to run it.

ok=false means fall back to an ordinary ping either way, but reason now says WHY — see KeepAliveSubstituteReason. Dispatch's own in-flight/concurrency refusal cannot be known at lookup time (it is checked inside Dispatch itself, via the shared single-flight registry), so that is reported on KeepAliveSummaryResult.Reason instead, once Dispatch has actually run.

Dispatch BLOCKS until the call resolves (or the given timeout elapses) and runs the real model call — the keeper's caller must therefore run it off its own goroutine, exactly as it already does for an ordinary ping.

info is returned alongside ok=true so the caller can additionally check cache_state against its OWN timing before deciding to dispatch — see KeepAliveCandidateInfo.

AN EXISTING CHECKPOINT REFUSES SUBSTITUTION, UNLESS IT IS A `pre_expiry` RESERVE WITH SOMETHING NEW TO FOLD IN. For `any` — "no combination wastes calls: with any, keep today's behaviour exactly" — any existing checkpoint refuses, unconditionally, precisely as before: the next real turn splices it for free, so a call here would summarize a span nobody is waiting on. For `pre_expiry`, a reserve with an empty tail refuses the same way (there is nothing to gain from paying for a summary identical to the one already held); a reserve with ANY nonempty tail is offered to the caller as `info.IsRefresh` with `info.RefreshTailTokens` set, for fireSummarySubstitute's own money gate (issue #415) to weigh against the call's cost before actually dispatching — this function does not itself decide whether that tail is "enough".

func KeptVerbatim added in v0.1.1

func KeptVerbatim(st store.Store, session, original string) bool

KeptVerbatim reports whether this content has already been marked in THIS session. The expand repair reads it to charge a restored original to the dashboard ONCE: the client keeps its own copy of the error, so the same repair runs on every later turn, and counting each one drives the headline savings arbitrarily negative (ExpandTokens is subtracted from a unique-counted total, so the units do not even match).

It is session-scoped like the mark, and that is a choice (#175): the dashboard row is per session, so a second session that gets the same bytes back is a second recovery and is charged. A global "counted" flag would charge it to the first session only.

func LLMCallTimeout added in v0.1.1

func LLMCallTimeout() time.Duration

LLMCallTimeout exposes the resolved per-call budget so /stats can report the configuration next to the counters (a timeout count is meaningless without it).

func LLMErrors added in v0.1.1

func LLMErrors() int64

LLMErrors returns non-timeout failures of extract_llm model calls (transport, HTTP status, unparseable body, or a cancelled parent request).

func LLMTimeouts added in v0.1.1

func LLMTimeouts() int64

LLMTimeouts returns the number of extract_llm calls abandoned on the per-call deadline. Non-zero means CONTEXT_GURU_LLM_TIMEOUT is too small for the current server load, and any token-savings number from this arm is an UNDERCOUNT of what the pipeline would have done on an unloaded server.

func LLMTruncated added in v0.1.1

func LLMTruncated() int64

LLMTruncated returns the number of extraction replies cut off at the output cap.

func MarkKeptVerbatim

func MarkKeptVerbatim(st store.Store, session, original string)

MarkKeptVerbatim records that this session expanded this original content, so it must not be re-compacted in this session (keyed by session and content hash). Exported for the proxy's expand loop, which has the restored original but not the offload Ctx.

An empty session writes NOTHING. A fallback to a global key would bring the cross-session leak back through the default path.

func MaxConcurrentSummaries added in v0.2.0

func MaxConcurrentSummaries() int64

MaxConcurrentSummaries is the global bound, reported beside the counts for the reason llm_call_timeout_ms travels with its timeout total: a refusal count is meaningless without the ceiling it was measured against.

func NoteSweepBatchSkippedForTest added in v0.6.2

func NoteSweepBatchSkippedForTest(n int)

NoteSweepBatchSkippedForTest books n skipped batches in the ledger, so the host's tests can check that /stats publishes the counter without staging a sweep that runs out of time.

func OwnsKey

func OwnsKey(st store.Store, session, key string) bool

OwnsKey reports whether session stashed key. Exported for the proxy's GET /expand handler to scope retrieval to the caller's session (prevents cross-session/tenant disclosure of offloaded originals). Returns false when either is empty.

func RegisterConfigKeepAliveCandidateForTest added in v0.7.2

func RegisterConfigKeepAliveCandidateForTest(session string, st store.Store,
	call func(ctx context.Context) (string, error), path string, span []bschemas.ChatMessage, coveredCount int)

RegisterConfigKeepAliveCandidateForTest is RegisterKeepAliveCandidateForTest for a call that goes to the operator's configured model, not with the user's own credential. Its answer's headers then never reach the keeper (#1016).

func RegisterKeepAliveCandidateForTest added in v0.5.0

func RegisterKeepAliveCandidateForTest(session string, st store.Store,
	call func(ctx context.Context) (string, error), path string, span []bschemas.ChatMessage, coveredCount int,
	cacheState string, preExpirySeconds int)

RegisterKeepAliveCandidateForTest installs commission material directly, for proxy's keeper tests to exercise KeepAliveSubstitute without driving a real Offload call through a mocked model and a full pipeline Ctx. Test-only: nothing outside a test has a legitimate reason to register a candidate that was not produced by an actual commission, which is why this is the one function in this file that does not require a *CacheAwareSummarizer the registry built itself — it builds the minimal receiver inline.

call takes the plain, unnamed function shape rather than the package-private summaryCaller type, so a test in another package (proxy's keeper tests) can build one from either a mocked MessagesModel or a mocked PrefixAsker without needing to see that type at all — Go's assignability rules let an unnamed function literal satisfy a named parameter of the identical underlying type regardless of which package declared it.

cacheState/preExpirySeconds let a test drive KeepAliveCandidateInfo's values without constructing a real component through its registered constructor — "" behaves as `any`, matching a component whose trigger never set cache_state at all.

func RegisterKeepAliveCandidateWithRefreshCostForTest added in v0.7.4

func RegisterKeepAliveCandidateWithRefreshCostForTest(session string, st store.Store,
	call func(ctx context.Context) (string, error), path string, span []bschemas.ChatMessage, coveredCount int,
	cacheState string, preExpirySeconds int)

RegisterKeepAliveCandidateWithRefreshCostForTest is RegisterKeepAliveCandidateForTest for a component configured with refresh_cost: full.

func RegisterSweepPingForTest added in v0.6.0

func RegisterSweepPingForTest(session, threadID string, st store.Store, asker components.PrefixAsker,
	model string, msgs []bschemas.ChatMessage, cfgYAML string) error

RegisterSweepPingForTest runs the sweep's own Offload once over msgs, as the request path does, so the thread registers its ping-time question exactly the way production registers it. For the keeper's tests in another package, which cannot reach the unexported constructor.

cfgYAML is the component's config block ("" is the shipped defaults). model is the request's model id. The registry is a package global keyed by thread.Key(session, threadID); a test must call ClearKeepAliveCandidate for it when done.

func RegisterThreadKeepAliveCandidateForTest added in v0.5.0

func RegisterThreadKeepAliveCandidateForTest(session, threadID string, st store.Store,
	call func(ctx context.Context) (string, error), path string, span []bschemas.ChatMessage, coveredCount int,
	cacheState string, preExpirySeconds int)

RegisterThreadKeepAliveCandidateForTest is RegisterKeepAliveCandidateForTest for one thread of the session. The registry key is then thread.Key(session, threadID). The call counts as sent with the user's own credential, as on the incoming and PrefixAsk paths.

func ResetSweepBatchForTest added in v0.6.2

func ResetSweepBatchForTest()

ResetSweepBatchForTest clears the batching ledger. For the host's tests, which drive a whole sweep and read the counters.

func ResetSweepLedgerForTest added in v0.6.0

func ResetSweepLedgerForTest()

ResetSweepLedgerForTest clears the process-wide quality ledger. The ledger is global, like the ping counters, so a test that drives a drop must clear it again or it leaks into /stats for every test that follows in the same process.

func ResetV3ForTest added in v0.7.2

func ResetV3ForTest()

ResetV3ForTest clears sweep v3's ledger, for the host's tests.

func ResolveDeferredCacheAwareSummary added in v0.5.0

func ResolveDeferredCacheAwareSummary(session, threadID string)

ResolveDeferredCacheAwareSummary dispatches a summary held for the triggering turn's own forwarded request: a cold commission, so the side call reads a now-warm prefix instead of racing the forwarded request to rewrite it twice, and a warm prefix-ask commission, so its call reads this turn's body from the host's stash rather than the previous turn's (#722).

A HOST THAT SETS Ctx.PrefixAsk MUST CALL THIS when each request ends, after it has stashed that request's forwarded body. Without it a warm prefix-ask commission is dispatched only when a newer request on the thread replaces it, or by the fallback timer.

Called by the proxy right after that turn's own upstream usage is observed — success or failure. FAILURE STILL RESOLVES, deliberately: a forwarded request that errored or timed out may or may not have reached the provider far enough to write the cache, but there is no decidable "did it rewrite" signal narrower than "the round trip finished", and waiting for one that never fires would silently lose the compaction via the fallback timer only — a worse outcome than occasionally dispatching the side call against a prefix that, in fact, never got rewritten (which is simply the ordinary cold-and-will-miss case this deferral did not create).

A no-op when no deferral is pending for the thread.

threadID is the request's thread (Ctx.Thread): the deferral is keyed by thread (convKey, #430), so a subagent's forwarded request resolves only the subagent's own deferral, never the main thread's, whose cache that request did not rewrite.

func ResolveWarmQuestion added in v0.7.2

func ResolveWarmQuestion(session, threadID string, forwarded bool, turnRead int)

ResolveWarmQuestion is called by the host after the thread's request was forwarded and its response read. forwarded=false (the request failed) drops the registration: the stashed body is not the one the snapshot was taken from. The question runs on its own goroutine, so the caller waits for nothing.

func SeedCarriedCountersForTest added in v0.7.2

func SeedCarriedCountersForTest() (reset func())

SeedCarriedCountersForTest sets each carried-set counter to a distinct non-zero value and returns a func that clears the warm state. It lets the keeper's test prove every counter reaches /stats.

func SeedReservedCheckpointForTest added in v0.5.0

func SeedReservedCheckpointForTest(session string, st store.Store, coveredSpan []bschemas.ChatMessage, summaryText string)

SeedReservedCheckpointForTest writes a `Reserved` checkpoint directly to the store, covering exactly coveredSpan, for a proxy-side test to put a session into "has a pre_expiry reserve with a tail of known size" without driving a real commission through Offload. Test-only, for the same reason RegisterKeepAliveCandidateForTest is: a legitimate caller only ever gets a checkpoint from an actual commission.

A later RegisterKeepAliveCandidateForTest call whose span starts with these exact messages (byte for byte) gives checkpointRefreshOpportunity a prefix hash it recognizes, with everything past coveredSpan read as the refresh's own tail — this is the one lever a test needs to control info.RefreshTailTokens without needing to see spanHash/sumCheckpoint, which stay package-private.

func SeedSweepDropForTest added in v0.6.0

func SeedSweepDropForTest(st store.Store, threadKey, content, marker string)

SeedSweepDropForTest records, as a cold apply would, that the sweep dropped `content` on a thread and stashed it under the marker id `marker`. For the host's tests, which drive an expand through the real proxy and cannot reach the unexported record.

func StashMissing added in v0.1.1

func StashMissing() int64

StashMissing returns how many marker replays found no payload behind them. Non-zero means markers ARE on the wire that the store cannot resolve — unlike StashRefusals, this is a broken promise, and the leading indicator for expand_unresolved_missing.

func StashRefusals added in v0.1.1

func StashRefusals() int64

StashRefusals returns how many removals were declined because the store's rewind reserve was full. Non-zero means max_entries is too small for what this configuration removes; the removals did not happen, so nothing became irreversible.

func SummarizeCallTimeout added in v0.1.1

func SummarizeCallTimeout() time.Duration

SummarizeCallTimeout exposes the resolved budget so /stats can report the configuration next to the counters (a timeout count is meaningless without it).

func SummarizeErrors added in v0.1.1

func SummarizeErrors() int64

SummarizeErrors returns non-timeout failures of summarize model calls (transport, HTTP status, empty/unparseable body, or a cancelled parent request).

func SummarizeTimeouts added in v0.1.1

func SummarizeTimeouts() int64

SummarizeTimeouts returns the number of summarize calls abandoned on the per-request deadline. Non-zero means CONTEXT_GURU_SUMMARIZE_TIMEOUT is too small for the current server load, and this arm compacted less than the method would on an idle server.

func SweepApplyPanics added in v0.6.0

func SweepApplyPanics() int64

SweepApplyPanics is the process-wide count of recovered cold-apply panics.

func SweepMarkerID added in v0.6.0

func SweepMarkerID(original string) string

SweepMarkerID is the marker id an original is stashed under: the id an expand of it names. For a host that has the restored original but not the id it was asked for.

func SweepPingSubstitute added in v0.6.0

func SweepPingSubstitute(threadKey string) (dispatch func(timeout time.Duration, wait SweepPingWait) SweepPingResult,
	info SweepPingInfo, reason SweepPingReason, ok bool)

SweepPingSubstitute reports whether a thread has a sweep question the keep-alive may send instead of a bare ping, and a dispatch to send it. threadKey is thread.Key(session, thread).

ok=false means send the ordinary ping; reason says why. dispatch BLOCKS for the whole call and the keeper runs it off its own goroutine, as it does for any ping.

func SweepSlotsInUseForTest added in v0.6.0

func SweepSlotsInUseForTest() int

SweepSlotsInUseForTest reports how many sweep slots are held right now.

func V3CutsForTest added in v0.7.2

func V3CutsForTest() int64

V3CutsForTest is the number of cuts v3 has applied.

func V3DryRunCutsForTest added in v0.7.2

func V3DryRunCutsForTest() int64

V3DryRunCutsForTest is the number of would-be cuts a dry run has booked.

func WaitForAllSummariesForTest added in v0.2.0

func WaitForAllSummariesForTest(within time.Duration) bool

WaitForAllSummariesForTest drains every in-flight summary, whatever session it belongs to.

For tests that drive the pipeline through apply rather than calling the component directly: apply DERIVES a session id from the transcript when the caller supplies none (session.Scoped over the system prompt and first user message), so such a test cannot name the session it just created and cannot wait on it by name.

It polls, unlike WaitForSummaryForTest, because "no summaries are running" is a property of the whole registry rather than of one channel. The interval is short and the deadline is the caller's, so a passing test is bounded by the work rather than by the poll.

func WaitForSummaryForTest added in v0.2.0

func WaitForSummaryForTest(session string, within time.Duration) bool

WaitForSummaryForTest blocks until the thread's in-flight summary has landed, or the deadline passes. It reports whether one landed. session is the THREAD key, thread.Key(session, thread) (#430); for the primary thread that is the bare session id.

EXPORTED AND TEST-ONLY, and it is deliberately not a `_test.go` file: components/all's tests drive summarize through the registry from another package, and they need the same drain. The alternative was every caller sleeping, which is how a suite becomes both slow and flaky.

It waits on the SAME channel a real turn waits on (summaryFlight.done), so a test that passes here is exercising the production synchronisation rather than a sleep that happens to be long enough on the machine that ran it.

It first waits out a DEFERRED commission for the thread (#722): a host dispatches one from its request-end hook, which can run after the client already has its response, so a caller that waits right after its request returns could otherwise see nothing in flight yet and return before the summary has even started.

Types

type AgentDiet added in v0.1.1

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

AgentDiet is a baseline reproduction of the trajectory-reduction method from "Reducing Cost of LLM Agents with Trajectory Reduction" (Xiao, Gao, Peng, Xiong; FSE 2026, arXiv:2509.23586), which the paper calls AgentDiet. It is offered as a COMPARABLE BASELINE next to context-guru's own reducers, so the published method can be A/B'd against `extract_llm` / `summarize` on the same traffic.

The method, and what makes it different from extract_llm:

  1. Its unit is the STEP — one assistant message plus the tool results answering it — not one tool output. A step is reduced as a whole.
  2. A FIXED AGE, not a size or an economic estimate, chooses the target: when the agent has completed step s, only step s-a is eligible (`delay_steps`, a=2). The most recent a steps are never touched, so a bad reduction can never corrupt what the agent is working on right now — the paper's protection against a malfunctioning reflection model.
  3. The reflection model gets a SLIDING WINDOW of surrounding steps as context (`context_steps`, b=1 ⇒ steps [s-a-b … s]), serialized as XML. This is the part extract_llm structurally cannot do: seeing neighbouring steps is what lets the model recognise content as *redundant* (already stated nearby) or *expired* (mattered only to a finished sub-goal) rather than merely verbose.
  4. Two thresholds bound the spend. A step shorter than `min_step_tokens` (θ=500) is not worth a call at all; and a reduction that comes back is APPLIED only if it clears `min_saved_tokens` OR `max_keep_ratio`, so a marginal rewrite does not pay a cache-write for nothing.
  5. A reduction is made ONCE and then frozen: later turns replay the same bytes (freeze/reapplyFrozen), so the request prefix stays stable and reductions accumulate across the session exactly as they do in the paper, where the agent's own trajectory is edited in place.

Deviations from the paper, all forced by the wire and documented in docs/components/agentdiet.md:

  • The paper's reflection module REPLACES the whole step with one assistant message. context-guru rewrites messages in place (only `summarize` changes the message count, and it must run alone for that reason), so the reduction is written into the step's tool-result messages — where 63% of trajectory tokens live, by the paper's own accounting (30.4K of 48.4K).
  • Tool-call ARGUMENTS are not reduced. On Anthropic traffic bifrost's schema does not model `tool_use` blocks at all, so their name and input are not visible to any component here; the assistant message is not even Rewritable. That forgoes the paper's str_replace_editor redundancy case (~25% of trajectory tokens) and is the main reason to expect a smaller reduction here than the paper's 39.9%–59.7%.
  • The reflection prompt is written from the paper's description (its four parts: job, format, the three waste categories, anti-loss guidelines) rather than copied from the authors' artifact.

Defaults are the paper's tuned values (a=2, b=1, θ=500). `min_saved_tokens` (400) and `max_keep_ratio` (0.8) come from the authors' artifact, whose apply-gate is `saved >= 400 || keep < 0.8` — Algorithm 1 in the paper states this more simply as `l_orig - l_reduced > θ`. The artifact's form is used because it is what produced the published numbers; setting `min_saved_tokens` to θ and `max_keep_ratio` to 0 reproduces the paper's stated gate exactly.

func (*AgentDiet) Enabled added in v0.1.1

func (*AgentDiet) Enabled(*components.Ctx) bool

func (*AgentDiet) Name added in v0.1.1

func (*AgentDiet) Name() string

func (*AgentDiet) NeedsModel added in v0.1.1

func (*AgentDiet) NeedsModel() bool

NeedsModel reports that this component calls an LLM. With no model available it degrades to replaying whatever it already froze — never an error.

func (*AgentDiet) Offload added in v0.1.1

type CacheAwareSummarizer added in v0.2.0

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

CacheAwareSummarizer summarizes by APPENDING the instruction to the conversation instead of rebuilding the prompt, so the summarization call can reuse a prefix the backend already has rather than paying fresh prefill for tokens it has already seen.

`summarize` builds a fresh prompt — a preamble plus the rendered transcript as one user message — which shares no prefix with the conversation it describes, so that call is a cache miss on every token. This one sends [the conversation, verbatim and in order] + [one appended instruction]. It is the shape prompt-caching guidance prescribes for a fork: reuse the parent's prefix and append only what the fork adds.

⛔ HOW FAR THE REUSE ACTUALLY GOES, because the naive reading of the paragraph above is wrong after the first compaction. The prefix that would be hit is one the BACKEND has seen, and the backend only ever receives what this proxy forwards. The agent keeps sending its own full uncompacted history, but from the first triggering turn onward the backend has received COMPACTED requests — so there is no full-history prefix upstream to match, and the shared prefix is roughly the pinned head. Two consequences worth measuring rather than assuming: the saving is largest on the first compaction and smaller afterwards, and sending the full growing history as a side call can evict the compacted prefix the forwarded request needs. Judge this component on the backend's own telemetry (vllm:prefix_cache_hits_total, or usage.cache_read_input_tokens, which the OpenAI client records) — never on a savings percentage.

⛔ IT NEEDS EITHER A components.MessagesModel OR A components.PrefixAsker, AND DECLINES WITHOUT BOTH. A plain Model flattens the conversation to one string, which is exactly the prefix-destroying shape this exists to avoid, so a client without either capability makes the component skip. A silent fallback would report this method's latency while paying the old method's cost. Because a declining arm compacts nothing and is byte-identical to `off` on every other metric, the decline is COUNTED: read CacheAwareSummarizerDeclined before believing any delta from this arm.

THE PREFIXASKER PATH EXISTS BECAUSE THE MESSAGESMODEL ONE IS UNREACHABLE ON THIS DEPLOYMENT'S OWN TRAFFIC (#275). On Anthropic incoming-model requests — `model.source: incoming`, the default — the host wraps the request's own client as internal/cheapmodel.Anthropic, which implements Complete but not CompleteMessages; only internal/cheapmodel/openai.go does. Without a second path this component ran only on an OpenAI-shaped `model.source: config` deployment and declined every turn of Anthropic-only traffic — exactly `off`, invisibly, for the one route the feature was built for. Ctx.PrefixAsk completes one question against the PREVIOUS turn's SENT body (components.PrefixAsker's own docstring explains why that body, not the incoming one), so it is the SAME cache-reading shape as the MessagesModel path, just a different wire mechanism — one appended user-role message, no system-role option, since PrefixAsker always sends it as a trailing user turn (see summaryCaller in cache_aware_async.go for where the two converge, and CacheAwareSummarizerPrefixAskUsed for which one actually ran).

Span selection, kept-verbatim repair and orphan repair all come from summarize_pairing.go — the same functions `summarize` uses, not a second implementation. A tool exchange is atomic and both boundaries must respect that; a private copy of the invariant would be a second place for it to drift, and the drift would surface as an exception-rate difference blamed on the method under test.

Two cache-state modes, and they mean genuinely different things

`trigger.cache_state: any` (the default) summarizes and USES the summary now: the turn that crosses the fill threshold commissions a checkpoint, and the next eligible turn splices it, warm or cold, exactly as every component in this file described before this comment existed.

`trigger.cache_state: pre_expiry` means something else: PREPARE one in the background, and use it only on a cold return. A checkpoint commissioned while the cache is still believed live (phase PreExpiry) is held RESERVED (sumCheckpoint.Reserved) rather than spliced — warm turns keep forwarding the full history untouched, because splicing it now would be the exact cache-destructive rewrite this mode exists to avoid. While reserved, an idle keep-alive ping still pings the FULL history (that is what the provider actually has cached); whether a ping is instead spent refreshing the reserve with a FRESH summary is no longer a token-count comparison against resummarize_tokens — since #415 it is a money gate (expected saving on the eventual cold return against the refresh call's own projected cost; see checkpointRefreshOpportunity and fireSummarySubstitute) — rather than on a plain read of a prefix the reserve no longer matches. Only a turn whose phase is Cold (the cache is actually gone) or Unknown (no cache-aware tracking exists on this request at all, so there is nothing live to protect) graduates the reserve: splices it, tail and all, and marks it live from then on — see cacheAwareApplyPhase. From that turn forward the session behaves exactly like `any` for that one checkpoint: replayed while current, re-summarized fresh once stale, on any phase.

WHY THIS IS WORTH THE COMPLEXITY: a warm turn reading a 900k-token prefix costs about $0.18 on Sonnet 5 at the cache-read rate; reading the ~80k reserve summarizes down to costs about $0.016 instead — paid at every ping instead of a free read, which is why it is spent only when the reserve has grown enough to be worth refreshing, not on every ping unconditionally. The return this buys: a COLD return against the full 900k prefix costs about $0.20 to write once the ~80k reserve is already in hand, against roughly $2.25 to re-write the full 900k from scratch — the rewrite cache_state: pre_expiry exists to avoid paying for AT THE WORST possible moment, a cold turn that is already paying full freight for everything else.

func (*CacheAwareSummarizer) CutFrac added in v0.6.3

func (s *CacheAwareSummarizer) CutFrac() float64

CutFrac is the trigger fraction of the window at which this component cuts the conversation (components.CutFracProvider).

func (CacheAwareSummarizer) Enabled added in v0.2.0

func (*CacheAwareSummarizer) InstructionRole added in v0.2.0

func (s *CacheAwareSummarizer) InstructionRole() string

InstructionRole exposes the resolved role so /stats and a probe can report which channel this arm actually used; with `auto` it cannot be read off the config alone.

func (CacheAwareSummarizer) Name added in v0.2.0

func (*CacheAwareSummarizer) NeedsModel added in v0.2.0

func (*CacheAwareSummarizer) NeedsModel() bool

func (*CacheAwareSummarizer) Offload added in v0.2.0

Offload rewrites the transcript to [head, summary, tail]. The summary comes from a model call built as [the whole conversation] + [instruction], and is REUSED across turns until the tail grows past resummarize_tokens — without that reuse the forwarded prefix would change every turn and this component would invalidate the cache it exists to protect.

type Cmdfilter

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

Cmdfilter shrinks tool-output messages with declarative DSL filters. It is an Offload: it stashes the original before filtering so the expand tool can recover it. Filters match on the tool output's first few non-empty lines AND, when the transcript pairs the result with its call (schema.ToolCalls), on a leading `$ <command>` line — so a filter can key on the command that produced the output the way rtk's do, not only on the output's shape.

func (*Cmdfilter) Enabled

func (f *Cmdfilter) Enabled(*components.Ctx) bool

func (Cmdfilter) Name

func (Cmdfilter) Name() string

func (*Cmdfilter) Offload

type Collapse

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

Collapse is the content-agnostic fallback for an oversized tool output that no more specific component handled: it keeps a head + tail window, stashes the full original, and leaves an expand marker. Runs late in the pipeline (after cmdfilter/format), and skips anything already carrying a marker so it never double-collapses.

The window is cut by LINES when that actually shrinks the output, and by CHARACTERS when it does not. The character path is not a nicety. Being the last-resort catch-all, collapse declining a payload means nothing caps it, and the line-only version declined every output of head_lines+tail_lines lines or fewer — which includes the single most common shape of an enormous tool result: a database or HTTP API response serialised as ONE line of JSON. Measured on a live 128k-band arm: 16 upstream 400s ("prompt is too long") in 3,347 requests on outgoing bodies of 2.6 MB to 14.8 MB, and 17 of 75 runs errored. Nothing else caught them either — extract acted 0 times (no_obvious_noise 16,891, it only strips KNOWN noise patterns), cmdfilter 0 (no_filter_match, only known command families), toon 21 (not_uniform_object_array 233,501), dedup 774 (exact duplicates only), extract_llm declines by design when the output exceeds the compaction model's own window (over_model_context), and summarize protects keep_last, which is exactly where a FRESH oversized output sits. linecap's per-line cap does not rescue this shape either: its neverTruncate allow-list exempts any line matching `^\S+:\d+`, and a one-line JSON body (`{"items":[{"id":1,...`) matches that by accident.

The choice between the two windows is made on BYTES, not on the line count: an output with more than head_lines+tail_lines lines whose kept head or tail is itself multi-megabyte takes the CHARACTER window too. Gating on the line count alone left the motivating shape alive above 40 lines — measured at 4,195,111 B in, 4,194,922 B out, and worse than declining, because dropping the small filler lines in the middle counts as acting and stamps a marker, which then makes linecap decline (already_marked) and forwards 1.57 M tokens. linecap could not have capped it even without the marker: its neverTruncate allow-list exempts any line matching `^\S+:\d+`, which one-line JSON matches by accident (issue #151), so the mitigation this comment used to name is void rather than conditional.

ponytail: []rune(content) on the character path copies the whole output — ~59 MB for the 14.8 MB payloads that motivated this component — once per oversized message per turn, on top of the strings.Split above it. Fine at the measured rate (16 bodies in 3,347 requests) but it is the obvious thing to make streaming if that rate rises.

func (Collapse) Enabled

func (Collapse) Enabled(*components.Ctx) bool

func (Collapse) Name

func (Collapse) Name() string

func (*Collapse) Offload

func (cl *Collapse) Offload(req *schemas.BifrostChatRequest, rep *components.Report, c *components.Ctx) ([]string, error)

type Coref added in v0.2.0

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

Coref is co-reference-aware compaction: at a threshold crossing it cuts the tool outputs that later turns never carried anything forward from, in ONE batched pass. Design and derivation: docs/proposals/coref-compaction.md.

It differs from every other offloader here in one deliberate way, and the whole shape of the component follows from it: it MUTATES THE CACHED PREFIX on purpose. Age-based offloaders refuse to (Ctx.TailOnly) because breaking the prefix hash at index i cache-WRITES the suffix, at 11.5x a cache-read. So:

  • The cut is BATCHED. One rewrite has to serve every cut in the pass, because a single early cut can never repay its own rewrite on tokens: at 5k cut from 20% depth of a 150k transcript the break-even is T > 276 turns. Batched, 60k of the same transcript needs T > 23, which a long session actually reaches. Hence min_batch_frac, and hence "rare and certain" rather than "per output per turn".
  • The spend is BUDGETED and reported, not incidental (rewrite_budget). A component that spends cache-writes on purpose has to be answerable for how many.
  • The decision is LATCHED and replayed, never re-derived. See the freeze note in Offload; this is the constraint that rules out repairLostFreeze.

The default cut set is `unreferenced` only — outputs no later turn exactly reuses anything from. That is the honest ceiling of a zero-LLM implementation and needs no calibrated threshold. `closed` (the case-A large cut: referenced once or twice, long ago) is off by default because its two thresholds are the OUTPUT of the measurement pass in deploy/harbor/coref.py, which has not yet run on real traffic; shipping a guessed closed_dist would be shipping the one number the proposal says must be measured. Turn it on with cut_closed once there are numbers.

func (Coref) Enabled added in v0.2.0

func (Coref) Enabled(*components.Ctx) bool

func (Coref) Name added in v0.2.0

func (Coref) Name() string

func (*Coref) Offload added in v0.2.0

func (cf *Coref) Offload(req *bschemas.BifrostChatRequest, rep *components.Report, c *components.Ctx) ([]string, error)

type Dedup

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

Dedup replaces a tool output that is byte-identical to an earlier one in the same request with a short pointer + expand marker, stashing the original. Exact-match only in v1; near-duplicate (similarity threshold) is deferred.

func (Dedup) Enabled

func (Dedup) Enabled(*components.Ctx) bool

func (Dedup) Name

func (Dedup) Name() string

func (*Dedup) Offload

func (d *Dedup) Offload(req *schemas.BifrostChatRequest, rep *components.Report, c *components.Ctx) ([]string, error)

type Extract

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

Extract is the DETERMINISTIC (no-LLM) tool-output reducer. It runs every request (cheap) and is deliberately CONSERVATIVE: it removes only OBVIOUS, provably redundant noise (exactly repeated lines/blocks, runs of blank lines, progress bars/spinners) via collapseObviousNoise, keeping every unique informative line verbatim. This guarantees it can never hide content the agent needs and force it to redo work. Relevance-aware, aggressive trimming (regex rewrites, summaries) is the job of the separate `extract_llm` component — configure them together (`[extract, extract_llm]`) so the cheap pass runs every step and the LLM pass only every few steps.

It is byte-stable on unchanged content (deterministic per-message), so it is cache-safe and needs no cache-boundary restriction. The full original is stashed under a marker (reversible via the expand tool).

func (Extract) Enabled

func (Extract) Enabled(*components.Ctx) bool

func (Extract) Name

func (Extract) Name() string

func (*Extract) Offload

func (e *Extract) Offload(req *bschemas.BifrostChatRequest, rep *components.Report, c *components.Ctx) ([]string, error)

type ExtractLLM

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

ExtractLLM is the relevance-aware, LLM-driven tool-output reducer. A cheap model writes a small Starlark program that trims ONE tool output down to what the agent needs next (it may delete OR rewrite via regex, preserving ids/paths/errors verbatim, and may emit a one-line SUMMARY that goes into the marker). The program runs in a sandbox (no imports/IO, step+time limited) and the result must pass a sanity check (non-empty, strictly smaller, keep-ids present); on any miss the item is left verbatim. The full original is always stashed (reversible via expand).

It is the EXPENSIVE pass, so it is throttled (per-session cadence + per-request cap) and — in cache-aware mode — only rewrites tool outputs in the uncached tail that are still medium/large AFTER the deterministic components ran. Prior compactions are reused byte-for-byte from state so the request prefix stays stable.

func (*ExtractLLM) Enabled

func (*ExtractLLM) Enabled(*components.Ctx) bool

func (*ExtractLLM) Name

func (*ExtractLLM) Name() string

func (*ExtractLLM) Offload

type ExtractSweep added in v0.1.1

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

ExtractSweep is the SWEEP ADJUDICATOR: it asks the request's OWN model, over the transcript that model already has in its prompt cache, which tool outputs are spent — and removes those, leaving a shape descriptor plus a recoverable marker. It never rewrites anything and it never copies output content into a prompt.

WHY IT IS A SEPARATE COMPONENT FROM extract_llm. The two situations want different operations. On a warm turn extract_llm works the uncached tail: the output is recent, the agent may still want most of it, and a smaller version of it is more useful than none of it. The sweep works DEEP HISTORY, where rewriting is the wrong operation on either branch of the only question that matters — deep history is either still load-bearing, in which case rewriting corrupts content the model has already reasoned about, or it is spent, in which case the answer is to remove it.

WHY IT ASKS THE REQUEST'S MODEL OVER THE CACHE, in one call, shipping an inventory:

Need is relevance MINUS what has already been captured elsewhere, and that second term lives in
the LATER TURNS. A judgement shown only the candidate cannot see them.
Verbatim quoting — the only signal that says whether the model is inventing — degraded to 20.8%
on the cheap model at bulk batch sizes, against 0 of 59 on the request model.
Appending a trailing user message to a byte-identical prefix read 19,595 tokens from cache and
created 0, so the whole transcript is affordable exactly once: as a cache read.

See internal/extract/adjudicate.go for the full evidence and components.PrefixAsker for the construction.

WHAT IT NEVER DOES. It selects no compaction strategy, produces no rewritten text, and there is no reply field a model could return content through. `strategy`, `rewrite`, `aggressiveness` and `max_chars` are therefore not merely defaulted differently here, they are meaningless, and writing one is a config error rather than a silently ignored key (see newExtractSweep).

func (*ExtractSweep) Enabled added in v0.1.1

func (*ExtractSweep) Enabled(*components.Ctx) bool

func (*ExtractSweep) Name added in v0.1.1

func (*ExtractSweep) Name() string

func (*ExtractSweep) Offload added in v0.1.1

type FailedRun

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

FailedRun collapses earlier test/build runs that a later run supersedes: only the most recent run-like tool output is kept in full; earlier ones become a pointer + stash. This is the "provable-reason" collapse — a superseded run is safely recoverable via expand if the agent still needs it.

func (FailedRun) Enabled

func (FailedRun) Enabled(*components.Ctx) bool

func (FailedRun) Name

func (FailedRun) Name() string

func (*FailedRun) Offload

func (fr *FailedRun) Offload(req *schemas.BifrostChatRequest, rep *components.Report, c *components.Ctx) ([]string, error)

type KeepAliveCandidateInfo added in v0.5.0

type KeepAliveCandidateInfo struct {
	CacheState       string
	PreExpirySeconds int
	// IsRefresh is true when a Dispatch, if run, would REFRESH an existing `pre_expiry` reserve —
	// replace it with a new one covering a larger span — rather than create the session's first
	// one. The keeper's own money gate (issue #415: refresh only when the expected saving on the
	// eventual cold return covers what the refresh costs, see RefreshFullCost) applies ONLY to a refresh:
	// creating the first reserve is compared against having none at all (the full-rewrite cold
	// return this whole mechanism exists to avoid), not against a slightly smaller reserve, so it
	// has no such test.
	IsRefresh bool
	// RefreshTailTokens is the token size of the material a refresh would fold in beyond what the
	// existing reserve already covers — the number the money gate prices, at the cache-write rate,
	// and weighs against the refresh's cost. Meaningful only when IsRefresh is true.
	RefreshTailTokens int
	// RefreshFullCost is the component's refresh_cost: full. The keeper then weighs a refresh's
	// saving against the whole summary call. False (the default) weighs it against the cost over
	// the ping the refresh replaces (#1144).
	RefreshFullCost bool
	// ReadsPingPrefix is true when the candidate's call reads the same cached bytes as the ping it
	// replaces: the prefix_ask path, which sends the stashed body the ping resends. Only then does
	// the ping's read cancel out of a refresh's cost. The messages path builds its request from the
	// pipeline's own view of the conversation, which later components can change, and model.source:
	// config sends it to another model with its own cache. Those calls may still hit the same cache,
	// but nothing guarantees it, so the gate stays conservative there and weighs the whole call.
	ReadsPingPrefix bool
}

KeepAliveCandidateInfo is what a registered candidate asked for, surfaced so the keeper can decide whether ITS OWN notion of "due" also satisfies the candidate's cache_state — a `pre_expiry` candidate must not be substituted on a ping the keeper is sending for some other reason (e.g. a strategy-driven K>1 schedule, or simply because Idle has elapsed on a session whose cache is still warm by the component's own, possibly narrower, pre_expiry_seconds).

type KeepAliveSubstituteReason added in v0.5.0

type KeepAliveSubstituteReason string

KeepAliveSubstituteReason explains why KeepAliveSubstitute declined (ok=false), or why a Dispatch it returned did not commit — so a caller's counters and logs can tell "nothing was ever registered for this session" from "something WAS registered and was lost", which used to be one silent boolean. See fireSummarySubstitute's own comment on why that distinction matters: a session that should have had a candidate and does not is a real bug, while one that never had cache_aware_summarizer in its pipeline at all is the ordinary, overwhelming majority case.

const (
	// KeepAliveReasonNone is the zero value: either ok=true (a Dispatch was returned), or
	// Dispatch's own result committed — there is nothing to explain.
	KeepAliveReasonNone KeepAliveSubstituteReason = ""
	// KeepAliveReasonNoCandidate: no turn has registered material for this session at all — the
	// component is not in this tenant's pipeline, no turn has reached the registration point
	// yet, or ClearKeepAliveCandidate ran and nothing has re-registered since. The ordinary case
	// for the vast majority of sessions.
	KeepAliveReasonNoCandidate KeepAliveSubstituteReason = "no_candidate"
	// KeepAliveReasonCheckpointExists: a candidate WAS registered, but a checkpoint already
	// exists for this session — the next real turn will splice it for free, so spending a call
	// here would summarize a span nobody is waiting on.
	KeepAliveReasonCheckpointExists KeepAliveSubstituteReason = "checkpoint_exists"
	// KeepAliveReasonInFlight: Dispatch collided with a commission already in flight for this
	// session (the async path, or another keep-alive dispatch) — checked only inside Dispatch
	// itself via the shared single-flight registry, so it cannot be known at lookup time.
	KeepAliveReasonInFlight KeepAliveSubstituteReason = "in_flight"
	// KeepAliveReasonConcurrencyFull: Dispatch was refused by the global concurrency bound this
	// path shares with the detached async one — the proxy is shedding compaction under load.
	KeepAliveReasonConcurrencyFull KeepAliveSubstituteReason = "concurrency_full"
)

type KeepAliveSummaryResult added in v0.5.0

type KeepAliveSummaryResult struct {
	Model                                     string
	FreshInput, Output, CacheWrite, CacheRead int
	// CacheWrite1h is the SUBSET of CacheWrite this call billed at the one-hour write premium
	// (the `1-hour-head` cache strategy's own breakpoint) — never an addition to CacheWrite. The
	// keeper's recordSummarySubstitute needs this to price the call with
	// modelinfo.Price.CostWithCacheWrite1h the same way record1 prices an ordinary ping, instead
	// of folding every write into the five-minute rate.
	CacheWrite1h int
	// Header is the call's response headers, or nil when no answer came back. The keeper puts them
	// on the ping row it books (KeepAliveReport.Header), so the host can read the subscription limit
	// headers from them as it does for an ordinary ping (#1016). Nothing here reads them. It is nil
	// too when the call went to the operator's configured model and not with the user's own
	// credential: that answer carries the operator's limits (KeepAliveSubstitute clears it).
	Header http.Header
	// Committed is false either because the call could not be started (another commission —
	// async or keep-alive — is already in flight for this session, or the global concurrency
	// bound is full), or because it ran and produced nothing usable (error, timeout, empty
	// reply). Either way the caller's answer is the same: fall back to an ordinary ping.
	Committed bool
	// Reason explains a false Committed — KeepAliveReasonInFlight or KeepAliveReasonConcurrencyFull
	// for the two refusals that happen before any call is made, or "" (KeepAliveReasonNone) for a
	// call that was made and simply did not commit (its own error/empty counters already say why —
	// see classifyCallErr and cacheAwareEmpty).
	Reason KeepAliveSubstituteReason
}

KeepAliveSummaryResult is what one keep-alive-substituted summary call cost and produced, read straight off the model call's own usage sink so the keeper can book it exactly as it would a ping — see cache_aware_keepalive.go.

type Linecap added in v0.1.1

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

Linecap applies the two COMMAND-AGNOSTIC output rules, in one pass over each tool message: scattered duplicate-line collapse, then a per-line character cap.

Why generic rather than more cmdfilter filters. cmdfilter ships 939 lines of per-command filters and production has matched exactly two of them (`ssh`, `uv-sync`; `no_filter_match` 164,865). Sixteen further rtk command signatures — pytest, apt, npm, pip, go test, cargo, tsc, eslint, mypy, ruff, docker, kubectl, make, gcc, git log, ps — were replayed against 9,763 real messages and every one matched ZERO. These two rules need no command signature, which is exactly why they fire where the signatures do not: on the same corpus they remove 1.75M tokens, 20.3% of everything shipped.

It is an Offload, not a Reformat: both rules drop bytes. Under the default marker_mode the original is stashed and a <<cg:HASH>> marker names it, so the agent can call the expand tool and get the whole output back.

Cache safety needs no depth gate. The rewrite is a pure function of the message's own text, so a message re-sent next turn rewrites to the same bytes and no cached position is re-anchored — the same argument format, textclean, searchfold and cmdfilter rely on.

func (*Linecap) Enabled added in v0.1.1

func (lc *Linecap) Enabled(*components.Ctx) bool

func (Linecap) Name added in v0.1.1

func (Linecap) Name() string

func (*Linecap) Offload added in v0.1.1

func (lc *Linecap) Offload(req *schemas.BifrostChatRequest, rep *components.Report, c *components.Ctx) ([]string, error)

type Mask

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

Mask hides older tool outputs beyond a keep-recent window (after CE-Manager's context garbage collection): the newest KeepRecent tool results stay verbatim, older ones are replaced with a short marker + stash. Age-based, complementary to the content-based offloaders.

func (Mask) Enabled

func (Mask) Enabled(*components.Ctx) bool

func (Mask) Name

func (Mask) Name() string

func (*Mask) Offload

func (m *Mask) Offload(req *bschemas.BifrostChatRequest, rep *components.Report, c *components.Ctx) ([]string, error)

type PingChoice added in v0.6.0

type PingChoice string

PingChoice names what may stand in for one ping.

const (
	// PingPlain: send the ordinary ping, and try no substitute. The thread is busy.
	PingPlain PingChoice = "plain"
	// PingNone: neither component registered for the thread. The keeper still looks each one up, so
	// its no-candidate counters keep counting. Both lookups decline.
	PingNone PingChoice = "none"
	// PingSummary: cache_aware_summarizer's call may take the ping.
	PingSummary PingChoice = "summary"
	// PingSweep: extract_llm_sweep's question may take the ping.
	PingSweep PingChoice = "sweep"
)

type PingClaim added in v0.6.0

type PingClaim struct {
	Choice PingChoice
	// contains filtered or unexported fields
}

PingClaim is the result of ClaimPing. The caller must call Release when the substitute attempt is over, whatever its outcome.

func ClaimPing added in v0.6.0

func ClaimPing(threadKey string) PingClaim

ClaimPing decides, for threadKey (thread.Key(session, thread)), what takes this ping, and holds the thread until Release. A plain claim holds nothing.

func (*PingClaim) Release added in v0.6.0

func (c *PingClaim) Release()

Release frees the thread for the next ping. Safe to call more than once, and on a plain claim.

type ReadLifecycle added in v0.1.1

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

ReadLifecycle offloads a file Read whose body no longer describes the file, judged from the transcript itself (after headroom's read_lifecycle.py). Two classes, and only these two:

  • STALE — an Edit/Write/MultiEdit/NotebookEdit on the same path appears LATER in the transcript. What sits in context is then FACTUALLY WRONG, so removing it is a correctness argument before it is a token argument: the model is otherwise reasoning about line numbers and content that no longer exist.
  • SUPERSEDED — the same path is Read again later with the SAME range, so the later Read is authoritative and the earlier body is redundant.

A FRESH Read — no later edit, no later re-read — is never touched. That is the safety property the component stands on: it removes only what the transcript itself proves is out of date, and the marker says only what is true (the file was modified / was read again), never "identical to", which a re-indent would already falsify.

Deliberately conservative, in three places that each cost measurable savings:

  • Supersession keys on (path, offset, limit), not path alone. Claude Code Reads ranges; a later Read of lines 500-600 does not supersede an earlier read of the whole file, and calling it superseded would delete content nothing replaced. Containment (a later full read covering an earlier partial one) is NOT modelled — measured at 867 tokens on the whole corpus on this box, which does not pay for the reasoning.
  • An Edit anywhere in the file staleizes every prior Read of it, including a Read of a different range: an edit shifts the line numbers the Read printed, so the rest of the body is wrong even where the text is not.
  • Bash commands count as edits only under `bash_edits`, off by default, and only for the narrow write forms listed in bashEditPaths. A false positive here deletes CORRECT context, which is the one failure this component must not have.

Cache safety. The classification is MONOTONE: it is a function of strictly later events, and events only ever accumulate, so a Read goes fresh → stale/superseded exactly once and never flaps back. The replacement text is a pure function of (content, class, path, config) — the marker key is sha256(content) — so it is byte-identical every time it is re-derived, from any process, with no map iteration on the path that produces it. That is what makes the freeze/reapply machinery this component shares with mask and failed_run correct here: a NEW offload happens only in the uncached tail (or at depth on a provably cold turn, `cold_cache`), and once frozen it is REPLAYED on every later turn regardless of depth, so the forwarded prefix is byte-stable. Determinism, not "only touch the delta", is the argument — see TestFrozenPrefixIsByteStable and TestDeterministicAcrossProcesses. atDepth (config `stale_at_depth`) is the one knob that can make this component pay on a WARM turn, and it is off by default because it costs a cache-write to buy one.

The measured reason it exists: with the tail gate on, a real SWE-bench session declined 1,125 stale-Read candidates as `cached_prefix` and removed ZERO tokens — structurally, not accidentally. A Read only becomes stale when a LATER Edit appears, and by that turn the Read is already in the provider's cached prefix, so the gate can essentially never let this component act warm.

Lifting it costs one re-anchor: rewriting the Read at index i forces a cache-write of everything after i, once, at the turn the Read goes stale. That is cheap exactly when the Read is near the tail at that moment — which the Read→Edit loop makes the common case — and the freeze then replays the decision on every later turn, so the body is gone for the rest of the session. See TestStaleAtDepthAmortizes for the measured distance, and the doc for the dollars.

func (ReadLifecycle) Enabled added in v0.1.1

func (ReadLifecycle) Enabled(*components.Ctx) bool

func (ReadLifecycle) Name added in v0.1.1

func (ReadLifecycle) Name() string

func (*ReadLifecycle) Offload added in v0.1.1

type SmartCrush

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

SmartCrush is headroom's statistical JSON-array compressor, in essence: keep a first-K/last-K anchor window plus any item that carries an error signal, drop the rest, and stash the full original. Schema-preserving (kept items are verbatim originals). v1 uses fixed anchors; headroom's Kneedle adaptive-K is a documented refinement.

func (SmartCrush) Enabled

func (SmartCrush) Enabled(*components.Ctx) bool

func (SmartCrush) Name

func (SmartCrush) Name() string

func (*SmartCrush) Offload

type Summarize

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

Summarize compresses the middle of a long trajectory into one LLM-written summary (ported from CE-Manager's ReSum-style summarizer). It restructures the message list to [msg0, <summary system message>, last-K messages], replacing everything in between. It is an Offload: the replaced span is stashed under a <<cg:HASH>> marker (carried in the summary message) so the expand tool can restore it. NeedsModel — it no-ops when no model is available.

This is the one component that changes the message count; apply.Body rebuilds the body preserving the retained messages' original bytes.

func (*Summarize) CutFrac added in v0.6.3

func (s *Summarize) CutFrac() float64

CutFrac is the trigger fraction of the window at which this component cuts the conversation (components.CutFracProvider).

func (Summarize) Enabled

func (Summarize) Enabled(c *components.Ctx) bool

func (Summarize) Name

func (Summarize) Name() string

func (*Summarize) NeedsModel

func (*Summarize) NeedsModel() bool

func (*Summarize) Offload

type SweepBatchIndexStats added in v0.7.2

type SweepBatchIndexStats struct {
	Asked, Judged, Fabricated int64
	// Items is the candidates the batches at this position carried, so Judged/Items shows how many verdicts
	// came back, and a batch of 5 is not read like a batch of 12.
	Items int64
}

SweepBatchIndexStats is the tally for one batch position.

type SweepBatchStats added in v0.6.2

type SweepBatchStats struct {
	// ByIndex tells the batches apart by their position in a sweep: how many were asked, how many verdicts
	// they judged, and how many of those carried a fabricated quote. A fabrication rate that differs between
	// the first batch and the later ones is a batch effect; one that is the same everywhere is the model.
	// ByIndex[0] is the first batch of every sweep. Capped at maxBatchIndexStats entries.
	ByIndex         []SweepBatchIndexStats
	Batches, Failed int64
	// Skipped counts batches never started because the sweep's deadline passed. OverCap counts candidates
	// left unasked because the limit (max_ask_batches, or the keeper's cost ceiling) allowed fewer batches.
	Skipped, OverCap int64
	FailedBy         map[string]int64
}

SweepBatchStats is the batching ledger for /stats: how many questions were asked in all, how many batches failed, and why.

func SweepBatchCounters added in v0.6.2

func SweepBatchCounters() SweepBatchStats

SweepBatchCounters snapshots the batching ledger.

type SweepDropStats added in v0.6.0

type SweepDropStats struct {
	Overall SweepQuality
	// Threads lists the busiest threads (most applied first), at most maxLedgerShown.
	Threads []SweepThreadQuality
}

SweepDropStats is the sweep's quality ledger for /stats.

func SweepDropCounters added in v0.6.0

func SweepDropCounters() SweepDropStats

SweepDropCounters snapshots the quality ledger.

type SweepExpandNote added in v0.6.0

type SweepExpandNote struct {
	// Sweep: the marker is one the sweep made. The caller charges the expand to the sweep.
	Sweep bool
	// First: this is the first expand of that drop. Only a first expand is a new false drop.
	First bool
	// Overlap: the drop had already been counted as referenced, so it is not a new false drop.
	Overlap bool
	// Warm: the first expand was of a drop applied on a warm request (#491).
	Warm bool
}

SweepExpandNote says what an expand call of a marker meant to the sweep.

func NoteSweepExpand added in v0.6.0

func NoteSweepExpand(st store.Store, markerID string, tokens int, threadKey string) (note SweepExpandNote)

NoteSweepExpand is called by the host for every expand call that resolved; tokens is what the restored text measures. It reports whether the marker is a sweep drop and records the expand on the drop and in the ledger. It never fails the expand.

threadKey is the thread that made the expand (thread.Key(session, thread)), or "" when the host does not know it yet (the request-path repair runs before the thread is resolved). A marker can be carried by several threads that dropped the same bytes. With a thread, only that thread is credited, and only if it is an owner. Without one, every owner is credited, because every owner carries the marker.

type SweepPingInfo added in v0.6.0

type SweepPingInfo struct {
	Model   string
	Offered int
	// Batches is the number of questions this sweep PLANS to ask: ceil(Offered / 12). The keeper prices
	// that many answers against its per-ping cost ceiling and may lower it (SweepPingWait.MaxBatches).
	Batches int
}

SweepPingInfo is what a registered candidate looks like before the question is sent, for the keeper's cost projection and logs.

type SweepPingReason added in v0.6.0

type SweepPingReason string

SweepPingReason says why SweepPingSubstitute declined, so the keeper's counters can tell "this thread never registered" from "it did and the model is one the question would hurt".

const (
	SweepReasonNone SweepPingReason = ""
	// SweepReasonNoCandidate: nothing registered. The component is not in this tenant's pipeline, or
	// the thread's last request did not reach the registration point. The ordinary case.
	SweepReasonNoCandidate SweepPingReason = "no_candidate"
	// SweepReasonModelDeclined: sweep_model_declined (#422). On this model the question would strip
	// the thinking blocks from the cached prefix and rewrite the cache at the write rate.
	SweepReasonModelDeclined SweepPingReason = "model_declined"
	// SweepReasonNoInventory: the conversation has no output the sweep may offer.
	SweepReasonNoInventory SweepPingReason = "no_inventory"
	// SweepReasonBelowMin: fewer candidates than min_inventory (1 unless an operator raised it).
	SweepReasonBelowMin SweepPingReason = "below_min_inventory"
	// SweepReasonAlreadyAsked: this conversation was already asked about at an earlier ping.
	SweepReasonAlreadyAsked SweepPingReason = "already_asked"
	// SweepReasonConcurrencyFull: the bound on simultaneous questions is full.
	SweepReasonConcurrencyFull SweepPingReason = "concurrency_full"
	// SweepReasonNoAsker: the route has no prefix asker.
	SweepReasonNoAsker SweepPingReason = "no_asker"
	// SweepReasonV3Rule: sweep v3 with selector rule makes no model call, so the ping is plain.
	SweepReasonV3Rule SweepPingReason = "v3_rule"
	// SweepReasonPanic: the question panicked and was recovered. The ping stays plain, and the
	// conversation is marked asked so the next ping is plain too. A panic inside ONE batch is caught per
	// batch (reason batch_panic): the other batches' answers are kept, and the conversation is still marked
	// asked, because that batch's model call may already have been paid for.
	SweepReasonPanic SweepPingReason = "panic"
)

type SweepPingResult added in v0.6.0

type SweepPingResult struct {
	Model                                     string
	FreshInput, Output, CacheWrite, CacheRead int
	CacheWrite1h                              int
	// Header is the response headers of the newest question that got an answer, or nil. The keeper
	// puts them on the ping row it books, as for KeepAliveSummaryResult.Header (#1016).
	Header http.Header
	// Substituted is true when the question reached the provider and touched the prefix (read or
	// wrote it). The keeper then counts it as the ping for this idle span. False means the keeper
	// sends the ordinary ping: the call never left, or failed before using the cache.
	Substituted bool
	// Held is true when the model's reply parsed and the answer is now held for this thread.
	Held bool
	// Offered, Proposed and ProposedTokens describe the answer: candidates asked, drops voted for,
	// and what those drops would remove.
	Offered, Proposed, ProposedTokens int
	Reason                            SweepPingReason
	// Gates and Events are the adjudication's own gate and event names for this question
	// (sweep_kept, sweep_unparseable, sweep_dropped, ...), the lists a request's Report would have
	// carried. The process-wide totals are in SweepPingCounters().Gates.
	Gates, Events map[string]int
}

SweepPingResult is what one question cost and produced, shaped like KeepAliveSummaryResult so the keeper books it exactly as it books a ping.

type SweepPingStats added in v0.6.0

type SweepPingStats struct {
	// Asked: questions that reached the provider. Held: of those, answers that parsed and are held.
	Asked, Held, Failed int64
	// ModelDeclined is sweep_model_declined: pings sent plain because the question would break the
	// cache on this model.
	ModelDeclined int64
	// NoInventory, AlreadyAsked and NoCandidate are the ordinary reasons a ping stayed a ping.
	NoInventory, AlreadyAsked, NoCandidate int64
	// HoldNoToolID counts judged outputs that could not be held because the agent's request has no
	// tool id for them.
	HoldNoToolID int64
	// ConcurrencyFull is sweep_concurrency_full: questions refused because every slot was busy. The
	// ping stays plain. NotRegistered counts requests that kept no conversation copy because the
	// keep-alive cannot ping their thread.
	ConcurrencyFull, NotRegistered int64
	// SummaryOwnedPing is sweep_summary_owned_ping (#404 point 10): pings where the sweep had a candidate
	// but the summarizer had one too, so the summary owned the ping and the sweep did not ask.
	SummaryOwnedPing int64
	// SummaryInFlight is sweep_summary_in_flight: pings where a summary was already running for the
	// thread, so the sweep did not ask.
	SummaryInFlight int64
	// ThreadBusy is sweep_ping_thread_busy: pings sent plain because an earlier substitute still held the
	// thread's claim.
	ThreadBusy int64
	// RetiredKeys counts retired settings found (and ignored) in configs, by key.
	RetiredKeys map[string]int64
	// Panics counts panics recovered in the ping-time question (collection, the ask, or the hold). Each
	// leaves the ping a plain ping.
	Panics int64
	// Gates counts the adjudication's own gate and event names (sweep_kept, sweep_unparseable, ...)
	// across ping-time questions, the counters a request's Report would have carried.
	Gates map[string]int64
}

SweepPingStats is the ledger of the ping-time question.

func SweepPingCounters added in v0.6.0

func SweepPingCounters() SweepPingStats

SweepPingCounters snapshots the ledger.

type SweepPingWait added in v0.6.0

type SweepPingWait struct {
	WaitingFor, WaitTool string
	// LastTurnRead is the cache_read of the thread's last real turn, 0 when unknown. It is the one
	// field here that decides something: the cache gate compares the question's read to it (#721).
	LastTurnRead int
	// MaxBatches, when > 0, is the most batches this sweep may ask: the keeper sets it to the number of
	// answers its per-ping cost ceiling admits (#132). The sweep then asks that many and leaves the rest
	// of the candidates unasked, counted as sweep_over_ask_cap. 0 = no limit beyond max_ask_batches.
	MaxBatches int
}

SweepPingWait is the thread's wait cause (#453) at the moment of the question, handed in by the keeper, which is where the tool names and the open-task counts are. Stored with the held answer. Stored, never used to decide, except LastTurnRead below.

type SweepQuality added in v0.6.0

type SweepQuality struct {
	Applied, AppliedCold, AppliedChangedPrefix int64
	// AppliedWarm and the three Warm counters below are the warm path's share (#491). They are PART of
	// Applied, Referenced, Expanded and Overlap, never added on top, so the cold figures are the totals
	// minus these.
	AppliedWarm                               int64
	ReferencedWarm, ExpandedWarm, OverlapWarm int64
	// ApplyDeclined: valid drops the store or the never-worse check refused. They stayed verbatim.
	ApplyDeclined int64
	Referenced    int64
	Expanded      int64
	Overlap       int64
	// ExpandEvents and ExpandTokens count every expand call of a sweep marker, and what it returned.
	ExpandEvents, ExpandTokens int64
}

SweepQuality counts what became of the drops the sweep applied. A drop is FALSE when a later turn needed it: the agent expanded the marker (Expanded), or a later turn used something the output introduced without expanding it (Referenced). A drop that is both is counted once (Overlap).

func (SweepQuality) FalseDropRate added in v0.6.0

func (q SweepQuality) FalseDropRate() float64

FalseDropRate is FalseDrops over Applied, or 0 with nothing applied.

func (SweepQuality) FalseDropRateCold added in v0.7.2

func (q SweepQuality) FalseDropRateCold() float64

FalseDropRateCold is the false-drop rate of every drop that was not applied warm.

func (SweepQuality) FalseDropRateWarm added in v0.7.2

func (q SweepQuality) FalseDropRateWarm() float64

FalseDropRateWarm is FalseDropsWarm over AppliedWarm, or 0 with none applied.

func (SweepQuality) FalseDrops added in v0.6.0

func (q SweepQuality) FalseDrops() int64

FalseDrops is the number of distinct drops a later turn needed.

func (SweepQuality) FalseDropsWarm added in v0.7.2

func (q SweepQuality) FalseDropsWarm() int64

FalseDropsWarm is FalseDrops for the drops applied on a warm request.

type SweepThreadQuality added in v0.6.0

type SweepThreadQuality struct {
	Label string
	SweepQuality
}

SweepThreadQuality is one thread's SweepQuality under a label that is not the session id.

type SweepWarmStats added in v0.7.2

type SweepWarmStats struct {
	// Fired: questions the trigger registered. Asked: of those, questions that reached the provider.
	// Held: answers held since start (cumulative, not "now waiting"). Failed: questions with no usable answer.
	Fired, Asked, Held, Failed int64
	// NotWorth: checks where the candidates could not pay back. NoBilled: checks skipped because the
	// provider's billed size was not known yet. ThreadBusy, ModelDeclined, ConcurrencyFull: questions
	// not sent, for the same reasons as at the ping. HeldExpired: waiting answers dropped for age.
	NotWorth, NoBilled, ThreadBusy, ModelDeclined, ConcurrencyFull, HeldExpired, HeldShrunk, CarriedMerged, CarriedOverridden, CarriedRefused, CarriedExpired, CarriedCapped, NotRegistered, ThreadsFull, AlreadyAsked, NoInventory, PriceModelUnknown int64
	// GatePriceModel is the diagnostic warm_gate_price_model, "" in a normal run.
	GatePriceModel string
	// GateAccept and GateRefuse count the economic gate's verdicts; Reasons splits the refusals.
	GateAccept, GateRefuse int64
	Reasons                map[string]int64
	// TriggerReasons counts the refusals at the trigger (before a question), by reason.
	TriggerReasons map[string]int64
	// Recent lists the last warm sweeps applied, with the gate's numbers.
	Recent []WarmSweep
	// RecentDecisions lists the last trigger and apply-gate decisions, accepted or refused, with the
	// numbers they were made on.
	RecentDecisions []WarmDecision
	Panics          int64
	// V3 is the sweep v3 ledger (extract_sweep_v3.go).
	V3 V3Stats
	// Gates counts the question's own gate and event names (sweep_kept, sweep_unparseable, ...) for warm
	// questions, apart from the ping's.
	Gates map[string]int64
}

SweepWarmStats is the warm path's ledger for /stats.

func SweepWarmCounters added in v0.7.2

func SweepWarmCounters() SweepWarmStats

SweepWarmCounters snapshots the warm path's ledger.

func (SweepWarmStats) Any added in v0.7.2

func (w SweepWarmStats) Any() bool

Any reports whether the warm path did or counted anything, so /stats shows nothing when it never ran.

type V3Cut added in v0.7.2

type V3Cut struct {
	Thread     string  `json:"thread"`
	AtMs       int64   `json:"at_ms"`
	Selector   string  `json:"selector"`
	P          int     `json:"billed_prompt"`
	C          int     `json:"cut_point"`
	CSource    string  `json:"c_source"`
	D          int     `json:"dropped_billed"`
	DShareP    float64 `json:"d_share_of_p"`
	PShareC    float64 `json:"p_share_of_c"`
	RuleDrops  int     `json:"rule_drops"`
	JudgeDrops int     `json:"judge_drops"`
}

V3Cut is one accepted v3 cut, in numbers. The thread is a hash label.

type V3Refusal added in v0.7.2

type V3Refusal struct {
	Thread  string         `json:"thread"`
	AtMs    int64          `json:"at_ms"`
	Reason  string         `json:"reason"`
	P       int            `json:"billed_prompt"`
	C       int            `json:"cut_point"`
	CSource string         `json:"c_source"`
	D       int            `json:"dropped_billed"`
	DShareP float64        `json:"d_share_of_p"`
	RuleD   map[string]int `json:"rule_d,omitempty"`
}

V3Refusal is one cut attempt refused before the gate, in numbers. The thread is a hash label.

type V3Reread added in v0.7.2

type V3Reread struct {
	Total    int64            `json:"total"`
	BySource map[string]int64 `json:"by_source,omitempty"`
	ByKind   map[string]int64 `json:"by_kind,omitempty"`
}

V3Reread counts re-reads of dropped targets.

type V3Stats added in v0.7.2

type V3Stats struct {
	// Refused counts why a cut attempt was refused: not_in_sweet_spot, drop_too_small, waiting_for_growth,
	// does_not_pay (and cut_point_unknown, when C or P is not known).
	Refused map[string]int64 `json:"refused,omitempty"`
	// RuleDrops counts the drops of accepted cuts that a rule chose, by rule. JudgeDrops counts the model's.
	RuleDrops  map[string]int64 `json:"rule_drops,omitempty"`
	JudgeDrops int64            `json:"judge_drops,omitempty"`
	// HybridRulesOnly counts hybrid attempts that went ahead on the rules alone: the judge gave no answer.
	HybridRulesOnly int64 `json:"hybrid_rules_only,omitempty"`
	Cuts            int64 `json:"cuts"`
	// DryRunCuts counts the cuts a dry run decided and did not apply (dry_run). DryRunDrops counts the drops in them.
	// DryRunRecent lists the last of them with a real cut's numbers.
	DryRunCuts   int64   `json:"dry_run_cuts,omitempty"`
	DryRunDrops  int64   `json:"dry_run_drops,omitempty"`
	DryRunRecent []V3Cut `json:"dry_run_recent_cuts,omitempty"`
	// CutsOnCost and CutsOnPremium split the accepted, gated cuts by whether the saving to N beat the rewrite alone
	// or needed compaction_premium_usd. A cold or changed-prefix cut runs no gate and is in neither.
	CutsOnCost    int64 `json:"cuts_on_cost,omitempty"`
	CutsOnPremium int64 `json:"cuts_on_premium,omitempty"`
	// CSource counts the sweet-spot checks by where C came from: cutfrac (a summarizer's fraction of the effective
	// context), compaction (the compaction point: operator, measured or assumed) or window (the model's window).
	CSource map[string]int64 `json:"c_source,omitempty"`
	Recent  []V3Cut          `json:"recent_cuts,omitempty"`
	// Expands counts the first expands of v3 drops by what chose them: a rule name, or judge. With rule_drops and
	// judge_drops it gives the expand rate per rule and for the judge.
	Expands map[string]int64 `json:"expands,omitempty"`
	// DroppedByKind counts applied v3 drops by the class of the tool whose output was dropped (read, edit, command,
	// other). Reread counts the later tool calls that went back to what a drop removed (the same file read or
	// edited again, or the same command run again), by what chose the drop and by the same class. With the drop
	// counts it gives the re-read rate. It matches path HASHES: no path is stored.
	DroppedByKind map[string]int64 `json:"dropped_by_kind,omitempty"`
	Reread        V3Reread         `json:"reread_after_drop"`
	// RecentRefusals lists the last cut attempts refused before the gate (not_in_sweet_spot, and in rule mode
	// drop_too_small and no_rule_drops), with D, D/P, C, where C came from, and D by rule. The gate's own refusals
	// (drop_too_small, does_not_pay) are in the decision log, not here.
	RecentRefusals []V3Refusal `json:"recent_refusals,omitempty"`
}

V3Stats is the sweep v3 ledger for /stats.

func (V3Stats) Any added in v0.7.2

func (s V3Stats) Any() bool

Any reports whether v3 did or counted anything.

type WarmDecision added in v0.7.2

type WarmDecision struct {
	Thread string `json:"thread"`
	AtMs   int64  `json:"at_ms"`
	// Stage is "trigger" (before a question) or "apply" (the gate on a held answer).
	Stage  string `json:"stage"`
	Accept bool   `json:"accept"`
	// Reason is why a decision was a refusal ("" on accept).
	Reason string `json:"reason,omitempty"`
	// RemovedLocal and RemovedBilled are D: the tokens the drops would remove, by this package's count and
	// scaled by the content ratio. RewrittenLocal and RewrittenBilled are R: what the provider would write
	// again, scaled by the full ratio.
	RemovedLocal    int `json:"removed_local"`
	RemovedBilled   int `json:"removed_billed"`
	RewrittenLocal  int `json:"rewritten_local"`
	RewrittenBilled int `json:"rewritten_billed"`
	// Turns is N, the expected warm turns; Weight is the wait-cause weight at the apply (1 at the trigger,
	// which applies none).
	Turns  float64 `json:"turns"`
	Weight float64 `json:"weight"`
	// RatioFull and RatioContent are the billed-over-local ratios the gate used.
	RatioFull    float64 `json:"ratio_full"`
	RatioContent float64 `json:"ratio_content"`
	Deep         bool    `json:"deep"`
	// Proposed is how many drops the held answer carried into the recheck, and Dropped is what the recheck
	// removed from them, by reason (output_gone, content_changed, referenced_later, expanded, conversation_shorter).
	// Without it a refused apply read as "no valid drop" with no way to say why 59 to 87% of the judge's
	// drops were gone by the time the gate saw them. Apply stage only.
	Proposed int            `json:"proposed,omitempty"`
	Dropped  map[string]int `json:"dropped,omitempty"`
	// Carried and New split the merged answer the recheck saw: drops carried forward from earlier REFUSED
	// answers, and drops the newest question proposed (CarriedTokens and NewTokens are their Saves). Merged
	// D is RemovedLocal, the surviving set the gate priced. Apply stage only.
	Carried       int `json:"carried,omitempty"`
	New           int `json:"new,omitempty"`
	CarriedTokens int `json:"carried_tokens,omitempty"`
	NewTokens     int `json:"new_tokens,omitempty"`
	// TurnsModel says which model produced Turns: "expected" (warm_expected_turns), "cut" (turns left before
	// the conversation is cut, from the billed growth per turn) or "so_far_fallback" (the warm turns so
	// far). TurnsRaw is N before the warm_max_turns cap and the weight; Cut is the billed size the model
	// assumed the session runs to; GrowthPerTurn is the average billed growth per turn; TurnsWhy names why
	// the "cut" model was not used when it was not.
	TurnsModel    string  `json:"turns_model,omitempty"`
	TurnsRaw      float64 `json:"turns_raw"`
	Cut           int     `json:"cut,omitempty"`
	GrowthPerTurn float64 `json:"growth_per_turn,omitempty"`
	TurnsWhy      string  `json:"turns_why,omitempty"`
	// Saving and Rewrite are the gate's two sides in USD, so the refusal reads as numbers.
	Saving  float64 `json:"saving_usd"`
	Rewrite float64 `json:"rewrite_usd"`
	// Sweep v3 only: D as a share of P (the billed prompt), and P as a share of C (the cut point).
	DShareP float64 `json:"d_share_of_p,omitempty"`
	PShareC float64 `json:"p_share_of_c,omitempty"`
	// CutPoint is C in billed tokens, and CSource where it came from (cutfrac, compaction, window). v3 only.
	CutPoint int    `json:"cut_point,omitempty"`
	CSource  string `json:"c_source,omitempty"`
	// RuleD is D by what chose it: a rule name, or judge (v3 only), in billed tokens.
	RuleD map[string]int `json:"rule_d,omitempty"`
	// Sweep v3: the turns left if nothing were cut (N, the one the saving is priced on) and counted from the prompt
	// after the cut (N', for reading only), both capped by warm_max_turns and before the wait-cause weight.
	TurnsNoCut    float64 `json:"turns_no_cut,omitempty"`
	TurnsAfterCut float64 `json:"turns_after_cut,omitempty"`
	// PremiumUSD is the experiment premium the gate added to the saving (0 unless compaction_premium_usd is set and
	// the cut postpones the compaction). PassedOnCost says the saving to N alone beat the rewrite, so a run shows
	// which cuts needed the premium. Sweep v3 only.
	PremiumUSD   float64 `json:"premium_usd,omitempty"`
	PassedOnCost *bool   `json:"passed_on_cost,omitempty"`
}

WarmDecision is one trigger or apply-gate decision, accepted OR refused, with the numbers it was made on. A refused sweep used to record nothing, so a live run could not say why. Numbers only: the thread is a hash label and no content is in it.

type WarmSweep added in v0.7.2

type WarmSweep struct {
	Thread string `json:"thread"`
	AtMs   int64  `json:"at_ms"`
	Drops  int    `json:"drops"`
	// RemovedLocal is the tokens removed by this package's count; RemovedBilled is the same scaled by the
	// content ratio the gate used.
	RemovedLocal  int `json:"removed_tokens_local"`
	RemovedBilled int `json:"removed_tokens_billed"`
	// RewriteBilled is the rewrite the gate counted, billed-scaled.
	RewriteBilled int `json:"rewrite_tokens_billed"`
	// ConvBefore and ConvAfter are the conversation's local token count before and after the sweep.
	ConvBefore int `json:"conversation_before"`
	ConvAfter  int `json:"conversation_after"`
	// ExpectedTurns is the warm turns the gate expected; NetUSD is saving - rewrite over them.
	ExpectedTurns float64 `json:"expected_turns"`
	NetUSD        float64 `json:"expected_net_usd"`
	// Deep: the drop was deeper than the provider's look-back, so the rewrite was the whole conversation.
	Deep bool `json:"deep"`
}

WarmSweep is one applied warm sweep: what it removed, the conversation before and after, the gate's numbers and the net it expected. Numbers only: the thread is a hash label, never a session id.

Jump to

Keyboard shortcuts

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