envlib-ingest-base 0.4.2__tar.gz → 0.6.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,23 @@
1
+ Metadata-Version: 2.5
2
+ Name: envlib-ingest-base
3
+ Version: 0.6.0
4
+ Summary: Shared toolkit for envlib data-ingest repos: source-agnostic time-series resampling and ts_ortho (station) dataset build + idempotent commons update.
5
+ Project-URL: Source, https://github.com/envlib/envlib-ingest-base
6
+ Author-email: mullenkamp <mullenkamp1@gmail.com>
7
+ License-Expression: Apache-2.0
8
+ License-File: LICENSE
9
+ Classifier: Programming Language :: Python :: 3 :: Only
10
+ Requires-Python: >=3.10
11
+ Requires-Dist: booklet>=0.12.10
12
+ Requires-Dist: cfdb>=0.11.0
13
+ Requires-Dist: ebooklet>=0.11.0
14
+ Requires-Dist: envlib>=0.1.8
15
+ Requires-Dist: numpy
16
+ Requires-Dist: rechunkit>=0.6.0
17
+ Requires-Dist: sentry-sdk
18
+ Requires-Dist: shapely>=2.0
19
+ Description-Content-Type: text/markdown
20
+
1
21
  # envlib-ingest-base
2
22
 
3
23
  Shared, tested toolkit for the envlib data-ingest family — and the Docker base image that carries
@@ -256,11 +276,15 @@ attrs so merges apply the same filter). `precision` is
256
276
  **decimal places** (cfdb picks the int packing width from `precision` + `min_value`/`max_value`);
257
277
  pass `standard_name` to override envlib's auto-derived CF name. Returns the path.
258
278
 
259
- **Memory: bounded by ONE STATION ROW, not by the dataset.** Rows are written individually
260
- (`var[i, :] = row`), matching the ts_ortho `chunk_shape` of `(1, time_chunk)`, so a build's peak
261
- tracks `n_times` rather than `n_stations × n_times`. Measured on 400 stations × 150,000 steps:
262
- ~11 MB peak, against ~480 MB for a single dense plane — and it is *faster* than the whole-plane
263
- write, since the large transient allocations are gone. **What this does NOT cover:** `series` is
279
+ **Chunks and write order.** The default `chunk_shape` is `(1, time_chunk)`: one station, and a time
280
+ chunk that is the first highly composite number of steps ≥ 2520 spanning whole days (2520 for hourly
281
+ data = 105 days; 10,080 for 15-minute data). It is not clipped to the build's length, because the
282
+ chunk shape is fixed for the dataset's life. The build writes **block by block** — every station's
283
+ chunk (and its ancillary planes) for one time block, then the next — because grouped remotes pack
284
+ chunks in write order: a block-major file keeps each time block in its own few groups, so the hourly
285
+ update re-uploads only the current block's groups. Peak memory is one block of one station.
286
+ Measured on 400 stations × 150,000 steps with the earlier row-at-a-time writer: ~11 MB peak, against
287
+ ~480 MB for a single dense plane. **What this does NOT cover:** `series` is
264
288
  still a dict holding every station's arrays, so the *caller* carries ~24 B per stored observation
265
289
  for the whole build (~784 MB on a 33 M-observation source). On a large source that dict — not the
266
290
  write — is the ceiling.
@@ -394,15 +418,22 @@ update_and_publish(cat, 'flow.cfdb', member, rcg, stations, series_recent,
394
418
  variable='streamflow')
