Appearance
Statistics and cost records API
Use run statistics to check delivered work, selected timing sites to investigate execution, and cost records to price future plans. These are separate observations: a cache hit count or a modeled cost is not an end-to-end throughput measurement.
python
from pycellpack.loader import LoaderConfig, RunStats, MemoryEstimate, profile_sites, profile_groups
from pycellpack.loader import costsChoose the information you need
- Check what a run did and where it spent time.RunStats and ProfileReportRead final counters first; enable only the timing sites you need.
- Size known native reservations before starting.MemoryEstimateInclude output memory and private scratch alongside the planned cache.
- Supply costs for cache decisions.costs.resolve / calibrateResolve stored values or defaults; run actual measurements only when requested.
Read a run result
run.snapshot() returns the currently published RunStats without waiting for completion; it requires an open Run. Workers publish periodically, so small or recent runs can still show zero counters. The snapshot is not a barrier across threads. Consume output before run.join(), which waits for completion and returns final statistics or propagates failure. See run lifecycle.
| Record / fields | Meaning and unit |
|---|---|
RunStats.accesses | Schema deliveries: positions × schemas, not unique cells or batches |
decoded_rows, mapped_rows, row_hits, process_calls | Work and reuse counters; a shared input can serve several outputs |
io: IoStats | Issued requests, requested/returned bytes and request counts by page-size band |
outputs: dict[str, OutputStats] | Access, decode, row-hit and process counts keyed by output name |
elapsed, setup_elapsed | Execution wall time after setup, and setup time, in seconds |
cache_bytes, private_bytes | Cache-frame and worker-private-frame reservations, in bytes |
profile, online | Optional timing report and online compiler statistics |
Python exposes counters directly on RunStats, rather than under a counters attribute. to_dict() produces nested JSON-ready values; RunStats.from_dict(d) restores typed I/O, output, profile and online records. These dataclasses are frozen; use the returned records rather than changing counters to represent another run.
I/O bytes count application reads, including reads served by the OS page cache; they are not physical-device bytes. io.sizes counts requests in bands of 1, 2, 3–4, 5–8, 9–16, 17–32, and 33+ pages. Its entries sum to io.requests. The planning guide shows a complete run and how to compare its values and final statistics.
Select and interpret timing
LoaderConfig.profile | Behavior |
|---|---|
None or False | Untimed execution; event counters remain available |
True or "all" | Time every available site |
| Site/group string or sequence of names | Time the selected sites; unknown names raise ValueError |
| Empty sequence | Timed implementation with no selected sites; use None for an untimed baseline |
profile_sites() maps site names to descriptions. profile_groups() maps group names to member names, which may include other groups. Names are case-sensitive; the native parser prefers a site over a same-named group. In particular, profile="worker" selects the worker-lifetime site. Expand the group explicitly when you want its stage coverage:
python
config = LoaderConfig(profile=profile_groups()["worker"])ProfileReport contains schemas, process-size bands, and sites keyed by name. Every selected site can appear even when its call count is zero. A missing site is not evidence that the operation took no time.
| Query | Result |
|---|---|
report.site(name) | SiteReport or None when unrecorded/unknown |
report.time(*names) | Sum of named site seconds; absent sites contribute zero |
report.map_time(schema) | Mapping seconds for a zero-based schema index |
report.process_bands(schema) | Full/partial calls and seconds for each element-count band |
report.process_key(schema, band, partial) | Integer detail key; band is an index into report.bands |
All Python profile durations are seconds, including SiteReport time, self_time, detail tuples (key, calls, seconds), and histogram lower bounds (seconds, count). Process-size bounds count elements, not time. Schema indices follow loader output order; they are not application schema IDs or output names.
time includes child sites; self_time subtracts only recorded direct children, clamped at zero. If a child was not timed, its work remains in the parent's self time. Durations aggregate across threads and can exceed wall time. Neither summing nested site times nor treating io.latency as device-only latency gives an end-to-end elapsed time. Compare profiled work with the same untimed workload when assessing instrumentation overhead.
Estimate memory
loading.memory_estimate(plan=..., slots=..., world=...) returns MemoryEstimate for the selected planning mode and output layout. to_dict() reports byte reservations for cache frames, generation words, worker-private frames, scratch, PlanRing, known metadata and the output ring; known_reservation_bytes is their sum. Match the plan, slot count and world size to the intended run.
Compiler state, allocator overhead and OS page cache are excluded. This is neither measured RSS nor a hard process-memory limit. Cache capacity alone does not bound the loader's complete memory use.
Resolve a cost model
- 01Resolve
costs.resolveFind cost records or use defaults for this loader. This does not calibrate hardware.
- 02Observe
costs.record_runRecord measurements from a representative completed run.
- 03Calibrate deliberately
costs.calibrateRequest real measurements with representative cells and explicit resource limits.
These are distinct operations, not automatic actions performed together. Calibration can be expensive.
costs.resolve(loading, store=None) returns a CostModel without running a calibration. Its provenance identifies each source; inspect it before treating the model as measured for the current workload.
- If
CELLPACK_COST_MODELnames a saved model, load it. Matching output names, or merely matching output count, admit that model; outputs are then assigned to loader names in order andcoresis replaced byloading.cores. Verify the order yourself. A count mismatch warns and continues with record lookup; explicit file read/parse errors propagate. - Otherwise, fetch matching host, storage and process-output records from the CostStore. Each missing part uses package defaults and warns once per record in this process. Built-in output costs come from the host's dtype entry, falling back to its generic entry.
- Assemble costs in loader output order, with the loader's physical core count.
costs.keys(loading) returns host, storage, tier and named outputs lookup identities. Host identity covers CPU/build/kernel context; storage identity covers the largest source file's mount, backend, direct-I/O mode and page size. A process output identity includes callback code, declared identity and output shape. Built-in outputs have no separate output-record key. costs.compose(...) assembles an explicit model from supplied records/defaults; it does not measure them.
Cost rates use requests/second and bytes/second. Work coefficients use core-seconds per stated operation, element or byte. See planning for the cost-model fields and modeled-time contract.
Record observations or calibrate
| Operation | Work and side effect | Result |
|---|---|---|
costs.record_run(loading, stats, store=None) | Merge eligible process timing observations into process-output records | Number of records updated; warns and returns 0 on failure |
costs.calibrate(loading, cells=None, ...) | Pilot plus repeated timed/untimed loader runs, plan compilation and fitting; saves accepted record parts by default | CostModel with provenance |
record_run needs a run that selected the process site and actually called a process function. It does not save all RunStats or calibrate host/storage rates. It converts worker seconds to core-seconds, applies measured profiling correction when available, and merges per-size-band samples with decaying earlier weights. Without eligible observations, it returns zero. Recording failures do not fail the completed loading run; updates across several records are not one transaction.
Calibration uses a subset of supplied global cells, or the source's full cell range when cells=None, and measures seven configurations. Its principal options are:
| Option | Default | Contract |
|---|---|---|
steady_seconds | 30.0 | Required steady measurement window per configuration, excluding warm-up |
max_warmup | None | Steady-state detector's warm-up allowance |
budget | None | Cache bytes; derived from subset footprint when unset, capped at one quarter of available memory |
save / force | True / False | Write accepted parts; force permits saving parts whose quality checks failed |
store | None | Use the default CostStore |
seed / verbose | 0 / True | Subset/order seed and stderr progress |
Runtime includes the pilot, warm-up, retries, planning and measurement windows; steady_seconds=30 is not a 30-second total-runtime bound. Saving is judged per host, storage and output part, so one calibration can retain existing values for some parts. Buffered I/O can measure page-cache behavior rather than storage. Choose representative cells and resource limits before deliberately starting it.
CostStore persistence
CostStore(root=None) treats root as a home directory and appends costs/v1. The default home is CELLPACK_HOME, or ~/.cellpack. Record kinds are host, storage and output; files contain identity, values, measurement metadata and timestamps.
get(kind, key) returns a record or None; unreadable or mismatched records warn and count as absent. records() iterates readable records by kind then key. put replaces one record, update performs a locked read-modify-write, and remove deletes one record, returning False when absent. Writes use an atomic file replacement under a store lock. These mutation methods change local cost records, not matrix files.
Declarations
Complete declarations and members
RunStats
A run's counts (always kept) and, for profiled runs, its sites.
Counts: accesses, decoded and mapped rows, process calls, bytes written; record pages used, served from cache frames (page_hits) and read; pages admitted into cache frames and the extra admission reads among them (block_reads); accesses served by a cached row and the row bytes gathered for them, rows built and their bytes; tasks that waited for a frame another access admits; claims held back by the window, the plan and the output ring; tasks whose reads waited for private frames (starved). elapsed is the workers' and plan thread's wall time after setup_elapsed; peak_span the most accesses claimed past the frontier; cache_bytes the plan's cache frames (cache frames × page size) and private_bytes the workers' private frames. outputs maps output names to their counts; online is the online compiler's statistics (OnlineStats.accesses counts accesses, not positions).
Fields and defaults
python
accesses: int
decoded_rows: int
mapped_rows: int
process_calls: int
written_bytes: int
page_uses: int
page_hits: int
page_reads: int
admitted: int
block_reads: int
row_hits: int
row_gather_bytes: int
rows_admitted: int
row_admit_bytes: int
waited: int
window_stalls: int
plan_stalls: int
output_stalls: int
starved: int
elapsed: float
setup_elapsed: float
peak_span: int
cache_bytes: int
private_bytes: int
io: IoStats
outputs: dict[str, OutputStats]
profile: ProfileReport | None
online: OnlineStats | NoneRunStats.from_dict
python
RunStats.from_dict(d) -> RunStatsA record from to_dict (or the native counts).
RunStats.to_dict
python
RunStats.to_dict() -> dictThe record as nested plain values, ready for JSON or another process (DistributedRun passes it through the status region).
IoStats
Read requests, bytes requested and read, and requests by size in pages (1, 2, 3-4, 5-8, 9-16, 17-32, 33+).
requested_bytes counts what the issued requests asked for (pages per request times the page size), read_bytes what the device returned; sizes has one count per band, summing to requests.
Fields and defaults
python
requests: int
requested_bytes: int
read_bytes: int
sizes: tuple[int, ...]IoStats.from_dict
python
IoStats.from_dict(d) -> IoStatsA record from its dict form (sizes back as a tuple).
OutputStats
One output's access counts: accesses of that schema, records decoded for it (a cell shared by two outputs decodes once, so outputs of a position can differ), hits served by a cached row, and process function calls (0 for the built-in output).
Fields and defaults
python
accesses: int
decoded_rows: int
row_hits: int
process_calls: intMemoryEstimate
A run's known reservations in bytes: cache frames and their generation words, private frames, worker scratch, the plan ring, metadata and the output ring, and their sum. Compiler state, allocator overhead and the OS cache are not included; this is not RSS.
Fields and defaults
python
cache_frame_bytes: int
generation_bytes: int
private_frame_bytes: int
worker_scratch_bytes: int
plan_ring_bytes: int
metadata_bytes: int
output_ring_bytes: int
known_reservation_bytes: intMemoryEstimate.to_dict
python
MemoryEstimate.to_dict() -> dictThe estimate as a plain dict, keyed like the native fields.
ProfileReport
The sites a profiled run recorded: schemas the outputs the sites were laid out for, bands the process size bounds (PROCESS_BOUNDS), and sites the reports by site name.
Fields and defaults
python
schemas: int
bands: tuple[int, ...]
sites: dict[str, SiteReport]ProfileReport.from_dict
python
ProfileReport.from_dict(d) -> ProfileReportA report from its dict form, rebuilding each site's record.
ProfileReport.site
python
ProfileReport.site(name) -> SiteReport | NoneThe site's report, or None when it was not recorded.
ProfileReport.time
python
ProfileReport.time(*names) -> floatSummed seconds of the named sites (0 for unrecorded ones).
ProfileReport.process_key
python
ProfileReport.process_key(schema: int, band: int, partial: bool) -> intThe process detail key of a schema, size band and row kind.
ProfileReport.process_bands
python
ProfileReport.process_bands(schema: int) -> list[dict]Per size band of schema: full and partial calls and seconds.
ProfileReport.map_time
python
ProfileReport.map_time(schema: int) -> floatSeconds mapping schema's rows.
SiteReport
One profiled site: calls, seconds inside it (time, including child sites) and without its recorded children (self_time); details as (key, calls, seconds) per schema (map) or per schema, size band and row kind (process, see ProfileReport.process_key); hist as (lower bound in seconds, count) per log2 bucket for histogram sites.
Fields and defaults
python
calls: int
time: float
self_time: float
details: tuple[tuple[int, int, float], ...]
hist: tuple[tuple[float, int], ...] | NoneSiteReport.from_dict
python
SiteReport.from_dict(d) -> SiteReportA record from its dict form, restoring the tuple fields and an absent hist as None.
profile_sites
python
profile_sites() -> dict[str, str]Every profiling site this build carries: name -> what it times.
profile_groups
python
profile_groups() -> dict[str, tuple[str, ...]]Named site sets: group -> its member sites and groups (a group may name another); profile also takes all for every site.
resolve
python
resolve(loading, *, store: CostStore | None=None) -> CostModelThe cost model of loading on this machine.
$CELLPACK_COST_MODEL names a saved model that replaces everything when its outputs match the loader's schemas (the same names, or the same count); when it does not, that model is ignored with a warning. Otherwise each part comes from the store when a record matches (the host's worker constants, the storage's device rates, each process function's costs) and from pycellpack.loader.costs defaults when none does, which warns once per missing record. cores is the loader's (physical cores its workers run on). provenance names each part's source.
keys
python
keys(loading, mappings: Mappings | None=None) -> dictThe record keys a loader's cost model is looked up by, with their identities and the storage tier.
compose
python
compose(loading, host: dict, storage: dict, outputs: dict, provenance: dict | None=None) -> CostModelA cost model from host values, storage values and per-output costs; values a record lacks are the defaults'.
calibrate
python
calibrate(loading, cells=None, *, steady_seconds=30.0, max_warmup=None, budget=None, save=True, force=False, store: CostStore | None=None, seed=0, verbose=True)Measures loading's cost model on this machine and stores it.
Seven configurations over a random subset of cells (default: every cell) each hold a steady state for steady_seconds (warm-up excluded; see pycellpack.loader.costs.Steady): no cache, and its untimed twin; a page plan of budget bytes (default: a quarter of the subset's page footprint, at least 64 pages and at most a quarter of the available memory); a row plan of budget bytes and its untimed twin; a page plan over a block shuffle; an online page plan. Worker seconds become core-seconds where workers outnumber the physical cores they run on (Loader.cores). Their snapshot differences fit the host's worker constants, the storage's device rates and each process function's costs, saved as three records (see CostStore) unless save is false. Each part is saved only when its own windows are sound (unless force): the worker constants when windows that keep the workers busy fit them within MAX_RESIDUAL, the device rates when the uncached windows are steady, process costs when the profiled windows are; a part not saved keeps its stored record or defaults. Shared storage that fluctuates may thus yield device rates only.
Returns the measured model (provenance says what was measured).
record_run
python
record_run(loading, stats, *, store: CostStore | None=None) -> intMerges the size profile (the process site) of each process function a profiled run called into its stored costs (scaled by the host's measured profile overhead, if any). Returns the records updated; failures only warn.
CostStore
python
CostStore(root=None)The cost records of one home directory.
CostStore.path
python
CostStore.path(kind: str, key: str) -> PathThe file holding one record; raises ValueError for an unknown kind.
CostStore.get
python
CostStore.get(kind: str, key: str) -> dict | NoneA record by kind and key, or None when there is none. A record that cannot be read, or whose format, kind or key disagree with its position, warns and counts as absent.
CostStore.put
python
CostStore.put(kind: str, key: str, identity: dict, values: dict, measured: dict | None=None) -> dictWrites a record, replacing any with this key.
CostStore.update
python
CostStore.update(kind: str, key: str, identity: dict, merge) -> dictRead-modify-write under the lock: merge(old record or None) returns (values, measured).
CostStore.records
python
CostStore.records()Every readable record, by kind then key.
CostStore.remove
python
CostStore.remove(kind: str, key: str) -> boolDeletes one record; False when it was not there.