Skip to main content

xue/encode/
convert.rs

1//! Build Xue v1 bundles from gridded input — the port of `xuebuild/binconvert.py`.
2//!
3//! Each variable is packaged into its own single-variable `.xue` file so the
4//! frontend can download exactly the fields it needs. A forecast source
5//! arrives as one GRIB2 file per forecast hour; an observation source
6//! (`observation.rs`) as one NetCDF file whose bands are the time axis.
7//! Everything past frame discovery — crop, quantize, temporal grouping,
8//! container write, manifest — is the same for both.
9
10use std::collections::BTreeMap;
11use std::path::{Path, PathBuf};
12use std::sync::{Arc, Condvar, Mutex};
13
14use serde_json::{json, Map, Value};
15use time::OffsetDateTime;
16
17use crate::encode::binformat::{self, ChunkPayload, ChunkTables, HOUR_SECONDS};
18use crate::encode::derive::{
19    derive_cat_plane, derive_ptype, derive_theta_e, derive_vapour_flux, derive_wave_vector,
20    interval_rate,
21};
22use crate::encode::discover::{
23    discover_records, discover_series, frame_of, Discovered, FileFrames,
24};
25use crate::encode::errors::{EncodeError, Result};
26use crate::encode::gdalio::{needs_serial_access, netcdf_guard, Dataset};
27use crate::encode::gribpng::GribPngFile;
28use crate::encode::grid::{
29    crop_grid, gaussian_rows, normalize_longitudes, snap_global_longitudes, snap_regional_steps,
30    GridInfo,
31};
32use crate::encode::ladder::{build_ladder, bundle_tile, playback_bandwidth, Rung, Tier};
33use crate::encode::metadata::{axis_unit_seconds, build_metadata};
34use crate::encode::model::{PlaneSource, SourceFrame};
35use crate::encode::parallel::for_each_ordered;
36use crate::encode::poster::encode_poster;
37use crate::encode::pyjson::dumps_default;
38use crate::encode::quantize::Book;
39use crate::encode::registry::{Companion, DerivationKind, Registry};
40use crate::encode::report::{build_report, write_manifest};
41use crate::encode::reproject::{lambert_conformal_from_wkt, rotate_winds, ProjectedGrid};
42use crate::encode::sources::{family_frame_path, SourceSpec};
43use crate::encode::spool::SeriesSpool;
44use crate::encode::temporal::build_chunks;
45use crate::encode::variables::VariableSpec;
46use crate::encode::zarrstore;
47use crate::format::{ChunkEntry, Predictor, TileGeometry, VariableEntry, NO_DEPENDENCY};
48
49// The precipitation arithmetic stays reachable where `tests/encoder.rs`
50// has always imported it from.
51pub use crate::encode::derive::{
52    align_packing_steps, average_window_start, deaccumulate_precipitation, deaverage_precipitation,
53    dewindow_precipitation,
54};
55// The wheel's `decimate` is this sampling, so the two cannot drift.
56pub use crate::encode::ladder::decimate_codes;
57
58pub const DEFAULT_ZSTD_LEVEL: i32 = 15;
59
60#[derive(Debug, Clone)]
61pub struct ConvertOptions {
62    pub profile: String,
63    pub zstd_level: i32,
64    pub require_complete: bool,
65    pub expected_hours: i64,
66    pub manifest_path: Option<PathBuf>,
67    pub force: bool,
68    pub skip_variants: bool,
69    pub model: String,
70    pub bbox: Option<(f64, f64, f64, f64)>,
71    pub bundle_ids: Option<Vec<String>>,
72    pub last_hour: Option<i64>,
73    pub extract_workers: usize,
74    pub compress_workers: usize,
75    pub verbose: bool,
76    /// Write each bundle's Zarr store (`docs/zarr-profile.md`) from the
77    /// codes, and name it in the manifest.
78    pub zarr: bool,
79    /// Write each bundle's `.xue` container as well. A build needs at least
80    /// one of the two.
81    pub container: bool,
82    /// The full-resolution bundles that also ship a series store
83    /// (`SourceSpec.series_bundle_ids` in `xuebuild/sources.py`, handed in by
84    /// the caller); only read when `zarr` is on.
85    pub series_bundle_ids: Vec<String>,
86}
87
88impl Default for ConvertOptions {
89    fn default() -> Self {
90        let cpus = std::thread::available_parallelism().map_or(4, std::num::NonZeroUsize::get);
91        Self {
92            profile: "quality".into(),
93            zstd_level: DEFAULT_ZSTD_LEVEL,
94            require_complete: false,
95            expected_hours: 120,
96            manifest_path: None,
97            force: false,
98            skip_variants: false,
99            model: "gfs".into(),
100            bbox: None,
101            bundle_ids: None,
102            last_hour: None,
103            // GRIB unpacking is CPU-bound: one worker per core.
104            extract_workers: cpus.min(16),
105            compress_workers: cpus,
106            verbose: false,
107            // The store alone, the way every run publishes; the container
108            // is opt-in.
109            zarr: true,
110            container: false,
111            series_bundle_ids: Vec::new(),
112        }
113    }
114}
115
116/// The id of the grid family one input is read from, or `None` for an input
117/// on the source's own grid (`SourceSpec::grid_family_of`). Mirrors
118/// `grid_family_of` in `xuebuild/discover.py`.
119pub fn grid_family_of<'a>(source: &'a SourceSpec, variable_id: &str) -> Option<&'a str> {
120    source
121        .grid_family_of(variable_id)
122        .map(|companion| companion.id.as_str())
123}
124
125/// The grid family one bundle is built on: the family every one of its inputs
126/// is read from, so the bundle's grid, tile, variants and poster are that
127/// family's.
128///
129/// A bundle whose inputs span two grids could not be written at all — its
130/// planes would not be the same shape — so a source that declares one is a
131/// registry bug, and it is refused here rather than half-built. (The vapour
132/// flux at 850 hPa reads the specific humidity and the wind pair there, all
133/// three from the CFSv2 pressure-level family, which is what makes it one
134/// bundle's worth of one grid.) Mirrors `bundle_grid_family` in
135/// `xuebuild/discover.py`.
136pub fn bundle_grid_family<'a>(
137    registry: &Registry,
138    source: &'a SourceSpec,
139    bundle_id: &str,
140) -> Result<Option<&'a str>> {
141    let mut families: Vec<Option<&'a str>> = Vec::new();
142    for variable_id in registry.bundle_input_ids(source, bundle_id) {
143        let family = grid_family_of(source, &variable_id);
144        if !families.contains(&family) {
145            families.push(family);
146        }
147    }
148    if families.len() > 1 {
149        let mut named: Vec<&str> = families
150            .iter()
151            .map(|family| family.unwrap_or("the primary file"))
152            .collect();
153        named.sort_unstable();
154        return Err(EncodeError::conversion(format!(
155            "the {bundle_id} bundle of {} reads {}: every variable of a bundle must be on one grid",
156            source.manifest_model,
157            named.join(", ")
158        )));
159    }
160    Ok(families.first().copied().flatten())
161}
162
163/// The dimension names a bundle's arrays carry in its run's shared store
164/// (`docs/zarr-profile.md`, "Coordinates"), and so the coordinate arrays the
165/// bundle uses there. Mirrors `store_dimensions` in `xuebuild/discover.py`.
166///
167/// `time_<bundle id>` for a published scalar whose series has no analysis
168/// frame (`Registry::analysis_optional_ids`), for one whose series starts at
169/// a first hour of its own (`Registry::bundle_first_hour`), for one read
170/// from an input written only every so many hours
171/// (`Registry::bundle_has_step`) and for a static field;
172/// `latitude_<family>` / `longitude_<family>` for a bundle on a grid family
173/// of its own, `<family>` being exactly what [`bundle_grid_family`] returns;
174/// `y` and `x` in place of the latitude and longitude names throughout on a
175/// source published on a map projection.
176/// The decision is the rule, not a comparison of axes, so it is a pure
177/// function of the source and the bundle id: a fan-out job building a subset
178/// of the bundles and a whole build write the same objects.
179pub fn store_dimensions(
180    registry: &Registry,
181    source: &SourceSpec,
182    bundle_id: &str,
183) -> Result<[String; 3]> {
184    let variable_ids = registry.bundle_variable_ids(bundle_id);
185    let own_axis = (source.bundle_scalar_ids.iter().any(|id| id == bundle_id)
186        && (!registry
187            .analysis_optional_ids(source, &[bundle_id])
188            .is_empty()
189            || registry.bundle_first_hour(source, bundle_id).is_some()
190            || registry.bundle_has_step(source, bundle_id)))
191        || registry.is_static(&variable_ids[0]);
192    let family = bundle_grid_family(registry, source, bundle_id)?;
193    if let Some(family) = family {
194        if !zarrstore::is_coordinate_suffix(family) {
195            return Err(EncodeError::conversion(format!(
196                "grid family {family:?} of {} cannot name a coordinate array",
197                source.manifest_model
198            )));
199        }
200    }
201    let (row, column) = if source.grid_relative_winds {
202        ("y", "x")
203    } else {
204        ("latitude", "longitude")
205    };
206    Ok([
207        if own_axis {
208            format!("time_{bundle_id}")
209        } else {
210            "time".to_owned()
211        },
212        family.map_or_else(|| row.to_owned(), |family| format!("{row}_{family}")),
213        family.map_or_else(|| column.to_owned(), |family| format!("{column}_{family}")),
214    ])
215}
216
217// -- grid --------------------------------------------------------------------
218
219/// The grid, from the geotransform as `gdalinfo -json` prints it
220/// ([`Dataset::geo_transform`]): the reference encoder reads its grid out of
221/// that text, whose rounding moves a noisy step such as the CWA radar's
222/// 0.0125° by an ulp that no snap below takes back.
223///
224/// A file on a map projection describes its grid in projected metres. A source
225/// declares which it reads (`SourceSpec::grid_relative_winds`), so a file of the
226/// wrong kind is refused rather than misread. `family` is the grid family the
227/// file was read for: a family on a grid of its own (CFSv2's 1° pressure levels)
228/// is not the model's Gaussian grid.
229fn grid_info(path: &Path, source: &SourceSpec, family: Option<&str>) -> Result<GridInfo> {
230    let dataset = Dataset::open(path)?;
231    let (width, height) = dataset.size();
232    let transform = dataset.geo_transform()?;
233    if transform[2] != 0.0 || transform[4] != 0.0 {
234        return Err(EncodeError::conversion(format!(
235            "rotated grids are unsupported: {}",
236            path.display()
237        )));
238    }
239    let projection = lambert_conformal_from_wkt(&dataset.projection_wkt())?;
240    if let Some(projection) = projection {
241        if !source.grid_relative_winds {
242            return Err(EncodeError::conversion(format!(
243                "{} is on a map projection, which this source does not declare",
244                path.display()
245            )));
246        }
247        if transform[1] <= 0.0 || transform[5] >= 0.0 {
248            return Err(EncodeError::conversion(format!(
249                "grid must run west-to-east and north-to-south: {}",
250                path.display()
251            )));
252        }
253        // To the millimetre, as the reference encoder takes them: GDAL
254        // releases place a projected grid's origin a few nanometres apart,
255        // and the published grid and every rotated wind descend from these
256        // four numbers.
257        let [x0, dx, y0, dy] = [transform[0], transform[1], transform[3], transform[5]].map(round3);
258        return Ok(GridInfo::projected(
259            ProjectedGrid {
260                projection,
261                width,
262                height,
263                x0: x0 + dx / 2.0,
264                y0: y0 + dy / 2.0,
265                dx,
266                dy,
267            },
268            None,
269        ));
270    }
271    if source.grid_relative_winds {
272        return Err(EncodeError::conversion(format!(
273            "{} is a regular grid, but this source declares a projected one",
274            path.display()
275        )));
276    }
277    let (longitude_step, latitude_step) = (transform[1], transform[5]);
278    if longitude_step <= 0.0 || latitude_step >= 0.0 {
279        return Err(EncodeError::conversion(format!(
280            "grid must run west-to-east and north-to-south: {}",
281            path.display()
282        )));
283    }
284    let mut grid =
285        normalize_longitudes(snap_regional_steps(snap_global_longitudes(GridInfo::new(
286            width,
287            height,
288            transform[0] + longitude_step / 2.0,
289            transform[3] + latitude_step / 2.0,
290            longitude_step,
291            latitude_step,
292        ))));
293    if let Some(downsample) = source.downsample {
294        grid = grid.downsampled(downsample.factor, path)?;
295    }
296    if let (Some(n), None) = (source.gaussian_n, family) {
297        grid.gaussian = Some(gaussian_rows(&grid, n, path)?);
298    }
299    Ok(grid)
300}
301
302/// The vector bundles of this build whose pairs must be turned to east and
303/// north: all of them on a source with grid-relative winds. A derived one would
304/// read winds that are not its own pair's, and no such source publishes one, so
305/// a registry that lists one is refused rather than half-rotated. Mirrors
306/// `_grid_relative_vectors` in `xuebuild/binconvert.py`.
307fn grid_relative_vectors<'a>(
308    registry: &Registry,
309    source: &SourceSpec,
310    vector_ids: &[&'a str],
311) -> Result<Vec<&'a str>> {
312    if !source.grid_relative_winds {
313        return Ok(Vec::new());
314    }
315    let derived: Vec<&str> = vector_ids
316        .iter()
317        .copied()
318        .filter(|id| registry.is_derived_vector(id))
319        .collect();
320    if !derived.is_empty() {
321        return Err(EncodeError::conversion(format!(
322            "{} has grid-relative winds, so it cannot derive {derived:?}",
323            source.manifest_model
324        )));
325    }
326    Ok(vector_ids.to_vec())
327}
328
329/// Round to three decimal places the way Python's `round(value, 3)` does:
330/// correct decimal rounding, ties to even.
331fn round3(value: f64) -> f64 {
332    format!("{value:.3}").parse().unwrap_or(value)
333}
334
335// -- extraction --------------------------------------------------------------
336
337/// Take one plane to the variable's unit by its conversion rule
338/// (`units.rs`): the arithmetic the rule applies under the record's
339/// spelling, once per value, in f64 — the operation `rules.convert` runs
340/// for `_convert_units` in `xuebuild/binconvert.py`. The spelling was
341/// accepted when the frame was inspected; a spelling the rule does not
342/// scale under (a series already in the published unit) takes the identity.
343fn convert_units(spec: &VariableSpec, unit: &str, values: &mut [f64]) -> Result<()> {
344    spec.conversion.convert(unit, values)
345}
346
347/// How the planes of a frame are read: one file's plane source (GRIB: the
348/// same for every record) or an observation window's per-variable ones.
349/// Mirrors `_plane_source_for` in `xuebuild/binconvert.py`.
350pub enum PlaneSources {
351    Uniform(PlaneSource),
352    PerVariable(Vec<(String, PlaneSource)>),
353}
354
355impl PlaneSources {
356    fn for_variable(&self, variable_id: &str) -> Result<&PlaneSource> {
357        match self {
358            PlaneSources::Uniform(source) => Ok(source),
359            PlaneSources::PerVariable(sources) => sources
360                .iter()
361                .find(|(id, _)| id == variable_id)
362                .map(|(_, source)| source)
363                .ok_or_else(|| {
364                    EncodeError::conversion(format!("no plane source for {variable_id}"))
365                }),
366        }
367    }
368}
369
370/// One grid per variable of a frame: the run's single grid for every source
371/// with one, and — on a source with a grid family — the grid of the family
372/// each variable is read from. Mirrors `_grid_for` in
373/// `xuebuild/binconvert.py`, where the same thing is a `GridInfo` or a
374/// mapping.
375pub struct PlaneGrids(Vec<(String, GridInfo)>);
376
377impl PlaneGrids {
378    fn for_variable(&self, variable_id: &str) -> Result<&GridInfo> {
379        self.0
380            .iter()
381            .find(|(id, _)| id == variable_id)
382            .map(|(_, grid)| grid)
383            .ok_or_else(|| EncodeError::conversion(format!("no grid for {variable_id}")))
384    }
385}
386
387/// Extract every requested band of one frame, as float64 planes in physical
388/// units, cropped and rolled into the published layout: one dataset open
389/// per file the frame's variables live in — one for a GRIB record set, one
390/// per variable for a satellite window whose series are one file each, one
391/// per grid family for a source with more than one grid (mirrors
392/// `_extract_planes` in `xuebuild/binconvert.py`).
393///
394/// `grids` is the published grid per variable; a file holds one family's
395/// records, so the plane size is read off the grid of whatever the file
396/// carries.
397///
398/// Each of `uncropped_ids` on a cropped grid also comes back in the second
399/// list as it was before the crop window was cut, unit-converted the same
400/// way — the whole plane a derivation reading neighbours needs
401/// ([`derive_cat_plane`]). On an uncropped grid the published plane is that
402/// plane already, and is not copied.
403///
404/// Each band is taken through the whole per-plane chain ([`finish_plane`])
405/// as soon as it is read, so a frame never holds more than one
406/// full-resolution plane beside the thinned ones already finished: an MRMS
407/// 3D frame is 33 levels of 7000 x 3500 doubles, 6.5 GB read whole, and
408/// 196 MB a plane. The chain is per plane and the planes come back in
409/// `frames` order, so the output is the same either way. A file the netCDF
410/// driver reads is the exception: its reads are serialized
411/// (`netcdf_guard`), so its planes are read under the guard, the guard
412/// released, and only then finished, rather than holding every other
413/// worker's reads behind this one's arithmetic.
414fn extract_planes(
415    frames: &FileFrames,
416    grids: &PlaneGrids,
417    plane_sources: &PlaneSources,
418    uncropped_ids: &[String],
419    registry: &Registry,
420) -> Result<(Vec<(String, Vec<f64>)>, Vec<(String, Vec<f64>)>)> {
421    // The files in first-seen order, each with the positions in `frames` of
422    // the variables it holds.
423    let mut by_file: Vec<(&PathBuf, Vec<usize>)> = Vec::new();
424    for (index, entry) in frames.iter().enumerate() {
425        match by_file.iter_mut().find(|(path, _)| **path == entry.1.path) {
426            Some((_, held)) => held.push(index),
427            None => by_file.push((&entry.1.path, vec![index])),
428        }
429    }
430    let mut planes: Vec<Option<Vec<f64>>> = vec![None; frames.len()];
431    let mut wholes: Vec<Option<Vec<f64>>> = vec![None; frames.len()];
432    let keep_whole = |position: usize| uncropped_ids.contains(&frames[position].0);
433    for (source, positions) in by_file {
434        let first_id = &frames[positions[0]].0;
435        let (source_height, source_width) = grids.for_variable(first_id)?.source_shape();
436        let unscale = plane_sources.for_variable(first_id)?.unscale;
437        let serial = needs_serial_access(source);
438        let mut unfinished: Vec<(usize, Vec<f64>)> = Vec::new();
439        {
440            // The netCDF driver is not thread-safe; the guard is held for
441            // the file's open and every read, and is a no-op for every GRIB
442            // source.
443            let _serial = serial.then(netcdf_guard);
444            let dataset = Dataset::open(source)?;
445            let png = GribPngFile::open(source);
446            if dataset.size() != (source_width, source_height) {
447                return Err(EncodeError::conversion(format!(
448                    "extracted plane size mismatch for {}",
449                    source.display()
450                )));
451            }
452            for &position in &positions {
453                let frame = &frames[position].1;
454                let mut plane = match &png {
455                    Some(png) => png.read_band_f64(&dataset, frame.band)?,
456                    None => dataset.read_band_f64(frame.band)?,
457                };
458                if unscale {
459                    let band = dataset.band_info(frame.band)?;
460                    if band.scale != 1.0 || band.offset != 0.0 {
461                        for value in &mut plane {
462                            *value = *value * band.scale + band.offset;
463                        }
464                    }
465                }
466                if serial {
467                    unfinished.push((position, plane));
468                } else {
469                    let (finished, whole) = finish_plane(
470                        &frames[position],
471                        plane,
472                        grids,
473                        plane_sources,
474                        keep_whole(position),
475                        registry,
476                    )?;
477                    planes[position] = Some(finished);
478                    wholes[position] = whole;
479                }
480            }
481        }
482        for (position, plane) in unfinished {
483            let (finished, whole) = finish_plane(
484                &frames[position],
485                plane,
486                grids,
487                plane_sources,
488                keep_whole(position),
489                registry,
490            )?;
491            planes[position] = Some(finished);
492            wholes[position] = whole;
493        }
494    }
495    let uncropped = frames
496        .iter()
497        .zip(wholes)
498        .filter_map(|((variable_id, _), whole)| whole.map(|whole| (variable_id.clone(), whole)))
499        .collect();
500    let planes = frames
501        .iter()
502        .zip(planes)
503        .map(|((variable_id, _), plane)| (variable_id.clone(), plane.expect("every frame read")))
504        .collect();
505    Ok((planes, uncropped))
506}
507
508/// One extracted plane through the per-plane chain, into the published
509/// layout and physical units: the column roll, the fill values, the missing
510/// points, the block thinning, the regional crop, the completeness check and the unit conversion, in that
511/// order. With `keep_whole` on a cropped grid, the plane as it was before
512/// the crop also comes back, unit-converted and never checked for
513/// completeness, as `_extract_planes` keeps it.
514fn finish_plane(
515    (variable_id, frame): &(String, SourceFrame),
516    mut plane: Vec<f64>,
517    grids: &PlaneGrids,
518    plane_sources: &PlaneSources,
519    keep_whole: bool,
520    registry: &Registry,
521) -> Result<(Vec<f64>, Option<Vec<f64>>)> {
522    let source = &frame.path;
523    let spec = registry.variable(variable_id)?;
524    let grid = grids.for_variable(variable_id)?;
525    let (source_height, source_width) = grid.source_shape();
526    if grid.column_roll > 0 {
527        let roll = grid.column_roll;
528        let mut rolled = vec![0f64; plane.len()];
529        for row in 0..source_height {
530            let base = row * source_width;
531            for column in 0..source_width {
532                rolled[base + column] = plane[base + (column + source_width - roll) % source_width];
533            }
534        }
535        plane = rolled;
536    }
537    // Missing data becomes a value before the plane is thinned, so a fill
538    // never decides a block, and only then is a regional window cut.
539    plane_sources
540        .for_variable(variable_id)?
541        .apply_fill(&mut plane);
542    fill_missing(spec, &mut plane);
543    if let Some(downsample) = &grid.downsample {
544        plane = downsample.take(&plane)?;
545    }
546    let mut whole: Option<Vec<f64>> = None;
547    if let Some(crop) = grid.crop {
548        let cropped = crop.take(&plane);
549        if keep_whole {
550            whole = Some(plane);
551        }
552        plane = cropped;
553    }
554    if plane.iter().any(|value| !value.is_finite()) {
555        return Err(EncodeError::conversion(format!(
556            "Xue v1 requires complete planes, found non-finite values in {}",
557            source.display()
558        )));
559    }
560    convert_units(spec, &frame.unit, &mut plane)?;
561    if let Some(whole) = whole.as_mut() {
562        convert_units(spec, &frame.unit, whole)?;
563    }
564    Ok((plane, whole))
565}
566
567/// Map the points a record does not cover to the bottom of the variable's
568/// codebook — a value, not a gap. Which values mark them is the variable's
569/// own to declare (`VariableSpec::fill_values`: GDAL's 9999 for a GRIB2
570/// bitmap); a variable that covers its grid declares none and passes through
571/// untouched. Runs before unit conversion, on the raw record values — the
572/// port of `_fill_missing` in `xuebuild/binconvert.py`.
573fn fill_missing(spec: &VariableSpec, plane: &mut [f64]) {
574    if spec.fill_values.is_empty() {
575        return;
576    }
577    PlaneSource {
578        unscale: false,
579        fill_values: spec.fill_values.clone(),
580        fill_nan: false,
581        fill_replacement: spec.value_range.0,
582    }
583    .apply_fill(plane);
584}
585
586// -- per-file quantization ---------------------------------------------------
587
588#[derive(Debug, Clone)]
589pub(super) struct PlaneStats {
590    pub variable_id: String,
591    pub max_abs_error: f64,
592    pub clamped_points: u64,
593    pub overflow_points: u64,
594}
595
596/// A raw precipitation plane one file publishes for its successor to
597/// difference against. Filled once, read once, then dropped.
598#[derive(Default)]
599struct PlaneSlot {
600    state: Mutex<Option<std::result::Result<Arc<Vec<f64>>, String>>>,
601    ready: Condvar,
602}
603
604impl PlaneSlot {
605    fn publish(&self, value: std::result::Result<Arc<Vec<f64>>, String>) {
606        *self.state.lock().expect("plane slot") = Some(value);
607        self.ready.notify_all();
608    }
609
610    fn wait(&self) -> Result<Arc<Vec<f64>>> {
611        let mut state = self.state.lock().expect("plane slot");
612        while state.is_none() {
613            state = self.ready.wait(state).expect("plane slot");
614        }
615        state.clone().expect("published").map_err(EncodeError)
616    }
617}
618
619/// A bundle's series store (`_series_source` in the reference): the map
620/// store's codes and metadata exactly where no variable of the bundle is
621/// widened; otherwise each widened variable's spooled sixteen-bit planes on
622/// the bundle's axis, under its series codebook in the store's metadata.
623fn write_series_store(
624    codes: &zarrstore::StoreCodes<'_>,
625    variables: &[&str],
626    bundle_offsets: &[i64],
627    spool: Option<&SeriesSpool>,
628    path: &Path,
629    pool: &rayon::ThreadPool,
630) -> Result<zarrstore::StoreReport> {
631    let widened: Vec<&str> = variables
632        .iter()
633        .copied()
634        .filter(|variable_id| spool.is_some_and(|spool| spool.contains(variable_id)))
635        .collect();
636    let Some(spool) = spool.filter(|_| !widened.is_empty()) else {
637        return zarrstore::write_store(codes, path, true, Some(zarrstore::SERIES_BLOCK), pool);
638    };
639    let quantizations: Vec<(&str, Map<String, Value>)> = widened
640        .iter()
641        .map(|variable_id| {
642            (
643                *variable_id,
644                spool.codebook(variable_id).expect("spooled").metadata(),
645            )
646        })
647        .collect();
648    let metadata = zarrstore::series_metadata(codes.metadata, &quantizations);
649    let planes = widened
650        .iter()
651        .map(|variable_id| spool.planes(variable_id, bundle_offsets))
652        .collect::<Result<Vec<_>>>()?;
653    let wide: Vec<zarrstore::WideVariable<'_>> = widened
654        .iter()
655        .zip(&planes)
656        .map(|(variable_id, planes)| zarrstore::WideVariable {
657            id: (*variable_id).to_owned(),
658            codes: planes,
659        })
660        .collect();
661    let series_codes = zarrstore::StoreCodes {
662        metadata: &metadata,
663        variables: codes
664            .variables
665            .iter()
666            .map(|variable| zarrstore::StoreVariable {
667                id: variable.id.clone(),
668                previous: variable.previous,
669                planes: if widened.contains(&variable.id.as_str()) {
670                    Vec::new()
671                } else {
672                    variable.planes.clone()
673                },
674            })
675            .collect(),
676        tile: codes.tile,
677    };
678    zarrstore::write_store_widened(
679        &series_codes,
680        &wide,
681        path,
682        true,
683        Some(zarrstore::SERIES_BLOCK),
684        pool,
685    )
686}
687
688/// One file's quantized planes: its lead time, the codes per variable, and the
689/// per-variable quantization statistics the acceptance gate reads.
690type QuantizedFile = (i64, Vec<(String, Vec<u8>)>, Vec<PlaneStats>);
691
692/// The precipitation rate the per-file stage derives on a source whose
693/// precipitation arrives accumulated, averaged, as an interval total or
694/// as a window's: `(bundle id, raw input id)`
695/// (`Registry::derived_precipitation`).
696type DerivedPrecipitation = (String, String);
697
698#[allow(clippy::too_many_arguments)]
699fn quantize_file(
700    frames: &FileFrames,
701    grids: &PlaneGrids,
702    profile: &str,
703    plane_source: &PlaneSources,
704    source: &SourceSpec,
705    precipitation: Option<&DerivedPrecipitation>,
706    interval_pairs: &[DerivedPrecipitation],
707    interval_start: Option<i64>,
708    previous: Option<(i64, Option<Arc<PlaneSlot>>)>,
709    own: Option<Arc<PlaneSlot>>,
710    derived_vector_ids: &[&str],
711    drop_ids: &[String],
712    derived_scalar_ids: &[&str],
713    rotated_vector_ids: &[&str],
714    registry: &Registry,
715    series_spool: Option<&SeriesSpool>,
716) -> Result<QuantizedFile> {
717    let lead = frames[0].1.lead_seconds;
718    // The precipitation derivations below are GRIB-only, and every GRIB record
719    // is a whole hour out, so they can work in hours.
720    let hour = lead / HOUR_SECONDS;
721
722    // A derivation reading neighbours (the turbulence index) takes its
723    // inputs whole, before any crop.
724    let mut uncropped_ids: Vec<String> = Vec::new();
725    for bundle_id in derived_scalar_ids {
726        let Some(derivation) = registry.scalar_derivation(bundle_id) else {
727            continue;
728        };
729        if derivation.kind != DerivationKind::ClearAirTurbulence {
730            continue;
731        }
732        for id in &derivation.inputs {
733            if !uncropped_ids.contains(id) {
734                uncropped_ids.push(id.clone());
735            }
736        }
737    }
738    let (extracted, uncropped) =
739        match extract_planes(frames, grids, plane_source, &uncropped_ids, registry) {
740            Ok(planes) => planes,
741            Err(error) => {
742                // Unblock the successor waiting on this worker's plane.
743                if let Some(slot) = own {
744                    slot.publish(Err(error.to_string()));
745                }
746                return Err(error);
747            }
748        };
749    let mut values: Vec<(String, Vec<f64>)> = extracted;
750
751    let raw_precipitation_id = precipitation
752        .filter(|(_, raw_id)| values.iter().any(|(name, _)| name == raw_id))
753        .map(|(_, raw_id)| raw_id.as_str());
754    if let (Some(slot), Some(raw_id)) = (own, raw_precipitation_id) {
755        let plane = values
756            .iter()
757            .find(|(name, _)| name == raw_id)
758            .map(|(_, plane)| Arc::new(plane.clone()))
759            .expect("published raw precipitation plane");
760        slot.publish(Ok(plane));
761    }
762    let mut previous_plane: Option<Arc<Vec<f64>>> = None;
763    let mut previous_hour: Option<i64> = None;
764    if let Some((hour, slot)) = previous {
765        previous_hour = Some(hour);
766        // An interval total names its interval's start without a plane
767        // behind it (`sharing_plan`).
768        previous_plane = match slot {
769            Some(slot) => Some(slot.wait()?),
770            None => None,
771        };
772    }
773
774    if let (Some(raw_id), Some((bundle_id, _))) = (raw_precipitation_id, precipitation) {
775        let position = values
776            .iter()
777            .position(|(name, _)| name == raw_id)
778            .expect("raw precipitation plane");
779        let (_, raw) = values.remove(position);
780        let derived = if source.accumulated_precipitation {
781            // ECMWF: replace the run-total accumulation (already mm) with the
782            // mean rate over the step that ends at this frame (mm/h). The step
783            // is the actual distance to the previous frame.
784            // The two totals are first put on one packing lattice.
785            let step = previous_hour.map_or(1, |previous| hour - previous);
786            let (current_total, previous_total) =
787                align_packing_steps(&raw, previous_plane.as_deref().map(Vec::as_slice));
788            deaccumulate_precipitation(&current_total, previous_total.as_deref(), step)
789        } else if source.interval_precipitation {
790            // Open-Meteo: the file already holds the total that fell over the
791            // interval since the model's previous native output time, so the
792            // rate is that total over the interval's length in hours — the
793            // distance to the frame before this one on the axis.
794            let previous_hour = previous_hour.ok_or_else(|| {
795                EncodeError::conversion(format!(
796                    "the interval precipitation frame at hour {hour} names no interval"
797                ))
798            })?;
799            interval_rate(&raw, hour - previous_hour)?
800        } else if source.windowed_precipitation {
801            // The NAM: APCP is the total (mm) since the start of a window
802            // that resets every twelve hours; derive the per-step rate
803            // against the previous frame of the same window.
804            dewindow_precipitation(
805                &raw,
806                hour,
807                previous_plane.as_deref().map(Vec::as_slice),
808                previous_hour,
809                source.accumulation_window_hours,
810            )?
811        } else {
812            // sflux: PRATE is the window-cumulative mean rate (kg/m^2 s);
813            // derive the per-step rate against the previous frame of the same
814            // averaging window.
815            deaverage_precipitation(
816                &raw,
817                hour,
818                previous_plane.as_deref().map(Vec::as_slice),
819                previous_hour,
820                source.average_window_hours,
821            )?
822        };
823        values.insert(position, (bundle_id.clone(), derived));
824    }
825    // The further interval totals, each to its rate the way the one above
826    // is, over the same interval.
827    for (rate_id, total_id) in interval_pairs {
828        let Some(position) = values.iter().position(|(name, _)| name == total_id) else {
829            continue;
830        };
831        let interval_start = interval_start.ok_or_else(|| {
832            EncodeError::conversion(format!(
833                "the interval precipitation frame at hour {hour} names no interval"
834            ))
835        })?;
836        let (_, total) = values.remove(position);
837        values.insert(
838            position,
839            (
840                rate_id.clone(),
841                interval_rate(&total, hour - interval_start)?,
842            ),
843        );
844    }
845
846    // Grid-relative pairs turned to east and north once the extraction has cut
847    // any window: the rotation reads the plane's own grid, so it is the same
848    // cell's wind whichever window it is cut from, and everything from
849    // quantization on, the ladder's decimation among it, sees a wind in earth
850    // terms.
851    for bundle_id in rotated_vector_ids {
852        let (u_id, v_id) = registry.vector_components(bundle_id).ok_or_else(|| {
853            EncodeError::conversion(format!("{bundle_id} is not a vector bundle"))
854        })?;
855        let projection = grids.for_variable(u_id)?.projection.ok_or_else(|| {
856            EncodeError::conversion(format!(
857                "{bundle_id} has grid-relative winds on a regular grid"
858            ))
859        })?;
860        let position = |name: &str| {
861            values.iter().position(|(id, _)| id == name).ok_or_else(|| {
862                EncodeError::conversion(format!("missing {name} plane for {bundle_id}"))
863            })
864        };
865        let (u_at, v_at) = (position(u_id)?, position(v_id)?);
866        let mut u = std::mem::take(&mut values[u_at].1);
867        let mut v = std::mem::take(&mut values[v_at].1);
868        rotate_winds(&projection, &mut u, &mut v)?;
869        values[u_at].1 = u;
870        values[v_at].1 = v;
871    }
872
873    // The derived vector bundles — the vapour flux, the wave vector — from
874    // the planes just extracted; the inputs that served only such a
875    // derivation (and are not published themselves) are released here
876    // rather than quantized and carried through the whole run.
877    for bundle_id in derived_vector_ids {
878        let derivation = registry.derivation(bundle_id).ok_or_else(|| {
879            EncodeError::conversion(format!("{bundle_id} is not a derived bundle"))
880        })?;
881        let inputs = &derivation.inputs;
882        let plane = |name: &str| -> Result<&Vec<f64>> {
883            values
884                .iter()
885                .find(|(id, _)| id == name)
886                .map(|(_, plane)| plane)
887                .ok_or_else(|| {
888                    EncodeError::conversion(format!("missing {name} plane for {bundle_id}"))
889                })
890        };
891        let (component_u, component_v) = match derivation.kind {
892            DerivationKind::WaveVector => derive_wave_vector(plane(&inputs[0])?, plane(&inputs[1])?),
893            DerivationKind::VapourFlux => {
894                derive_vapour_flux(plane(&inputs[0])?, plane(&inputs[1])?, plane(&inputs[2])?)
895            }
896            other => {
897                return Err(EncodeError::conversion(format!(
898                    "{bundle_id} is a vector bundle derived by {other:?}, which is not a vector algorithm"
899                )))
900            }
901        };
902        let (u_id, v_id) = registry
903            .vector_components(bundle_id)
904            .expect("a derived vector bundle is a vector");
905        values.push((u_id.to_string(), component_u));
906        values.push((v_id.to_string(), component_v));
907    }
908    // The derived scalars, after the vapour flux and before the
909    // derivation-only inputs go: the equivalent potential temperatures read
910    // the specific humidity on their surface, the precipitation type the four
911    // categorical flags.
912    for bundle_id in derived_scalar_ids {
913        let derivation = registry.scalar_derivation(bundle_id).ok_or_else(|| {
914            EncodeError::conversion(format!("{bundle_id} is not a derived scalar"))
915        })?;
916        let inputs = &derivation.inputs;
917        let derived = match derivation.kind {
918            DerivationKind::PrecipitationType => derive_ptype(&values, inputs)?,
919            DerivationKind::ClearAirTurbulence => {
920                let level = derivation.level_hpa.expect("validated: a surface");
921                let grid = grids.for_variable(&inputs[0])?;
922                // A cropped grid's inputs were kept whole beside the window;
923                // an uncropped grid's published planes are the whole planes.
924                let plane = |name: &str| -> Result<&[f64]> {
925                    uncropped
926                        .iter()
927                        .chain(values.iter())
928                        .find(|(id, _)| id == name)
929                        .map(|(_, plane)| plane.as_slice())
930                        .ok_or_else(|| EncodeError::conversion(format!("missing {name} plane for {bundle_id}")))
931                };
932                derive_cat_plane(plane, bundle_id, level, inputs, grid, &source.cat_calibration)?
933            }
934            DerivationKind::ThetaE => {
935                let level = derivation.level_hpa.expect("validated: a surface");
936                let plane = |name: &str| -> Result<&Vec<f64>> {
937                    values
938                        .iter()
939                        .find(|(id, _)| id == name)
940                        .map(|(_, plane)| plane)
941                        .ok_or_else(|| EncodeError::conversion(format!("missing {name} plane for {bundle_id}")))
942                };
943                derive_theta_e(plane(&inputs[0])?, plane(&inputs[1])?, level)
944            }
945            other => {
946                return Err(EncodeError::conversion(format!(
947                    "{bundle_id} is a scalar bundle derived by {other:?}, which is not a per-frame algorithm"
948                )))
949            }
950        };
951        values.push(((*bundle_id).to_string(), derived));
952    }
953    values.retain(|(name, _)| !drop_ids.contains(name));
954
955    let mut codes = Vec::with_capacity(values.len());
956    let mut stats = Vec::with_capacity(values.len());
957    for (variable_id, plane_values) in &values {
958        let book = registry.codebook(profile, variable_id)?;
959        let mut plane_codes = vec![0u8; plane_values.len()];
960        book.quantize(plane_values, &mut plane_codes)?;
961        match &book.book {
962            Book::Linear(linear) => {
963                let mut clamped = 0u64;
964                let mut max_error = 0.0f64;
965                for (value, code) in plane_values.iter().zip(&plane_codes) {
966                    if *value < linear.minimum || *value > linear.maximum {
967                        clamped += 1;
968                    } else {
969                        max_error = max_error.max((linear.decode(*code) - value).abs());
970                    }
971                }
972                stats.push(PlaneStats {
973                    variable_id: variable_id.clone(),
974                    max_abs_error: max_error,
975                    clamped_points: clamped,
976                    overflow_points: 0,
977                });
978            }
979            Book::Precipitation(precipitation) => {
980                let overflow = plane_codes
981                    .iter()
982                    .filter(|code| u16::from(**code) == precipitation.overflow_code)
983                    .count() as u64;
984                stats.push(PlaneStats {
985                    variable_id: variable_id.clone(),
986                    max_abs_error: 0.0,
987                    clamped_points: 0,
988                    overflow_points: overflow,
989                });
990            }
991        }
992        codes.push((variable_id.clone(), plane_codes));
993        // A widened variable is quantized a second time, from the same float
994        // plane, under its series codebook, and the sixteen-bit codes go
995        // straight to the spool: never derived from the byte codes, whose
996        // rounding they would inherit.
997        if let Some(spool) = series_spool.filter(|spool| spool.contains(variable_id)) {
998            spool.quantize_and_write(variable_id, lead, plane_values)?;
999        }
1000    }
1001    Ok((lead, codes, stats))
1002}
1003
1004// -- payload assembly --------------------------------------------------------
1005
1006/// The v2 index tables and uncompressed chunks of one bundle.
1007///
1008/// Every variable of a bundle shares the file's one axis and therefore its
1009/// temporal groups, and the chunks come out in the physical order the spec
1010/// fixes — group, then tile row-major, then variable. That order is what puts
1011/// the two components of the wind bundle next to each other inside a tile, so
1012/// one range request still covers a wind frame while a viewport's tile row
1013/// and a cell's series each stay one narrow span.
1014///
1015/// `variableId` is file-local and assigned here exactly the way
1016/// [`build_metadata`](crate::encode::metadata::build_metadata) assigns it —
1017/// 1..n by position in `variable_ids` — so the index and the metadata agree
1018/// by construction, and the ascending id order the spec fixes is the bundle's
1019/// own variable order.
1020fn bundle_chunks(
1021    variable_ids: &[&str],
1022    offsets: &[i64],
1023    codes: &BTreeMap<i64, Vec<(String, Vec<u8>)>>,
1024    geometry: &TileGeometry,
1025    registry: &Registry,
1026) -> Result<ChunkTables> {
1027    let mut variables: Vec<VariableEntry> = Vec::with_capacity(variable_ids.len());
1028    for (index, variable_id) in variable_ids.iter().enumerate() {
1029        variables.push(VariableEntry {
1030            variable_id: index as u8 + 1,
1031            predictor: if registry.is_raw(variable_id)? {
1032                Predictor::Raw
1033            } else {
1034                Predictor::Previous
1035            },
1036        });
1037    }
1038
1039    // Numeric id back to the name the code planes are keyed by.
1040    let names: BTreeMap<u8, &str> = variable_ids
1041        .iter()
1042        .enumerate()
1043        .map(|(index, variable_id)| (index as u8 + 1, *variable_id))
1044        .collect();
1045    let plane = |offset: i64, variable_id: u8| -> Result<&[u8]> {
1046        let name = names[&variable_id];
1047        codes
1048            .get(&offset)
1049            .and_then(|planes| planes.iter().find(|(id, _)| id == name))
1050            .map(|(_, plane)| plane.as_slice())
1051            .ok_or_else(|| {
1052                EncodeError::conversion(format!("missing {name} plane at offset {offset}"))
1053            })
1054    };
1055    let (groups, raw) = build_chunks(offsets, &variables, &plane, geometry)?;
1056    Ok(ChunkTables {
1057        variables,
1058        groups,
1059        chunks: raw
1060            .into_iter()
1061            .map(|(entry, payload)| ChunkPayload { entry, payload })
1062            .collect(),
1063    })
1064}
1065
1066fn crc32_hex(bytes: &[u8]) -> String {
1067    format!("{:08x}", binformat::crc32_plane(bytes))
1068}
1069
1070// -- bundle writing ----------------------------------------------------------
1071
1072/// Tiers written at once; the compression pool bounds the CPU, this bounds
1073/// how many tiers' chunks are alive. Mirrors `_BUNDLE_WRITERS`.
1074const BUNDLE_WRITERS: usize = 4;
1075
1076fn write_variable_bundle(
1077    variable_id: &str,
1078    output: &Path,
1079    metadata: &Value,
1080    geometry: &TileGeometry,
1081    tables: ChunkTables,
1082    frame_count: u32,
1083    zstd_level: i32,
1084    options: &ConvertOptions,
1085    pool: &rayon::ThreadPool,
1086) -> Result<Value> {
1087    log!(
1088        options,
1089        "compressing {} {variable_id} chunks at zstd level {zstd_level}",
1090        tables.chunks.len()
1091    );
1092    let tables = compress_all(tables, zstd_level, pool)?;
1093    let metadata_json = serde_json::to_string(metadata).expect("serializable metadata");
1094    let bundle_bytes =
1095        binformat::write_bundle_v2(output, &metadata_json, geometry, &tables, frame_count)?;
1096    log!(
1097        options,
1098        "wrote {} ({:.2} MB)",
1099        output.display(),
1100        bundle_bytes.len() as f64 / 1e6
1101    );
1102
1103    // Read the complete file back and reconstruct every chunk before
1104    // publishing stats — the same acceptance gate the Python encoder applies,
1105    // run through the production decoder crate.
1106    verify_bundle_bytes(&bundle_bytes)?;
1107    log!(
1108        options,
1109        "verified {} {variable_id} chunks by full read-back decode",
1110        tables.chunks.len()
1111    );
1112
1113    let mut report = Map::new();
1114    report.insert("variable".into(), json!(variable_id));
1115    report.insert("output".into(), json!(output.display().to_string()));
1116    report.insert("byteLength".into(), json!(bundle_bytes.len()));
1117    report.insert("crc32".into(), json!(crc32_hex(&bundle_bytes)));
1118    Ok(Value::Object(report))
1119}
1120
1121fn compress_all(
1122    tables: ChunkTables,
1123    zstd_level: i32,
1124    pool: &rayon::ThreadPool,
1125) -> Result<ChunkTables> {
1126    use rayon::prelude::*;
1127
1128    let ChunkTables {
1129        variables,
1130        groups,
1131        chunks,
1132    } = tables;
1133    let chunks = pool.install(|| {
1134        chunks
1135            .into_par_iter()
1136            .map(|chunk| {
1137                let payload = zstd_compress(&chunk.payload, zstd_level)?;
1138                Ok(ChunkPayload {
1139                    entry: ChunkEntry {
1140                        compressed_length: payload.len() as u32,
1141                        crc32: chunk.entry.crc32,
1142                    },
1143                    payload,
1144                })
1145            })
1146            .collect::<Result<Vec<_>>>()
1147    })?;
1148    Ok(ChunkTables {
1149        variables,
1150        groups,
1151        chunks,
1152    })
1153}
1154
1155pub(crate) fn zstd_compress(payload: &[u8], level: i32) -> Result<Vec<u8>> {
1156    // One-shot `ZSTD_compress2` with an explicit checksum, which is what the
1157    // Python encoder's `compression.zstd.compress` calls. The streaming
1158    // encoder would produce a frame without the pledged source size and pick
1159    // different window parameters, so the two would not agree byte for byte.
1160    use zstd::zstd_safe::{CCtx, CParameter};
1161
1162    let mut context = CCtx::create();
1163    for parameter in [
1164        CParameter::CompressionLevel(level),
1165        CParameter::ChecksumFlag(true),
1166    ] {
1167        context.set_parameter(parameter).map_err(|code| {
1168            EncodeError::conversion(format!("zstd parameter rejected: {}", error_name(code)))
1169        })?;
1170    }
1171    let mut output = Vec::with_capacity(zstd::zstd_safe::compress_bound(payload.len()));
1172    context.compress2(&mut output, payload).map_err(|code| {
1173        EncodeError::conversion(format!("zstd compression failed: {}", error_name(code)))
1174    })?;
1175    Ok(output)
1176}
1177
1178fn error_name(code: usize) -> &'static str {
1179    zstd::zstd_safe::get_error_name(code)
1180}
1181
1182/// Decode every plane of a freshly written bundle with the decoder crate.
1183fn verify_bundle_bytes(bytes: &[u8]) -> Result<()> {
1184    let mut bundle = crate::Bundle::open(bytes)
1185        .map_err(|error| EncodeError::bundle(format!("read-back parse failed: {}", error.0)))?;
1186    let variables: Vec<u8> = bundle.variable_ids().to_vec();
1187    let offsets: Vec<u16> = bundle.frame_offsets().to_vec();
1188    for variable_id in variables {
1189        for frame_offset in &offsets {
1190            match bundle.decode_frame(crate::FrameRequest {
1191                variable_id,
1192                frame_offset: *frame_offset,
1193            }) {
1194                Ok(_) => {}
1195                Err(error) => {
1196                    // A variable need not carry every offset on the bundle's
1197                    // axis only when the bundle mixes axes, which the encoder
1198                    // never writes; anything else is a real failure.
1199                    return Err(EncodeError::bundle(format!(
1200                        "read-back decode failed for variable {variable_id} at offset {frame_offset}: {}",
1201                        error.0
1202                    )));
1203                }
1204            }
1205        }
1206    }
1207    Ok(())
1208}
1209
1210// -- the conversion ----------------------------------------------------------
1211
1212/// The offsets of `offsets` a bundle read from a cadenced input keeps: the
1213/// whole hours at which every input is carried
1214/// (`Registry::bundle_carried_at`). Empty when the build ends before the
1215/// first such hour. Mirrors the cadence cut of `_variable_offsets` in
1216/// `xuebuild/binconvert.py`.
1217fn cadence_offsets(
1218    registry: &Registry,
1219    source: &SourceSpec,
1220    bundle_id: &str,
1221    offsets: &[i64],
1222    unit_seconds: i64,
1223) -> Vec<i64> {
1224    offsets
1225        .iter()
1226        .copied()
1227        .filter(|offset| {
1228            let seconds = offset * unit_seconds;
1229            seconds % HOUR_SECONDS == 0
1230                && registry.bundle_carried_at(source, bundle_id, seconds / HOUR_SECONDS)
1231        })
1232        .collect()
1233}
1234
1235/// Whether this encoder builds `options.model` from `registry` with the
1236/// profile and bundles `options` asks for, decided from the document alone:
1237/// the source, the profile, a codebook for every published variable and the
1238/// requested bundles. Nothing is read or written. `convert_bin` runs it
1239/// first, so a build and the question asked before it cannot disagree.
1240pub fn validate_build<'a>(
1241    options: &ConvertOptions,
1242    registry: &'a Registry,
1243) -> Result<(&'a SourceSpec, Vec<&'a str>)> {
1244    let source = registry.source(&options.model)?;
1245    if !registry.knows_profile(&options.profile) {
1246        return Err(EncodeError::conversion(format!(
1247            "unknown profile: {}",
1248            options.profile
1249        )));
1250    }
1251    let published = registry.published_bundle_ids(source);
1252    // Every published variable must carry the profile asked for, and the
1253    // document is refused before any input is read when one does not.
1254    for bundle_id in &published {
1255        for variable_id in registry.bundle_variable_ids(bundle_id) {
1256            registry.codebook(&options.profile, &variable_id)?;
1257        }
1258    }
1259    if let Some(bundle_ids) = &options.bundle_ids {
1260        let unsupported = bundle_ids
1261            .iter()
1262            .any(|id| !published.contains(&id.as_str()));
1263        if unsupported || bundle_ids.is_empty() {
1264            return Err(EncodeError::conversion(format!(
1265                "{} publishes {published:?}, not {bundle_ids:?}",
1266                source.manifest_model
1267            )));
1268        }
1269    }
1270    Ok((source, published))
1271}
1272
1273/// Convert a GRIB run (or one observation NetCDF file) into per-variable Xue
1274/// bundles.
1275///
1276/// Writes `<output_dir>/<variable>.xue` for every scalar variable plus the
1277/// two-variable `wind10m.xue` bundle when the input files carry the 10 m wind
1278/// components, per-variable posters, the reduced `<bundle>.<tier>.xue`
1279/// variants of the source's resolution ladder (`.half.xue`, and `.quarter`
1280/// on the satellite disks), and returns build statistics. It writes no live
1281/// pointer: `xuebuild/native.py` writes that once the manifest is final.
1282///
1283/// `bbox` crops every plane to a region and `bundle_ids` restricts which
1284/// bundles are built — the two knobs the historical showcase cases use.
1285/// `last_hour` trims an observation source's series to a leading window.
1286///
1287/// The optional H.264 companion artifacts are not built here; this
1288/// experimental encoder leaves them to the Python pipeline, and the frontend
1289/// treats them as optional by design.
1290pub fn convert_bin(
1291    inputs: &[PathBuf],
1292    output_dir: &Path,
1293    options: &ConvertOptions,
1294    registry: &Registry,
1295) -> Result<Value> {
1296    if !options.container && !options.zarr {
1297        return Err(EncodeError::conversion(
1298            "a build without the container needs the store: pass zarr=True",
1299        ));
1300    }
1301    let (source, published) = validate_build(options, registry)?;
1302
1303    // -- frame discovery ----------------------------------------------------
1304    let Discovered {
1305        per_file,
1306        variable_ids,
1307        available_vector_ids,
1308        available_derived_ids,
1309        available_composite_ids,
1310        available_volume_ids,
1311        drop_ids,
1312        grid_path,
1313        plane_source,
1314        producer_versions,
1315        mut variable_families,
1316    } = if source.series_file {
1317        discover_series(inputs, options, source, &published, registry)?
1318    } else {
1319        discover_records(inputs, options, source, &published, registry)?
1320    };
1321
1322    // -- the time axis ------------------------------------------------------
1323    let reference_id = variable_ids[0].as_str();
1324    let lead_seconds: Vec<i64> = per_file
1325        .iter()
1326        .map(|frames| {
1327            frame_of(frames, reference_id)
1328                .map(|frame| frame.lead_seconds)
1329                .ok_or_else(|| EncodeError::conversion(format!("missing {reference_id} record")))
1330        })
1331        .collect::<Result<_>>()?;
1332    let unit_seconds = axis_unit_seconds(&lead_seconds);
1333    let offsets: Vec<i64> = lead_seconds
1334        .iter()
1335        .map(|seconds| seconds / unit_seconds)
1336        .collect();
1337    if *offsets.last().expect("non-empty axis") >= i64::from(NO_DEPENDENCY) {
1338        return Err(EncodeError::conversion(format!(
1339            "the axis needs {} steps of {unit_seconds} s, past the u16 frame offset range",
1340            offsets.last().expect("non-empty axis")
1341        )));
1342    }
1343    let run_time: OffsetDateTime = frame_of(&per_file[0], reference_id)
1344        .expect("reference frame")
1345        .run_time
1346        .to_offset(time::UtcOffset::UTC);
1347    if !source.observation {
1348        // The input hours must be a contiguous run of the source's published
1349        // axis, so no frame is missing and every step matches the cadence.
1350        // The run's own cycle decides whether a longer axis applies.
1351        let cycle = Some(u32::from(run_time.hour()));
1352        let axis = source.forecast_hours(*offsets.last().expect("non-empty axis"), cycle)?;
1353        let tail: Vec<i64> = axis
1354            .iter()
1355            .copied()
1356            .filter(|hour| *hour >= offsets[0])
1357            .collect();
1358        if offsets != tail {
1359            return Err(EncodeError::conversion(format!(
1360                "forecast hours must be a contiguous run of the {} axis",
1361                source.manifest_model
1362            )));
1363        }
1364        if options.require_complete {
1365            let expected = source.forecast_hours(options.expected_hours, cycle)?;
1366            if offsets != expected {
1367                return Err(EncodeError::conversion(format!(
1368                    "complete build requires forecast hours 0 through {} on the {} axis",
1369                    options.expected_hours, source.manifest_model
1370                )));
1371            }
1372        }
1373    }
1374
1375    // -- the grid -----------------------------------------------------------
1376    // Every published variable's grid family: for a variable the converter
1377    // derives (the vapour flux pair, the rate) the family its bundle's inputs
1378    // are read from, for one it reads its own. `None` throughout on every
1379    // source but CFSv2, so there is one family and one grid as there always
1380    // was.
1381    for bundle_id in registry.published_bundle_ids(source) {
1382        let family = bundle_grid_family(registry, source, bundle_id)?;
1383        for variable_id in registry.bundle_variable_ids(bundle_id) {
1384            variable_families.retain(|(id, _)| *id != variable_id);
1385            variable_families.push((variable_id, family));
1386        }
1387    }
1388    let family_of = |variable_id: &str| -> Option<&str> {
1389        variable_families
1390            .iter()
1391            .find(|(id, _)| id == variable_id)
1392            .and_then(|(_, family)| *family)
1393    };
1394    // One grid per family in play, each read from that family's own file and
1395    // checked against that family's production grid. The families are in
1396    // input order, so the primary file's — the run's grid in the build report
1397    // — comes first wherever this build reads it at all.
1398    let mut family_order: Vec<Option<&str>> = Vec::new();
1399    for variable_id in &variable_ids {
1400        let family = family_of(variable_id);
1401        if !family_order.contains(&family) {
1402            family_order.push(family);
1403        }
1404    }
1405    let mut grids: Vec<(Option<&str>, GridInfo)> = Vec::new();
1406    for family in &family_order {
1407        let mut family_grid = grid_info(&family_frame_path(&grid_path, *family), source, *family)?;
1408        if options.require_complete {
1409            let (production_grid, _) = source.family_grid(*family)?;
1410            if (family_grid.width, family_grid.height) != production_grid {
1411                let where_ = match family {
1412                    Some(family) => format!(" for the {family} family"),
1413                    None => String::new(),
1414                };
1415                return Err(EncodeError::conversion(format!(
1416                    "production build requires a {}x{} grid{where_}",
1417                    production_grid.0, production_grid.1
1418                )));
1419            }
1420        }
1421        if let Some(bbox) = options.bbox {
1422            family_grid = crop_grid(family_grid, bbox)?;
1423            log!(
1424                options,
1425                "cropped {} to {}x{} ({bbox:?})",
1426                family.unwrap_or("the run"),
1427                family_grid.width,
1428                family_grid.height
1429            );
1430        }
1431        grids.push((*family, family_grid));
1432    }
1433    let grid_for = |family: Option<&str>| -> &GridInfo {
1434        &grids
1435            .iter()
1436            .find(|(held, _)| *held == family)
1437            .expect("every family in play has a grid")
1438            .1
1439    };
1440    // The run-level grid — the build report's, and the one every source with
1441    // a single grid uses throughout.
1442    let grid = grid_for(family_order[0]).clone();
1443    // The grid each variable's planes are read and cropped on.
1444    let read_grids = PlaneGrids(
1445        variable_ids
1446            .iter()
1447            .map(|variable_id| {
1448                (
1449                    variable_id.clone(),
1450                    grid_for(family_of(variable_id)).clone(),
1451                )
1452            })
1453            .collect(),
1454    );
1455
1456    // -- extract and quantize ------------------------------------------------
1457    log!(
1458        options,
1459        "extracting and quantizing {} files with {} workers",
1460        per_file.len(),
1461        options.extract_workers
1462    );
1463    // The rate the per-file stage derives, when this build reads its raw
1464    // input at all.
1465    let precipitation: Option<DerivedPrecipitation> = registry
1466        .derived_precipitation(source)?
1467        .filter(|(_, raw_id)| variable_ids.contains(raw_id));
1468    let plan = sharing_plan(
1469        &per_file,
1470        precipitation.as_ref().map(|(_, raw_id)| raw_id.as_str()),
1471        source,
1472    )?;
1473    // The further rates an interval source derives, whose totals this build
1474    // reads, and each file's interval where it holds one of those totals.
1475    let interval_pairs: Vec<DerivedPrecipitation> = registry
1476        .interval_precipitation_pairs(source)
1477        .into_iter()
1478        .filter(|(_, total_id)| variable_ids.contains(total_id))
1479        .collect();
1480    let interval_starts: Vec<Option<i64>> = per_file
1481        .iter()
1482        .enumerate()
1483        .map(|(index, frames)| {
1484            let held = interval_pairs
1485                .iter()
1486                .find_map(|(_, total_id)| frame_of(frames, total_id));
1487            held.map(|frame| interval_start(&per_file, index, frame, source))
1488                .transpose()
1489        })
1490        .collect::<Result<_>>()?;
1491    let derived_vector_ids: Vec<&str> = available_vector_ids
1492        .iter()
1493        .copied()
1494        .filter(|bundle_id| registry.is_derived_vector(bundle_id))
1495        .collect();
1496    let derived_scalar_ids: Vec<&str> = available_derived_ids.clone();
1497    let rotated_vector_ids = grid_relative_vectors(registry, source, &available_vector_ids)?;
1498    // The series stores' sixteen-bit codes, spooled to files as each file is
1499    // quantized and read back a block row at a time when the series stores
1500    // are written; removed with the spool, on every way out of the build.
1501    // The system temporary directory, never the output: a publish uploads
1502    // that directory, and a build killed outright would leave the spool in it.
1503    let widened = if options.zarr {
1504        registry.series_widened_ids(&options.series_bundle_ids, options.bundle_ids.as_deref())
1505    } else {
1506        Vec::new()
1507    };
1508    let series_spool = SeriesSpool::create(
1509        &std::env::temp_dir(),
1510        widened
1511            .iter()
1512            .map(|variable_id| {
1513                let grid = grid_for(family_of(variable_id));
1514                let codebook = registry
1515                    .series_codebook(variable_id)
1516                    .expect("a widened variable has one")
1517                    .clone();
1518                (variable_id.clone(), codebook, grid.width * grid.height)
1519            })
1520            .collect(),
1521        &offsets,
1522        unit_seconds,
1523    )?;
1524    let results = for_each_ordered(per_file.len(), options.extract_workers, |index| {
1525        let (previous, own) = plan[index].clone();
1526        quantize_file(
1527            &per_file[index],
1528            &read_grids,
1529            &options.profile,
1530            &plane_source,
1531            source,
1532            precipitation.as_ref(),
1533            &interval_pairs,
1534            interval_starts[index],
1535            previous,
1536            own,
1537            &derived_vector_ids,
1538            &drop_ids,
1539            &derived_scalar_ids,
1540            &rotated_vector_ids,
1541            registry,
1542            series_spool.as_ref(),
1543        )
1544    })?;
1545
1546    let mut stats: Vec<PlaneStats> = Vec::new();
1547    let mut codes_by_offset: BTreeMap<i64, Vec<(String, Vec<u8>)>> = BTreeMap::new();
1548    for (lead, codes, file_stats) in results {
1549        codes_by_offset.insert(lead / unit_seconds, codes);
1550        stats.extend(file_stats);
1551    }
1552    log!(
1553        options,
1554        "quantized {} planes",
1555        codes_by_offset.values().map(Vec::len).sum::<usize>()
1556    );
1557
1558    // -- what gets published -------------------------------------------------
1559    // A derived scalar whose inputs the run lacked is left out like a vector
1560    // bundle is.
1561    let mut scalar_variable_ids: Vec<&str> = source
1562        .bundle_scalar_ids
1563        .iter()
1564        .map(String::as_str)
1565        .filter(|id| registry.scalar_derivation(id).is_none() || available_derived_ids.contains(id))
1566        .collect();
1567    if let Some(bundle_ids) = &options.bundle_ids {
1568        scalar_variable_ids.retain(|id| bundle_ids.iter().any(|wanted| wanted == id));
1569    }
1570    let mut encoded_variable_ids: Vec<String> = scalar_variable_ids
1571        .iter()
1572        .map(|id| (*id).to_string())
1573        .collect();
1574    for bundle_id in available_vector_ids
1575        .iter()
1576        .chain(&available_composite_ids)
1577        .chain(&available_volume_ids)
1578    {
1579        encoded_variable_ids.extend(registry.bundle_variable_ids(bundle_id));
1580    }
1581    // Scalars that also ship a poster — every published scalar whose entry
1582    // lists one; the contour-drawn pressure family lists none, since a
1583    // filled first-frame poster would misrepresent it. A `video` companion
1584    // names the retired H.264 artifact, which no encoder builds.
1585    let mut companion_variable_ids: Vec<&str> = scalar_variable_ids
1586        .iter()
1587        .copied()
1588        .filter(|id| {
1589            registry
1590                .variable(id)
1591                .is_ok_and(|spec| spec.companions.contains(&Companion::Poster))
1592        })
1593        .collect();
1594
1595    // Per-variable time axes. A variable with no data for the analysis frame
1596    // starts at the first real step, and every artifact of it carries its
1597    // own shorter axis: the rate on a derived-precipitation source, whose
1598    // interval would precede the run, and any scalar whose record the source
1599    // lists as optional at the analysis (ECMWF's gust). Mirrors
1600    // `analysis_optional_ids` in `xuebuild/discover.py`.
1601    let mut variable_offsets: BTreeMap<String, Vec<i64>> = encoded_variable_ids
1602        .iter()
1603        .map(|id| (id.clone(), offsets.clone()))
1604        .collect();
1605    // Only a run that starts at the analysis has an analysis frame to be
1606    // missing from: a build whose axis already starts at the first step (a
1607    // job for the rate alone on a source whose precipitation input has no
1608    // analysis file) carries every frame it read.
1609    if offsets.len() > 1 && offsets[0] == 0 {
1610        for variable_id in registry.analysis_optional_ids(source, &scalar_variable_ids) {
1611            variable_offsets.insert(variable_id.to_string(), offsets[1..].to_vec());
1612        }
1613    }
1614    // A variable absent before an hour of its own starts there, one written
1615    // only every so many hours keeps the hours on that cadence, and a bundle
1616    // with no frame left is left out of this build.
1617    let mut late_ids: Vec<String> = Vec::new();
1618    for bundle_id in &scalar_variable_ids {
1619        if !registry.bundle_is_cadenced(source, bundle_id) {
1620            continue;
1621        }
1622        let kept = cadence_offsets(
1623            registry,
1624            source,
1625            bundle_id,
1626            &variable_offsets[*bundle_id],
1627            unit_seconds,
1628        );
1629        if kept.is_empty() {
1630            late_ids.push((*bundle_id).to_string());
1631        } else {
1632            variable_offsets.insert((*bundle_id).to_string(), kept);
1633        }
1634    }
1635    if !late_ids.is_empty() {
1636        eprintln!(
1637            "WARNING building without {}, which start past the last frame of this run",
1638            late_ids.join(", ")
1639        );
1640        scalar_variable_ids.retain(|id| !late_ids.iter().any(|late| late == id));
1641        companion_variable_ids.retain(|id| !late_ids.iter().any(|late| late == id));
1642        encoded_variable_ids.retain(|id| !late_ids.contains(id));
1643        for id in &late_ids {
1644            variable_offsets.remove(id);
1645        }
1646    }
1647    // A static field does not vary in time: its one frame is the first, and
1648    // its bundle carries just that offset. Mirrors `_variable_offsets` in
1649    // `xuebuild/binconvert.py`.
1650    for variable_id in &encoded_variable_ids {
1651        if registry.is_static(variable_id) {
1652            variable_offsets.insert(variable_id.clone(), vec![offsets[0]]);
1653        }
1654    }
1655
1656    // -- posters --------------------------------------------------------------
1657    std::fs::create_dir_all(output_dir).map_err(|error| {
1658        EncodeError::conversion(format!("cannot create {}: {error}", output_dir.display()))
1659    })?;
1660    let mut poster_reports: BTreeMap<&str, Value> = BTreeMap::new();
1661    for variable_id in &companion_variable_ids {
1662        let first = variable_offsets[*variable_id][0];
1663        let plane = codes_by_offset[&first]
1664            .iter()
1665            .find(|(name, _)| name == variable_id)
1666            .map(|(_, plane)| plane)
1667            .ok_or_else(|| {
1668                EncodeError::conversion(format!("missing {variable_id} plane at the first frame"))
1669            })?;
1670        let (payload, poster_grid) = encode_poster(plane, grid_for(family_of(variable_id)))?;
1671        let poster_path = output_dir.join(format!("{variable_id}.poster.bin"));
1672        binformat::write_atomic(&poster_path, &payload)?;
1673        let metadata = build_metadata(
1674            run_time,
1675            &variable_offsets[*variable_id],
1676            &poster_grid,
1677            &options.profile,
1678            &[variable_id],
1679            source,
1680            unit_seconds,
1681            &producer_versions,
1682            registry,
1683        )?;
1684        poster_reports.insert(
1685            variable_id,
1686            json!({
1687                "path": poster_path.display().to_string(),
1688                "width": poster_grid.width,
1689                "height": poster_grid.height,
1690                "byteLength": payload.len(),
1691                "crc32": crc32_hex(&payload),
1692                "metadataJson": dumps_default(&metadata),
1693            }),
1694        );
1695        log!(
1696            options,
1697            "wrote {} ({:.1} KB)",
1698            poster_path.display(),
1699            payload.len() as f64 / 1e3
1700        );
1701    }
1702
1703    // -- bundles and the resolution ladder -------------------------------------
1704    // One rung per factor of the source's ladder, in ascending factor order
1705    // (half, quarter, eighth): its file suffix, factor, grid and the codes of
1706    // every plane sampled from the full ones. `skip_variants` skips every
1707    // rung.
1708    //
1709    // A source with more than one grid gets one rung per factor per family:
1710    // a family's rung is its own grid decimated, so a bundle's tier keeps the
1711    // tile geometry of its own grid.
1712    let ladder: Vec<Rung<'_>> = if options.skip_variants {
1713        Vec::new()
1714    } else {
1715        build_ladder(
1716            &source.variant_factors,
1717            &grids,
1718            &codes_by_offset,
1719            |name| grid_for(family_of(name)),
1720            &options.profile,
1721            registry,
1722        )?
1723    };
1724
1725    // Volume, composite and vector bundles first (the largest), scalars
1726    // after; reports keep the scalars-vectors-composites-volumes manifest
1727    // order regardless.
1728    let mut submit_order: Vec<&str> = available_volume_ids.clone();
1729    submit_order.extend_from_slice(&available_composite_ids);
1730    submit_order.extend_from_slice(&available_vector_ids);
1731    submit_order.extend_from_slice(&scalar_variable_ids);
1732    let mut report_order: Vec<&str> = scalar_variable_ids.clone();
1733    report_order.extend_from_slice(&available_vector_ids);
1734    report_order.extend_from_slice(&available_composite_ids);
1735    report_order.extend_from_slice(&available_volume_ids);
1736
1737    // Every tier of every bundle is one task: the full tier, then each rung
1738    // of the ladder, in submit order. Up to `BUNDLE_WRITERS` run at once over
1739    // one machine-sized compression pool, so one bundle's serial tail (its
1740    // file writes, its shard index, its container read-back) overlaps the
1741    // next one's compression — `_BUNDLE_WRITERS` in the reference. A tier's
1742    // reports come back in task order, so a bundle's variants stay in the
1743    // ladder's ascending factor order whatever finished first.
1744    let mut tiers: Vec<Tier<'_>> = Vec::new();
1745    for bundle_id in &submit_order {
1746        // The bundle is written on its own family's grid, with that family's
1747        // tile: one grid for every source but CFSv2, whose pressure-level
1748        // bundles are 1° where its surface ones are the T126 Gaussian grid.
1749        let family = family_of(registry.bundle_variable_ids(bundle_id)[0].as_str());
1750        tiers.push(Tier {
1751            bundle_id,
1752            suffix: "",
1753            factor: 1,
1754            grid: grid_for(family),
1755            codes: &codes_by_offset,
1756        });
1757        for rung in &ladder {
1758            tiers.push(Tier {
1759                bundle_id,
1760                suffix: rung.suffix.as_str(),
1761                factor: rung.factor,
1762                grid: &rung
1763                    .grids
1764                    .iter()
1765                    .find(|(held, _)| *held == family)
1766                    .expect("every family in play has a rung")
1767                    .1,
1768                codes: &rung.codes_by_offset,
1769            });
1770        }
1771    }
1772    // The shared stores this build writes into, one per tier. A fanned-out
1773    // job shares them with the run's other jobs, so nothing already in them
1774    // is removed but the group document, which this build's arrays make
1775    // stale until the reference's `finalize_store` writes it from the parts.
1776    let mut shared_stores: Vec<(usize, PathBuf)> = Vec::new();
1777    if options.zarr {
1778        let mut tiers_in_play: Vec<(usize, &str)> = vec![(1, "")];
1779        tiers_in_play.extend(
1780            ladder
1781                .iter()
1782                .map(|rung| (rung.factor, rung.suffix.as_str())),
1783        );
1784        for (factor, suffix) in tiers_in_play {
1785            let store = output_dir.join(format!("{}{suffix}.zarr", zarrstore::SHARED_STORE_STEM));
1786            let group = store.join("zarr.json");
1787            if group.is_file() {
1788                std::fs::remove_file(&group).map_err(|error| {
1789                    EncodeError::conversion(format!("cannot remove {}: {error}", group.display()))
1790                })?;
1791            }
1792            shared_stores.push((factor, store));
1793        }
1794    }
1795    let shared_store = |factor: usize| -> &Path {
1796        &shared_stores
1797            .iter()
1798            .find(|(held, _)| *held == factor)
1799            .expect("every tier has a shared store")
1800            .1
1801    };
1802    let pool = zarrstore::compression_pool(options.compress_workers)?;
1803    let write_tier = |tier: &Tier<'_>| -> Result<(Value, Option<zarrstore::BundleWrite>)> {
1804        let bundle_variables: Vec<String> = registry.bundle_variable_ids(tier.bundle_id);
1805        let variables: Vec<&str> = bundle_variables.iter().map(String::as_str).collect();
1806        let bundle_offsets: &[i64] = &variable_offsets[variables[0]];
1807        let (_, family_tile) = source.family_grid(family_of(variables[0]))?;
1808        let metadata = build_metadata(
1809            run_time,
1810            bundle_offsets,
1811            tier.grid,
1812            &options.profile,
1813            &variables,
1814            source,
1815            unit_seconds,
1816            &producer_versions,
1817            registry,
1818        )?;
1819        let tile = bundle_tile(family_tile, tier.grid, tier.factor);
1820        let mut report = if options.container {
1821            let geometry = TileGeometry::new(
1822                tier.grid.width as u32,
1823                tier.grid.height as u32,
1824                tile.0 as u32,
1825                tile.1 as u32,
1826            )
1827            .map_err(|error| EncodeError::conversion(error.0))?;
1828            let tables =
1829                bundle_chunks(&variables, bundle_offsets, tier.codes, &geometry, registry)?;
1830            write_variable_bundle(
1831                tier.bundle_id,
1832                &output_dir.join(format!("{}{}.xue", tier.bundle_id, tier.suffix)),
1833                &metadata,
1834                &geometry,
1835                tables,
1836                bundle_offsets.len() as u32,
1837                options.zstd_level,
1838                options,
1839                &pool,
1840            )?
1841        } else {
1842            json!({"variable": tier.bundle_id, "container": false})
1843        };
1844        let mut bundle_write = None;
1845        if options.zarr {
1846            // Written from the codes in memory: a bundle's arrays are a
1847            // function of the metadata, the codes, the tile, the predictors
1848            // and its dimension names alone, so they never wait on a
1849            // container. The part comes after every bundle of the tier.
1850            let mut store_variables = Vec::with_capacity(variables.len());
1851            for variable_id in &variables {
1852                let planes = bundle_offsets
1853                    .iter()
1854                    .map(|offset| {
1855                        tier.codes
1856                            .get(offset)
1857                            .and_then(|planes| planes.iter().find(|(id, _)| id == variable_id))
1858                            .map(|(_, plane)| plane.as_slice())
1859                            .ok_or_else(|| {
1860                                EncodeError::conversion(format!(
1861                                    "missing {variable_id} plane at offset {offset}"
1862                                ))
1863                            })
1864                    })
1865                    .collect::<Result<Vec<_>>>()?;
1866                store_variables.push(zarrstore::StoreVariable {
1867                    id: (*variable_id).to_owned(),
1868                    previous: !registry.is_raw(variable_id)?,
1869                    planes,
1870                });
1871            }
1872            let codes = zarrstore::StoreCodes {
1873                metadata: &metadata,
1874                variables: store_variables,
1875                tile,
1876            };
1877            let store_path = shared_store(tier.factor);
1878            let store = zarrstore::write_bundle_arrays(
1879                &codes,
1880                store_path,
1881                tier.bundle_id,
1882                &store_dimensions(registry, source, tier.bundle_id)?,
1883                &pool,
1884            )?;
1885            log!(
1886                options,
1887                "wrote {} into {} ({:.2} MB)",
1888                tier.bundle_id,
1889                store_path.display(),
1890                store.byte_length as f64 / 1e6
1891            );
1892            report["zarr"] = store.to_value();
1893            bundle_write = Some(store);
1894            if tier.factor == 1
1895                && options
1896                    .series_bundle_ids
1897                    .iter()
1898                    .any(|id| id == tier.bundle_id)
1899            {
1900                // The series companion is a full-resolution artifact: a
1901                // pinned point reads the canonical bundle, never a tier. Its
1902                // codec chain carries the bundle's own predictor, and its
1903                // widened variables their sixteen-bit codes.
1904                let series_path = output_dir.join(format!("{}.series.zarr", tier.bundle_id));
1905                let series = write_series_store(
1906                    &codes,
1907                    &variables,
1908                    bundle_offsets,
1909                    series_spool.as_ref(),
1910                    &series_path,
1911                    &pool,
1912                );
1913                if let Some(spool) = &series_spool {
1914                    for variable_id in &variables {
1915                        spool.release(variable_id);
1916                    }
1917                }
1918                let series = series?;
1919                log!(
1920                    options,
1921                    "wrote {} ({:.2} MB)",
1922                    series_path.display(),
1923                    series.byte_length as f64 / 1e6
1924                );
1925                report["series"] = series.to_value();
1926            }
1927        }
1928        if tier.factor > 1 {
1929            // A tier's playback hint is the delivery it ships: the
1930            // container where one is written, the store otherwise.
1931            let byte_length = if options.container {
1932                report["byteLength"].as_u64()
1933            } else {
1934                report["zarr"]["byteLength"].as_u64()
1935            }
1936            .unwrap_or(0) as usize;
1937            let object = report.as_object_mut().expect("report object");
1938            object.insert("width".into(), json!(tier.grid.width));
1939            object.insert("height".into(), json!(tier.grid.height));
1940            object.insert(
1941                "bandwidth".into(),
1942                json!(playback_bandwidth(byte_length, bundle_offsets.len())),
1943            );
1944        }
1945        Ok((report, bundle_write))
1946    };
1947    let written = for_each_ordered(tiers.len(), BUNDLE_WRITERS, |index| {
1948        write_tier(&tiers[index])
1949    })?;
1950    // Every series store is written: the spool's directory goes now.
1951    drop(series_spool);
1952
1953    let mut full_reports: BTreeMap<&str, Value> = BTreeMap::new();
1954    let mut variant_reports: BTreeMap<&str, Vec<Value>> = BTreeMap::new();
1955    let mut store_writes: Vec<((usize, &str), zarrstore::BundleWrite)> = Vec::new();
1956    for (tier, (report, bundle_write)) in tiers.iter().zip(written) {
1957        if let Some(bundle_write) = bundle_write {
1958            store_writes.push(((tier.factor, tier.bundle_id), bundle_write));
1959        }
1960        if tier.factor == 1 {
1961            full_reports.insert(tier.bundle_id, report);
1962        } else {
1963            variant_reports
1964                .entry(tier.bundle_id)
1965                .or_default()
1966                .push(report);
1967        }
1968    }
1969
1970    // Each tier's partial group document, last: over this build's bundles in
1971    // manifest order. Every entry naming the store carries its CRC-32 until
1972    // the group document is written from the parts.
1973    for (factor, store) in &shared_stores {
1974        let writes = report_order
1975            .iter()
1976            .map(|bundle_id| {
1977                store_writes
1978                    .iter()
1979                    .find(|((held_factor, held_id), _)| {
1980                        held_factor == factor && held_id == bundle_id
1981                    })
1982                    .map(|(_, bundle_write)| bundle_write)
1983                    .ok_or_else(|| {
1984                        EncodeError::bundle(format!(
1985                            "{bundle_id} was not written into {}",
1986                            store.display()
1987                        ))
1988                    })
1989            })
1990            .collect::<Result<Vec<_>>>()?;
1991        let (part, crc32) = zarrstore::write_part(store, &writes)?;
1992        log!(options, "wrote {}", part.display());
1993        let rung = ladder.iter().position(|rung| rung.factor == *factor);
1994        for bundle_id in &report_order {
1995            let report = match rung {
1996                None => full_reports.get_mut(bundle_id),
1997                Some(index) => variant_reports
1998                    .get_mut(bundle_id)
1999                    .and_then(|reports| reports.get_mut(index)),
2000            }
2001            .expect("every bundle has a report on every tier");
2002            report["zarr"]["crc32"] = json!(crc32);
2003        }
2004    }
2005
2006    let bundle_reports: Vec<Value> = report_order
2007        .iter()
2008        .map(|bundle_id| full_reports[bundle_id].clone())
2009        .collect();
2010
2011    // -- report ---------------------------------------------------------------
2012    let report = build_report(
2013        output_dir,
2014        source,
2015        &grid,
2016        options,
2017        &bundle_reports,
2018        &variant_reports,
2019        &poster_reports,
2020        &stats,
2021        &available_vector_ids,
2022        &encoded_variable_ids,
2023        registry,
2024    )?;
2025
2026    // -- manifest -------------------------------------------------------------
2027    if let Some(manifest_path) = &options.manifest_path {
2028        write_manifest(
2029            manifest_path,
2030            options,
2031            source,
2032            &bundle_reports,
2033            &variant_reports,
2034            &poster_reports,
2035            grid_for,
2036            &offsets,
2037            unit_seconds,
2038            run_time,
2039            registry,
2040        )?;
2041    }
2042
2043    Ok(Value::Object(report))
2044}
2045
2046pub fn zstd_version() -> String {
2047    let version = zstd::zstd_safe::version_number();
2048    format!(
2049        "{}.{}.{}",
2050        version / 10_000,
2051        (version / 100) % 100,
2052        version % 100
2053    )
2054}
2055
2056/// The hour an interval total at `per_file[index]` (`frame`) accumulated
2057/// from: the frame before it on the axis being built. A series that starts
2058/// at a step of its own — the rate's, whose analysis frame does not exist —
2059/// takes the distance from the previous step of the source's published axis
2060/// instead, which is the interval the model itself accumulated over; and
2061/// the first step of an axis that itself starts past the analysis
2062/// (`first_hour`) accumulated from the run time, hour 0. Only a total at
2063/// the analysis names no interval at all.
2064fn interval_start(
2065    per_file: &[FileFrames],
2066    index: usize,
2067    frame: &SourceFrame,
2068    source: &SourceSpec,
2069) -> Result<i64> {
2070    let hour = frame.lead_seconds / HOUR_SECONDS;
2071    if index > 0 {
2072        return Ok(per_file[index - 1][0].1.lead_seconds / HOUR_SECONDS);
2073    }
2074    let cycle = frame.run_time.to_offset(time::UtcOffset::UTC).hour();
2075    let axis = source.forecast_hours(hour, Some(u32::from(cycle)))?;
2076    match axis.get(axis.len().wrapping_sub(2)) {
2077        Some(&start) => Ok(start),
2078        None if hour > 0 => Ok(0),
2079        None => Err(EncodeError::conversion(format!(
2080            "the interval precipitation frame at hour {hour} names no interval"
2081        ))),
2082    }
2083}
2084
2085/// Yield `(previous (hour, slot), own slot)` per file. A slot is created only
2086/// when the next file will difference against this file's raw plane, so each
2087/// shared plane is freed once its consumer finishes. An interval total
2088/// (Open-Meteo apcp) needs no predecessor plane at all — only the hour beside
2089/// the slot, which is then `None`. Mirrors `_sharing_plan` in
2090/// `xuebuild/binconvert.py`.
2091type SharingPlan = Vec<(
2092    Option<(i64, Option<Arc<PlaneSlot>>)>,
2093    Option<Arc<PlaneSlot>>,
2094)>;
2095
2096fn sharing_plan(
2097    per_file: &[FileFrames],
2098    raw_precipitation_id: Option<&str>,
2099    source: &SourceSpec,
2100) -> Result<SharingPlan> {
2101    let mut plan: SharingPlan = Vec::with_capacity(per_file.len());
2102    let mut previous_slot: Option<Arc<PlaneSlot>> = None;
2103    for (index, frames) in per_file.iter().enumerate() {
2104        let frame = raw_precipitation_id.and_then(|id| frame_of(frames, id));
2105        let previous = match (&previous_slot, frame) {
2106            _ if frame.is_some() && source.interval_precipitation => Some((
2107                interval_start(per_file, index, frame.expect("a frame"), source)?,
2108                None,
2109            )),
2110            (Some(slot), Some(_)) => Some((
2111                frame_of(&per_file[index - 1], raw_precipitation_id.expect("id"))
2112                    .expect("predecessor frame")
2113                    .lead_seconds
2114                    / HOUR_SECONDS,
2115                Some(Arc::clone(slot)),
2116            )),
2117            _ => None,
2118        };
2119        let mut own = None;
2120        if let (Some(frame), Some(raw_id)) = (frame, raw_precipitation_id) {
2121            if !source.interval_precipitation && index + 1 < per_file.len() {
2122                if let Some(successor) = frame_of(&per_file[index + 1], raw_id) {
2123                    let hour = frame.lead_seconds / HOUR_SECONDS;
2124                    // A run total differences against its predecessor
2125                    // unconditionally; a window's average or total only
2126                    // against the previous frame of the same window.
2127                    let shares = source.accumulated_precipitation
2128                        || average_window_start(
2129                            successor.lead_seconds / HOUR_SECONDS,
2130                            source.precipitation_window_hours(),
2131                        )? < hour;
2132                    if shares {
2133                        own = Some(Arc::new(PlaneSlot::default()));
2134                    }
2135                }
2136            }
2137        }
2138        previous_slot = own.clone();
2139        plan.push((previous, own));
2140    }
2141    Ok(plan)
2142}
2143
2144#[cfg(test)]
2145mod grid_family_tests {
2146    use super::{bundle_grid_family, grid_family_of};
2147    use crate::encode::registry::Registry;
2148
2149    /// Which grid each of a source's bundles is built on, from the registry
2150    /// alone: every CFSv2 pressure-level bundle reads the `pgb` family, every
2151    /// surface one the primary file, and no bundle of any other source reads
2152    /// a family at all — the wave companions share their source's grid, so
2153    /// nothing about them changed.
2154    #[test]
2155    fn every_bundle_is_built_on_one_grid() {
2156        let registry = Registry::embedded();
2157        let cfs = registry.source("cfs").expect("cfs");
2158        for bundle_id in [
2159            "tmp2m", "prate", "tcdc", "dswrf", "tmpsfc", "icec", "icetk", "wind10m",
2160        ] {
2161            assert_eq!(
2162                bundle_grid_family(&registry, cfs, bundle_id).expect("one grid"),
2163                None,
2164                "{bundle_id}"
2165            );
2166        }
2167        for bundle_id in [
2168            "prmsl", "hgt1000", "hgt850", "hgt700", "hgt500", "hgt200", "tmp1000", "tmp850",
2169            "tmp700", "tmp500", "tmp250", "tmp200", "vvel500", "wind1000", "wind925", "wind850",
2170            "wind700", "wind500", "wind250", "wind200", "qflux925", "qflux850", "qflux700",
2171            "qflux500",
2172        ] {
2173            assert_eq!(
2174                bundle_grid_family(&registry, cfs, bundle_id).expect("one grid"),
2175                Some("pgb"),
2176                "{bundle_id}"
2177            );
2178        }
2179        // The vapour flux reads the humidity and the wind pair on its
2180        // surface, all three from the family, which is what makes it one
2181        // bundle's worth of one grid.
2182        for variable_id in &cfs.companion_files[0].variable_ids {
2183            assert_eq!(
2184                grid_family_of(cfs, variable_id),
2185                Some("pgb"),
2186                "{variable_id}"
2187            );
2188        }
2189        for model in [
2190            "gfs", "ecmwf", "ifs", "aifs", "sflux", "hrrr", "rrfs", "gefsaero", "ifshres", "mrms",
2191            "mrms3d",
2192        ] {
2193            let source = registry.source(model).expect(model);
2194            for bundle_id in source
2195                .bundle_scalar_ids
2196                .iter()
2197                .chain(&source.bundle_vector_ids)
2198                .chain(&source.bundle_volume_ids)
2199            {
2200                assert_eq!(
2201                    bundle_grid_family(&registry, source, bundle_id).expect("one grid"),
2202                    None,
2203                    "{model} {bundle_id}"
2204                );
2205            }
2206        }
2207    }
2208}
2209
2210#[cfg(test)]
2211mod composite_tests {
2212    use crate::encode::registry::Registry;
2213
2214    #[test]
2215    fn the_dust_rgb_reads_four_windows_or_three_without_the_11_2_one() {
2216        // Mirrors `DustRGBProducer.inputs_for`: AHI and ABI carry the 11.2 µm
2217        // window, FCI does not and the 10.4 µm one stands in — the document's
2218        // `optionalInputs`, read when the source fetches them.
2219        let registry = Registry::embedded();
2220        for model in ["himawari", "himawarijp", "goeseast", "goeswest"] {
2221            let source = registry.source(model).expect(model);
2222            assert_eq!(
2223                registry.bundle_input_ids(source, "dustrgb"),
2224                ["ir086", "ir104", "ir112", "ir123"],
2225                "{model}"
2226            );
2227        }
2228        let meteosat = registry.source("meteosat").expect("meteosat");
2229        assert_eq!(
2230            registry.bundle_input_ids(meteosat, "dustrgb"),
2231            ["ir086", "ir104", "ir123"]
2232        );
2233        // The components are the same three guns everywhere, and every
2234        // satellite source publishes ir104 and ir039, then the composite.
2235        for model in ["himawari", "goeseast", "goeswest", "meteosat"] {
2236            let source = registry.source(model).expect(model);
2237            assert_eq!(
2238                registry.bundle_variable_ids("dustrgb"),
2239                ["dustr", "dustg", "dustb"]
2240            );
2241            assert!(
2242                registry
2243                    .published_bundle_ids(source)
2244                    .starts_with(&["ir104", "ir039", "dustrgb"]),
2245                "{model}"
2246            );
2247        }
2248    }
2249
2250    #[test]
2251    fn the_debra_confidence_reads_five_windows_and_is_one_variable() {
2252        // The DEBRA confidence has no stand-in: the same five inputs on
2253        // every platform, and a source that fetches fewer (Meteosat) does
2254        // not publish it. The ZHOUYE confidence is composed in the same
2255        // pass from the same five, its own bundle of one variable after it.
2256        let registry = Registry::embedded();
2257        assert_eq!(registry.bundle_variable_ids("dustcf"), ["dustcf"]);
2258        assert_eq!(registry.bundle_variable_ids("zhouye"), ["zhouye"]);
2259        for model in ["himawari", "goeseast", "goeswest"] {
2260            let source = registry.source(model).expect(model);
2261            for bundle_id in ["dustcf", "zhouye"] {
2262                assert_eq!(
2263                    registry.bundle_input_ids(source, bundle_id),
2264                    ["ir039", "wv062", "ir086", "ir104", "ir123"],
2265                    "{model} {bundle_id}"
2266                );
2267            }
2268            assert_eq!(
2269                registry.published_bundle_ids(source),
2270                ["ir104", "ir039", "dustrgb", "dustcf", "zhouye", "truecolor"],
2271                "{model}"
2272            );
2273        }
2274        let meteosat = registry.source("meteosat").expect("meteosat");
2275        assert_eq!(
2276            registry.published_bundle_ids(meteosat),
2277            ["ir104", "ir039", "dustrgb", "truecolor"]
2278        );
2279    }
2280
2281    #[test]
2282    fn the_true_colour_reads_four_bands_or_three_without_the_green_one() {
2283        // Mirrors `TrueColorProducer.inputs_for`: the AHI has a 0.51 µm
2284        // band, the ABI does not and its green is synthesized from the
2285        // other three; the FCI has one, so Meteosat reads the four.
2286        let registry = Registry::embedded();
2287        assert_eq!(
2288            registry.bundle_variable_ids("truecolor"),
2289            ["truer", "trueg", "trueb"]
2290        );
2291        for model in ["himawari", "himawarijp", "meteosat"] {
2292            let source = registry.source(model).expect(model);
2293            assert_eq!(
2294                registry.bundle_input_ids(source, "truecolor"),
2295                ["vis047", "vis051", "vis064", "nir086", "ir039", "ir104"],
2296                "{model}"
2297            );
2298        }
2299        assert_eq!(
2300            registry.published_bundle_ids(registry.source("himawarijp").expect("himawarijp")),
2301            ["ir104", "ir039", "dustrgb", "truecolor"]
2302        );
2303        for model in ["goeseast", "goeswest"] {
2304            let source = registry.source(model).expect(model);
2305            assert_eq!(
2306                registry.bundle_input_ids(source, "truecolor"),
2307                ["vis047", "vis064", "nir086", "ir039", "ir104"],
2308                "{model}"
2309            );
2310        }
2311        // Every satellite source fetches what the true colour reads.
2312        for source in registry.sources().filter(|source| {
2313            source
2314                .bundle_composite_ids
2315                .iter()
2316                .any(|id| id == "truecolor")
2317        }) {
2318            for input in registry.bundle_input_ids(source, "truecolor") {
2319                assert!(source.has_input(&input), "{} {input}", source.id);
2320            }
2321        }
2322        assert!(registry.composite_components("nightmicro").is_none());
2323    }
2324}
2325
2326#[cfg(test)]
2327mod volume_tests {
2328    use crate::encode::registry::Registry;
2329
2330    /// The `refl3d` volume carries the 33 levels bottom to top, reads each
2331    /// from its own record, publishes after every other kind of bundle and
2332    /// stacks every level RAW, as the composite does.
2333    #[test]
2334    fn the_reflectivity_volume_is_its_33_levels_in_order() {
2335        let registry = Registry::embedded();
2336        let source = registry.source("mrms3d").expect("mrms3d");
2337        let levels = registry.volume_components("refl3d").expect("a volume");
2338        assert_eq!(levels.len(), 33);
2339        assert_eq!(
2340            (levels[0].as_str(), levels[32].as_str()),
2341            ("refl500", "refl19000")
2342        );
2343        assert_eq!(registry.bundle_variable_ids("refl3d"), levels);
2344        assert_eq!(registry.bundle_input_ids(source, "refl3d"), levels);
2345        assert_eq!(registry.published_bundle_ids(source), ["refl3d"]);
2346        for variable_id in levels {
2347            assert!(registry.is_raw(variable_id).unwrap(), "{variable_id}");
2348        }
2349        for variable_id in ["prate", "cref", "ptype", "cat300"] {
2350            assert!(registry.is_raw(variable_id).unwrap(), "{variable_id}");
2351        }
2352        for variable_id in ["tmp2m", "ir104", "clw1500"] {
2353            assert!(!registry.is_raw(variable_id).unwrap(), "{variable_id}");
2354        }
2355        assert!(registry.is_raw("refl600").is_err());
2356        // No other source publishes one.
2357        for model in ["gfs", "ecmwf", "mrms", "himawari", "cma", "woof"] {
2358            assert!(
2359                !registry
2360                    .published_bundle_ids(registry.source(model).expect(model))
2361                    .contains(&"refl3d"),
2362                "{model}"
2363            );
2364        }
2365    }
2366
2367    /// The `cloud3d` volume carries the 24 cloud water levels bottom to
2368    /// top, reads each from its own series and publishes after the nest's
2369    /// scalars and its wind.
2370    #[test]
2371    fn the_cloud_water_volume_is_its_24_levels_in_order() {
2372        let registry = Registry::embedded();
2373        let source = registry.source("woof").expect("woof");
2374        let levels = registry.volume_components("cloud3d").expect("a volume");
2375        assert_eq!(levels.len(), 24);
2376        assert_eq!(
2377            (levels[0].as_str(), levels[23].as_str()),
2378            ("clw250", "clw12000")
2379        );
2380        assert_eq!(registry.bundle_input_ids(source, "cloud3d"), levels);
2381        assert_eq!(
2382            registry.published_bundle_ids(source),
2383            [
2384                "tmp2m", "prate", "tmpsfc", "dpt2m", "tcdc", "lcdc", "mcdc", "hcdc", "hpbl",
2385                "dswrf", "orog", "prmsl", "wind10m", "wind80m", "cloud3d",
2386            ]
2387        );
2388        for model in [
2389            "gfs", "ecmwf", "hrrr", "rrfs", "ifshres", "mrms3d", "himawari",
2390        ] {
2391            assert!(
2392                !registry
2393                    .published_bundle_ids(registry.source(model).expect(model))
2394                    .contains(&"cloud3d"),
2395                "{model}"
2396            );
2397        }
2398    }
2399}
2400
2401#[cfg(test)]
2402mod store_dimension_tests {
2403    use super::{cadence_offsets, store_dimensions};
2404    use crate::encode::binformat::HOUR_SECONDS;
2405    use crate::encode::registry::Registry;
2406
2407    fn names(model: &str, bundle_id: &str) -> [String; 3] {
2408        let registry = Registry::embedded();
2409        let source = registry.source(model).expect("source");
2410        store_dimensions(&registry, source, bundle_id).expect("dimensions")
2411    }
2412
2413    /// The reference's `store_dimensions` over the same registry: the run's
2414    /// axis and grid for most bundles, a time of its own where a rule cuts
2415    /// the axis (a rate without its analysis frame, an interval maximum, a
2416    /// static field), a grid family's pair for the CFSv2 pressure levels, and
2417    /// `y` / `x` on a source published on a projection.
2418    #[test]
2419    fn a_bundle_takes_its_own_names_only_where_a_rule_cuts_it() {
2420        assert_eq!(names("gfs", "tmp2m"), ["time", "latitude", "longitude"]);
2421        assert_eq!(names("gfs", "wind10m"), ["time", "latitude", "longitude"]);
2422        assert_eq!(names("gfs", "prate"), ["time", "latitude", "longitude"]);
2423        assert_eq!(names("gfs", "orog"), ["time_orog", "latitude", "longitude"]);
2424        assert_eq!(
2425            names("ecmwf", "prate"),
2426            ["time_prate", "latitude", "longitude"]
2427        );
2428        assert_eq!(
2429            names("ecmwf", "gust"),
2430            ["time_gust", "latitude", "longitude"]
2431        );
2432        assert_eq!(
2433            names("ecmwf", "apcp24gt10"),
2434            ["time_apcp24gt10", "latitude", "longitude"]
2435        );
2436        assert_eq!(names("ecmwf", "prmslsd"), ["time", "latitude", "longitude"]);
2437        assert_eq!(
2438            names("ecmwf", "tmp850sd"),
2439            ["time", "latitude", "longitude"]
2440        );
2441        assert_eq!(
2442            names("ifshres", "dswrf"),
2443            ["time_dswrf", "latitude", "longitude"]
2444        );
2445        assert_eq!(names("cfs", "tmp2m"), ["time", "latitude", "longitude"]);
2446        assert_eq!(
2447            names("cfs", "hgt500"),
2448            ["time", "latitude_pgb", "longitude_pgb"]
2449        );
2450        assert_eq!(
2451            names("cfs", "wind850"),
2452            ["time", "latitude_pgb", "longitude_pgb"]
2453        );
2454        assert_eq!(names("hrrr", "tmp2m"), ["time", "y", "x"]);
2455        assert_eq!(names("hrrr", "wind10m"), ["time", "y", "x"]);
2456        assert_eq!(names("hrrr", "orog"), ["time_orog", "y", "x"]);
2457        assert_eq!(names("rrfs", "smokesfc"), ["time", "y", "x"]);
2458    }
2459
2460    /// An ensemble source's further rates cut the axis as its one rate
2461    /// does, and a variable with a first hour of its own takes a time of its
2462    /// own; a quartile read at every frame shares the run's.
2463    #[test]
2464    fn a_first_hour_and_an_interval_pair_cut_the_axis() {
2465        let document = crate::encode::registry::ensemble_fixture::document().to_string();
2466        let registry = Registry::parse(&document).unwrap();
2467        let source = registry.source("cmageps").unwrap();
2468        let names =
2469            |bundle_id: &str| store_dimensions(&registry, source, bundle_id).expect("dimensions");
2470        assert_eq!(
2471            names("apcp24gt10"),
2472            ["time_apcp24gt10", "latitude", "longitude"]
2473        );
2474        assert_eq!(
2475            names("prateq25"),
2476            ["time_prateq25", "latitude", "longitude"]
2477        );
2478        assert_eq!(names("prate"), ["time_prate", "latitude", "longitude"]);
2479        assert_eq!(names("tmp2mq25"), ["time", "latitude", "longitude"]);
2480        assert_eq!(names("prmslsd"), ["time", "latitude", "longitude"]);
2481    }
2482
2483    /// A registry whose `cmageps` writes its 24-hour probability every 12
2484    /// hours from the 24th and its pressure spread every 6 from the
2485    /// analysis — the shapes of ECMWF's `ep` products.
2486    fn stepped_registry() -> std::sync::Arc<Registry> {
2487        let mut document = crate::encode::registry::ensemble_fixture::document();
2488        document["sources"]["cmageps"]["variableStepHours"] =
2489            serde_json::json!([["apcp24gt10", 12], ["prmslsd", 6]]);
2490        Registry::parse(&document.to_string()).unwrap()
2491    }
2492
2493    #[test]
2494    fn a_step_gives_a_bundle_its_own_axis() {
2495        let registry = stepped_registry();
2496        let source = registry.source("cmageps").unwrap();
2497        let names =
2498            |bundle_id: &str| store_dimensions(&registry, source, bundle_id).expect("dimensions");
2499        assert_eq!(
2500            names("apcp24gt10"),
2501            ["time_apcp24gt10", "latitude", "longitude"]
2502        );
2503        // A step from the analysis is still an axis of its own.
2504        assert_eq!(names("prmslsd"), ["time_prmslsd", "latitude", "longitude"]);
2505        assert_eq!(names("tmp2mq25"), ["time", "latitude", "longitude"]);
2506    }
2507
2508    #[test]
2509    fn a_step_thins_the_axis_to_its_cadence() {
2510        let registry = stepped_registry();
2511        let source = registry.source("cmageps").unwrap();
2512        let axis: Vec<i64> = (0..=144).step_by(3).chain((150..=240).step_by(6)).collect();
2513        assert_eq!(
2514            cadence_offsets(&registry, source, "apcp24gt10", &axis, HOUR_SECONDS),
2515            (24..=240).step_by(12).collect::<Vec<i64>>()
2516        );
2517        assert_eq!(
2518            cadence_offsets(&registry, source, "prmslsd", &axis, HOUR_SECONDS),
2519            axis.iter()
2520                .copied()
2521                .filter(|hour| hour % 6 == 0)
2522                .collect::<Vec<i64>>()
2523        );
2524        // A build that ends before the first window has nothing to publish.
2525        assert!(
2526            cadence_offsets(&registry, source, "apcp24gt10", &[0, 3, 6], HOUR_SECONDS).is_empty()
2527        );
2528        // Offsets in minutes keep only whole hours on the cadence.
2529        assert_eq!(
2530            cadence_offsets(&registry, source, "apcp24gt10", &[1410, 1440, 2160], 60),
2531            [1440, 2160]
2532        );
2533    }
2534}
2535
2536#[cfg(test)]
2537mod validate_tests {
2538    use super::{validate_build, ConvertOptions};
2539    use crate::encode::registry::Registry;
2540
2541    fn options(model: &str) -> ConvertOptions {
2542        ConvertOptions {
2543            model: model.into(),
2544            ..ConvertOptions::default()
2545        }
2546    }
2547
2548    /// The document alone answers: a known source with every bundle it
2549    /// publishes passes, and the same refusals a build would give come back
2550    /// without an input in sight.
2551    #[test]
2552    fn a_build_is_validated_from_the_document_alone() {
2553        let registry = Registry::embedded();
2554        let (source, published) = validate_build(&options("gfs"), &registry).expect("gfs builds");
2555        assert_eq!(source.manifest_model, "GFS");
2556        let every = ConvertOptions {
2557            bundle_ids: Some(published.iter().map(|id| (*id).to_string()).collect()),
2558            ..options("gfs")
2559        };
2560        assert!(validate_build(&every, &registry).is_ok());
2561
2562        let refusal =
2563            |options: &ConvertOptions| validate_build(options, &registry).unwrap_err().to_string();
2564        assert_eq!(
2565            refusal(&options("nosuchmodel")),
2566            "unsupported model: nosuchmodel"
2567        );
2568        let profile = ConvertOptions {
2569            profile: "nosuchprofile".into(),
2570            ..options("gfs")
2571        };
2572        assert_eq!(refusal(&profile), "unknown profile: nosuchprofile");
2573        let bundles = ConvertOptions {
2574            bundle_ids: Some(vec!["nosuchbundle".into()]),
2575            ..options("gfs")
2576        };
2577        assert!(refusal(&bundles).starts_with("GFS publishes "));
2578        let none = ConvertOptions {
2579            bundle_ids: Some(Vec::new()),
2580            ..options("gfs")
2581        };
2582        assert!(refusal(&none).starts_with("GFS publishes "));
2583    }
2584}