envlib 0.1.2__tar.gz → 0.1.4__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
- Metadata-Version: 2.4
1
+ Metadata-Version: 2.5
2
2
  Name: envlib
3
- Version: 0.1.2
3
+ Version: 0.1.4
4
4
  Summary: The environmental library
5
5
  Project-URL: Documentation, https://envlib.github.io/envlib/
6
6
  Project-URL: Source, https://github.com/envlib/envlib
@@ -10,7 +10,7 @@ Classifier: Programming Language :: Python :: 3 :: Only
10
10
  Requires-Python: >=3.10
11
11
  Requires-Dist: booklet>=0.12.6
12
12
  Requires-Dist: cfdb>=0.9.1
13
- Requires-Dist: ebooklet>=0.10.0
13
+ Requires-Dist: ebooklet>=0.10.3
14
14
  Requires-Dist: pyproj
15
15
  Requires-Dist: shapely>=2.0
16
16
  Requires-Dist: urllib3
@@ -0,0 +1,17 @@
1
+ """envlib: a distributed database and catalogue for environmental data."""
2
+
3
+ from envlib import vocabularies
4
+ from envlib.catalogue import Catalogue, DatasetRef
5
+ from envlib.metadata import Metadata, ValidationError, canonical_station_point, compute_station_id
6
+
7
+ __version__ = '0.1.4'
8
+
9
+ __all__ = [
10
+ 'Catalogue',
11
+ 'DatasetRef',
12
+ 'Metadata',
13
+ 'ValidationError',
14
+ 'canonical_station_point',
15
+ 'compute_station_id',
16
+ 'vocabularies',
17
+ ]
@@ -27,6 +27,7 @@ from envlib.metadata import (
27
27
  GENERAL_FIELDS,
28
28
  IDENTITY_FIELDS,
29
29
  Metadata,
30
+ PublishIntegrityError,
30
31
  ValidationError,
31
32
  compute_station_id,
32
33
  )
@@ -62,6 +63,34 @@ def _raise_on_push_failure(result, context: str):
62
63
  raise RuntimeError(msg)
63
64
 
64
65
 
66
+ def _verify_remote_objects(member_conn: ebooklet.S3Connection) -> None:
67
+ """Confirm the just-pushed remote's committed index matches the objects
68
+ actually in the store, BEFORE the catalogue entry is written.
69
+
70
+ A push can report success while some objects never durably landed (a
71
+ 2xx-without-persist), leaving the index referencing objects the store does
72
+ not have - a silent over-claim that only surfaces later as a reader's
73
+ RemoteIntegrityError. fsck lists the remote and compares it to the index; any
74
+ mismatch means we must NOT advertise the dataset. Raises PublishIntegrityError
75
+ (a plain re-run does NOT heal it - see the message)."""
76
+ rep = ebooklet.fsck(member_conn, check_objects=True)
77
+ problems = []
78
+ if not rep.db_object_exists:
79
+ problems.append('no db object was committed')
80
+ if rep.claimed_but_missing:
81
+ problems.append(f'{len(rep.claimed_but_missing)} referenced object(s) missing from the store')
82
+ if rep.unmanifested_group_ids:
83
+ problems.append(f'{len(rep.unmanifested_group_ids)} index group(s) absent from the manifest')
84
+ if problems:
85
+ raise PublishIntegrityError(
86
+ f'refusing to register {member_conn.db_key!r}: the pushed remote is inconsistent '
87
+ f'({"; ".join(problems)}). A plain re-run will NOT heal this - the push changelog is a '
88
+ 'timestamp diff (empty once the bad generation is committed) and a fresh rebuild raises '
89
+ 'UUIDMismatchError; recover by retracting the dataset (deregister with delete_data=True) '
90
+ f'and doing a full republish. Missing sample: {list(rep.claimed_but_missing)[:10]}'
91
+ )
92
+
93
+
65
94
  def _public_rcg_url() -> str | None:
66
95
  return os.environ.get(PUBLIC_RCG_ENV_VAR) or PUBLIC_RCG_URL
67
96
 
@@ -333,10 +362,16 @@ def _check_stations(ds):
333
362
  stored = [str(v) for v in sid_var.data]
334
363
  if stored != expected:
335
364
  first_bad = next(i for i, (s, e) in enumerate(zip(stored, expected, strict=True)) if s != e)
