Introducing a new way to review your PRs.

Read the announcement

reflex-dev / xy

Ultra-fast and customizable Python charts

View on GitHub

20 documents · Updated Nov 18, 2026

docs / native-kernels-and-python-bindings

Native kernels and Python bindings

The native kernel system moves high-cost chart preparation and numeric work from Python into a compiled Rust library. Python keeps the main data arrays and asks Rust to scan, reduce, sample, transform, or build geometry through a small C ABI, while runtime SIMD and thread use improve speed without changing the result. This page is a child of the Rust acceleration engine; native drawing resources are described in Native rendering primitives.

Kernel system

The kernel system provides focused computations over caller-owned numeric buffers. It supports chart preparation, large-data view changes, analysis features, and geometry generation while leaving chart policy and final display decisions to the Python and client layers. The Python-facing names are gathered in python/…/kernels.py, and the Rust entry points are grouped in src/kernels.rs.

Data preparation and numeric reduction

These kernels turn source columns into compact values that later chart stages can use. They preserve row identity and handle invalid numeric values in a defined way, so autorange, selection, and rendering do not make different choices about the same data.

CapabilitySystem purpose
Zone mapsSummarize chunks with bounds, valid and null counts, sums, and positive bounds for fast range decisions.
Relative f32 encodingKeep useful precision when large source values contain small visible changes.
Fixed-record factorizationConvert repeated labels or fixed-width values into compact codes and first-seen unique rows.
Validity and order scansFind usable rows, check sorted inputs, and compute finite min/max values without Python-sized temporary arrays.
Histogram and stack preparationBuild uniform or arbitrary-edge counts and compute stacked-area bounds.

NaN and infinite values are treated as invalid where a kernel needs plottable values. The zone-map contract counts them as nulls, while relative encoding can preserve a NaN for a later stage that owns gap handling.

References: src/kernels.rs• L689-779 src/kernels.rs• L865-881 src/kernels.rs• L4596 src/kernels.rs• L5349-5427

Screen-bounded geometry and density

These kernels reduce or reshape data to match the current view. Their outputs are usually bounded by the screen or by the requested geometry size, which keeps interaction work proportional to what the user can see rather than to the full source column.

CapabilitySystem purpose
M4 line reductionKeep the first, minimum, maximum, and last point in each visible bucket so spikes and line shape survive reduction.
Two-dimensional binningTurn points into a viewport-sized density grid and provide variants for f32 inputs, colors, indices, and samples.
Window and lasso selectionReturn canonical row IDs inside rectangular or polygon regions.
Local densityGive each point a normalized density value by combining grid counts with point lookup.
Tile-pyramid accessBuild, append, count, and compose reusable density summaries for repeated zoom and pan requests.

The density family has fused forms that return related results in one source scan. For example, a combined density-and-index request keeps the grid equal to standalone binning while avoiding a second read of the source columns.

References: src/kernels.rs• L2474-2506 src/kernels.rs• L3040-3052 src/kernels.rs• L3690 src/kernels.rs• L4846-4860 src/kernels.rs• L5241-5282 python/…/_native.py• L2325-2430

Geometry and signal analysis

The library also owns common transforms that would otherwise create large intermediate arrays in Python. It emits compact geometry or analysis arrays that the chart adapters can pass to the render and layout stages.

CapabilitySystem purpose
Grid and polygon geometryProduce triangles, edges, contours, vector segments, and streamlines from regular or indexed data.
Sector and mesh geometryTurn pie, donut, quad, and curvilinear data into render-ready triangles.
Spectral analysisProvide real FFT, Welch auto or cross spectra, spectrograms, and lag correlation.
Weighted distribution analysisSort and combine values for weighted empirical CDF output.
Deterministic samplingProduce repeatable row masks or row IDs, including category-balanced samples for dense views.

The Python adapters use these results to implement chart features such as contours, vector fields, spectral plots, and density overlays. They do not need to reproduce the Rust math or allocate a full source-sized temporary for each operation.

