Skip to content
API REFERENCEUsage guides →

Planning API ​

Use this reference for mode selection, option units and plan identity. The planning guide compiles, saves and executes a small plan while checking its decoded result.

python
from pycellpack.loader.opt import PlanOptions, Plan, PageTrace, CostModel

Select a planning interface

Execution and compilation modes ​

CallPlanning behaviorReturns
start(accesses, plan=None)No planned cacheRun
start(accesses, plan=plan)Execute a compatible fixed PlanRun
start(accesses, plan=options)Compile online ahead of executing workersRun
start(accesses, plan=byte_budget)Resolve default options/costs and compile onlineRun
compile(accesses, options, online=False)Whole-sequence compilationPlan
compile(accesses, options, online=True)Finite-horizon compilation into a retained planPlan with OnlineStats
compile_stats(accesses, options)Online compilation without output delivery or retained decisionsOnlineStats
replay(plan, accesses, cost=None)Verify binding and simulate serial actionsPlanSummary

compile accepts PlanOptions or a byte budget and materializes computed Accesses into a stored sequence. compile_stats and online start can generate intervals without retaining all cell IDs. Access counts are position-first, schema-second and must be divisible by the loader's schema count. See access sequences for composition and deterministic callbacks.

plan_options(cache_bytes, cost="auto") returns frozen PlanOptions with the loader's window as gap. Automatic cost resolution consults saved records and defaults; it does not calibrate hardware. Pass a CostModel explicitly or cost=None for equal-valued page hits. Constructing PlanOptions directly does not resolve costs automatically. The loader fills unset gap/thread values in a copy, leaving your object unchanged.

PlanOptions parameters ​

FieldDefaultContract
cache_bytesRequiredNonnegative frame budget in bytes; rounded down to whole source pages; frame count must fit uint32
gapNoneReuse reservation in slots; resolves to loader window; positive, with its access distance below 2**32 - 1
threadsNonePositive compiler thread count; automatic offline/online policies described below
objective"time"Minimize modeled time or "misses" for page misses
costNoneCostModel for this loader; required when rows or block candidates are requested
rowsFalseConsider native-precision decoded rows; effective only with "time" and at least one frame
block_pagesNoneOptional candidate read width in 2–128 pages; requires costs
row_policy"incremental"Incremental decisions, or "global" as a complete-stored-sequence reference
horizonNoneConfigured online lookahead in slots, at least gap; offline compilation uses the whole sequence
chunkNonePositive advance in accesses; native default 16384
cpus()Compiler CPU affinity; empty inherits caller affinity

Automatic threads is one per usable CPU offline, or a quarter of executor workers online, bounded to 1–16 and the usable CPU count. An explicit positive value bypasses that automatic cap. cpus influences the usable count and pins compiler threads; it does not configure executor workers.

rows=True with objective="misses" is disabled by the engine, rather than selecting a mixed row/page miss objective. The requested row mode still requires a cost model during validation. A zero-byte plan still compiles and uses a PlanRing; choose plan=None to disable planning. Global row selection requires effective row caching over a fully available stored sequence and full horizon; use the incremental policy for finite-horizon or generated streams.

Slots versus accesses ​

One slot represents S × slot_rows accesses, where S is the number of loader schemas. The gap reserves frames before their admission; loader window controls execution lead and may not exceed that gap. Neither setting is the output ring's slots capacity.

Configured horizon is converted to accesses. With no explicit horizon, online lookahead starts at twice the source cell count per schema. The engine raises it to at least distance + chunk, then caps it at sequence length (at least one for an empty sequence). Consequently OnlineStats reports the effective horizon, which can differ from the configured request.

Reported fieldUnit
Plan.reuse_gapSlots
Plan.distance, OnlineStats.distanceAccesses
OnlineStats.horizon, OnlineStats.chunkAccesses
Plan.slot_rowsPositions per slot
len(plan)Accesses

Plan identity and serialization ​

A Plan binds graph/source identity, column mappings, schema/process identities, schema order, slot_rows, and the exact access sequence. Reordered accesses or a different schema require recompilation. Ring slot count and consumer world size are not plan fingerprints; execution must still satisfy the loader's layout, window and ring contracts. Changing source files in place is outside the immutable input contract.

Plan.write(path) and Plan.open(path) use CPKPLAN1 files. to_bytes and from_bytes use the same format; a Plan also pickles through those bytes. The file stores fingerprints, residency decisions and the optional cost model. Opening parses the file, while start or replay checks compatibility with an actual loader and sequence.

