diff --git a/changelog/1477.fixed.md b/changelog/1477.fixed.md new file mode 100644 index 000000000..ed0e7f1e1 --- /dev/null +++ b/changelog/1477.fixed.md @@ -0,0 +1,5 @@ +A tracking run with `delete_unused_nodes=True` (as used by generators) now deletes unused nodes that hold each other through a mandatory relationship in one run. + +The cleanup deleted the unused members in the order the group returns them, which is creation order. A node created first, such as an IP address, was deleted before the unused node that holds it through a mandatory relationship, such as a BGP session. The server refused the delete, so the run failed with `TrackingGroupCleanupError` and the node was only deleted by the next run. + +The cleanup now deletes a node before the nodes it holds through a mandatory relationship. The order between kinds comes from the cached schema and sends no request. Nodes of a kind with a mandatory relationship to its own kind (or kinds that hold each other) are ordered from their peers, which takes one query per such kind. A member that a node outside the group holds is still refused, kept in the group and reported in `TrackingGroupCleanupError`. diff --git a/infrahub_sdk/query_groups.py b/infrahub_sdk/query_groups.py index 8f65314cb..395c88040 100644 --- a/infrahub_sdk/query_groups.py +++ b/infrahub_sdk/query_groups.py @@ -1,6 +1,6 @@ from __future__ import annotations -from collections.abc import Sequence +from collections.abc import Mapping, Sequence from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any @@ -14,6 +14,7 @@ URLNotFoundError, code_names_the_failure, ) +from .schema.dependencies import DeletionOrder from .utils import dict_hash if TYPE_CHECKING: @@ -99,12 +100,15 @@ class ReapResult: unattempted: The ids the reap never got to, because something unrelated to any member stopped it. error: The failure that stopped the reap, if one did. + ordering_error: The failure that prevented working out the deletion order, if one did. + The members were then deleted in group order, so this does not stop the reap. """ refused: dict[str, str] = field(default_factory=dict) unattempted: list[str] = field(default_factory=list) error: Exception | None = None + ordering_error: Exception | None = None @property def retained_member_ids(self) -> list[str]: @@ -112,14 +116,40 @@ def retained_member_ids(self) -> list[str]: return list(self.refused) + self.unattempted def failure(self) -> Exception | None: - """What to raise once the group is written: the error that stopped the reap, or the refusals.""" + """What to raise once the group is written. + + The error that stopped the reap comes first, then the failure to work out the deletion + order, then the refusals. The refused members stay in the group whichever is raised. + """ if self.error is not None: return self.error + if self.ordering_error is not None: + return self.ordering_error if self.refused: return TrackingGroupCleanupError(failures=self.refused) return None +def _mandatory_peer_ids(node: InfrahubNode | InfrahubNodeSync, relationships: Mapping[str, bool]) -> set[str]: + """The ids of the peers `node` holds through the named relationships.""" + peer_ids: set[str] = set() + for name, cardinality_many in relationships.items(): + if cardinality_many: + peer_ids.update(node._get_relationship_many(name=name).peer_ids) + elif (peer_id := node._get_relationship_one(name=name).id) is not None: + peer_ids.add(peer_id) + return peer_ids + + +def _member_peers( + nodes: Sequence[InfrahubNode | InfrahubNodeSync], relationships: Mapping[str, bool] +) -> dict[str, set[str]]: + """The mandatory peer ids of each node, by node id.""" + return { + node.id: _mandatory_peer_ids(node=node, relationships=relationships) for node in nodes if node.id is not None + } + + class InfrahubGroupContextBase: """Base class for InfrahubGroupContext and InfrahubGroupContextSync.""" @@ -256,9 +286,39 @@ async def get_group(self, store_peers: bool = False) -> InfrahubNode | None: self.previous_members = group._get_relationship_many(name="members").peers return group + async def _order_for_deletion(self, candidates: list[tuple[str, str]]) -> list[tuple[str, str]]: + """The candidates in the order given by `DeletionOrder`. + + The schema comes from the client's cache, so ordering sends a request only for members that + must be ordered among themselves, or once to refresh the schema when a member's kind is not cached. + """ + if len(candidates) < 2: + return candidates + deletion_order = DeletionOrder(candidates=candidates, schemas=await self.client.schema.all(branch=self.branch)) + if deletion_order.unknown_kinds: + deletion_order = DeletionOrder( + candidates=candidates, schemas=await self.client.schema.all(branch=self.branch, refresh=True) + ) + member_peers: dict[str, set[str]] = {} + for lookup in deletion_order.peer_lookups: + nodes = await self.client.filters( + kind=lookup.kind, + ids=lookup.ids, + only=list(lookup.relationships), + branch=self.branch, + populate_store=False, + ) + member_peers.update(_member_peers(nodes=nodes, relationships=lookup.relationships)) + return deletion_order.order(node_peers=member_peers) + async def delete_unused(self) -> ReapResult: """Delete the members that this run no longer uses. + Members are deleted in an order where no member is deleted while another member + still holds it through a mandatory relationship (see `DeletionOrder`). If that order + cannot be worked out, the members are deleted in group order instead, so the members + that nothing holds are still deleted, and the failure is returned in `ordering_error`. + A refusal by the server is a fact about the member, so it is recorded against it and the remaining candidates are still attempted. Any other failure is not a fact about the member being deleted, so it stops the reap and is returned as itself @@ -273,6 +333,10 @@ async def delete_unused(self) -> ReapResult: """ result = ReapResult() candidates = self._reap_candidates() + try: + candidates = await self._order_for_deletion(candidates) + except Exception as exc: + result.ordering_error = exc for position, (kind, member_id) in enumerate(candidates): try: @@ -348,10 +412,13 @@ async def update_group(self) -> None: ) await group.save(allow_upsert=True, update_group_context=False) except Exception as exc: - if reap.error is None: - raise - # The write usually fails for the reason the reap stopped; report that reason. - raise reap.error from exc + if reap.error is not None: + # The write usually fails for the reason the reap stopped; report that reason. + raise reap.error from exc + if reap.ordering_error is not None: + # The ordering failure did not stop the reap, so the write failed on its own. + raise exc from reap.ordering_error + raise if (failure := reap.failure()) is not None: raise failure @@ -382,9 +449,39 @@ def get_group(self, store_peers: bool = False) -> InfrahubNodeSync | None: self.previous_members = group._get_relationship_many(name="members").peers return group + def _order_for_deletion(self, candidates: list[tuple[str, str]]) -> list[tuple[str, str]]: + """The candidates in the order given by `DeletionOrder`. + + The schema comes from the client's cache, so ordering sends a request only for members that + must be ordered among themselves, or once to refresh the schema when a member's kind is not cached. + """ + if len(candidates) < 2: + return candidates + deletion_order = DeletionOrder(candidates=candidates, schemas=self.client.schema.all(branch=self.branch)) + if deletion_order.unknown_kinds: + deletion_order = DeletionOrder( + candidates=candidates, schemas=self.client.schema.all(branch=self.branch, refresh=True) + ) + member_peers: dict[str, set[str]] = {} + for lookup in deletion_order.peer_lookups: + nodes = self.client.filters( + kind=lookup.kind, + ids=lookup.ids, + only=list(lookup.relationships), + branch=self.branch, + populate_store=False, + ) + member_peers.update(_member_peers(nodes=nodes, relationships=lookup.relationships)) + return deletion_order.order(node_peers=member_peers) + def delete_unused(self) -> ReapResult: """Delete the members that this run no longer uses. + Members are deleted in an order where no member is deleted while another member + still holds it through a mandatory relationship (see `DeletionOrder`). If that order + cannot be worked out, the members are deleted in group order instead, so the members + that nothing holds are still deleted, and the failure is returned in `ordering_error`. + A refusal by the server is a fact about the member, so it is recorded against it and the remaining candidates are still attempted. Any other failure is not a fact about the member being deleted, so it stops the reap and is returned as itself @@ -399,6 +496,10 @@ def delete_unused(self) -> ReapResult: """ result = ReapResult() candidates = self._reap_candidates() + try: + candidates = self._order_for_deletion(candidates) + except Exception as exc: + result.ordering_error = exc for position, (kind, member_id) in enumerate(candidates): try: @@ -474,10 +575,13 @@ def update_group(self) -> None: ) group.save(allow_upsert=True, update_group_context=False) except Exception as exc: - if reap.error is None: - raise - # The write usually fails for the reason the reap stopped; report that reason. - raise reap.error from exc + if reap.error is not None: + # The write usually fails for the reason the reap stopped; report that reason. + raise reap.error from exc + if reap.ordering_error is not None: + # The ordering failure did not stop the reap, so the write failed on its own. + raise exc from reap.ordering_error + raise if (failure := reap.failure()) is not None: raise failure diff --git a/infrahub_sdk/schema/dependencies.py b/infrahub_sdk/schema/dependencies.py new file mode 100644 index 000000000..3c6c6d553 --- /dev/null +++ b/infrahub_sdk/schema/dependencies.py @@ -0,0 +1,163 @@ +"""The order in which to delete nodes, from their kinds' mandatory relationships. + +The server refuses to delete a node while another node holds it through a mandatory relationship, +so the node that holds it is deleted first. +""" + +from __future__ import annotations + +from collections.abc import Mapping +from dataclasses import dataclass +from typing import TYPE_CHECKING + +from ..topological_sort import dependents_first, strongly_connected_components +from .main import GenericSchemaAPI + +if TYPE_CHECKING: + from . import MainSchemaTypesAPI + + +@dataclass +class PeerLookup: + """The nodes of one kind whose mandatory peers must be read to order them among themselves. + + Attributes: + kind: The kind of the nodes. + ids: The ids of the nodes of that kind. + relationships: The name of each mandatory relationship to read, mapped to whether it has cardinality many. + + """ + + kind: str + ids: list[str] + relationships: dict[str, bool] + + +def _mandatory_peer_kinds( + schema: MainSchemaTypesAPI, schemas: Mapping[str, MainSchemaTypesAPI], candidate_kinds: set[str] +) -> dict[str, set[str]]: + """The name of each mandatory relationship of `schema`, mapped to the kinds in `candidate_kinds` its peer can be. + + A peer that is a generic in `schemas` matches the kinds listed in its `used_by`. This includes + `CoreNode`, which every node implements without naming it in `inherit_from`. A generic missing + from `schemas` matches the kinds whose `inherit_from` names it. + """ + peer_kinds: dict[str, set[str]] = {} + for name in schema.mandatory_relationship_names: + peer = schema.get_relationship(name).peer + kinds = {peer} & candidate_kinds + peer_schema = schemas.get(peer) + if isinstance(peer_schema, GenericSchemaAPI): + kinds |= set(peer_schema.used_by) & candidate_kinds + kinds |= {kind for kind in candidate_kinds if peer in getattr(schemas[kind], "inherit_from", [])} + if kinds: + peer_kinds[name] = kinds + return peer_kinds + + +class DeletionOrder: + """Orders the nodes to delete so that no node is deleted while another one still holds it. + + The server refuses to delete a node that another node holds through a mandatory relationship, so + the node that holds it has to be deleted first. Kinds are ordered from the schema alone. Nodes of + the same kind, or of kinds that hold each other, can only be ordered from their actual peers, which + `peer_lookups` names and `order` takes. + + `schemas` holds every schema of the branch, generics included, because a peer that is a generic + is resolved through the generic's `used_by`. + + A kind missing from the schema cannot be ordered, so its nodes go last. + """ + + def __init__(self, candidates: list[tuple[str, str]], schemas: Mapping[str, MainSchemaTypesAPI]) -> None: + self.candidates = candidates + kinds = list(dict.fromkeys(kind for kind, _ in candidates)) + self.kinds = [kind for kind in kinds if kind in schemas] + self.unknown_kinds = {kind for kind in kinds if kind not in schemas} + + candidate_kinds = set(self.kinds) + self.relationships = { + kind: _mandatory_peer_kinds(schema=schemas[kind], schemas=schemas, candidate_kinds=candidate_kinds) + for kind in self.kinds + } + self.cardinality_many = { + kind: {name: schemas[kind].get_relationship(name).cardinality_is_many for name in self.relationships[kind]} + for kind in self.kinds + } + self.graph: dict[str, set[str]] = {kind: set().union(*self.relationships[kind].values()) for kind in self.kinds} + self.blocks = strongly_connected_components(graph=self.graph, order=self.kinds) + + def _is_cyclic(self, block: list[str]) -> bool: + return len(block) > 1 or block[0] in self.graph[block[0]] + + @property + def peer_lookups(self) -> list[PeerLookup]: + """The nodes whose mandatory peers are needed, one entry per kind. Empty in the common case.""" + lookups: list[PeerLookup] = [] + for block in self.blocks: + if not self._is_cyclic(block): + continue + block_kinds = set(block) + # Every kind in a cyclic block has at least one mandatory relationship into the block. + for kind in block: + relationships = { + name: self.cardinality_many[kind][name] + for name, peer_kinds in self.relationships[kind].items() + if peer_kinds & block_kinds + } + ids = [node_id for node_kind, node_id in self.candidates if node_kind == kind] + lookups.append(PeerLookup(kind=kind, ids=ids, relationships=relationships)) + return lookups + + def order(self, node_peers: Mapping[str, set[str]] | None = None) -> list[tuple[str, str]]: + """The candidates in the order to delete them. + + Args: + node_peers: The mandatory peer ids of each node named by `peer_lookups`. + + Raises: + RuntimeError: If the kinds cannot be ordered, so that no candidate is left out of the order. + + """ + node_peers = node_peers or {} + block_key = {kind: block[0] for block in self.blocks for kind in block} + block_graph = { + block[0]: {block_key[peer_kind] for kind in block for peer_kind in self.graph[kind]} - {block[0]} + for block in self.blocks + } + block_order = dependents_first(dependencies=block_graph, order=self.kinds) + if block_order is None: + raise RuntimeError("The strongly connected components of the kinds to delete form a cycle") + blocks = {block[0]: block for block in self.blocks} + + ordered: list[tuple[str, str]] = [] + for key in block_order: + ordered.extend(self._order_block(block=blocks[key], node_peers=node_peers)) + ordered.extend(candidate for candidate in self.candidates if candidate[0] in self.unknown_kinds) + return ordered + + def _order_block(self, block: list[str], node_peers: Mapping[str, set[str]]) -> list[tuple[str, str]]: + block_kinds = set(block) + nodes = [candidate for candidate in self.candidates if candidate[0] in block_kinds] + if not self._is_cyclic(block): + return nodes + + node_ids = [node_id for _, node_id in nodes] + id_set = set(node_ids) + dependencies = {node_id: (node_peers.get(node_id, set()) & id_set) - {node_id} for node_id in node_ids} + # Nodes that hold each other in a cycle cannot be deleted in any order, so the nodes of each + # cycle keep group order and the server refuses them. The cycles are ordered among the other + # nodes, so a node that is not part of a cycle is still deleted. + components = strongly_connected_components(graph=dependencies, order=node_ids) + component_key = {node_id: component[0] for component in components for node_id in component} + component_graph = { + component[0]: {component_key[peer] for node_id in component for peer in dependencies[node_id]} + - {component[0]} + for component in components + } + component_order = dependents_first(dependencies=component_graph, order=node_ids) + if component_order is None: + raise RuntimeError("The strongly connected components of the nodes to delete form a cycle") + members = {component[0]: component for component in components} + kind_of = {node_id: kind for kind, node_id in nodes} + return [(kind_of[node_id], node_id) for key in component_order for node_id in members[key]] diff --git a/infrahub_sdk/topological_sort.py b/infrahub_sdk/topological_sort.py index 58047bd4d..ab12ac259 100644 --- a/infrahub_sdk/topological_sort.py +++ b/infrahub_sdk/topological_sort.py @@ -67,3 +67,56 @@ def _get_cycles(dependency_dict: dict[str, Iterable[str]], path: list[str]) -> l if next_cycles: cycles += next_cycles return cycles + + +def strongly_connected_components(graph: Mapping[str, set[str]], order: Sequence[str]) -> list[list[str]]: + """Group the keys of `graph` into components where every key can reach every other one (Tarjan). + + Keys and components follow `order`, so the result does not depend on set iteration order. + """ + position = {key: index for index, key in enumerate(order)} + index: dict[str, int] = {} + low: dict[str, int] = {} + stack: list[str] = [] + on_stack: set[str] = set() + components: list[list[str]] = [] + + def visit(key: str) -> None: + index[key] = low[key] = len(index) + stack.append(key) + on_stack.add(key) + for peer in sorted(graph[key], key=position.__getitem__): + if peer not in index: + visit(peer) + low[key] = min(low[key], low[peer]) + elif peer in on_stack: + low[key] = min(low[key], index[peer]) + if low[key] == index[key]: + component: list[str] = [] + while True: + member = stack.pop() + on_stack.discard(member) + component.append(member) + if member == key: + break + components.append(sorted(component, key=position.__getitem__)) + + for key in order: + if key not in index: + visit(key) + return components + + +def dependents_first(dependencies: Mapping[str, set[str]], order: Sequence[str]) -> list[str] | None: + """Sort the keys of `dependencies` so each key comes before the keys it depends on. + + Keys are grouped by the length of the dependency chain below them and returned from the longest + chain to the shortest; within a group they follow `order`. A key without dependencies can + therefore come after an unrelated key that has some. Returns None on a cycle. + """ + position = {key: index for index, key in enumerate(order)} + try: + levels = topological_sort(dependencies) + except DependencyCycleExistsError: + return None + return [key for level in reversed(levels) for key in sorted(level, key=position.__getitem__)] diff --git a/tests/helpers/schemas.py b/tests/helpers/schemas.py new file mode 100644 index 000000000..4de66d6b2 --- /dev/null +++ b/tests/helpers/schemas.py @@ -0,0 +1,34 @@ +from __future__ import annotations + +from typing import Any + +from infrahub_sdk.schema import GenericSchemaAPI, NodeSchemaAPI + + +def node_schema( + name: str, relationships: list[dict[str, Any]] | None = None, inherit_from: list[str] | None = None +) -> dict[str, Any]: + """A node schema in the Repro namespace, as the schema API returns it.""" + return { + "name": name, + "namespace": "Repro", + "inherit_from": inherit_from or [], + "attributes": [{"name": "name", "kind": "Text"}], + "relationships": relationships or [], + } + + +def mandatory(name: str, peer: str, cardinality: str = "one") -> dict[str, Any]: + """A mandatory relationship to `peer`.""" + return {"name": name, "peer": peer, "optional": False, "cardinality": cardinality} + + +def node_schemas(*nodes: dict[str, Any]) -> dict[str, NodeSchemaAPI]: + """The given node schemas, by kind.""" + schemas = [NodeSchemaAPI(**node) for node in nodes] + return {schema.kind: schema for schema in schemas} + + +def generic_schema(name: str, namespace: str, used_by: list[str]) -> GenericSchemaAPI: + """A generic schema implemented by the kinds in `used_by`, as the schema API returns it.""" + return GenericSchemaAPI(name=name, namespace=namespace, used_by=used_by) diff --git a/tests/integration/test_tracking_zero_members.py b/tests/integration/test_tracking_zero_members.py index 53007fe59..83ed8859c 100644 --- a/tests/integration/test_tracking_zero_members.py +++ b/tests/integration/test_tracking_zero_members.py @@ -197,6 +197,33 @@ async def test_zero_member_run_prunes_on_the_tracked_branch( with pytest.raises(NodeNotFoundError, match=person_name): await client.get(kind=TESTING_PERSON, name__value=person_name, branch=self.BRANCH) + async def test_unused_owner_and_animal_are_deleted_in_one_run( + self, client: InfrahubClient, base_dataset: None + ) -> None: + """The person is created first, so the group lists it before the cat that holds it.""" + person_name = "TrackingOrderedPerson" + params = {"person_name": person_name} + + async with client.start_tracking(identifier=self.IDENTIFIER, params=params, delete_unused_nodes=True) as clt: + person = await clt.create(kind=TESTING_PERSON, name=person_name) + await person.save(allow_upsert=True) + cat = await clt.create(kind=TESTING_CAT, name="TrackingOrderedCat", breed="Bengal", owner=person) + await cat.save(allow_upsert=True) + + group_name = client.group_context._generate_group_name() + group = await client.get(kind="CoreStandardGroup", name__value=group_name, include=["members"]) + assert group.members.peer_ids == [person.id, cat.id] + + async with client.start_tracking(identifier=self.IDENTIFIER, params=params, delete_unused_nodes=True): + pass + + group = await client.get(kind="CoreStandardGroup", name__value=group_name, include=["members"]) + assert len(group.members.peers) == 0 + with pytest.raises(NodeNotFoundError, match=cat.id): + await client.get(kind=TESTING_CAT, id=cat.id) + with pytest.raises(NodeNotFoundError, match=person.id): + await client.get(kind=TESTING_PERSON, id=person.id) + class TestTrackingSync(TestInfrahubDockerClient, SchemaAnimal): BRANCH = "sync-tracking-branch01" @@ -366,3 +393,30 @@ def test_zero_member_run_prunes_on_the_tracked_branch( client_sync.get(kind="BuiltinTag", name__value=tag_name, branch=self.BRANCH) with pytest.raises(NodeNotFoundError, match=person_name): client_sync.get(kind=TESTING_PERSON, name__value=person_name, branch=self.BRANCH) + + def test_unused_owner_and_animal_are_deleted_in_one_run( + self, client_sync: InfrahubClientSync, base_dataset: None + ) -> None: + """The person is created first, so the group lists it before the cat that holds it.""" + person_name = "SyncTrackingOrderedPerson" + params = {"person_name": person_name} + + with client_sync.start_tracking(identifier=self.IDENTIFIER, params=params, delete_unused_nodes=True) as clt: + person = clt.create(kind=TESTING_PERSON, name=person_name) + person.save(allow_upsert=True) + cat = clt.create(kind=TESTING_CAT, name="SyncTrackingOrderedCat", breed="Bengal", owner=person) + cat.save(allow_upsert=True) + + group_name = client_sync.group_context._generate_group_name() + group = client_sync.get(kind="CoreStandardGroup", name__value=group_name, include=["members"]) + assert group.members.peer_ids == [person.id, cat.id] + + with client_sync.start_tracking(identifier=self.IDENTIFIER, params=params, delete_unused_nodes=True): + pass + + group = client_sync.get(kind="CoreStandardGroup", name__value=group_name, include=["members"]) + assert len(group.members.peers) == 0 + with pytest.raises(NodeNotFoundError, match=cat.id): + client_sync.get(kind=TESTING_CAT, id=cat.id) + with pytest.raises(NodeNotFoundError, match=person.id): + client_sync.get(kind=TESTING_PERSON, id=person.id) diff --git a/tests/unit/sdk/test_group_context.py b/tests/unit/sdk/test_group_context.py index d81122697..5001a0f04 100644 --- a/tests/unit/sdk/test_group_context.py +++ b/tests/unit/sdk/test_group_context.py @@ -31,6 +31,7 @@ ReapResult, ) from tests.helpers.fixtures import read_fixture +from tests.helpers.schemas import mandatory, node_schema, node_schemas if TYPE_CHECKING: from pytest_httpx import HTTPXMock @@ -522,7 +523,407 @@ def test_reap_result_failure_prefers_the_error_that_stopped_the_reap() -> None: assert ReapResult().failure() is None +def test_reap_result_failure_prefers_the_stopping_error_then_the_ordering_error() -> None: + """The ordering failure is raised over refusals, but not over an error that stopped the reap.""" + interruption = ServerNotResponsiveError(url="http://mock/graphql/main") + ordering_error = RecursionError("maximum recursion depth exceeded") + refusals = {"refused1": MANDATORY_RELATIONSHIP_ERROR} + + assert ReapResult(refused=refusals, error=interruption, ordering_error=ordering_error).failure() is interruption + assert ReapResult(refused=refusals, ordering_error=ordering_error).failure() is ordering_error + assert ReapResult(refused=refusals, ordering_error=ordering_error).retained_member_ids == ["refused1"] + + def test_reap_result_retains_refused_and_unattempted_members() -> None: result = ReapResult(refused={"refused1": MANDATORY_RELATIONSHIP_ERROR}, unattempted=["unattempted1"]) assert result.retained_member_ids == ["refused1", "unattempted1"] assert ReapResult().retained_member_ids == [] + + +TARGET_ID = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa" +DEPENDENT_ID = "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb" +CHAIN_IDS = [ + "c1c1c1c1-c1c1-c1c1-c1c1-c1c1c1c1c1c1", + "c2c2c2c2-c2c2-c2c2-c2c2-c2c2c2c2c2c2", + "c3c3c3c3-c3c3-c3c3-c3c3-c3c3c3c3c3c3", +] + + +def _schema_with(base: dict, *nodes: dict[str, Any]) -> dict: + return {**base, "nodes": [*base["nodes"], *nodes]} + + +def _group_with_members(members: list[tuple[str, str]]) -> dict[str, Any]: + response = _group_query_response(member_ids=[]) + group = response["data"]["CoreStandardGroup"]["edges"][0]["node"] + group["members"] = { + "count": len(members), + "edges": [ + {"node": {"id": member_id, "display_label": member_id, "__typename": kind}} for kind, member_id in members + ], + } + return response + + +def _delete_response(kind: str) -> dict[str, Any]: + return {"data": {f"{kind}Delete": {"ok": True}}} + + +def _deleted_ids(requests: list[httpx.Request], ids: list[str]) -> list[str]: + """The ids named by the delete mutations, in the order they were sent.""" + deleted: list[str] = [] + for request in requests: + body = request.read().decode() + if "Delete" in body: + deleted.extend(member_id for member_id in ids if member_id in body) + return deleted + + +@pytest.mark.parametrize("client_type", client_types) +async def test_reap_deletes_the_holder_before_the_node_it_holds( + clients: BothClients, client_type: str, schema_query_05_data: dict, httpx_mock: HTTPXMock +) -> None: + """One run deletes both unused nodes, without a refused delete and without an extra request.""" + schema = _schema_with( + schema_query_05_data, + node_schema("Target"), + node_schema("Dependent", relationships=[mandatory("target", "ReproTarget")]), + ) + httpx_mock.add_response( + method="POST", + url="http://mock/graphql/main", + json=_group_with_members([("ReproTarget", TARGET_ID), ("ReproDependent", DEPENDENT_ID)]), + ) + httpx_mock.add_response(method="POST", url="http://mock/graphql/main", json=_delete_response("ReproDependent")) + httpx_mock.add_response(method="POST", url="http://mock/graphql/main", json=_delete_response("ReproTarget")) + httpx_mock.add_response(method="POST", url="http://mock/graphql/main", json=UPSERT_RESPONSE) + + await _track_nothing(clients=clients, client_type=client_type, schema=schema) + + requests = httpx_mock.get_requests() + assert len(requests) == 4 + assert _deleted_ids(requests, [TARGET_ID, DEPENDENT_ID]) == [DEPENDENT_ID, TARGET_ID] + + +@pytest.mark.parametrize("client_type", client_types) +async def test_reap_reads_peers_to_order_members_of_a_self_referencing_kind( + clients: BothClients, client_type: str, schema_query_05_data: dict, httpx_mock: HTTPXMock +) -> None: + """One query reads the chain links' peers, then the last link is deleted first.""" + schema = _schema_with( + schema_query_05_data, node_schema("Chain", relationships=[mandatory("previous", "ReproChain")]) + ) + previous = {CHAIN_IDS[1]: CHAIN_IDS[0], CHAIN_IDS[2]: CHAIN_IDS[1]} + chain_response = { + "data": { + "ReproChain": { + "count": len(CHAIN_IDS), + "edges": [ + { + "node": { + "id": member_id, + "display_label": member_id, + "__typename": "ReproChain", + "name": {"value": member_id}, + "previous": { + "node": {"id": previous[member_id], "__typename": "ReproChain"} + if member_id in previous + else None + }, + } + } + for member_id in CHAIN_IDS + ], + } + } + } + httpx_mock.add_response( + method="POST", + url="http://mock/graphql/main", + json=_group_with_members([("ReproChain", member_id) for member_id in CHAIN_IDS]), + ) + httpx_mock.add_response(method="POST", url="http://mock/graphql/main", json=chain_response) + # The test clients page by 3 items, so a full first page is followed by an empty one. + httpx_mock.add_response( + method="POST", + url="http://mock/graphql/main", + json={"data": {"ReproChain": {"count": len(CHAIN_IDS), "edges": []}}}, + ) + for _ in CHAIN_IDS: + httpx_mock.add_response(method="POST", url="http://mock/graphql/main", json=_delete_response("ReproChain")) + httpx_mock.add_response(method="POST", url="http://mock/graphql/main", json=UPSERT_RESPONSE) + + await _track_nothing(clients=clients, client_type=client_type, schema=schema) + + requests = httpx_mock.get_requests() + assert len(requests) == 7 + assert _deleted_ids(requests, CHAIN_IDS) == CHAIN_IDS[::-1] + + +@pytest.mark.parametrize("client_type", client_types) +async def test_member_held_from_outside_the_group_is_kept_and_reported( + clients: BothClients, client_type: str, schema_query_05_data: dict, httpx_mock: HTTPXMock +) -> None: + """Ordering cannot help when a node the run does not delete holds the member.""" + schema = _schema_with(schema_query_05_data, node_schema("Target")) + httpx_mock.add_response( + method="POST", url="http://mock/graphql/main", json=_group_with_members([("ReproTarget", TARGET_ID)]) + ) + httpx_mock.add_response( + method="POST", + url="http://mock/graphql/main", + json={"data": None, "errors": [{"message": MANDATORY_RELATIONSHIP_ERROR}]}, + ) + httpx_mock.add_response(method="POST", url="http://mock/graphql/main", json=UPSERT_RESPONSE) + + with pytest.raises(TrackingGroupCleanupError, match="Unable to delete 1 unused member") as exc_info: + await _track_nothing(clients=clients, client_type=client_type, schema=schema) + + assert list(exc_info.value.failures) == [TARGET_ID] + assert TARGET_ID in httpx_mock.get_requests()[-1].read().decode() + + +@pytest.mark.parametrize("client_type", client_types) +async def test_failed_peer_query_deletes_in_group_order_and_raises_after_the_group_write( + clients: BothClients, client_type: str, schema_query_05_data: dict, httpx_mock: HTTPXMock +) -> None: + """Without the order the members are deleted in group order, and the failure is raised once the group is written.""" + schema = _schema_with( + schema_query_05_data, node_schema("Chain", relationships=[mandatory("previous", "ReproChain")]) + ) + members = [("ReproChain", member_id) for member_id in CHAIN_IDS] + httpx_mock.add_response(method="POST", url="http://mock/graphql/main", json=_group_with_members(members)) + httpx_mock.add_exception(httpx.ReadTimeout("read timed out"), method="POST", url="http://mock/graphql/main") + for _ in CHAIN_IDS: + httpx_mock.add_response(method="POST", url="http://mock/graphql/main", json=_delete_response("ReproChain")) + httpx_mock.add_response(method="POST", url="http://mock/graphql/main", json=UPSERT_RESPONSE) + + with pytest.raises(ServerNotResponsiveError, match="Unable to read from"): + await _track_nothing(clients=clients, client_type=client_type, schema=schema) + + requests = httpx_mock.get_requests() + assert len(requests) == 6 + assert _deleted_ids(requests, CHAIN_IDS) == CHAIN_IDS + upsert = requests[-1].read().decode() + assert "Upsert" in upsert + assert not any(member_id in upsert for member_id in CHAIN_IDS) + + +@pytest.mark.parametrize("client_type", client_types) +async def test_failed_write_after_a_failed_peer_query_raises_the_write_error( + clients: BothClients, client_type: str, schema_query_05_data: dict, httpx_mock: HTTPXMock +) -> None: + """The ordering failure did not stop the deletes, so a write that fails on its own is what is raised.""" + schema = _schema_with( + schema_query_05_data, node_schema("Chain", relationships=[mandatory("previous", "ReproChain")]) + ) + members = [("ReproChain", member_id) for member_id in CHAIN_IDS] + httpx_mock.add_response(method="POST", url="http://mock/graphql/main", json=_group_with_members(members)) + httpx_mock.add_exception(httpx.ReadTimeout("read timed out"), method="POST", url="http://mock/graphql/main") + for _ in CHAIN_IDS: + httpx_mock.add_response(method="POST", url="http://mock/graphql/main", json=_delete_response("ReproChain")) + httpx_mock.add_response(method="POST", url="http://mock/graphql/main", json=code_response("merge_in_progress")) + + with pytest.raises(MergeInProgressError, match=r"^MERGE_IN_PROGRESS: ") as exc_info: + await _track_nothing(clients=clients, client_type=client_type, schema=schema) + + assert isinstance(exc_info.value.__cause__, ServerNotResponsiveError) + + +@pytest.mark.parametrize("client_type", client_types) +async def test_failed_peer_query_keeps_the_refused_member_and_raises_the_ordering_failure( + clients: BothClients, client_type: str, schema_query_05_data: dict, httpx_mock: HTTPXMock +) -> None: + """A member refused during the group-order fallback stays in the group; the ordering failure is still raised.""" + schema = _schema_with( + schema_query_05_data, node_schema("Chain", relationships=[mandatory("previous", "ReproChain")]) + ) + members = [("ReproChain", member_id) for member_id in CHAIN_IDS] + httpx_mock.add_response(method="POST", url="http://mock/graphql/main", json=_group_with_members(members)) + httpx_mock.add_exception(httpx.ReadTimeout("read timed out"), method="POST", url="http://mock/graphql/main") + httpx_mock.add_response( + method="POST", + url="http://mock/graphql/main", + json={"data": None, "errors": [{"message": MANDATORY_RELATIONSHIP_ERROR}]}, + ) + for _ in CHAIN_IDS[1:]: + httpx_mock.add_response(method="POST", url="http://mock/graphql/main", json=_delete_response("ReproChain")) + httpx_mock.add_response(method="POST", url="http://mock/graphql/main", json=UPSERT_RESPONSE) + + with pytest.raises(ServerNotResponsiveError, match="Unable to read from"): + await _track_nothing(clients=clients, client_type=client_type, schema=schema) + + requests = httpx_mock.get_requests() + assert len(requests) == 6 + assert _deleted_ids(requests, CHAIN_IDS) == CHAIN_IDS + upsert = requests[-1].read().decode() + assert CHAIN_IDS[0] in upsert + assert not any(member_id in upsert for member_id in CHAIN_IDS[1:]) + + +def test_mandatory_peer_ids_reads_both_cardinalities(clients: BothClients) -> None: + from infrahub_sdk.node import InfrahubNode # noqa: PLC0415 + + schema = node_schemas( + node_schema( + "Left", + relationships=[ + mandatory("rights", "ReproRight", cardinality="many"), + mandatory("anchor", "ReproRight"), + mandatory("spare", "ReproRight"), + ], + ) + )["ReproLeft"] + node = InfrahubNode( + client=clients.standard, + schema=schema, + data={"id": TARGET_ID, "rights": [{"id": CHAIN_IDS[0]}, {"id": CHAIN_IDS[1]}], "anchor": {"id": CHAIN_IDS[2]}}, + ) + + peer_ids = query_groups._mandatory_peer_ids( + node=node, relationships={"rights": True, "anchor": False, "spare": False} + ) + + assert peer_ids == set(CHAIN_IDS) + + +LEFT_IDS = ["l1l1l1l1-l1l1-l1l1-l1l1-l1l1l1l1l1l1", "l2l2l2l2-l2l2-l2l2-l2l2-l2l2l2l2l2l2"] +RIGHT_ID = "r1r1r1r1-r1r1-r1r1-r1r1-r1r1r1r1r1r1" +OUTSIDE_RIGHT_ID = "r9r9r9r9-r9r9-r9r9-r9r9-r9r9r9r9r9r9" + + +def _peer_query_response(kind: str, relationship: str, peers: dict[str, tuple[str, list[str]]]) -> dict[str, Any]: + """The answer to a peer query on `kind` that reads one cardinality-many relationship, in the shape it asks for. + + `peers` maps each node id to the kind and the ids of the peers it holds through `relationship`. + """ + return { + "data": { + kind: { + "count": len(peers), + "edges": [ + { + "node": { + "id": node_id, + "display_label": node_id, + "__typename": kind, + relationship: { + "edges": [ + { + "node": { + "id": peer_id, + "hfid": None, + "display_label": peer_id, + "__typename": peer_kind, + } + } + for peer_id in peer_ids + ], + }, + } + } + for node_id, (peer_kind, peer_ids) in peers.items() + ], + } + } + } + + +@pytest.mark.parametrize("client_type", client_types) +async def test_reap_reads_cardinality_many_peers_to_order_kinds_that_hold_each_other( + clients: BothClients, client_type: str, schema_query_05_data: dict, httpx_mock: HTTPXMock +) -> None: + """Each kind's peers are read through a cardinality-many relationship, then the holders are deleted first. + + The first left holds the right, which holds the second left, so group order would be refused twice. + """ + schema = _schema_with( + schema_query_05_data, + node_schema("Left", relationships=[mandatory("rights", "ReproRight", cardinality="many")]), + node_schema("Right", relationships=[mandatory("lefts", "ReproLeft", cardinality="many")]), + ) + members = [("ReproLeft", LEFT_IDS[1]), ("ReproRight", RIGHT_ID), ("ReproLeft", LEFT_IDS[0])] + httpx_mock.add_response(method="POST", url="http://mock/graphql/main", json=_group_with_members(members)) + httpx_mock.add_response( + method="POST", + url="http://mock/graphql/main", + json=_peer_query_response( + kind="ReproLeft", + relationship="rights", + peers={LEFT_IDS[1]: ("ReproRight", [OUTSIDE_RIGHT_ID]), LEFT_IDS[0]: ("ReproRight", [RIGHT_ID])}, + ), + ) + httpx_mock.add_response( + method="POST", + url="http://mock/graphql/main", + json=_peer_query_response( + kind="ReproRight", relationship="lefts", peers={RIGHT_ID: ("ReproLeft", [LEFT_IDS[1]])} + ), + ) + httpx_mock.add_response(method="POST", url="http://mock/graphql/main", json=_delete_response("ReproLeft")) + httpx_mock.add_response(method="POST", url="http://mock/graphql/main", json=_delete_response("ReproRight")) + httpx_mock.add_response(method="POST", url="http://mock/graphql/main", json=_delete_response("ReproLeft")) + httpx_mock.add_response(method="POST", url="http://mock/graphql/main", json=UPSERT_RESPONSE) + + # An ordering failure would be raised here, after the group write. + await _track_nothing(clients=clients, client_type=client_type, schema=schema) + + requests = httpx_mock.get_requests() + assert len(requests) == 7 + assert "rights {" in requests[1].read().decode() + assert "lefts {" in requests[2].read().decode() + assert _deleted_ids(requests, [*LEFT_IDS, RIGHT_ID]) == [LEFT_IDS[0], RIGHT_ID, LEFT_IDS[1]] + assert "Upsert" in requests[-1].read().decode() + + +async def _order(clients: BothClients, client_type: str, candidates: list[tuple[str, str]]) -> list[tuple[str, str]]: + """Order the candidates with the context of the client under test.""" + if client_type == "standard": + context = InfrahubGroupContext(client=clients.standard) + context.set_properties(identifier=IDENTIFIER, branch="main") + return await context._order_for_deletion(candidates) + sync_context = InfrahubGroupContextSync(client=clients.sync) + sync_context.set_properties(identifier=IDENTIFIER, branch="main") + return sync_context._order_for_deletion(candidates) + + +@pytest.mark.parametrize("client_type", client_types) +async def test_ordering_refreshes_the_schema_once_when_a_member_kind_is_not_cached( + clients: BothClients, client_type: str, schema_query_05_data: dict, httpx_mock: HTTPXMock +) -> None: + """A kind missing from the cached schema is fetched once, then ordered like any other.""" + client = clients.standard if client_type == "standard" else clients.sync + client.schema.set_cache(schema=schema_query_05_data, branch="main") + refreshed = _schema_with( + schema_query_05_data, + node_schema("Target"), + node_schema("Dependent", relationships=[mandatory("target", "ReproTarget")]), + ) + httpx_mock.add_response(method="GET", url="http://mock/api/schema?branch=main", json=refreshed) + candidates = [("ReproTarget", TARGET_ID), ("ReproDependent", DEPENDENT_ID)] + + ordered = await _order(clients=clients, client_type=client_type, candidates=candidates) + + assert ordered == [("ReproDependent", DEPENDENT_ID), ("ReproTarget", TARGET_ID)] + assert len(httpx_mock.get_requests()) == 1 + + +@pytest.mark.parametrize("client_type", client_types) +async def test_ordering_sends_no_schema_request_when_every_member_kind_is_cached( + clients: BothClients, client_type: str, schema_query_05_data: dict, httpx_mock: HTTPXMock +) -> None: + client = clients.standard if client_type == "standard" else clients.sync + client.schema.set_cache( + schema=_schema_with( + schema_query_05_data, + node_schema("Target"), + node_schema("Dependent", relationships=[mandatory("target", "ReproTarget")]), + ), + branch="main", + ) + candidates = [("ReproTarget", TARGET_ID), ("ReproDependent", DEPENDENT_ID)] + + ordered = await _order(clients=clients, client_type=client_type, candidates=candidates) + + assert ordered == [("ReproDependent", DEPENDENT_ID), ("ReproTarget", TARGET_ID)] + assert httpx_mock.get_requests() == [] diff --git a/tests/unit/sdk/test_schema_dependencies.py b/tests/unit/sdk/test_schema_dependencies.py new file mode 100644 index 000000000..7782c354e --- /dev/null +++ b/tests/unit/sdk/test_schema_dependencies.py @@ -0,0 +1,164 @@ +from __future__ import annotations + +import pytest + +from infrahub_sdk.schema import dependencies +from infrahub_sdk.schema.dependencies import DeletionOrder, PeerLookup +from tests.helpers.schemas import generic_schema, mandatory, node_schema, node_schemas + +TARGET_ID = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa" +DEPENDENT_ID = "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb" +CHAIN_IDS = [ + "c1c1c1c1-c1c1-c1c1-c1c1-c1c1c1c1c1c1", + "c2c2c2c2-c2c2-c2c2-c2c2-c2c2c2c2c2c2", + "c3c3c3c3-c3c3-c3c3-c3c3-c3c3c3c3c3c3", +] + + +def test_deletion_order_deletes_the_holder_before_the_node_it_holds() -> None: + """Group order is creation order, so the node that is held comes first and must be moved last.""" + schemas = node_schemas( + node_schema("Target"), node_schema("Dependent", relationships=[mandatory("target", "ReproTarget")]) + ) + order = DeletionOrder(candidates=[("ReproTarget", TARGET_ID), ("ReproDependent", DEPENDENT_ID)], schemas=schemas) + + assert order.peer_lookups == [] + assert order.order() == [("ReproDependent", DEPENDENT_ID), ("ReproTarget", TARGET_ID)] + + +def test_deletion_order_resolves_a_generic_peer_to_the_kinds_inheriting_it() -> None: + schemas = node_schemas( + node_schema("Address", inherit_from=["ReproEndpoint"]), + node_schema("Session", relationships=[mandatory("src", "ReproEndpoint")]), + ) + order = DeletionOrder(candidates=[("ReproAddress", TARGET_ID), ("ReproSession", DEPENDENT_ID)], schemas=schemas) + + assert order.order() == [("ReproSession", DEPENDENT_ID), ("ReproAddress", TARGET_ID)] + + +def test_deletion_order_resolves_a_generic_peer_through_its_used_by() -> None: + """Every node implements CoreNode without naming it in inherit_from, as CoreGeneratorInstance.object shows.""" + schemas = { + **node_schemas(node_schema("Thing"), node_schema("Note", relationships=[mandatory("object", "CoreNode")])), + "CoreNode": generic_schema("Node", namespace="Core", used_by=["ReproThing", "ReproNote"]), + } + order = DeletionOrder(candidates=[("ReproThing", TARGET_ID), ("ReproNote", DEPENDENT_ID)], schemas=schemas) + + # ReproNote implements CoreNode too, so it can hold another ReproNote and its peers must be read. + assert order.peer_lookups == [PeerLookup(kind="ReproNote", ids=[DEPENDENT_ID], relationships={"object": False})] + assert order.order(node_peers={DEPENDENT_ID: {TARGET_ID}}) == [ + ("ReproNote", DEPENDENT_ID), + ("ReproThing", TARGET_ID), + ] + + +def test_deletion_order_follows_a_chain_of_kinds() -> None: + schemas = node_schemas( + node_schema("First"), + node_schema("Second", relationships=[mandatory("first", "ReproFirst")]), + node_schema("Third", relationships=[mandatory("second", "ReproSecond")]), + ) + candidates = [("ReproFirst", CHAIN_IDS[0]), ("ReproSecond", CHAIN_IDS[1]), ("ReproThird", CHAIN_IDS[2])] + + assert DeletionOrder(candidates=candidates, schemas=schemas).order() == candidates[::-1] + + +def test_deletion_order_ignores_optional_relationships() -> None: + schemas = node_schemas( + node_schema("Target"), + node_schema("Dependent", relationships=[{"name": "target", "peer": "ReproTarget", "optional": True}]), + ) + candidates = [("ReproTarget", TARGET_ID), ("ReproDependent", DEPENDENT_ID)] + + assert DeletionOrder(candidates=candidates, schemas=schemas).order() == candidates + + +def test_deletion_order_orders_members_of_the_same_kind_by_their_peers() -> None: + """Each chain link holds the previous one, so the last created is deleted first.""" + schemas = node_schemas(node_schema("Chain", relationships=[mandatory("previous", "ReproChain")])) + candidates = [("ReproChain", member_id) for member_id in CHAIN_IDS] + order = DeletionOrder(candidates=candidates, schemas=schemas) + + assert order.peer_lookups == [PeerLookup(kind="ReproChain", ids=CHAIN_IDS, relationships={"previous": False})] + member_peers = {CHAIN_IDS[1]: {CHAIN_IDS[0]}, CHAIN_IDS[2]: {CHAIN_IDS[1]}} + assert order.order(node_peers=member_peers) == candidates[::-1] + + +def test_deletion_order_orders_kinds_that_hold_each_other_by_their_peers() -> None: + schemas = node_schemas( + node_schema("Left", relationships=[mandatory("rights", "ReproRight", cardinality="many")]), + node_schema("Right", relationships=[mandatory("lefts", "ReproLeft", cardinality="many")]), + ) + candidates = [("ReproLeft", TARGET_ID), ("ReproRight", DEPENDENT_ID)] + order = DeletionOrder(candidates=candidates, schemas=schemas) + + assert {lookup.kind for lookup in order.peer_lookups} == {"ReproLeft", "ReproRight"} + assert order.order(node_peers={DEPENDENT_ID: {TARGET_ID}}) == candidates[::-1] + + +def test_deletion_order_keeps_group_order_without_peers_for_a_self_referencing_kind() -> None: + schemas = node_schemas(node_schema("Chain", relationships=[mandatory("previous", "ReproChain")])) + candidates = [("ReproChain", member_id) for member_id in CHAIN_IDS] + + assert DeletionOrder(candidates=candidates, schemas=schemas).order() == candidates + + +def test_deletion_order_puts_a_kind_missing_from_the_schema_last() -> None: + schemas = node_schemas( + node_schema("Target"), node_schema("Dependent", relationships=[mandatory("target", "ReproTarget")]) + ) + candidates = [("ReproRemoved", CHAIN_IDS[0]), ("ReproTarget", TARGET_ID), ("ReproDependent", DEPENDENT_ID)] + + assert DeletionOrder(candidates=candidates, schemas=schemas).order() == [ + ("ReproDependent", DEPENDENT_ID), + ("ReproTarget", TARGET_ID), + ("ReproRemoved", CHAIN_IDS[0]), + ] + + +def test_deletion_order_ignores_a_mandatory_peer_that_is_not_a_candidate() -> None: + """A peer kind the run is not deleting adds no dependency between the candidates.""" + schemas = node_schemas( + node_schema("Target"), + node_schema("Dependent", relationships=[mandatory("target", "ReproTarget")]), + ) + candidates = [("ReproDependent", DEPENDENT_ID), ("ReproDependent", CHAIN_IDS[0])] + order = DeletionOrder(candidates=candidates, schemas=schemas) + + assert order.peer_lookups == [] + assert order.order() == candidates + + +def test_deletion_order_keeps_group_order_when_the_peers_form_a_cycle() -> None: + """The server cannot store such a cycle; if the peers read back describe one, the group order is kept.""" + schemas = node_schemas(node_schema("Chain", relationships=[mandatory("previous", "ReproChain")])) + candidates = [("ReproChain", member_id) for member_id in CHAIN_IDS[:2]] + member_peers = {CHAIN_IDS[0]: {CHAIN_IDS[1]}, CHAIN_IDS[1]: {CHAIN_IDS[0]}} + + order = DeletionOrder(candidates=candidates, schemas=schemas) + + assert order.order(node_peers=member_peers) == candidates + + +def test_deletion_order_orders_the_other_nodes_around_a_cycle() -> None: + """Only the nodes in the cycle keep group order; the chain beside it is still ordered by its peers.""" + schemas = node_schemas(node_schema("Chain", relationships=[mandatory("previous", "ReproChain")])) + a, b, c, x, y = ("a", "b", "c", "x", "y") + candidates = [("ReproChain", member_id) for member_id in (a, b, c, x, y)] + member_peers = {b: {a}, c: {b}, x: {y}, y: {x}} + + order = DeletionOrder(candidates=candidates, schemas=schemas) + + assert order.order(node_peers=member_peers) == [("ReproChain", member_id) for member_id in (c, b, a, x, y)] + + +def test_deletion_order_raises_when_the_kinds_cannot_be_ordered(monkeypatch: pytest.MonkeyPatch) -> None: + """Without an order of the kinds, the candidates of known kinds must not be dropped.""" + schemas = node_schemas( + node_schema("Target"), node_schema("Dependent", relationships=[mandatory("target", "ReproTarget")]) + ) + order = DeletionOrder(candidates=[("ReproTarget", TARGET_ID), ("ReproDependent", DEPENDENT_ID)], schemas=schemas) + monkeypatch.setattr(dependencies, "dependents_first", lambda **_: None) + + with pytest.raises(RuntimeError, match="components of the kinds to delete form a cycle"): + order.order() diff --git a/tests/unit/sdk/test_topological_sort.py b/tests/unit/sdk/test_topological_sort.py index a9769d715..2ad4d0056 100644 --- a/tests/unit/sdk/test_topological_sort.py +++ b/tests/unit/sdk/test_topological_sort.py @@ -1,6 +1,11 @@ import pytest -from infrahub_sdk.topological_sort import DependencyCycleExistsError, topological_sort +from infrahub_sdk.topological_sort import ( + DependencyCycleExistsError, + dependents_first, + strongly_connected_components, + topological_sort, +) def test_topological_sort_empty() -> None: @@ -96,3 +101,25 @@ def test_topological_sort_binary_tree() -> None: ordered = topological_sort(dependencies) assert ordered == [{"l", "m", "h", "i", "e", "g", "k"}, {"j", "d"}, {"b", "f"}, {"c"}, {"a"}] + + +def test_strongly_connected_components_groups_keys_that_reach_each_other() -> None: + graph = {"a": {"b"}, "b": {"a"}, "c": {"c"}, "d": {"a"}} + + components = strongly_connected_components(graph=graph, order=["a", "b", "c", "d"]) + + assert sorted(components) == [["a", "b"], ["c"], ["d"]] + + +def test_dependents_first_puts_each_key_before_its_dependencies() -> None: + dependencies = {"held": set(), "holder": {"held"}, "unrelated": set()} + + assert dependents_first(dependencies=dependencies, order=["held", "holder", "unrelated"]) == [ + "holder", + "held", + "unrelated", + ] + + +def test_dependents_first_returns_none_on_a_cycle() -> None: + assert dependents_first(dependencies={"a": {"b"}, "b": {"a"}}, order=["a", "b"]) is None