envlib-ingest-base 0.2.0__tar.gz → 0.3.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,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: envlib-ingest-base
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: Shared toolkit for envlib data-ingest repos: source-agnostic time-series resampling and ts_ortho (station) dataset build + idempotent commons update.
5
5
  Project-URL: Source, https://github.com/envlib/envlib-ingest-base
6
6
  Author-email: mullenkamp <mullenkamp1@gmail.com>
@@ -265,6 +265,15 @@ attrs so merges apply the same filter). `precision` is
265
265
  **decimal places** (cfdb picks the int packing width from `precision` + `min_value`/`max_value`);
266
266
  pass `standard_name` to override envlib's auto-derived CF name. Returns the path.
267
267
 
268
+ **Memory: bounded by ONE STATION ROW, not by the dataset.** Rows are written individually
269
+ (`var[i, :] = row`), matching the ts_ortho `chunk_shape` of `(1, time_chunk)`, so a build's peak
270
+ tracks `n_times` rather than `n_stations × n_times`. Measured on 400 stations × 150,000 steps:
271
+ ~11 MB peak, against ~480 MB for a single dense plane — and it is *faster* than the whole-plane
272
+ write, since the large transient allocations are gone. **What this does NOT cover:** `series` is
273
+ still a dict holding every station's arrays, so the *caller* carries ~24 B per stored observation
274
+ for the whole build (~784 MB on a 33 M-observation source). On a large source that dict — not the
275
+ write — is the ceiling.
276
+
268
277
  ```python
269
278
  from envlib_ingest_base import build_local
270
279
 
@@ -316,10 +325,22 @@ encodable range and a junk high code would persist silently.
316
325
  Fold a recent window into an **open** ts_ortho dataset (cfdb `Dataset` or `EDataset`, opened `flag='w'`).
317
326
  The cadence is read back from the dataset's own envlib attrs and cross-checked against the stored
318
327
  axis (epoch-aligned origin, dense constant step — mismatches raise). Appends genuinely-new stations
319
- and new steps, then does one contiguous read-modify-write over the affected block, writing incoming
320
- values **only where they are non-NaN** — so a station that is offline this window (or an interval
321
- that resamples to NaN) is never clobbered. Idempotent for a fixed input window; a window entirely
322
- before the axis start raises (no history prepending). Returns a small report dict.
328
+ and new steps, then read-modify-writes **one station at a time, each over its own window**, writing
329
+ incoming values **only where they are non-NaN** — so a station that is offline this window (or an
330
+ interval that resamples to NaN) is never clobbered. Idempotent for a fixed input window; a window
331
+ entirely before the axis start raises (no history prepending). Returns a small report dict.
332
+
333
+ **Memory is bounded by one station's window, not by the point dimension.** This previously read one
334
+ contiguous block spanning *every* station, sized from the global min/max incoming timestamp — so a
335
+ single station reporting one backdated value widened the read for all of them (measured: a routine
336
+ 48-step merge went from 6 MB to 552 MB from one stale value). Per-station, a backdated value widens
337
+ only its own row. **Stations that supply nothing this run are not touched at all**, which also means
338
+ they are no longer rewritten — relevant to an `EDataset`, where a rewritten chunk is a pushed chunk.
339
+
340
+ ⚠️ **The store is log-structured, so every merge grows the file** (each reporting station's tail
341
+ chunk is rewritten and the old block orphaned). A continuously-merged dataset needs `ds.prune()` to
342
+ reclaim it — cheap, local-only, and it preserves per-key timestamps so it cannot inflate the next
343
+ push. Prune after publishing.
323
344
 
324
345
  ```python
325
346
  from cfdb import open_dataset
@@ -327,8 +348,11 @@ from envlib_ingest_base import merge_dataset
327
348
 
328
349
  with open_dataset('flow.cfdb', flag='w') as ds:
329
350
  merge_dataset(ds, stations, series_recent, variable='streamflow')
