Skip to content

ABI ​

CellPack calls application code at two points of a run, through plain C function pointers and an opaque context pointer:

InterfacePurposeRust bindingC declarationsCalled by
Process functionTurns one mapped, converted row into a fixed-size output recordProcessFn with CsrFn / DenseFninclude/process_fn_cabi.hLoader workers, once per loaded cell of a process schema
Access functionProduces the cell id of each access in the sequenceExternAccesses with AccessFninclude/access_fn_cabi.hWorkers and online planner threads, per range
Corpus access functionProduces (dataset, local row) pairs instead of global idsExternCorpusAccesses with CorpusAccessFninclude/access_fn_cabi.hAs above; the adapter translates pairs into cell ids

Both interfaces are unsafe extern "C". The loader validates the values that come back where it can, but it cannot check what a callback reads, writes or retains. Those obligations are listed per interface below; breaking one is undefined behavior, not an error. See data contracts for the matching rules on data the application passes in.

Headers live in crates/cellpack/include/. The process header keeps its PyCellPack prefix because Python capsules share the same layout; the Rust structs below are the same types.

Which side of the pipeline are you extending?

For the first Rust integration, follow the process-function guide or access-sequence guide. This page supplies the layouts, native signatures and foreign-code obligations those workflows rely on.

Process functions ​

A process function sees each loaded cell after the loader has decoded its record, mapped its columns to the schema's output dims and converted values to the schema dtype. It writes exactly the schema's cell_bytes at out:

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.

Signatures ​

rust
pub type CsrFn = unsafe extern "C" fn(*const CsrRow) -> i32;
pub type DenseFn = unsafe extern "C" fn(*const DenseRow) -> i32;
pub type ResolveFn = unsafe extern "C" fn(
    row: *const c_void, positions: *const u32, count: u64,
    columns: *mut u32, values: *mut c_void,
) -> i32;

Return 0 on success. Any other value cancels the run with loader::Error::Process(status); the status is passed through unchanged, so callbacks can encode their own failure reasons.

Struct layouts ​

All three structs are #[repr(C)]. Offsets are for 64-bit targets. Use the shipped header's declarations rather than recreating these layouts in foreign code. context.schema is a vector index; it is not OutputSchema::id.

Field types, 64-bit offsets and dtype codes
ProcessContext fieldTypeOffsetMeaning
abi_versionu320PROCESS_ABI_VERSION (currently 1)
struct_sizeu324Size of the row struct passed (112 for CsrRow, 80 for DenseRow)
positionu648Position in the sequence; every schema of one position sees the same value
cellu6416Global CellId being loaded
schemau3224Schema index in the loader
dtypeu3228Dtype code of values (table below)
user_data*const c_void32The pointer given to ProcessFn::new
CsrRow fieldOffsetDenseRow fieldOffset
context0context0
out_dim: u6440out_dim: u6440
nnz: u6448values: *const c_void48
columns: *const u3256out: *mut u856
values: *const c_void64scratch: *mut u864
row: *const c_void72scratch_bytes: u6472
resolve: Option<ResolveFn>80
out: *mut u888
scratch: *mut u896
scratch_bytes: u64104
Code0123456789
dtypeu8u16u32u64i8i16i32i64f32f64

Check abi_version, the expected row struct_size, and dtype on entry. A callback compiled for one dtype that receives another reads the wrong element width. Row sizes are 112 bytes for CsrRow and 80 for DenseRow on the 64-bit layout above.

What each row contains ​

RowvaluesColumnsOmitted output dims
CsrRownnz values of the schema dtypecolumns[i] < out_dim, in the chunk's coded order, not sortedZero or missing: a CSR row cannot tell which
DenseRowout_dim values of the schema dtypeImplicit: index i is output dim iPresent but unstored → 0; missing from the matrix → the schema default

RowFormat selects the callbacks the loader may call:

RowFormatCallbacks requiredDelivered rows
Auto (ProcessFn::new)CSR and denseChosen per record from layout, dims, conversion and cache state
CsrCSREvery record as a CSR row (dense records list their non-zeros)
DenseDenseEvery record as a dense row

Under Auto the two callbacks must produce identical output for the same cell. Which one runs is a performance decision that can change between runs, cache plans and library versions.

The callback contract ​

ProcessFn::new and ProcessFn::with_format are unsafe because the loader trusts all of the following:

