Skip to main content

xue/encode/
zarrstore.rs

1//! Xue bundles as Zarr v3 stores, written straight from their codes.
2//!
3//! Two layouts, both normative in `docs/zarr-profile.md`, and both mirroring
4//! `xuebuild/zarrstore.py`, the reference, byte for byte. A **shared store**
5//! (profile 2, `bundles[.<tier>].zarr`) holds every bundle of one resolution
6//! tier: [`write_bundle_arrays`] writes one bundle's arrays and the
7//! coordinates its dimension names name into it, [`write_part`] the partial
8//! group document over the bundles one build wrote. The store's `zarr.json`
9//! itself is never written here: the reference's `finalize_store` merges the
10//! parts into it, so the group document has one implementation. A
11//! **one-bundle store** (profile 1, [`write_store`]) is what a series store
12//! is.
13//!
14//! Documents are serialized the way Python's `json.dumps(..., indent=2,
15//! ensure_ascii=False)` does, plus a trailing newline; inner chunks are
16//! padded and compressed by the same one-shot zstd call, with the same shard
17//! index and CRC-32C. A bundle's arrays are a function of its metadata, its
18//! codes, its tile, each variable's predictor and its dimension names, so
19//! nothing here reads a container. Every chunk is decompressed again right
20//! after it is compressed and compared with what went in, and every document
21//! written is parsed back by the decoder's own store validators
22//! (`crate::zarr`), the store's counterpart of the container's full
23//! read-back.
24
25use std::fs;
26use std::io::{BufWriter, Write};
27use std::path::{Path, PathBuf};
28use std::sync::atomic::{AtomicU64, Ordering};
29
30use rayon::prelude::*;
31use serde_json::{json, Map, Value};
32
33use crate::encode::binformat::crc32_plane;
34use crate::encode::errors::{EncodeError, Result};
35use crate::encode::pyjson::dumps_indented;
36use crate::encode::reproject::cf_attributes;
37use crate::format::TileGeometry;
38use crate::zarr;
39
40/// Frames per time chunk of a map store: the bundle's own group length, on a
41/// regular grid.
42pub const TIME_CHUNK: usize = 6;
43/// The spatial block of a series store, `(width, height)`.
44pub const SERIES_BLOCK: (usize, usize) = (8, 8);
45/// The inner chunks' zstd level, which the array documents declare.
46pub const ZSTD_LEVEL: i32 = 15;
47const PROFILE_VERSION: u64 = 1;
48/// The `xue_profile` of a shared store (`bundles[.<tier>].zarr`).
49pub const SHARED_PROFILE_VERSION: u64 = 2;
50/// The reserved stem of a shared store; no bundle may be named it.
51pub const SHARED_STORE_STEM: &str = "bundles";
52/// File name prefix of a partial group document inside a shared store
53/// (`zarr.part.<first bundle id>.json`).
54pub const PART_PREFIX: &str = "zarr.part.";
55const DELTA_CODEC: &str = "xue.delta";
56/// The primary dimension names, which are also the store's primary
57/// coordinate arrays.
58pub const DIMENSIONS: [&str; 3] = ["time", "latitude", "longitude"];
59/// A projected store's primary dimensions.
60const PROJECTED_DIMENSIONS: [&str; 3] = ["time", "y", "x"];
61/// The scalar array a projected bundle's variables name as their `grid_mapping`.
62const CRS_ARRAY: &str = "crs";
63/// The coordinates a group document lists first, in this order.
64const PRIMARY_COORDINATES: [&str; 6] = ["time", "latitude", "longitude", "y", "x", CRS_ARRAY];
65
66/// One variable's codes: its planes in axis order, each `width * height`.
67pub struct StoreVariable<'a> {
68    pub id: String,
69    /// Stored as residuals against the previous frame in the container
70    /// (`previous`), or not (`raw`).
71    pub previous: bool,
72    pub planes: Vec<&'a [u8]>,
73}
74
75/// A bundle's codes as the writer reads them.
76pub struct StoreCodes<'a> {
77    /// The bundle's metadata document, exactly as a container embeds it.
78    pub metadata: &'a Value,
79    /// In the metadata's variable order, which is the store's array order.
80    pub variables: Vec<StoreVariable<'a>>,
81    /// `(width, height)` of the tile the bundle is cut with.
82    pub tile: (usize, usize),
83}
84
85/// A code array's `data_type`: `uint16` exactly when the codebook's nodata
86/// code does not fit a byte, which only a series codebook's does
87/// (`docs/zarr-profile.md`, "Series store"); `uint8` otherwise. The
88/// reference's `code_data_type`.
89pub fn code_data_type(quantization: &Value) -> &'static str {
90    if quantization["nodataCode"]
91        .as_u64()
92        .is_some_and(|code| code > 0xFF)
93    {
94        "uint16"
95    } else {
96        "uint8"
97    }
98}
99
100/// A series store's metadata: the bundle's, with each variable named in
101/// `quantizations` holding that block as its `quantization`, the codes the
102/// store holds for it. The key keeps its place, so everything else, key
103/// order included, is the bundle's, and a series store with no widened
104/// variable carries the bundle's metadata exactly. The reference's
105/// `series_metadata`.
106pub fn series_metadata(metadata: &Value, quantizations: &[(&str, Map<String, Value>)]) -> Value {
107    let mut copied = metadata.clone();
108    if let Some(variables) = copied.get_mut("variables").and_then(Value::as_array_mut) {
109        for variable in variables {
110            let id = variable["id"].as_str().unwrap_or_default().to_owned();
111            if let Some((_, block)) = quantizations.iter().find(|(name, _)| *name == id) {
112                if let Some(object) = variable.as_object_mut() {
113                    object.insert("quantization".into(), Value::Object(block.clone()));
114                }
115            }
116        }
117    }
118    copied
119}
120
121/// A widened variable's sixteen-bit codes, which a series store reads a band
122/// of rows at a time rather than holding the whole axis: planes in memory
123/// ([`WidePlanes`]), or a build's spool on disk.
124pub trait WideCodes: Sync {
125    /// The planes on the axis.
126    fn frame_count(&self) -> usize;
127    /// The codes one plane holds, `width * height` on its grid.
128    fn plane_length(&self, frame: usize) -> usize;
129    /// `out.len()` codes of plane `frame` from cell `start` on, row-major.
130    fn read_cells(&self, frame: usize, start: usize, out: &mut [u16]) -> Result<()>;
131}
132
133/// Sixteen-bit planes held in memory, in axis order.
134pub struct WidePlanes<'a>(pub Vec<&'a [u16]>);
135
136impl WideCodes for WidePlanes<'_> {
137    fn frame_count(&self) -> usize {
138        self.0.len()
139    }
140
141    fn plane_length(&self, frame: usize) -> usize {
142        self.0[frame].len()
143    }
144
145    fn read_cells(&self, frame: usize, start: usize, out: &mut [u16]) -> Result<()> {
146        let plane = self.0[frame];
147        let cells = plane
148            .get(start..start + out.len())
149            .ok_or_else(|| EncodeError::bundle("a band of rows runs past its plane"))?;
150        out.copy_from_slice(cells);
151        Ok(())
152    }
153}
154
155/// One widened variable of a series store: its codes, by the id its
156/// [`StoreVariable`] (whose byte planes are then empty) names.
157pub struct WideVariable<'a> {
158    pub id: String,
159    pub codes: &'a dyn WideCodes,
160}
161
162/// What one store write produced: the manifest descriptor's three values
163/// plus the report fields `ExportReport.to_dict` carries.
164#[derive(Debug, Clone)]
165pub struct StoreReport {
166    pub path: PathBuf,
167    pub byte_length: u64,
168    pub crc32: String,
169    pub delta: bool,
170    pub arrays: Vec<(String, u64)>,
171    pub chunk_count: u64,
172}
173
174impl StoreReport {
175    /// The report block, keyed as the reference's `ExportReport.to_dict`.
176    pub fn to_value(&self) -> Value {
177        let mut arrays = Map::new();
178        for (name, written) in &self.arrays {
179            arrays.insert(name.clone(), json!(written));
180        }
181        json!({
182            "path": self.path.display().to_string(),
183            "byteLength": self.byte_length,
184            "crc32": self.crc32,
185            "delta": self.delta,
186            "indexLocation": "end",
187            "arrays": Value::Object(arrays),
188            "chunkCount": self.chunk_count,
189            "comparableChunks": 0,
190            "identicalChunks": 0,
191        })
192    }
193}
194
195/// How one array is cut (`ArrayGeometry` in the reference): inner chunk
196/// `[time_chunk, tile_height, tile_width]`, one shard of the whole axis
197/// rounded up to whole time chunks over the whole grid of whole tiles.
198#[derive(Debug, Clone, Copy)]
199struct Geometry {
200    frame_count: usize,
201    height: usize,
202    width: usize,
203    time_chunk: usize,
204    tile_height: usize,
205    tile_width: usize,
206}
207
208impl Geometry {
209    /// The grid's tiling, the container's arithmetic over the same cells.
210    fn tiles(&self) -> TileGeometry {
211        TileGeometry {
212            width: self.width as u32,
213            height: self.height as u32,
214            tile_width: self.tile_width as u32,
215            tile_height: self.tile_height as u32,
216        }
217    }
218    fn tile_rows(&self) -> usize {
219        self.tiles().rows() as usize
220    }
221    fn tile_columns(&self) -> usize {
222        self.tiles().columns() as usize
223    }
224    fn tile_count(&self) -> usize {
225        self.tiles().count() as usize
226    }
227    fn time_chunks(&self) -> usize {
228        self.frame_count.div_ceil(self.time_chunk)
229    }
230    fn shard_frames(&self) -> usize {
231        self.time_chunks() * self.time_chunk
232    }
233    fn chunks_per_shard(&self) -> usize {
234        self.time_chunks() * self.tile_count()
235    }
236    fn inner_length(&self) -> usize {
237        self.time_chunk * self.tile_height * self.tile_width
238    }
239    fn tile_origin(&self, tile: usize) -> (usize, usize) {
240        let (row, column) = self.tiles().origin(tile as u32);
241        (row as usize, column as usize)
242    }
243    fn tile_shape(&self, tile: usize) -> (usize, usize) {
244        let (height, width) = self.tiles().shape(tile as u32);
245        (height as usize, width as usize)
246    }
247}
248
249pub(super) fn write_file(path: &Path, data: &[u8]) -> Result<u64> {
250    if let Some(parent) = path.parent() {
251        fs::create_dir_all(parent).map_err(|error| io_error(parent, &error))?;
252    }
253    fs::write(path, data).map_err(|error| io_error(path, &error))?;
254    Ok(data.len() as u64)
255}
256
257fn io_error(path: &Path, error: &std::io::Error) -> EncodeError {
258    EncodeError::conversion(format!("cannot write {}: {error}", path.display()))
259}
260
261// -- documents -----------------------------------------------------------------
262
263/// One variable array's document. `bundle` is set in a shared store only,
264/// where it leads the `xue` block so an array opened alone knows which
265/// bundle's metadata describes it. On a `projected` grid the array names the
266/// `crs` array, last among its attributes.
267fn array_metadata(
268    geometry: &Geometry,
269    variable: &Value,
270    predictor: &str,
271    delta: bool,
272    bundle: Option<&str>,
273    dimensions: &[String; 3],
274    projected: bool,
275) -> Value {
276    let quantization = &variable["quantization"];
277    let mut xue = Map::new();
278    if let Some(bundle) = bundle {
279        xue.insert("bundle".into(), json!(bundle));
280    }
281    xue.insert("variable".into(), variable.clone());
282    xue.insert("predictor".into(), json!(predictor));
283    let mut attributes = Map::new();
284    attributes.insert("xue".into(), Value::Object(xue));
285    if quantization.get("type").and_then(Value::as_str) == Some("linear") {
286        attributes.insert("scale_factor".into(), quantization["scale"].clone());
287        attributes.insert("add_offset".into(), quantization["offset"].clone());
288    }
289    attributes.insert("_FillValue".into(), quantization["nodataCode"].clone());
290    if projected {
291        attributes.insert("grid_mapping".into(), json!(CRS_ARRAY));
292    }
293    let data_type = code_data_type(quantization);
294    let mut inner = Vec::new();
295    if delta {
296        inner.push(json!({"name": DELTA_CODEC, "configuration": {"axis": 0}}));
297    }
298    // A byte has no order, so a uint8 array keeps the bare `bytes` every
299    // store has been written with; a uint16 one spells its order out.
300    if data_type == "uint8" {
301        inner.push(json!({"name": "bytes"}));
302    } else {
303        inner.push(json!({"name": "bytes", "configuration": {"endian": "little"}}));
304    }
305    inner.push(json!({"name": "zstd", "configuration": {"level": ZSTD_LEVEL, "checksum": true}}));
306    json!({
307        "zarr_format": 3,
308        "node_type": "array",
309        "shape": [geometry.frame_count, geometry.height, geometry.width],
310        "data_type": data_type,
311        "chunk_grid": {"name": "regular", "configuration": {"chunk_shape": [
312            geometry.shard_frames(),
313            geometry.tile_rows() * geometry.tile_height,
314            geometry.tile_columns() * geometry.tile_width,
315        ]}},
316        "chunk_key_encoding": {"name": "default"},
317        "fill_value": quantization["nodataCode"].clone(),
318        "codecs": [{
319            "name": "sharding_indexed",
320            "configuration": {
321                "chunk_shape": [geometry.time_chunk, geometry.tile_height, geometry.tile_width],
322                "codecs": inner,
323                "index_codecs": [
324                    {"name": "bytes", "configuration": {"endian": "little"}},
325                    {"name": "crc32c"},
326                ],
327                "index_location": "end",
328            },
329        }],
330        "attributes": Value::Object(attributes),
331        "dimension_names": dimensions,
332    })
333}
334
335pub(super) fn coordinate_metadata(
336    length: usize,
337    data_type: &str,
338    fill_value: Value,
339    attributes: Value,
340    name: &str,
341) -> Value {
342    json!({
343        "zarr_format": 3,
344        "node_type": "array",
345        "shape": [length],
346        "data_type": data_type,
347        "chunk_grid": {"name": "regular", "configuration": {"chunk_shape": [length]}},
348        "chunk_key_encoding": {"name": "default"},
349        "fill_value": fill_value,
350        "codecs": [{"name": "bytes", "configuration": {"endian": "little"}}],
351        "attributes": attributes,
352        "dimension_names": [name],
353    })
354}
355
356/// The `crs` array's document (`docs/zarr-profile.md`, "Coordinates"): a scalar
357/// with no chunk, there for the grid mapping in its attributes.
358fn crs_metadata(attributes: Value) -> Value {
359    json!({
360        "zarr_format": 3,
361        "node_type": "array",
362        "shape": [],
363        "data_type": "int32",
364        "chunk_grid": {"name": "regular", "configuration": {"chunk_shape": []}},
365        "chunk_key_encoding": {"name": "default"},
366        "fill_value": 0,
367        "codecs": [{"name": "bytes", "configuration": {"endian": "little"}}],
368        "attributes": attributes,
369        "dimension_names": [],
370    })
371}
372
373fn number(value: &Value, what: &str) -> Result<f64> {
374    value
375        .as_f64()
376        .ok_or_else(|| EncodeError::conversion(format!("metadata grid {what} is not a number")))
377}
378
379/// Write by rename: in a shared store several bundles write the same
380/// coordinate array concurrently, always the same bytes, and a rename never
381/// leaves a reader (or the last writer) a torn file.
382pub(super) fn write_file_atomic(path: &Path, data: &[u8]) -> Result<u64> {
383    static SEQUENCE: AtomicU64 = AtomicU64::new(0);
384    let parent = path.parent().unwrap_or(Path::new("."));
385    fs::create_dir_all(parent).map_err(|error| io_error(parent, &error))?;
386    let name = path
387        .file_name()
388        .map(|name| name.to_string_lossy().into_owned())
389        .unwrap_or_default();
390    let temporary = parent.join(format!(
391        ".{name}.{}.{}",
392        std::process::id(),
393        SEQUENCE.fetch_add(1, Ordering::Relaxed)
394    ));
395    if let Err(error) = fs::write(&temporary, data) {
396        let _ = fs::remove_file(&temporary);
397        return Err(io_error(&temporary, &error));
398    }
399    if let Err(error) = fs::rename(&temporary, path) {
400        let _ = fs::remove_file(&temporary);
401        return Err(io_error(path, &error));
402    }
403    Ok(data.len() as u64)
404}
405
406/// The three one-dimensional coordinate arrays, each one chunk: for xarray
407/// and its kind, never read by the viewer. `names` are the bundle's
408/// dimension names (`time` or `time_<bundle>`, and so on): a coordinate array
409/// is named by the dimension it labels, and its encoding does not depend on
410/// the name. A projected grid's two are in metres and the `crs` array follows
411/// them; a Gaussian grid's latitudes are its true rows, not the regular fields'
412/// even ones. `atomic` writes by rename, for a shared store.
413pub(super) fn write_coordinates(
414    metadata: &Value,
415    (height, width): (usize, usize),
416    store: &Path,
417    names: &[String; 3],
418    atomic: bool,
419    documents: &mut Vec<(String, Value)>,
420) -> Result<Vec<(String, u64)>> {
421    let text = serde_json::to_string(metadata).expect("serializable metadata");
422    let parsed = zarr::parse_bundle_metadata(&text)
423        .map_err(|error| EncodeError::bundle(format!("store metadata is invalid: {}", error.0)))?;
424    let grid = &metadata["grid"];
425    let run_time = metadata["runTime"].as_str().unwrap_or_default();
426    let unit_seconds = i64::from(parsed.unit_seconds);
427    let mut time = Vec::with_capacity(parsed.offsets.len() * 4);
428    for &offset in &parsed.offsets {
429        let seconds = i32::try_from(i64::from(offset) * unit_seconds).map_err(|_| {
430            EncodeError::conversion("a frame offset overflows the int32 time coordinate")
431        })?;
432        time.extend_from_slice(&seconds.to_le_bytes());
433    }
434    let axis = |first: f64, step: f64, count: usize| -> Vec<u8> {
435        let mut bytes = Vec::with_capacity(count * 8);
436        for index in 0..count {
437            // Two roundings, as NumPy's `first + arange(n) * step` makes them.
438            let value = first + (index as f64) * step;
439            bytes.extend_from_slice(&value.to_le_bytes());
440        }
441        bytes
442    };
443    let layout = zarr::Grid::from_metadata(metadata)
444        .map_err(|error| EncodeError::bundle(format!("store metadata is invalid: {}", error.0)))?;
445    let mut crs = None;
446    let (rows, row_attributes, columns, column_attributes) = match layout {
447        zarr::Grid::Lambert(grid) => {
448            crs = Some(grid.projection);
449            (
450                axis(grid.y0, grid.dy, height),
451                json!({"units": "m", "standard_name": "projection_y_coordinate"}),
452                axis(grid.x0, grid.dx, width),
453                json!({"units": "m", "standard_name": "projection_x_coordinate"}),
454            )
455        }
456        zarr::Grid::Regular(regular) => {
457            let rows = match regular.gaussian {
458                Some(gaussian) => {
459                    let mut bytes = Vec::with_capacity(height * 8);
460                    for row in 0..height {
461                        let latitude = gaussian.latitude(row as u32).ok_or_else(|| {
462                            EncodeError::bundle("a row runs past the Gaussian grid")
463                        })?;
464                        bytes.extend_from_slice(&latitude.to_le_bytes());
465                    }
466                    bytes
467                }
468                None => axis(
469                    number(&grid["firstLatitude"], "firstLatitude")?,
470                    number(&grid["latitudeStep"], "latitudeStep")?,
471                    height,
472                ),
473            };
474            (
475                rows,
476                json!({"units": "degrees_north", "standard_name": "latitude"}),
477                axis(
478                    number(&grid["firstLongitude"], "firstLongitude")?,
479                    number(&grid["longitudeStep"], "longitudeStep")?,
480                    width,
481                ),
482                json!({"units": "degrees_east", "standard_name": "longitude"}),
483            )
484        }
485    };
486    let coordinates = [
487        (
488            names[0].as_str(),
489            time,
490            parsed.offsets.len(),
491            "int32",
492            json!(0),
493            json!({
494                "units": format!("seconds since {run_time}"),
495                "calendar": "proleptic_gregorian",
496                "standard_name": "time",
497            }),
498        ),
499        (
500            names[1].as_str(),
501            rows,
502            height,
503            "float64",
504            json!("NaN"),
505            row_attributes,
506        ),
507        (
508            names[2].as_str(),
509            columns,
510            width,
511            "float64",
512            json!("NaN"),
513            column_attributes,
514        ),
515    ];
516    let write = if atomic {
517        write_file_atomic
518    } else {
519        write_file
520    };
521    let mut sizes = Vec::new();
522    for (name, values, length, data_type, fill_value, attributes) in coordinates {
523        let document = coordinate_metadata(length, data_type, fill_value, attributes, name);
524        let directory = store.join(name);
525        let written = write(
526            &directory.join("zarr.json"),
527            &dumps_indented(&document).into_bytes(),
528        )? + write(&directory.join("c").join("0"), &values)?;
529        documents.push((name.to_owned(), document));
530        sizes.push((name.to_owned(), written));
531    }
532    if let Some(projection) = crs {
533        let document = crs_metadata(cf_attributes(&projection));
534        let written = write(
535            &store.join(CRS_ARRAY).join("zarr.json"),
536            &dumps_indented(&document).into_bytes(),
537        )?;
538        documents.push((CRS_ARRAY.to_owned(), document));
539        sizes.push((CRS_ARRAY.to_owned(), written));
540    }
541    Ok(sizes)
542}
543
544// -- chunks --------------------------------------------------------------------
545
546/// One inner chunk at its full shape: the clipped tile's codes for the frames
547/// the time chunk holds, `fill` beyond the grid and beyond the axis, then the
548/// `xue.delta` encode over the padded block when asked (`_pad_block` and
549/// `_delta_encode` in the reference).
550fn inner_chunk(
551    planes: &[&[u8]],
552    geometry: &Geometry,
553    time_chunk: usize,
554    tile: usize,
555    fill: u8,
556    delta: bool,
557) -> Vec<u8> {
558    let mut block = vec![fill; geometry.inner_length()];
559    let (row, column) = geometry.tile_origin(tile);
560    let (height, width) = geometry.tile_shape(tile);
561    let first = time_chunk * geometry.time_chunk;
562    let last = (first + geometry.time_chunk).min(geometry.frame_count);
563    let frame_cells = geometry.tile_height * geometry.tile_width;
564    for (slot, frame) in (first..last).enumerate() {
565        let plane = planes[frame];
566        for line in 0..height {
567            let source = (row + line) * geometry.width + column;
568            let target = slot * frame_cells + line * geometry.tile_width;
569            block[target..target + width].copy_from_slice(&plane[source..source + width]);
570        }
571    }
572    if delta {
573        for index in (frame_cells..block.len()).rev() {
574            block[index] = block[index].wrapping_sub(block[index - frame_cells]);
575        }
576    }
577    block
578}
579
580/// One block row of a series geometry over every frame of the axis:
581/// `[frames, rows, width]`, the rows the block row covers and nothing more.
582fn wide_band(codes: &dyn WideCodes, geometry: &Geometry, tile_row: usize) -> Result<Vec<u16>> {
583    let first = tile_row * geometry.tile_height;
584    let rows = geometry.tile_height.min(geometry.height - first);
585    let cells = rows * geometry.width;
586    let mut band = vec![0u16; geometry.frame_count * cells];
587    for (frame, out) in band.chunks_exact_mut(cells).enumerate() {
588        codes.read_cells(frame, first * geometry.width, out)?;
589    }
590    Ok(band)
591}
592
593/// [`inner_chunk`] on sixteen-bit codes, from a block row's band
594/// ([`wide_band`]): the clipped tile's codes, `fill` beyond the grid, then
595/// the `xue.delta` encode over the padded block modulo 65536.
596fn wide_inner_chunk(
597    band: &[u16],
598    geometry: &Geometry,
599    tile_row: usize,
600    tile: usize,
601    fill: u16,
602    delta: bool,
603) -> Vec<u16> {
604    let mut block = vec![fill; geometry.inner_length()];
605    let (row, column) = geometry.tile_origin(tile);
606    debug_assert_eq!(row, tile_row * geometry.tile_height);
607    let (height, width) = geometry.tile_shape(tile);
608    let band_rows = geometry
609        .tile_height
610        .min(geometry.height - tile_row * geometry.tile_height);
611    let frame_cells = geometry.tile_height * geometry.tile_width;
612    for frame in 0..geometry.frame_count.min(geometry.time_chunk) {
613        for line in 0..height {
614            let source = (frame * band_rows + line) * geometry.width + column;
615            let target = frame * frame_cells + line * geometry.tile_width;
616            block[target..target + width].copy_from_slice(&band[source..source + width]);
617        }
618    }
619    if delta {
620        for index in (frame_cells..block.len()).rev() {
621            block[index] = block[index].wrapping_sub(block[index - frame_cells]);
622        }
623    }
624    block
625}
626
627/// The `bytes` codec's order for sixteen-bit codes: little-endian, whatever
628/// the machine's.
629fn wide_bytes(block: &[u16]) -> Vec<u8> {
630    let mut bytes = Vec::with_capacity(block.len() * 2);
631    for code in block {
632        bytes.extend_from_slice(&code.to_le_bytes());
633    }
634    bytes
635}
636
637/// Compress one inner chunk and prove the frame decodes back to it.
638pub(super) fn compress_chunk(block: &[u8], level: i32) -> Result<Vec<u8>> {
639    let payload = crate::encode::convert::zstd_compress(block, level)?;
640    let round_trip = zstd::bulk::decompress(&payload, block.len()).map_err(|error| {
641        EncodeError::bundle(format!("store chunk does not decompress: {error}"))
642    })?;
643    if round_trip != block {
644        return Err(EncodeError::bundle(
645            "store chunk does not decompress to its codes",
646        ));
647    }
648    Ok(payload)
649}
650
651/// One variable's array: its document and its one shard, the inner chunks in
652/// row-major order (time chunk, then tile) followed by the index. `bundle`
653/// and `dimensions` are a shared store's ([`write_bundle_arrays`]).
654///
655/// A variable whose codebook is sixteen-bit ([`code_data_type`]) is written
656/// from `wide`, which only a series geometry takes: map frames are bytes on
657/// every reader's frame path.
658#[allow(clippy::too_many_arguments)]
659fn write_array(
660    variable: &StoreVariable<'_>,
661    wide: Option<&dyn WideCodes>,
662    document_variable: &Value,
663    geometry: &Geometry,
664    directory: &Path,
665    delta: bool,
666    series: bool,
667    pool: &rayon::ThreadPool,
668    bundle: Option<&str>,
669    dimensions: &[String; 3],
670    projected: bool,
671) -> Result<(u64, u64, Value)> {
672    let predictor = if variable.previous { "previous" } else { "raw" };
673    let use_delta = delta && variable.previous;
674    let nodata = document_variable["quantization"]["nodataCode"]
675        .as_u64()
676        .and_then(|code| u16::try_from(code).ok())
677        .ok_or_else(|| {
678            EncodeError::conversion(format!("{}: nodataCode is not a code", variable.id))
679        })?;
680    let widened = code_data_type(&document_variable["quantization"]) == "uint16";
681    let frame_count = if widened {
682        if !series {
683            return Err(EncodeError::bundle(format!(
684                "{}: a uint16 array is a series array",
685                variable.id
686            )));
687        }
688        let Some(wide) = wide else {
689            return Err(EncodeError::bundle(format!(
690                "{}: its codebook's codes are sixteen-bit, and no sixteen-bit codes were given",
691                variable.id
692            )));
693        };
694        if !variable.planes.is_empty() {
695            return Err(EncodeError::bundle(format!(
696                "{}: holds byte codes besides its sixteen-bit ones",
697                variable.id
698            )));
699        }
700        if let Some(frame) = (0..wide.frame_count())
701            .find(|&frame| wide.plane_length(frame) != geometry.width * geometry.height)
702        {
703            return Err(EncodeError::conversion(format!(
704                "{}: a plane of {} codes on a {}x{} grid",
705                variable.id,
706                wide.plane_length(frame),
707                geometry.width,
708                geometry.height
709            )));
710        }
711        wide.frame_count()
712    } else {
713        if wide.is_some() {
714            // Codes of the other width are another codebook's: refused
715            // rather than cast, which would keep the numbers and change
716            // their meaning.
717            return Err(EncodeError::bundle(format!(
718                "{}: holds sixteen-bit codes where its codebook's are uint8",
719                variable.id
720            )));
721        }
722        if let Some(plane) = variable
723            .planes
724            .iter()
725            .find(|plane| plane.len() != geometry.width * geometry.height)
726        {
727            return Err(EncodeError::conversion(format!(
728                "{}: a plane of {} codes on a {}x{} grid",
729                variable.id,
730                plane.len(),
731                geometry.width,
732                geometry.height
733            )));
734        }
735        variable.planes.len()
736    };
737    if frame_count != geometry.frame_count {
738        return Err(EncodeError::conversion(format!(
739            "{}: {} planes for an axis of {} frames",
740            variable.id, frame_count, geometry.frame_count
741        )));
742    }
743    let document = array_metadata(
744        geometry,
745        document_variable,
746        predictor,
747        use_delta,
748        bundle,
749        dimensions,
750        projected,
751    );
752    let text = dumps_indented(&document).into_bytes();
753    zarr::parse_array_metadata(std::str::from_utf8(&text).expect("UTF-8 JSON")).map_err(
754        |error| {
755            EncodeError::bundle(format!(
756                "{}: array document is invalid: {}",
757                variable.id, error.0
758            ))
759        },
760    )?;
761    let mut written = write_file(&directory.join("zarr.json"), &text)?;
762
763    let shard_path = directory.join("c").join("0").join("0").join("0");
764    fs::create_dir_all(shard_path.parent().expect("shard directory"))
765        .map_err(|error| io_error(&shard_path, &error))?;
766    let file = fs::File::create(&shard_path).map_err(|error| io_error(&shard_path, &error))?;
767    let mut shard = BufWriter::new(file);
768    let mut entries: Vec<u8> = Vec::with_capacity(16 * geometry.chunks_per_shard());
769    let mut cursor = 0u64;
770    let mut count = 0usize;
771    let mut append = |payloads: Vec<Vec<u8>>, shard: &mut BufWriter<fs::File>| -> Result<()> {
772        for payload in payloads {
773            entries.extend_from_slice(&cursor.to_le_bytes());
774            entries.extend_from_slice(&(payload.len() as u64).to_le_bytes());
775            cursor += payload.len() as u64;
776            count += 1;
777            shard
778                .write_all(&payload)
779                .map_err(|error| io_error(&shard_path, &error))?;
780        }
781        Ok(())
782    };
783    let mut chunks = 0u64;
784    match wide {
785        Some(wide) if widened => {
786            if geometry.time_chunks() != 1 {
787                return Err(EncodeError::bundle("a series geometry has one time chunk"));
788            }
789            // Cut a block row at a time, every frame of it read in one band,
790            // so the whole axis of the whole grid is never held at once; the
791            // payloads still arrive in the tile order the index names them in.
792            for tile_row in 0..geometry.tile_rows() {
793                let band = wide_band(wide, geometry, tile_row)?;
794                let tiles =
795                    tile_row * geometry.tile_columns()..(tile_row + 1) * geometry.tile_columns();
796                let payloads = pool.install(|| {
797                    tiles
798                        .into_par_iter()
799                        .map(|tile| {
800                            let block = wide_inner_chunk(
801                                &band, geometry, tile_row, tile, nodata, use_delta,
802                            );
803                            compress_chunk(&wide_bytes(&block), ZSTD_LEVEL)
804                        })
805                        .collect::<Result<Vec<_>>>()
806                })?;
807                chunks += payloads.len() as u64;
808                append(payloads, &mut shard)?;
809            }
810        }
811        _ => {
812            let fill = nodata as u8;
813            for time_chunk in 0..geometry.time_chunks() {
814                let payloads = pool.install(|| {
815                    (0..geometry.tile_count())
816                        .into_par_iter()
817                        .map(|tile| {
818                            compress_chunk(
819                                &inner_chunk(
820                                    &variable.planes,
821                                    geometry,
822                                    time_chunk,
823                                    tile,
824                                    fill,
825                                    use_delta,
826                                ),
827                                ZSTD_LEVEL,
828                            )
829                        })
830                        .collect::<Result<Vec<_>>>()
831                })?;
832                chunks += payloads.len() as u64;
833                append(payloads, &mut shard)?;
834            }
835        }
836    }
837    // Every inner chunk the shard's shape names is stored; a time chunk past
838    // the axis (none, with the shard cut to the axis) would be fill.
839    let remaining = geometry.chunks_per_shard().saturating_sub(chunks as usize);
840    if remaining > 0 {
841        let fill_chunk = if widened {
842            compress_chunk(
843                &wide_bytes(&vec![nodata; geometry.inner_length()]),
844                ZSTD_LEVEL,
845            )?
846        } else {
847            compress_chunk(&vec![nodata as u8; geometry.inner_length()], ZSTD_LEVEL)?
848        };
849        append(vec![fill_chunk; remaining], &mut shard)?;
850    }
851    if count != geometry.chunks_per_shard() {
852        return Err(EncodeError::bundle(
853            "shard payload count disagrees with the geometry",
854        ));
855    }
856    let checksum = zarr::crc32c(&entries);
857    let mut index = entries;
858    index.extend_from_slice(&checksum.to_le_bytes());
859    zarr::parse_shard_index(&index, geometry.chunks_per_shard()).map_err(|error| {
860        EncodeError::bundle(format!(
861            "{}: shard index is invalid: {}",
862            variable.id, error.0
863        ))
864    })?;
865    shard
866        .write_all(&index)
867        .map_err(|error| io_error(&shard_path, &error))?;
868    shard
869        .flush()
870        .map_err(|error| io_error(&shard_path, &error))?;
871    drop(shard);
872    let shard_length = cursor + index.len() as u64;
873    let on_disk = fs::metadata(&shard_path)
874        .map_err(|error| io_error(&shard_path, &error))?
875        .len();
876    if on_disk != shard_length {
877        return Err(EncodeError::bundle(format!(
878            "{}: shard is {on_disk} bytes, not {shard_length}",
879            variable.id
880        )));
881    }
882    written += shard_length;
883    Ok((written, chunks, document))
884}
885
886fn map_geometry(
887    codes: &StoreCodes<'_>,
888    frame_count: usize,
889    width: usize,
890    height: usize,
891) -> Geometry {
892    Geometry {
893        frame_count,
894        height,
895        width,
896        time_chunk: TIME_CHUNK,
897        tile_height: codes.tile.1.min(height),
898        tile_width: codes.tile.0.min(width),
899    }
900}
901
902fn series_geometry(
903    block: (usize, usize),
904    frame_count: usize,
905    width: usize,
906    height: usize,
907) -> Geometry {
908    Geometry {
909        frame_count,
910        height,
911        width,
912        time_chunk: frame_count,
913        tile_height: block.1,
914        tile_width: block.0,
915    }
916}
917
918/// The compression pool a caller outside the crate hands to [`write_store`].
919pub fn compression_pool(workers: usize) -> Result<rayon::ThreadPool> {
920    rayon::ThreadPoolBuilder::new()
921        .num_threads(workers.max(1))
922        .build()
923        .map_err(|error| EncodeError::conversion(format!("cannot start zstd pool: {error}")))
924}
925
926fn is_projected(metadata: &Value) -> bool {
927    metadata["grid"].get("projection").is_some()
928}
929
930fn primary_dimensions(projected: bool) -> [String; 3] {
931    if projected {
932        PROJECTED_DIMENSIONS
933    } else {
934        DIMENSIONS
935    }
936    .map(str::to_owned)
937}
938
939/// The geometry a bundle's codes are cut with, and the metadata's variable
940/// documents, which must name the codes' variables in order.
941fn store_geometry<'m>(
942    codes: &StoreCodes<'m>,
943    series: Option<(usize, usize)>,
944) -> Result<(Geometry, &'m Vec<Value>)> {
945    let metadata = codes.metadata;
946    let grid = &metadata["grid"];
947    let dimension = |key: &str| -> Result<usize> {
948        grid[key]
949            .as_u64()
950            .filter(|&value| value > 0)
951            .map(|value| value as usize)
952            .ok_or_else(|| EncodeError::conversion(format!("metadata grid {key} is invalid")))
953    };
954    let width = dimension("width")?;
955    let height = dimension("height")?;
956    let frame_count = metadata["time"]["frameCount"]
957        .as_u64()
958        .filter(|&value| value > 0)
959        .map(|value| value as usize)
960        .ok_or_else(|| EncodeError::conversion("metadata frameCount is invalid"))?;
961    let geometry = match series {
962        Some(block) => {
963            if block.0 == 0 || block.1 == 0 {
964                return Err(EncodeError::conversion(
965                    "a series block must be two positive cell counts",
966                ));
967            }
968            series_geometry(block, frame_count, width, height)
969        }
970        None => map_geometry(codes, frame_count, width, height),
971    };
972    let document_variables = metadata["variables"]
973        .as_array()
974        .ok_or_else(|| EncodeError::conversion("metadata variables missing"))?;
975    let names: Vec<&str> = document_variables
976        .iter()
977        .map(|variable| variable["id"].as_str().unwrap_or_default())
978        .collect();
979    let given: Vec<&str> = codes
980        .variables
981        .iter()
982        .map(|variable| variable.id.as_str())
983        .collect();
984    if names != given {
985        return Err(EncodeError::bundle(
986            "the codes do not name the metadata's variables in order",
987        ));
988    }
989    Ok((geometry, document_variables))
990}
991
992/// Write one bundle's store at `store` (replaced whole). `series` cuts the
993/// series layout over that block instead of the map layout; `delta` puts
994/// `xue.delta` in front of `bytes` on every previous-predicted variable.
995pub fn write_store(
996    codes: &StoreCodes<'_>,
997    store: &Path,
998    delta: bool,
999    series: Option<(usize, usize)>,
1000    pool: &rayon::ThreadPool,
1001) -> Result<StoreReport> {
1002    write_store_widened(codes, &[], store, delta, series, pool)
1003}
1004
1005/// [`write_store`] for a series store whose `wide` variables hold
1006/// sixteen-bit codes: the metadata names their series codebooks
1007/// ([`series_metadata`]), their [`StoreVariable`]s carry no byte planes,
1008/// and their arrays are `uint16`.
1009pub fn write_store_widened(
1010    codes: &StoreCodes<'_>,
1011    wide: &[WideVariable<'_>],
1012    store: &Path,
1013    delta: bool,
1014    series: Option<(usize, usize)>,
1015    pool: &rayon::ThreadPool,
1016) -> Result<StoreReport> {
1017    let metadata = codes.metadata;
1018    let (geometry, document_variables) = store_geometry(codes, series)?;
1019    if let Some(stray) = wide.iter().find(|held| {
1020        !codes
1021            .variables
1022            .iter()
1023            .any(|variable| variable.id == held.id)
1024    }) {
1025        return Err(EncodeError::bundle(format!(
1026            "{}: sixteen-bit codes for no variable of the bundle",
1027            stray.id
1028        )));
1029    }
1030    let projected = is_projected(metadata);
1031    let dimensions = primary_dimensions(projected);
1032
1033    if store.exists() {
1034        if !store.is_dir() {
1035            return Err(EncodeError::conversion(format!(
1036                "{} exists and is not a directory",
1037                store.display()
1038            )));
1039        }
1040        fs::remove_dir_all(store).map_err(|error| io_error(store, &error))?;
1041    }
1042    fs::create_dir_all(store).map_err(|error| io_error(store, &error))?;
1043
1044    let mut report = StoreReport {
1045        path: store.to_path_buf(),
1046        byte_length: 0,
1047        crc32: String::new(),
1048        delta,
1049        arrays: Vec::new(),
1050        chunk_count: 0,
1051    };
1052    let mut documents: Vec<(String, Value)> = Vec::new();
1053    for (variable, document_variable) in codes.variables.iter().zip(document_variables) {
1054        let held = wide
1055            .iter()
1056            .find(|held| held.id == variable.id)
1057            .map(|held| held.codes);
1058        let (written, chunks, document) = write_array(
1059            variable,
1060            held,
1061            document_variable,
1062            &geometry,
1063            &store.join(&variable.id),
1064            delta,
1065            series.is_some(),
1066            pool,
1067            None,
1068            &dimensions,
1069            projected,
1070        )?;
1071        report.arrays.push((variable.id.clone(), written));
1072        report.byte_length += written;
1073        report.chunk_count += chunks;
1074        documents.push((variable.id.clone(), document));
1075    }
1076    for (name, written) in write_coordinates(
1077        metadata,
1078        (geometry.height, geometry.width),
1079        store,
1080        &dimensions,
1081        false,
1082        &mut documents,
1083    )? {
1084        report.arrays.push((name, written));
1085        report.byte_length += written;
1086    }
1087    // The root group last, its consolidated metadata every array document
1088    // just written; its CRC-32 is the store's `?v=`.
1089    let mut consolidated = Map::new();
1090    for (name, document) in documents {
1091        consolidated.insert(name, document);
1092    }
1093    let root = json!({
1094        "zarr_format": 3,
1095        "node_type": "group",
1096        "attributes": {"xue": metadata.clone(), "xue_profile": PROFILE_VERSION},
1097        "consolidated_metadata": {
1098            "kind": "inline",
1099            "must_understand": false,
1100            "metadata": Value::Object(consolidated),
1101        },
1102    });
1103    let text = dumps_indented(&root).into_bytes();
1104    zarr::parse_group_metadata(std::str::from_utf8(&text).expect("UTF-8 JSON"))
1105        .map_err(|error| EncodeError::bundle(format!("group document is invalid: {}", error.0)))?;
1106    report.byte_length += write_file(&store.join("zarr.json"), &text)?;
1107    report.crc32 = format!("{:08x}", crc32_plane(&text));
1108    Ok(report)
1109}
1110
1111// -- the shared store (profile 2) ----------------------------------------------
1112
1113/// `bundles.zarr` for the full tier, `bundles.<tier>.zarr` for a rung of the
1114/// resolution ladder.
1115pub fn shared_store_name(tier: Option<&str>) -> String {
1116    match tier {
1117        Some(tier) => format!("{SHARED_STORE_STEM}.{tier}.zarr"),
1118        None => format!("{SHARED_STORE_STEM}.zarr"),
1119    }
1120}
1121
1122/// `<store>/zarr.part.<first bundle id>.json`: a build's bundles are disjoint
1123/// from every other build's of the same run, so the first one names the part
1124/// uniquely.
1125pub fn part_path(store: &Path, first_bundle_id: &str) -> PathBuf {
1126    store.join(format!("{PART_PREFIX}{first_bundle_id}.json"))
1127}
1128
1129/// `^[a-z][a-z0-9]*$`: a bundle id, and the suffix of a coordinate named
1130/// for a grid family.
1131pub fn is_coordinate_suffix(text: &str) -> bool {
1132    let mut bytes = text.bytes();
1133    bytes.next().is_some_and(|first| first.is_ascii_lowercase())
1134        && bytes.all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit())
1135}
1136
1137/// `Some("")` for the primary name, `Some(family)` for `<primary>_<family>`,
1138/// `None` for anything else.
1139fn grid_suffix<'a>(name: &'a str, primary: &str) -> Option<&'a str> {
1140    if name == primary {
1141        return Some("");
1142    }
1143    name.strip_prefix(primary)
1144        .and_then(|rest| rest.strip_prefix('_'))
1145        .filter(|family| is_coordinate_suffix(family))
1146}
1147
1148/// A bundle's dimension names (`docs/zarr-profile.md`, "Coordinates"): `time`
1149/// or `time_<bundle id>`, then `latitude` / `longitude` or `latitude_<family>`
1150/// / `longitude_<family>` of one family id, or on a projected grid `y` / `x` or
1151/// `y_<family>` / `x_<family>`. `projected` is what the bundle's `grid` block
1152/// says, when the caller has it: the names must agree with it.
1153fn check_dimensions(bundle_id: &str, dimensions: &[String], projected: Option<bool>) -> Result<()> {
1154    let named = |row: &str, column: &str| {
1155        grid_suffix(&dimensions[1], row)
1156            .is_some_and(|suffix| grid_suffix(&dimensions[2], column) == Some(suffix))
1157    };
1158    let valid = dimensions.len() == 3
1159        && (dimensions[0] == "time" || dimensions[0] == format!("time_{bundle_id}"))
1160        && ((projected != Some(true) && named("latitude", "longitude"))
1161            || (projected != Some(false) && named("y", "x")));
1162    if valid {
1163        Ok(())
1164    } else {
1165        Err(EncodeError::bundle(format!(
1166            "{bundle_id}: dimension names {dimensions:?} are not the profile's"
1167        )))
1168    }
1169}
1170
1171/// A variable array names the `crs` array exactly when its bundle's grid is
1172/// projected, so xarray and rioxarray find the CRS the metadata declares.
1173fn check_grid_mapping(
1174    bundle_id: &str,
1175    name: &str,
1176    document: &Value,
1177    projected: bool,
1178) -> Result<()> {
1179    let mapping = document["attributes"]
1180        .get("grid_mapping")
1181        .and_then(Value::as_str);
1182    if mapping != projected.then_some(CRS_ARRAY) {
1183        return Err(EncodeError::bundle(format!(
1184            "{bundle_id}: array {name} has grid_mapping {mapping:?} on a grid that says otherwise"
1185        )));
1186    }
1187    Ok(())
1188}
1189
1190/// The `crs` array: zero-dimensional, holding only its attributes.
1191fn check_crs(bundle_id: &str, document: Option<&Value>) -> Result<()> {
1192    let document = document.ok_or_else(|| {
1193        EncodeError::bundle(format!("{bundle_id}: no array document for {CRS_ARRAY}"))
1194    })?;
1195    if document.get("shape") != Some(&json!([])) {
1196        return Err(EncodeError::bundle(format!(
1197            "{bundle_id}: {CRS_ARRAY} must be a scalar array"
1198        )));
1199    }
1200    Ok(())
1201}
1202
1203/// One bundle written into a shared store (`BundleWrite` in the reference).
1204///
1205/// `documents` holds every array document the bundle uses, its variable
1206/// arrays in the metadata's order and then the coordinate arrays its
1207/// dimensions name; `byte_length` is those arrays' objects (each `zarr.json`
1208/// plus shard or chunk), which is what a viewer downloads for the bundle
1209/// alone and what its manifest entry reports. `crc32` is the CRC-32 of the
1210/// group document naming the bundle, stamped once that is written: here the
1211/// part's.
1212#[derive(Debug, Clone)]
1213pub struct BundleWrite {
1214    pub bundle_id: String,
1215    pub path: PathBuf,
1216    pub metadata: Value,
1217    pub dimensions: [String; 3],
1218    pub documents: Vec<(String, Value)>,
1219    pub byte_length: u64,
1220    pub arrays: Vec<(String, u64)>,
1221    pub chunk_count: u64,
1222    pub crc32: String,
1223}
1224
1225impl BundleWrite {
1226    /// The report block, keyed as the reference's `BundleWrite.to_dict`.
1227    pub fn to_value(&self) -> Value {
1228        let mut arrays = Map::new();
1229        for (name, written) in &self.arrays {
1230            arrays.insert(name.clone(), json!(written));
1231        }
1232        json!({
1233            "path": self.path.display().to_string(),
1234            "bundle": self.bundle_id,
1235            "byteLength": self.byte_length,
1236            "crc32": self.crc32,
1237            "delta": false,
1238            "indexLocation": "end",
1239            "dimensions": self.dimensions,
1240            "arrays": Value::Object(arrays),
1241            "chunkCount": self.chunk_count,
1242            "comparableChunks": 0,
1243            "identicalChunks": 0,
1244        })
1245    }
1246}
1247
1248/// Write one bundle's variable arrays and the coordinate arrays its
1249/// `dimensions` name into the shared store `store`, which is created if
1250/// absent and otherwise left as it is: other bundles' arrays, written before
1251/// or concurrently, stay. The group document is not touched.
1252///
1253/// `dimensions` is what the encoder decided for the bundle
1254/// (`convert::store_dimensions`); a coordinate shared with another bundle is
1255/// the same bytes from either, and is written by rename so two concurrent
1256/// writers never tear it. Arrays, codecs and chunking are exactly a
1257/// one-bundle store's, with `attributes.xue.bundle` added.
1258pub fn write_bundle_arrays(
1259    codes: &StoreCodes<'_>,
1260    store: &Path,
1261    bundle_id: &str,
1262    dimensions: &[String; 3],
1263    pool: &rayon::ThreadPool,
1264) -> Result<BundleWrite> {
1265    if !is_coordinate_suffix(bundle_id) || bundle_id == SHARED_STORE_STEM {
1266        return Err(EncodeError::bundle(format!(
1267            "{bundle_id:?} cannot name a bundle of a shared store"
1268        )));
1269    }
1270    let metadata = codes.metadata;
1271    let projected = is_projected(metadata);
1272    check_dimensions(bundle_id, dimensions, Some(projected))?;
1273    let (geometry, document_variables) = store_geometry(codes, None)?;
1274    if store.exists() && !store.is_dir() {
1275        return Err(EncodeError::conversion(format!(
1276            "{} exists and is not a directory",
1277            store.display()
1278        )));
1279    }
1280    fs::create_dir_all(store).map_err(|error| io_error(store, &error))?;
1281
1282    let mut report = BundleWrite {
1283        bundle_id: bundle_id.to_owned(),
1284        path: store.to_path_buf(),
1285        metadata: metadata.clone(),
1286        dimensions: dimensions.clone(),
1287        documents: Vec::new(),
1288        byte_length: 0,
1289        arrays: Vec::new(),
1290        chunk_count: 0,
1291        crc32: String::new(),
1292    };
1293    for (variable, document_variable) in codes.variables.iter().zip(document_variables) {
1294        if dimensions.contains(&variable.id) || variable.id == CRS_ARRAY {
1295            return Err(EncodeError::bundle(format!(
1296                "{bundle_id}: variable {} is named like a coordinate",
1297                variable.id
1298            )));
1299        }
1300        let (written, chunks, document) = write_array(
1301            variable,
1302            None,
1303            document_variable,
1304            &geometry,
1305            &store.join(&variable.id),
1306            false,
1307            false,
1308            pool,
1309            Some(bundle_id),
1310            dimensions,
1311            projected,
1312        )?;
1313        report.arrays.push((variable.id.clone(), written));
1314        report.chunk_count += chunks;
1315        report.documents.push((variable.id.clone(), document));
1316    }
1317    let sizes = write_coordinates(
1318        metadata,
1319        (geometry.height, geometry.width),
1320        store,
1321        dimensions,
1322        true,
1323        &mut report.documents,
1324    )?;
1325    report.arrays.extend(sizes);
1326    report.byte_length = report.arrays.iter().map(|(_, written)| written).sum();
1327    Ok(report)
1328}
1329
1330/// A shared store's group document over `bundles`, in manifest order
1331/// (`group_document` in the reference).
1332///
1333/// Key order is part of the bytes (`docs/zarr-profile.md`, "Group
1334/// document"): `attributes` holds `xue_profile` then `xue_bundles`, the
1335/// bundles in the given order; `consolidated_metadata.metadata` holds every
1336/// variable array, bundle by bundle and in each bundle's `variables` order,
1337/// then the primary coordinates `time`, `latitude`, `longitude` that some
1338/// bundle uses, then every other coordinate in the order its first bundle
1339/// names it. Two bundles naming one coordinate must carry the same document
1340/// for it.
1341pub fn group_document(bundles: &[&BundleWrite]) -> Result<Value> {
1342    if bundles.is_empty() {
1343        return Err(EncodeError::bundle(
1344            "a shared store holds at least one bundle",
1345        ));
1346    }
1347    let mut metadata_by_bundle = Map::new();
1348    let mut variable_arrays = Map::new();
1349    let mut coordinates = Map::new();
1350    for bundle in bundles {
1351        let bundle_id = bundle.bundle_id.as_str();
1352        if metadata_by_bundle.contains_key(bundle_id) {
1353            return Err(EncodeError::bundle(format!(
1354                "bundle {bundle_id} appears twice in one shared store"
1355            )));
1356        }
1357        metadata_by_bundle.insert(bundle_id.to_owned(), bundle.metadata.clone());
1358        let document_of = |name: &str| {
1359            bundle
1360                .documents
1361                .iter()
1362                .find(|(held, _)| held == name)
1363                .map(|(_, document)| document)
1364        };
1365        let variables = bundle.metadata["variables"].as_array().ok_or_else(|| {
1366            EncodeError::bundle(format!("{bundle_id}: metadata variables missing"))
1367        })?;
1368        let projected = is_projected(&bundle.metadata);
1369        let mut dimensions: Option<Vec<String>> = None;
1370        for variable in variables {
1371            let name = variable["id"].as_str().unwrap_or_default();
1372            let document = document_of(name).ok_or_else(|| {
1373                EncodeError::bundle(format!("{bundle_id}: no array document for {name}"))
1374            })?;
1375            if variable_arrays.contains_key(name) || coordinates.contains_key(name) {
1376                return Err(EncodeError::bundle(format!(
1377                    "array {name} appears twice in one shared store"
1378                )));
1379            }
1380            let names: Vec<String> = document["dimension_names"]
1381                .as_array()
1382                .map(|names| {
1383                    names
1384                        .iter()
1385                        .map(|name| name.as_str().unwrap_or_default().to_owned())
1386                        .collect()
1387                })
1388                .unwrap_or_default();
1389            match &dimensions {
1390                None => dimensions = Some(names),
1391                Some(held) if *held != names => {
1392                    return Err(EncodeError::bundle(format!(
1393                        "{bundle_id}: its arrays do not share one set of dimension names"
1394                    )))
1395                }
1396                Some(_) => {}
1397            }
1398            check_grid_mapping(bundle_id, name, document, projected)?;
1399            variable_arrays.insert(name.to_owned(), document.clone());
1400        }
1401        let mut dimensions = dimensions.unwrap_or_default();
1402        check_dimensions(bundle_id, &dimensions, Some(projected))?;
1403        if projected {
1404            check_crs(bundle_id, document_of(CRS_ARRAY))?;
1405            dimensions.push(CRS_ARRAY.to_owned());
1406        }
1407        for name in &dimensions {
1408            let document = document_of(name).ok_or_else(|| {
1409                EncodeError::bundle(format!(
1410                    "{bundle_id}: no array document for its coordinate {name}"
1411                ))
1412            })?;
1413            if variable_arrays.contains_key(name) {
1414                return Err(EncodeError::bundle(format!(
1415                    "coordinate {name} is named like a variable"
1416                )));
1417            }
1418            match coordinates.get(name) {
1419                Some(held) if held != document => {
1420                    return Err(EncodeError::bundle(format!(
1421                        "coordinate {name} differs between the bundles that use it"
1422                    )))
1423                }
1424                Some(_) => {}
1425                None => {
1426                    coordinates.insert(name.clone(), document.clone());
1427                }
1428            }
1429        }
1430    }
1431    let mut ordered = variable_arrays;
1432    for name in PRIMARY_COORDINATES {
1433        if let Some(document) = coordinates.get(name) {
1434            ordered.insert(name.to_owned(), document.clone());
1435        }
1436    }
1437    for (name, document) in &coordinates {
1438        if !PRIMARY_COORDINATES.contains(&name.as_str()) {
1439            ordered.insert(name.clone(), document.clone());
1440        }
1441    }
1442    Ok(json!({
1443        "zarr_format": 3,
1444        "node_type": "group",
1445        "attributes": {
1446            "xue_profile": SHARED_PROFILE_VERSION,
1447            "xue_bundles": Value::Object(metadata_by_bundle),
1448        },
1449        "consolidated_metadata": {
1450            "kind": "inline",
1451            "must_understand": false,
1452            "metadata": Value::Object(ordered),
1453        },
1454    }))
1455}
1456
1457/// The partial group document over the bundles one build wrote into `store`,
1458/// in manifest order: [`group_document`] over them alone, at
1459/// [`part_path`] of the first. Returns its path and its CRC-32, which the
1460/// build's entries carry until the reference's `finalize_store` writes the
1461/// store's group document from the parts.
1462///
1463/// The part is parsed back as every bundle's view of a profile-2 group, the
1464/// decoder's own check (`zarr::parse_group_metadata_for`), so a part the
1465/// readers would refuse once merged never leaves the encoder.
1466pub fn write_part(store: &Path, bundles: &[&BundleWrite]) -> Result<(PathBuf, String)> {
1467    let text = dumps_indented(&group_document(bundles)?).into_bytes();
1468    let utf8 = std::str::from_utf8(&text).expect("UTF-8 JSON");
1469    for bundle in bundles {
1470        zarr::parse_group_metadata_for(utf8, &bundle.bundle_id).map_err(|error| {
1471            EncodeError::bundle(format!(
1472                "{}: partial group document is invalid: {}",
1473                bundle.bundle_id, error.0
1474            ))
1475        })?;
1476    }
1477    let path = part_path(store, &bundles[0].bundle_id);
1478    write_file(&path, &text)?;
1479    Ok((path, format!("{:08x}", crc32_plane(&text))))
1480}
1481
1482#[cfg(test)]
1483mod tests {
1484    use super::*;
1485
1486    fn pool() -> rayon::ThreadPool {
1487        rayon::ThreadPoolBuilder::new()
1488            .num_threads(2)
1489            .build()
1490            .expect("pool")
1491    }
1492
1493    #[test]
1494    fn a_padded_chunk_differences_every_frame_against_the_one_before() {
1495        let geometry = Geometry {
1496            frame_count: 2,
1497            height: 3,
1498            width: 3,
1499            time_chunk: 6,
1500            tile_height: 2,
1501            tile_width: 2,
1502        };
1503        let first: Vec<u8> = (0..9).collect();
1504        let second: Vec<u8> = (10..19).collect();
1505        let planes: Vec<&[u8]> = vec![&first, &second];
1506        let raw = inner_chunk(&planes, &geometry, 0, 3, 255, false);
1507        // The south-east tile is one cell; the rest is fill, and so are the
1508        // four frames past the axis.
1509        assert_eq!(&raw[..4], &[8, 255, 255, 255]);
1510        assert_eq!(&raw[4..8], &[18, 255, 255, 255]);
1511        assert!(raw[8..].iter().all(|&code| code == 255));
1512        let stored = inner_chunk(&planes, &geometry, 0, 3, 255, true);
1513        assert_eq!(&stored[..4], &[8, 255, 255, 255]);
1514        assert_eq!(&stored[4..8], &[10, 0, 0, 0]);
1515        assert_eq!(&stored[8..12], &[255u8.wrapping_sub(18), 0, 0, 0]);
1516    }
1517
1518    #[test]
1519    fn a_store_reads_back_through_the_decoder_validators() {
1520        let metadata = json!({
1521            "schemaVersion": 1,
1522            "model": "TEST",
1523            "product": "test",
1524            "runTime": "2026-08-14T06:00:00Z",
1525            "profile": "quality",
1526            "time": {"firstForecastHour": 0, "stepHours": 1, "frameCount": 7},
1527            "grid": {"width": 5, "height": 3, "firstLongitude": -180.0, "firstLatitude": 90.0,
1528                     "longitudeStep": 72.0, "latitudeStep": -90.0, "wrapLongitude": true},
1529            "variables": [{"numericId": 1, "id": "tmp2m", "label": "T", "unit": "°C",
1530                           "quantization": {"type": "linear", "offset": -60.0, "scale": 0.5,
1531                                            "minimumCode": 0, "maximumCode": 220, "nodataCode": 255}}],
1532        });
1533        let planes: Vec<Vec<u8>> = (0..7u8)
1534            .map(|frame| (0..15u8).map(|cell| cell * 3 + frame).collect())
1535            .collect();
1536        let codes = StoreCodes {
1537            metadata: &metadata,
1538            variables: vec![StoreVariable {
1539                id: "tmp2m".into(),
1540                previous: true,
1541                planes: planes.iter().map(Vec::as_slice).collect(),
1542            }],
1543            tile: (2, 2),
1544        };
1545        let root = std::env::temp_dir().join(format!("xue-zarrstore-{}", std::process::id()));
1546        let report =
1547            write_store(&codes, &root.join("tmp2m.zarr"), false, None, &pool()).expect("map store");
1548        // Seven frames make two time chunks, of six tiles each.
1549        assert_eq!(report.chunk_count, 12);
1550        let series = write_store(
1551            &codes,
1552            &root.join("tmp2m.series.zarr"),
1553            true,
1554            Some(SERIES_BLOCK),
1555            &pool(),
1556        )
1557        .expect("series store");
1558        assert_eq!(series.chunk_count, 1);
1559        let on_disk: u64 = ["tmp2m.zarr"]
1560            .iter()
1561            .map(|store| walk(&root.join(store)))
1562            .sum();
1563        assert_eq!(on_disk, report.byte_length);
1564        let _ = fs::remove_dir_all(&root);
1565    }
1566
1567    fn bundle_metadata(variables: &[&str], frame_count: u64) -> Value {
1568        json!({
1569            "schemaVersion": 1,
1570            "model": "TEST",
1571            "product": "test",
1572            "runTime": "2026-08-14T06:00:00Z",
1573            "profile": "quality",
1574            "time": {"firstForecastHour": 0, "stepHours": 1, "frameCount": frame_count},
1575            "grid": {"width": 5, "height": 3, "firstLongitude": -180.0, "firstLatitude": 90.0,
1576                     "longitudeStep": 72.0, "latitudeStep": -90.0, "wrapLongitude": true},
1577            "variables": variables.iter().enumerate().map(|(index, id)| json!({
1578                "numericId": index + 1, "id": id, "label": id, "unit": "1",
1579                "quantization": {"type": "linear", "offset": 0.0, "scale": 1.0,
1580                                 "minimumCode": 0, "maximumCode": 250, "nodataCode": 255},
1581            })).collect::<Vec<_>>(),
1582        })
1583    }
1584
1585    fn dimensions(names: [&str; 3]) -> [String; 3] {
1586        names.map(str::to_owned)
1587    }
1588
1589    /// The part's key order is the reference's: `xue_profile` before
1590    /// `xue_bundles`, bundles in the order given, then every variable array
1591    /// bundle by bundle, the primary coordinates, and the other coordinates
1592    /// in first-appearance order; arrays lead their `xue` block with the
1593    /// bundle and carry the bundle's dimension names.
1594    #[test]
1595    fn a_part_orders_bundles_arrays_and_coordinates_like_the_reference() {
1596        let root = std::env::temp_dir().join(format!("xue-shared-store-{}", std::process::id()));
1597        let store = root.join(shared_store_name(None));
1598        let wind = bundle_metadata(&["ugrd10m", "vgrd10m"], 3);
1599        let rate = bundle_metadata(&["prate"], 2);
1600        let height = bundle_metadata(&["hgt500"], 3);
1601        let planes: Vec<Vec<u8>> = (0..3u8).map(|frame| vec![frame; 15]).collect();
1602        let variable = |id: &str, count: usize| StoreVariable {
1603            id: id.into(),
1604            previous: true,
1605            planes: planes[..count].iter().map(Vec::as_slice).collect(),
1606        };
1607        let write = |metadata: &Value,
1608                     variables: Vec<StoreVariable<'_>>,
1609                     bundle_id: &str,
1610                     names: [&str; 3]| {
1611            let codes = StoreCodes {
1612                metadata,
1613                variables,
1614                tile: (2, 2),
1615            };
1616            write_bundle_arrays(&codes, &store, bundle_id, &dimensions(names), &pool())
1617                .expect("bundle")
1618        };
1619        let prate = write(
1620            &rate,
1621            vec![variable("prate", 2)],
1622            "prate",
1623            ["time_prate", "latitude", "longitude"],
1624        );
1625        let wind10m = write(
1626            &wind,
1627            vec![variable("ugrd10m", 3), variable("vgrd10m", 3)],
1628            "wind10m",
1629            ["time", "latitude", "longitude"],
1630        );
1631        let hgt500 = write(
1632            &height,
1633            vec![variable("hgt500", 3)],
1634            "hgt500",
1635            ["time", "latitude_pgb", "longitude_pgb"],
1636        );
1637
1638        let (path, crc32) = write_part(&store, &[&prate, &wind10m, &hgt500]).expect("part");
1639        assert_eq!(path, store.join("zarr.part.prate.json"));
1640        assert!(
1641            !store.join("zarr.json").exists(),
1642            "the group document is the reference's to write"
1643        );
1644        let text = fs::read(&path).expect("part");
1645        assert_eq!(crc32, format!("{:08x}", crc32_plane(&text)));
1646        let part: Value = serde_json::from_slice(&text).expect("JSON");
1647        let keys = |value: &Value| {
1648            value
1649                .as_object()
1650                .expect("object")
1651                .keys()
1652                .cloned()
1653                .collect::<Vec<_>>()
1654        };
1655        assert_eq!(
1656            keys(&part),
1657            [
1658                "zarr_format",
1659                "node_type",
1660                "attributes",
1661                "consolidated_metadata"
1662            ]
1663        );
1664        assert_eq!(keys(&part["attributes"]), ["xue_profile", "xue_bundles"]);
1665        assert_eq!(
1666            keys(&part["attributes"]["xue_bundles"]),
1667            ["prate", "wind10m", "hgt500"]
1668        );
1669        assert_eq!(
1670            keys(&part["consolidated_metadata"]["metadata"]),
1671            [
1672                "prate",
1673                "ugrd10m",
1674                "vgrd10m",
1675                "hgt500",
1676                "time",
1677                "latitude",
1678                "longitude",
1679                "time_prate",
1680                "latitude_pgb",
1681                "longitude_pgb",
1682            ]
1683        );
1684        let array = &part["consolidated_metadata"]["metadata"]["hgt500"];
1685        assert_eq!(
1686            keys(&array["attributes"]["xue"]),
1687            ["bundle", "variable", "predictor"]
1688        );
1689        assert_eq!(array["attributes"]["xue"]["bundle"], "hgt500");
1690        assert_eq!(
1691            array["dimension_names"],
1692            json!(["time", "latitude_pgb", "longitude_pgb"])
1693        );
1694        assert_eq!(
1695            keys(&wind10m.to_value())[..3],
1696            ["path", "bundle", "byteLength"]
1697        );
1698        // A bundle's size is its arrays and the coordinates it uses.
1699        let used: u64 = ["ugrd10m", "vgrd10m", "time", "latitude", "longitude"]
1700            .iter()
1701            .map(|name| walk(&store.join(name)))
1702            .sum();
1703        assert_eq!(wind10m.byte_length, used);
1704        let _ = fs::remove_dir_all(&root);
1705    }
1706
1707    #[test]
1708    fn names_outside_the_profile_are_refused() {
1709        assert!(check_dimensions(
1710            "prate",
1711            &dimensions(["time_prate", "latitude", "longitude"]),
1712            None
1713        )
1714        .is_ok());
1715        assert!(check_dimensions(
1716            "prate",
1717            &dimensions(["time_gust", "latitude", "longitude"]),
1718            None
1719        )
1720        .is_err());
1721        assert!(check_dimensions(
1722            "hgt500",
1723            &dimensions(["time", "latitude_pgb", "longitude_pgb"]),
1724            None
1725        )
1726        .is_ok());
1727        assert!(check_dimensions(
1728            "hgt500",
1729            &dimensions(["time", "latitude_pgb", "longitude"]),
1730            None
1731        )
1732        .is_err());
1733        assert!(check_dimensions(
1734            "hgt500",
1735            &dimensions(["time", "latitude_", "longitude_"]),
1736            None
1737        )
1738        .is_err());
1739        assert!(check_dimensions(
1740            "hgt500",
1741            &dimensions(["time", "latitude_Pgb", "longitude_Pgb"]),
1742            None
1743        )
1744        .is_err());
1745        // The names must agree with the grid block when the caller has it.
1746        assert!(check_dimensions("tmp2m", &dimensions(["time", "y", "x"]), None).is_ok());
1747        assert!(check_dimensions("tmp2m", &dimensions(["time", "y", "x"]), Some(true)).is_ok());
1748        assert!(
1749            check_dimensions("tmp2m", &dimensions(["time", "y_pgb", "x_pgb"]), Some(true)).is_ok()
1750        );
1751        assert!(check_dimensions("tmp2m", &dimensions(["time", "y", "x"]), Some(false)).is_err());
1752        assert!(check_dimensions(
1753            "tmp2m",
1754            &dimensions(["time", "latitude", "longitude"]),
1755            Some(true)
1756        )
1757        .is_err());
1758        assert!(check_dimensions("tmp2m", &dimensions(["time", "y", "longitude"]), None).is_err());
1759        assert_eq!(shared_store_name(Some("half")), "bundles.half.zarr");
1760    }
1761
1762    /// One `tmp2m` bundle of three frames at the schema the two native grid
1763    /// blocks need.
1764    fn native_grid_metadata(schema_version: u64, grid: Value) -> Value {
1765        json!({
1766            "schemaVersion": schema_version,
1767            "model": "TEST",
1768            "product": "test",
1769            "runTime": "2026-08-14T06:00:00Z",
1770            "profile": "quality",
1771            "time": {"unitSeconds": 3600, "firstFrameOffset": 0, "frameCount": 3, "frameStep": 1},
1772            "grid": grid,
1773            "variables": [{
1774                "numericId": 1, "id": "tmp2m", "label": "T", "unit": "°C",
1775                "parameter": {"discipline": 0, "parameterCategory": 0, "parameterNumber": 0,
1776                              "typeOfFirstFixedSurface": 103, "scaleFactorOfFirstFixedSurface": 0,
1777                              "scaledValueOfFirstFixedSurface": 2},
1778                "quantization": {"type": "linear", "offset": -60.0, "scale": 0.5,
1779                                 "minimumCode": 0, "maximumCode": 220, "nodataCode": 255},
1780            }],
1781        })
1782    }
1783
1784    /// A projected bundle's coordinates are in metres, its `crs` array is a
1785    /// document with no chunk, every variable names it, and the part lists it
1786    /// after `y` and `x`.
1787    #[test]
1788    fn a_projected_bundle_writes_y_x_and_its_crs() {
1789        let root = std::env::temp_dir().join(format!("xue-projected-store-{}", std::process::id()));
1790        let store = root.join(shared_store_name(None));
1791        let metadata = native_grid_metadata(
1792            4,
1793            json!({
1794                "width": 5, "height": 3, "wrapLongitude": false,
1795                "projection": {"kind": "lambert-conformal", "radius": 6371229.0, "standardParallel1": 38.5,
1796                               "standardParallel2": 38.5, "latitudeOfOrigin": 38.5, "centralMeridian": -97.5,
1797                               "x0": -1500.0, "y0": 1500.0, "dx": 3000.0, "dy": -3000.0},
1798            }),
1799        );
1800        let planes: Vec<Vec<u8>> = (0..3u8).map(|frame| vec![frame; 15]).collect();
1801        let codes = StoreCodes {
1802            metadata: &metadata,
1803            variables: vec![StoreVariable {
1804                id: "tmp2m".into(),
1805                previous: true,
1806                planes: planes.iter().map(Vec::as_slice).collect(),
1807            }],
1808            tile: (2, 2),
1809        };
1810        let bundle = write_bundle_arrays(
1811            &codes,
1812            &store,
1813            "tmp2m",
1814            &dimensions(["time", "y", "x"]),
1815            &pool(),
1816        )
1817        .expect("bundle");
1818        let (path, _) = write_part(&store, &[&bundle]).expect("part");
1819        let part: Value = serde_json::from_slice(&fs::read(&path).expect("part")).expect("JSON");
1820        let held = &part["consolidated_metadata"]["metadata"];
1821        assert_eq!(
1822            held.as_object()
1823                .expect("object")
1824                .keys()
1825                .map(String::as_str)
1826                .collect::<Vec<_>>(),
1827            ["tmp2m", "time", "y", "x", "crs"]
1828        );
1829        assert_eq!(held["tmp2m"]["attributes"]["grid_mapping"], "crs");
1830        assert_eq!(
1831            held["y"]["attributes"]["standard_name"],
1832            "projection_y_coordinate"
1833        );
1834        assert_eq!(held["crs"]["shape"], json!([]));
1835        assert_eq!(held["crs"]["attributes"]["earth_radius"], 6371229.0);
1836        let y = fs::read(store.join("y").join("c").join("0")).expect("y");
1837        assert_eq!(y[8..16], (-1500.0_f64).to_le_bytes());
1838        assert!(store.join("crs").join("zarr.json").is_file());
1839        assert!(!store.join("crs").join("c").exists());
1840        assert_eq!(
1841            bundle.byte_length,
1842            ["tmp2m", "time", "y", "x", "crs"]
1843                .iter()
1844                .map(|name| walk(&store.join(name)))
1845                .sum::<u64>()
1846        );
1847
1848        // A latitude pair on this grid, or y and x on a regular one, is refused.
1849        assert!(write_bundle_arrays(
1850            &codes,
1851            &store,
1852            "tmp2m",
1853            &dimensions(["time", "latitude", "longitude"]),
1854            &pool()
1855        )
1856        .is_err());
1857        let series = write_store(
1858            &codes,
1859            &root.join("tmp2m.series.zarr"),
1860            true,
1861            Some(SERIES_BLOCK),
1862            &pool(),
1863        )
1864        .expect("series");
1865        assert!(series.arrays.iter().any(|(name, _)| name == "crs"));
1866        assert!(root.join("tmp2m.series.zarr").join("y").is_dir());
1867        let _ = fs::remove_dir_all(&root);
1868    }
1869
1870    /// A Gaussian grid's `latitude` holds its true rows.
1871    #[test]
1872    fn a_gaussian_grid_writes_its_true_latitudes() {
1873        let root = std::env::temp_dir().join(format!("xue-gaussian-store-{}", std::process::id()));
1874        let metadata = native_grid_metadata(
1875            3,
1876            json!({
1877                "width": 5, "height": 3, "firstLongitude": -180.0, "firstLatitude": 86.0,
1878                "longitudeStep": 72.0, "latitudeStep": -2.0, "wrapLongitude": true,
1879                "gaussian": {"n": 95, "firstRow": 4, "rowStride": 2},
1880            }),
1881        );
1882        let planes: Vec<Vec<u8>> = (0..3u8).map(|frame| vec![frame; 15]).collect();
1883        let codes = StoreCodes {
1884            metadata: &metadata,
1885            variables: vec![StoreVariable {
1886                id: "tmp2m".into(),
1887                previous: true,
1888                planes: planes.iter().map(Vec::as_slice).collect(),
1889            }],
1890            tile: (2, 2),
1891        };
1892        write_store(&codes, &root.join("tmp2m.zarr"), false, None, &pool()).expect("store");
1893        let latitude = fs::read(root.join("tmp2m.zarr").join("latitude").join("c").join("0"))
1894            .expect("latitude");
1895        assert_eq!(
1896            latitude[8..16],
1897            crate::projection::gaussian_latitude(95, 6).to_le_bytes()
1898        );
1899        let _ = fs::remove_dir_all(&root);
1900    }
1901
1902    /// The pair a series store holds, `tmp2m` under the sixteen-bit
1903    /// codebook of the reference's `SERIES_CODEBOOK_TABLE` and `ugrd10m` on
1904    /// its byte codes.
1905    fn widened_metadata(frame_count: u64) -> Value {
1906        let block = json!({"type": "linear", "offset": -90.0, "scale": 0.1, "minimumCode": 0, "maximumCode": 1500, "nodataCode": 65535});
1907        series_metadata(
1908            &bundle_metadata(&["tmp2m", "ugrd10m"], frame_count),
1909            &[("tmp2m", block.as_object().unwrap().clone())],
1910        )
1911    }
1912
1913    /// Codes that run the codebook and fall from its top to its bottom
1914    /// between frames, so the delta wraps modulo 65536, with one nodata cell.
1915    fn wide_planes(frame_count: usize) -> Vec<Vec<u16>> {
1916        (0..frame_count)
1917            .map(|frame| {
1918                let mut plane: Vec<u16> = (0..15usize)
1919                    .map(|cell| ((cell * 41 + frame * 911) % 1501) as u16)
1920                    .map(|code| if frame % 2 == 1 { 1500 - code } else { code })
1921                    .collect();
1922                plane[0] = 65535;
1923                plane
1924            })
1925            .collect()
1926    }
1927
1928    #[test]
1929    fn a_widened_series_store_holds_sixteen_bit_codes_little_endian() {
1930        let frame_count = 7;
1931        let metadata = widened_metadata(frame_count as u64);
1932        // The key keeps its place: the block is the variable's last, as the
1933        // bundle's own quantization was.
1934        let keys: Vec<&String> = metadata["variables"][0]
1935            .as_object()
1936            .unwrap()
1937            .keys()
1938            .collect();
1939        assert_eq!(keys.last().map(|key| key.as_str()), Some("quantization"));
1940        assert_eq!(
1941            metadata["variables"][0]["quantization"]["nodataCode"],
1942            json!(65535)
1943        );
1944        assert_eq!(
1945            metadata["variables"][1],
1946            bundle_metadata(&["tmp2m", "ugrd10m"], 7)["variables"][1]
1947        );
1948
1949        let wide = wide_planes(frame_count);
1950        let bytes: Vec<Vec<u8>> = (0..frame_count as u8)
1951            .map(|frame| (0..15u8).map(|cell| cell * 5 + frame).collect())
1952            .collect();
1953        let codes = StoreCodes {
1954            metadata: &metadata,
1955            variables: vec![
1956                StoreVariable {
1957                    id: "tmp2m".into(),
1958                    previous: true,
1959                    planes: Vec::new(),
1960                },
1961                StoreVariable {
1962                    id: "ugrd10m".into(),
1963                    previous: true,
1964                    planes: bytes.iter().map(Vec::as_slice).collect(),
1965                },
1966            ],
1967            tile: (2, 2),
1968        };
1969        let planes = WidePlanes(wide.iter().map(Vec::as_slice).collect());
1970        let held = [WideVariable {
1971            id: "tmp2m".into(),
1972            codes: &planes,
1973        }];
1974        let root = std::env::temp_dir().join(format!("xue-zarrstore-wide-{}", std::process::id()));
1975        let store = root.join("pair.series.zarr");
1976        // A 2x2 block over a 5x3 grid: three block columns, two block rows,
1977        // the last of them one row high.
1978        let report = write_store_widened(&codes, &held, &store, true, Some((2, 2)), &pool())
1979            .expect("series store");
1980        assert_eq!(report.chunk_count, 12);
1981
1982        let group: Value =
1983            serde_json::from_slice(&fs::read(store.join("zarr.json")).unwrap()).unwrap();
1984        assert_eq!(
1985            group["attributes"]["xue"], metadata,
1986            "the group carries the series metadata"
1987        );
1988        let text = fs::read_to_string(store.join("tmp2m").join("zarr.json")).unwrap();
1989        let document: Value = serde_json::from_str(&text).unwrap();
1990        assert_eq!(document["data_type"], json!("uint16"));
1991        assert_eq!(document["fill_value"], json!(65535));
1992        assert_eq!(document["attributes"]["_FillValue"], json!(65535));
1993        assert_eq!(document["attributes"]["scale_factor"], json!(0.1));
1994        assert_eq!(document["attributes"]["add_offset"], json!(-90.0));
1995        assert_eq!(
1996            document["attributes"]["xue"]["variable"],
1997            metadata["variables"][0]
1998        );
1999        assert_eq!(
2000            document["codecs"][0]["configuration"]["codecs"],
2001            json!([
2002                {"name": "xue.delta", "configuration": {"axis": 0}},
2003                {"name": "bytes", "configuration": {"endian": "little"}},
2004                {"name": "zstd", "configuration": {"level": ZSTD_LEVEL, "checksum": true}},
2005            ])
2006        );
2007        let narrow: Value =
2008            serde_json::from_slice(&fs::read(store.join("ugrd10m").join("zarr.json")).unwrap())
2009                .unwrap();
2010        assert_eq!(narrow["data_type"], json!("uint8"));
2011        assert_eq!(
2012            narrow["codecs"][0]["configuration"]["codecs"][1],
2013            json!({"name": "bytes"})
2014        );
2015
2016        // Every chunk decodes, through the decoder's own reader, to the
2017        // codes at the full inner shape, the nodata code beyond the grid.
2018        let layout = zarr::parse_array_metadata(&text).unwrap();
2019        assert_eq!(layout.data_type, zarr::DataType::U16);
2020        let shard = fs::read(store.join("tmp2m").join("c").join("0").join("0").join("0")).unwrap();
2021        let count = layout.chunks_per_shard as usize;
2022        let index = zarr::parse_shard_index(
2023            &shard[shard.len() - zarr::shard_index_length(count)..],
2024            count,
2025        )
2026        .unwrap();
2027        for tile in 0..layout.tile_count {
2028            let entry = index[tile as usize].expect("stored");
2029            let payload = &shard[entry.offset as usize..(entry.offset + entry.length) as usize];
2030            let block = zarr::decode_inner_chunk(&layout, payload).unwrap();
2031            let (row, column) = zarr::tile_origin(&layout, tile);
2032            let (height, width) = zarr::tile_shape(&layout, tile);
2033            for frame in 0..frame_count {
2034                for line in 0..2usize {
2035                    for cell in 0..2usize {
2036                        let held = block[frame * 4 + line * 2 + cell];
2037                        let expected = if line < height as usize && cell < width as usize {
2038                            wide[frame][(row as usize + line) * 5 + column as usize + cell]
2039                        } else {
2040                            65535
2041                        };
2042                        assert_eq!(
2043                            held, expected,
2044                            "tile {tile} frame {frame} cell {line},{cell}"
2045                        );
2046                    }
2047                }
2048            }
2049        }
2050        let _ = fs::remove_dir_all(&root);
2051    }
2052
2053    #[test]
2054    fn sixteen_bit_codes_are_a_series_store_s_and_their_codebook_s_alone() {
2055        let metadata = widened_metadata(2);
2056        let wide = wide_planes(2);
2057        let bytes: Vec<Vec<u8>> = vec![vec![1; 15]; 2];
2058        let planes = WidePlanes(wide.iter().map(Vec::as_slice).collect());
2059        let root =
2060            std::env::temp_dir().join(format!("xue-zarrstore-wide-refused-{}", std::process::id()));
2061        let byte_planes: Vec<&[u8]> = bytes.iter().map(Vec::as_slice).collect();
2062        let pair = |metadata| StoreCodes {
2063            metadata,
2064            variables: vec![
2065                StoreVariable {
2066                    id: "tmp2m".into(),
2067                    previous: true,
2068                    planes: Vec::new(),
2069                },
2070                StoreVariable {
2071                    id: "ugrd10m".into(),
2072                    previous: true,
2073                    planes: byte_planes.clone(),
2074                },
2075            ],
2076            tile: (2, 2),
2077        };
2078        let mut codes = pair(&metadata);
2079        let held = [WideVariable {
2080            id: "tmp2m".into(),
2081            codes: &planes,
2082        }];
2083        // A map layout never holds them.
2084        let message =
2085            write_store_widened(&codes, &held, &root.join("map.zarr"), true, None, &pool())
2086                .err()
2087                .unwrap()
2088                .to_string();
2089        assert!(
2090            message.contains("a uint16 array is a series array"),
2091            "{message}"
2092        );
2093        // A sixteen-bit codebook with no sixteen-bit codes.
2094        let message = write_store(&codes, &root.join("none.zarr"), true, Some((2, 2)), &pool())
2095            .err()
2096            .unwrap()
2097            .to_string();
2098        assert!(message.contains("no sixteen-bit codes"), "{message}");
2099        // Byte codes beside them.
2100        codes.variables[0].planes = byte_planes.clone();
2101        let message = write_store_widened(
2102            &codes,
2103            &held,
2104            &root.join("both.zarr"),
2105            true,
2106            Some((2, 2)),
2107            &pool(),
2108        )
2109        .err()
2110        .unwrap()
2111        .to_string();
2112        assert!(message.contains("byte codes besides"), "{message}");
2113        // Sixteen-bit codes under a byte codebook, or for no variable.
2114        let narrow = bundle_metadata(&["tmp2m", "ugrd10m"], 2);
2115        let codes = pair(&narrow);
2116        let message = write_store_widened(
2117            &codes,
2118            &held,
2119            &root.join("narrow.zarr"),
2120            true,
2121            Some((2, 2)),
2122            &pool(),
2123        )
2124        .err()
2125        .unwrap()
2126        .to_string();
2127        assert!(
2128            message.contains("where its codebook's are uint8"),
2129            "{message}"
2130        );
2131        let stray = [WideVariable {
2132            id: "prmsl".into(),
2133            codes: &planes,
2134        }];
2135        let message = write_store_widened(
2136            &codes,
2137            &stray,
2138            &root.join("stray.zarr"),
2139            true,
2140            Some((2, 2)),
2141            &pool(),
2142        )
2143        .err()
2144        .unwrap()
2145        .to_string();
2146        assert!(message.contains("prmsl"), "{message}");
2147        let _ = fs::remove_dir_all(&root);
2148    }
2149
2150    fn walk(path: &Path) -> u64 {
2151        fs::read_dir(path)
2152            .expect("store directory")
2153            .map(|entry| {
2154                let path = entry.expect("entry").path();
2155                if path.is_dir() {
2156                    walk(&path)
2157                } else {
2158                    fs::metadata(&path).expect("file").len()
2159                }
2160            })
2161            .sum()
2162    }
2163}
2164
2165#[cfg(test)]
2166mod schema_tie_tests {
2167    //! The attributes a projected store writes are the ones
2168    //! `docs/schemas/store-array.schema.json` names.
2169    use crate::schematie::assert_named;
2170
2171    #[test]
2172    fn the_projected_attributes_are_the_schemas() {
2173        assert_named(
2174            "store-array",
2175            "/$defs/Attributes",
2176            &[
2177                "grid_mapping",
2178                "grid_mapping_name",
2179                "latitude_of_projection_origin",
2180                "longitude_of_central_meridian",
2181                "standard_parallel",
2182                "earth_radius",
2183                "crs_wkt",
2184            ],
2185        );
2186    }
2187}