compaction

package
v2.1.1 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: MIT Imports: 16 Imported by: ? modules, 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 compaction makes replayable context decisions from recorded facts and immutable index metadata. It performs no content reads or workflow effects.

Index

Constants

View Source
const (
	// None leaves both view watermarks unchanged.
	None Tier = "none"
	// Clear advances only the cleared-result watermark.
	Clear Tier = "clear"
	// Evict advances the tail, possibly after clearing results.
	Evict Tier = "evict"
	// NoProgress suppresses repeated attempts until enough estimated growth.
	NoProgress SkipReason = "no_progress"
	// BelowMinSaving reports a tier-one saving too small to advance its watermark.
	BelowMinSaving SkipReason = "below_min_saving"
)

Variables

This section is empty.

Functions

func Canonical

func Canonical(settings Settings) []byte

Canonical encodes the fixed-order v1 settings without resolving B-dependent rules.

func DecodeCanonical

func DecodeCanonical(data []byte, settings *Settings) error

DecodeCanonical rejects unknown settings and unsupported canonical versions.

func EffectiveBudget

func EffectiveBudget(settings Settings, fact contextmeasure.RequestFacts) (int, error)

EffectiveBudget uses the pretend window only for threshold decisions. Facts retain real provider limits for the advisory guard and overflow recovery.

func Minimal

func Minimal(entries []index.MessageEntry, view index.ViewRef) bool

Minimal reports whether the latest atomic unit is the only tail and every result in it is forcibly cleared. A result-free newest unit is already minimal.

func NonTextCoverage

func NonTextCoverage(entries []index.MessageEntry) string

NonTextCoverage binds original non-text metadata without carrying part descriptors. Text-only additions and committing the same pending entries preserve this identity.

func NonTextResident

func NonTextResident(state State, entries []index.MessageEntry, settings Settings) (bool, string, string)

NonTextResident reports whether original attachments must remain resident.

func On

func On(state State, _ []index.MessageEntry, settings Settings) bool

On reports whether the recorded policy permits threshold compaction.

func RecoveryBudget

func RecoveryBudget(fact contextmeasure.RequestFacts, previewTokens int) index.RenderBudget

RecoveryBudget computes checkpoint defaults from the failed recorded model. Unknown windows use the existing component caps, with no live adapter lookup.

func Refill

func Refill(remaining, initial int) int

Refill adds ceil(initial/2), capped at three times initial. Settings validate positive initial values before workflow execution.

func RenderBudget

func RenderBudget(settings Settings, b, preview int) index.RenderBudget

RenderBudget resolves budget rules without changing the canonical settings.

func SummaryRate

func SummaryRate(state State) contextmeasure.Rate

SummaryRate selects the largest recorded text rate without map-order influence.

func SupportFingerprint

func SupportFingerprint(state State) string

SupportFingerprint binds first-observed call identities and immutable support.

func ToolResultParts

func ToolResultParts(state State) model.ToolResultPartSupport

ToolResultParts intersects the recorded support of every observed model. Model support is fixed on first observation, so adding models never widens it.

func ValidateAt

func ValidateAt(settings Settings, b int) error

ValidateAt checks resident and checkpoint capacity at the smallest adopted B.

func ValidateOverrides

func ValidateOverrides(registered Settings, overrides *ContextOverrides) error

ValidateOverrides checks presence-sensitive values and the merged start contract.

Types

type BudgetShortfallError

type BudgetShortfallError struct {
	Budget   int `json:"budget"`
	MaxBytes int `json:"max_bytes"`
	MinBytes int `json:"min_bytes"`
}

BudgetShortfallError names the recorded model budget that cannot render the default checkpoint. Recovery never increases that capacity or changes format.

func (*BudgetShortfallError) Error

func (e *BudgetShortfallError) Error() string

Error explains the byte shortfall while retaining the recorded token budget.

func (*BudgetShortfallError) Unwrap

func (e *BudgetShortfallError) Unwrap() error

Unwrap preserves the checkpoint renderer's budget category.

type Compatibility

type Compatibility struct {
	Coverage   string
	Support    string
	Checked    bool
	Compatible bool
	Reason     string
	Model      string
}