References: src/kernels.rs• L1523-1702 src/kernels.rs• L4014-4251 python/…/_native.py• L1824-1978 python/…/_native.py• L2748-2940

SIMD acceleration

SIMD means single instruction, multiple data: one CPU instruction handles several values at once. The Rust library uses runtime dispatch so a machine with AVX2 can use vector-friendly scan bodies, while other machines use the same scalar contract; SIMD is an execution choice and is not a separate Python backend.

Runtime dispatch and parity

The SIMD layer currently targets exact-path scans where the result does not depend on floating-point addition order. It accelerates finite min/max, two-dimensional point counts, rectangular range scans, and local-density grid gathers. The Rust kernel calls a safe try_* dispatch function and uses the scalar path when AVX2 is unavailable or disabled.

References: src/simd.rs• L1-30 src/simd.rs• L273-357 src/kernels.rs• L5060-5075 src/kernels.rs• L5241-5282 src/kernels.rs• L5404-5422

The dispatch preserves the scalar result bit for bit. Float-accumulating reductions such as zone-map sums stay outside the SIMD set because reassociation could change their bits. M4 and histogram work also stays scalar where bucket state or scatter updates cost more than vector math saves.

References: src/simd.rs• L16-30 src/kernels.rs• L2524-2529 src/kernels.rs• L1026-1047

The XY_SIMD=0 environment setting forces scalar execution. On non-x86-64 targets the SIMD module reports no AVX2, and the normal Rust loops remain the portable path. The parity test uses non-finite values, extreme magnitudes, and partial blocks to check that the accelerated and scalar paths agree.

References: src/simd.rs• L47-60 src/simd.rs• L360-447

Python binding boundary

The Python side exposes one native compute surface rather than several optional backends. python/…/kernels.py imports the compiled implementation from python/…/_native.py, re-exports its public kernel names, and reports BACKEND = "native"; there is no silent pure-Python downgrade.

References: python/…/kernels.py• L1-27 python/…/kernels.py• L29-91

Library loading and ABI identity

The binding loads a platform-specific Rust shared library from an explicit override, the installed package, or the development build output. It checks the ABI version before exposing any function. This keeps the Python declarations and Rust function signatures paired instead of allowing an old library to receive a new call layout.

References: python/…/_native.py• L27-83 src/lib.rs• L83-91

When the library is missing or the version is wrong, import fails with repair guidance. Supported wheels avoid a local compiler on supported platforms; other environments must build the Rust core from source. This failure is deliberate because using a slower path would hide a packaging or deployment problem.

References: python/…/_native.py• L1-11 python/…/_native.py• L49-69 python/…/kernels.py• L15-27

Buffer and result contract

The binding validates shapes, dtypes, ranges, and capacities before it crosses the language boundary. It makes a contiguous NumPy view when needed, passes its memory address to Rust, and allocates result arrays on the Python side. In this model, Rust reads or writes the live caller buffers during the call; it does not own the chart's canonical columns.

References: python/…/_native.py• L818-876 src/lib.rs• L1-19

The two sides use explicit status values and size returns. A Rust error sentinel becomes a Python exception, while a valid size lets Python trim an over-allocated result. Some output-producing calls use a first count query and a second write call when the result size is not known in advance.

References: python/…/_native.py• L1193-1330 python/…/_native.py• L2066-2161 src/lib.rs• L41-52

Fused calls and native hooks

Python-side acceleration hooks combine native operations when the same source data would otherwise be scanned more than once. Density requests can combine a grid with selected rows, categorical inputs can reuse factorization counts, and M4 can write selected points directly instead of returning indices for a later Python gather. These hooks keep the public result contract aligned with the separate operations.

References: python/…/_native.py• L879-1002 python/…/_native.py• L2012-2043 python/…/_native.py• L2325-2507