330
- # -> {'new_stations': 0, 'new_steps': 24, 'written_block': 72, 'gap_steps': 0,
351
+ # -> {'new_stations': 0, 'new_steps': 24, 'written_block': 48, 'gap_steps': 0,
331
352
  # 'qc_rejected': 0, 'anc_qc_rejected': 0, 'dropped_before_axis': 0}
353
+ # written_block: the WIDEST single station's window (the merge no longer has one global
354
+ # block). A large value now means one station genuinely carried a wide window,
355
+ # not that one stale timestamp stretched the block across every station.
332
356
  # gap_steps: steps left unfilled behind this window (pipeline downtime) — holes are NaN,
333
357
  # so refetching a wider window and re-merging heals them
334
358
  # qc_rejected: values outside the encodable range set to NaN by the min/max QC
@@ -247,6 +247,15 @@ attrs so merges apply the same filter). `precision` is
247
247
  **decimal places** (cfdb picks the int packing width from `precision` + `min_value`/`max_value`);
248
248
  pass `standard_name` to override envlib's auto-derived CF name. Returns the path.
249
249
 
250
+ **Memory: bounded by ONE STATION ROW, not by the dataset.** Rows are written individually
251
+ (`var[i, :] = row`), matching the ts_ortho `chunk_shape` of `(1, time_chunk)`, so a build's peak
252
+ tracks `n_times` rather than `n_stations × n_times`. Measured on 400 stations × 150,000 steps:
253
+ ~11 MB peak, against ~480 MB for a single dense plane — and it is *faster* than the whole-plane
254
+ write, since the large transient allocations are gone. **What this does NOT cover:** `series` is
255
+ still a dict holding every station's arrays, so the *caller* carries ~24 B per stored observation
256
+ for the whole build (~784 MB on a 33 M-observation source). On a large source that dict — not the
257
+ write — is the ceiling.
258
+
250
259
  ```python
251
260
  from envlib_ingest_base import build_local
252
261
 
@@ -298,10 +307,22 @@ encodable range and a junk high code would persist silently.
298
307
  Fold a recent window into an **open** ts_ortho dataset (cfdb `Dataset` or `EDataset`, opened `flag='w'`).
299
308
  The cadence is read back from the dataset's own envlib attrs and cross-checked against the stored
300
309
  axis (epoch-aligned origin, dense constant step — mismatches raise). Appends genuinely-new stations
301
- and new steps, then does one contiguous read-modify-write over the affected block, writing incoming
302
- values **only where they are non-NaN** — so a station that is offline this window (or an interval
303
- that resamples to NaN) is never clobbered. Idempotent for a fixed input window; a window entirely
304
- before the axis start raises (no history prepending). Returns a small report dict.
310
+ and new steps, then read-modify-writes **one station at a time, each over its own window**, writing
311
+ incoming values **only where they are non-NaN** — so a station that is offline this window (or an
312
+ interval that resamples to NaN) is never clobbered. Idempotent for a fixed input window; a window
313
+ entirely before the axis start raises (no history prepending). Returns a small report dict.
314
+
315
+ **Memory is bounded by one station's window, not by the point dimension.** This previously read one
316
+ contiguous block spanning *every* station, sized from the global min/max incoming timestamp — so a
317
+ single station reporting one backdated value widened the read for all of them (measured: a routine
318
+ 48-step merge went from 6 MB to 552 MB from one stale value). Per-station, a backdated value widens
319
+ only its own row. **Stations that supply nothing this run are not touched at all**, which also means
320
+ they are no longer rewritten — relevant to an `EDataset`, where a rewritten chunk is a pushed chunk.
321
+
322
+ ⚠️ **The store is log-structured, so every merge grows the file** (each reporting station's tail
323
+ chunk is rewritten and the old block orphaned). A continuously-merged dataset needs `ds.prune()` to
324
+ reclaim it — cheap, local-only, and it preserves per-key timestamps so it cannot inflate the next
325
+ push. Prune after publishing.
305
326
 
306
327
  ```python
307
328
  from cfdb import open_dataset
@@ -309,8 +330,11 @@ from envlib_ingest_base import merge_dataset
309
330
 
310
331
  with open_dataset('flow.cfdb', flag='w') as ds:
311
332
  merge_dataset(ds, stations, series_recent, variable='streamflow')
312
- # -> {'new_stations': 0, 'new_steps': 24, 'written_block': 72, 'gap_steps': 0,
333
+ # -> {'new_stations': 0, 'new_steps': 24, 'written_block': 48, 'gap_steps': 0,
313
334
  # 'qc_rejected': 0, 'anc_qc_rejected': 0, 'dropped_before_axis': 0}
335
+ # written_block: the WIDEST single station's window (the merge no longer has one global
336
+ # block). A large value now means one station genuinely carried a wide window,
337
+ # not that one stale timestamp stretched the block across every station.
314
338
  # gap_steps: steps left unfilled behind this window (pipeline downtime) — holes are NaN,
315
339
  # so refetching a wider window and re-merging heals them
316
340
  # qc_rejected: values outside the encodable range set to NaN by the min/max QC
@@ -7,7 +7,7 @@
7
7
  from envlib_ingest_base.resample import resample
8
8
  from envlib_ingest_base.tsortho import build_and_publish, build_local, merge_dataset, update_and_publish
9
9
 
10
- __version__ = '0.2.0'
10
+ __version__ = '0.3.0'
11
11
  __all__ = [
12
12
  'build_and_publish',
13
13
  'build_local',
@@ -60,11 +60,17 @@ grows an ``origin`` feature; see the OPEN_WORK follow-up):
60
60
  Known one-directional limit: data resampled *coarser* than declared (daily labels are valid
61
61
  hour multiples) builds a sparse-but-aligned axis the guards cannot detect.
62
62
 
