offload

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Sep 4, 2026 License: Apache-2.0 Imports: 31 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

This section is empty.

Variables

View Source
var AllowEnvModelKey = true

AllowEnvModelKey permits an api_key-less `model:` block to fall back to this process's provider credential (OPENAI_API_KEY / ANTHROPIC_API_KEY / ANTHROPIC_AUTH_TOKEN). True for single-tenant use, where the config and the environment belong to the same person.

A hosted host sets it FALSE: there, the config document is written by a tenant and the environment holds the operator's credential, so the fallback would let any tenant bill their compaction to the operator — the one thing per-caller credentials exist to prevent. A block with no key then builds no client, and the component degrades (fail open).

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 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 KeptVerbatim added in v0.1.1

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

KeptVerbatim reports whether this content has already been marked. 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).

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, original string)

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

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 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.

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 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 (marker_or_kept_verbatim) 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 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 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 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) Enabled

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

func (Summarize) Name

func (Summarize) Name() string

func (*Summarize) NeedsModel

func (*Summarize) NeedsModel() bool

func (*Summarize) Offload

Jump to

Keyboard shortcuts

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