The binding also owns the platform-sensitive parts of the boundary. It derives the usize error sentinel from ctypes, checks row IDs before narrowing them to u32, and keeps input arrays alive for the duration of each call. Rust adds a panic guard so a recoverable panic becomes the entry point's error result instead of unwinding into Python.

References: python/…/_native.py• L29-38 python/…/_native.py• L825-854 src/lib.rs• L41-80

Kernel request flow

The flow below shows how a Python chart feature reaches the native computation and returns a checked result without selecting a second backend.

flowchart LR
    A[Python chart or analysis request] --> B[xy.kernels public name]
    B --> C[_native validation and buffer views]
    C --> D[ctypes C ABI call]
    D --> E[Rust kernel]
    E --> F{AVX2 enabled?}
    F -->|yes| G[SIMD hot path]
    F -->|no| H[scalar or threaded path]
    G --> I[caller-owned output buffer]
    H --> I
    I --> J[NumPy result or Python error]

The native kernel remains inside the Python process. The client or renderer receives the resulting arrays through the normal chart pipeline, while drawing primitives themselves belong to Native rendering primitives.

References: src/lib.rs• L1-19 python/…/kernels.py• L1-11

Change checklist

When these files or sections are changed, remember to consider these:

  • A Rust C-ABI signature change must update ABI_VERSION, the matching ctypes declaration, and the Python result or error handling.
  • Any change to a size-returning sentinel must preserve platform width through ctypes.c_size_t; do not replace it with a fixed 64-bit value.
  • Any SIMD loop change must preserve scalar parity, the XY_SIMD=0 switch, and the scalar path on non-x86-64 targets.
  • A change to NaN handling, edge inclusion, row order, or output layout must be checked against both standalone and fused kernel callers.
  • A new public kernel must be wired through the C ABI, _native.py, and kernels.py so its name, validation, and __all__ surface stay aligned.
  • A count-query or retry change must keep the first reported size equal to the second write size; otherwise Python can return truncated or undefined output.

Important failure modes

TriggerConsequenceGuard
Native library is absent or its ABI version differsImport fails instead of silently using a slow alternate path.Install a matching wheel or rebuild the Rust library from source.
A Python wrapper sends unequal columns, invalid bounds, or an unsupported shapeThe wrapper raises ValueError before the native call or maps the native error result to one.Preserve the wrapper validation and the Rust argument checks together.
A size-returning native call returns an error sentinelPython must not slice the output as if the sentinel were a valid count.Compare with the platform-derived _USIZE_MAX and treat the output as undefined.
A compact categorical factorization exceeds 256 unique valuesThe compact path declines and the caller must use the general code path.Handle _FACTORIZE_CAPACITY_EXCEEDED as a capacity result, not as a native crash.
A Python-side row ID narrows outside the u32 rangeA different row could be selected after integer wraparound.Validate integer row IDs before converting them to uint32.
XY_SIMD=0 or no AVX2 support disables vector dispatchThe result stays correct but the selected hot path is slower.Use the scalar implementation as the normal fallback and treat SIMD as an optimization.
Fused output count changes between its query and write callsPython raises a consistency error or could otherwise expose incomplete output.Keep the native count deterministic for identical inputs and parameters.

Key files

FileWhy to read it
src/kernels.rsDefines the core computation contracts for reductions, decimation, density, selection, sampling, geometry, and signal analysis.
src/simd.rsExplains the AVX2 dispatch boundary, the scalar-parity rule, and the supported vectorized hot paths.
src/lib.rsDefines the stable C ABI, buffer ownership rules, ABI version, status sentinels, and panic shield.
python/…/_native.pyShows how NumPy arrays become validated caller-owned buffers and how native results become Python arrays or exceptions.
python/…/kernels.pyShows the public Python dispatch surface and the intentional native-only backend policy.
tests/test_kernels.pyStates the externally visible guarantees for precision, invalid data, output parity, sampling, density, geometry, and native error handling.