Skip to content

Cache planning ​

A cache plan decides which compressed pages and decoded input rows stay in memory between accesses. It assigns their frames before workers use them; workers then read, decode and wait on those assignments. Start after checking the values and ordering of an uncached loading run.

Choose a planning mode ​

Choose when to compile

Fixed and online runs use the same worker and output-ring contracts. A zero-byte plan still performs planning and uses a PlanRing; choose Planning::None to disable that work. The cache budget excludes worker buffers, output and compiler state; see memory reservations.

Compile, save, replay, and run ​

The example creates a four-row fixture, requests those rows repeatedly, and executes four variants. Its checks establish these results:

StageWhat it checks
Uncached runEvery delivered row equals the requested input row
Fixed page planDelivered values match; page hits, read bytes and requests equal serial replay
Decoded-row candidatesDelivered values match with row caching enabled
Online runDelivered values match and every access completes
Complete runnable example
rs
mod common;

use std::error::Error;
use std::sync::Arc;

use cellpack::loader::{
    DataSourceBuilder, Dtype, IoBackend, Loader, LoaderConfig, OutputSchema, Planning, Ring,
    RunStats,
};
use cellpack::opt::{Plan, PlanObjective};

fn consume(
    loader: &Loader,
    accesses: &[u32],
    planning: Planning,
) -> Result<RunStats, Box<dyn Error>> {
    let ring = Arc::new(Ring::allocate(loader.ring_layout(2, 1))?);
    let run = loader.prepare(&accesses, ring, planning)?;
    let stats = run.for_each_batch(|batch| {
        for (row, bytes) in batch.region(0).chunks_exact(16).enumerate() {
            let position = batch.first_position() as usize + row;
            let values: Vec<f32> = bytes
                .chunks_exact(4)
                .map(|v| f32::from_ne_bytes(v.try_into().unwrap()))
                .collect();
            assert_eq!(values, common::MATRIX[accesses[position] as usize]);
        }
        Ok(())
    })?;
    Ok(stats)
}

fn main() -> Result<(), Box<dyn Error>> {
    let path = common::fixture()?;
    let mut builder = DataSourceBuilder::new(4, 4096)?.direct_io(false);
    builder.add_cpk(path, &[0, 1, 2, 3])?;
    let source = Arc::new(builder.build()?);
    let schema = OutputSchema::dense(1, vec![0, 1, 2, 3], Dtype::F32)?;
    let config = LoaderConfig {
        workers: 2,
        backend: IoBackend::Pread,
        max_inflight_per_worker: 2,
        slot_cells: 2,
        ..LoaderConfig::default()
    };
    let loader = Loader::new(source, vec![schema], config)?;
    let accesses: Vec<u32> = (0..64).map(|i| (i % 4) as u32).collect();
    let uncached = consume(&loader, &accesses, Planning::None)?;

    let mut options = loader.plan_options(16 * 4096);
    options.threads = 2;
    options.objective = PlanObjective::Misses;
    let plan = loader.compile(&accesses, &options)?;
    let summary = loader.replay(&plan, &accesses)?;
    let path = common::directory()?.join("cache.plan");
    plan.write(&path)?;
    let fixed = Planning::Fixed(Arc::new(Plan::open(path)?));
    let memory = loader.memory_estimate_for(&fixed, 2, 1)?;
    let cached = consume(&loader, &accesses, fixed)?;
    assert_eq!(cached.counters.page_hits, summary.page_hits);
    assert_eq!(cached.io.requested_bytes, summary.read_bytes);
    assert_eq!(cached.io.requests, summary.requests);

    let mut row_options = loader.plan_options(16 * 4096);
    row_options.threads = 2;
    row_options.rows = true;
    let row_plan = loader.compile(&accesses, &row_options)?;
    let rows = consume(&loader, &accesses, Planning::Fixed(Arc::new(row_plan)))?;

    options.chunk = Some(8);
    options.horizon = Some(16);
    let online = consume(&loader, &accesses, loader.online(options)?)?;
    assert_eq!(online.counters.accesses, accesses.len() as u64);
    println!(
        "page reads: uncached={}, fixed={}, online={}; row hits={}; reservations={}",
        uncached.counters.page_reads,
        cached.counters.page_reads,
        online.counters.page_reads,
        rows.counters.row_hits,
        memory.known_reservation_bytes
    );
    Ok(())
}

In the application from installation, save planning.rs as src/main.rs and common.rs as src/common.rs, then run:

sh
cargo run -- output/planning

The final line starts with page reads: and reports the observed counters and known reservations. The tiny fixture and its counters are functional checks, not performance measurements; no particular hit count is needed for correctness.

The decoded-row variant uses the loader's default cost model for demonstration. It enables row candidates rather than forcing their admission; use measured costs to decide which candidates are worthwhile on your machine.