395
419
  ```
396
420
 
397
- **Remote storage layout**: by default (`num_groups=None`) each chunk is its own S3 object —
398
- the right choice for continuously-updated ts_ortho datasets (tens of keys; every hourly
399
- push/pull moves exactly the changed chunk and nothing else). Grouped storage is a
400
- request-batching optimization for **large, rarely-updated archives** (thousands of keys —
401
- ebooklet's guidance is 10–100 MB per group); pass a prime `num_groups` at first publish only
402
- for that shape. The choice is fixed once the dataset is first pushed. For how chunk size and shape
403
- trade off on each layout (request costs, per-station vs multi-station chunks), see cfdb's
421
+ **Remote storage layout** (the telemetry layout, decided 2026-10-08): by default
422
+ (`group_bytes='auto'`) `build_and_publish` publishes **grouped**, with `group_bytes_for(path,
423
+ variable)`: the largest power of two at most half a block (all stations × one time chunk), floored at
424
+ 64 KiB. One block then spans at least two groups, so a single-station read stays exact, and an
425
+ hourly update uploads a few groups instead of one object per station. Pass an int to choose the size,
426
+ or `None` for per-key storage (one S3 object per chunk; e.g. a frozen dataset). Later pushes inherit
427
+ the mode and the recorded size. The measurements behind this are in ebooklet's
428
+ `planning/write-order-groups-evidence/telemetry-layout/RESULTS.md`; for chunk sizes on remotes in
429
+ general see cfdb's
404
430
  [Chunk sizes for remote datasets](https://mullenkamp.github.io/cfdb/guide/s3-remote/#chunk-sizes-for-remote-datasets).
405
431
 
432
+ **Re-laying out an existing dataset**: `rechunk_copy(src, dst, time_chunk=...)` copies an open
433
+ ts_ortho dataset into an empty one with new time chunks, block by block, and `compare_datasets(a, b)`
434
+ lists every difference between two (attrs, CRS, coordinates, encodings and values; chunk shapes and
435
+ the time origin aside) as the gate before a republish.
436
+
406
437
  `build_and_publish` takes the same keyword build args as `build_local`
407
438
  (`variable`/`units`/`precision`/`min_value`/`max_value`/`standard_name`/…); `update_and_publish` only
408
439
  needs `variable` (the dataset already exists). Both push the cfdb data **before** the catalogue entry,
@@ -1,22 +1,3 @@
1
- Metadata-Version: 2.5
2
- Name: envlib-ingest-base
3
- Version: 0.4.2
4
- Summary: Shared toolkit for envlib data-ingest repos: source-agnostic time-series resampling and ts_ortho (station) dataset build + idempotent commons update.
5
- Project-URL: Source, https://github.com/envlib/envlib-ingest-base
6
- Author-email: mullenkamp <mullenkamp1@gmail.com>
7
- License-Expression: Apache-2.0
8
- License-File: LICENSE
9
- Classifier: Programming Language :: Python :: 3 :: Only
10
- Requires-Python: >=3.10
11
- Requires-Dist: booklet>=0.12.10
12
- Requires-Dist: cfdb>=0.10.0
13
- Requires-Dist: ebooklet>=0.10.5
14
- Requires-Dist: envlib>=0.1.7
15
- Requires-Dist: numpy
16
- Requires-Dist: sentry-sdk
17
- Requires-Dist: shapely>=2.0
18
- Description-Content-Type: text/markdown
19
-
20
1
  # envlib-ingest-base
21
2
 
22
3
  Shared, tested toolkit for the envlib data-ingest family — and the Docker base image that carries
@@ -275,11 +256,15 @@ attrs so merges apply the same filter). `precision` is
275
256
  **decimal places** (cfdb picks the int packing width from `precision` + `min_value`/`max_value`);
276
257
  pass `standard_name` to override envlib's auto-derived CF name. Returns the path.
277
258
 
278
- **Memory: bounded by ONE STATION ROW, not by the dataset.** Rows are written individually
279
- (`var[i, :] = row`), matching the ts_ortho `chunk_shape` of `(1, time_chunk)`, so a build's peak
280
- tracks `n_times` rather than `n_stations × n_times`. Measured on 400 stations × 150,000 steps:
281
- ~11 MB peak, against ~480 MB for a single dense plane — and it is *faster* than the whole-plane
282
- write, since the large transient allocations are gone. **What this does NOT cover:** `series` is
259
+ **Chunks and write order.** The default `chunk_shape` is `(1, time_chunk)`: one station, and a time
260
+ chunk that is the first highly composite number of steps ≥ 2520 spanning whole days (2520 for hourly
261
+ data = 105 days; 10,080 for 15-minute data). It is not clipped to the build's length, because the
262
+ chunk shape is fixed for the dataset's life. The build writes **block by block** — every station's
263
+ chunk (and its ancillary planes) for one time block, then the next — because grouped remotes pack
264
+ chunks in write order: a block-major file keeps each time block in its own few groups, so the hourly
265
+ update re-uploads only the current block's groups. Peak memory is one block of one station.
266
+ Measured on 400 stations × 150,000 steps with the earlier row-at-a-time writer: ~11 MB peak, against
267
+ ~480 MB for a single dense plane. **What this does NOT cover:** `series` is
283
268
  still a dict holding every station's arrays, so the *caller* carries ~24 B per stored observation
284
269
  for the whole build (~784 MB on a 33 M-observation source). On a large source that dict — not the
285
270
  write — is the ceiling.
@@ -413,15 +398,22 @@ update_and_publish(cat, 'flow.cfdb', member, rcg, stations, series_recent,
413
398
  variable='streamflow')
414
399
  ```
415
400
 
