From c27b9016a5cc9410f3c2575716094f36ce03df6a Mon Sep 17 00:00:00 2001 From: cwasicki <126617870+cwasicki@users.noreply.github.com> Date: Tue, 1 Dec 2026 17:16:46 +0100 Subject: [PATCH] Reject split gridpool relations of a market location A market location tied to a microgrid joins a gridpool through the three-sided relation. A gridpool relation naming it without the microgrid, next to one naming the microgrid, leaves it unclear whether it trades standalone or as part of the microgrid. Only overlapping relations are rejected, so a market location may move from standalone to a microgrid over time. Signed-off-by: cwasicki <126617870+cwasicki@users.noreply.github.com> --- RELEASE_NOTES.md | 3 + src/frequenz/gridpool/config/_assets.py | 34 ++++- src/frequenz/gridpool/config/_topology.py | 24 ++++ tests/test_topology.py | 160 ++++++++++++++++++++++ 4 files changed, 219 insertions(+), 2 deletions(-) diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index 1f1a0a1..243c02a 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -10,6 +10,9 @@ and producer formulas. `ComponentGraph.consumer_formula()` and `ComponentGraph.producer_formula()` can now return values previously pinned to zero: a negative consumer total, or a positive producer total. +- `AssetsConfig.check` rejects a market location whose gridpool relation names + no microgrid while another relation ties it to a microgrid at the same time; + name all three in one relation instead. ## New Features diff --git a/src/frequenz/gridpool/config/_assets.py b/src/frequenz/gridpool/config/_assets.py index d5b0b87..89bef13 100644 --- a/src/frequenz/gridpool/config/_assets.py +++ b/src/frequenz/gridpool/config/_assets.py @@ -141,8 +141,10 @@ def check(self) -> None: filed under, a relation names fewer than two sides, its key disagrees with its fields, a gridpool relation names no delivery area, one market location is placed in two of them, a legacy - microgrid gridpool ID disagrees with its relations, or a - gridpool's declared and inferred enterprise disagree. + microgrid gridpool ID disagrees with its relations, a market + location has a gridpool relation without a microgrid next to + one with, or a gridpool's declared and inferred enterprise + disagree. """ for key, location in self.market_locations.items(): if location.id is None: @@ -152,6 +154,7 @@ def check(self) -> None: f"Market location key mismatch: key {key} != {location.id}" ) self._check_relations() + self._check_split_market_locations() self._check_legacy_gridpool_ids() self._check_gridpool_enterprises() @@ -202,6 +205,33 @@ def _check_relations(self) -> None: f"{seen[area.code].code_type.name} and {area.code_type.name}" ) + def _check_split_market_locations(self) -> None: + """Check no market location joins a gridpool around its microgrid. + + Raises: + ValueError: If a gridpool relation names a market location but no + microgrid, and overlaps a relation naming it with a microgrid. + """ + with_microgrid: dict[str, list[RelationConfig]] = {} + without: list[tuple[str, RelationConfig]] = [] + for relation in self.relations.values(): + mlid = relation.market_location_id + if mlid is None: + continue + if relation.microgrid_id is None: + without.append((mlid, relation)) + else: + with_microgrid.setdefault(mlid, []).append(relation) + + for mlid, relation in without: + for other in with_microgrid.get(mlid, []): + if relation.overlaps(other): + raise ValueError( + f"Relations {relation.key} and {other.key} overlap: a " + "market location related to a microgrid joins a " + "gridpool only through a relation naming all three" + ) + def _check_legacy_gridpool_ids(self) -> None: """Check legacy microgrid gridpool IDs against the relations.""" gridpools_by_microgrid: dict[int, set[int]] = {} diff --git a/src/frequenz/gridpool/config/_topology.py b/src/frequenz/gridpool/config/_topology.py index 99c7e08..a447794 100644 --- a/src/frequenz/gridpool/config/_topology.py +++ b/src/frequenz/gridpool/config/_topology.py @@ -248,6 +248,10 @@ class RelationConfig: participations apart; one without is a plain window, for a relation that serves a single use or none, such as a bare microgrid-to-market-location metering relation. A relation with no periods applies at all times. + + A market location related to a microgrid joins a gridpool through the + three-sided relation only: a gridpool relation naming it without a + microgrid must not overlap any relation naming it with one. """ gridpool_id: int | None = None @@ -324,6 +328,26 @@ def covers(self, at: datetime) -> bool: return True return any(period.covers(at) for period in self.validity.values()) + def overlaps(self, other: "RelationConfig") -> bool: + """Check whether this relation and another share an instant. + + Periods of any use case count, and a relation with no periods applies + always, so it overlaps any other. + + Args: + other: The relation to compare with. + + Returns: + Whether the two relations apply over a shared instant. + """ + if not self.validity or not other.validity: + return True + return any( + period.overlaps(other_period) + for period in self.validity.values() + for other_period in other.validity.values() + ) + def matches( self, *, diff --git a/tests/test_topology.py b/tests/test_topology.py index d71c402..7be26dc 100644 --- a/tests/test_topology.py +++ b/tests/test_topology.py @@ -272,6 +272,166 @@ def test_market_location_in_two_delivery_areas_rejected() -> None: ) +_AREA = {"code": _AREA_A} + + +def _window(start: int | None, end: int | None) -> dict[str, Any]: + """Build a plain validity window between two years.""" + window: dict[str, Any] = {} + if start is not None: + window["start"] = _dt(start, 1, 1) + if end is not None: + window["end"] = _dt(end, 1, 1) + return {"w": window} + + +@pytest.mark.parametrize( + "with_microgrid", + [ + {"microgrid_id": 1, "market_location_id": "111"}, + { + "gridpool_id": 7, + "microgrid_id": 1, + "market_location_id": "111", + "delivery_area": _AREA, + }, + ], +) +def test_split_market_location_rejected(with_microgrid: dict[str, Any]) -> None: + """Reject a gridpool-only link alongside a microgrid link for the same MaLo.""" + with pytest.raises(ValueError, match="naming all three"): + _load( + **_relations( + with_microgrid, + {"gridpool_id": 7, "market_location_id": "111", "delivery_area": _AREA}, + ) + ) + + +@pytest.mark.parametrize( + ("gridpool_validity", "microgrid_validity"), + [ + pytest.param(_window(2026, 2028), _window(2027, 2029), id="bounded-overlap"), + pytest.param({}, _window(2027, 2029), id="timeless-gridpool"), + pytest.param(_window(2026, 2028), {}, id="timeless-microgrid"), + pytest.param( + {"early": {"end": _dt(2025, 1, 1)}, **_window(2027, 2029)}, + _window(2028, 2030), + id="later-gridpool-period", + ), + pytest.param( + _window(2028, 2030), + {"early": {"end": _dt(2025, 1, 1)}, **_window(2027, 2029)}, + id="later-microgrid-period", + ), + ], +) +def test_split_market_location_overlapping_periods_rejected( + gridpool_validity: dict[str, Any], microgrid_validity: dict[str, Any] +) -> None: + """Any shared instant makes a split market location invalid.""" + with pytest.raises(ValueError, match="naming all three"): + _load( + **_relations( + { + "gridpool_id": 7, + "market_location_id": "111", + "delivery_area": _AREA, + "validity": gridpool_validity, + }, + { + "microgrid_id": 1, + "market_location_id": "111", + "validity": microgrid_validity, + }, + ) + ) + + +def test_split_market_location_with_different_participations_rejected() -> None: + """Different market use cases do not exempt a split market location.""" + with pytest.raises(ValueError, match="naming all three"): + _load( + **_relations( + { + "gridpool_id": 7, + "market_location_id": "111", + "delivery_area": _AREA, + "validity": { + "trading": { + "participation": "ENERGY_TRADING", + "start": _dt(2026, 1, 1), + "end": _dt(2028, 1, 1), + } + }, + }, + { + "gridpool_id": 7, + "microgrid_id": 1, + "market_location_id": "111", + "delivery_area": _AREA, + "validity": { + "flex": { + "participation": "FLEX_MARKETS", + "start": _dt(2027, 1, 1), + "end": _dt(2029, 1, 1), + } + }, + }, + ) + ) + + +@pytest.mark.parametrize( + ("gridpool_validity", "microgrid_validity"), + [ + pytest.param(_window(None, 2027), _window(2027, None), id="adjacent"), + pytest.param(_window(2028, 2029), _window(2026, 2027), id="gap"), + pytest.param( + {"early": {"end": _dt(2026, 1, 1)}, **_window(2028, None)}, + _window(2026, 2028), + id="between-periods", + ), + ], +) +def test_split_market_location_over_disjoint_periods_allowed( + gridpool_validity: dict[str, Any], microgrid_validity: dict[str, Any] +) -> None: + """Split relations are allowed when they share no instant.""" + config = _load( + **_relations( + { + "gridpool_id": 7, + "market_location_id": "111", + "delivery_area": _AREA, + "validity": gridpool_validity, + }, + { + "microgrid_id": 1, + "market_location_id": "111", + "validity": microgrid_validity, + }, + ) + ) + assert set(config.relations) == {"G7L111", "M1L111"} + + +def test_metering_and_three_sided_relation_allowed() -> None: + """A metering relation sits next to the three-sided gridpool relation.""" + config = _load( + **_relations( + {"microgrid_id": 1, "market_location_id": "111"}, + { + "gridpool_id": 7, + "microgrid_id": 1, + "market_location_id": "111", + "delivery_area": _AREA, + }, + ) + ) + assert set(config.relations) == {"M1L111", "G7M1L111"} + + def test_delivery_area_code_with_two_code_types_rejected() -> None: """A delivery-area code is bound to a single code type across relations.""" with pytest.raises(ValueError, match="two code types"):