Compatibility is a compact result bound to original entries and model support.

type ContextModel

type ContextModel struct {
	ID                              string
	Class                           model.ModelClass
	AcceptsImages, AcceptsDocuments bool
}

ContextModel identifies a registered summariser and accepted evidence.

type ContextOverrides

type ContextOverrides struct {
	KeepNonTextResident       *bool          `json:"nontext_resident,omitzero"`
	Threshold                 *bool          `json:"threshold,omitzero"`
	MaxTier                   *Tier          `json:"max_tier,omitzero"`
	TriggerAt                 *Ratio         `json:"trigger_at,omitzero"`
	GuardMargin               *Ratio         `json:"guard_margin,omitzero"`
	DisableRecall             *bool          `json:"disable_recall,omitzero"`
	ContextModel              **ContextModel `json:"context_model,omitzero"`
	Summary                   *SummaryPrompt `json:"summary,omitzero"`
	KeepRecentTokens          *int           `json:"keep_recent_tokens,omitzero"`
	KeepUserTokens            *int           `json:"keep_user_tokens,omitzero"`
	ProtectRecentToolTokens   *int           `json:"protect_recent_tool_tokens,omitzero"`
	MinSavingTokens           *int           `json:"min_saving_tokens,omitzero"`
	MaxSummaryTokens          *int           `json:"max_summary_tokens,omitzero"`
	ReceiptTokens             *int           `json:"receipt_tokens,omitzero"`
	FramingTokens             *int           `json:"framing_tokens,omitzero"`
	MaxSummarisedResultTokens *int           `json:"max_summarised_result_tokens,omitzero"`
	MaxPins                   *int           `json:"max_pins,omitzero"`
	MaxPinnedParts            *int           `json:"max_pinned_parts,omitzero"`
	MaxSummaryChunks          *int           `json:"max_summary_chunks,omitzero"`
	RecallDiscoveryCalls      *int           `json:"recall_discovery_calls,omitzero"`
	RecallReadCalls           *int           `json:"recall_read_calls,omitzero"`
	RecallScanBytes           *int           `json:"recall_scan_bytes,omitzero"`
	ContextWindow             *int           `json:"context_window,omitzero"`
}

ContextOverrides replaces individual registered settings; nil fields inherit.

func (ContextOverrides) Clone

Clone detaches every pointer so callers cannot change submitted overrides.

func (*ContextOverrides) UnmarshalJSON

func (o *ContextOverrides) UnmarshalJSON(data []byte) error

UnmarshalJSON preserves an explicit null model as summaries-off, distinct from an omitted model which inherits the registered summariser.

type ContextSettings

type ContextSettings = Settings

ContextSettings snapshots both opt-in thresholds and always-on recovery.

type ContextSettingsError

type ContextSettingsError struct {
	Field string
	Value any
	Rule  string
	Model string
	B     int
}

ContextSettingsError identifies a rejected context setting before further work.

func (*ContextSettingsError) Error

func (e *ContextSettingsError) Error() string

Error describes both start-time and recorded model-budget failures.

type Decision

type Decision struct {
	View          index.ViewRef
	State         State
	Tier          Tier
	Before, After int
	Skipped       SkipReason
}

Decision returns the next view and state without mutating its inputs. A new TailFrom is an eviction intent; Phase 2 stores its receipt before adoption.

func Decide

func Decide(state State, entries []index.MessageEntry, view index.ViewRef, settings Settings) Decision

Decide applies tier one before choosing a closed-unit eviction cut. Only recorded entry sizes, facts and settings affect its result. Checkpoint size is conservatively MaxBytes until the caller can report a rendered size.

type Flags

type Flags struct{ Unmeasured, LimitsUnknown, BudgetTooSmall, NonTextResident, UnqualifiedStep bool }

Flags holds sticky observations for later workflow event emission.

type ModelState

type ModelState struct {
	Qualified       contextmeasure.QualificationTier
	ProviderConfig  string
	FirstCall       runstore.CallKey
	ToolResultParts model.ToolResultPartSupport
	Rate            contextmeasure.Rate
	Calibrated      bool
	Budget          int
	Known           bool
	FixedBytes      int
}