For your own loader, the core fixed-plan sequence is:

rust
let options = loader.plan_options(cache_bytes);
let plan = loader.compile(&accesses, &options)?;
let expected = loader.replay(&plan, &accesses)?;
plan.write("cache.plan")?;
// Pass Planning::Fixed(Arc::new(plan)) to loader.prepare, then consume the run.

accesses contains global cell IDs in position-first, schema-second order. Compilation and replay inspect source descriptors and plan actions; they do not deliver batches. Execute the plan to check actual decoded values and I/O behavior.

Choose what to retain ​

What a cache hit saves
Page hit

Reuse compressed pages; decoding still runs.

Row hit

Gather a decoded input row from frames; mapping and processing still run.

Rows retain their stored dtype. Mapped output and process results are not cached.

A page hit avoids storage reads but still requires decoding. A row hit gathers a decoded input row from cached frames; mapping and processing still run. Rows keep their stored dtype and can be shared by schemas. Mapped output and process results are not cached.

Begin with pages. Enable rows when repeated decoding is expensive enough to repay decoded-row admission and memory traffic. Rows occupy page-rounded frames and can be much wider than compressed records. Current row hits gather noncontiguous frames into worker scratch.

block_pages considers reading adjacent pages together to save requests, at the cost of retaining frames longer. It does not force every read to that size. Use measured costs for these decisions rather than treating more hits as the sole objective.

Set the lookahead and execution window ​

Start with Loader::plan_options(cache_bytes): it derives a reuse gap from the loader and installs the default NVMe cost model in schema order. Replace those costs with measurements for your target machine when evaluating performance.

FieldUnit or meaning
cache_bytesCache-frame byte budget, rounded down to whole pages
gapReuse reservation distance in output slots
threads, cpusCompiler parallelism and optional CPU affinity, separate from worker settings
objectivePage Misses or modeled Time
costHardware and operation costs; optional for page-only planning
rowsConsider decoded rows; requires costs and takes effect with Time and at least one frame
row_policyIncremental for ordinary runs; Global for a full-sequence stored reference
block_pagesNone, or a merged admission limit of 2–128 pages; requires costs
horizonOnline lookahead in output slots; an explicit value must be at least gap
chunkCompiler advance in accesses; default DEFAULT_CHUNK (16384)

One slot spans slot_cells × schemas accesses. For example, with 256 positions per slot and two schemas, gap = 4 reserves 2048 accesses. A chunk = 16384 advances 32 such slots. Plan::reuse_gap() reports slots, whereas Plan::distance() and OnlineStats::{distance, horizon, chunk} report accesses.

LoaderConfig::window is also in slots. With a plan it defaults to the plan's gap and cannot exceed it. Reservation distance prevents frame reuse while an earlier in-flight access still reads that frame.

Offline compilation sees the stored sequence. Online compilation limits reuse search to its effective horizon. If unset, the starting lookahead is twice the source's cell count times the schema count, in accesses. The compiler raises it to at least distance + chunk, then clips it to the sequence length; inspect OnlineStats.horizon when the effective value matters. Longer horizons retain more compiler state. Decisions can depend on compiler thread count through sharding, so keep it fixed for comparisons.

Plan identity ​

A fixed plan binds to input identity, graph and schemas, process identities, slot size, and exact access contents. prepare verifies this binding and frame reuse. Plan::write and Plan::open use the binary CPKPLAN1 format. Recompile after changing those semantics or replacing inputs.

A custom process schema's identity versions its callbacks and captured settings. Callback addresses do not describe semantics.

Opening a plan reads its serialized form. Compatibility with the actual loader and exact sequence is established when replaying or preparing it, not merely by successfully calling Plan::open.

Replay and optimal references ​

QuestionUseInterpret the result
Which work does this fixed plan imply?replayCounts actions without loading record payloads
How do other machine costs price those actions?replay_with_costChanges prices, not cache decisions; recompile to choose new decisions
What does finite-horizon compilation retain?compile_onlineReturns a collected Plan and OnlineStats; does not start a run
Can I inspect a computed sequence's planning?plan_onlineReturns compiler statistics without delivering batches

PlanSummary::seconds() and OnlineStats::modeled_seconds are model predictions. OnlineStats::compile_seconds measures compilation wall time, excluding its wait for PlanRing space; waiting_seconds reports that wait separately. Measure a real run's elapsed time and declared workload to assess throughput.

PageTrace::optimum is the serial page-only optimal reference with bypass. It does not model decoded rows, concurrent frame reservations, sharding, or finite lookahead. Production page-and-row planning uses constrained, cost-guided decisions; it is not a globally optimal end-to-end scheduler.

API: PlanOptions, Plan, PlanSummary, PageTrace.