# The native encoder

LLMS index: [llms.txt](/docs/llms.txt)

---

`xuebuild/` is the reference encoder: Python driving GDAL and zstd as CLI
subprocesses. `rust/xue/src/encode/` is the same `convert-bin` pipeline
written in Rust with those tools linked in process, behind the `xue` crate's
off-by-default `encoder` feature, and published as the `xuepy` wheel.

A build converts through it by default. The Python encoder remains the
reference (a format change lands there first), and the native encoder is
held to it by byte-for-byte identical output.

## Motivation

Profiling the Python pipeline put the remaining wall time in extraction:
`gdal_translate -of ENVI -ot Float64` writes every plane to disk as float64
and the encoder reads it back. A full GFS run is 121 files × 4 variables ×
1.04 M points × 8 bytes ≈ 4 GB written and re-read per build, plus one
subprocess per file. Reading the same bands through GDAL's C API skips all
of it.

## Components

| Stage | Python | Native |
|---|---|---|
| grid + band metadata | `gdalinfo -json` subprocess | `gdal-sys` (georust) in process, exported back to Python as `xue.gdal_info` so `xuebuild` can inspect without a system GDAL |
| plane extraction | `gdal_translate` → ENVI → `np.fromfile` | `GDALRasterIO` into a `Vec<f64>`; PNG-packed GRIB2 (template 5.41, every MRMS product) inflated directly (`gribpng.rs`), with the single-precision unpack calibrated against one GDAL read per process |
| GRIB2 record index | hand-rolled section walker (`xuebuild/grib2.py`) | [grib-rs](https://github.com/noritada/grib-rs) |
| compression | `compression.zstd` / `zstd` CLI | `zstd` crate (`ZSTD_compress2`) |
| poster deflate | `zlib.compress(level=9)` | `flate2` on libz |
| read-back verify | `xuebuild/binformat.py` reference reader | the `xue` decoder crate, the same code the browser runs |

`gdal-sys` is used rather than the high-level `gdal` crate because, as of
`gdal` 0.19, the safe wrapper does not compile against GDAL 3.13 (its
`GDALDataType` and `GDALRasterIOExtraArg` changed shape). The surface needed
here is a dozen stable C functions (`src/gdalio.rs`).

GDAL's GRIB driver takes about 0.3 s to unpack one 7000 × 3500 MRMS plane
whose PNG inflates in under 10 ms; `gribpng.rs` reads it in about 80 ms. Its
values must be GDAL's to the bit. g2clib computes `refD + bdscale × X` in
single precision, and whether that multiply-add is fused depends on how the
linked GDAL was compiled. So the first eligible plane is read both ways, and
the arithmetic that reproduces GDAL is used from then on. If neither does,
every read stays on GDAL.

Each band is taken through the whole per-plane chain (column roll, fill
values, block thinning, crop, the completeness check, unit
conversion) as soon as it is read, before the next band is read, so a
worker holds one full-resolution plane at a time rather than every record
of its file. That matters for the MRMS 3D mosaic, whose frame is 33
records of 7000 × 3500 doubles: 6.5 GB read whole, 196 MB a plane. A file
the netCDF driver reads is the exception: its reads stay serialized under
`netcdf_guard`, and its planes are finished after the guard is released.

## Building

GDAL must be discoverable through `pkg-config`, and `gdal-sys` generates its
bindings with `bindgen`, so libclang must be present too:

```sh
export PKG_CONFIG_PATH="$(gdal-config --prefix)/lib/pkgconfig"
cargo build --release -p xue-encode
```

Or, from the repository root, `make encoder-rust`.

## Using

```sh
xue-encode convert-bin data/raw/gfs.2026082006 --model gfs --output out/
xue-encode convert-bin cases/ --model gfs --output out/ \
    --bbox 105,28,122,42 --bundles prate,wind10m --manifest out/manifest.json
xue-encode convert-bin --help
```

`--skip-video` is accepted and ignored: no encoder builds the retired H.264
companion.

## In the build pipeline

`xuebuild` depends on the `xuepy` wheel and converts through it by default.
`xuebuild/encoder.py` is the dispatch and `XUE_ENCODER` overrides it:

| `XUE_ENCODER` | |
|---|---|
| `auto` (default) | the native encoder when the wheel imports, the Python pipeline otherwise |
| `native` | require the wheel; fail if it is missing |
| `python` | the reference pipeline, whatever is installed |

`make check` reports which one a build would take. The scheduled `publish-*`
workflows pin `native`: a run that fell back to the Python pipeline would
take hours longer and look identical in the logs. `publish-jma.yml` and the
other rolling windows are the exception: a wheel ships on the crate's
tags, so the wheel on PyPI can predate a rule the registry document now
names, and a scheduled run cannot pass an input. Their `Resolve the
encoder` step asks `native.knows_source(model)` and sets
`XUE_ENCODER=native` when the installed wheel implements the document,
else `python` with GDAL installed and a `::warning::` on the run, so the
fall back is explicit rather than silent; a dispatch can still insist on
either. The question is the wheel's `validate_build(registry=..., model=...,
bundle_ids=...)`: the checks `convert_bin` makes before it reads any input
(the document, the source, the profile's codebooks, the bundle list), run
alone. It returns `None`, or raises `xue.UnsupportedRegistry` (a
`RuntimeError`) naming what this wheel does not implement, which is the one
answer that falls back. Anything else it raises fails the step: the
reference pipeline runs through the same wheel, so a broken wheel would
fail that build too. A wheel without `validate_build` is asked with an
empty conversion instead, and only its refusal of the empty input list
(`no GRIB files given`, or a series-file source's `a <model> build takes
one NetCDF series, …`) counts as a yes.

## The registry document

The native encoder holds no table of variables, bundles or sources. It
reads the registry document ([`registry.md`](registry.md)) — the one JSON
document the Python tables author and `xue registry` prints — and builds
from that: every codebook, every GRIB band rule, every unit conversion,
every bundle's members and derivation, every source's inputs and grid
come out of the document (`rust/xue/src/encode/registry.rs` parses it,
`units.rs` and `inspect.rs` implement its rule names). No code path in
`rust/xue/src/encode/` selects behaviour by matching a variable or bundle
id; what an id *means* is what its entry says.

The document reaches the encoder two ways:

- the wheel's `convert_bin(..., registry=...)` takes it as a required
  keyword argument carrying the JSON text, and `xuebuild/native.py` passes
  `xuebuild.registry.document_json()` on every call, and
  `validate_build(registry=...)` takes it the same way; `xue.quantize` takes the same
  `registry=` keyword, since a codebook is a block of the document;
- `xue-encode convert-bin` takes `--registry <path>`, and without one
  reads the snapshot embedded at build time, `rust/xue/registry.json`,
  which `xue registry --output rust/xue/registry.json` regenerates and
  `tests/test_registry.py` holds to the Python tables.

The encoder validates the document it is handed before any input is read
(`registry.md` §Validation) and refuses it with the field and value named
when it carries a `registrySchema`, a rule, a derivation or a codebook
type the encoder does not implement; a key it does not know it ignores. A
build hands it only its own source's part (`registry.source_document_json`),
so a rule a wheel lacks stops the sources that use it and no others.
So a *table* change — a new source, a new bundle, another level of a known
family, a changed codebook, a changed set of inputs — is a commit to
`main` and needs no release: the next build hands the new document to the
wheel already installed. A release is still needed for what the document
cannot say: a new rule name under `conversion` or `match.gdal`, a new
`derivation.kind` or codebook `type`, a new ingest path (a file shape the
converter does not read), or a `registrySchema` bump, each of which the
installed wheel refuses, for the sources that use it, until the wheel that
implements it ships. A `seriesQuantization` is the exception that is not
refused: a wheel that predates it ignores the key and writes the series
store on byte codes, so a codebook enters `SERIES_CODEBOOKS` only once the
wheel the builds run writes sixteen-bit series stores.

The native encoder writes the Zarr stores' arrays itself, straight from its
codes (`rust/xue/src/encode/zarrstore.rs`, the counterpart of
`zarrstore.write_bundle_arrays` over a `CodesSource`), with the series
stores for the bundles the caller names (`SourceSpec.series_bundle_ids`,
passed in by `native.py`). A series store's widened variables
([`zarr-profile.md`](zarr-profile.md), "Series store") follow the
reference's rule over the same document: every variable of those bundles
(of `bundle_ids` alone on a restricted build) whose registry entry carries
a `seriesQuantization` is quantized a second time in the per-file stage,
from the float plane its byte codes come from, with the same round-half-up
and clamp, into sixteen-bit codes. Those go to a spool, one file per
variable in a scratch directory of the build's own under the system
temporary directory (`xue-series-<pid>-<n>`; the wheel takes no work
directory, and the output is never used, since a publish uploads it),
frame-major and little-endian, by positioned writes as each file finishes;
the series writer reads them back one block row (every frame of eight grid
rows) at a time, writes the variable as a `uint16` array under the series
metadata (the bundle's, the block as that variable's `quantization`), and
deletes the variable's file once its store is written; the directory goes
when the build returns, failed or not (only a process killed outright
leaves it, in the temporary directory). Every other variable of a series
store, and every map store, container and tier, keeps its byte codes
exactly. The wheel's `write_store` takes `uint16` planes for such a
variable too, which is what `tests/_support.py::native_writes_wide_series`
asks before a parity test over widened series stores runs. It does not
write two artifacts, and `xuebuild/native.py` supplies them:

- The shared stores' group documents. See "Shared stores" below.

- The live pointer. It carries the manifest's CRC32, and stamping the
  shared stores' CRCs in changes the manifest, so the native encoder has no
  pointer writer: it writes the manifest alone and the pointer is written
  afterwards, from the finished bytes. The wheel's `convert_bin` still
  accepts `latest_path` and `run_id` and ignores them.

`tests/test_native.py` holds the two together: one build through each
encoder into identically shaped directories, then every artifact compared
byte for byte (stores, containers where written, reduced-resolution
variants, posters, `manifest.json`, and the live pointer), and one fanned-out job's arrays,
parts and partial manifest the same way. `tests/test_zarr.py` also holds the
two one-bundle store writers to the same bytes directly (`xue.write_store`).

### Shared stores

A run's map stores are shared ([`zarr-profile.md`](zarr-profile.md),
profile 2): every bundle of one tier in `bundles[.<tier>].zarr`. The call
boundary is the partial group document. For every build, whole or one job
of a fan-out, the wheel writes into each tier's shared store:

- every bundle's variable arrays, as a one-bundle store's but with
  `attributes.xue.bundle` leading the block and the bundle's dimension
  names (`discover.store_dimensions`: `time_<bundle id>` for a published
  scalar in `analysis_optional_ids` or a static first variable,
  `latitude_<family>` / `longitude_<family>`, `<family>` the id
  `bundle_grid_family` returns, for a bundle off the primary grid);
- every coordinate array those names call for, the same bytes whichever
  bundle writes it;
- one partial group document, `zarr.part.<first bundle id>.json` — the
  profile's group document (`zarrstore.group_document`, same key orders,
  same serializer as `zarrstore._dump_json`) over the bundles this build
  wrote, in manifest order — and no `zarr.json`;

and names each store in its manifest entries with the entry's `byteLength`
(its arrays and the coordinates it uses) and the **part's** CRC-32 as
`crc32`, writing the manifest where `native.py` asks
(`.<manifest>.native`, beside the real one). `native.py` then, unless the
build is a fan-out job (`partial=True`), calls
`zarrstore.finalize_store` on each store — the reference's own merge, which
writes `zarr.json` and removes the part — and stamps the group document's
CRC-32 on every entry naming the store as it writes the real manifest. A
fan-out job keeps the part and the part's CRC; `assemble-run` does the
rest, as for the reference.

This keeps byte identity to what the native side writes anyway (arrays,
coordinates, and one JSON document per store in the profile's serializer)
and gives the group document, the merge with parts and live documents and
the CRC stamping one implementation, the reference's. The wheel's own
store reader opens a profile-2 group by bundle id
(`zarr::parse_group_metadata_for(text, bundle_id)`), which the encoder's
read-back self-check uses.

### Column stores

A run's column store ([`zarr-profile.md`](zarr-profile.md), "Column store")
is cut after the run is finished, from its map stores, so it is a call of its
own rather than part of a conversion: `xue.write_columns`
(`rust/xue/src/encode/columns.rs`), the counterpart of
`columns.write_column_store`. It is data processing alone. It takes no
registry document and knows no source; it takes a **plan**, the one document
both writers are called with, as JSON text:

```jsonc
{
  "columnsPlan": 1,
  "arrays": [
    { "id": "tmp", "predictor": "previous",        // or "raw"
      "levels": [1000, 975],                       // levelled arrays only
      "members": [
        { "bundle": "tmp1000", "variable": "tmp1000", "store": "bundles.zarr" },
        { "bundle": "tmp975", "variable": "tmp975", "store": "bundles.zarr" } ] },
    { "id": "orog", "predictor": "previous",
      "members": [ { "bundle": "orog", "variable": "orog", "store": "bundles.zarr" } ] }
  ]
}
```

`store` is relative to the run directory. The metadata, grid, axis,
codebooks, codes and tiling are read from the stores named, of either
profile: of each, the group document, whose consolidated metadata holds
every array's, and each member's shard. A `columnsPlan`, key or predictor
this writer does not implement is refused, and so is what a column store
cannot hold: members of one array that differ in axis or nodata code,
members of one store that differ in run, profile or grid (`1` and `1.0`
differ, as they are spelled apart in a document), a projected grid.
The Python side makes the plan from the source's `column_arrays`, the
registry and the manifest.

The unit of work is one shard of one array: a band of 96 rows, every level
over the whole axis, held uncompressed. A worker seeks to the inner chunks
of the map shards that overlap its band and decodes them one at a time, and
writes each payload as it is compressed, so memory is one band per worker:
for twenty-one levels of a 161-frame axis on the 0.25° global grid, 467 MB
each. The shards run in a pool of `jobs` threads and the bytes do not depend
on how many. The level is 6, not the grid stores' 15
([`zarr-profile.md`](zarr-profile.md)). Every chunk is decompressed again and compared with what went
in, and the group document is parsed by the decoder's reader
(`column::ColumnGroup`) twice: before the cut, so that what a reader would
refuse is refused at once, and as it is written. It is written last, by
rename; a cut that fails removes its directory, and an `output` that exists
is an error.

`xuebuild/encoder.py` picks the writer by `XUE_ENCODER` as it picks a
conversion's: under `auto` a wheel without `write_columns` falls back to
Python, under `native` it is an error. `tests/test_columns_native.py` holds
the two to the same directory, byte for byte, over the committed fixture and
over synthetic stores, at one worker and at four.

## Python bindings

`rust/xue-py/` is a thin PyO3 + `rust-numpy` wrapper, published as the
`xuepy` distribution and imported as `xue`. It carries both halves of the
crate.

The decoder is `Bundle`, the same reader the browser runs through wasm.
Planes come back as `uint8` NumPy arrays of quantized codes:

```python
import xue