365
+ bad_point = points[first_bad]
336
366
  msg = (
337
367
  f'{STATION_ID_VAR!r} values do not match the envlib derivation (first mismatch at index '
338
- f'{first_bad}: stored {stored[first_bad]!r}, derived {expected[first_bad]!r}). '
339
- f'Use envlib.compute_station_id on the EPSG:4326 station points.'
368
+ f'{first_bad}: stored {stored[first_bad]!r}, derived {expected[first_bad]!r} from the '
369
+ f'STORED geometry ({bad_point.x}, {bad_point.y})). The stored GEOMETRY is the usual '
370
+ f'culprit here, not the id: a store may re-round a point as it writes it (cfdb encodes '
371
+ f'point coordinates at 5 decimal places), so a point that derived the stored id before '
372
+ f'the write no longer derives it after. Pass station points through '
373
+ f'envlib.canonical_station_point BEFORE writing them to the geometry coordinate, so '
374
+ f'what is stored is already canonical and the round-trip is stable.'
340
375
  )
341
376
  raise ValidationError(msg)
342
377
 
@@ -768,12 +803,19 @@ class Catalogue:
768
803
  with cfdb.open_dataset(local_cfdb_path) as ds:
769
804
  return _validate_dataset(ds, validate_cv=True)
770
805
 
771
- def publish(self, local_cfdb_path, remote_conn, rcg_remote_conn, num_groups=None, **open_kwargs) -> dict:
772
- """Validate, push the cfdb data to its S3 remote, then register it in the RCG.
806
+ def publish(
807
+ self, local_cfdb_path, remote_conn, rcg_remote_conn, num_groups=None, verify_objects: bool = True, **open_kwargs
808
+ ) -> dict:
809
+ """Validate, push the cfdb data to its S3 remote, verify it, then register it in the RCG.
773
810
 
774
811
  The cfdb data is pushed BEFORE the RCG entry so the catalogue never
775
- references incomplete remote data. Re-running after a partial failure
776
- is safe (the push is idempotent; the entry write is an upsert).
812
+ references incomplete remote data. With ``verify_objects`` (default True),
813
+ after the push and before the entry is written the remote is fsck'd, and a
814
+ silent over-claim (the committed index references objects the store does not
815
+ actually hold) raises ``PublishIntegrityError`` so a broken dataset is never
816
+ advertised. A re-run after a LOUD push failure is safe (idempotent push,
817
+ upsert entry); a re-run after a SILENT over-claim does NOT heal it - recover
818
+ by retract + full republish (see ``_verify_remote_objects``).
777
819
  """
778
820
  member_conn = _as_connection(remote_conn)
779
821
  edataset_kwargs = dict(open_kwargs)
@@ -792,10 +834,12 @@ class Catalogue:
792
834
  _apply_derived_attrs(eds, result)
793
835
  _raise_on_push_failure(eds.push(), 'publish: pushing the dataset data')
794
836
 
837
+ if verify_objects:
838
+ _verify_remote_objects(member_conn)
795
839
  self._upsert_entry(rcg_remote_conn, member_conn, result)
796
840
  return result
797
841
 
798
- def register(self, remote_conn, rcg_remote_conn, **open_kwargs) -> dict:
842
+ def register(self, remote_conn, rcg_remote_conn, verify_objects: bool = True, **open_kwargs) -> dict:
799
843
  """Register an already-remote cfdb file in the catalogue (no data push).
800
844
 
801
845
  ``remote_conn`` must be writable (credentials): first registration
@@ -810,6 +854,8 @@ class Catalogue:
810
854
  if _apply_derived_attrs(eds, result):
811
855
  _raise_on_push_failure(eds.push(), 'register: pushing the self-identification attrs')
812
856
 
857
+ if verify_objects:
858
+ _verify_remote_objects(member_conn)
813
859
  self._upsert_entry(rcg_remote_conn, member_conn, result)
814
860
  return result
815
861
 