ObligationIf violated
Code and user_data stay valid for as long as the ProcessFn (keep them alive through owner)Use-after-free on a worker thread
Callbacks tolerate concurrent calls from several workersData races on shared state
Write only out[0..cell_bytes] and scratch[0..scratch_bytes]Corrupts neighbouring cells, slot headers or worker memory
Initialize every output byte consumers readConsumers read stale bytes from an earlier batch
Read values / columns only within nnz or out_dim, and only during the callOut-of-bounds or dangling reads
Never unwind (panic, C++ exception) across the ABIUndefined behavior; typically an abort
Change the schema identity when behavior or captured settings changePlans bound to the old identity are accepted as still valid

out has no alignment guarantee. Write records with write_unaligned, copy_nonoverlapping or memcpy. scratch is private to the call, at least scratch_bytes long, and reused between calls on the same worker, so its contents are unspecified on entry.

Example: a CSR + dense pair in Rust ​

In the application from installation, save the complete program as src/main.rs and the shared fixture as src/common.rs, then run:

sh
cargo run -- output/abi

Each cell produces a 12-byte record: the scaled row total, the column of its largest value, and its non-zero count. Settings reach both callbacks through user_data:

Output record and equivalent CSR/dense callbacks
rs
/// The fixed-size record each cell produces: 12 bytes, written unaligned.
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq)]
struct Summary {
    total: f32,
    peak_column: u32,
    nonzeros: u32,
}

/// Immutable settings both callbacks read through `user_data`.
struct Settings {
    scale: f32,
}

/// Accepts only the ABI and dtype this callback was written for.
fn settings(context: &ProcessContext) -> Option<&Settings> {
    if context.abi_version != PROCESS_ABI_VERSION || context.dtype != Dtype::F32 as u32 {
        return None;
    }
    // SAFETY: user_data points into the Arc<Settings> held by the ProcessFn owner.
    Some(unsafe { &*context.user_data.cast::<Settings>() })
}

The CSR callback cannot assume sorted columns, so tie-breaking uses the column id rather than arrival order. A panic is turned into a status instead of unwinding into the loader:

rs
unsafe extern "C" fn summarize_csr(call: *const CsrRow) -> i32 {
    // A panic must not unwind into the loader: report it as a status instead.
    catch_unwind(AssertUnwindSafe(|| {
        // SAFETY: the loader passes a valid CsrRow for the call's duration.
        let row = unsafe { &*call };
        let Some(settings) = settings(&row.context) else { return 1 };
        let n = row.nnz as usize;
        // SAFETY: full (non-partial) rows carry nnz columns and f32 values.
        let (columns, values) = unsafe {
            (
                std::slice::from_raw_parts(row.columns, n),
                std::slice::from_raw_parts(row.values.cast::<f32>(), n),
            )
        };
        let mut acc = EMPTY;
        for (&column, &value) in columns.iter().zip(values) {
            fold(&mut acc, column, value);
        }
        finish(acc, settings.scale, row.out);
        0
    }))
    .unwrap_or(2)
}

The dense callback visits every output dim, skipping zeros so that its count matches the CSR path:

rs
unsafe extern "C" fn summarize_dense(call: *const DenseRow) -> i32 {
    catch_unwind(AssertUnwindSafe(|| {
        // SAFETY: the loader passes a valid DenseRow for the call's duration.
        let row = unsafe { &*call };
        let Some(settings) = settings(&row.context) else { return 1 };
        // SAFETY: dense rows carry out_dim values of the schema dtype.
        let values =
            unsafe { std::slice::from_raw_parts(row.values.cast::<f32>(), row.out_dim as usize) };
        let mut acc = EMPTY;
        for (column, &value) in values.iter().enumerate() {
            if value != 0.0 {
                fold(&mut acc, column as u32, value);
            }
        }
        finish(acc, settings.scale, row.out);
        0
    }))
    .unwrap_or(2)
}

Binding keeps Settings alive through the owner Arc, and the pointer handed out as user_data points into that same allocation:

rs
let settings = Arc::new(Settings { scale: 0.5 });
let user_data = Arc::as_ptr(&settings).cast::<c_void>();
// SAFETY: both callbacks are stateless apart from `settings`, which the
// owner Arc keeps alive; they catch panics, write only 12 output bytes and
// retain no row pointer.
let process = unsafe { ProcessFn::new(summarize_csr, summarize_dense, user_data, settings) };
let cell_bytes = size_of::<Summary>();
// Bump the identity whenever callback behavior or `scale` changes.
let schema = OutputSchema::process(1, vec![0, 1, 2, 3], Dtype::F32, cell_bytes, process, 0x5eed_0001, 0)?;

Retain the storage addressed by user_data