bundle = xue.Bundle.open("web/public/data/gfs.2026082006/tmp2m.xue")
plane = bundle.decode(variable_id=1, frame_offset=24)  # uint8, width * height
codebook = bundle.metadata["variables"][0]["quantization"]
celsius = codebook["offset"] + plane * codebook["scale"]
```

The encoder is `convert_bin`, which runs the whole native conversion and
returns the same report dictionary the Python pipeline returns, plus
`quantize` / `encode_residual` / `decimate` / `encode_poster`, which take
and return NumPy arrays so individual stages can be compared against
`xuebuild/quantize.py` and `xuebuild/temporal.py` without running a build,
`write_store`, which writes one bundle's one-bundle (profile 1) Zarr
store from codes handed in as NumPy arrays, and `write_columns`, which cuts
a run's column store ("Column stores" above):

```python
report = xue.convert_bin(["data/raw/gfs.2026082006"], "out/", model="gfs")
# out/bundles.zarr, out/bundles.half.zarr with their parts (native.py writes
# the group documents); and the .xue containers too:
report = xue.convert_bin(["data/raw/gfs.2026082006"], "out/", model="gfs", container=True)
```

`convert_bin` writes the Zarr stores alone by default (`zarr=True`,
`container=False`), as every live run publishes; `container=True` adds
each bundle's `.xue` beside the stores, from the same codes, and
`zarr=False, container=True` writes the containers alone.

### Installing

```sh
pip install xuepy
```

The wheel carries its own GDAL, so nothing else has to be installed and no
environment variable has to be set. The wheel is `abi3-py314`: one per
platform, not one per Python minor version. Linux wheels are
`manylinux_2_39`, tagged with the glibc of the ubuntu-24.04 runner that
built them, which means Ubuntu 24.04 and later, Debian 13 and later;
broader coverage would mean building inside a `manylinux_2_28` container.
macOS is arm64 only.

### Building a wheel

```sh
make encoder-wheel          # minimal GDAL, then the wheel, then repair it
```

`scripts/build-gdal-minimal.sh` builds libaec, OpenJPEG, HDF5, netCDF, PROJ
and GDAL from source into `build/gdal-minimal`, and
`scripts/build-encoder-wheel.sh` stages GDAL's and PROJ's data directories
plus every licence text into the package, runs maturin, and lets `delocate`
(macOS) or `auditwheel` (Linux) move the shared libraries in. zlib and
sqlite3 come from the platform and are not bundled.

### Why a bundled GDAL, and why a minimal one

The wheel has to carry GDAL, because the GRIB driver will not read a band
without GDAL's own data directory: with `GDAL_DATA` unset it reports
`Cannot find grib2_center.csv` and then matches zero records, so record
matching fails outright rather than degrading.

A distribution GDAL is not suitable to carry. A package-manager build pulls
a 318 MB closure of 227 shared libraries (Arrow, TileDB, OpenBLAS, libicu,
x265), of which the encoder uses none. It also includes Poppler (GPL-2/3),
x265 (GPL-2), libde265 (LGPL-3), libspatialite and mariadb-connector-c
(LGPL), whose obligations a redistributed binary would have to answer for.

Built here with the GRIB and netCDF drivers, plus the JP2OpenJPEG driver
the GRIB driver decodes JPEG 2000-packed records through (WAVEWATCH III
packs the GFS-Wave files that way, DRS template 5.40), and nothing else,
the whole closure is eight libraries:

| | |
|---:|---|
| 16.4 MB | libgdal |
| 4.2 MB | libproj |
| 3.9 MB | libhdf5 |
| 1.2 MB | libnetcdf |
| 0.4 MB | libopenjp2 |
| | libhdf5_hl, libaec, libsz |

plus 10.2 MB of `proj.db` and 3 MB of GDAL's data tables: a 12 MB wheel.
zlib, sqlite3, libSystem and libc++ come from the platform.

Everything bundled is permissive and allows binary redistribution with
attribution: GDAL and PROJ (MIT), HDF5, libaec and OpenJPEG (BSD), netCDF
(MIT-style), and zlib and sqlite3 from the platform. Several ask explicitly
for their notice to travel with a binary, so the wheel carries them in
`xue/licenses/`.

### Build problems and their fixes

Each is commented where it happens:

- Enumerating the codecs to disable does not work. GDAL probes several
  through pkg-config, which has its own search path; a machine with
  Homebrew ends up linking libjxl and Brotli into a build with no driver
  able to use them, and because those were built for a newer macOS, the
  wheel comes out tagged `macosx_26_0` instead of `macosx_11_0`.
  `GDAL_USE_EXTERNAL_LIBS=OFF` plus the three dependencies by name is the
  reliable form, and for OpenJPEG the library's path as well: GDAL's probe
  goes through pkg-config, CMake caches what it found the first time the
  tree was configured, and a developer machine linked Homebrew's
  `libopenjp2` into a wheel meant to carry its own.
- CMake will compile against one copy of a library and link another. With
  Homebrew's HDF5 2.1 headers ahead of the 1.14 built here, netCDF built
  cleanly and then failed at run time on every netCDF-4 file with
  `H5Pset_libver_bounds(): high bound is not valid`, an enum value that
  only exists in the newer library. `CMAKE_IGNORE_PREFIX_PATH` keeps the
  prefix and the platform SDK the only things in scope.
- `delocate` cannot vendor what it cannot resolve. The extension links
  libgdal by its `@rpath` install name, so the build passes
  `-C link-arg=-Wl,-rpath,<prefix>/lib`; delocate strips the rpath again
  once the libraries are copied in.

## Equivalence

`make encoder-rust-test` runs the crate's unit tests plus a golden test that
encodes `tests/fixtures/gfs.2026081406.f000.crop.grib2` and demands the
exact bytes `tests/prepare_bin_fixture.py` produced with the Python encoder.

Four places needed care to reach that:

- The geotransform is what `gdalinfo -json` prints, on both sides. GDAL
  writes each coefficient in fixed notation with sixteen decimals, then its
  `intelliround` cuts a trailing `00000x` or `99999x` as binary noise (the
  same code in 3.8 and 3.13), so a netCDF axis's 0.012500000000000292 reads
  as 0.0125. The native encoder reads the doubles through the C API and
  passes them through the same formatting (`gdalio::as_gdalinfo_json`),
  which is also what the wheel's `gdal_info` reports, so the Python encoder
  sees one geotransform whichever GDAL it inspects through. A grid the snaps
  in `grid.rs` clean (whole thousandths or arc-minutes, a global width)
  never noticed the difference; the CWA radar's 0.0125° grid does.
- `flate2` links stock libz, not `zlib-rs`. `zlib-rs` is a port of zlib-ng,
  whose deflate output differs from the zlib CPython uses, which would
  change every poster payload.
- The manifest's embedded metadata strings are `json.dumps` at its
  defaults. A bundle stores its metadata compact and in raw UTF-8; the
  `metadataJson` a manifest carries for a poster is the same
  object written with a space after every separator and every non-ASCII
  character escaped, so the degree sign in the temperature unit reaches the
  manifest as `°`. `pyjson::dumps_default` does both.
- Compression is one-shot on both sides. The Python encoder calls
  `compression.zstd.compress`, which records the pledged source size in the
  frame header. The streaming encoder does not, and picks different window
  parameters (about 5 % larger payloads and different bytes), so
  `zstd_compress` here calls `ZSTD_compress2` one-shot as well.

The reference compresses through `compression.zstd` (Python 3.14, the
floor of `xuebuild`), so both encoders run one-shot libzstd. The byte
comparisons still skip when the two link different libzstd versions
(`require_comparable_compression` in `tests/_support.py`).

## Native grids

A model on its own grid (`docs/bundle.md`, "Projected Sources", "Gaussian rows")
adds three pieces of arithmetic on top of what a regular grid does. The operation
order is normative: both encoders land on the same doubles. On the native side
`rust/xue/src/projection.rs` holds the projection and the Gaussian iteration,
`encode/reproject.rs` the published grid, the rotation and the `crs` array's text,
and `encode/grid.rs` the window and the rows.

**Reading the grid.** `round3` of the geotransform's origin and steps, then half a
step in: `x0 = round3(gt0) + dx / 2`, `y0 = round3(gt3) + dy / 2`, `dy < 0`. A file
on a projection is only accepted for a source with `grid_relative_winds`, and that
source only accepts such a file. Its dimensions are `y` / `x` by the same flag
(`discover.store_dimensions`).

**Winds.** After the extraction (fill, unit conversion, crop) and before any
derivation and quantization, each vector bundle's pair on a `grid_relative_winds`
source is turned, on the plane the published window describes. No libm call runs
per cell. `ρ0` is the projection's `origin_radius`, computed once:

```text
x     = x0 + column × dx
apex  = ρ0 − (y0 + row × dy)
ρ     = copysign(1, n) × sqrt(apex × apex + x × x)
sin α = x / ρ
cos α = apex / ρ
u_e   = cos α × u + sin α × v
v_e   = −sin α × u + cos α × v
```

The sign is the cone's, as in the inverse projection; it changes nothing on a
northern cone. Decimation works on the codes of the turned planes, so a tier keeps
sample sites and rotation. A derived vector bundle on such a source is refused
(`binconvert._grid_relative_vectors`, `convert::grid_relative_vectors`), and so is
clear-air turbulence on any projected grid.

**A box on a projected grid.** `crop_grid` walks each edge of `(west, south, east,
north)` in 64 points, ends included, with latitudes clamped to ±89.9:
`longitude = west + (east − west) × i / 63.0`, `latitude = south + (north − south)
× i / 63.0`, each edge's fixed side as given. A point goes through
`LambertConformal.forward_wrapped`, then `column = (x − x0) / dx`,
`row = (y − y0) / dy`. The window is `floor(min + 1e-9)` to `ceil(max − 1e-9)` on
each axis, clamped to the grid, the rule a regular crop has. Empty is an error, and
so is a box whose east is west of its west. The window's `x0` is
`x0 + column_start × dx` and its `y0` likewise, unrounded. A tier doubles `dx` and
`dy`, keeps `x0` and `y0`, and takes `(n + 1) // 2` on each axis.