63
- The **merge** is the operational core: each run resamples a recent window and folds it in via a
64
- single contiguous read-modify-write of the affected time block, writing incoming values only
65
- where they are non-NaN (so a station that is briefly offline, or an interval that resamples to
66
- NaN, never clobbers good stored data). New stations append to the point axis; new steps extend
67
- the time axis (in the coord's own stored dtype). A re-run over the same window is a no-op.
63
+ The **merge** is the operational core: each run resamples a recent window and folds it in with a
64
+ read-modify-write **per station, each over its own window**, writing incoming values only where
65
+ they are non-NaN (so a station that is briefly offline, or an interval that resamples to NaN,
66
+ never clobbers good stored data). New stations append to the point axis; new steps extend the
67
+ time axis (in the coord's own stored dtype). A re-run over the same window is a no-op.
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.
71
+ Note the store is log-structured, so each merge orphans the chunks it rewrites: a continuously
72
+ merged dataset grows every run and wants a periodic `ds.prune()` (local-only, timestamp-preserving,
73
+ so it cannot inflate a push).
68
74
 
69
75
  The cfdb-level functions (``build_local``, ``merge_dataset``) take an open dataset / path and
70
76
  are unit-tested without any remote. ``build_and_publish`` / ``update_and_publish`` wrap them
@@ -343,26 +349,45 @@ def _check_extras(non_empty: dict, roster) -> None:
343
349
  raise ValueError(msg)
344
350
 
345
351
 
346
- def _assemble(stations: dict, series: dict, t0_us: int, n_times: int, step_us: int, plane=None) -> np.ndarray:
347
- """Dense (n_point, n_time) float array; NaN where a station has no value at a step.
352
+ def _write_rows(var, stations: dict, series: dict, t0_us: int, n_times: int, step_us: int, dt, plane=None) -> None:
353
+ """Write the dense ``(n_point, n_time)`` plane ONE STATION ROW AT A TIME.
348
354
 
349
- ``plane=None`` assembles the primary values; a string assembles that named ancillary
350
- (stations lacking it stay NaN), so both planes share this one code path and land on
351
- identical geometry.
355
+ This replaces an earlier ``_assemble`` that built the whole dense plane in memory and
356
+ returned it for a single ``var[:] = ...`` assignment. **That defeated the main reason to use
357
+ cfdb.** cfdb reads and writes in chunks, and the ts_ortho chunk shape is ``(1, time_chunk)``
358
+ — *one station row* — so the whole-plane approach allocated a station-count multiple of what
359
+ a write actually needs. Measured on a 606-station by 620,771-step dataset: 3.01 GB per plane,
360
+ two planes, and roughly double again for ``_nan_safe``'s mask and copy. Per row it is ~5 MB.
361
+
362
+ ``plane=None`` writes the primary values; a string writes that named ancillary (stations
363
+ lacking it stay NaN), so both share one code path and land on identical geometry.
364
+
365
+ ⚠️ **Iterate ``stations``, never ``series``.** The point coordinate and the
366
+ ``station_id``/``station_ref``/``station_name`` arrays are built in ``stations`` order, so row
367
+ ``i`` MUST be the ``i``-th entry of ``stations``. Driving the loop from ``series`` instead
368
+ would map the *i*-th station-that-has-data to point *i* and silently mislabel every station
369
+ after the first data-less one — a file that validates cleanly and is wrong.
370
+
371
+ A station with no data still gets an explicitly written all-NaN row, exactly as before: an
372
+ unwritten chunk also reads as NaN, but it would change which chunks exist and the file size.
373
+
374
+ Each row is written in ONE call, and each chunk therefore exactly once. Revisiting a chunk
375
+ costs a full decompress+recompress, orphans the previous block (the store is log-structured,
376
+ so the file grows until pruned), and can force a synchronous buffer flush.
352
377
  """
353
- data = np.full((len(stations), n_times), np.nan, dtype='float64')
354
378
  for i, ref in enumerate(stations):
379
+ # a fresh row per station: nothing is ever aliased into cfdb's chunk buffer, and the
380
+ # peak is one row regardless of station count
381
+ row = np.full(n_times, np.nan, dtype='float64')
355
382
  s = series.get(ref)
356
- if s is None:
357
- continue
358
- t, v, ex = s
359
- arr = v if plane is None else ex.get(plane)
360
- if arr is None:
361
- continue
362
- col = _step_index(t, t0_us, step_us)
363
- ok = (col >= 0) & (col < n_times)
364
- data[i, col[ok]] = arr[ok]
365
- return data
383
+ if s is not None:
384
+ t, v, ex = s
385
+ arr = v if plane is None else ex.get(plane)
386
+ if arr is not None:
387
+ col = _step_index(t, t0_us, step_us)
388
+ ok = (col >= 0) & (col < n_times)
389
+ row[col[ok]] = arr[ok]
390
+ var[i, :] = _nan_safe(row, dt)
366
391
 
367
392
 
368
393
  def _points_ids_names(stations: dict):
@@ -487,7 +512,8 @@ def build_local(
487
512
  tmin = _floor_step(min(int(t.astype('int64').min()) for t, *_ in non_empty.values()), step_us)
488
513
  tmax = _floor_step(max(int(t.astype('int64').max()) for t, *_ in non_empty.values()), step_us)
489
514
  times_us = np.arange(tmin, tmax + 1, step_us)
490
- data = _assemble(stations, non_empty, tmin, times_us.size, step_us)
515
+ # NOTE: the dense plane is NOT assembled here. Rows are written individually inside the
516
+ # dataset context below (see _write_rows) so peak memory is one row, not one plane.
491
517
  points, ids, names, refs = _points_ids_names(stations)
492
518
 
493
519
  if chunk_shape is None:
@@ -521,7 +547,7 @@ def build_local(
521
547
  # merge_dataset reads back, so the stored dataset stays the source of truth on update.
522
548
  if ancillary:
523
549
  dv.attrs['ancillary_variables'] = ' '.join(ancillary)
524
- dv[:] = _nan_safe(data, dt)
550
+ _write_rows(dv, stations, non_empty, tmin, times_us.size, step_us, dt)
525
551
 
526
552
  for aname, spec in ancillary.items():
527
553
  adt = dtypes.dtype(
@@ -537,9 +563,10 @@ def build_local(
537
563
  # written LAST so a caller-supplied attrs dict can never weaken the QC bounds
538
564
  av.attrs['valid_min'] = float(spec['min_value'])
539
565
  av.attrs['valid_max'] = float(spec['max_value'])
540
- av[:] = _nan_safe(
541
- _assemble(stations, non_empty, tmin, times_us.size, step_us, plane=aname), adt
542
- )
566
+ # Previously this nested a whole-plane _assemble INSIDE _nan_safe while the primary
567
+ # plane was still resident — three full planes plus a mask live at once, the worst
568
+ # single moment in the build. Now one row at a time, like the primary.
569
+ _write_rows(av, stations, non_empty, tmin, times_us.size, step_us, adt, plane=aname)
543
570
 
544
571
  sid = ds.create.data_var.generic(STATION_ID_VAR, ('point',), dtype=dtypes.dtype('str'))
545
572
  sid[:] = ids
@@ -569,9 +596,10 @@ def merge_dataset(ds, stations: dict, series: dict, *, variable: str):
569
596
 
570
597
  The cadence comes from the dataset's own ``envlib_frequency_interval`` attr (written at
571
598
  build), cross-checked against the actual axis (origin on the epoch grid, dense constant
572
- step). Appends new stations and new steps (in the coord's stored dtype), then does a single
573
- contiguous read-modify-write over the affected time block, keeping existing values where
574
- the incoming value is NaN. Idempotent for a fixed input window.
599
+ step). Appends new stations and new steps (in the coord's stored dtype), then read-modify-writes
600
+ ONE STATION AT A TIME, each over its own window, keeping existing values where the incoming
601
+ value is NaN. Idempotent for a fixed input window. Stations that supply nothing this run are
602
+ not read or written at all.
575
603
 
576
604
  Requires a writable dataset: the station-attr heal runs on every call (even an empty window,
577
605
  before the early return), so calling this on a read-only dataset raises rather than no-opping.
@@ -701,43 +729,77 @@ def merge_dataset(ds, stations: dict, series: dict, *, variable: str):
701
729
  if w_hi < 0:
702
730
  msg = f'incoming window ends before the axis start ({tdata[0]}) — refusing to prepend history'
703
731
  raise ValueError(msg)
704
- w_lo = max((inc_min - t0) // step_us, 0)
705
- width = w_hi - w_lo + 1
706
- existing = np.asarray(dv[:, w_lo : w_hi + 1].data, dtype='float64') # (n_point_total, width)
707
- incoming = np.full_like(existing, np.nan)
708
- existing_a = {n: np.asarray(anc_vars[n][:, w_lo : w_hi + 1].data, dtype='float64') for n in anc_names}
709
- incoming_a = {n: np.full_like(existing, np.nan) for n in anc_names}
732
+ # ONE STATION AT A TIME, each over ITS OWN window — never one block spanning every point.
733
+ #
734
+ # This previously read `dv[:, w_lo:w_hi+1]` across the FULL point dimension, where w_lo/w_hi
735
+ # came from the GLOBAL min/max incoming timestamp. Two consequences, both bad:
736
+ #
737
+ # * MEMORY: ~6-7 float64 blocks of (n_point x global_width) live at once. One station
738
+ # reporting a backdated timestamp widened the block for EVERY station — measured, a
739
+ # single stale value took a 48-step merge from 9 MB to 228 MB, and at production scale
740
+ # that is gigabytes inside an hourly cron.
741
+ # * WRITE AMPLIFICATION: every station's chunks in the block were rewritten even when that
742
+ # station supplied nothing this run (its slots merged to `existing`, i.e. back to
743
+ # themselves). Since the store is log-structured and the remote pushes changed keys,
744
+ # that is an upload of the whole block's chunks on every single run.
745
+ #
746
+ # Per-station is simply correct here: the union mask is elementwise and `incoming[row]` only
747
+ # ever carries data for the station at `row`, so there is NO cross-station dependency to
748
+ # preserve. Each station's window is its own, so a backdated value widens only its own read,
749
+ # and stations that reported nothing are not touched at all.
750
+ #
751
+ # chunk_shape is (1, time_chunk), so a row IS the chunk row: this reads and writes exactly
752
+ # the chunks it must, one station's worth at a time.
710
753
  n_before = 0
754
+ widest = 0
711
755
  for ref, (t, v, ex) in non_empty.items():
712
756
  d = stations[ref]
713
757
  sid = envlib.compute_station_id(shapely.Point(float(d['lon']), float(d['lat'])))
714
758
  row = id_to_row[sid]
715
- col = _step_index(t, t0, step_us) - w_lo
716
- ok = (col >= 0) & (col < width)
717
- n_before += int((col < 0).sum()) # window straddles the axis start: pre-axis values
718
- incoming[row, col[ok]] = v[ok]
759
+ col_abs = _step_index(t, t0, step_us)
760
+ n_before += int((col_abs < 0).sum()) # window straddles the axis start: pre-axis values
761
+ keep = col_abs >= 0
762
+ if not keep.any():
763
+ continue
764
+ lo, hi = int(col_abs[keep].min()), int(col_abs[keep].max())
765
+ width = hi - lo + 1
766
+ widest = max(widest, width)
767
+ col = col_abs[keep] - lo
768
+
769
+ existing = np.asarray(dv[row, lo : hi + 1].data, dtype='float64').ravel()
770
+ incoming = np.full(width, np.nan)
771
+ incoming[col] = v[keep]
772
+ existing_a, incoming_a = {}, {}
719
773
  for n in anc_names:
774
+ existing_a[n] = np.asarray(anc_vars[n][row, lo : hi + 1].data, dtype='float64').ravel()
775
+ inc = np.full(width, np.nan)
720
776
  a = ex.get(n)
721
777
  if a is not None:
722
- incoming_a[n][row, col[ok]] = a[ok]
778
+ inc[col] = a[keep]
779
+ incoming_a[n] = inc
780
+
781
+ # UNION mask: a slot is "supplied by this run" if the primary OR any ancillary has data
782
+ # there. One mask drives every plane, so a stored (value, code) pair can never be
783
+ # assembled from two different runs — and a code that explains an absent value survives.
784
+ mask = ~np.isnan(incoming)
785
+ for n in anc_names:
786
+ mask |= ~np.isnan(incoming_a[n])
787
+ dv[row, lo : hi + 1] = _nan_safe(np.where(mask, incoming, existing), dv.dtype)
788
+ for n in anc_names:
789
+ merged_a = np.where(mask, incoming_a[n], existing_a[n])
790
+ anc_vars[n][row, lo : hi + 1] = _nan_safe(merged_a, anc_vars[n].dtype)
791
+
723
792
  if n_before:
724
793
  logger.warning('merge %s: %d incoming value(s) predate the axis start and were dropped', variable, n_before)
725
-
726
- # UNION mask: a slot is "supplied by this run" if the primary OR any ancillary has data
727
- # there. One mask drives every plane, so a stored (value, code) pair can never be assembled
728
- # from two different runs — and a code that exists to explain an absent value survives.
729
- mask = ~np.isnan(incoming)
730
- for n in anc_names:
731
- mask |= ~np.isnan(incoming_a[n])
732
- merged = np.where(mask, incoming, existing)
733
- dv[:, w_lo : w_hi + 1] = _nan_safe(merged, dv.dtype)
734
- for n in anc_names:
735
- merged_a = np.where(mask, incoming_a[n], existing_a[n])
736
- anc_vars[n][:, w_lo : w_hi + 1] = _nan_safe(merged_a, anc_vars[n].dtype)
737
794
  return {
738
795
  'new_stations': n_new,
739
796
  'new_steps': int(n_new_steps),
740
- 'written_block': int(width),
797
+ # WIDEST single station's window, not one global block — the merge no longer has a
798
+ # single block width. Nothing consumes this field (ingest.py reads only gap_steps); it
799
+ # is a diagnostic, and per-station is the more useful reading of it anyway: a large
800
+ # value now means one station genuinely carried a wide window, not that one stale
801
+ # timestamp stretched the block across every station.
802
+ 'written_block': int(widest),
741
803
  'gap_steps': int(gap_steps),
742
804
  'qc_rejected': int(n_qc),
743
805
  'anc_qc_rejected': int(n_anc_qc),