ModelState holds the last view-bearing measurements for one model. Rate is replaced only by usage-bearing facts, independently of the latest overhead.

type Qualification

type Qualification struct {
	Config                            string
	Models                            []string
	Tier                              Tier
	Freeze, Calibration, Report, Date string
}

Qualification records an exact provider/model context qualification.

func Qualifications

func Qualifications() []Qualification

Qualifications returns the shipped attestations. No providers are qualified until their exact configuration has a committed qualification report.

type Ratio

type Ratio struct{ Num, Den int }

Ratio is an exact rational configuration value. Den must be positive.

type RecallAllowances

type RecallAllowances struct {
	Discovery int `json:"discovery"`
	Reads     int `json:"reads"`
}

RecallAllowances tracks independently charged discovery and read calls.

func NewRecall

func NewRecall(settings Settings) RecallAllowances

NewRecall resolves zero settings to twenty calls for each allowance.

func (*RecallAllowances) Charge

func (a *RecallAllowances) Charge(read bool) bool

Charge consumes one call, returning false without changing an exhausted allowance.

func (RecallAllowances) Refilled

func (a RecallAllowances) Refilled(settings Settings) RecallAllowances

Refilled returns the allowances after one committed compaction of any tier.

type Recovery

type Recovery struct {
	View          index.ViewRef
	Tier          Tier
	Reached       bool
	Reason        string
	Before, After int
	Shortfall     *BudgetShortfallError
}

Recovery describes a pure view recomputation for a recorded failed request.

func Recover

func Recover(state State, entries []index.MessageEntry, view index.ViewRef, failure contextmeasure.ContextOverflow, settings Settings, boundBudget bool) Recovery

Recover uses only the failed request's recorded budget and the adopted rate. It ignores threshold protection and saving gates. Checkpoints are charged at MaxBytes even when a preceding activity measured a smaller rendering. boundBudget preserves protocol-15 effective ceilings; pre-15 records use false.

type RenderedCheckpoint

type RenderedCheckpoint struct {
	Hash     string
	TailFrom index.MessageID
	Budget   index.RenderBudget
	Bytes    int
}

RenderedCheckpoint qualifies an activity measurement by the rendering inputs.

type Settings

type Settings struct {
	Default                   bool                `json:"default,omitzero"`
	KeepNonTextResident       bool                `json:"nontext_resident,omitzero"`
	Threshold                 bool                `json:"threshold,omitzero"`
	MaxTier                   Tier                `json:"max_tier,omitzero"`
	GuardMargin               contextmeasure.Rate `json:"guard_margin,omitzero"`
	DisableRecall             bool                `json:"disable_recall,omitzero"`
	Summary                   SummaryConfig       `json:"summary,omitzero"`
	Prompt                    SummaryPrompt       `json:"prompt,omitzero"`
	ContextWindow             int                 `json:"context_window,omitzero"`
	KeepUserTokens            int                 `json:"keep_user_tokens,omitzero"`
	MaxSummaryTokens          int                 `json:"max_summary_tokens,omitzero"`
	ReceiptTokens             int                 `json:"receipt_tokens,omitzero"`
	FramingTokens             int                 `json:"framing_tokens,omitzero"`
	MaxSummarisedResultTokens int                 `json:"max_summarised_result_tokens,omitzero"`
	MaxPins                   int                 `json:"max_pins,omitzero"`
	MaxPinnedParts            int                 `json:"max_pinned_parts,omitzero"`
	MaxSummaryChunks          int                 `json:"max_summary_chunks,omitzero"`
	RecallScanBytes           int                 `json:"recall_scan_bytes,omitzero"`
	TriggerAt                 contextmeasure.Rate
	KeepRecentTokens          int `json:"keep_recent_tokens,omitzero"`
	ProtectRecentToolTokens   int `json:"protect_recent_tool_tokens,omitzero"`
	MinSavingTokens           int `json:"min_saving_tokens,omitzero"`
	RecallDiscoveryCalls      int
	RecallReadCalls           int
}

Settings holds per-run trigger settings. Zero fields resolve to the design defaults against the smallest recorded usable model budget.

