Skip to content

Native process functions ​

A process function turns a mapped input row into a fixed-size output record. The loader maps columns and converts values to the schema dtype before the call. The callback runs on worker threads and writes its own output and private scratch.

Native row processing
  1. 01
    Read pages

    Fetch the compressed record.

  2. 02
    Decode

    Restore the input row.

  3. 03
    Map columns

    Address the schema’s output dimensions.

  4. 04
    Convert dtype

    Convert values to the schema input dtype.

  5. 05
    Call native code

    Invoke the CSR or dense callback.

  6. 06
    Write output

    Fill the fixed-size per-cell slot region.

Callbacks borrow input only for the call and write within their output and declared scratch regions.

Choose the input your transform needs ​

What must the callback inspect?

First define the model's output record, then its input panel and dtype. For a sum, the record can be one f32 even when the input panel has thousands of columns. Process results are delivered into output slots; input row caching does not cache the callback's final output.

A complete dense callback ​

This example requests four f32 values and writes one f32 sum per cell. It forces dense delivery, so only a dense callback is needed.

Complete program: dense callback, schema binding and output checks
rs
mod common;

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

use cellpack::loader::{
    DataSourceBuilder, DenseRow, Dtype, IoBackend, Loader, LoaderConfig, OutputSchema,
    PROCESS_ABI_VERSION, Planning, ProcessFn, Ring, RowFormat,
};

unsafe extern "C" fn sum_row(call: *const DenseRow) -> i32 {
    // SAFETY: the loader supplies a DenseRow for this callback's duration.
    let row = unsafe { &*call };
    if row.context.abi_version != PROCESS_ABI_VERSION || row.context.dtype != Dtype::F32 as u32 {
        return 1;
    }
    // SAFETY: this schema requests out_dim f32 values; the view does not escape.
    let values =
        unsafe { std::slice::from_raw_parts(row.values.cast::<f32>(), row.out_dim as usize) };
    let sum = values.iter().copied().sum::<f32>();
    // SAFETY: the schema reserves exactly four output bytes for this cell.
    unsafe { std::ptr::copy_nonoverlapping(sum.to_ne_bytes().as_ptr(), row.out, 4) };
    0
}

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])?;
    // SAFETY: a static callback uses no context, is thread-safe and retains no pointers.
    let process = unsafe {
        ProcessFn::with_format(
            RowFormat::Dense,
            None,
            Some(sum_row),
            std::ptr::null(),
            Arc::new(()),
        )?
    };
    let schema = OutputSchema::process(1, vec![0, 1, 2, 3], Dtype::F32, 4, process, 1, 0)?;
    let config = LoaderConfig {
        workers: 2,
        backend: IoBackend::Pread,
        max_inflight_per_worker: 2,
        slot_cells: 2,
        ..LoaderConfig::default()
    };
    let loader = Loader::new(Arc::new(builder.build()?), vec![schema], config)?;
    let accesses = [0u32, 1, 2, 3];
    let ring = Arc::new(Ring::allocate(loader.ring_layout(2, 1))?);
    let run = loader.prepare(&accesses, ring, Planning::None)?;
    let mut sums = Vec::new();
    let stats = run.for_each_batch(|batch| {
        sums.extend(
            batch
                .region(0)
                .chunks_exact(4)
                .map(|v| f32::from_ne_bytes(v.try_into().unwrap())),
        );
        Ok(())
    })?;
    assert_eq!(sums, [3.0, 7.0, 11.0, 15.0]);
    assert_eq!(stats.counters.process_calls, 4);
    println!("per-row sums: {sums:?}");
    Ok(())
}

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

sh
cargo run -- output/process

Expected sums are [3.0, 7.0, 11.0, 15.0]. The callback writes bytes without requiring alignment of its custom output record.

For this example, the schema input is four f32 values, while cell_bytes=4 reserves one output f32. Consumers interpret those four bytes with f32::from_ne_bytes. The byte count and interpretation belong to the application's record contract.

Row formats ​

RowFormatRequired callbacksInput
AutoCSR and denseRoute depends on stored layout and internal thresholds
CsrCSRAll rows as CsrRow, including compacted dense nonzeros
DenseDenseAll rows as DenseRow

ProcessFn::new selects Auto; with_format selects explicitly. In Auto, both callbacks must produce equivalent results. A file's declared source layout does not fix its callback route.

A CsrRow lists stored elements in coded traversal order, with columns already mapped to output positions. Columns are not necessarily sorted. It cannot distinguish omitted present zeros from missing dimensions. A DenseRow holds zero for present omitted values and the schema default for missing dimensions. Use dense delivery and a suitable default when that distinction matters.

For example, a source with columns A and B and row [0, 2], mapped to output [B, C, A] with default=NaN, yields dense [2, NaN, 0]. A sparse row can report B's stored value but cannot identify C's absence just from omitted entries.

ABI and ownership contract ​

ProcessContext contains abi_version, row struct_size, logical position, global cell, schema index, dtype code, and user_data. The current PROCESS_ABI_VERSION is 1. schema is the schema's vector index, not its application id, and struct_size is the row struct's byte size. Native integrations must use declarations matching the loader version.

Construction is unsafe because the application guarantees that callbacks:

  • remain valid through their owner and tolerate concurrent calls;
  • read input only during the call and retain no borrowed pointer;
  • write only their cell's cell_bytes and declared scratch;
  • initialize the output bytes that consumers will read;
  • never unwind across the C ABI;
  • return zero on success or a nonzero failure status.

An Arc<dyn Send + Sync> retains code and state. An unrelated owner does not extend the lifetime of the raw user_data pointee. A nonzero status stops the run with loader::Error::Process(status).

The loader does not clear output or scratch on the callback's behalf. Initialize every output byte the consumer reads, and treat scratch contents as unspecified on entry. Neither pointer promises alignment for a typed record: use byte copies or unaligned operations. See ABI layouts and native examples when integrating C, C++ or a dynamically loaded library.

OutputSchema::process sets output size independently of input panel dimensions. Its identity must change when callback behavior or captured settings change; fixed plans verify that identity.

Partial CSR delivery ​

Use this advanced path only when the transform needs a small subset of stored elements. It is unnecessary for the full-panel sum example above.

Unsafe with_partial_rows permits null columns and values. A callback then uses resolve for required element positions within nnz. The resolver and derived pointers are valid only during the call. A position at or beyond nnz makes resolve return a nonzero status.

Partial rows are offered only when every element maps to an output column. A partial-aware callback must also handle ordinary full CSR rows.

API: ProcessFn, CsrRow, DenseRow, ProcessContext.