**Gaussian rows.** A source with `gaussian_n` writes the `gaussian` block on its
primary grid, not on a grid family of its own: `firstRow = floor((90 − first
latitude) × (2n + 0.5) / 180 − 0.25)`, the inverse of the iteration's first guess,
rounded, `rowStride` 1. A file whose first latitude is more than a quarter of a row
from that row, whose rows run off the grid, or whose step is more than 1 % from
`180 / 2n` is refused. A crop adds its `row_start` to `firstRow`; a tier doubles
`rowStride`. The regular fields are computed as ever. The column roll moves columns
only. The store's `latitude` coordinate is the iteration of `docs/zarr-profile.md`,
"Coordinates", one row at a time.

## Grid families

One source publishes its inputs on two grids: CFSv2 writes the surface
series on the model's T126 Gaussian grid and the pressure-level and sea
level pressure series on a regular 1° one. GDAL cannot read a GRIB whose
messages disagree on the grid — it exposes the later bands at the first
message's size, warns that the data access may be incomplete and returns a
different checksum than reading that record alone — so the second grid
cannot simply be appended to the frame. It is a **grid family**:
`sources.CompanionFile` with a `production_grid` and a `tile` of its own.

What both encoders do with one:

- **Layout.** A family's records of a frame live in a sibling file of the
  same name under a directory named by the family id —
  `cfs.2026091912/pgb/cfs.2026091912.f006.grib2` beside
  `cfs.2026091912/cfs.2026091912.f006.grib2`
  (`sources.family_frame_path`, the one place the rule is written down).
  Listing a run directory lists files, not directories, so the frame list
  is unchanged; a build narrowed to one family's bundles writes no primary
  file at all, and then the frames are listed from that family's directory
  and named by the primary path they would have had.
