Skip to main content

engine.solvers.context

engine.solvers.context

Context-engineering solvers: what one agent request carries, and what it costs.

Domain implementations behind mlsysim.solvers (added 2026-10-20). Each model is arithmetic on serialized token counts: a budget by role against the window, one attention head’s softmax over fixed logits, the input bill of a zoned layout under prefix reuse, compaction between two watermarks, the edits that retire a stale observation, and the cost per accepted task of a protected-field check. None models tokenization across joins, cache eviction, or a trained model’s attention.

Classes

Name Description
AttentionDilutionModel One head’s weight on a target key among keys whose logits stay fixed.
CompactionCadenceModel Compaction between a trigger and a target watermark (hysteresis).
ContextBudgetModel A request budgeted by role: S_sys + S_tools + S_state + S_obs <= S_max - K_max.
ContextInvalidationModel Three edits that retire a superseded excerpt at the start of the trunk.
PrefixLayoutBillModel Input bill of turns calls whose requests are ordered root, trunk, leaf.
ProtectedFieldCheckModel Cost per accepted task with and without a protected-field check at each compaction.

AttentionDilutionModel

engine.solvers.context.AttentionDilutionModel()

One head’s weight on a target key among keys whose logits stay fixed.

short_keys and long_keys count every key, the target included, at background_logit. The look-alike case counts competitors only: unrelated_keys at the background logit plus lookalike_keys at the higher lookalike_logit of text that shares the evidence’s identifiers. A sufficient condition for dilution, not a forecast of a trained model.

Methods

Name Description
solve Compare target attention mass under fixed-logit key populations.
solve
engine.solvers.context.AttentionDilutionModel.solve(
    target_logit,
    background_logit,
    short_keys,
    long_keys,
    unrelated_keys=None,
    lookalike_keys=None,
    lookalike_logit=None,
)

Compare target attention mass under fixed-logit key populations.

Parameters
Name Type Description Default
target_logit float Finite dimensionless logit of the target key. required
background_logit float Finite dimensionless logit shared by ordinary competing keys. required
short_keys int Positive total key count in the short case, including the target. required
long_keys int Positive total key count in the long case, including the target. required
unrelated_keys int Nonnegative competitor count, excluding the target, for the look-alike case. None
lookalike_keys int Nonnegative look-alike competitor count; provide with unrelated_keys. None
lookalike_logit float Finite logit of each look-alike; required when both competitor counts are supplied. None
Returns
Name Type Description
AttentionDilutionResult Dimensionless target weights and optional equivalent-key counts under the supplied logit populations.
Notes

Equation: Target mass is exp(z_target) / (exp(z_target) + sum_j n_j*exp(z_j)). Equivalent background keys equal n_look*exp(z_look-z_background).

Assumptions: The logits stay fixed when competitors are added. Each member of a population has the same logit; counts are not learned.

Excludes: Queries changing with context, positional effects, multiple heads, value aggregation, and any prediction of answer accuracy.

References

Derivation: The softmax denominator sums one exponential per key. Grouping identical logits gives n_j*exp(z_j); equating denominator contributions yields equivalent-key count. Helpers live in physics.context.

Examples
>>> from mlsysim.solvers import AttentionDilutionModel
>>> result = AttentionDilutionModel().solve(1.0, 0.0, 2, 8)
>>> result.long_weight < result.short_weight
True

CompactionCadenceModel

engine.solvers.context.CompactionCadenceModel()

Compaction between a trigger and a target watermark (hysteresis).

Each turn appends delta tokens; a pass fires on the first turn that reaches the trigger and resets the request to the target, so passes come every ceil((trigger - target) / delta) turns. The trigger is soft: the request can overshoot it by less than one append, and the output reserve must still fit. An optional alternate target prices a narrower gap.

Methods

Name Description
solve Trace fixed-growth context between compaction watermarks.
solve
engine.solvers.context.CompactionCadenceModel.solve(
    window,
    output_reserve,
    target,
    trigger,
    tokens_per_turn,
    turns,
    alternate_target=None,
)

Trace fixed-growth context between compaction watermarks.

Parameters
Name Type Description Default
window int Positive context-window capacity, in tokens. required
output_reserve int Nonnegative output-token reservation. required
target int Nonnegative token count immediately after each compaction. required
trigger int Token watermark above target that triggers a compaction. required
tokens_per_turn int Positive token increment appended on every turn. required
turns int Nonnegative number of appended turns to trace. required
alternate_target int Alternative nonnegative reset length below trigger; None omits its trace. None
Returns
Name Type Description
CompactionCadenceResult Integer cycle length and token traces, pass counts, overshoot, and whether the peak request plus reservation fits the window.
Notes

Equation: Cycle length is ceil((trigger - target)/tokens_per_turn). Peak length is target + cycle*tokens_per_turn; passes equal turns//cycle.

Assumptions: Compaction instantly resets length to target after the turn that reaches the trigger. The trigger is soft and can be overshot.

Excludes: Summarizer runtime, fidelity loss, variable observation sizes, and interruptions while compaction runs.

References

