stac-valid 4.6.0__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.0/stac_valid.egg-info → stac_valid-4.6.2}/PKG-INFO +2 -2
  2. {stac_valid-4.6.0 → stac_valid-4.6.2}/pyproject.toml +9 -2
  3. {stac_valid-4.6.0 → stac_valid-4.6.2/stac_valid.egg-info}/PKG-INFO +2 -2
  4. {stac_valid-4.6.0 → stac_valid-4.6.2}/stac_valid.egg-info/requires.txt +1 -1
  5. {stac_valid-4.6.0 → stac_valid-4.6.2}/stac_validator/fast_validator.py +139 -34
  6. {stac_valid-4.6.0 → stac_valid-4.6.2}/tests/test_fast_validator.py +176 -1
  7. {stac_valid-4.6.0 → stac_valid-4.6.2}/LICENSE +0 -0
  8. {stac_valid-4.6.0 → stac_valid-4.6.2}/README.md +0 -0
  9. {stac_valid-4.6.0 → stac_valid-4.6.2}/setup.cfg +0 -0
  10. {stac_valid-4.6.0 → stac_valid-4.6.2}/stac_valid.egg-info/SOURCES.txt +0 -0
  11. {stac_valid-4.6.0 → stac_valid-4.6.2}/stac_valid.egg-info/dependency_links.txt +0 -0
  12. {stac_valid-4.6.0 → stac_valid-4.6.2}/stac_valid.egg-info/entry_points.txt +0 -0
  13. {stac_valid-4.6.0 → stac_valid-4.6.2}/stac_valid.egg-info/top_level.txt +0 -0
  14. {stac_valid-4.6.0 → stac_valid-4.6.2}/stac_validator/__init__.py +0 -0
  15. {stac_valid-4.6.0 → stac_valid-4.6.2}/stac_validator/batch_validator.py +0 -0
  16. {stac_valid-4.6.0 → stac_valid-4.6.2}/stac_validator/stac_validator.py +0 -0
  17. {stac_valid-4.6.0 → stac_valid-4.6.2}/stac_validator/utilities.py +0 -0
  18. {stac_valid-4.6.0 → stac_valid-4.6.2}/stac_validator/validate.py +0 -0
  19. {stac_valid-4.6.0 → stac_valid-4.6.2}/tests/test_assets.py +0 -0
  20. {stac_valid-4.6.0 → stac_valid-4.6.2}/tests/test_batch_validator.py +0 -0
  21. {stac_valid-4.6.0 → stac_valid-4.6.2}/tests/test_config.py +0 -0
  22. {stac_valid-4.6.0 → stac_valid-4.6.2}/tests/test_core.py +0 -0
  23. {stac_valid-4.6.0 → stac_valid-4.6.2}/tests/test_custom.py +0 -0
  24. {stac_valid-4.6.0 → stac_valid-4.6.2}/tests/test_default.py +0 -0
  25. {stac_valid-4.6.0 → stac_valid-4.6.2}/tests/test_error_reporting.py +0 -0
  26. {stac_valid-4.6.0 → stac_valid-4.6.2}/tests/test_extensions.py +0 -0
  27. {stac_valid-4.6.0 → stac_valid-4.6.2}/tests/test_fast_validator_enhancements.py +0 -0
  28. {stac_valid-4.6.0 → stac_valid-4.6.2}/tests/test_header.py +0 -0
  29. {stac_valid-4.6.0 → stac_valid-4.6.2}/tests/test_heavy_extensions.py +0 -0
  30. {stac_valid-4.6.0 → stac_valid-4.6.2}/tests/test_links.py +0 -0
  31. {stac_valid-4.6.0 → stac_valid-4.6.2}/tests/test_pydantic.py +0 -0
  32. {stac_valid-4.6.0 → stac_valid-4.6.2}/tests/test_recursion.py +0 -0
  33. {stac_valid-4.6.0 → stac_valid-4.6.2}/tests/test_schema_cache.py +0 -0
  34. {stac_valid-4.6.0 → stac_valid-4.6.2}/tests/test_sys_exit.py +0 -0
  35. {stac_valid-4.6.0 → stac_valid-4.6.2}/tests/test_validate_collections.py +0 -0
  36. {stac_valid-4.6.0 → stac_valid-4.6.2}/tests/test_validate_dict.py +0 -0
  37. {stac_valid-4.6.0 → 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.0
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.0"
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.0
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()
@@ -217,8 +219,12 @@ def fetch_schema(uri: str, quiet: bool = False) -> Dict[str, Any]:
217
219
 
218
220
 
219
221
  def compile_unrolled_schema(schema_dict: Dict[str, Any], quiet: bool = False) -> Any:
220
- """Unrolls top-level oneOf/anyOf branches into separate compiled fastjsonschema functions
221
- so field-level errors are never swallowed by branch exception handling.
222
+ """Unrolls top-level or allOf-nested oneOf/anyOf branches into separate compiled
223
+ fastjsonschema functions so field-level errors are never swallowed by branch handling.
224
+
225
+ Handles two patterns:
226
+ 1. Direct top-level oneOf/anyOf
227
+ 2. oneOf/anyOf nested inside allOf (e.g., Projection v2.0.0)
222
228
 
223
229
  Returns a validator function that tries each branch independently and reports
224
230
  the deepest error found (most specific field path).
@@ -233,16 +239,47 @@ def compile_unrolled_schema(schema_dict: Dict[str, Any], quiet: bool = False) ->
233
239
 
234
240
  handlers_dict = {"http": handler, "https": handler}
235
241
 
242
+ target_keyword = None
243
+ branches = []
244
+ base_meta = {}
245
+
246
+ # Case 1: Direct top-level oneOf/anyOf
236
247
  if "oneOf" in schema_dict or "anyOf" in schema_dict:
237
- keyword = "oneOf" if "oneOf" in schema_dict else "anyOf"
238
- branches = schema_dict[keyword]
248
+ target_keyword = "oneOf" if "oneOf" in schema_dict else "anyOf"
249
+ branches = schema_dict[target_keyword]
239
250
  base_meta = {
240
251
  k: v for k, v in schema_dict.items() if k not in ("oneOf", "anyOf")
241
252
  }
242
253
 
254
+ # Case 2: oneOf/anyOf nested inside allOf (e.g., Projection v2.0.0)
255
+ elif "allOf" in schema_dict and isinstance(schema_dict["allOf"], list):
256
+ other_allOf = []
257
+ for elem in schema_dict["allOf"]:
258
+ if isinstance(elem, dict) and ("oneOf" in elem or "anyOf" in elem):
259
+ target_keyword = "oneOf" if "oneOf" in elem else "anyOf"
260
+ branches = elem[target_keyword]
261
+ remainder = {
262
+ k: v for k, v in elem.items() if k not in ("oneOf", "anyOf")
263
+ }
264
+ if remainder:
265
+ other_allOf.append(remainder)
266
+ else:
267
+ other_allOf.append(elem)
268
+
269
+ if branches:
270
+ base_meta = {k: v for k, v in schema_dict.items() if k != "allOf"}
271
+ if other_allOf:
272
+ base_meta["allOf"] = other_allOf
273
+
274
+ # Compile each branch independently
275
+ if branches:
243
276
  compiled_branches = []
244
277
  for branch in branches:
245
- merged = {**base_meta, **branch}
278
+ if "allOf" in base_meta:
279
+ merged = {**base_meta, "allOf": base_meta["allOf"] + [branch]}
280
+ else:
281
+ merged = {**base_meta, **branch}
282
+
246
283
  try:
247
284
  # Tier 1: Standard optimization (keeps oneOf/allOf)
248
285
  opt = optimize_schema_for_compiler(merged, remove_allof=False)
@@ -268,8 +305,11 @@ def compile_unrolled_schema(schema_dict: Dict[str, Any], quiet: bool = False) ->
268
305
  val(data)
269
306
  return
270
307
  except fastjsonschema.JsonSchemaValueException as err:
271
- # Split on both brackets and dots to calculate true path depth
272
- depth = len(re.split(r"[\[\.]", err.name))
308
+ clean_p = parse_json_pointer(err.name)
309
+ # Root '$' errors score 0; deeper paths score higher
310
+ depth = (
311
+ 0 if clean_p == "$" else len(re.split(r"[\[\.]", err.name))
312
+ )
273
313
  if depth > max_depth:
274
314
  max_depth = depth
275
315
  best_err = err
@@ -286,28 +326,29 @@ def compile_unrolled_schema(schema_dict: Dict[str, Any], quiet: bool = False) ->
286
326
  def optimize_schema_for_compiler(
287
327
  schema: Any,
288
328
  remove_allof: bool = False,
289
- depth: int = 0,
329
+ in_props_branch: bool = False,
290
330
  in_shared_props: bool = False,
291
331
  ) -> Any:
292
- """Recursively patches STAC schemas in-memory to bypass fastjsonschema code generation bugs.
332
+ r"""Recursively patches STAC schemas in-memory for fastjsonschema code generation.
293
333
 
294
334
  Strips problematic constructs (like duration formats or dangling conditionals) and prunes
295
335
  empty subschemas ({}) that cause CPython IndentationErrors during compilation.
296
336
 
297
- Scopes additionalProperties stripping exclusively to the top-level shared Item/Collection
298
- properties block so nested object strictness is preserved.
337
+ Strips restrictive additionalProperties/unevaluatedProperties flags when traversing
338
+ shared STAC Item properties so active extensions don't reject sibling fields,
339
+ while preserving additionalProperties: false inside nested sub-objects (assets, links).
299
340
 
300
341
  Args:
301
342
  schema: The JSON schema dictionary to optimize
302
343
  remove_allof: If True, also remove allOf/oneOf/anyOf (used for aggressive patching)
303
- depth: Current recursion depth (0 = root)
304
- in_shared_props: True if we are inside the top-level shared properties block
344
+ in_props_branch: True if we are inside a properties block (first level)
345
+ in_shared_props: True if we are inside shared Item/Collection properties
305
346
  """
306
347
  if isinstance(schema, list):
307
348
  cleaned_list = []
308
349
  for item in schema:
309
350
  opt_item = optimize_schema_for_compiler(
310
- item, remove_allof, depth + 1, in_shared_props
351
+ item, remove_allof, in_props_branch, in_shared_props
311
352
  )
312
353
  # Omit empty dictionaries inside composition lists (allOf, oneOf, anyOf)
313
354
  if isinstance(opt_item, dict) and not opt_item:
@@ -322,15 +363,21 @@ def optimize_schema_for_compiler(
322
363
  if k == "format" and v == "duration":
323
364
  continue
324
365
 
325
- # BUG FIX 2: Scoped additionalProperties/unevaluatedProperties removal
326
- # Strip these flags ONLY when inside the shared STAC properties map.
327
- # This enables multi-extension composition while preserving strict validation
328
- # on nested objects (assets, bands, classification:classes, etc.).
329
- if k in ("additionalProperties", "unevaluatedProperties") and v is False:
366
+ # BUG FIX 2: Strip unevaluatedProperties: false EVERYWHERE (Draft 2020-12 issue)
367
+ # Modern extension schemas use unevaluatedProperties: false which causes false positives
368
+ # when multiple extensions are composed. Each oneOf branch sees sibling extension fields
369
+ # (eo:cloud_cover, datetime, etc.) and rejects them as unevaluated, collapsing to
370
+ # "must be valid exactly by one definition (0 matches found)". Strip unconditionally.
371
+ if k == "unevaluatedProperties" and v is False:
372
+ continue
373
+
374
+ # BUG FIX 3: Strip additionalProperties: false ONLY in shared Item properties
375
+ # Preserve it in nested objects like assets, links, and sub-definitions
376
+ if k == "additionalProperties" and v is False:
330
377
  if in_shared_props:
331
378
  continue
332
379
 
333
- # BUG FIX 3: Conditionals & dependencies that produce empty Python code blocks
380
+ # BUG FIX 4: Conditionals & dependencies that produce empty Python code blocks
334
381
  if k in (
335
382
  "if",
336
383
  "then",
@@ -342,17 +389,34 @@ def optimize_schema_for_compiler(
342
389
  ):
343
390
  continue
344
391
 
345
- # BUG FIX 4: Remove allOf/oneOf/anyOf at top level when requested
392
+ # BUG FIX 5: Remove allOf/oneOf/anyOf at top level when requested
346
393
  if remove_allof and k in ("allOf", "oneOf", "anyOf") and len(schema) > 1:
347
394
  continue
348
395
 
349
- # Set in_shared_props=True ONLY when entering the top-level STAC "properties" object
350
- # (depth == 1 means we're at the root's direct children, so "properties" at depth 1 is the shared STAC properties)
351
- is_props_block = k == "properties" and depth == 1
396
+ # Context tracking across schema hierarchy
397
+ next_in_props_branch = in_props_branch
398
+ next_in_shared_props = in_shared_props
399
+
400
+ if k == "properties":
401
+ # Entering a properties block
402
+ if in_props_branch or in_shared_props:
403
+ # Already in properties context, mark as shared
404
+ next_in_shared_props = True
405
+ else:
406
+ # First properties block encountered
407
+ next_in_props_branch = True
408
+ elif k in ("assets", "links"):
409
+ # Nested objects - exit shared properties context
410
+ next_in_shared_props = False
411
+ elif k in ("$defs", "definitions"):
412
+ # Definitions are part of shared properties context
413
+ next_in_shared_props = True
414
+
352
415
  opt_v = optimize_schema_for_compiler(
353
- v, remove_allof, depth + 1, in_shared_props or is_props_block
416
+ v, remove_allof, next_in_props_branch, next_in_shared_props
354
417
  )
355
418
 
419
+ # BUG FIX 6: Prune empty subschemas ({}) in properties & patternProperties
356
420
  # BUG FIX 5: Prune empty subschemas ({}) in properties & patternProperties
357
421
  # to prevent fastjsonschema from generating empty for/else blocks
358
422
  if k in ("patternProperties", "properties", "dependentSchemas"):
@@ -402,11 +466,39 @@ def get_validator(
402
466
  ext_key = tuple(sorted(extensions))
403
467
  cache_key = (stac_type, stac_version, ext_key)
404
468
 
405
- # Thread-safe Cache Read
469
+ # Thread-safe Cache Read; join the in-flight build for this key if there is one
406
470
  with CACHE_LOCK:
407
471
  if cache_key in VALIDATOR_CACHE:
408
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()
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
409
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."""
410
502
  # Determine base schema URI
411
503
  stac_type_lower = stac_type.lower()
412
504
  if stac_type_lower in ["item", "feature"]:
@@ -515,7 +607,19 @@ def get_validator(
515
607
 
516
608
  # 2. Pre-compile unrolled branch validator as a lazy diagnostic backup
517
609
  branch_val = None
518
- if "oneOf" in raw_ext_schema or "anyOf" in raw_ext_schema:
610
+ has_branches = "oneOf" in raw_ext_schema or "anyOf" in raw_ext_schema
611
+ # Also check for oneOf/anyOf nested inside allOf (e.g., Projection v2.0.0)
612
+ if (
613
+ not has_branches
614
+ and "allOf" in raw_ext_schema
615
+ and isinstance(raw_ext_schema["allOf"], list)
616
+ ):
617
+ for elem in raw_ext_schema["allOf"]:
618
+ if isinstance(elem, dict) and ("oneOf" in elem or "anyOf" in elem):
619
+ has_branches = True
620
+ break
621
+
622
+ if has_branches:
519
623
  try:
520
624
  branch_val = compile_unrolled_schema(raw_ext_schema, quiet=quiet)
521
625
  except Exception:
@@ -569,11 +673,15 @@ def get_validator(
569
673
  clean_path = parse_json_pointer(e.name)
570
674
  msg = e.message.replace(e.name, "").strip()
571
675
 
572
- # Unmask swallowed oneOf paths ($) using our diagnostic branch helper
573
- if clean_path == "$" and branch_val is not None:
676
+ # If we have a branch validator, try it to unmask composition errors
677
+ # (e.g., oneOf/anyOf where fastjsonschema swallows the real error)
678
+ if branch_val is not None:
574
679
  try:
575
680
  branch_val(data)
681
+ # Branch validator passed - item is valid, don't report error
682
+ continue
576
683
  except fastjsonschema.JsonSchemaValueException as branch_e:
684
+ # Branch validator also failed - use its more specific error
577
685
  clean_path = parse_json_pointer(branch_e.name)
578
686
  msg = branch_e.message.replace(branch_e.name, "").strip()
579
687
 
@@ -585,10 +693,7 @@ def get_validator(
585
693
  if collected_errors:
586
694
  raise FastSTACMultiValidationError(collected_errors)
587
695
 
588
- # Cache the resulting validator so future items use it instantly (Thread-safe Write)
589
- with CACHE_LOCK:
590
- VALIDATOR_CACHE[cache_key] = validator
591
- return validator, False
696
+ return validator
592
697
 
593
698
 
594
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