For a freshly compiled Plan, summary contains serial replay counts. A restored Plan's summary is initially empty and is populated when a loader first verifies it through start or replay; inspect it after that step. online_stats belongs to a compile(..., online=True) result and is not retained by the plan file or pickle. Keep those observations separately if you need them.

residencies() returns arrays in admission order: kind (0 page, 1 row), key (global page ID or cell ID), start, end, offsets and frames. Residency i uses frames[offsets[i]:offsets[i + 1]]; start/end address accesses, not positions or batches. cache_bytes is the original budget and cache_frames is its whole-page capacity, not measured resident memory.

replay(..., cost=other_model) prices the same actions with another compatible model without changing the Plan or its stored summary. PlanSummary seconds are modeled; OnlineStats separates modeled seconds from compiler/wait wall seconds. Use executed RunStats for run observations.

Costs and reference comparisons ​

CostModel prices request capacity, byte bandwidth, worker physical cores, cached-row memory traffic and operation costs in core-seconds. Rates must be positive and finite, costs finite and nonnegative, serial in [0, 1], and bucket >= 1. Output records must match the loader's outputs. Compilation and replay check model compatibility; constructing a dataclass alone is not that validation.

to_dict / from_dict use the versioned native JSON field names; save writes JSON by sibling-file replacement, and load reads it. Required resource rates remain required; omitted optional fields use current defaults. Neither operation measures hardware. For resolution, record provenance and calibration, see statistics and cost records.

PageTrace.from_pages(pages, universe=None) normalizes a one-dimensional nonnegative uint32-range page sequence; the default universe is maximum ID + 1, or zero for an empty sequence. from_source(source, accesses) expands the pages needed by those global cells. optimum(capacity_pages) returns CacheSummary for serial Belady replacement. Its capacity counts pages, and its model excludes reuse-gap reservation, execution concurrency, decoded rows and management costs. It is not an optimal mixed page/row plan.

Validation and declarations ​

Invalid Python enum/count declarations raise ValueError; native checks also validate the resolved gap, horizon, frame count, CPU indices, cost model and plan binding. I/O errors opening or writing a plan raise OSError. Keep outputs and records from failed runs out of downstream results; lifecycle recovery is covered by rings and runs.

Complete declarations and members

PlanOptions ​

What a plan is compiled for. gap is the reuse gap in slots (default: the loader's window); runs of the plan execute within a window of at most it, and every residency reserves its frames from that far before its admission. rows caches rows too (page+row; needs a cost model), chosen by row_policy: "incremental" (each reuse decided as it arrives, against a shadow price of capacity learned from the pages) or "global" (rows first over the whole stored sequence; offline only). block_pages merges adjacent admissions into reads of 2 to 128 pages (needs a cost model). horizon bounds, in slots, the reuse intervals an online plan considers (at least gap); chunk is how many accesses the online compiler advances, freezes and publishes at a time. objective minimizes the modeled time ("time", the default) or page misses ("misses"); cost prices the decisions and is required for rows and block_pages.

threads=None resolves when a loader uses the options: offline, one per usable CPU (cpus if pinned); online, a quarter of the loader's workers; both at most 16. cpus pins the compiler threads (empty inherits the calling thread's CPUs).

Fields and defaults ​

python
cache_bytes: int
gap: int | None = None
threads: int | None = None
objective: str = 'time'
cost: CostModel | None = None
rows: bool = False
block_pages: int | None = None
row_policy: str = 'incremental'
horizon: int | None = None
chunk: int | None = None
cpus: tuple[int, ...] = ()

CostModel ​

The loader's resources on one machine and the work it does (see cellpack::opt::model).

Four resources serve a run: the device's read requests (iops) and bytes (bandwidth), the workers' physical cores (cores) and main memory traffic of cached rows (memory_bandwidth). Work is in core-seconds: per access (access), per read request (request), per access the online compiler takes from the workers' cores (compile, online plans only), decoding (input), cached rows (rows) and each output (outputs, keyed by the loader's output names, or by position; convert adds a per-element cost for each conversion class, CONVERSIONS). A window of bucket accesses takes its device time (the longer of requests and bytes) or its core time, whichever is longer, plus serial of the shorter; a longer memory time overrides that sum. provenance records where each part came from (see pycellpack.loader.costs.resolve); it is not compared. The rates are positive and finite, costs finite and nonnegative, serial in [0, 1], bucket at least 1, and outputs has one entry per loader output; compilation and replay reject a model that breaks this.

to_dict/save write JSON in the native field names (outputs as a list in mapping order, each with its name), which the Rust crate reads with its serde feature.