Derivation: The first integer increment count reaching the trigger is the ceiling of its distance from target divided by tokens_per_turn. Repeating that reset yields the trace in _trace and the cycle helper in physics.context.

Examples
>>> from mlsysim.solvers import CompactionCadenceModel
>>> result = CompactionCadenceModel().solve(100, 10, 20, 60, 10, 8)
>>> result.fits_window and result.passes > 0
True

ContextBudgetModel

engine.solvers.context.ContextBudgetModel()

A request budgeted by role: S_sys + S_tools + S_state + S_obs <= S_max - K_max.

Appending every tool result grows S_obs by delta per turn until the observation budget overflows, and resends the history, so the input bill grows quadratically. Selecting a fixed observation share keeps every request the same size and the bill linear. Bills assume no prefix reuse and, for the appending policy, a window large enough to admit every request.

Methods

Name Description
solve Compare appending and selecting observations within a token budget.
solve
engine.solvers.context.ContextBudgetModel.solve(
    window,
    output_reserve,
    system_tokens,
    tool_tokens,
    state_tokens,
    observation_per_turn,
    selected_observation,
    turns,
    digest_tokens,
)

Compare appending and selecting observations within a token budget.

Parameters
Name Type Description Default
window int Positive total context-window capacity, in tokens. required
output_reserve int Nonnegative reply reservation, in tokens, no larger than window. required
system_tokens int Nonnegative serialized system-instruction count, in tokens. required
tool_tokens int Nonnegative serialized tool-descriptor count, in tokens. required
state_tokens int Nonnegative retained-state count, in tokens. required
observation_per_turn int Positive count of observation tokens appended each turn. required
selected_observation int Nonnegative observation tokens selected for each fixed-size request. required
turns int Positive number of requests to account for. required
digest_tokens int Positive tokens per digest, used for an alternative capacity calculation. required
Returns
Name Type Description
ContextBudgetResult Token budgets and per-turn request traces, integer overflow turns, cumulative token bills, and dimensionless ratios.
Notes

Equation: Observation budget is window - output_reserve - system_tokens - tool_tokens - state_tokens. Appending sums fixed + t*observation_per_turn for t=1..turns; selection sends turns*(fixed + selected_observation).

Assumptions: Counts are already serialized tokens. Fixed roles fit inside the input budget; selected requests are nonempty. The append bill counts all requested turns even when their sizes exceed the supplied window.

Excludes: Cache reuse, tokenization across joins, retrieval quality, compaction cost, and automatic rejection or truncation of oversized requests.

References

Derivation: Subtract reserved roles from a finite capacity, then sum an arithmetic progression for appending and a constant sequence for selection. The helpers in physics.context compute remaining capacity and integer fit.

Examples
>>> from mlsysim.solvers import ContextBudgetModel
>>> result = ContextBudgetModel().solve(100, 10, 5, 5, 10, 10, 10, 3, 5)
>>> result.append_bill > result.select_bill
True

ContextInvalidationModel

engine.solvers.context.ContextInvalidationModel()

Three edits that retire a superseded excerpt at the start of the trunk.

Removing it or replacing it in place with a short marker changes the request right after the reused root, so every later token is prefilled again; appending a notice keeps the prefix and prefills only the notice, but leaves the stale tokens resident on every later call.

Methods

Name Description
solve Count cache suffixes for three ways to retire stale text.
solve
engine.solvers.context.ContextInvalidationModel.solve(
    request_tokens,
    prefix_tokens,
    superseded_tokens,
    marker_tokens,
    notice_tokens,
)

Count cache suffixes for three ways to retire stale text.

Parameters
Name Type Description Default
request_tokens int Positive original request length, in tokens. required
prefix_tokens int Nonnegative reusable prefix ending before the superseded passage. required
superseded_tokens int Nonnegative passage length; prefix plus passage must fit the request. required
marker_tokens int Nonnegative replacement-marker length. required
notice_tokens int Positive length of a notice appended after the original request. required
Returns
Name Type Description
ContextInvalidationResult Total and newly prefilling suffix lengths in tokens for deletion, replacement, and append, plus a dimensionless suffix ratio.
Notes

Equation: Deletion leaves request_tokens - superseded_tokens; replacement adds marker_tokens. Their fresh suffix starts at prefix_tokens. Appending adds notice_tokens, all of which are new.

Assumptions: Cached prefix validity ends exactly at the first edited token. The appended notice leaves every original token resident.

Excludes: Semantic compliance with the notice, cache eviction, tokenization changes at edit boundaries, and the cost of editing.

References

Derivation: Subtract removed spans and add inserted spans to obtain total length. Subtract the unchanged prefix to obtain work requiring fresh prefill.

Examples
>>> from mlsysim.solvers import ContextInvalidationModel
>>> result = ContextInvalidationModel().solve(100, 20, 30, 5, 5)
>>> result.removed_total < result.replaced_total < result.appended_total
True

PrefixLayoutBillModel

engine.solvers.context.PrefixLayoutBillModel()

Input bill of turns calls whose requests are ordered root, trunk, leaf.

