stac-valid 4.6.1__tar.gz → 4.6.2__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.
Files changed (37) hide show
  1. {stac_valid-4.6.1/stac_valid.egg-info → stac_valid-4.6.2}/PKG-INFO +2 -2
  2. {stac_valid-4.6.1 → stac_valid-4.6.2}/pyproject.toml +9 -2
  3. {stac_valid-4.6.1 → stac_valid-4.6.2/stac_valid.egg-info}/PKG-INFO +2 -2
  4. {stac_valid-4.6.1 → stac_valid-4.6.2}/stac_valid.egg-info/requires.txt +1 -1
  5. {stac_valid-4.6.1 → stac_valid-4.6.2}/stac_validator/fast_validator.py +33 -6
  6. {stac_valid-4.6.1 → stac_valid-4.6.2}/tests/test_fast_validator.py +176 -1
  7. {stac_valid-4.6.1 → stac_valid-4.6.2}/LICENSE +0 -0
  8. {stac_valid-4.6.1 → stac_valid-4.6.2}/README.md +0 -0
  9. {stac_valid-4.6.1 → stac_valid-4.6.2}/setup.cfg +0 -0
  10. {stac_valid-4.6.1 → stac_valid-4.6.2}/stac_valid.egg-info/SOURCES.txt +0 -0
  11. {stac_valid-4.6.1 → stac_valid-4.6.2}/stac_valid.egg-info/dependency_links.txt +0 -0
  12. {stac_valid-4.6.1 → stac_valid-4.6.2}/stac_valid.egg-info/entry_points.txt +0 -0
  13. {stac_valid-4.6.1 → stac_valid-4.6.2}/stac_valid.egg-info/top_level.txt +0 -0
  14. {stac_valid-4.6.1 → stac_valid-4.6.2}/stac_validator/__init__.py +0 -0
  15. {stac_valid-4.6.1 → stac_valid-4.6.2}/stac_validator/batch_validator.py +0 -0
  16. {stac_valid-4.6.1 → stac_valid-4.6.2}/stac_validator/stac_validator.py +0 -0
  17. {stac_valid-4.6.1 → stac_valid-4.6.2}/stac_validator/utilities.py +0 -0
  18. {stac_valid-4.6.1 → stac_valid-4.6.2}/stac_validator/validate.py +0 -0
  19. {stac_valid-4.6.1 → stac_valid-4.6.2}/tests/test_assets.py +0 -0
  20. {stac_valid-4.6.1 → stac_valid-4.6.2}/tests/test_batch_validator.py +0 -0
  21. {stac_valid-4.6.1 → stac_valid-4.6.2}/tests/test_config.py +0 -0
  22. {stac_valid-4.6.1 → stac_valid-4.6.2}/tests/test_core.py +0 -0
  23. {stac_valid-4.6.1 → stac_valid-4.6.2}/tests/test_custom.py +0 -0
  24. {stac_valid-4.6.1 → stac_valid-4.6.2}/tests/test_default.py +0 -0
  25. {stac_valid-4.6.1 → stac_valid-4.6.2}/tests/test_error_reporting.py +0 -0
  26. {stac_valid-4.6.1 → stac_valid-4.6.2}/tests/test_extensions.py +0 -0
  27. {stac_valid-4.6.1 → stac_valid-4.6.2}/tests/test_fast_validator_enhancements.py +0 -0
  28. {stac_valid-4.6.1 → stac_valid-4.6.2}/tests/test_header.py +0 -0
  29. {stac_valid-4.6.1 → stac_valid-4.6.2}/tests/test_heavy_extensions.py +0 -0
  30. {stac_valid-4.6.1 → stac_valid-4.6.2}/tests/test_links.py +0 -0
  31. {stac_valid-4.6.1 → stac_valid-4.6.2}/tests/test_pydantic.py +0 -0
  32. {stac_valid-4.6.1 → stac_valid-4.6.2}/tests/test_recursion.py +0 -0
  33. {stac_valid-4.6.1 → stac_valid-4.6.2}/tests/test_schema_cache.py +0 -0
  34. {stac_valid-4.6.1 → stac_valid-4.6.2}/tests/test_sys_exit.py +0 -0
  35. {stac_valid-4.6.1 → stac_valid-4.6.2}/tests/test_validate_collections.py +0 -0
  36. {stac_valid-4.6.1 → stac_valid-4.6.2}/tests/test_validate_dict.py +0 -0
  37. {stac_valid-4.6.1 → stac_valid-4.6.2}/tests/test_validate_item_collection.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: stac_valid
3
- Version: 4.6.1
3
+ Version: 4.6.2
4
4
  Summary: A package to validate STAC files
5
5
  Author: James Banting
6
6
  Author-email: Jonathan Healy <jon@healy-hyperspatial.dev>