owner only extends the lifetime of the allocation or dependencies it owns. The example points user_data into the retained Settings allocation. An unrelated Arc::new(()) does not keep a stack value or separately dropped box alive, even though the binding compiles.

Example: a dense callback in C ​

Any language that exports a C function works. With the published header:

C implementation and Rust binding: one f32 mean per cell
c
#include <string.h>
#include "process_fn_cabi.h"

/* Mean of the dense row; one f32 per cell. */
int32_t mean_dense(const PyCellPackDenseRow *row) {
  if (row->context.abi_version != PYCELLPACK_PROCESS_ABI_VERSION ||
      row->context.struct_size != sizeof(*row) ||
      row->context.dtype != 8 /* f32 */)
    return 1;
  const float *v = (const float *)row->values;
  double sum = 0.0;
  for (uint64_t i = 0; i < row->out_dim; i++) sum += v[i];
  float mean = row->out_dim ? (float)(sum / (double)row->out_dim) : 0.0f;
  memcpy(row->out, &mean, sizeof mean); /* out may be unaligned */
  return 0;
}

Link the object into the Rust binary (for example with the cc crate) and bind it with a forced dense format:

rust
unsafe extern "C" {
    fn mean_dense(row: *const DenseRow) -> i32;
}

// SAFETY: mean_dense is stateless, thread-safe, writes 4 bytes and retains nothing.
let process = unsafe {
    ProcessFn::with_format(RowFormat::Dense, None, Some(mean_dense), std::ptr::null(), Arc::new(()))?
};
let schema = OutputSchema::process(id, out_ids, Dtype::F32, 4, process, MEAN_V1, 0)?;

C++ code must mark the function extern "C" and must not let exceptions escape it; wrap the body in try { … } catch (...) { return 2; }.

Scratch space ​

OutputSchema::process(…, scratch_bytes) gives each call a private buffer. Use it instead of allocating per cell, for example to sort a CSR row's columns before a rank-based transform. The following fragment only demonstrates checking and borrowing scratch; supply the transform and output writes:

Scratch-space fragment with an explicit alignment check
rust
unsafe extern "C" fn ranked(call: *const CsrRow) -> i32 {
    let row = unsafe { &*call };
    let n = row.nnz as usize;
    // Declared scratch_bytes = out_dim * 4 covers n ≤ out_dim positions.
    if row.scratch_bytes < (n * 4) as u64 || row.scratch.align_offset(4) != 0 { return 3; }
    let order = unsafe { std::slice::from_raw_parts_mut(row.scratch.cast::<u32>(), n) };
    // … fill `order`, sort it by value, write ranks to `out` …
    0
}

The ABI does not promise an alignment for scratch. Check it, as above, before forming a typed slice, or use unaligned reads and writes.

Partial CSR rows ​

ProcessFn::with_partial_rows (also unsafe) lets the loader skip materializing columns and values. The callback then sees null columns and values and asks resolve for the elements it needs. A partial-aware callback must still handle full rows. The following fragment illustrates resolution, not a complete output-producing callback:

Partial-row resolution fragment
rust
unsafe extern "C" fn first_k(call: *const CsrRow) -> i32 {
    let row = unsafe { &*call };
    let k = row.nnz.min(16) as usize;
    let mut columns = [0u32; 16];
    let mut values = [0f32; 16];
    if row.columns.is_null() {
        let positions: [u32; 16] = std::array::from_fn(|i| i as u32);
        // A position at or beyond nnz makes resolve return nonzero.
        let resolve = row.resolve.unwrap();
        let status = unsafe {
            resolve(row.row, positions.as_ptr(), k as u64, columns.as_mut_ptr(), values.as_mut_ptr().cast())
        };
        if status != 0 { return status; }
    } else {
        // Full rows still arrive: copy from row.columns / row.values.
    }
    // … write `out` …
    0
}

resolve and row are valid only during the call. columns and values must each have room for count entries, and values must be aligned for the schema dtype. Passing a null positions with count == nnz returns every element in row order. A partial-aware callback must still handle full rows, because partial delivery is offered only when every element of the row maps to an output column.

Access functions ​

Deterministic native sample generation
  1. 01
    Request a range

    Workers or planners ask for a starting access and count.

  2. 02
    Compute from position

    Use immutable seed/epoch settings and the requested positions; tolerate concurrent and repeated calls.

  3. 03
    Fill the outputs

    Write exactly the requested IDs or dataset/local-row pairs, then return status zero.

Retain no borrowed output pointers. A nonzero status fails the run.

An access sequence is a pure function from access index to cell. With S schemas, access k is schema k % S of position k / S. The native form fills a range:

rust
pub type AccessFn =
    unsafe extern "C" fn(context: *mut c_void, start: u64, count: u64, cells: *mut CellId) -> i32;
c
typedef int32_t (*CellPackAccessFn)(void *context, uint64_t start,
                                    uint64_t count, uint32_t *cells);

What the loader checks and what it trusts ​

PropertyChecked?
Requested range lies within lenYes: the adapter rejects it before calling
Returned ids are below the source's cell countYes: Error::Access { position, cell } when the cell is located
Nonzero statusYes: Error::Accesses(status) cancels the run
Writes stay within cells[0..count]No: writing past count corrupts the caller's buffer
Output depends only on (start + i) and immutable configurationOnly under a plan: a worker whose cell differs from its plan entry's stops the run with Error::Plan. Without a plan a stateful generator silently gives different batches
context outlives the sequence and tolerates concurrent readsNo: use-after-free or data races
No unwinding across the boundaryNo

Do not advance a shared random-number generator inside the function. Derive randomness from the position, for example by hashing (seed, epoch, index), as Shuffle does.

Example: a native order in Rust ​

rs
/// Native access order: position `p` loads cell `p * stride mod cells`.
#[repr(C)]
struct Stride {
    cells: u64,
    stride: u64,
}

unsafe extern "C" fn strided(context: *mut c_void, start: u64, count: u64, out: *mut CellId) -> i32 {
    // SAFETY: context is the Stride below, alive and read-only for the run.
    let stride = unsafe { &*context.cast::<Stride>() };
    // SAFETY: the loader passes exactly `count` writable cells.
    let out = unsafe { std::slice::from_raw_parts_mut(out, count as usize) };
    for (i, cell) in out.iter_mut().enumerate() {
        *cell = ((start + i as u64) * stride.stride % stride.cells) as CellId;
    }
    0
}
rs
let order = Stride { cells: 4, stride: 3 };
// SAFETY: `strided` is pure, thread-safe and writes exactly `count` ids;
// `order` outlives the run below.
let accesses = unsafe { ExternAccesses::new(strided, (&raw const order).cast_mut().cast(), 4) };

The example then runs the loader with &accesses exactly as with a Vec<CellId>. Because ExternAccesses has no backing slice, a fixed plan must materialize it for verification; prefer online planning for long generated sequences.

Example: the same order in C ​

C callback with immutable striding configuration
c
#include "access_fn_cabi.h"

typedef struct { uint64_t cells, stride; } Stride;

CELLPACK_ACCESS_EXTERN CELLPACK_ACCESS_EXPORT
int32_t strided(void *context, uint64_t start, uint64_t count, uint32_t *cells) {
  const Stride *s = (const Stride *)context;   /* read-only: safe to share */
  if (s->cells == 0) return 1;
  for (uint64_t i = 0; i < count; i++)        /* exactly count entries */
    cells[i] = (uint32_t)(((start + i) * s->stride) % s->cells);
  return 0;
}

Choose counts and stride values whose multiplication fits in uint64_t if you need mathematical modular-stride behavior; C unsigned overflow otherwise wraps before the remainder. The application must keep Stride alive through every callback and keep its fields unchanged.

Corpus access functions ​

When the application indexes cells as (dataset, row) pairs, implement CorpusAccessFn instead and bind the row count of each registered matrix:

c
typedef int32_t (*CellPackCorpusAccessFn)(void *context, uint64_t start,
                                          uint64_t count, uint32_t *dataset_ids,
                                          uint64_t *rows);
rust
// counts[d] is the row count of the d-th registered matrix, in registration order.
let accesses = unsafe { ExternCorpusAccesses::new(corpus_fn, context, len, &counts)? };

The adapter translates each pair to offset[dataset] + row and rejects a dataset or row outside the bound counts with an error. The same write-bounds, determinism, lifetime and thread-safety obligations apply. counts must match the order in which matrices were added to the DataSourceBuilder; a different but in-range order is not detected and loads the wrong cells.

Versioning ​

ConstantValueCovers
loader::PROCESS_ABI_VERSION / PYCELLPACK_PROCESS_ABI_VERSION1ProcessContext, CsrRow, DenseRow, ResolveFn
CELLPACK_ACCESS_ABI_VERSION1AccessFn, CorpusAccessFn

struct_size reports the size of the row struct actually passed, which lets a callback detect a newer, longer struct. A callback built against a different abi_version must not be bound; reject the call with a nonzero status when the version does not match.

API: ProcessFn, CsrRow, DenseRow, ProcessContext, AccessFn, ExternAccesses, ExternCorpusAccesses.