With a volatile field first, no prefix is reused and every input token is billed at full price. Ordered by change rate, the first call is cold, each trunk rewrite prefills trunk and leaf, and every other call prefills only the leaf; reused tokens are billed at cached_fraction of the price. Assumes compatible cached state is retained; prices only input tokens.

Methods

Name Description
solve Price repeated requests with root, trunk, and leaf cache zones.
solve
engine.solvers.context.PrefixLayoutBillModel.solve(
    turns,
    root_tokens,
    trunk_tokens,
    leaf_tokens,
    trunk_rewrites,
    input_price,
    cached_fraction,
)

Price repeated requests with root, trunk, and leaf cache zones.

Parameters
Name Type Description Default
turns int Positive number of calls. required
root_tokens int Nonnegative tokens in the unchanged root prefix. required
trunk_tokens int Nonnegative tokens in the occasionally rewritten trunk. required
leaf_tokens int Positive tokens in the per-call leaf. required
trunk_rewrites int Number of trunk changes after the cold call, from zero through turns - 1. required
input_price Quantity Nonnegative uncached price, convertible to USD/token; positive for cost ratios. required
cached_fraction float Cached-input price as a fraction of uncached price, in [0, 1]. required
Returns
Name Type Description
PrefixLayoutBillResult Token counts, dimensionless reuse and cost ratios, and USD-valued total and per-call bills for the two layouts.
Notes

Equation: Total input is turns*(root + trunk + leaf). Fresh prefill is root + trunk + leaf + trunk_rewrites*(trunk + leaf) + (turns - 1 - trunk_rewrites)*leaf; cached input is the remainder.

Assumptions: The first call is cold. Compatible cached state remains available, and each trunk rewrite invalidates all following tokens.

Excludes: Cache eviction, output-token bills, latency, and differences in answer quality between layouts.

References

Derivation: Partition calls into cold, trunk-rewrite, and leaf-only cases. Sum their newly computed tokens, then charge cached tokens at the stated price fraction. physics.context.calc_zoned_prefill_tokens owns the count.

Examples
>>> from mlsysim import Q_
>>> from mlsysim.solvers import PrefixLayoutBillModel
>>> result = PrefixLayoutBillModel().solve(3, 20, 10, 5, 0, Q_(1, "USD/token"), 0.5)
>>> result.stable_cost < result.unstable_cost
True

ProtectedFieldCheckModel

engine.solvers.context.ProtectedFieldCheckModel()

Cost per accepted task with and without a protected-field check at each compaction.

Each of constraints is lost independently with loss_per_round in each of rounds; a lost constraint makes the task unacceptable, so acceptance is p_intact (1 - eps)^(n R). A check that detects detection of losses and repairs them leaves eps (1 - detection) per round and adds check_cost per round to the attempt.

Methods

Name Description
solve Compare acceptance cost with checks at context compactions.
solve
engine.solvers.context.ProtectedFieldCheckModel.solve(
    constraints,
    loss_per_round,
    rounds,
    acceptance_if_intact,
    attempt_cost,
    detection,
    check_cost_per_round,
    survival_floor,
    target_survival=None,
)

Compare acceptance cost with checks at context compactions.

Parameters
Name Type Description Default
constraints int Positive number of protected constraints exposed at each compaction. required
loss_per_round float Independent loss probability per constraint per round, in (0, 1). required
rounds int Positive number of compaction rounds. required
acceptance_if_intact float Task acceptance probability conditional on intact constraints, in (0, 1]. required
attempt_cost Quantity Positive unchecked attempt cost, convertible to USD. required
detection float Fraction of losses detected and repaired, in [0, 1); exact one is outside the horizon-ratio calculation. required
check_cost_per_round Quantity Nonnegative cost of each check in USD. required
survival_floor float Probability in (0, 1) used to locate the first unacceptable round count. required
target_survival float Desired intact probability in (0, 1); None omits the inverse loss budget. None
Returns
Name Type Description
ProtectedFieldCheckResult Dimensionless survival and acceptance probabilities, USD-valued scalar costs, exposure counts, and optional maximum loss probability.
Notes

Equation: With N=constraints*rounds and loss e, survival is (1-e)**N. Checking changes e to e*(1-detection) and adds rounds*check_cost_per_round to attempt cost. Effective cost divides attempt cost by acceptance.

Assumptions: Losses are independent; all detected losses are repaired. Every constraint must remain intact, and checking has no other side effects.

Excludes: Correlated loss, imperfect repairs, false alarms, and measured quality improvements; detection and conditional acceptance are inputs.

References

Derivation: Multiply survival probabilities across constraint-round exposures, then multiply by conditional acceptance. Expected repeated-attempt cost follows the geometric identity implemented in physics.agents.

Examples
>>> from mlsysim import Q_
>>> from mlsysim.solvers import ProtectedFieldCheckModel
>>> result = ProtectedFieldCheckModel().solve(2, 0.1, 3, 0.9, Q_(1, "USD"), 0.5, Q_(0.1, "USD"), 0.8)
>>> result.survival_checked > result.survival_unchecked
True
Back to top