@@ -33,7 +33,7 @@ Requires-Dist: pre-commit; extra == "dev"
33
33
  Requires-Dist: requests-mock; extra == "dev"
34
34
  Requires-Dist: types-setuptools; extra == "dev"
35
35
  Requires-Dist: stac-pydantic>=3.3.0; extra == "dev"
36
- Requires-Dist: mypy; extra == "dev"
36
+ Requires-Dist: mypy==2.4.1; extra == "dev"
37
37
  Requires-Dist: types-attrs; extra == "dev"
38
38
  Requires-Dist: types-requests; extra == "dev"
39
39
  Requires-Dist: types-jsonschema; extra == "dev"
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "stac_valid"
7
- version = "4.6.1"
7
+ version = "4.6.2"
8
8
  description = "A package to validate STAC files"
9
9
  authors = [
10
10
  {name = "Jonathan Healy", email = "jon@healy-hyperspatial.dev"},
@@ -43,7 +43,7 @@ dev = [
43
43
  "requests-mock",
44
44
  "types-setuptools",
45
45
  "stac-pydantic>=3.3.0",
46
- "mypy",
46
+ "mypy==2.4.1",
47
47
  "types-attrs",
48
48
  "types-requests",
49
49
  "types-jsonschema",
@@ -65,6 +65,13 @@ Repository = "https://github.com/stac-utils/stac-validator"
65
65
  file = "README.md"
66
66
  content-type = "text/markdown"
67
67
 
68
+ [tool.mypy]
69
+ strict_optional = false
70
+ ignore_missing_imports = true
71
+ implicit_reexport = true
72
+ explicit_package_bases = true
73
+ exclude = "^tests/"
74
+
68
75
  [tool.setuptools]
69
76
  packages = ["stac_validator"]
70
77
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: stac_valid
3
- Version: 4.6.1
3
+ Version: 4.6.2
4
4
  Summary: A package to validate STAC files
5
5
  Author: James Banting
6
6
  Author-email: Jonathan Healy <jon@healy-hyperspatial.dev>
@@ -33,7 +33,7 @@ Requires-Dist: pre-commit; extra == "dev"
33
33
  Requires-Dist: requests-mock; extra == "dev"
34
34
  Requires-Dist: types-setuptools; extra == "dev"
35
35
  Requires-Dist: stac-pydantic>=3.3.0; extra == "dev"
36
- Requires-Dist: mypy; extra == "dev"
36
+ Requires-Dist: mypy==2.4.1; extra == "dev"
37
37
  Requires-Dist: types-attrs; extra == "dev"
38
38
  Requires-Dist: types-requests; extra == "dev"
39
39
  Requires-Dist: types-jsonschema; extra == "dev"
@@ -14,7 +14,7 @@ pre-commit
14
14
  requests-mock
15
15
  types-setuptools
16
16
  stac-pydantic>=3.3.0
17
- mypy
17
+ mypy==2.4.1
18
18
  types-attrs
19
19
  types-requests
20
20
  types-jsonschema
@@ -8,7 +8,7 @@ import threading
8
8
  import time
9
9
  from concurrent.futures import Future, ThreadPoolExecutor
10
10
  from contextlib import redirect_stderr, redirect_stdout
11
- from typing import Any, Dict, List, Optional, Set, Tuple
11
+ from typing import Any, Callable, Dict, List, Optional, Set, Tuple
12
12
 
13
13
  import click
14
14
  import fastjsonschema # type: ignore
@@ -134,6 +134,8 @@ def get_cache_directory() -> str:
134
134
  # --- Thread-Safe Caches & Lock ---
135
135
  SCHEMA_CACHE: Dict[str, Any] = {}
136
136
  VALIDATOR_CACHE: Dict[Any, Any] = {}
137
+ # Builds in progress, so concurrent callers for the same key wait for one compile
138
+ VALIDATOR_BUILDS: Dict[Any, "Future[Any]"] = {}
137
139
  CACHE_LOCK = threading.Lock()
138
140
  # Dynamically determine writable cache directory across environments
139
141
  LOCAL_SCHEMA_DIR = get_cache_directory()
@@ -464,11 +466,39 @@ def get_validator(
464
466
  ext_key = tuple(sorted(extensions))
465
467
  cache_key = (stac_type, stac_version, ext_key)
466
468
 
467
- # Thread-safe Cache Read
469
+ # Thread-safe Cache Read; join the in-flight build for this key if there is one
468
470
  with CACHE_LOCK:
469
471
  if cache_key in VALIDATOR_CACHE:
470
472
  return VALIDATOR_CACHE[cache_key], True
473
+ build = VALIDATOR_BUILDS.get(cache_key)
474
+ is_builder = build is None
475
+ if build is None:
476
+ build = VALIDATOR_BUILDS[cache_key] = Future()
471
477
 
478
+ if not is_builder:
479
+ # Another thread is building this key: share its validator or its exception.
480
+ return build.result(), True
481
+
482
+ try:
483
+ validator = _build_validator(stac_type, stac_version, extensions, quiet)
484
+ except BaseException as e:
485
+ with CACHE_LOCK:
486
+ del VALIDATOR_BUILDS[cache_key]
487
+ build.set_exception(e)
488
+ raise
489
+
490
+ # Cache the resulting validator so future items use it instantly (Thread-safe Write)
491
+ with CACHE_LOCK:
492
+ VALIDATOR_CACHE[cache_key] = validator
493
+ del VALIDATOR_BUILDS[cache_key]
494
+ build.set_result(validator)
495
+ return validator, False
496
+
497
+
498
+ def _build_validator(
499
+ stac_type: str, stac_version: str, extensions: List[str], quiet: bool
500
+ ) -> Callable[[Dict[str, Any]], None]:
501
+ """Fetches and compiles the base and extension schemas into one validator."""
472
502
  # Determine base schema URI
473
503
  stac_type_lower = stac_type.lower()
474
504
  if stac_type_lower in ["item", "feature"]:
@@ -663,10 +693,7 @@ def get_validator(
663
693
  if collected_errors:
664
694
  raise FastSTACMultiValidationError(collected_errors)
665
695
 
666
- # Cache the resulting validator so future items use it instantly (Thread-safe Write)
667
- with CACHE_LOCK:
668
- VALIDATOR_CACHE[cache_key] = validator
669
- return validator, False
696
+ return validator
670
697
 
671
698
 
672
699
  class FastValidator:
@@ -1,8 +1,12 @@
1
1
  import json
2
+ import threading
3
+ import time
4
+ from concurrent.futures import Future
2
5
 
3
6
  import pytest
4
7
 
5
- from stac_validator.fast_validator import FastValidator
8
+ from stac_validator import fast_validator
9
+ from stac_validator.fast_validator import FastSTACMultiValidationError, FastValidator
6
10
 
7
11
 
8
12
  @pytest.fixture
@@ -1078,3 +1082,174 @@ class TestFastValidatorPerformance:
1078
1082
  assert "count" in error
1079
1083
  assert isinstance(error["affected_items"], list)
1080
1084
  assert error["count"] == len(error["affected_items"])
1085
+
1086
+
1087
+ def _item_schema_uri(version):
1088
+ return f"https://schemas.stacspec.org/v{version}/item-spec/json-schema/item.json"
1089
+
1090
+
1091
+ def _prefill_item_schema(version):
1092
+ fast_validator.SCHEMA_CACHE[_item_schema_uri(version)] = {
1093
+ "type": "object",
1094
+ "required": ["id"],
1095
+ }
1096
+
1097
+
1098
+ def _run_in_threads(targets):
1099
+ """Run each callable in its own thread; return its result or the exception it raised."""
1100
+ results = [None] * len(targets)
1101
+
1102
+ def run(index, target):
1103
+ try:
1104
+ results[index] = target()
1105
+ except Exception as e:
1106
+ results[index] = e
1107
+
1108
+ # Daemon threads and one shared deadline: a stuck waiter fails the test, not the run.
1109
+ threads = [
1110
+ threading.Thread(target=run, args=(index, target), daemon=True)
1111
+ for index, target in enumerate(targets)
1112
+ ]
1113
+ for thread in threads:
1114
+ thread.start()
1115
+ deadline = time.monotonic() + 30
1116
+ for thread in threads:
1117
+ thread.join(max(0, deadline - time.monotonic()))
1118
+ assert not any(thread.is_alive() for thread in threads), "worker threads hung"
1119
+ return results
1120
+
1121
+
1122
+ @pytest.fixture
1123
+ def fake_version():
1124
+ """Return unique fake STAC versions and drop their cached schemas and validators."""
1125
+ versions = []
1126
+
1127
+ def make(name):
1128
+ version = f"0.0.0-singleflight-{name}"
1129
+ versions.append(version)
1130
+ return version
1131
+
1132
+ yield make
1133
+ for version in versions:
1134
+ fast_validator.SCHEMA_CACHE.pop(_item_schema_uri(version), None)
1135
+ fast_validator.VALIDATOR_CACHE.pop(("Item", version, ()), None)
1136
+
1137
+
1138
+ class TestGetValidatorConcurrency:
1139
+ """Concurrent cold get_validator calls build each cache key once."""
1140
+
1141
+ def test_get_validator_compiles_once_under_concurrency(
1142
+ self, fake_version, monkeypatch
1143
+ ):
1144
+ version = fake_version("same-key")
1145
+ _prefill_item_schema(version)
1146
+ compile_calls = []
1147
+ original_compile = fast_validator.compile_unrolled_schema
1148
+
1149
+ def counting_compile(schema, quiet=False):
1150
+ compile_calls.append(schema)
1151
+ time.sleep(0.05) # widen the race window
1152
+ return original_compile(schema, quiet=quiet)
1153
+
1154
+ monkeypatch.setattr(fast_validator, "compile_unrolled_schema", counting_compile)
1155
+ start = threading.Barrier(20)
1156
+
1157
+ def call():
1158
+ start.wait(timeout=5)
1159
+ validator, was_cached = fast_validator.get_validator(
1160
+ "Item", version, [], quiet=True
1161
+ )
1162
+ validator({"id": "x"})
1163
+ return validator, was_cached
1164
+
1165
+ results = _run_in_threads([call] * 20)
1166
+
1167
+ assert [r for r in results if isinstance(r, Exception)] == []
1168
+ assert len(compile_calls) == 1
1169
+ assert len({id(validator) for validator, _ in results}) == 1
1170
+ assert [was_cached for _, was_cached in results].count(False) == 1
1171
+ with pytest.raises(FastSTACMultiValidationError):
1172
+ results[0][0]({})
1173
+
1174
+ def test_get_validator_compiles_different_keys_in_parallel(
1175
+ self, fake_version, monkeypatch
1176
+ ):
1177
+ versions = [fake_version("parallel-a"), fake_version("parallel-b")]
1178
+ for version in versions:
1179
+ _prefill_item_schema(version)
1180
+ both_compiling = threading.Event()
1181
+ rendezvous = threading.Barrier(2, action=both_compiling.set)
1182
+ original_compile = fast_validator.compile_unrolled_schema
1183
+
1184
+ def compile_together(schema, quiet=False):
1185
+ # Tier 1's fallback swallows a BrokenBarrierError, so the event is the check.
1186
+ rendezvous.wait(timeout=5)
1187
+ return original_compile(schema, quiet=quiet)
1188
+
1189
+ monkeypatch.setattr(fast_validator, "compile_unrolled_schema", compile_together)
1190
+
1191
+ results = _run_in_threads(
1192
+ [
1193
+ lambda v=version: fast_validator.get_validator(
1194
+ "Item", v, [], quiet=True
1195
+ )
1196
+ for version in versions
1197
+ ]
1198
+ )
1199
+
1200
+ assert [r for r in results if isinstance(r, Exception)] == []
1201
+ assert both_compiling.is_set()
1202
+
1203
+ def test_get_validator_shares_build_failure_then_retries(
1204
+ self, fake_version, monkeypatch
1205
+ ):
1206
+ version = fake_version("failure")
1207
+ workers = 20
1208
+ arrived = threading.Condition()
1209
+ arrivals = 0
1210
+ fetch_calls = []
1211
+
1212
+ def arrive():
1213
+ nonlocal arrivals
1214
+ with arrived:
1215
+ arrivals += 1
1216
+ arrived.notify_all()
1217
+
1218
+ class CountingFuture(Future):
1219
+ def result(self, timeout=None):
1220
+ arrive()
1221
+ return super().result(timeout=10)
1222
+
1223
+ def failing_fetch(uri, quiet=False):
1224
+ fetch_calls.append(uri)
1225
+ arrive()
1226
+ # Fail only once every worker is either fetching or waiting on the build.
1227
+ with arrived:
1228
+ arrived.wait_for(lambda: arrivals == workers, timeout=5)
1229
+ raise RuntimeError("schema fetch failed")
1230
+
1231
+ # get_validator creates in-flight builds from this module-level name.
1232
+ monkeypatch.setattr(fast_validator, "Future", CountingFuture)
1233
+ monkeypatch.setattr(fast_validator, "fetch_schema", failing_fetch)
1234
+ start = threading.Barrier(workers)
1235
+
1236
+ def call():
1237
+ start.wait(timeout=5)
1238
+ return fast_validator.get_validator("Item", version, [], quiet=True)
1239
+
1240
+ results = _run_in_threads([call] * workers)
1241
+
1242
+ assert all(
1243
+ isinstance(r, RuntimeError) and str(r) == "schema fetch failed"
1244
+ for r in results
1245
+ ), results
1246
+ assert len(fetch_calls) == 1
1247
+ assert fast_validator.VALIDATOR_BUILDS == {}
1248
+
1249
+ monkeypatch.undo()
1250
+ _prefill_item_schema(version)
1251
+ validator, was_cached = fast_validator.get_validator(
1252
+ "Item", version, [], quiet=True
1253
+ )
1254
+ assert was_cached is False
1255
+ validator({"id": "x"})
File without changes
File without changes
File without changes