diff --git a/reports/technical_risk_register.md b/reports/technical_risk_register.md index bf885a8..bfc2ec5 100644 --- a/reports/technical_risk_register.md +++ b/reports/technical_risk_register.md @@ -4,10 +4,10 @@ |-------------------|--------------------------------------| | Project | views-postprocessing | | Owner | Dylan Pinheiro / PRIO MD&D Team | -| Last Updated | 2026-11-12 | -| Total Concerns | 124 | +| Last Updated | 2026-11-18 | +| Total Concerns | 125 | | Open Concerns | 40 | -| Resolved Concerns | 84 | +| Resolved Concerns | 85 | --- @@ -177,8 +177,8 @@ that indexes only deleted code is noise. ### Cluster O: A guard that cannot fail **Root cause:** the guards here are declarative — they check code against a stated contract — and the failure that keeps recurring is the *inverse* of a wrong check: a declaration nothing enforces, or a check that cannot fire. Each instance was filed as an unrelated finding. Together they are one review habit, not seven defects. -**Entries:** C-113 (an undeclared region's skip is indistinguishable from the supported one), C-114 (stubs that can neither fail for a stated reason nor ever flip), C-116 (a bound that permits a year-long escape), C-121 (an assertion that has never executed), C-122 (a launch-axis guard covering one partner of two), C-123 (a declared interface enforced in half), C-108 (two `xfail(strict=True)` deploy gates that have never evaluated their assertions) — precedent in **C-102** and **C-89, both RESOLVED**. -**Highest tier:** 2 (C-113, C-116) +**Entries:** C-114 (stubs that can neither fail for a stated reason nor ever flip), C-116 (a bound that permits a year-long escape), C-121 (an assertion that has never executed), C-122 (a launch-axis guard covering one partner of two), C-123 (a declared interface enforced in half), C-108 (two `xfail(strict=True)` deploy gates that have never evaluated their assertions) — plus **C-113, RESOLVED 2026-11-12**, the cluster's first discharge — precedent in **C-102** and **C-89, both RESOLVED**. +**Highest tier:** 2 (C-116) **Fix strategy:** not one deletion and not one new guard. Each member is its own small code change — and the cluster exists to stop seven entries reading as seven backlog items when the thing they have in common is a habit at review time: *a guard is not evidence until a mutation proves it can fail.* ADR-014 §2 already states the trap in the obvious alternative — a second declaration to check the first can itself go stale. **C-102** is the resolved precedent and the method: derive the probe from the declaration rather than hardcoding it, so the proof survives the next rotation instead of expiring with it. **Resolution scope:** Full per member, and the members are independent — this cluster will not collapse on one change the way **Cluster L** did. What closes together is the habit; what closes one at a time is the code. **Why this cluster was late, and it is the same reason Cluster N was.** Seven of its members arrived in two sprints (C-108 on 2026-08-17, the other six on 2026-11-12), every one of them from a `/code-review max` or `/falsify` pass rather than from a failing test — which is the cluster's own thesis restated: nothing in the suite can report a guard that cannot fail, because a guard that cannot fail is green. @@ -1226,7 +1226,7 @@ Cross-refs: **C-100** (the live sibling — a four-method port with three used m | Source | `/repo-assimilation` (2026-08-16), measured | | Trigger | When the next module moves under `views_postprocessing/`, check its inbound docstring references as well as its markdown ones — or when someone proposes widening `tests/test_doc_accuracy.py`'s corpus, at which point C-97's objection applies and this entry states what the gap actually is. | | Owner | This repository. | -| Location | `tests/test_doc_accuracy.py:76-78,133-134` (the scanned corpus); `views_postprocessing/delivery/coverage.py:5`; `views_postprocessing/delivery/observed_range.py:6` | +| Location | `tests/test_doc_accuracy.py:76-78,133-134` (the scanned corpus); ~~`views_postprocessing/delivery/coverage.py:5`~~ **corrected 2026-11-12** with C-113's fix; `views_postprocessing/delivery/observed_range.py:6` (still stale) | `test_doc_accuracy` scans `README.md`, `docs/architecture/*.md`, package `README.md` files, ADRs and CICs. Python docstrings are outside that corpus. Two are already stale, and both point at files that moved in exactly the refactors whose *markdown* fallout the same test was extended to catch: `delivery/coverage.py` sends the reader to `views_postprocessing/unfao/extraction.py`, deleted in #151, and `delivery/observed_range.py` to `views_postprocessing/unfao/source_metadata.py`, moved to `contract/` in #153. @@ -1347,29 +1347,6 @@ Cross-refs: **D-06** (RESOLVED — the general principle, and the finding that n --- -### C-113: An undeclared `region` skips both coverage gates, and the skip is indistinguishable from the one the code deliberately supports - -| Field | Value | -|-------|-------| -| ID | C-113 | -| Tier | 2 — structural fragility with a clear trigger and a partner-facing consequence: a launch config that omits `region` ships a delivery whose cell curation and completeness gate both silently did nothing. Not Tier 1 because the count-gate logs a warning before skipping, so the evidence does reach the run log. | -| Source | `/code-review max`, 2026-11-12 (findings 10-12), measured | -| Trigger | When a new launch config, partner or region is added — or when anyone proposes a test asserting that unpinned regions are refused. Check that "no region declared" and "a named region that is not pinned" are distinguishable before writing that assertion. | -| Owner | This repository. | -| Location | `views_postprocessing/delivery/coverage.py:62` (`return EXPECTED_CELLS.get(region) if region else None`), `:99` (`return EXCLUDED_GIDS_BY_REGION.get(region, frozenset()) if region else frozenset()`); call sites `views_postprocessing/crafd/managers/crafd.py:228-229`, `:300-301`, `:419` — and the *same* lines in `views_postprocessing/unfao/managers/unfao.py`, verified identical. *(This row cited `:223,299,415` until 2026-11-12. Those numbers were wrong on the day the entry was written — the managers' last change predates it — which makes C-109's point sharper than C-109 makes it: the decay is not only over time.)* | - -Both accessors collapse two different conditions into one return value. `expected_for(None)` and `expected_for("not_a_pinned_region")` both return `None`; `excluded_for(None)` and `excluded_for()` both return `frozenset()`. - -One of those is a supported configuration. `coverage.py:52-54` records that `africa_me_legacy` is **intentionally** not pinned — the register cites 5 pure-ocean cells for which "complete" is ambiguous — and both managers implement the matching documented skip. The other is ADR-003 inference by omission, which must refuse. - -Measured consequence: a config that omits `region` reaches `assert_no_excluded_cells` with an empty exclusion set, so the GAUL-uncovered cell check is a no-op, and `assert_complete_coverage` with `None`, so the count-gate is skipped. `region` is the only one of the product-defining launch axes read through a bare `.get()`; `wire_contract` and the historical `data_format` each have a declared assertion (`launch_config.assert_contract_mode`, `assert_frame_native_historical`). - -**The fix is one branch, not a fourth launch axis.** Splitting `if region else` at both lines — raise on undeclared, keep the documented skip for named-but-unpinned — repairs all six call sites at once. A guard written the other way round, refusing any region absent from `EXPECTED_CELLS`, would make `africa_me_legacy` unlaunchable. - -Cross-refs: **C-30** (absorbs C-34 — the coverage contract these gates enforce), ADR-003 (inference by omission), **views-models ADR-021** (`docs/ADRs/021_coverage_is_declared_once.md` — the upstream half). - ---- - ### C-114: The release-readiness falsification stubs can neither fail for a stated reason nor ever flip — and a behaviour-preserving rename turns one into a hard red on a required check | Field | Value | @@ -1435,7 +1412,7 @@ Cross-refs: **C-110** (RESOLVED — *"the obvious shortcut is closed, and closed --- -### C-117: The seam-pin drift detector projects three fields, so a rotation the registry has not recorded is invisible — and the pinned registry still declares two retired keys dying 2026-11-17 +### C-117: The seam-pin drift detector projects three fields, so a rotation the registry has not recorded is invisible — and the pinned registry still declares two retired keys dying 2026-11-17 *(that date passed on 2026-11-17; checked 2026-11-18)* | Field | Value | |-------|-------| @@ -1558,9 +1535,33 @@ The module opens *"Representation-free — primitives only (a 2-D numpy array + **Why it is registered rather than fixed on sight.** The docstring was narrowed in `b80bd3d` to state the gap instead of overclaiming past it — *"The declared ints are a separate matter and are still unenforced"* — so the prose is honest and the shortfall is declared, which is the condition under which this register tracks rather than blocks. What makes it standing risk is the direction of travel: the floor becomes a per-audience value the moment that decision lands, and a declaration that arrives missing or as a string would then surface on the partner-facing path as an exception type no caller is written to catch. -The failing stubs are kept **outside `tests/`**, at `/tmp/claude-1000/-home-simon-Documents-scripts-views-platform-views-postprocessing/f3881619-6312-451d-b6b0-4d69424f45be/scratchpad/test_falsify_draws_raises_contract.py`, deliberately: C-114 and the untracked region stub are this repository's live record of what an unmarked or self-absorbing falsification stub does to a required check, and a third one would add to that hazard rather than to the evidence. +The failing stubs were kept **outside `tests/`**, in this session's scratchpad directory — *checked 2026-11-18: that directory has since been cleared, so the stubs are gone and the path no longer resolves. A session scratchpad is not a durable home; the entry body above is now the only record of what the stubs asserted, which is why it states both falsifications in full.* They were kept out of `tests/` deliberately: C-114 and the untracked region stub are this repository's live record of what an unmarked or self-absorbing falsification stub does to a required check, and a third one would add to that hazard rather than to the evidence. + +Cross-refs: **C-107** (the same docstring, the opposite shape — there the prose had drifted from the code; here the prose is accurate and the code is what falls short), **C-120** (ADR-013 §6's four-rule count, which the two new refusals already sit outside), **C-114** (why these stubs are not in `tests/`), **C-124** (the same function's other failure of discrimination — there a declared type is unchecked, here an unrelated failure is given a confident wrong diagnosis). + +--- + +### C-124: The §6 draws gate catches `Exception` and reports every failure as malformed input — including the `MemoryError` this exact path has a measured history of + +| Field | Value | +|-------|-------| +| ID | C-124 | +| Tier | 3 — it misdiagnoses, it does not mis-deliver. The gate still refuses and nothing ships, so there is no partner-facing correctness consequence; what is lost is the operator's time and the traceback that would have named the real fault. | +| Source | `/code-review`, 2026-11-18 | +| Trigger | When the first global forecast delivery is cut, or when either product's `S_MIN` rises — both enlarge the array this line materializes. Also when anyone diagnoses a failed delivery from this gate's message rather than from the run log. | +| Owner | This repository. | +| Tracked | views-postprocessing#336 | +| Location | `views_postprocessing/delivery/draws.py:83-94` (the `try`/`except Exception` around `np.asarray`) | + +The gate wraps `np.asarray(values)` in `except Exception` and raises `DrawsCollapseError` saying *"the payload could not be read as an array at all … this is malformed input, not a collapsed forecast. Nothing about the draws has been checked."* That sentence is a diagnosis, and it is only correct for the failure it was written for: ragged input, which `np.asarray` reports as a `ValueError`. + +`MemoryError` is a subclass of `Exception`. An out-of-memory failure while materializing a large draws payload is therefore reported as a producer having published a malformed artifact, and the reader is sent upstream. This repository has measured that exact failure twice on this path — **C-32** (run 0 OOM-killed at 23.8 GB during the historical enrichment join) and **C-101** (the streaming fix, where downloading every shard of a target before decoding the first made peak 3.06× the delivered frame). The streaming fix is what keeps this cheap today; a larger sample width is what makes it dear again. -Cross-refs: **C-107** (the same docstring, the opposite shape — there the prose had drifted from the code; here the prose is accurate and the code is what falls short), **C-120** (ADR-013 §6's four-rule count, which the two new refusals already sit outside), **C-114** (why these stubs are not in `tests/`). +Narrowing to `except (ValueError, TypeError)` restores the diagnosis to the failures it describes and lets `MemoryError` propagate with its own traceback. This is one line and one test. + +**Registered rather than fixed on sight**, because the branch that found it exists to fix C-113 in `delivery/coverage.py` and the two managers. Mixing an unrelated narrowing into `delivery/draws.py` — a module with two other open entries about its own docstring, last touched by a separate pull request for exactly that reason — would make each change harder to review than it is on its own. + +Cross-refs: **C-123** (same function, the declared-type half), **C-105** / the `source_metadata` entry recording `except Exception: lv = None` (the same disease: two faults leaving through one branch with one outcome), **C-32** and **C-101** (the measured OOMs this message would mislabel), **ADR-008** (log persistently and raise). --- @@ -1633,6 +1634,64 @@ See also C-40 (the inheritance/representation coupling this migration unwinds), ## Resolved Concerns +### C-113: An undeclared `region` skips both coverage gates, and the skip is indistinguishable from the one the code deliberately supports — RESOLVED + +| Field | Value | +|-------|-------| +| ID | C-113 | +| Tier | 2 — structural fragility with a clear trigger and a partner-facing consequence: a launch config that omits `region` ships a delivery whose cell curation and completeness gate both silently did nothing. Not Tier 1 because the count-gate logs a warning before skipping, so the evidence does reach the run log. | +| Source | `/code-review max`, 2026-11-12 (findings 10-12), measured | +| Trigger | When a new launch config, partner or region is added — or when anyone proposes a test asserting that unpinned regions are refused. Check that "no region declared" and "a named region that is not pinned" are distinguishable before writing that assertion. | +| Owner | This repository. | +| Location | `views_postprocessing/delivery/coverage.py:62` (`return EXPECTED_CELLS.get(region) if region else None`), `:99` (`return EXCLUDED_GIDS_BY_REGION.get(region, frozenset()) if region else frozenset()`); call sites `views_postprocessing/crafd/managers/crafd.py:228-229`, `:300-301`, `:419` — and the *same* lines in `views_postprocessing/unfao/managers/unfao.py`, verified identical. *(This row cited `:223,299,415` until 2026-11-12. Those numbers were wrong on the day the entry was written — the managers' last change predates it — which makes C-109's point sharper than C-109 makes it: the decay is not only over time.)* | + +Both accessors collapse two different conditions into one return value. `expected_for(None)` and `expected_for("not_a_pinned_region")` both return `None`; `excluded_for(None)` and `excluded_for()` both return `frozenset()`. + +One of those is a supported configuration. `coverage.py:52-54` records that `africa_me_legacy` is **intentionally** not pinned — the register cites 5 pure-ocean cells for which "complete" is ambiguous — and both managers implement the matching documented skip. The other is ADR-003 inference by omission, which must refuse. + +Measured consequence: a config that omits `region` reaches `assert_no_excluded_cells` with an empty exclusion set, so the GAUL-uncovered cell check is a no-op, and `assert_complete_coverage` with `None`, so the count-gate is skipped. `region` is the only one of the product-defining launch axes read through a bare `.get()`; `wire_contract` and the historical `data_format` each have a declared assertion (`launch_config.assert_contract_mode`, `assert_frame_native_historical`). + +**The fix is one branch, not a fourth launch axis.** Splitting `if region else` at both lines — raise on undeclared, keep the documented skip for named-but-unpinned — repairs all six call sites at once. A guard written the other way round, refusing any region absent from `EXPECTED_CELLS`, would make `africa_me_legacy` unlaunchable. + +**RESOLVED 2026-11-12 — and the entry's own prescription held, including the part that said what NOT to build.** + +The refusal landed where the repository already keeps launch declarations rather than as a fourth guard invented next to the gates: **`contract/launch_config.assert_region_declared`**, a sibling of `assert_contract_mode` and `assert_frame_native_historical`, called from `_read_forecast_data` in both managers before any store call. `delivery/coverage.py` holds the same rule at the invariant for every other caller — `expected_for` and `excluded_for` now raise **`RegionNotDeclaredError`** on an undeclared region and still return `None`/empty for one that is declared but unpinned. + +`RegionNotDeclaredError` is deliberately **not** a `CoverageError` subclass. Nothing was delivered wrongly; the question could not be asked. A caller catching `CoverageError` to report a coverage failure must not catch this and mislabel it. + +**The entry's warning was the load-bearing part.** It said: *"A guard written the other way round, refusing any region absent from `EXPECTED_CELLS`, would make `africa_me_legacy` unlaunchable."* A falsification stub written the same day prescribed exactly that — `test_a_region_that_is_not_pinned_is_refused_rather_than_skipped`, asserting a refusal naming `land_gaul` for any unpinned region. It was never committed, and `tests/test_launch_config.py::test_a_declared_region_passes_whether_or_not_it_is_pinned` now pins the opposite. The stub's other two failures were a name it had guessed (`assert_coverage_region`); its finding was right and its remedy was wrong on one of two points. + +**A second, silent half of the same defect, fixed with it.** The count gate logged its skip; the exclusion gate did not. So a delivery curated by nothing left only half the evidence in the run log — which is why this entry's Tier rationale (*"the count-gate logs a warning before skipping, so the evidence does reach the run log"*) was true of one gate and not the pair. Both gates now report their own skip, **inside the invariant** rather than at the call site: `assert_complete_coverage` accepts `expected_count=None` and `assert_no_excluded_cells` an empty manifest, each logging a WARNING naming the leg. That removed the orchestration from both managers — the `if expected is not None: ... else: log` block in each — which is what let this land at all: the first attempt put the reporting in the shell and tripped `test_doc_accuracy`'s 300-line manager ratchet at 319. The ratchet was right, and C-40(a) is the reason: *logic that can be called with declared arguments belongs where it can be tested without a manager, an Appwrite environment or a views-models path manager.* Both skips are now proven by `caplog` in `tests/test_delivery_coverage.py`, with no framework at all. + +**Sixteen new tests, suite 529 → 545 passed.** The type half is covered too — a `region` that is not a non-empty string is refused rather than reaching the gates as though it had been declared, which is the local instance of the gap **C-123** registers generally. + +**AMENDED 2026-11-18 — the resolution above was true of the smaller leg and wrong about the larger one.** `/code-review` on the resolving branch found that the sentence *"Both gates now report their own skip"* did not hold where most of the coverage checking happens. Forecast coverage is not asserted in the managers at all: it is asserted inside `contract/wire/source_selection.py`'s `TargetLease.load()`, and that method guarded both calls with `if self.excluded_gids:` and `if self.expected_cells is not None:`. For a region that pins neither — the supported unpinned case — both conditions were false, so **every forecast target loaded with both gates skipped and nothing at all in the run log**. The managers' `_check_coverage`, which the first fix corrected, covers the historical leg. Both `if`s are now gone and the lease calls each gate unconditionally, which is the only form that lets the invariant own its own skip report. + +**And the same defect one level in: an unrecognised region name was still silently the unpinned case.** `assert_region_declared` accepted any non-empty string, so `region: "lnd_gaul"` passed the launch assertion, missed both dictionary lookups, and skipped both gates — reporting itself as the configuration someone deliberately chose. Measured: `expected_for("lnd_gaul")` returned `None` and `excluded_for("lnd_gaul")` returned `frozenset()`, and a two-cell delivery was accepted. The register entry above anticipated the wrong guard (*"refusing any region absent from `EXPECTED_CELLS`"*, which would ground `africa_me_legacy`) and this is the right one: a declared set of **known** regions, `delivery.coverage.KNOWN_REGIONS`, separate from the question of whether a known region's cell count has been pinned. `africa_me_legacy` is known and still deliberately unpinned, so it still launches and still logs a skipped count-gate. An unknown name now raises `UnknownRegionError` at the invariant and `LaunchConfigError` at launch, each naming the known set and both repair paths. + +Two tests in the resolving commit **pinned the old behaviour** — `expected_for("does_not_exist") is None` and `assert_region_declared({"region": "not_pinned_anywhere"}) is None` — the second written on purpose, to record that an unpinned region must stay launchable. It was right about `africa_me_legacy` and wrong to generalise from it to any string. Both are rewritten. + +**The guard audit then found that the fix's own guards were asymmetric.** `/falsify guard`, run independently, applied 38 mutations to production code and ran each one: 31 were caught, **7 survived**, 0 unrun. Every mutation against `delivery/coverage.py` itself was caught — the invariant layer is strongly guarded. All seven survivors sat at the **call sites** the change had created an obligation for, or in the declaration the invariant is told to trust: + +- **Restoring `if excluded:` / `if expected is not None:` in BOTH managers left the whole suite green.** That mutation reopens this entry's own silence on the historical leg, and nothing noticed. The forecast leg's equivalents were both caught, because the forecast leg got a new test and the managers got rewritten production code and none. Closed by an `ast` scan over both managers' `_check_coverage`: each gate is called exactly once, and neither call is enclosed by an `If`. +- **Adding `"atlantis"` to `KNOWN_REGIONS` left the suite green** — the new declaration was checked in one direction only (pinned ⊆ known) and not against what views-datafactory actually serves, which is C-113's shape re-entering through the declaration rather than through an omission. Closed by a cross-check against the sibling checkout's `src/datafactory_query/regions.py`, read with `ast` (the package is not a dependency here), skipped when no checkout is present, the same pattern as the excluded-gid cross-check above it. +- **Deleting both `logger.error` calls from `assert_region_declared` left the suite green**, breaking ADR-008 unnoticed — although this repository already owns the mechanism that catches it, `tests/test_env_declaration.py::_REFUSALS`, whose own comment says *"adding a third validator is one line here, not a new test."* The validator had not been added. It now is, for both refusals. +- **Deleting the manager call site of `assert_region_declared` left the suite green**: the source scan that checks for the other two assertions read `unfao.py` only and listed two of three. It is now parametrised over both partners and covers all three. +- **Swapping the two gate calls left the suite green** on all three legs, although both managers and the lease carry a comment saying the order is load-bearing (exclusion first, so a leaked island names itself). Now executable: a call-order assertion on the forecast leg and a line-order assertion in both managers. +- **One of the new tests asserted something untrue of itself.** Its comment said *"the exclusion gate still fires when a dropped cell comes back"*; it does not, because `drop_units` removes the excluded cell on the line directly above the gates, so the `CoverageError` it caught came from the count gate. Making the exclusion gate blind kept it green. The comment is corrected, the assertion now names the count gate, and a separate test states what the exclusion gate is actually for on that leg — a post-condition on the curation it follows. + +All seven are closed. The pattern is worth keeping: the design decision to move skip-reporting out of the two shells and into the invariant was sound and is well guarded; what went unguarded was the shells' remaining obligation to *call* it, which the change itself created. + +Measured 2026-11-18 in the `poetry.lock` environment: **565 passed, 3 skipped, 41 xfailed** (twenty tests more than the resolving commit's 545), `ruff check` clean. + +Cross-refs added on resolution: **C-122** (the launch-axis guard this one's fix lands beside — still one partner of two), **C-123** (declared types unenforced, the general form), **C-40** (the manager line ratchet that shaped the fix), **C-107** (whose `delivery/coverage.py:5` stale pointer was corrected in the same change). Added on amendment: **C-109** (an entry's own `Location` decays — here the *resolution prose* was the thing that was wrong, which no `Location` check would have caught). + +Cross-refs: **C-30** (absorbs C-34 — the coverage contract these gates enforce), ADR-003 (inference by omission), **views-models ADR-021** (`docs/ADRs/021_coverage_is_declared_once.md` — the upstream half). + +--- + +--- + ### C-119: Resolving C-84 and C-110 left three live records asserting a red build that is green — RESOLVED | Field | Value | diff --git a/tests/test_delivery_coverage.py b/tests/test_delivery_coverage.py index 0dca72a..3852348 100644 --- a/tests/test_delivery_coverage.py +++ b/tests/test_delivery_coverage.py @@ -11,7 +11,10 @@ from views_postprocessing.delivery.coverage import ( EXPECTED_CELLS, + KNOWN_REGIONS, CoverageError, + RegionNotDeclaredError, + UnknownRegionError, assert_complete_coverage, assert_no_excluded_cells, excluded_for, @@ -44,11 +47,60 @@ def test_land_gaul_is_pinned(): assert EXPECTED_CELLS["land_gaul"] == 64_742 -def test_unpinned_or_missing_region_is_none(): - # africa_me_legacy is deliberately unpinned (ambiguous count); None must not raise. +def test_a_declared_but_unpinned_region_has_no_target_and_does_not_raise(): + # africa_me_legacy is deliberately unpinned (ambiguous count). It must stay + # launchable: the count gate reports a skip, it does not refuse. assert expected_for("africa_me_legacy") is None - assert expected_for(None) is None - assert expected_for("does_not_exist") is None + + +def test_an_unrecognised_region_is_refused_not_treated_as_unpinned(): + """C-113 one level in: `expected_for("does_not_exist")` used to return None. + + This test asserted that return value until 2026-11-18 — it pinned the defect. + A name this delivery does not recognise is not the supported unpinned case: it + misses both dictionary lookups, so BOTH gates skip and the delivery reports + itself as a configuration someone chose. One mistyped letter did that. + """ + for unknown in ("does_not_exist", "lnd_gaul", "land_gaul ", "LAND_GAUL"): + with pytest.raises(UnknownRegionError, match="not one this delivery recognises"): + expected_for(unknown) + + +def test_the_two_region_refusals_are_different_faults(): + # Different fixes: add the config key, versus correct a name or declare a region. + # Neither is a CoverageError — nothing was delivered wrongly in either case. + assert not issubclass(UnknownRegionError, RegionNotDeclaredError) + assert not issubclass(RegionNotDeclaredError, UnknownRegionError) + assert not issubclass(UnknownRegionError, CoverageError) + + +def test_every_pinned_region_is_a_known_region(): + # A region pinned in either table but absent from KNOWN_REGIONS would be + # unreachable: `_declared` refuses it before the lookup runs. + from views_postprocessing.delivery.coverage import EXCLUDED_GIDS_BY_REGION + + assert set(EXPECTED_CELLS) <= set(KNOWN_REGIONS) + assert set(EXCLUDED_GIDS_BY_REGION) <= set(KNOWN_REGIONS) + + +def test_an_undeclared_region_is_refused_and_not_reported_as_unpinned(): + """C-113. ``expected_for(None)`` returned None, exactly like an unpinned region. + + The two must not share a representation: one means "this delivery has no + completeness target, which we accept", the other means "nobody said what this + delivery is supposed to cover". The second shipped as the first. + """ + for undeclared in (None, "", " ", 0, ["land_gaul"]): + with pytest.raises(RegionNotDeclaredError, match="no region declared"): + expected_for(undeclared) + + +def test_the_refusal_is_not_a_coverage_error(): + # Nothing was delivered wrongly; the question could not be asked. A caller + # catching CoverageError to report a coverage failure must not catch this. + assert not issubclass(RegionNotDeclaredError, CoverageError) + with pytest.raises(RegionNotDeclaredError): + expected_for(None) # --- S4 / C-30: the GAUL-uncovered exclusion manifest ------------------------------- @@ -59,11 +111,24 @@ def test_land_gaul_exclusions_count_is_pinned(): assert len(excluded_for("land_gaul")) == 76 -def test_unpinned_region_has_no_exclusions(): +def test_a_declared_but_unpinned_region_has_no_exclusions(): # africa_me_legacy keeps its 5 ocean cells today — they must NOT be force-excluded. assert excluded_for("africa_me_legacy") == frozenset() - assert excluded_for(None) == frozenset() - assert excluded_for("does_not_exist") == frozenset() + + +def test_an_unrecognised_region_is_refused_by_the_exclusion_side_too(): + # The same hole on the curation side: a misspelling returned frozenset(), so + # nothing was curated and it read as the region that is MEANT to curate nothing. + with pytest.raises(UnknownRegionError): + excluded_for("lnd_gaul") + + +def test_an_undeclared_region_is_refused_by_the_exclusion_side_too(): + # C-113: this returned frozenset(), so an undeclared region curated nothing and + # looked exactly like the region that is MEANT to curate nothing. + for undeclared in (None, "", " "): + with pytest.raises(RegionNotDeclaredError, match="no region declared"): + excluded_for(undeclared) def test_known_sub_antarctic_gids_are_excluded(): @@ -92,6 +157,45 @@ def test_no_excluded_cells_is_noop_when_region_unpinned(): assert assert_no_excluded_cells({62356, 94776}, excluded_for("africa_me_legacy")) is None +# --- C-113: a skipped gate must say so, and both gates must say it ------------------ + + +def test_a_skipped_exclusion_gate_is_reported(caplog): + """This skip was silent, while the count gate's was logged. + + Half the evidence that a delivery had been curated by nothing never reached the + run log. Asserted on the WARNING record, not on the return, because returning + None is what the old silent version did too. + """ + with caplog.at_level("WARNING"): + assert assert_no_excluded_cells({1, 2}, frozenset(), label="historical") is None + assert any( + r.levelname == "WARNING" and "exclusion-gate SKIPPED" in r.getMessage() + and "historical" in r.getMessage() + for r in caplog.records + ), caplog.text + + +def test_a_skipped_count_gate_is_reported(caplog): + # The count gate now owns the skip the managers used to each report themselves, + # so it can be proven here without a manager or an Appwrite environment (C-40(a)). + with caplog.at_level("WARNING"): + assert assert_complete_coverage({1, 2}, None, label="forecast") is None + assert any( + r.levelname == "WARNING" and "count-gate SKIPPED" in r.getMessage() + and "forecast" in r.getMessage() + for r in caplog.records + ), caplog.text + + +def test_a_pinned_region_still_enforces_both_gates(): + # The skip paths must not have made the gates themselves optional. + with pytest.raises(CoverageError, match="under-coverage"): + assert_complete_coverage({1, 2}, expected_for("land_gaul"), label="historical") + with pytest.raises(CoverageError, match="62356"): + assert_no_excluded_cells({62356}, excluded_for("land_gaul"), label="historical") + + # Cross-check the frozen manifest against the live producer. This is the drift tripwire # C-30 asks for, and since 2026-08-17 it RUNS IN CI: `run_pytest.yml` fetches # views-datafactory, and both pgid lists below are tracked there. It backs a guarantee @@ -115,3 +219,143 @@ def test_manifest_matches_datafactory_land_minus_land_gaul(): land_gaul = {int(x) for x in json.loads((_DF / "land_gaul_pgids.json").read_text())} assert excluded_for("land_gaul") == frozenset(land - land_gaul) assert EXPECTED_CELLS["land_gaul"] == len(land_gaul) + + +# --- the SHELLS' remaining obligation: call both gates, unconditionally, in order --- +# +# The skip-reporting rule lives in this module, not in the two managers (C-40(a)). +# That leaves each manager one obligation — call both gates and wrap neither in a +# condition — and nothing verified it: a guard audit restored `if excluded:` / +# `if expected is not None:` in BOTH managers and the whole suite stayed green +# (2026-11-18, ME2). That mutation reopens exactly the silence C-113 is about, on +# the historical leg. A manager cannot be imported without the full pipeline-core +# framework, so this reads the source — the repo's standing pattern for manager +# shape (see tests/test_launch_config.py, tests/test_doc_accuracy.py). + + +def _check_coverage_body(partner: str): + import ast + from pathlib import Path + + source = ( + Path(__file__).resolve().parent.parent + / "views_postprocessing" / partner / "managers" / f"{partner}.py" + ).read_text() + for node in ast.walk(ast.parse(source)): + if isinstance(node, ast.FunctionDef) and node.name == "_check_coverage": + return node + raise AssertionError(f"{partner}: no _check_coverage to inspect") + + +def _gate_calls(node): + """(attribute name, lineno) for each coverage gate call, and whether an `if` + encloses it — walking down from the function body so enclosure is observed, not + inferred from indentation.""" + import ast + + found = [] + + def walk(n, under_if): + for child in ast.iter_child_nodes(n): + if isinstance(child, ast.Call) and isinstance(child.func, ast.Attribute): + if child.func.attr in ("assert_no_excluded_cells", "assert_complete_coverage"): + found.append((child.func.attr, child.lineno, under_if)) + walk(child, under_if or isinstance(child, ast.If)) + + walk(node, False) + return found + + +@pytest.mark.parametrize("partner", ["unfao", "crafd"]) +def test_the_manager_calls_both_gates_unconditionally(partner): + calls = _gate_calls(_check_coverage_body(partner)) + names = [name for name, _, _ in calls] + assert names.count("assert_no_excluded_cells") == 1, calls + assert names.count("assert_complete_coverage") == 1, calls + conditional = [(name, line) for name, line, under_if in calls if under_if] + assert not conditional, ( + f"{partner}: {conditional} sits inside an `if`. Each gate owns its own skip " + "report for an unpinned region; a caller-side condition skips the gate AND " + "the report, which is the silent skip C-113 exists for." + ) + + +@pytest.mark.parametrize("partner", ["unfao", "crafd"]) +def test_the_manager_runs_exclusion_before_count(partner): + # So a leaked island names itself instead of arriving as "over-coverage by 1" + # (S4/C-30). Stated in a comment in both managers and in nothing executable + # until now; a guard audit swapped the pair with the suite green (MF3). + lines = {name: line for name, line, _ in _gate_calls(_check_coverage_body(partner))} + assert lines["assert_no_excluded_cells"] < lines["assert_complete_coverage"], lines + + +# --- the declaration itself: KNOWN_REGIONS must name regions that exist ------------- +# +# `test_every_pinned_region_is_a_known_region` checks conformance to the declaration +# in one direction. A guard audit added "atlantis" to KNOWN_REGIONS and the whole +# suite stayed green (2026-11-18, MA6) — a region nobody curated would then launch, +# pin no count and no manifest, and skip both gates: C-113's shape re-entered through +# the declaration instead of through an omission. Which regions exist is a +# views-datafactory fact, so this is the direction only a cross-check can hold. + + +def _datafactory_declared_regions() -> set[str] | None: + """The region names views-datafactory's `regions.py` says it serves. + + Read with `ast` rather than imported: `datafactory_query` is not a dependency of + this package and is absent from the project venv, which is why the sibling + cross-check above reads its JSON files directly instead. + """ + import ast + + if _DATAFACTORY is None: + return None + path = _DATAFACTORY / "src" / "datafactory_query" / "regions.py" + if not path.exists(): + return None + tree = ast.parse(path.read_text()) + names: set[str] = set() + for node in ast.walk(tree): + # `list_regions()` returns the special values plus REGIONS' keys. + if isinstance(node, ast.FunctionDef) and node.name == "list_regions": + doc = ast.get_docstring(node, clean=False) + names |= { + n.value for n in ast.walk(node) + if isinstance(n, ast.Constant) + and isinstance(n.value, str) + and n.value != doc + } + # `REGIONS: dict[str, list[str]] = {...}` is an AnnAssign, not an Assign. + if isinstance(node, (ast.Assign, ast.AnnAssign)): + targets = node.targets if isinstance(node, ast.Assign) else [node.target] + if any(isinstance(x, ast.Name) and x.id == "REGIONS" for x in targets): + names |= { + k.value for k in getattr(node.value, "keys", []) + if isinstance(k, ast.Constant) and isinstance(k.value, str) + } + return names or None + + +@pytest.mark.skipif( + _datafactory_declared_regions() is None, + reason=( + "views-datafactory checkout not found, or its " + "src/datafactory_query/regions.py declares no region names — set " + "VIEWS_DATAFACTORY=/path/to/views-datafactory, or place it alongside this " + "repo (this runs in CI)" + ), +) +def test_every_known_region_is_one_views_datafactory_actually_serves(): + declared = _datafactory_declared_regions() + assert declared is not None + unknown_upstream = sorted(set(KNOWN_REGIONS) - declared) + assert not unknown_upstream, ( + f"delivery.coverage.KNOWN_REGIONS names {unknown_upstream}, which " + "views-datafactory's regions.py does not serve. A region declared here but " + "absent upstream launches, pins nothing, and skips both coverage gates. " + f"Upstream serves: {sorted(declared)}." + ) + # The reverse must NOT hold: this delivery supports a subset deliberately + # (it does not deliver "global" or bare "land"), so an upstream region missing + # from KNOWN_REGIONS is a choice, not drift. + assert set(KNOWN_REGIONS) <= declared diff --git a/tests/test_env_declaration.py b/tests/test_env_declaration.py index 8964300..6f3593c 100644 --- a/tests/test_env_declaration.py +++ b/tests/test_env_declaration.py @@ -377,6 +377,21 @@ def test_both_managers_check_importability_before_asking_what_was_declared(): launch_config.FEATURE_FRAME_FORMAT, id="launch_config.assert_frame_native_historical", ), + # Added 2026-11-18: a guard audit deleted both `logger.error` calls from + # `assert_region_declared` with the whole suite green. This list is the + # mechanism that catches that, and the validator had not been added to it. + pytest.param( + lambda: launch_config.assert_region_declared({}), + launch_config.LaunchConfigError, + launch_config.REGION_KEY, + id="launch_config.assert_region_declared[undeclared]", + ), + pytest.param( + lambda: launch_config.assert_region_declared({"region": "lnd_gaul"}), + launch_config.LaunchConfigError, + "lnd_gaul", + id="launch_config.assert_region_declared[unrecognised]", + ), ) diff --git a/tests/test_launch_config.py b/tests/test_launch_config.py index 8f8f841..36c6a14 100644 --- a/tests/test_launch_config.py +++ b/tests/test_launch_config.py @@ -103,22 +103,102 @@ def test_declared_feature_frame_passes(): # ── the manager actually calls them ───────────────────────────────────────── -def test_the_manager_asserts_both_axes(): +@pytest.mark.parametrize("partner", ["unfao", "crafd"]) +def test_the_manager_asserts_every_launch_axis(partner): """Source-scan: the manager pulls the full pipeline-core framework and cannot be imported in every test environment (the repo's standing pattern — see - `test_env_declaration.py`). What matters is that neither axis is left to - `.get()` with a silent default.""" + `test_env_declaration.py`). What matters is that no axis is left to `.get()` + with a silent default. + + Parametrised over both partners, and covering `assert_region_declared`, because + a guard audit removed that call from both managers with the whole suite green: + the scan read one file and listed two of the three assertions (2026-11-18, ME1). + """ from pathlib import Path source = ( Path(__file__).resolve().parent.parent - / "views_postprocessing" / "unfao" / "managers" / "unfao.py" + / "views_postprocessing" / partner / "managers" / f"{partner}.py" ).read_text() assert "launch_config.assert_contract_mode(" in source assert "launch_config.assert_frame_native_historical(" in source + assert "launch_config.assert_region_declared(" in source, ( + f"{partner}: the region axis is read by both coverage gates, so a manager " + "that does not assert it ships a delivery whose gates chose themselves " + "(C-113)." + ) # And the inference it replaced must not survive anywhere. assert 'configs.get("wire_contract")' not in source, ( "the manager still branches on wire_contract — S1 replaced that fork with a " "single refusal (C-63)." ) + + +# --- C-113: the region is a declaration, not something to omit --------------------- + + +def test_a_missing_region_is_refused_naming_the_key(): + """The omission that disabled both coverage gates while reading as supported. + + `configs.get("region")` returned None, and None took the same path through + `delivery.coverage` as a region that is declared but not yet pinned — so a + delivery shipped with its cell curation and its completeness check both having + done nothing. Same shape as C-83: the absence of an answer given the shape of + an answer (ADR-003). + """ + with pytest.raises(launch_config.LaunchConfigError, match="region"): + launch_config.assert_region_declared({"wire_contract": True}) + + +@pytest.mark.parametrize("region", [None, "", " ", 0, False, ["land_gaul"], 7]) +def test_a_blank_or_non_string_region_is_refused_too(region): + # Declared-don't-infer applies to the TYPE as well: a region that is not a + # non-empty string cannot select a manifest, and must not reach the gates as + # though it had. (C-123 registers the general version of this gap elsewhere.) + # `match=` matters: without it this test cannot tell "you declared no region" + # from "that region is unrecognised", and a check that collapses the two walks + # through it (guard audit 2026-11-18, mutations MD3/MD4b/MD9). + with pytest.raises(launch_config.LaunchConfigError, match="did not declare"): + launch_config.assert_region_declared({"region": region}) + + +def test_the_refusal_distinguishes_itself_from_an_unpinned_region(): + # The message must not send the reader to pin a region that is already declared: + # the unpinned case is supported and is a different fix. + with pytest.raises(launch_config.LaunchConfigError) as excinfo: + launch_config.assert_region_declared({}) + message = str(excinfo.value) + assert "not yet" in message and "pinned" in message + assert "stays launchable" in message + + +def test_a_known_region_passes_whether_or_not_it_is_pinned(): + # africa_me_legacy is deliberately unpinned and MUST stay launchable — the + # falsification stub that prescribed refusing it would have grounded it. + assert launch_config.assert_region_declared({"region": "land_gaul"}) is None + assert launch_config.assert_region_declared({"region": "africa_me_legacy"}) is None + + +@pytest.mark.parametrize("region", ["lnd_gaul", "land-gaul", "not_pinned_anywhere"]) +def test_an_unrecognised_region_is_refused_at_launch(region): + """Found by review 2026-11-18, and this test replaces one that pinned the defect. + + The line above used to assert that `region: "not_pinned_anywhere"` LAUNCHED. It + does not any more, and the reason is that a name nobody recognises is not the + unpinned case: it misses both lookups in `delivery.coverage`, so both gates skip. + Refusing at launch means the operator hears about a misspelling before any store + call, not from a run log after the delivery shipped unchecked. + """ + with pytest.raises(launch_config.LaunchConfigError, match="does not recognise"): + launch_config.assert_region_declared({"region": region}) + + +def test_the_unrecognised_refusal_names_the_regions_it_knows(): + # So the fix is in the message: either the name is wrong, or the region is new + # and must be declared in one named place. + with pytest.raises(launch_config.LaunchConfigError) as excinfo: + launch_config.assert_region_declared({"region": "lnd_gaul"}) + message = str(excinfo.value) + assert "land_gaul" in message and "africa_me_legacy" in message + assert "KNOWN_REGIONS" in message diff --git a/tests/test_wire_source_selection.py b/tests/test_wire_source_selection.py index 0d84e23..2281e55 100644 --- a/tests/test_wire_source_selection.py +++ b/tests/test_wire_source_selection.py @@ -179,3 +179,81 @@ def download(self, file_id): assert excinfo.value.__cause__ is not None, ( "the store's own KeyError must be chained, not discarded" ) + + +# --- C-113, the forecast leg: an unpinned region leaves evidence ------------------- +# +# Found by review 2026-11-18. The managers' `_check_coverage` was fixed to call both +# gates unconditionally, but forecast coverage is asserted HERE, inside the lease's +# `load()`, behind two caller-side `if`s. For an unpinned region those `if`s were both +# false, so every target loaded with both gates skipped and NOTHING in the run log — +# the larger half of the defect the managers' fix claimed to have closed. + + +def test_an_unpinned_region_reports_both_skipped_gates_on_the_forecast_leg(caplog): + import logging + + with caplog.at_level(logging.WARNING, logger="views_postprocessing.delivery.coverage"): + leases = _resolve() # no excluded_gids, no expected_cells: the unpinned region + leases["lr_ged_sb"].load() + messages = [r.getMessage() for r in caplog.records] + assert any("exclusion-gate SKIPPED" in m for m in messages), messages + assert any("count-gate SKIPPED" in m for m in messages), messages + # Both name the leg, so a two-target run says which target was unchecked. + assert all("forecast[lr_ged_sb]" in m for m in messages if "SKIPPED" in m), messages + + +def test_a_pinned_region_still_enforces_both_gates_and_reports_no_skip(caplog): + import logging + + from views_postprocessing.delivery.coverage import CoverageError + + with caplog.at_level(logging.WARNING, logger="views_postprocessing.delivery.coverage"): + leases = _resolve(excluded_gids=frozenset({100006}), expected_cells=5) + leases["lr_ged_sb"].load() # 6 cells, one excluded -> 5 delivered: passes + assert not [r for r in caplog.records if "SKIPPED" in r.getMessage()] + + # The count gate still refuses when the pinned count does not match. This says + # "count gate" and not "exclusion gate" on purpose: `drop_units` removes the + # excluded cell on the line directly above the gates, so on THIS leg the + # exclusion gate is a post-condition on that call and cannot fire from a + # declared exclusion alone. An earlier version of this test claimed otherwise + # and a guard audit disproved it by making the exclusion gate blind and keeping + # the test green (2026-11-18, MF4). The exclusion gate's own refusal is tested + # where it can actually fire: tests/test_delivery_coverage.py. + leases = _resolve(excluded_gids=frozenset({100006}), expected_cells=6) + with pytest.raises(CoverageError, match="under-coverage"): + leases["lr_ged_sb"].load() + + +def test_the_exclusion_gate_is_a_post_condition_on_the_curation_it_follows(): + """What the exclusion gate is FOR on this leg: catching a `drop_units` that did + not drop. Proven by feeding the gate the uncurated cell set directly, which is + the state the gate exists to refuse. + """ + from views_postprocessing.contract.frame_extraction import cells_of + from views_postprocessing.delivery.coverage import ( + CoverageError, + assert_no_excluded_cells, + ) + + leases = _resolve() # no curation: the raw producer frame, 100006 included + frame, _ = leases["lr_ged_sb"].load() + assert 100006 in cells_of(frame) + with pytest.raises(CoverageError, match="100006"): + assert_no_excluded_cells(cells_of(frame), frozenset({100006}), label="forecast") + + +def test_the_gates_run_exclusion_before_count(monkeypatch): + """The order is load-bearing and was stated only in a comment: a leaked island + must name itself rather than arriving as "over-coverage by 1" (S4/C-30). A guard + audit swapped the two calls with the whole suite green (2026-11-18, MF3). + """ + from views_postprocessing.delivery import coverage as cov + + called = [] + monkeypatch.setattr(cov, "assert_no_excluded_cells", lambda *a, **k: called.append("exclusion")) + monkeypatch.setattr(cov, "assert_complete_coverage", lambda *a, **k: called.append("count")) + leases = _resolve(excluded_gids=frozenset({100006}), expected_cells=5) + leases["lr_ged_sb"].load() + assert called == ["exclusion", "count"] diff --git a/views_postprocessing/contract/launch_config.py b/views_postprocessing/contract/launch_config.py index 8ebcafb..8e5e55f 100644 --- a/views_postprocessing/contract/launch_config.py +++ b/views_postprocessing/contract/launch_config.py @@ -20,13 +20,17 @@ Deliberately dependency-light: no pipeline-core, no pandas, no frames — the queryset's ``data_format`` arrives as a plain string from the caller, so this -module stays importable (and testable) anywhere. +module stays importable (and testable) anywhere. The one package import, +``delivery.coverage``, imports nothing but ``logging`` itself and is here so the +set of regions has a single home rather than a copy in this file. """ from __future__ import annotations import logging +from views_postprocessing.delivery import coverage + logger = logging.getLogger(__name__) # The launch-config key that selects the ADR-013 contract delivery. Declared, never @@ -39,6 +43,11 @@ # passed here as a string so this module needs no pipeline-core import. FEATURE_FRAME_FORMAT = "feature_frame" +# The launch-config key naming the region whose cells the delivery must cover. +# Declared, never inferred, and never defaulted: the two coverage gates are chosen +# BY this value, so an absent one silently selects "check nothing" (register C-113). +REGION_KEY = "region" + class LaunchConfigError(ValueError): """The launcher did not declare the delivery this package implements.""" @@ -65,6 +74,73 @@ def assert_contract_mode(configs: dict) -> None: raise LaunchConfigError(err_msg) +def assert_region_declared(configs: dict) -> None: + """Raise unless the launch config declares a region. + + **Register C-113: an omission that disables two gates and looks like a feature.** + ``delivery.coverage`` chooses both gates by region — ``expected_for(region)`` gives + the completeness target and ``excluded_for(region)`` the curation manifest. Both + read the value out of ``configs`` with ``.get("region")``, so a launcher that never + mentioned a region produced ``None``, and ``None`` took the same path as a region + that is declared but **not yet pinned**: + + - ``expected_for(None) -> None`` → the count gate logs "skipped" and returns + - ``excluded_for(None) -> frozenset()`` → the exclusion gate is a no-op + + A delivery then shipped with its cell curation and its completeness check both + having done nothing, reported as a supported configuration. The supported one is + real — ``africa_me_legacy`` is deliberately unpinned, because "complete" is + ambiguous there until a run settles it — which is exactly why the two must not + share a representation. This is ADR-003's rule in the shape C-83 already found + once: the *absence* of an answer silently given the shape of an answer. + + A region that is declared but unpinned stays launchable and still logs a skipped + gate. Two cases are refused: no region at all, and a region this delivery does not + recognise. The second was found by review on 2026-11-18 and is the same defect one + level in — ``region: "lnd_gaul"`` is a non-empty string, so it passed this + assertion, missed both dictionary lookups, and disabled both gates while reporting + itself as the supported unpinned configuration. The recognised set is + ``delivery.coverage.KNOWN_REGIONS``, which is where regions are declared; this + function refuses in the launcher's own terms rather than keeping a second copy. + + Args: + configs: the launcher's config mapping. + + Raises: + LaunchConfigError: naming the missing key, or the unrecognised region, and + distinguishing both from the unpinned-region case so the reader does not + "fix" the wrong one. + """ + region = configs.get(REGION_KEY) + if not isinstance(region, str) or not region.strip(): + err_msg = ( + f"the launcher did not declare {REGION_KEY!r} (got {region!r}) — the " + "delivery chooses its cell-curation manifest and its completeness target " + "by region, so without one BOTH coverage gates silently pass. Set " + f"{REGION_KEY}: '' in the postprocessor's config_meta. " + "Note this is NOT the same as a region that is declared but not yet " + "pinned in delivery.coverage.EXPECTED_CELLS: that is supported, stays " + "launchable, and logs a skipped count-gate. There is no region to omit " + "your way into." + ) + logger.error(err_msg) # ADR-008: logged persistently AND raised + raise LaunchConfigError(err_msg) + if region not in coverage.KNOWN_REGIONS: + err_msg = ( + f"the launcher declared {REGION_KEY}: {region!r}, which this delivery does " + f"not recognise (known: {sorted(coverage.KNOWN_REGIONS)}). Both coverage " + "gates are selected by the region name, so an unrecognised one passes both " + "without checking anything — a mistyped letter disables exactly what " + "declaring a region is for, and it does so while looking like the " + "supported declared-but-unpinned case. Fix the name in the " + "postprocessor's config_meta, or, if views-datafactory has curated a new " + "region, declare it in delivery.coverage.KNOWN_REGIONS (and pin its cell " + "count and excluded-cell manifest once each is verified)." + ) + logger.error(err_msg) # ADR-008: logged persistently AND raised + raise LaunchConfigError(err_msg) + + def assert_queryset_was_importable(queryset: object | None) -> None: """Raise if the queryset could not be read at all — before asking what it declares. diff --git a/views_postprocessing/contract/wire/source_selection.py b/views_postprocessing/contract/wire/source_selection.py index 25a79bc..1c16e92 100644 --- a/views_postprocessing/contract/wire/source_selection.py +++ b/views_postprocessing/contract/wire/source_selection.py @@ -105,10 +105,16 @@ def fetch(name): # grid; the product excludes the declared GAUL-uncovered cells. frame = drop_units(frame, self.excluded_gids) cells = cells_of(frame) - if self.excluded_gids: - coverage.assert_no_excluded_cells(cells, self.excluded_gids, label=f"forecast[{self.target}]") - if self.expected_cells is not None: - coverage.assert_complete_coverage(cells, self.expected_cells, label=f"forecast[{self.target}]") + # Both gates are called UNCONDITIONALLY, and each reports its own skip for a + # region that pins no manifest or no count. The two `if`s that stood here were + # the same silence C-113 is about, on the larger leg: forecast coverage is + # asserted here, not in the managers, so an unpinned region loaded every target + # with both gates skipped and nothing in the run log. A caller-side `if` would + # restore it. Exclusion before count, so a leaked island names itself rather + # than reading as "over-coverage by 1" (S4/C-30). + label = f"forecast[{self.target}]" + coverage.assert_no_excluded_cells(cells, self.excluded_gids, label=label) + coverage.assert_complete_coverage(cells, self.expected_cells, label=label) return frame, headers diff --git a/views_postprocessing/crafd/managers/crafd.py b/views_postprocessing/crafd/managers/crafd.py index 947a8af..3bdc6da 100644 --- a/views_postprocessing/crafd/managers/crafd.py +++ b/views_postprocessing/crafd/managers/crafd.py @@ -243,8 +243,15 @@ def _read_forecast_data(self): The launcher must DECLARE ``wire_contract: True``. The pandas reader this key used to select was retired in #149; omitting the key is a refusal, not a fallback (register C-63). + + It must also DECLARE ``region``, for the same reason one axis further out: + both coverage gates are chosen by region, so an omitted one used to select + "check nothing" and report it as a supported configuration (register + C-113). Asserted here rather than at the first gate so the refusal arrives + before any contract-store call, not after the shards are leased. """ launch_config.assert_contract_mode(self.configs) + launch_config.assert_region_declared(self.configs) self._read_forecast_data_contract() def _read(self) -> any: @@ -306,21 +313,12 @@ def _check_coverage(self) -> None: len(cells), n_rows, ) - # GAUL-uncovered cells the curated region must drop (S4/C-30) — checked - # before the count gate so a leaked island names itself, not "over-coverage - # by 1". Empty for unpinned regions (e.g. africa_me_legacy keeps its ocean - # cells), so this is a no-op there. - if excluded: - coverage.assert_no_excluded_cells(cells, excluded, label=label) - if expected is not None: - coverage.assert_complete_coverage(cells, expected, label=label) - else: - logger.warning( - "Coverage count-gate skipped for %s: region %r is not pinned in " - "delivery.coverage.EXPECTED_CELLS — verify and pin before relying on it.", - label, - region, - ) + # Exclusion before count, so a leaked island names itself rather than + # reading as "over-coverage by 1" (S4/C-30). Each gate reports its own + # skip for an unpinned region — that is the invariant's business, not + # the shell's (C-113, C-40(a)). + coverage.assert_no_excluded_cells(cells, excluded, label=label) + coverage.assert_complete_coverage(cells, expected, label=label) def _save_contract(self) -> dict: """ADR-013 contract outbound (epic #105): the composed sink delivers the run. diff --git a/views_postprocessing/delivery/coverage.py b/views_postprocessing/delivery/coverage.py index 06722e6..0fc9197 100644 --- a/views_postprocessing/delivery/coverage.py +++ b/views_postprocessing/delivery/coverage.py @@ -2,29 +2,133 @@ Representation-free — primitives only (a set of cell ids + an int). No pandas, no views_frames. The manager feeds it primitives via -``views_postprocessing/unfao/extraction.py``; the rule lives here (S1 / register C-34). +``views_postprocessing/contract/frame_extraction.py``; the rule lives here +(S1 / register C-34). *(This pointed at ``unfao/extraction.py``, deleted in #151, +until 2026-11-12 — one of the two stale docstring pointers register C-107 names.)* + +**A region must be DECLARED to reach either gate.** ``expected_for`` and +``excluded_for`` refuse ``None``, because the gates are chosen by region and an +absent one used to select "check nothing" while reading as a supported +configuration (register C-113). A region that is declared but not yet *pinned* is +supported and different: it returns ``None``/empty, and the caller reports a +skipped gate. The launcher-facing refusal is +``contract.launch_config.assert_region_declared``; these two are the same rule held +at the invariant, for every other caller. """ from __future__ import annotations +import logging + +logger = logging.getLogger(__name__) + class CoverageError(ValueError): """A delivery did not cover exactly the expected set of cells.""" +class UnknownRegionError(ValueError): + """A region was declared, but not one this delivery recognises. + + A sibling of ``RegionNotDeclaredError`` and not a subclass of it: there the + launcher said nothing, here it said something this repository does not know. The + two have different fixes — add the config key, versus correct a misspelling or + declare a new region — so they must not share a message. Until 2026-11-18 an + unrecognised name took the declared-but-unpinned path, which means a single + mistyped letter disabled both gates and reported itself as a supported + configuration: register C-113's own shape, one level in. + """ + + +class RegionNotDeclaredError(ValueError): + """No region was declared, so neither coverage gate can be chosen. + + A sibling of ``CoverageError`` rather than a subclass, deliberately: nothing has + been delivered wrongly here. The *question* could not be asked, which is a + different fault with a different fix, and a caller catching ``CoverageError`` to + report a coverage failure must not catch this and mislabel it as one. + """ + + +# The region names this delivery recognises. +# +# SSOT CAVEAT, the same one EXPECTED_CELLS carries below: which regions exist is a +# *views-datafactory* fact (it curates the region cell-sets). It is declared here +# because both gates are selected BY the region name, so a name this repository does +# not recognise must not be allowed to select "check nothing". Source this from +# datafactory region metadata once it publishes a region list. +# +# Being KNOWN and being PINNED are separate statements. A region is known once +# datafactory curates it; it is pinned only once its cell count has been verified +# against a real run. ``africa_me_legacy`` is known and deliberately unpinned. +# +# Adding a region is a one-line declaration here. That is the intended cost: a region +# this file has not heard of produces a refusal that names it, never a silent pass. +KNOWN_REGIONS: frozenset[str] = frozenset({"land_gaul", "africa_me_legacy"}) + + +def _declared(region: str | None) -> str: + """The region, or refuse — declared, and one this delivery recognises. + + Chosen by region means an absent region checks nothing, and a region nobody here + has heard of checks nothing either. + """ + if not isinstance(region, str) or not region.strip(): + raise RegionNotDeclaredError( + f"no region declared (got {region!r}): the completeness target and the " + "cell-curation manifest are both selected BY the region, so there is " + "nothing to check and nothing to curate. This is not the same as a " + "region that is declared but unpinned — that is supported, returns no " + "target, and is reported as a skipped gate by the caller. Known " + f"regions: {sorted(KNOWN_REGIONS)} (of those, pinned: " + f"{sorted(EXPECTED_CELLS)}). Declared at launch; see " + "contract.launch_config.assert_region_declared (register C-113)." + ) + if region not in KNOWN_REGIONS: + raise UnknownRegionError( + f"region {region!r} is not one this delivery recognises (known: " + f"{sorted(KNOWN_REGIONS)}). Both coverage gates are selected by the region " + "name, so an unrecognised one would pass both without checking anything — " + "a single mistyped letter disables exactly what declaring a region is for. " + "If the name is wrong, fix it in the postprocessor's config_meta. If the " + "region is real and newly curated by views-datafactory, declare it in " + "delivery.coverage.KNOWN_REGIONS; pin its cell count in EXPECTED_CELLS and " + "its excluded-cell manifest in EXCLUDED_GIDS_BY_REGION once each is " + "verified against a run (register C-113)." + ) + return region + + def assert_complete_coverage( - received_gids: set[int], expected_count: int, *, label: str = "delivery" + received_gids: set[int], expected_count: int | None, *, label: str = "delivery" ) -> None: """Raise unless exactly ``expected_count`` distinct cells were delivered. + ``expected_count=None`` means the region is declared but **not pinned**, which is + supported: the gate cannot run, so it says so and returns. Reporting that here + rather than at the call site is what keeps the two managers from each carrying + their own copy of the rule — and it is the half of C-113 that was **silently** + skipped on the exclusion side while this side logged. + + An *undeclared* region never reaches this function: ``expected_for`` refuses it. + Args: received_gids: the distinct PRIO-GRID cell ids actually delivered. - expected_count: the number of cells the configured region must cover. + expected_count: the number of cells the configured region must cover, or + ``None`` for a declared-but-unpinned region. label: short tag for the message (e.g. ``"historical"`` / ``"forecast"``). Raises: CoverageError: on under- or over-coverage. """ + if expected_count is None: + logger.warning( + "%s: coverage count-gate SKIPPED — the declared region pins no cell count " + "in delivery.coverage.EXPECTED_CELLS, so completeness was not enforced. " + "Verify and pin the count before relying on this delivery being complete.", + label, + ) + return actual = len(received_gids) if actual != expected_count: kind = "under-coverage" if actual < expected_count else "over-coverage" @@ -58,8 +162,18 @@ def assert_complete_coverage( def expected_for(region: str | None) -> int | None: - """The pinned expected cell count for ``region``, or None if unpinned/unknown.""" - return EXPECTED_CELLS.get(region) if region else None + """The pinned expected cell count for ``region``. + + Returns: + The pinned count, or ``None`` for a region that is declared but not pinned + (``africa_me_legacy``) — a supported state the caller reports as a skipped + count-gate. + + Raises: + RegionNotDeclaredError: no region was declared at all. Until 2026-11-12 this + returned ``None`` too, which made the two indistinguishable (C-113). + """ + return EXPECTED_CELLS.get(_declared(region)) # Region -> the GAUL-uncovered cells the curated region deliberately drops. @@ -95,8 +209,19 @@ def expected_for(region: str | None) -> int | None: def excluded_for(region: str | None) -> frozenset[int]: - """The GAUL-uncovered gids the region must exclude — empty for unpinned regions.""" - return EXCLUDED_GIDS_BY_REGION.get(region, frozenset()) if region else frozenset() + """The GAUL-uncovered gids the region must exclude. + + Returns: + The frozen manifest, or an empty set for a region that is declared but not + pinned (``africa_me_legacy`` keeps its ocean cells) — supported, and a no-op + at the call site. + + Raises: + RegionNotDeclaredError: no region was declared at all. Until 2026-11-12 this + returned an empty set too, so an undeclared region curated nothing and + looked exactly like the region that is meant to curate nothing (C-113). + """ + return EXCLUDED_GIDS_BY_REGION.get(_declared(region), frozenset()) def assert_no_excluded_cells( @@ -112,10 +237,26 @@ def assert_no_excluded_cells( excluded_gids: the cells the configured region must exclude (see ``excluded_for``). label: short tag for the message (e.g. ``"historical"`` / ``"forecast"``). + An empty ``excluded_gids`` means the declared region pins no curation manifest + (``africa_me_legacy`` keeps its ocean cells) — supported, and the skip is + **reported** rather than passed over in silence. That silence was half of C-113: + the count gate logged its skip and this one did not, so a delivery could be + uncurated with only half the evidence reaching the run log. + + An *undeclared* region never reaches this function: ``excluded_for`` refuses it. + Raises: CoverageError: naming the leaked cells (these have no GAUL assignment, so shipping them would attribute partner rows to a non-country). """ + if not excluded_gids: + logger.warning( + "%s: coverage exclusion-gate SKIPPED — the declared region pins no " + "excluded-cell manifest in delivery.coverage.EXCLUDED_GIDS_BY_REGION, so " + "no cell curation was enforced.", + label, + ) + return leaked = sorted(received_gids & excluded_gids) if leaked: shown = leaked[:10] diff --git a/views_postprocessing/unfao/managers/unfao.py b/views_postprocessing/unfao/managers/unfao.py index fd047d2..bd6f2a3 100644 --- a/views_postprocessing/unfao/managers/unfao.py +++ b/views_postprocessing/unfao/managers/unfao.py @@ -243,8 +243,15 @@ def _read_forecast_data(self): The launcher must DECLARE ``wire_contract: True``. The pandas reader this key used to select was retired in #149; omitting the key is a refusal, not a fallback (register C-63). + + It must also DECLARE ``region``, for the same reason one axis further out: + both coverage gates are chosen by region, so an omitted one used to select + "check nothing" and report it as a supported configuration (register + C-113). Asserted here rather than at the first gate so the refusal arrives + before any contract-store call, not after the shards are leased. """ launch_config.assert_contract_mode(self.configs) + launch_config.assert_region_declared(self.configs) self._read_forecast_data_contract() def _read(self) -> any: @@ -306,21 +313,12 @@ def _check_coverage(self) -> None: len(cells), n_rows, ) - # GAUL-uncovered cells the curated region must drop (S4/C-30) — checked - # before the count gate so a leaked island names itself, not "over-coverage - # by 1". Empty for unpinned regions (e.g. africa_me_legacy keeps its ocean - # cells), so this is a no-op there. - if excluded: - coverage.assert_no_excluded_cells(cells, excluded, label=label) - if expected is not None: - coverage.assert_complete_coverage(cells, expected, label=label) - else: - logger.warning( - "Coverage count-gate skipped for %s: region %r is not pinned in " - "delivery.coverage.EXPECTED_CELLS — verify and pin before relying on it.", - label, - region, - ) + # Exclusion before count, so a leaked island names itself rather than + # reading as "over-coverage by 1" (S4/C-30). Each gate reports its own + # skip for an unpinned region — that is the invariant's business, not + # the shell's (C-113, C-40(a)). + coverage.assert_no_excluded_cells(cells, excluded, label=label) + coverage.assert_complete_coverage(cells, expected, label=label) def _save_contract(self) -> dict: """ADR-013 contract outbound (epic #105): the composed sink delivers the run.