- **Inspection and extraction.** A family's variables are inspected and
  extracted from its own file, and a frame's answers are merged into the
  one frame dictionary the rest of the converter reads. A missing family
  file is an error, not a fall-back.
- **Grid.** Each family gets its own `GridInfo`, read from its own file by
  the same rules (the global longitude snap, the regional step snap, the
  column roll). A complete build checks each family's grid against that
  family's `production_grid`, and `--bbox` crops each family separately.
- **Bundles.** A bundle is built on the family every one of its inputs is
  read from — the vapour flux at 850 hPa reads the specific humidity and
  the wind pair there, all from the same family — and a bundle whose inputs
  would span two grids is refused outright. Its grid, its tile, its
  resolution ladder, its poster and its metadata are that family's.
- **What stays the primary family's.** The build report's run-level `grid`,
  and therefore the STAC Item's bbox and spatial dimensions, which are read
  off the core scalars' poster metadata. The manifest has no run-level
  grid and the frontend opens one grid per session, so nothing in the
  delivery contract changes.

A companion family without a `production_grid` is unchanged in every
respect: GFS-Wave and the ECMWF `wave` stream are still appended to the
frame's GRIB after the primary file's records, on the source's own grid.

## Not covered

Fetching (`xue fetch`), the showcase driver and `build-bin` stay in Python.

