modes

package
v0.6.7 Latest Latest
Warning

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

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

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

Documentation

Overview

Package modes holds the per-session state context-guru's operating modes need.

Today that is one thing: the cached-prefix boundary, i.e. how many normalized messages the previous turn of a session carried. Everything at or below it is already committed to the provider's cache, so supersession/age-based offloaders must confine their mutations to the tail above it (components.Ctx.MaxCachedIdx).

It lives here rather than in the TTL store because it is turn accounting, not cached payload, and because reading it and recording the new value must be ONE atomic step. The previous implementation read it from the store and wrote it back in a `defer`, so two concurrent turns of one session raced: both read the same length, and the second's write-back could land before the first's, leaving the boundary describing neither turn. A boundary that is too high lets an offloader mutate content the provider has cached, which costs a full cache-write of the suffix.

Index

Constants

View Source
const (
	DefaultMaxQueue = 256
	DefaultWorkers  = 1
)

Defaults for the pool's two knobs. One worker is deliberate: an observation may make a cheap-model call, and one in flight per process keeps that spend and the gateway's rate limit predictable while still keeping the work off the request path.

View Source
const DefaultMaxKeys = 4096

DefaultMaxKeys bounds the tracker so an unbounded stream of distinct keys cannot grow it without limit. The key is a THREAD (thread.Key), not a session (#484), so one busy session holds one entry per subagent and per side request. 4,096 entries of about 40 bytes plus the key is well under 1 MB. Exported so other per-thread maps (extract_llm's growth record) use the same bound.

View Source
const StaleAfter = 6 * time.Hour

StaleAfter is how long a key may go without a request before the tracker may expire it. It is a MEMORY bound, not a cache verdict: a keep-alive can hold a provider entry warm with no request at all, so an expired key is remembered as dropped (see Tracker.dropped) and never read as "nothing cached". 6 hours is far past the longest provider TTL (1 hour) plus the default keep-alive span.

Variables

This section is empty.

Functions

func Boundary

func Boundary(prev, n int) int

Boundary returns the cached-prefix boundary a turn carrying n normalized messages must be built against, given that the previous turn of the same session carried prev.

A SHRINK means compaction: the agent replaced its own transcript with a summary and continued, so this request is not an extension of the one prev was recorded against — prev describes message indices that no longer exist. The boundary restarts at 0 (whole request is the mutable tail) so components can act against the NEW prefix, and the reset is counted.

The rule is "any shrink", not "a shrink past some fraction". Distinguishing a real compaction from a rewind/retry/truncated resend would need content comparison on the hot path, and a fractional threshold silently misses a partial compaction (Claude Code's "RECENT portion" bodies trim far less than half). The trade is asymmetric: a spurious reset costs at most one bounded cache-write over a transcript that is by definition SHORTER (and the freeze/reapply machinery keeps the resulting decision byte-stable thereafter), while failing to reset freezes every message of every later turn for the REST OF THE SESSION — savings gone permanently. So reset, and count it.

This replaces the older "the boundary only ever grows" rule, which was load-bearing only while a compaction flipped the session id and started the tracker fresh. Its stated reason — content the provider already cached would fall back into the mutable tail — does not survive a real compaction: the agent has already replaced that content, so the provider's cached prefix stops matching beyond the common head no matter what we do. The invalidation has happened; rewriting the new tail is not what costs it.

One consequence, deliberate: two CONCURRENT turns of one session that arrive out of order now look like a shrink, so the later-but-shorter one resets and reports a compaction. That is lost savings for one turn, never a wrong rewrite, and per-session concurrency is not how agents talk.

func CompactionResets

func CompactionResets() int64

CompactionResets returns the cumulative compaction resets since process start.

Types

type Pool

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

Pool is the bounded off-path worker pool observe mode measures on: one queue, a fixed number of drain goroutines, owned by the host rather than spawned per request.

The shape is headroom's BackgroundCompressor, ported:

  • a bounded queue that DROPS rather than blocks — the request has already been forwarded, so a drop costs a measurement, never correctness, and the request path must never wait on this;
  • dedup by key, with the pending slot claimed BEFORE the job becomes observable in the queue, so dedup is atomic against a concurrent enqueue of the same key;
  • no request-coupled deadline: jobs run under the pool's own context, not the inbound request's, which is cancelled the moment the response is written;
  • fail-open on every path, including a panicking job;
  • the FULL counter tuple exposed, `dropped` included. headroom's dashboard shows only `queued`, which hides exactly the counter that says "we silently gave up a measurement".

func NewPool

func NewPool(maxQueue, workers int) *Pool

NewPool builds and starts a pool. maxQueue/workers <= 0 take the defaults. Call Stop to shut it down; a stopped pool drops every later enqueue.

func (*Pool) Enqueue

func (p *Pool) Enqueue(key string, run func(context.Context)) bool

Enqueue queues run under key, returning false if it was dropped — because the key is already queued or in flight, the queue is full, or the pool is stopped. Never blocks.

func (*Pool) Stats

func (p *Pool) Stats() Stats

Stats returns the counter tuple.

func (*Pool) Stop

func (p *Pool) Stop() bool

Stop cancels the pool's context and waits briefly for its workers to exit. Queued jobs are abandoned — they were measurements, and the requests they belonged to went out long ago. Returns false if a worker was still running at the grace deadline (its goroutine is left to exit on its own; nothing depends on its result). Idempotent.

type Stats

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

Stats is the queue's counter tuple, surfaced whole in /stats.

type Tracker

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

Tracker holds the cached-prefix boundary per key (a session, or one thread of a session), each key's state guarded by one lock so concurrent turns cannot interleave a read and a write.

func NewTracker

func NewTracker(maxKeys int) *Tracker

NewTracker returns an empty tracker. maxKeys <= 0 uses DefaultMaxKeys.

func (*Tracker) Sessions

func (t *Tracker) Sessions() int

Sessions reports how many sessions are tracked (test/telemetry aid).

func (*Tracker) SetLastSeen added in v0.6.4

func (t *Tracker) SetLastSeen(f func(key string) (atMs int64, known, have bool))

SetLastSeen gives the tracker a "last seen" lookup for the restart grace (#766): when this key's cached prefix was last refreshed, as far as state that survived the restart knows — by the thread's own last request or by a keep-alive ping that read the cache; the host decides what counts. The proxy sets it from the dashboard recorder, which reloads that time per thread at startup; the library itself must not import dash, so the host hands the function in. Three answers: known=true carries the timestamp; known=false with have=true says "looked, never seen" (a new thread); have=false says "cannot answer for this key" (no database, or a deployment whose rows carry no session id), and #759's start-time rule answers instead. Startup setting, like SetRestartGrace. The lookup runs under the tracker's lock, so it must not call back into the tracker; a panic inside it reads as "no lookup", so a broken lookup cannot fail a request.

func (*Tracker) SetRestartGrace added in v0.6.3

func (t *Tracker) SetRestartGrace(on bool)

SetRestartGrace switches the restart grace on or off. The grace's LENGTH is per request (the caller passes the cache lifetime to TurnFrom); this is only the on/off switch, which the host passes its setting to (the proxy's --restart-grace). A benchmark that sends whole transcripts to a fresh proxy switches it off. Startup setting, not a live knob.

func (*Tracker) SetStartedAt added in v0.6.3

func (t *Tracker) SetStartedAt(ms int64)

SetStartedAt sets the tracker's start time (unix milliseconds). NewTracker stamps the real clock; a test can set a past time to build a tracker BEYOND its restart grace (#496) without waiting for the grace to pass.

func (*Tracker) Turn

func (t *Tracker) Turn(session string, n int) (prevLen int)

Turn records that this session's current turn carries n normalized messages and returns the PREVIOUS turn's count — the cached-prefix boundary the request must be built against. Read and write happen under one lock, which is what removes the race described in the package comment.

A shorter transcript under the same session id is the agent's own compaction, and resets the boundary to 0 — see Boundary for the rule and why it is not "grow only".

func (*Tracker) TurnAt

func (t *Tracker) TurnAt(session string, n int, nowMs int64, grace time.Duration) (prevLen int, prevAtMs int64)

TurnAt is Turn plus the previous turn's timestamp, so the caller can tell how long this session has been idle. nowMs of 0 means "do not record a time" (the legacy Turn path); the clock is the caller's so this stays a pure, testable function. grace is this request's cache lifetime; it matters only for a key with no record (see TurnFrom).

prevAtMs is 0 when there is no previous turn recorded — a new session, or one evicted by the bound above. A caller MUST treat that as "unknown", never as "idle forever": acting on a fabricated idle time is how a warm cache gets invalidated after a proxy restart.

func (*Tracker) TurnFrom added in v0.5.0

func (t *Tracker) TurnFrom(key, parent, aliasKey, aliasParent string, n int, nowMs int64, grace time.Duration) (prevLen int, prevAtMs int64)

TurnFrom is TurnAt for a key that may be a NEW thread continuing another thread's prefix.

parent is the key of the thread this one inherits from ("" for none): Claude Code's side requests (title, quota check, end-of-turn note) and forks start with the main thread's whole transcript, which the provider already holds. When key has no record of its own, its boundary and idle clock come from parent's record, so the first request of such a thread protects the cached prefix it reads. parent's record is only READ, never written: the parent's next request must still be measured against its own last request (#484).

aliasKey and aliasParent are the SAME thread and parent under the session's ALIAS id (also "" for none): one conversation can reach the proxy under two ids — an explicit session header on some turns and a content-derived id on others — so a record under either id says the prefix is warm. The restart grace asks the last-seen lookup for both keys and takes the LATER timestamp, the same widening apply.go gives the cold decision's alias clock. They matter only in the grace; the tracker's own records stay keyed by the id the request carried.

The inherited boundary is min(parent's count, n): a fork shorter than its parent diverged somewhere inside the parent's prefix, and freezing all of it is the safe direction. It is never counted as a compaction.

A key the tracker dropped (evicted or expired), or a new key whose parent was dropped, gets prevLen = n: the whole request is treated as cached, so nothing changes on this one turn, and the next turn has a real record again.

The same answer serves a proxy restart (#496, #766): a key with no record, no drop and no usable parent falls to the restart grace, which asks the host's last-seen lookup (SetLastSeen) for when this thread's cached prefix was last refreshed — its own last request, a ping that read the cache, under either session id. Inside this request's cache lifetime (the caller passes it as grace) the key reads as all-cached, because the process forgot the record, not the provider the prefix; past it the thread is expired — cold, not new. A key the lookup does not know under either id is a really new thread: nothing is cached, so its first request is editable as usual. Without a lookup (no database, dashboard off, or one that declines the key — an observe-mode deployment records no session ids), #759's start-time rule answers instead, and the host can switch the grace off entirely (SetRestartGrace).

Jump to

Keyboard shortcuts

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