Skip to content

API Reference parrot.tools.compression.budget

github-actions[bot] edited this page Dec 2, 2026 · 4 revisions

parrot.tools.compression.budget

View source

Latency budget router + per-codec circuit breaker (G7, G9).

Decides, from a cheap size estimate taken BEFORE compressing, whether a codec call runs inline, is offloaded to an executor (meaningful only when the Rust extension releases the GIL via py.allow_threads()), or is skipped entirely (passthrough). A per-codec :class:CircuitBreaker self-degrades a sustainedly over-budget codec to passthrough.

Without the Rust extension, run_in_executor buys no real parallelism — the GIL is still held, so offloading is theater. Sending a fat payload uncompressed beats stalling the event loop (G9): that is why the "over threshold, no Rust" route is PASSTHROUGH, not EXECUTOR.

Default calibration (TASK-1959, 2026-07-28): the spec's original defaults (inline_budget_ms=1.0, minimal_budget_ms=0.3, row_threshold=5000) were explicit proposals pending measurement (spec Sec 3 Module 5: "All values configurable; a benchmark task calibrates them against real payloads"). Measured against pure-Python codecs (no Rust extension) on a 500-row x 12-col payload (Intel i7-9850H @ 2.60GHz, Python 3.11.15): json_compact MINIMAL p99 ~= 4.6ms, columnar NORMAL p99 ~= 2.8ms — both well above the original budgets. The defaults below reflect that measurement; see tests/tools/compression/test_benchmarks.py (opt-in, PARROT_RUN_BENCHMARKS=1) and TASK-1959's Completion Note for the full table and reasoning. executor_budget_ms is unchanged (15.0) — no Rust extension exists yet to measure the off-loop path against (TASK-1955); recalibrate once it lands.

Class BudgetRouter

Pre-compression latency-budget router + circuit breaker (G7, G9).

Combines the route decision table from spec Sec 3 Module 5 with a per-codec :class:CircuitBreaker. All thresholds are configurable via constructor kwargs; defaults match the spec.

Parameter Type Default Description
size_threshold_bytes int 256 * 1024
row_threshold int 1500
window_calls int 100
window_seconds float 60.0
consecutive_windows int 3
cooldown_seconds float 300.0
inline_budget_ms float 3.0
minimal_budget_ms float 5.0
executor_budget_ms float 15.0
time_fn Callable[[], float] time.monotonic

Method BudgetRouter.route

Decide where a codec call should run, from a size estimate taken BEFORE compressing. The codec itself is never constructed or invoked to make this decision — synchronous, no I/O, no await.

route(payload: Any, *, level: FilterLevel, codec_name: str, rust_available: bool) -> Route

Parameter Type Default Description
payload Any The unwrapped tool result that would be compressed.
level FilterLevel Effective :class:FilterLevel for this call.
codec_name str Name of the codec that would run (breaker key).
rust_available bool Whether the parrot_codec Rust extension is available (see :func:is_rust_available).

Returns: Route — class:Route to take.

Method BudgetRouter.record

Feed a completed call's duration into the circuit breaker.

record(codec_name: str, duration_ms: float, route: Route, level: Optional[FilterLevel] = None) -> None

Parameter Type Default Description
codec_name str Name of the codec that ran.
duration_ms float Wall-clock duration of the call, in milliseconds.
route Route The :class:Route the call actually took.
level Optional[FilterLevel] None The effective :class:FilterLevel for this call. Needed to judge MINIMAL-level (always-INLINE) calls against minimal_budget_ms instead of the coarser inline_budget_ms (code-review fix). None preserves the pre-fix behavior (judged as a generic inline call).

Method BudgetRouter.p99

Rolling p99 duration (ms) for codec_name. See :meth:CircuitBreaker.p99; exposed for TASK-1957's savings report.

p99(codec_name: str) -> float | None

Parameter Type Default Description
codec_name str

Returns: float | None

Class CircuitBreaker

Per-codec rolling-window circuit breaker (G7).

A codec that sustainedly busts its latency budget self-degrades to Route.PASSTHROUGH. Rolling windows close on window_calls calls OR window_seconds elapsed, whichever comes first. A window with zero calls does not advance the consecutive-over-budget count. consecutive_windows consecutive over-budget windows open the breaker; after cooldown_seconds it enters a half-open state that allows exactly one probe call through — success re-arms (closes) the breaker, failure reopens it and restarts the cooldown.