## Verified against

Every source, on real runs, with every artifact compared byte for byte:

| Source | What it exercises |
|---|---|
| GFS | the plain path, the two-variable wind bundles, the derived vapour flux and the derived 850 hPa equivalent potential temperature (`exp` / `ln` / `pow` on both sides), the surface diagnostics, and the ocean fields: the wave records' bitmap fill and, on a whole frame, the WAVEWATCH III grid snapped to the exact 0.25° grid |
| ECMWF | de-accumulating `tp`, and the shorter prate axis that follows; the records that arrive under another identity than GFS's (the interval-maximum gust on the 10 m surface and its own analysis-less axis, the cloud cover as a local parameter in a 0–1 fraction, the most-unstable CAPE on surface type 17, the skin temperature as 0/0/17, the ice thickness with a bitmap, the wave period and direction under neighbouring parameter numbers), each matched both by the GRIB2 header index and by GDAL's band metadata; the ensemble products appended by the fetch (template 4.2 spreads as code-table-4.7 code 2 and the sea-level pressure's as 0/3/0, template 4.9 probabilities on 0/1/52 with an unscaled limit), matched by the extra `template-ensemble` rules of the CMA ids and published under the registry's identity; the probabilities' twelve-hourly axis from +24 h (`variable_step_hours`, a `time_<id>` axis thinned from the run's) (`tests/test_ecmwf.py`, on the Kara Sea fixture) |
| ECMWF 0.1° (`ifs`) | the ECMWF row's work on the model's full 0.1° grid (3600 × 1801), with the IFS HRES tile (90 × 95) and two-rung ladder; the split `sfc` / `pl` objects are reassembled by the fetch stage, so the encoder reads one GRIB per frame as for ECMWF (`tests/test_ifs.py`, on a Kara Sea crop) |
| GFS-SFLUX | de-averaging `prate_ave`, the Gaussian grid and its `gaussian` block, the -180 column roll, `dswrf` |
| RRFS | the `mass-density-to-micrograms` rule, and HRRR's projection on a frame from two file families (`tests/test_rrfs.py`) |
| WOOF-NAM | a second Lambert conformal grid, NCEP 218 (tangent at 25°N), and a precipitation total that restarts every twelve hours, differenced within its window into the rate (`tests/test_woofnam.py`) |
| HRRR | a projected source: the Lambert conformal grid read out of GDAL's WKT and published as it is, schemaVersion 4, the `y` / `x` coordinates and the `crs` array, the winds turned to east and north (exact IEEE arithmetic per cell; `tests/test_hrrr.py`), and the `MSLMA` / `REFC` aliases |
| GEFS-AEROSOLS | GRIB2 product definition template 4.48: the aerosol type and the size and wavelength intervals parsed out of the template by the header index and out of GDAL's `GRIB_PDS_TEMPLATE_ASSEMBLED_VALUES` by the band matcher, compared whole with the registered `AerosolIdentity` (a dozen `AOTK` records per frame share the parameter and surface), written as the metadata's `aerosol` block; the `log1p` codebooks on fields other than precipitation, NCEP's local PMTF / PMTC numbers in µg/m³ as GDAL reports them (`tests/test_aerosol.py`, on the Saharan fixture) |
| CFSv2 | a seasonal run on two grids: the T126 Gaussian surface grid, its column roll, its `gaussian` block and the true latitudes of its store coordinate, the 1° pressure-level **grid family** beside it (its own frame file, its own `GridInfo`, its own tile and ladder, and the vapour flux derived on it), NCEP's local "entire atmosphere" surface (type 200) accepted under the pgrb2 total cloud cover's identity, the `9999` ice-thickness fill, and an axis that begins at a step rather than at the analysis (`first_hour` 6, so every bundle carries `firstFrameOffset: 6`) with the three flux fields' `typeOfStatisticalProcessing` written into metadata although the records are the instantaneous template (`tests/test_cfs.py`, on the East Asian fixture) |
| ICON-EU | a regional regular grid at a power-of-two step (0.0625°) that the regional snap leaves as it is, DWD's encodings under the existing alternates (the run-total `TOT_PREC` as AIFS's WMO 0/1/52 in kg/m², `VMAX_10M` as ECMWF's interval-maximum gust on the 10 m surface, `CLCT` as AIFS's 0/6/1 in percent on the ground surface, `HSURF` as the orography's 0/3/6 geometric-height alternate in metres), de-accumulation from an analysis total, the gust's analysis-less axis (`tests/test_iconeu.py`, on the Alpine fixture) |
| ARPEGE | the ICON-EU encodings on the 0.25° global grid, with the analysis precipitation total the fetch writes as a zero record (the package has none), so the first hour's rate is that hour's total (`tests/test_arpege.py`, on the western Mediterranean fixture) |
| GSM | the GFS identities on a 1.25° global grid with no ladder; the isobaric surfaces scaled by -2 in sign-and-magnitude, which the header index reads as GDAL does; 10 hPa, whose `1000-ISBL` the `isobaric` rule tells from 1000 hPa by the assembled template; the relative vorticity under the `per-second-to-1e-5` rule; the run-total precipitation as the WMO 0/1/8 accumulated from the analysis (the `accumulation-from-start` rule and `tp`'s 0/1/8 alternate), with the analysis record the fetch writes as a zero record in pure Python (`tests/test_gsm.py`, on the Japan fixture) |
| CMA-GEPS | a global grid without its pole rows (1440 × 720, first centre 89.875°N); ensemble products read as CMA writes them (templates 4.2, 4.6, 4.9, 4.10), matched by `template-ensemble` rules in the header index and the band matcher alike and written as the metadata's `ensemble` block — the centre under the deterministic ids with the block the source names (`ensembles`), the quartiles, spreads and probabilities under ids of their own; the interval precipitation path on GRIB frames (the six-hour median `apcp` total divided by the step) and its pairs (`interval_precipitation_pairs`: the quartile totals into `prateq25` / `prateq75` the same way); bundles that start past the analysis at an hour of their own (`variable_first_hours`: the 24-hour probabilities from +24 h, on a `time_<id>` axis, left out with a warning by a build that ends before it) (`tests/test_cmageps.py`, on the Japan fixture's five frames) |
| WOOF-WRF | the series-file forecast path on a source with no feed: one CF NetCDF per variable from the `wrf-series` tool, an axis from f001 (`first_hour` 1, so every bundle carries `firstFrameOffset: 1`) with the hour's precipitation total on every frame (`interval_precipitation`, nothing analysis-optional), a regional 0.005° grid that one tile covers and no ladder (`variant_factors` empty), a sea level pressure series in pascals turned into hectopascals like a GRIB record, the `wind80m` pair read as two series, the `cloud3d` volume bundle (24 `clw<m>` levels from 250 m to 12 km MSL, cloud water mixing ratio 0/1/22 on surface 102 at the level in metres, g/kg on the linear 0.01 g/kg codebook, a level under the model terrain filled as 0 g/kg), and `fetched()` false — `require_complete` is refused and the source is built from a dataset directory by a showcase case alone (`tests/test_woof.py`, on the Fuji fixture) |
| EFAS-v5, EFAS-v5-WB | the series-file forecast path again, with no feed: one CF NetCDF per variable from the `efas-series` tool, an axis of six-hour means from f006 to f120 (`first_hour` 6, `firstFrameOffset: 6`) with `dis06` declared a mean (`typeOfStatisticalProcessing` 0), the file's declared `_FillValue` of -9999 and the registry's `fill_values` both folded to the bottom of the range (zero discharge, zero area, return-period class 0 "not evaluated"), `log1p` codebooks on the discharge and the upstream area, a class codebook on `disrp`, the `xue` producer version read off the `disrp` and `upstream` series, the 1/60° European grid with no ladder, and `fetched()` false (`tests/test_efas.py`, on the Valencia fixtures) |
| ERA5 | the series-file forecast path with no feed, for a reanalysis: one CF NetCDF per variable from the `era5-series` tool, the window's first hour as the run (any hour, `cycle_hours` 1), an hourly axis from f000 to at most f1440 with every frame an analysis, the temperatures already in degrees Celsius, `gust` declared a maximum over the hour (`typeOfStatisticalProcessing` 2), the 0.25° grid cropped to the case with no ladder, and `fetched()` false (`tests/test_era5.py`) |
| CAMS | the same path for an aerosol analysis: one CF NetCDF per variable from the `cams-series` tool, the window's first hour as the run (any 3 h mark, `cycle_hours` 3), a three-hourly axis from f000 to at most f1440, PM2.5 already in µg/m³, the 0.4° grid cropped to the case with no ladder, and `fetched()` false (`tests/test_cams.py`) |
| GFS, cropped | `--bbox` with `--bundles`, and `manifest.json` |
| CMA-RADAR | the NetCDF observation path: unscaling, the fill value, a `unitSeconds: 360` axis listing its offsets around archive gaps, `--hours`; since 0.17 a fetched window like JMA's, read out of its archive with the window's first hour as the run (`tests/test_cma.py`); the id is `cma` since then, `radar` being the local-file shape the wheels before 0.17 know |
| JMA-HRPNS | a fetched observation that arrives as a NetCDF series (`series_file`), the way the CMA file does, with a cadence: the five-minute times snapped to their slots and the window's first hour taken as the run (`unitSeconds: 300`, `firstFrameOffset: 1`, offsets listed around a gap), a byte-packed rate unscaled through `scale_factor` 0.5 with the 255 fill folded to the codebook bottom, and a run directory holding exactly one series (`tests/test_jma.py`) |
| NOAA-MRMS | a fetched observation: one GRIB per two-minute frame, each its own reference time, re-keyed onto the window's axis (`unitSeconds: 120`, the observation times snapped to the mark, the first hour as the run); the MRMS-local identities (discipline 209) under `cref` and `prate` through the registry's alternates and `rqi` (209/8/0) under its own, a rate already in mm/h, the `-999` / `-99` / `-3` / `-1` sentinels folded to the codebook bottom (for `rqi` a tenth below an index of 0); a regional grid described on its round step; and the 2 x 2 block-maximum thinning onto 0.02° (`tests/test_mrms.py`) |
| NOAA-MRMS3D | the same bucket's 3D mosaic: the 33 constant-altitude levels of `MergedReflectivityQC` (209/9/0 on surface type 102, 0.5–19 km) read from one GRIB per ten-minute frame, every level matched on its altitude rather than on the element the levels share (by the assembled template 4.0, or GDAL's `<metres>-GPML` short name), published as the one `refl3d` volume bundle in level order (`unitSeconds: 600`), each level RAW with the composite's codebook, and thinned 5 x 5 by block maximum onto 0.05° (`tests/test_mrms3d.py`) |
| SWPC-AURORA | a fetched observation that arrives as a NetCDF series (`series_file`) like JMA's but grown from a frame cache, since the live feed carries only the newest grid: `xuebuild/aurora.py` parses the OVATION JSON, snaps its valid time to the five-minute mark and writes one small NetCDF per slot; the fetch assembles the window's cached frames, the window's first hour being the run (`unitSeconds: 300`); a linear 0–100 % codebook on a 1° global grid, and a window that is a sequence of successive forecasts, not one run's lead times (`tests/test_aurora.py`) |

One condition the reference never met: GDAL's netCDF driver is not
thread-safe, and reading one file from several threads fails with `netCDF
chunk fetch failed: NetCDF: HDF error`. Every extraction was its own
`gdal_translate` process in Python. `encode::gdalio::netcdf_guard`
serializes those reads; GRIB stays parallel.

---

Part of the Xue specification, licensed under [CC BY 4.0](../LICENSE-CC-BY).