Fields and defaults ​

python
cores: float
iops: float
bandwidth: float
memory_bandwidth: float = _DEFAULTS['host']['memory_bandwidth']
serial: float = 0.0
bucket: int = _DEFAULTS['bucket']
access: float = 0.0
request: float = 0.0
compile: float = 0.0
input: InputCost = field(default_factory=InputCost)
rows: RowCost = field(default_factory=RowCost)
outputs: Mapping = field(default_factory=dict)
convert: tuple = (0.0,) * len(CONVERSIONS)
provenance: Mapping = field(default_factory=dict, compare=False, repr=False)

CostModel.to_dict ​

python
CostModel.to_dict() -> dict

JSON-ready fields (see the class documentation).

CostModel.from_dict ​

python
CostModel.from_dict(d) -> CostModel

Reads to_dict; outputs without a name are keyed by position, and fields this version does not know are ignored.

CostModel.save ​

python
CostModel.save(path) -> Path

Writes to_dict as JSON, atomically (a temporary file renamed).

CostModel.load ​

python
CostModel.load(path) -> CostModel

A model read from a JSON file written by save. $CELLPACK_COST_MODEL names such a file for pycellpack.loader.costs.resolve.

InputCost ​

Core-seconds of decoding records: per decoded record, per stored element decoded, and per decoded record in a chunk not among the few most recently used (cold decode tables and maps).

Fields and defaults ​

python
decode: float = 0.0
decode_element: float = 0.0
cold: float = 0.0

RowCost ​

Core-seconds of cached rows, per payload byte: gathering a row from its frames for a hit, and building and writing it on admission.

Fields and defaults ​

python
gather: float = 0.0
admit: float = 0.0

OutputCost ​

Core-seconds of one output: its process function per call (none for the built-in output), per element mapped to its output dims and written, and per output dim filled with the default (dense rows). A partial call adds resolve per call and resolve_element per stored element; a non-empty curve replaces the fixed process and resolver costs with size bands.

Fields and defaults ​

python
process: float = 0.0
map_element: float = 0.0
fill_element: float = 0.0
resolve: float = 0.0
resolve_element: float = 0.0
curve: tuple[ProcessCost, ...] = ()

ProcessCost ​

Per-call costs through this inclusive element bound: the stored elements a CSR row carries, or the output dims a dense row fills. A curve's bounds increase and its last covers 2**32 - 1.

Fields and defaults ​

python
max_elements: int
process: float
resolve: float = 0.0

Plan ​

A compiled cache plan (see Loader.compile), bound to its loader's data source, schemas and slots, and to its access sequence. Pass it to Loader.start. A plan pickles (by its file bytes); online_stats holds the compilation's statistics when it was compiled as an online run would.

Plan.open ​

python
Plan.open(path) -> Plan

A plan read from a CPKPLAN1 file; its summary is counted when a loader first verifies it.

Plan.write ​

python
Plan.write(path) -> None

Writes the plan file (the CPKPLAN1 v1 form, with its cost model and fingerprints).

Plan.from_bytes ​

python
Plan.from_bytes(data) -> Plan

A plan read from the bytes of a plan file.

Plan.to_bytes ​

python
Plan.to_bytes() -> bytes

The plan file's bytes, for another process or for storage.

Plan.summary ​

summary: PlanSummary — property.

The serial replay's counts; for a plan read from a file or bytes, counted when a loader first verifies it (start or replay).

Plan.distance ​

distance: int — property.

The reuse gap in accesses.

Plan.reuse_gap ​

reuse_gap: int — property.

The reuse gap in slots, independent of the runtime window.

Plan.cache_bytes ​

cache_bytes: int — property.

The cache budget the plan was compiled for, in bytes.

Plan.cache_frames ​

cache_frames: int — property.

Cache frames the plan's budget buys (frame ids lie below it).

Plan.schemas ​

schemas: int — property.