func Merge

func Merge(registered Settings, overrides *ContextOverrides) Settings

Merge owns effective settings and retains zero token values as budget rules. Call ValidateOverrides before Merge to distinguish explicit zero from inheritance.

func (Settings) RecallPageBytes

func (s Settings) RecallPageBytes(budget int) int

RecallPageBytes returns the byte page bound from the resolved protected result setting. The minimum allows a useful page even at the smallest supported window.

func (Settings) RecallPartTokens

func (s Settings) RecallPartTokens(budget int) int

RecallPartTokens bounds each recalled attachment by the protected result budget.

type SkipReason

type SkipReason string

SkipReason explains an attempted or suppressed threshold compaction.

type State

type State struct {
	// Compatibility holds the last durably adopted attachment check.
	Compatibility Compatibility
	// ValidateBudgets enables strict mid-run validation for explicit run overrides.
	// This provenance is separate from the canonical effective settings.
	ValidateBudgets bool
	// InvalidLimitsModel retains the first invalid override diagnostic identity.
	InvalidLimitsModel string
	Summary            SummaryState
	Recall             RecallAllowances
	Models             map[string]ModelState
	MinB               int
	// EffectiveWindow is the window of the fact that established MinB.
	LimitingModel   string
	EffectiveWindow int
	NoProgressAt    int
	OpenFrom        index.MessageID
	Flags           Flags
	// Rendered records the last adopted checkpoint measurement.
	Rendered RenderedCheckpoint
}

State is reconstructed from adopted facts and preceding decisions. OpenFrom is the first entry of an open await/confirmation/clarification, set by the caller from workflow state before Decide; zero means no open suffix.

func Observe

func Observe(state State, facts []contextmeasure.RequestFacts) State

Observe adopts facts in recorded call order. Non-view-bearing calls never change model rates or budgets. MinB only falls, and small-budget disablement lasts for the run, even if a later call reports a larger window.

func ObserveEffective

func ObserveEffective(state State, facts []contextmeasure.RequestFacts, settings Settings) (State, error)

ObserveEffective adopts real facts using the immutable run's trigger window. It checks budgets when a view-bearing model first supplies B or lowers MinB. Only explicit run overrides or a pretend window make a shortfall fatal.

type SummaryConfig

type SummaryConfig struct {
	Enabled  bool
	Model    ContextModel
	Settings SummarySettings
}

SummaryConfig is an immutable run-stamped snapshot, comparable by value.

type SummaryPrompt

type SummaryPrompt struct {
	Ref      prompt.PromptRef
	Template runstore.Hash
}

SummaryPrompt pins the resolved summary template in the root content scope.

type SummarySettings

type SummarySettings struct{ Instructions, Prompt string }

SummarySettings customizes the baseline prompt.

type SummaryState

type SummaryState struct {
	Rejections int
	Disabled   bool
}

SummaryState counts non-stale summary rejections for this run.

func (SummaryState) Reject

func (s SummaryState) Reject(kind string) SummaryState

Reject counts a summary rejection; stale results and the disable notification do not count.

type Tier

Tier names the strongest transformation requested by a decision.

const (
	// Preview bounds all newest-unit result previews evenly.
	Preview Tier = "preview"
	// Placeholder replaces newest-unit results, including Keep results.
	Placeholder Tier = "placeholder"
	// MinPreviewBytes is the smallest preview before replacing results.
	MinPreviewBytes = 256
)
const Summary Tier = "summary"

Summary is the strongest threshold tier; recovery is independent of MaxTier.

func EffectiveTier

func EffectiveTier(state State, settings Settings) Tier

EffectiveTier limits default transformations to the recorded qualification.

func LookupQualification

func LookupQualification(qualifications []Qualification, config, modelID string) Tier

LookupQualification matches only exact normalized pairs in supplied attestations.

func ObservedQualifiedTier

func ObservedQualifiedTier(state State) Tier

ObservedQualifiedTier folds immutable recorded model qualifications.

func QualifiedTier

func QualifiedTier(config, modelID string) Tier

QualifiedTier looks up an exact pair in the shipped qualification table.

Jump to

Keyboard shortcuts

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