@@ -72,6 +72,18 @@ class ValidationError(ValueError):
72
72
  """
73
73
 
74
74
 
75
+ class PublishIntegrityError(ValidationError):
76
+ """Raised when a just-pushed remote is internally inconsistent — its committed
77
+ index references objects that are not actually in the store (a silent
78
+ over-claim). A publish refuses to register such a dataset, so the catalogue
79
+ never advertises broken data.
80
+
81
+ Deliberately NOT an ``ebooklet.RemoteIntegrityError`` (which subclasses
82
+ ``urllib3.exceptions.HTTPError``): a transport-retry wrapper must not mistake
83
+ this permanent integrity fault for a transient network error and retry it.
84
+ """
85
+
86
+
75
87
  ###################################################
76
88
  # Field validators (pure functions; return the normalized value or raise)
77
89
 
@@ -238,13 +250,30 @@ def _hash_fields(field_values) -> str:
238
250
  return blake2b(joined.encode('utf-8'), digest_size=12).hexdigest()
239
251
 
240
252
 
241
- def compute_station_id(geometry) -> str:
242
- """Deterministic station id from a shapely Point in EPSG:4326.
243
-
244
- tethys-compatible derivation: z stripped if present; WKT round-trip with
245
- ``rounding_precision=5`` (~1 m at the equator); signed zero collapsed
246
- (``-0.0`` -> ``0.0``, reachable after reprojection); explicit little-endian
247
- WKB; keyless blake2b-12 hex. Same x/y at different z share a station_id.
253
+ def canonical_station_point(geometry) -> shapely.Point:
254
+ """The canonical EPSG:4326 Point whose WKB :func:`compute_station_id` hashes.
255
+
256
+ z stripped if present; WKT round-trip with ``rounding_precision=5`` (~1 m at
257
+ the equator); signed zero collapsed (``-0.0`` -> ``0.0``, reachable after
258
+ reprojection). Same validation, and the same ``ValidationError``, as
259
+ :func:`compute_station_id` — a producer wants a bad geometry rejected here
260
+ rather than one step later.
261
+
262
+ **Producers must STORE this point, not the raw one.** A store that re-rounds
263
+ the geometry its own way will otherwise hold a point that no longer derives
264
+ the ``station_id`` stored beside it, and the dataset becomes unpublishable.
265
+ cfdb is exactly such a store: it encodes point coordinates with
266
+ ``shapely.to_wkt(..., rounding_precision=5)``, whose ``trim=True`` default
267
+ rounds the shortest decimal *string* half-to-even, while the derivation here
268
+ uses ``wkt.dumps`` (``trim=False``), which rounds the underlying *binary*
269
+ value. The two disagree on roughly 9% of coordinates given to 6 decimal
270
+ places — every case being an ordinate whose shortest representation ends in
271
+ a trailing '5' past the 5th decimal. Passing a point through this function
272
+ first makes the round-trip a fixed point, because a canonical point has no
273
+ 6th decimal left to round. (envlib 0.1.4; found on a live publish failure,
274
+ 2026-08-24.)
275
+
276
+ Idempotent: ``canonical_station_point(canonical_station_point(p))`` is ``p``.
248
277
  """
249
278
  if not isinstance(geometry, shapely.Point):
250
279
  msg = f'station geometry must be a shapely Point (v1 supports Points only), not {type(geometry).__name__}.'
@@ -260,7 +289,22 @@ def compute_station_id(geometry) -> str:
260
289
  if geometry.has_z:
261
290
  geometry = shapely.Point(geometry.x, geometry.y)
262
291
  rounded = cast('shapely.Point', wkt.loads(wkt.dumps(geometry, rounding_precision=5)))
263
- canonical_point = shapely.Point(rounded.x + 0.0, rounded.y + 0.0)
292
+ return shapely.Point(rounded.x + 0.0, rounded.y + 0.0)
293
+
294
+
295
+ def compute_station_id(geometry) -> str:
296
+ """Deterministic station id from a shapely Point in EPSG:4326.
297
+
298
+ tethys-compatible derivation: z stripped if present; WKT round-trip with
299
+ ``rounding_precision=5`` (~1 m at the equator); signed zero collapsed
300
+ (``-0.0`` -> ``0.0``, reachable after reprojection); explicit little-endian
301
+ WKB; keyless blake2b-12 hex. Same x/y at different z share a station_id.
302
+
303
+ The canonicalization is :func:`canonical_station_point`; this hashes its WKB.
304
+ Splitting the two moved no id (verified against 0.1.3 over ~143,000 points
305
+ in review round ``envlib-stationid-1``, including exception parity).
306
+ """
307
+ canonical_point = canonical_station_point(geometry)
264
308
  return blake2b(shapely.to_wkb(canonical_point, byte_order=1), digest_size=12).hexdigest()
265
309
 
266
310
 
@@ -12,7 +12,7 @@ classifiers = [
12
12
  requires-python = ">=3.10"
13
13
  dependencies = [
14
14
  "cfdb>=0.9.1",
15
- "ebooklet>=0.10.0",
15
+ "ebooklet>=0.10.3",
16
16
  "booklet>=0.12.6",
17
17
  "pyproj",
18
18
  "shapely>=2.0",
@@ -1,9 +0,0 @@
1
- """envlib: a distributed database and catalogue for environmental data."""
2
-
3
- from envlib import vocabularies
4
- from envlib.catalogue import Catalogue, DatasetRef
5
- from envlib.metadata import Metadata, ValidationError, compute_station_id
6
-
7
- __version__ = '0.1.2'
8
-
9
- __all__ = ['Catalogue', 'DatasetRef', 'Metadata', 'ValidationError', 'compute_station_id', 'vocabularies']
File without changes
File without changes
File without changes