The breaker is keyed per codec: degrading one codec never affects another's routing.

Parameter Type Default Description
window_calls int 100
window_seconds float 60.0
consecutive_windows int 3
cooldown_seconds float 300.0
inline_budget_ms float 3.0
minimal_budget_ms float 5.0
executor_budget_ms float 15.0
time_fn Callable[[], float] time.monotonic

Method CircuitBreaker.is_open

Return True if the breaker currently blocks calls for codec_name (fully open, cooldown not yet elapsed, OR a probe is already in flight).

When the cooldown has elapsed, transitions the breaker to half-open (allows exactly one probe call) and returns False. Also lazily expires a stale, zero-call window purely on elapsed time (a window is only ever advanced/closed on a record() call otherwise, which would never observe a truly empty window).

is_open(codec_name: str) -> bool

Parameter Type Default Description
codec_name str

Returns: bool

Method CircuitBreaker.record

Feed a completed call's duration into the breaker.

record(codec_name: str, duration_ms: float, route: Route, level: FilterLevel | None = None) -> None

Parameter Type Default Description
codec_name str Name of the codec that ran.
duration_ms float Wall-clock duration of the call, in milliseconds.
route Route The :class:Route the call actually took.
level FilterLevel | None None The effective :class:FilterLevel for this call, used to pick the right budget (see :meth:_budget_for).

Method CircuitBreaker.p99

Rolling p99 duration (ms) for codec_name, or None if no calls have been recorded yet. Exposed for the savings report (TASK-1957).

p99(codec_name: str) -> float | None

Parameter Type Default Description
codec_name str

Returns: float | None

Alias FilterLevel

Re-exported from parrot.tools.compression.levels.FilterLevel.

Class Route

Where a codec call should run, decided BEFORE compressing.

Attributes:

Attribute Type Description
INLINE Run synchronously on the event loop, within a low-single-digit- millisecond budget (see :class:BudgetRouter's inline_budget_ms / minimal_budget_ms, calibrated against measured pure-Python codec latency — TASK-1959).
EXECUTOR Offload to run_in_executor; only meaningful with the Rust extension's allow_threads() GIL release.
PASSTHROUGH Skip compression entirely; return the original payload unchanged.

Function estimate_size

Cheap (bytes, rows) estimate of payload's size.

Deliberately does NOT fully serialize or fully walk a large payload — doing so to decide whether to compress it would defeat the purpose. For lists, only the first element is sampled and its size multiplied by the row count. An over-estimate is safe (it only ever routes to a more conservative decision); an under-estimate is not, so this function favors over-estimating.

QueryResult-shaped dicts (e.g. {"driver": ..., "rows": [...], "row_count": ...} — this feature's flagship use case, see columnar.py's _locate_rows()) carry the bulk of their size in a single list-valued field. Those are sampled the SAME cheap way as a bare list: the dominant list's first element, multiplied by its length, plus a full (but normally tiny) walk of the remaining "shell" fields. Only a dict with no such dominant list falls back to a full recursive walk (code-review fix — previously ALL dict payloads, including QueryResult-shaped ones, took the expensive full-walk path).

estimate_size(payload: Any) -> tuple[int, int]

Parameter Type Default Description
payload Any The unwrapped tool result to estimate.

Returns: tuple[int, int] — A (bytes, rows) tuple. rows is 0 for non-list payloads with no dominant list-valued field.

Function is_rust_available

Detect the optional parrot_codec Rust extension.

Detected once per process and cached; absence is logged exactly once at debug level, never per call (the common case until the extension is compiled, TASK-1955).

is_rust_available() -> bool

Returns: bool — True if parrot_codec is importable, False otherwise.

Alias lazy_import

Re-exported from parrot._imports.lazy_import.

Attribute logger

Architecture

Clients

Bots & Agents

Memory

Knowledge

Tools & Toolkits

Flows

Experts

Skills

Stores & Loaders

MCP & A2A

Server & APIs

Integrations

Outputs & A2UI

Prompts

Security

Operations

Migration

SDD Tooling

LLM Wiki

Deployment

Decisions

API Reference

Clone this wiki locally