Schemas per position the plan was compiled for (the loader's).

Plan.slot_rows ​

slot_rows: int — property.

Positions per slot the plan's sequences are expressed in.

Plan.residencies ​

python
Plan.residencies() -> dict[str, np.ndarray]

The residencies in admission order as arrays: kind (0 a page, 1 a row), key (global page id, or cell), start (the admitting access), end (the last use), and the frames of residency i as frames[offsets[i]:offsets[i + 1]].

PageTrace ​

A page trace over a page sequence or a data source's accesses; optimum gives what a cache of a given size could hit at best.

PageTrace.from_pages ​

python
PageTrace.from_pages(pages, *, universe=None) -> PageTrace

A trace over a stored page sequence. universe is the page id space's size (default: the largest id plus one); ids must fit uint32. Raises ValueError for a sequence that is not one-dimensional or holds a negative or too large id.

PageTrace.from_source ​

python
PageTrace.from_source(source, accesses) -> PageTrace

The pages accesses (global cell ids of source) read.

PageTrace.page_uses ​

page_uses: int — property.

Pages the sequence touches, repeats included.

PageTrace.distinct_pages ​

distinct_pages: int — property.

Pages of the id space the sequence reads at least once.

PageTrace.optimum ​

python
PageTrace.optimum(capacity_pages) -> CacheSummary

The hits and misses of a page cache of capacity_pages under the optimal offline policy (Belady).

PlanSummary ​

A plan's serial replay: page uses and hits; read requests and bytes; residencies and extra admission reads (block_reads); decoded records, their elements and those in a cold chunk; row hits and admissions with their elements and payload bytes; per schema (in loader order) the elements mapped, rows filled, process and partial calls; elements per conversion class; the most cache bytes held (serially, and reserved from each admission's reuse gap); modeled core-seconds (worker_seconds). Per quarter of the sequence (one epoch of a 4-epoch run): page uses, hits, requests, modeled seconds and each resource's service seconds (requests, bytes, cores, memory: the largest binds). Seconds are zero without a cost model.

Fields and defaults ​

python
accesses: int
page_uses: int
page_hits: int
requests: int
read_bytes: int
page_residencies: int
row_residencies: int
block_reads: int
decoded_rows: int
decoded_elements: int
cold_rows: int
row_hits: int
row_elements: int
row_bytes: int
admitted_elements: int
admitted_bytes: int
mapped_elements: tuple[int, ...]
filled_elements: tuple[int, ...]
converted_elements: tuple[int, ...]
process_calls: tuple[int, ...]
partial_calls: tuple[int, ...]
partial_elements: tuple[int, ...]
peak_bytes: int
concurrent_peak_bytes: int
worker_seconds: float
quarter_uses: tuple[int, ...]
quarter_hits: tuple[int, ...]
quarter_requests: tuple[int, ...]
quarter_seconds: tuple[float, ...]
quarter_service_seconds: tuple[tuple[float, ...], ...]

PlanSummary.from_dict ​

python
PlanSummary.from_dict(d) -> PlanSummary

A summary from the native counts, restoring its per-quarter and per-schema vectors as tuples.

PlanSummary.seconds ​

seconds: float — property.

Modeled seconds of the whole sequence.

PlanSummary.quarter_accesses ​

python
PlanSummary.quarter_accesses() -> tuple[int, ...]

Accesses per quarter of the sequence.

PlanSummary.to_dict ​

python
PlanSummary.to_dict() -> dict

The summary as nested plain values (JSON or another process).

OnlineStats ​

An online compilation: accesses, chunks and the chunk size, horizon and reuse gap (distance) in accesses, shards; page uses, hits and admissions, row hits and admissions, block reads and read requests of the published plan; row candidates seen and kept and page intervals refused; the last capacity price (row_price, seconds per frame-position) and resource prices; modeled seconds and core-seconds; wall seconds compiling and waiting for the loader.

Fields and defaults ​

python
accesses: int
chunks: int
chunk: int
horizon: int
distance: int
shards: int
page_uses: int
page_hits: int
page_admissions: int
row_admissions: int
row_hits: int
block_reads: int
requests: int
row_candidates: int
row_kept: int
page_refused: int
row_price: float
prices: Prices
modeled_seconds: float
worker_seconds: float
compile_seconds: float
waiting_seconds: float

OnlineStats.from_dict ​

python
OnlineStats.from_dict(d) -> OnlineStats

An online compilation's statistics from the native record, its resource prices rebuilt as Prices.

OnlineStats.to_dict ​

python
OnlineStats.to_dict() -> dict

The statistics as nested plain values (JSON or another process).

CacheSummary ​

The serial page optimum at a capacity: page uses, distinct pages, hits and misses (row and output hits are zero for pages).

Fields and defaults ​

python
page_uses: int
distinct_pages: int
hits: int
misses: int
capacity_pages: int
row_hits: int
output_hits: int

Prices ​

Marginal seconds of modeled time per read request, byte read, core-second of worker work and byte of cached-row memory traffic: which resource binds (the cost model's gradient).

Fields and defaults ​

python
request: float
byte: float
core: float
memory: float