416
- **Remote storage layout**: by default (`num_groups=None`) each chunk is its own S3 object —
417
- the right choice for continuously-updated ts_ortho datasets (tens of keys; every hourly
418
- push/pull moves exactly the changed chunk and nothing else). Grouped storage is a
419
- request-batching optimization for **large, rarely-updated archives** (thousands of keys —
420
- ebooklet's guidance is 10–100 MB per group); pass a prime `num_groups` at first publish only
421
- for that shape. The choice is fixed once the dataset is first pushed. For how chunk size and shape
422
- trade off on each layout (request costs, per-station vs multi-station chunks), see cfdb's
401
+ **Remote storage layout** (the telemetry layout, decided 2026-10-08): by default
402
+ (`group_bytes='auto'`) `build_and_publish` publishes **grouped**, with `group_bytes_for(path,
403
+ variable)`: the largest power of two at most half a block (all stations × one time chunk), floored at
404
+ 64 KiB. One block then spans at least two groups, so a single-station read stays exact, and an
405
+ hourly update uploads a few groups instead of one object per station. Pass an int to choose the size,
406
+ or `None` for per-key storage (one S3 object per chunk; e.g. a frozen dataset). Later pushes inherit
407
+ the mode and the recorded size. The measurements behind this are in ebooklet's
408
+ `planning/write-order-groups-evidence/telemetry-layout/RESULTS.md`; for chunk sizes on remotes in
409
+ general see cfdb's
423
410
  [Chunk sizes for remote datasets](https://mullenkamp.github.io/cfdb/guide/s3-remote/#chunk-sizes-for-remote-datasets).
424
411
 
412
+ **Re-laying out an existing dataset**: `rechunk_copy(src, dst, time_chunk=...)` copies an open
413
+ ts_ortho dataset into an empty one with new time chunks, block by block, and `compare_datasets(a, b)`
414
+ lists every difference between two (attrs, CRS, coordinates, encodings and values; chunk shapes and
415
+ the time origin aside) as the gate before a republish.
416
+
425
417
  `build_and_publish` takes the same keyword build args as `build_local`
426
418
  (`variable`/`units`/`precision`/`min_value`/`max_value`/`standard_name`/…); `update_and_publish` only
427
419
  needs `variable` (the dataset already exists). Both push the cfdb data **before** the catalogue entry,
@@ -9,16 +9,27 @@
9
9
  from envlib_ingest_base.resample import resample
10
10
  from envlib_ingest_base.tsforecast import build_and_push, merge_run, update_and_push
11
11
  from envlib_ingest_base.tsforecast import build_local as build_forecast_local
12
- from envlib_ingest_base.tsortho import build_and_publish, build_local, merge_dataset, update_and_publish
12
+ from envlib_ingest_base.tsortho import (
13
+ build_and_publish,
14
+ build_local,
15
+ compare_datasets,
16
+ group_bytes_for,
17
+ merge_dataset,
18
+ rechunk_copy,
19
+ update_and_publish,
20
+ )
13
21
 
14
- __version__ = '0.4.2'
22
+ __version__ = '0.6.0'
15
23
  __all__ = [
16
24
  'build_and_publish',
17
25
  'build_and_push',
18
26
  'build_forecast_local',
19
27
  'build_local',
28
+ 'compare_datasets',
29
+ 'group_bytes_for',
20
30
  'merge_dataset',
21
31
  'merge_run',
32
+ 'rechunk_copy',
22
33
  'resample',
23
34
  'update_and_publish',
24
35
  'update_and_push',
@@ -456,7 +456,7 @@ def merge_run(ds, stations: dict, run: dict, *, variable: str, overwrite: bool =
456
456
  }
457
457
 
458
458
 
459
- def build_and_push(member_conn, path, meta, stations: dict, run: dict, *, num_groups=None, **build_kwargs):
459
+ def build_and_push(member_conn, path, meta, stations: dict, run: dict, *, group_bytes=None, **build_kwargs):
460
460
  """First run: build the local ``ts_forecast`` and push it to its S3 remote.
461
461
 
462
462
  There is deliberately **no catalogue here**. A forecast archive of a commercial provider's
@@ -465,17 +465,18 @@ def build_and_push(member_conn, path, meta, stations: dict, run: dict, *, num_gr
465
465
  ``envlib.validate_dataset`` in ``build_local``, so the dataset carries CV-validated identity
466
466
  fields and is trivially promotable later if that ever changes.
467
467
 
468
- ``num_groups=None`` (per-key objects) is right for a continuously-appended archive: each run
469
- is one small chunk, and every push moves exactly the run that changed.
468
+ ``group_bytes=None`` (per-key objects) is right for a continuously-appended archive: each run
469
+ is one small chunk, and every push moves exactly the run that changed (a grouped remote would
470
+ re-upload its partly filled last group on every run).
470
471
  """
471
472
  build_local(path, meta, stations, run, **build_kwargs)
472
- with open_edataset(member_conn, str(path), flag='w', num_groups=num_groups) as eds:
473
+ with open_edataset(member_conn, str(path), flag='w', group_bytes=group_bytes) as eds:
473
474
  result = eds.push()
474
475
  return {'path': str(path), 'push': result}
475
476
 
476
477
 
477
478
  def update_and_push(
478
- member_conn, path, stations: dict, run: dict, *, variable: str, overwrite: bool = False, num_groups=None
479
+ member_conn, path, stations: dict, run: dict, *, variable: str, overwrite: bool = False
479
480
  ):
480
481
  """Incremental run: pull the remote, merge one run, push.
481
482
 
@@ -484,7 +485,7 @@ def update_and_push(
484
485
  on every run and wants a periodic ``ds.prune()``, AFTER the push (pruning is local-only and
485
486
  preserves key timestamps, so it cannot inflate the next push).
486
487
  """
487
- with open_edataset(member_conn, str(path), flag='w', num_groups=num_groups) as ds:
488
+ with open_edataset(member_conn, str(path), flag='w') as ds: # the existing remote's storage mode
488
489
  report = merge_run(ds, stations, run, variable=variable, overwrite=overwrite)
489
490
  result = ds.push()
490
491
  return {'merge': report, 'push': result}
@@ -66,8 +66,13 @@ they are non-NaN (so a station that is briefly offline, or an interval that resa
66
66
  never clobbers good stored data). New stations append to the point axis; new steps extend the
67
67
  time axis (in the coord's own stored dtype). A re-run over the same window is a no-op.
68
68
 
69
- Both write paths — build and merge — iterate BY STATION, matching the ts_ortho chunk shape of
70
- `(1, time_chunk)`. Peak memory therefore tracks one station's row, never the point dimension.
69
+ The chunk shape is ``(1, time_chunk)``: one station, and by default a time chunk that is a highly
70
+ composite number of steps spanning whole days (2520 for hourly data; see ``_default_time_chunk``).
71
+ The build writes **block by block** — every station's chunk for one time block, then the next
72
+ block — because ebooklet's write-order groups pack chunks in the order they were written: a
73
+ block-major file keeps each time block in its own few groups, so the hourly update re-uploads the
74
+ current block's groups, not the whole dataset. The merge iterates by station over its window.
75
+ Peak memory tracks one block of one station, never the point dimension.
71
76
  Note the store is log-structured, so each merge orphans the chunks it rewrites: a continuously
72
77
  merged dataset grows every run and wants a periodic `ds.prune()` (local-only, timestamp-preserving,
73
78
  so it cannot inflate a push).
@@ -80,10 +85,14 @@ with the ebooklet edataset + ``envlib.Catalogue`` publish.
80
85
  from __future__ import annotations
81
86
 
82
87
  import logging
88
+ import math
83
89
 
90
+ import booklet
84
91
  import numpy as np
85
92
  from cfdb import dtypes, open_dataset, open_edataset
93
+ from ebooklet import DEFAULT_GROUP_BYTES
86
94
  from envlib.vocabularies import frequency_entry
95
+ from rechunkit.main import composite_numbers
87
96
 
88
97
  from envlib_ingest_base.stations import (
89
98
  STATION_ALTITUDE_VAR,
@@ -102,7 +111,13 @@ from envlib_ingest_base.stations import (
102
111
  logger = logging.getLogger(__name__)
103
112
 
104
113
 
105
- _DEFAULT_TIME_CHUNK = 25_000 # steps; see the chunk_shape default rationale in build_local
114
+ # the default time chunk is the first highly composite number of steps at or above this that spans
115
+ # whole days (2520 hourly = 105 days); see _default_time_chunk and the layout decision of 2026-10-08
116
+ _MIN_TIME_CHUNK = 2520
117
+ _DAY_US = 86_400_000_000
118
+ # group_bytes for a grouped remote: a power of two at most half a block (all stations x one time
119
+ # chunk), so one block spans at least two groups and a single-station read stays exact
120
+ _MIN_GROUP_BYTES = 64 * 1024
106
121
  # a series entry is (times, values) or (times, values, extras) — the 3rd slot carries ancillary data
107
122
  _SERIES_WITH_EXTRAS = 3
108
123
  # natural-unit ladder: the largest unit that divides the step becomes the stored coord unit
@@ -133,6 +148,57 @@ def _freq_step(code) -> tuple[int, str]:
133
148
  return step_us, 'us' # unreachable with the current CV (whole-second codes only)
134
149
 
135
150
 
151
+ def _default_time_chunk(step_us: int) -> int:
152
+ """The default ts_ortho time chunk for a fixed step: the first highly composite number (from
153
+ rechunkit's list, so later rechunks stay cheap) that is at least ``_MIN_TIME_CHUNK`` steps and
154
+ spans a whole number of days. Hourly -> 2520 (105 days), 15-minute -> 10,080 (105 days).
155
+
156
+ The size trades the hourly push (the current chunks plus their groups) against the remote
157
+ index every reader re-downloads after each change (one entry per chunk) and against
158
+ compression (~2 % worse than 25,000 steps). Measurements: ebooklet
159
+ ``planning/write-order-groups-evidence/telemetry-layout/RESULTS.md``.
160
+ """
161
+ for n in composite_numbers:
162
+ if n >= _MIN_TIME_CHUNK and (n * step_us) % _DAY_US == 0:
163
+ return int(n)
164
+ msg = f'no highly composite time chunk spans whole days at a step of {step_us} us'
165
+ raise ValueError(msg)
166
+
167
+
168
+ def _pow2_group_bytes(block_bytes: float) -> int:
169
+ """The largest power of two at most half of ``block_bytes``, floored at 64 KiB and capped at
170
+ ebooklet's default group size (above it, full-band reads get slower)."""
171
+ half = block_bytes / 2
172
+ if half < _MIN_GROUP_BYTES:
173
+ return _MIN_GROUP_BYTES
174
+ return int(min(2 ** math.floor(math.log2(half)), DEFAULT_GROUP_BYTES))
175
+
176
+
177
+ def group_bytes_for(path, variable: str) -> int:
178
+ """The ``group_bytes`` for publishing the local ts_ortho cfdb at ``path`` grouped.
179
+
180
+ One block — all stations x one time chunk of ``variable`` — must span at least two groups, or
181
+ a group holds several blocks of every station and a single-station read over-reads by about a
182
+ group. The block size is measured from the stored (compressed) chunk bytes of ``variable``,
183
+ scaled from the file's time length to one chunk. A short or sparse first build measures
184
+ small, which errs toward smaller groups (the safe direction), and a remote can be re-packed to
185
+ another value later by passing it on a push.
186
+ """
187
+ return _pow2_group_bytes(_block_bytes(path, variable))
188
+
189
+
190
+ def _block_bytes(path, variable: str) -> float:
191
+ """Stored bytes of one block of ``variable``: its live chunk bytes scaled from the file's time
192
+ length to one time chunk."""
193
+ with open_dataset(str(path)) as ds:
194
+ n_times = ds[variable].shape[1]
195
+ time_chunk = ds[variable].chunk_shape[1]
196
+ prefix = f'{variable}!'
197
+ with booklet.open(str(path), 'r') as blt:
198
+ stored = sum(vlen for key, _ts, _off, vlen in blt.locations() if key.startswith(prefix))
199
+ return stored * time_chunk / n_times
200
+
201
+
136
202
  def _floor_step(us: int, step_us: int) -> int:
137
203
  return (us // step_us) * step_us
138
204
 
@@ -253,18 +319,22 @@ def _check_extras(non_empty: dict, roster) -> None:
253
319
  raise ValueError(msg)
254
320
 
255
321
 
256
- def _write_rows(var, stations: dict, series: dict, t0_us: int, n_times: int, step_us: int, dt, plane=None) -> None:
257
- """Write the dense ``(n_point, n_time)`` plane ONE STATION ROW AT A TIME.
322
+ def _write_blocks(planes, stations: dict, series: dict, t0_us: int, n_times: int, step_us: int, block: int) -> None:
323
+ """Write the dense ``(n_point, n_time)`` planes BLOCK BY BLOCK: for each time block of
324
+ ``block`` steps (the time chunk), every station's chunk of every plane, then the next block.
258
325
 
259
- This replaces an earlier ``_assemble`` that built the whole dense plane in memory and
260
- returned it for a single ``var[:] = ...`` assignment. **That defeated the main reason to use
261
- cfdb.** cfdb reads and writes in chunks, and the ts_ortho chunk shape is ``(1, time_chunk)``
262
- — *one station row* — so the whole-plane approach allocated a station-count multiple of what
263
- a write actually needs. Measured on a 606-station by 620,771-step dataset: 3.01 GB per plane,
264
- two planes, and roughly double again for ``_nan_safe``'s mask and copy. Per row it is ~5 MB.
326
+ ``planes`` is a list of ``(var, dt, plane)``: ``plane=None`` writes the primary values, a
327
+ string writes that named ancillary (stations lacking it stay NaN). Within a block each station's
328
+ planes are written together, so a value and its ancillary grade sit next to each other.
265
329
 
266
- ``plane=None`` writes the primary values; a string writes that named ancillary (stations
267
- lacking it stay NaN), so both share one code path and land on identical geometry.
330
+ **Why block-major.** ebooklet's write-order groups pack chunks in the order they were written
331
+ to the local file. Written station by station, each group holds whole station histories, so the
332
+ hourly update (which rewrites every station's current chunk) touches nearly every group and
333
+ re-uploads about the whole dataset until the next rollover. Written block by block, each group
334
+ holds one time block, and an update touches only the current block's groups.
335
+
336
+ It replaced a whole-plane ``_assemble`` (3.01 GB per plane on a 606-station x 620,771-step
337
+ dataset) and then a row-at-a-time writer. Peak memory is one block of one station.
268
338
 
269
339
  ⚠️ **Iterate ``stations``, never ``series``.** The point coordinate and the
270
340
  ``station_id``/``station_ref``/``station_name`` arrays are built in ``stations`` order, so row
@@ -272,26 +342,45 @@ def _write_rows(var, stations: dict, series: dict, t0_us: int, n_times: int, ste
272
342
  would map the *i*-th station-that-has-data to point *i* and silently mislabel every station
273
343
  after the first data-less one — a file that validates cleanly and is wrong.
274
344
 
275
- A station with no data still gets an explicitly written all-NaN row, exactly as before: an
276
- unwritten chunk also reads as NaN, but it would change which chunks exist and the file size.
345
+ A station with no data still gets explicitly written all-NaN chunks: an unwritten chunk also
346
+ reads as NaN, but it would change which chunks exist and the file size.
277
347
 
278
- Each row is written in ONE call, and each chunk therefore exactly once. Revisiting a chunk
279
- costs a full decompress+recompress, orphans the previous block (the store is log-structured,
280
- so the file grows until pruned), and can force a synchronous buffer flush.
348
+ With a point chunk of 1 (the ts_ortho default) each chunk is written exactly once (blocks are
349
+ chunk-aligned on a fresh axis); a caller's larger point chunk is revisited once per station, as
350
+ the row writer before it did. Revisiting a chunk costs a full decompress+recompress, orphans the
351
+ previous block (the store is log-structured, so the file grows until pruned), and can force a
352
+ synchronous buffer flush.
281
353
  """
282
- for i, ref in enumerate(stations):
283
- # a fresh row per station: nothing is ever aliased into cfdb's chunk buffer, and the
284
- # peak is one row regardless of station count
285
- row = np.full(n_times, np.nan, dtype='float64')
354
+ # per station, its integer timestamps in ascending order (the series contract; sorted once if
355
+ # a producer broke it), so each block's slice is two binary searches, not a scan
356
+ ordered = {}
357
+ for ref in stations:
286
358
  s = series.get(ref)
287
- if s is not None:
288
- t, v, ex = s
289
- arr = v if plane is None else ex.get(plane)
290
- if arr is not None:
291
- col = _step_index(t, t0_us, step_us)
292
- ok = (col >= 0) & (col < n_times)
293
- row[col[ok]] = arr[ok]
294
- var[i, :] = _nan_safe(row, dt)
359
+ if s is None:
360
+ continue
361
+ t, v, ex = s
362
+ ti = t.view('int64')
363
+ if ti.size > 1 and not bool((ti[1:] >= ti[:-1]).all()):
364
+ order = np.argsort(ti, kind='stable')
365
+ ti, v, ex = ti[order], v[order], {k: a[order] for k, a in ex.items()}
366
+ ordered[ref] = (ti, v, ex)
367
+
368
+ for b0 in range(0, n_times, block):
369
+ b1 = min(b0 + block, n_times)
370
+ lo_us, hi_us = t0_us + b0 * step_us, t0_us + b1 * step_us
371
+ for i, ref in enumerate(stations):
372
+ s = ordered.get(ref)
373
+ if s is not None:
374
+ ti, v, ex = s
375
+ lo, hi = (int(x) for x in np.searchsorted(ti, [lo_us, hi_us], side='left'))
376
+ for var, dt, plane in planes:
377
+ # a fresh segment per write: nothing is ever aliased into cfdb's chunk buffer
378
+ seg = np.full(b1 - b0, np.nan, dtype='float64')
379
+ if s is not None and hi > lo:
380
+ arr = v if plane is None else ex.get(plane)
381
+ if arr is not None:
382
+ seg[(ti[lo:hi] - lo_us) // step_us] = arr[lo:hi]
383
+ var[i, b0:b1] = _nan_safe(seg, dt)
295
384
 
296
385
 
297
386
  def build_local(
@@ -362,19 +451,20 @@ def build_local(
362
451
  tmin = _floor_step(min(int(t.astype('int64').min()) for t, *_ in non_empty.values()), step_us)
363
452
  tmax = _floor_step(max(int(t.astype('int64').max()) for t, *_ in non_empty.values()), step_us)
364
453
  times_us = np.arange(tmin, tmax + 1, step_us)
365
- # NOTE: the dense plane is NOT assembled here. Rows are written individually inside the
366
- # dataset context below (see _write_rows) so peak memory is one row, not one plane.
454
+ # NOTE: the dense plane is NOT assembled here. Blocks are written individually inside the
455
+ # dataset context below (see _write_blocks) so peak memory is one block, not one plane.
367
456
  points, ids, names, refs = _points_ids_names(stations)
368
457
 
369
458
  if chunk_shape is None:
370
459
  # ts_ortho default: point dim = 1 (ruling 2026-07-20). The dominant consumer read is
371
460
  # ONE station's history — an all-stations point chunk forces downloading the whole
372
461
  # dataset to read one station (~250x amplification); one-station chunk columns also
373
- # keep new-station appends and per-station updates independent. The time chunk trades
374
- # object count vs per-chunk compression vs the perpetual per-update upload (each run
375
- # rewrites every station's TAIL chunk): ~25k steps ≈ a handful of objects per station
376
- # at ~50-200 KB each, a few MB of upload per update run.
377
- chunk_shape = (1, int(min(times_us.size, _DEFAULT_TIME_CHUNK)))
462
+ # keep new-station appends and per-station updates independent. The time chunk is the
463
+ # telemetry layout of 2026-10-08 (see _default_time_chunk). It is NOT clipped to this
464
+ # build's length: the chunk shape is fixed for the dataset's life, so a short first
465
+ # build (e.g. a one-month backfill) must not fix a short chunk forever; cfdb stores the
466
+ # partly filled chunk and the axis grows into it.
467
+ chunk_shape = (1, _default_time_chunk(step_us))
378
468
 
379
469
  unit_us = dict(_UNIT_US).get(unit, 1)
380
470
  tvals = times_us.astype('datetime64[us]').astype(f'datetime64[{unit}]')
@@ -397,7 +487,7 @@ def build_local(
397
487
  # merge_dataset reads back, so the stored dataset stays the source of truth on update.
398
488
  if ancillary:
399
489
  dv.attrs['ancillary_variables'] = ' '.join(ancillary)
400
- _write_rows(dv, stations, non_empty, tmin, times_us.size, step_us, dt)
490
+ planes = [(dv, dt, None)]
401
491
 
402
492
  for aname, spec in ancillary.items():
403
493
  adt = dtypes.dtype(
@@ -413,10 +503,10 @@ def build_local(
413
503
  # written LAST so a caller-supplied attrs dict can never weaken the QC bounds
414
504
  av.attrs['valid_min'] = float(spec['min_value'])
415
505
  av.attrs['valid_max'] = float(spec['max_value'])
416
- # Previously this nested a whole-plane _assemble INSIDE _nan_safe while the primary
417
- # plane was still resident — three full planes plus a mask live at once, the worst
418
- # single moment in the build. Now one row at a time, like the primary.
419
- _write_rows(av, stations, non_empty, tmin, times_us.size, step_us, adt, plane=aname)
506
+ planes.append((av, adt, aname))
507
+
508
+ # every plane in one block-major pass, so a value and its ancillary grade land together
509
+ _write_blocks(planes, stations, non_empty, tmin, times_us.size, step_us, chunk_shape[1])
420
510
 
421
511
  sid = ds.create.data_var.generic(STATION_ID_VAR, ('point',), dtype=dtypes.dtype('str'))
422
512
  sid[:] = ids
@@ -660,15 +750,166 @@ def merge_dataset(ds, stations: dict, series: dict, *, variable: str):
660
750
  }
661
751
 
662
752
 
663
- def build_and_publish(cat, path, member_conn, rcg_conn, meta, stations, series, *, num_groups=None, **build_kwargs):
753
+ def rechunk_copy(src, dst, *, time_chunk: int) -> None:
754
+ """Copy the ts_ortho dataset ``src`` into the EMPTY ts_ortho dataset ``dst`` with
755
+ ``(1, time_chunk)`` data chunks, written block by block (see ``_write_blocks`` for why).
756
+
757
+ ``src`` is any open ts_ortho dataset (a local file, or an EDataset whose chunks it pulls).
758
+ ``dst`` is open for write and empty; the caller decides its header (for example passing an
759
+ existing remote's ``init_bytes`` through ``open_dataset`` to keep that remote's uuid).
760
+
761
+ Copied: the dataset attrs, the CRS, the point and time coordinates (the time axis from its
762
+ decoded values, so a source origin left by a truncation does not carry over) with their attrs,
763
+ every ``(point, time)`` variable with the source's dtype/encoding and attrs, and every
764
+ ``(point,)`` station variable with its values and attrs. Anything else (another coordinate, a
765
+ variable on other dims) raises rather than being dropped silently. Memory is one block of every
766
+ ``(point, time)`` variable across all stations, plus what cfdb holds to serve a slice (up to one
767
+ source chunk per station; measured 19.7 MB peak for a 6 MB block). Compression is not copied:
768
+ ``dst`` keeps whatever it was opened with, so pass ``compression=`` there to choose it.
769
+ """
770
+ for name, ds in (('src', src), ('dst', dst)):
771
+ if ds.dataset_type != 'ts_ortho':
772
+ msg = f'rechunk_copy: {name} is a {ds.dataset_type!r} dataset, not ts_ortho'
773
+ raise ValueError(msg)
774
+ if dst.coord_names or dst.data_var_names:
775
+ msg = f'rechunk_copy: dst must be empty, but holds {dst.coord_names + dst.data_var_names}'
776
+ raise ValueError(msg)
777
+ extra = set(src.coord_names) - {'point', 'time'}
778
+ if extra:
779
+ msg = f'rechunk_copy: coordinates {sorted(extra)} are not supported'
780
+ raise NotImplementedError(msg)
781
+ planes, statics = [], []
782
+ for name in src.data_var_names:
783
+ dims = tuple(src[name].coord_names)
784
+ if dims == ('point', 'time'):
785
+ planes.append(name)
786
+ elif dims == ('point',):
787
+ statics.append(name)
788
+ else:
789
+ msg = f'rechunk_copy: variable {name!r} on dims {dims} is not supported'
790
+ raise NotImplementedError(msg)
791
+
792
+ dst.create.coord.point()
793
+ dst['point'].append(src['point'].data)
794
+ dst.create.coord.time(data=src['time'].data, step=src['time'].step)
795
+ for name in ('point', 'time'):
796
+ dst[name].attrs.update(dict(src[name].attrs))
797
+ if src.crs is not None:
798
+ dst.create.crs.from_user_input(src.crs, xy_coord='point')
799
+
800
+ out = {}
801
+ for name in planes:
802
+ out[name] = dst.create.data_var.generic(
803
+ name, ('point', 'time'), dtype=src[name].dtype, chunk_shape=(1, int(time_chunk))
804
+ )
805
+ out[name].attrs.update(dict(src[name].attrs))
806
+ if planes:
807
+ n_points, n_times = src[planes[0]].shape
808
+ for b0 in range(0, n_times, time_chunk):
809
+ b1 = min(b0 + time_chunk, n_times)
810
+ block = {name: np.asarray(src[name][:, b0:b1].data, dtype='float64') for name in planes}
811
+ for i in range(n_points):
812
+ for name in planes:
813
+ out[name][i, b0:b1] = _nan_safe(block[name][i].copy(), out[name].dtype)
814
+
815
+ for name in statics:
816
+ sv = dst.create.data_var.generic(name, ('point',), dtype=src[name].dtype)
817
+ sv[:] = src[name].data
818
+ sv.attrs.update(dict(src[name].attrs))
819
+ dst.attrs.update(dict(src.attrs))
820
+
821
+
822
+ _DTYPE_FIELDS = ('name', 'dtype_encoded', 'dtype_decoded', 'precision', 'fillvalue', 'offset')
823
+
824
+
825
+ def _dtype_fields(dt) -> dict:
826
+ return {f: str(getattr(dt, f, None)) for f in _DTYPE_FIELDS}
827
+
828
+
829
+ def _values_differ(x, y) -> bool:
830
+ x, y = np.asarray(x), np.asarray(y)
831
+ if x.shape != y.shape:
832
+ return True
833
+ if x.dtype.kind in 'fc' or y.dtype.kind in 'fc':
834
+ return not np.array_equal(x.astype('float64'), y.astype('float64'), equal_nan=True)
835
+ return list(x.ravel().tolist()) != list(y.ravel().tolist())
836
+
837
+
838
+ def compare_datasets(a, b, *, block: int = _MIN_TIME_CHUNK) -> list:
839
+ """Every difference between two ts_ortho datasets, ignoring only chunk shapes and the time
840
+ coordinate's origin. An empty list means equal. Built as the gate before an irreversible
841
+ republish, so it checks everything a rechunk must preserve:
842
+
843
+ - the dataset type, its attrs and the CRS;
844
+ - the coordinates: decoded values (points by their WKB), every dtype field, step and attrs;
845
+ - every variable: dims, shape, attrs, and every dtype/encoding field (``_DTYPE_FIELDS``);
846
+ - the values: ``(point, time)`` variables block by block (``block`` steps across all stations,
847
+ NaN-aware), station variables whole.
848
+
849
+ Read through an EDataset, a chunk the local file lacks is pulled, not read as fill; read
850
+ through a plain local file, a chunk that was never materialised reads as fill — so compare
851
+ against a remote read when the question is "did the copy keep everything".
852
+ """
853
+ diffs = []
854
+ if a.dataset_type != b.dataset_type:
855
+ diffs.append(f'dataset_type: {a.dataset_type!r} != {b.dataset_type!r}')
856
+ # dict() first: cfdb's Attributes.__iter__ returns dict_keys, not an iterator, so set()/iter() on it raise
857
+ da, db = dict(a.attrs), dict(b.attrs)
858
+ if da != db:
859
+ diffs.append(f'dataset attrs differ: {sorted(k for k in da.keys() | db.keys() if da.get(k) != db.get(k))}')
860
+ if (a.crs is None) != (b.crs is None) or (a.crs is not None and a.crs != b.crs):
861
+ diffs.append(f'crs: {a.crs!r} != {b.crs!r}')
862
+
863
+ if set(a.coord_names) != set(b.coord_names):
864
+ diffs.append(f'coordinates: {sorted(a.coord_names)} != {sorted(b.coord_names)}')
865
+ for name in sorted(set(a.coord_names) & set(b.coord_names)):
866
+ ca, cb = a[name], b[name]
867
+ fa, fb = _dtype_fields(ca.dtype), _dtype_fields(cb.dtype)
868
+ if fa != fb or ca.step != cb.step:
869
+ diffs.append(f'coord {name}: dtype/step {fa}/{ca.step} != {fb}/{cb.step}')
870
+ if dict(ca.attrs) != dict(cb.attrs):
871
+ diffs.append(f'coord {name}: attrs differ')
872
+ va, vb = np.asarray(ca.data), np.asarray(cb.data)
873
+ if name == 'point':
874
+ same = va.shape == vb.shape and [g.wkb for g in va] == [g.wkb for g in vb]
875
+ else:
876
+ same = not _values_differ(va, vb)
877
+ if not same:
878
+ diffs.append(f'coord {name}: values differ')
879
+
880
+ if set(a.data_var_names) != set(b.data_var_names):
881
+ diffs.append(f'variables: {sorted(a.data_var_names)} != {sorted(b.data_var_names)}')
882
+ for name in sorted(set(a.data_var_names) & set(b.data_var_names)):
883
+ va, vb = a[name], b[name]
884
+ if tuple(va.coord_names) != tuple(vb.coord_names) or va.shape != vb.shape:
885
+ diffs.append(f'{name}: dims/shape {va.coord_names}{va.shape} != {vb.coord_names}{vb.shape}')
886
+ continue
887
+ aa, ab = dict(va.attrs), dict(vb.attrs)
888
+ if aa != ab:
889
+ diffs.append(f'{name}: attrs differ: {sorted(k for k in aa.keys() | ab.keys() if aa.get(k) != ab.get(k))}')
890
+ if _dtype_fields(va.dtype) != _dtype_fields(vb.dtype):
891
+ diffs.append(f'{name}: dtype/encoding {_dtype_fields(va.dtype)} != {_dtype_fields(vb.dtype)}')
892
+ if tuple(va.coord_names) == ('point', 'time'):
893
+ n_times = va.shape[1]
894
+ for b0 in range(0, n_times, block):
895
+ b1 = min(b0 + block, n_times)
896
+ if _values_differ(va[:, b0:b1].data, vb[:, b0:b1].data):
897
+ diffs.append(f'{name}: values differ in steps [{b0}, {b1})')
898
+ break
899
+ elif _values_differ(va.data, vb.data):
900
+ diffs.append(f'{name}: values differ')
901
+ return diffs
902
+
903
+
904
+ def build_and_publish(cat, path, member_conn, rcg_conn, meta, stations, series, *, group_bytes='auto', **build_kwargs):
664
905
  """First publish: build a local ts_ortho cfdb and publish it to the commons (data then RCG entry).
665
906
 
666
- ``num_groups=None`` (default) stores each chunk as its own S3 object — the right choice
667
- for continuously-updated ts_ortho datasets (small key counts, frequent single-chunk
668
- updates: every push/pull moves exactly the changed data). Grouping is a request-batching
669
- optimization for LARGE, rarely-updated archives (thousands of keys — see ebooklet's
670
- guidance of 10-100MB per group); pass a prime ``num_groups`` only for that shape.
671
- The choice is fixed at first publish.
907
+ ``group_bytes='auto'`` (default) publishes grouped with ``group_bytes_for(path, variable)``:
908
+ the telemetry layout of 2026-10-08, where the block-major build keeps each time block in its
909
+ own few groups, so the hourly update uploads the current block's groups rather than one object
910
+ per station. Pass an int to choose the group size, or ``None`` for per-key storage (one S3
911
+ object per chunk; e.g. a frozen dataset that is never updated). Later pushes inherit the mode
912
+ and the recorded group size.
672
913
 
673
914
  ``**build_kwargs`` go straight to ``build_local`` — including ``ancillary=`` to declare
674
915
  companion ``(point, time)`` planes (e.g. a per-timestep quality grade), whose data rides in
@@ -676,17 +917,20 @@ def build_and_publish(cat, path, member_conn, rcg_conn, meta, stations, series,
676
917
  the roster is read back from the stored dataset's ``ancillary_variables`` attr.
677
918
  """
678
919
  build_local(path, meta, stations, series, **build_kwargs)
679
- return cat.publish(str(path), member_conn, rcg_conn, num_groups=num_groups)
920
+ if group_bytes == 'auto':
921
+ group_bytes = group_bytes_for(path, build_kwargs['variable'])
922
+ logger.info('publish %s: grouped, group_bytes=%d', build_kwargs['variable'], group_bytes)
923
+ return cat.publish(str(path), member_conn, rcg_conn, group_bytes=group_bytes)
680
924
 
681
925
 
682
- def update_and_publish(cat, path, member_conn, rcg_conn, stations, series, *, variable, num_groups=None):
926
+ def update_and_publish(cat, path, member_conn, rcg_conn, stations, series, *, variable):
683
927
  """Incremental update: pull the remote, merge the recent window, then publish (diff + entry refresh).
684
928
 
685
929
  ``path`` is a local working cache linked to ``member_conn``; the merge reads only the coords +
686
- the affected time block, so no full-remote materialization is required. ``num_groups`` is
687
- read from the remote for existing datasets (the first-publish choice wins) — leave it None.
930
+ the affected time block, so no full-remote materialization is required. The storage mode is
931
+ the existing remote's (fixed at first publish), so none is passed here.
688
932
  """
689
- with open_edataset(member_conn, str(path), flag='w', num_groups=num_groups) as ds:
933
+ with open_edataset(member_conn, str(path), flag='w') as ds:
690
934
  report = merge_dataset(ds, stations, series, variable=variable)
691
- result = cat.publish(str(path), member_conn, rcg_conn, num_groups=num_groups)
935
+ result = cat.publish(str(path), member_conn, rcg_conn)
692
936
  return {'merge': report, 'publish': result}
@@ -20,19 +20,24 @@ dependencies = [
20
20
  # validation entry point, which does not exist before it. Raised in the SAME commit as the code
21
21
  # that needs it -- 0.1.5 satisfies the old ">=0.1.5" floor, so an in-place upgrade would keep it
22
22
  # and the failure would surface as an AttributeError far from its cause.
23
- "envlib>=0.1.7",
23
+ # >=0.1.8 (with cfdb/ebooklet >=0.11): publish() and open_edataset take group_bytes, which
24
+ # build_and_publish/build_and_push now pass; num_groups is gone.
25
+ "envlib>=0.1.8",
24
26
  # >=0.9.4 is a HARD floor: older cfdb fabricates values when its packed encoder meets
25
27
  # NaN/out-of-range data (cfdb changelog 0.9.4); tsortho also enforces this at runtime.
26
28
  # >=0.10.0: cfdb 0.10 writes byte-shuffled compression (zstd_shuffle) by default, which an older
27
29
  # cfdb cannot open. The toolkit also READS existing datasets (update/merge paths pull the remote),
28
30
  # so it must be able to open whatever another producer on 0.10 published. Existing datasets keep
29
31
  # their recorded compression when updated; only newly built ones are shuffled.
30
- "cfdb>=0.10.0",
31
- "ebooklet>=0.10.5",
32
+ "cfdb>=0.11.0",
33
+ "ebooklet>=0.11.0", # raised to >=0.11.1 once released (index prune, refusal close)
32
34
  "numpy",
33
35
  "shapely>=2.0",
34
36
  "sentry-sdk",
35
37
  "booklet>=0.12.10",
38
+ # the default ts_ortho time chunk is picked from rechunkit's highly composite list
39
+ # (tsortho._default_time_chunk), so later rechunks have small common multiples
40
+ "rechunkit>=0.6.0",
36
41
  ]
37
42
 
38
43
  [dependency-groups]