From db8656dbaec4c3495adc8177f8b395fcfb033c3a Mon Sep 17 00:00:00 2001 From: Mikhail Yohman Date: Thu, 5 Nov 2026 11:21:08 -0700 Subject: [PATCH 01/11] fix(tracking): delete unused members before the nodes they hold The tracking cleanup deleted unused group members in the order the group returns them, which is creation order. A node created first was deleted before the unused node that holds it through a mandatory relationship, so the server refused the delete and the run failed with TrackingGroupCleanupError. Order the deletes from the cached schema, and from the members' peers for kinds that hold nodes of their own kind. If the order cannot be worked out, nothing is deleted and the failure stops the cleanup, keeping every member in the group. Co-Authored-By: Claude Opus 5.5 --- changelog/1477.fixed.md | 5 + infrahub_sdk/query_groups.py | 268 ++++++++++++++++- .../integration/test_tracking_zero_members.py | 54 ++++ tests/unit/sdk/test_group_context.py | 280 ++++++++++++++++++ 4 files changed, 606 insertions(+), 1 deletion(-) create mode 100644 changelog/1477.fixed.md 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..fe44d301d 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 .topological_sort import DependencyCycleExistsError, topological_sort from .utils import dict_hash if TYPE_CHECKING: @@ -120,6 +121,207 @@ def failure(self) -> Exception | None: return None +@dataclass +class PeerLookup: + """The members of one kind whose mandatory peers must be read to order them among themselves. + + Attributes: + kind: The kind of the members. + ids: The ids of the members 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]) -> dict[str, set[str]]: + """The name of each mandatory relationship of `schema`, mapped to the kinds in `schemas` its peer can be. + + A peer that is a generic matches every kind in `schemas` that inherits from it. + """ + peer_kinds: dict[str, set[str]] = {} + for relationship in schema.relationships: + if relationship.optional: + continue + kinds = { + kind + for kind, peer_schema in schemas.items() + if relationship.peer == kind or relationship.peer in getattr(peer_schema, "inherit_from", []) + } + if kinds: + peer_kinds[relationship.name] = kinds + return peer_kinds + + +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 with no dependency between them keep their place in `order`. 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__)] + + +class DeletionOrder: + """Orders the members to delete so that no member 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. Members 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. + + A kind missing from the schema cannot be ordered, so its members 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_schemas = {kind: schemas[kind] for kind in self.kinds} + self.relationships = { + kind: _mandatory_peer_kinds(candidate_schemas[kind], candidate_schemas) for kind in self.kinds + } + self.cardinality_many = { + kind: { + name: candidate_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 members 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) + 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 + } + if relationships: + ids = [member_id for candidate_kind, member_id in self.candidates if candidate_kind == kind] + lookups.append(PeerLookup(kind=kind, ids=ids, relationships=relationships)) + return lookups + + def order(self, member_peers: Mapping[str, set[str]] | None = None) -> list[tuple[str, str]]: + """The candidates in the order to delete them. + + Args: + member_peers: The mandatory peer ids of each member named by `peer_lookups`. + + """ + member_peers = member_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) or [] + 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], member_peers=member_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], member_peers: Mapping[str, set[str]]) -> list[tuple[str, str]]: + block_kinds = set(block) + members = [candidate for candidate in self.candidates if candidate[0] in block_kinds] + if not self._is_cyclic(block): + return members + + member_ids = [member_id for _, member_id in members] + id_set = set(member_ids) + dependencies = { + member_id: (member_peers.get(member_id, set()) & id_set) - {member_id} for member_id in member_ids + } + # A cycle of mandatory relationships between nodes cannot be stored, but keep the + # group order rather than fail if the peers read back describe one. + ordered_ids = _dependents_first(dependencies=dependencies, order=member_ids) + if ordered_ids is None: + return members + kind_of = {member_id: kind for kind, member_id in members} + return [(kind_of[member_id], member_id) for member_id in ordered_ids] + + +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 +458,34 @@ 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. + """ + if len(candidates) < 2: + return candidates + deletion_order = DeletionOrder(candidates=candidates, schemas=await self.client.schema.all(branch=self.branch)) + 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(member_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, nothing is deleted and the failure stops the reap. + 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 +500,13 @@ async def delete_unused(self) -> ReapResult: """ result = ReapResult() candidates = self._reap_candidates() + try: + candidates = await self._order_for_deletion(candidates) + except Exception as exc: + # Deleting unordered would only trade this failure for refusals; nothing was deleted yet. + result.error = exc + result.unattempted = [member_id for _, member_id in candidates] + return result for position, (kind, member_id) in enumerate(candidates): try: @@ -382,9 +616,34 @@ 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. + """ + if len(candidates) < 2: + return candidates + deletion_order = DeletionOrder(candidates=candidates, schemas=self.client.schema.all(branch=self.branch)) + 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(member_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, nothing is deleted and the failure stops the reap. + 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 +658,13 @@ def delete_unused(self) -> ReapResult: """ result = ReapResult() candidates = self._reap_candidates() + try: + candidates = self._order_for_deletion(candidates) + except Exception as exc: + # Deleting unordered would only trade this failure for refusals; nothing was deleted yet. + result.error = exc + result.unattempted = [member_id for _, member_id in candidates] + return result for position, (kind, member_id) in enumerate(candidates): try: diff --git a/tests/integration/test_tracking_zero_members.py b/tests/integration/test_tracking_zero_members.py index 53007fe59..21ce65421 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): + await client.get(kind=TESTING_CAT, id=cat.id) + with pytest.raises(NodeNotFoundError): + 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): + client_sync.get(kind=TESTING_CAT, id=cat.id) + with pytest.raises(NodeNotFoundError): + 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..926df051f 100644 --- a/tests/unit/sdk/test_group_context.py +++ b/tests/unit/sdk/test_group_context.py @@ -526,3 +526,283 @@ 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 _node_schema( + name: str, relationships: list[dict[str, Any]] | None = None, inherit_from: list[str] | None = None +) -> dict[str, Any]: + 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]: + return {"name": name, "peer": peer, "optional": False, "cardinality": cardinality} + + +def _schemas(*nodes: dict[str, Any]) -> dict[str, NodeSchemaAPI]: + from infrahub_sdk.schema import NodeSchemaAPI # noqa: PLC0415 + + schemas = [NodeSchemaAPI(**node) for node in nodes] + return {schema.kind: schema for schema in schemas} + + +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 = _schemas( + _node_schema("Target"), _node_schema("Dependent", relationships=[_mandatory("target", "ReproTarget")]) + ) + order = query_groups.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 = _schemas( + _node_schema("Address", inherit_from=["ReproEndpoint"]), + _node_schema("Session", relationships=[_mandatory("src", "ReproEndpoint")]), + ) + order = query_groups.DeletionOrder( + candidates=[("ReproAddress", TARGET_ID), ("ReproSession", DEPENDENT_ID)], schemas=schemas + ) + + assert order.order() == [("ReproSession", DEPENDENT_ID), ("ReproAddress", TARGET_ID)] + + +def test_deletion_order_follows_a_chain_of_kinds() -> None: + schemas = _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 query_groups.DeletionOrder(candidates=candidates, schemas=schemas).order() == candidates[::-1] + + +def test_deletion_order_ignores_optional_relationships() -> None: + schemas = _schemas( + _node_schema("Target"), + _node_schema("Dependent", relationships=[{"name": "target", "peer": "ReproTarget", "optional": True}]), + ) + candidates = [("ReproTarget", TARGET_ID), ("ReproDependent", DEPENDENT_ID)] + + assert query_groups.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 = _schemas(_node_schema("Chain", relationships=[_mandatory("previous", "ReproChain")])) + candidates = [("ReproChain", member_id) for member_id in CHAIN_IDS] + order = query_groups.DeletionOrder(candidates=candidates, schemas=schemas) + + assert order.peer_lookups == [ + query_groups.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(member_peers=member_peers) == candidates[::-1] + + +def test_deletion_order_orders_kinds_that_hold_each_other_by_their_peers() -> None: + schemas = _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 = query_groups.DeletionOrder(candidates=candidates, schemas=schemas) + + assert {lookup.kind for lookup in order.peer_lookups} == {"ReproLeft", "ReproRight"} + assert order.order(member_peers={DEPENDENT_ID: {TARGET_ID}}) == candidates[::-1] + + +def test_deletion_order_keeps_group_order_without_peers_for_a_self_referencing_kind() -> None: + schemas = _schemas(_node_schema("Chain", relationships=[_mandatory("previous", "ReproChain")])) + candidates = [("ReproChain", member_id) for member_id in CHAIN_IDS] + + assert query_groups.DeletionOrder(candidates=candidates, schemas=schemas).order() == candidates + + +def test_deletion_order_puts_a_kind_missing_from_the_schema_last() -> None: + schemas = _schemas( + _node_schema("Target"), _node_schema("Dependent", relationships=[_mandatory("target", "ReproTarget")]) + ) + candidates = [("ReproRemoved", CHAIN_IDS[0]), ("ReproTarget", TARGET_ID), ("ReproDependent", DEPENDENT_ID)] + + assert query_groups.DeletionOrder(candidates=candidates, schemas=schemas).order() == [ + ("ReproDependent", DEPENDENT_ID), + ("ReproTarget", TARGET_ID), + ("ReproRemoved", CHAIN_IDS[0]), + ] + + +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) 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_stops_the_reap_and_keeps_every_member( + clients: BothClients, client_type: str, schema_query_05_data: dict, httpx_mock: HTTPXMock +) -> None: + """Without the order nothing is deleted: every member stays in the group and the failure 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") + 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) == 3 + assert _deleted_ids(requests, CHAIN_IDS) == [] + upsert = requests[-1].read().decode() + assert all(member_id in upsert for member_id in CHAIN_IDS) From 694c68775a9e2e5bc6ccbdacb34366f4d772ee7f Mon Sep 17 00:00:00 2001 From: Mikhail Yohman Date: Thu, 5 Nov 2026 13:43:38 -0700 Subject: [PATCH 02/11] test(tracking): cover the remaining deletion order paths Add tests for a mandatory peer that is not being deleted, peers that form a cycle, and reading peers of both cardinalities. Remove a check in DeletionOrder.peer_lookups that could never be false. Co-Authored-By: Claude Opus 5.5 --- infrahub_sdk/query_groups.py | 6 ++-- tests/unit/sdk/test_group_context.py | 50 ++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 3 deletions(-) diff --git a/infrahub_sdk/query_groups.py b/infrahub_sdk/query_groups.py index fe44d301d..d8c4300fe 100644 --- a/infrahub_sdk/query_groups.py +++ b/infrahub_sdk/query_groups.py @@ -249,15 +249,15 @@ def peer_lookups(self) -> list[PeerLookup]: 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 } - if relationships: - ids = [member_id for candidate_kind, member_id in self.candidates if candidate_kind == kind] - lookups.append(PeerLookup(kind=kind, ids=ids, relationships=relationships)) + ids = [member_id for candidate_kind, member_id in self.candidates if candidate_kind == kind] + lookups.append(PeerLookup(kind=kind, ids=ids, relationships=relationships)) return lookups def order(self, member_peers: Mapping[str, set[str]] | None = None) -> list[tuple[str, str]]: diff --git a/tests/unit/sdk/test_group_context.py b/tests/unit/sdk/test_group_context.py index 926df051f..6ac6a0b3d 100644 --- a/tests/unit/sdk/test_group_context.py +++ b/tests/unit/sdk/test_group_context.py @@ -806,3 +806,53 @@ async def test_failed_peer_query_stops_the_reap_and_keeps_every_member( assert _deleted_ids(requests, CHAIN_IDS) == [] upsert = requests[-1].read().decode() assert all(member_id in upsert for member_id in CHAIN_IDS) + + +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 = _schemas( + _node_schema("Target"), + _node_schema("Dependent", relationships=[_mandatory("target", "ReproTarget")]), + ) + candidates = [("ReproDependent", DEPENDENT_ID), ("ReproDependent", CHAIN_IDS[0])] + order = query_groups.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 = _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 = query_groups.DeletionOrder(candidates=candidates, schemas=schemas) + + assert order.order(member_peers=member_peers) == candidates + + +def test_mandatory_peer_ids_reads_both_cardinalities(clients: BothClients) -> None: + from infrahub_sdk.node import InfrahubNode # noqa: PLC0415 + + schema = _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) From 70101e03e3075863edb6ea0321abe380dd75339f Mon Sep 17 00:00:00 2001 From: Mikhail Yohman Date: Mon, 9 Nov 2026 09:13:55 -0700 Subject: [PATCH 03/11] refactor(schema): move the deletion order out of the tracking groups Ordering nodes for deletion depends only on the schema, not on tracking groups. Move DeletionOrder to infrahub_sdk/schema/dependencies.py and its graph helpers to infrahub_sdk/topological_sort.py. query_groups.py keeps only what needs the client: reading the cached schema, the peer queries and stopping the cleanup when the order cannot be worked out. The mandatory relationships now come from mandatory_relationship_names. No behaviour changes. Co-Authored-By: Claude Opus 5.5 --- infrahub_sdk/query_groups.py | 187 +-------------------- infrahub_sdk/schema/dependencies.py | 143 ++++++++++++++++ infrahub_sdk/topological_sort.py | 51 ++++++ tests/helpers/schemas.py | 29 ++++ tests/unit/sdk/test_group_context.py | 159 ++---------------- tests/unit/sdk/test_schema_dependencies.py | 121 +++++++++++++ tests/unit/sdk/test_topological_sort.py | 29 +++- 7 files changed, 386 insertions(+), 333 deletions(-) create mode 100644 infrahub_sdk/schema/dependencies.py create mode 100644 tests/helpers/schemas.py create mode 100644 tests/unit/sdk/test_schema_dependencies.py diff --git a/infrahub_sdk/query_groups.py b/infrahub_sdk/query_groups.py index d8c4300fe..febdce5c8 100644 --- a/infrahub_sdk/query_groups.py +++ b/infrahub_sdk/query_groups.py @@ -14,7 +14,7 @@ URLNotFoundError, code_names_the_failure, ) -from .topological_sort import DependencyCycleExistsError, topological_sort +from .schema.dependencies import DeletionOrder from .utils import dict_hash if TYPE_CHECKING: @@ -121,187 +121,6 @@ def failure(self) -> Exception | None: return None -@dataclass -class PeerLookup: - """The members of one kind whose mandatory peers must be read to order them among themselves. - - Attributes: - kind: The kind of the members. - ids: The ids of the members 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]) -> dict[str, set[str]]: - """The name of each mandatory relationship of `schema`, mapped to the kinds in `schemas` its peer can be. - - A peer that is a generic matches every kind in `schemas` that inherits from it. - """ - peer_kinds: dict[str, set[str]] = {} - for relationship in schema.relationships: - if relationship.optional: - continue - kinds = { - kind - for kind, peer_schema in schemas.items() - if relationship.peer == kind or relationship.peer in getattr(peer_schema, "inherit_from", []) - } - if kinds: - peer_kinds[relationship.name] = kinds - return peer_kinds - - -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 with no dependency between them keep their place in `order`. 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__)] - - -class DeletionOrder: - """Orders the members to delete so that no member 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. Members 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. - - A kind missing from the schema cannot be ordered, so its members 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_schemas = {kind: schemas[kind] for kind in self.kinds} - self.relationships = { - kind: _mandatory_peer_kinds(candidate_schemas[kind], candidate_schemas) for kind in self.kinds - } - self.cardinality_many = { - kind: { - name: candidate_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 members 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 = [member_id for candidate_kind, member_id in self.candidates if candidate_kind == kind] - lookups.append(PeerLookup(kind=kind, ids=ids, relationships=relationships)) - return lookups - - def order(self, member_peers: Mapping[str, set[str]] | None = None) -> list[tuple[str, str]]: - """The candidates in the order to delete them. - - Args: - member_peers: The mandatory peer ids of each member named by `peer_lookups`. - - """ - member_peers = member_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) or [] - 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], member_peers=member_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], member_peers: Mapping[str, set[str]]) -> list[tuple[str, str]]: - block_kinds = set(block) - members = [candidate for candidate in self.candidates if candidate[0] in block_kinds] - if not self._is_cyclic(block): - return members - - member_ids = [member_id for _, member_id in members] - id_set = set(member_ids) - dependencies = { - member_id: (member_peers.get(member_id, set()) & id_set) - {member_id} for member_id in member_ids - } - # A cycle of mandatory relationships between nodes cannot be stored, but keep the - # group order rather than fail if the peers read back describe one. - ordered_ids = _dependents_first(dependencies=dependencies, order=member_ids) - if ordered_ids is None: - return members - kind_of = {member_id: kind for kind, member_id in members} - return [(kind_of[member_id], member_id) for member_id in ordered_ids] - - 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() @@ -477,7 +296,7 @@ async def _order_for_deletion(self, candidates: list[tuple[str, str]]) -> list[t populate_store=False, ) member_peers.update(_member_peers(nodes=nodes, relationships=lookup.relationships)) - return deletion_order.order(member_peers=member_peers) + return deletion_order.order(node_peers=member_peers) async def delete_unused(self) -> ReapResult: """Delete the members that this run no longer uses. @@ -635,7 +454,7 @@ def _order_for_deletion(self, candidates: list[tuple[str, str]]) -> list[tuple[s populate_store=False, ) member_peers.update(_member_peers(nodes=nodes, relationships=lookup.relationships)) - return deletion_order.order(member_peers=member_peers) + return deletion_order.order(node_peers=member_peers) def delete_unused(self) -> ReapResult: """Delete the members that this run no longer uses. diff --git a/infrahub_sdk/schema/dependencies.py b/infrahub_sdk/schema/dependencies.py new file mode 100644 index 000000000..9d7142c0c --- /dev/null +++ b/infrahub_sdk/schema/dependencies.py @@ -0,0 +1,143 @@ +"""Dependencies between kinds through their mandatory relationships. + +The server refuses to delete a node while another node holds it through a mandatory relationship, +and refuses to create a node before the nodes it must hold exist. +""" + +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 + +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]) -> dict[str, set[str]]: + """The name of each mandatory relationship of `schema`, mapped to the kinds in `schemas` its peer can be. + + A peer that is a generic matches every kind in `schemas` that inherits from it. + """ + peer_kinds: dict[str, set[str]] = {} + for name in schema.mandatory_relationship_names: + peer = schema.get_relationship(name).peer + kinds = { + kind + for kind, peer_schema in schemas.items() + if peer == kind or peer in getattr(peer_schema, "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. + + 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_schemas = {kind: schemas[kind] for kind in self.kinds} + self.relationships = { + kind: _mandatory_peer_kinds(candidate_schemas[kind], candidate_schemas) for kind in self.kinds + } + self.cardinality_many = { + kind: { + name: candidate_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`. + + """ + 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) or [] + 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 whose mandatory relationships form a cycle cannot be deleted in any order. Group + # order lets the server refuse them while the other nodes are still deleted. + ordered_ids = dependents_first(dependencies=dependencies, order=node_ids) + if ordered_ids is None: + return nodes + kind_of = {node_id: kind for kind, node_id in nodes} + return [(kind_of[node_id], node_id) for node_id in ordered_ids] diff --git a/infrahub_sdk/topological_sort.py b/infrahub_sdk/topological_sort.py index 58047bd4d..e8b8b9633 100644 --- a/infrahub_sdk/topological_sort.py +++ b/infrahub_sdk/topological_sort.py @@ -67,3 +67,54 @@ 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 with no dependency between them keep their place in `order`. 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..80e83afb4 --- /dev/null +++ b/tests/helpers/schemas.py @@ -0,0 +1,29 @@ +from __future__ import annotations + +from typing import Any + +from infrahub_sdk.schema import 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} diff --git a/tests/unit/sdk/test_group_context.py b/tests/unit/sdk/test_group_context.py index 6ac6a0b3d..4df1d4b60 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 @@ -537,120 +538,6 @@ def test_reap_result_retains_refused_and_unattempted_members() -> None: ] -def _node_schema( - name: str, relationships: list[dict[str, Any]] | None = None, inherit_from: list[str] | None = None -) -> dict[str, Any]: - 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]: - return {"name": name, "peer": peer, "optional": False, "cardinality": cardinality} - - -def _schemas(*nodes: dict[str, Any]) -> dict[str, NodeSchemaAPI]: - from infrahub_sdk.schema import NodeSchemaAPI # noqa: PLC0415 - - schemas = [NodeSchemaAPI(**node) for node in nodes] - return {schema.kind: schema for schema in schemas} - - -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 = _schemas( - _node_schema("Target"), _node_schema("Dependent", relationships=[_mandatory("target", "ReproTarget")]) - ) - order = query_groups.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 = _schemas( - _node_schema("Address", inherit_from=["ReproEndpoint"]), - _node_schema("Session", relationships=[_mandatory("src", "ReproEndpoint")]), - ) - order = query_groups.DeletionOrder( - candidates=[("ReproAddress", TARGET_ID), ("ReproSession", DEPENDENT_ID)], schemas=schemas - ) - - assert order.order() == [("ReproSession", DEPENDENT_ID), ("ReproAddress", TARGET_ID)] - - -def test_deletion_order_follows_a_chain_of_kinds() -> None: - schemas = _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 query_groups.DeletionOrder(candidates=candidates, schemas=schemas).order() == candidates[::-1] - - -def test_deletion_order_ignores_optional_relationships() -> None: - schemas = _schemas( - _node_schema("Target"), - _node_schema("Dependent", relationships=[{"name": "target", "peer": "ReproTarget", "optional": True}]), - ) - candidates = [("ReproTarget", TARGET_ID), ("ReproDependent", DEPENDENT_ID)] - - assert query_groups.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 = _schemas(_node_schema("Chain", relationships=[_mandatory("previous", "ReproChain")])) - candidates = [("ReproChain", member_id) for member_id in CHAIN_IDS] - order = query_groups.DeletionOrder(candidates=candidates, schemas=schemas) - - assert order.peer_lookups == [ - query_groups.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(member_peers=member_peers) == candidates[::-1] - - -def test_deletion_order_orders_kinds_that_hold_each_other_by_their_peers() -> None: - schemas = _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 = query_groups.DeletionOrder(candidates=candidates, schemas=schemas) - - assert {lookup.kind for lookup in order.peer_lookups} == {"ReproLeft", "ReproRight"} - assert order.order(member_peers={DEPENDENT_ID: {TARGET_ID}}) == candidates[::-1] - - -def test_deletion_order_keeps_group_order_without_peers_for_a_self_referencing_kind() -> None: - schemas = _schemas(_node_schema("Chain", relationships=[_mandatory("previous", "ReproChain")])) - candidates = [("ReproChain", member_id) for member_id in CHAIN_IDS] - - assert query_groups.DeletionOrder(candidates=candidates, schemas=schemas).order() == candidates - - -def test_deletion_order_puts_a_kind_missing_from_the_schema_last() -> None: - schemas = _schemas( - _node_schema("Target"), _node_schema("Dependent", relationships=[_mandatory("target", "ReproTarget")]) - ) - candidates = [("ReproRemoved", CHAIN_IDS[0]), ("ReproTarget", TARGET_ID), ("ReproDependent", DEPENDENT_ID)] - - assert query_groups.DeletionOrder(candidates=candidates, schemas=schemas).order() == [ - ("ReproDependent", DEPENDENT_ID), - ("ReproTarget", TARGET_ID), - ("ReproRemoved", CHAIN_IDS[0]), - ] - - def _schema_with(base: dict, *nodes: dict[str, Any]) -> dict: return {**base, "nodes": [*base["nodes"], *nodes]} @@ -688,8 +575,8 @@ async def test_reap_deletes_the_holder_before_the_node_it_holds( """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")]), + node_schema("Target"), + node_schema("Dependent", relationships=[mandatory("target", "ReproTarget")]), ) httpx_mock.add_response( method="POST", @@ -713,7 +600,7 @@ async def test_reap_reads_peers_to_order_members_of_a_self_referencing_kind( ) -> 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")]) + 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 = { @@ -767,7 +654,7 @@ 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")) + 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)]) ) @@ -791,7 +678,7 @@ async def test_failed_peer_query_stops_the_reap_and_keeps_every_member( ) -> None: """Without the order nothing is deleted: every member stays in the group and the failure is raised.""" schema = _schema_with( - schema_query_05_data, _node_schema("Chain", relationships=[_mandatory("previous", "ReproChain")]) + 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)) @@ -808,40 +695,16 @@ async def test_failed_peer_query_stops_the_reap_and_keeps_every_member( assert all(member_id in upsert for member_id in CHAIN_IDS) -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 = _schemas( - _node_schema("Target"), - _node_schema("Dependent", relationships=[_mandatory("target", "ReproTarget")]), - ) - candidates = [("ReproDependent", DEPENDENT_ID), ("ReproDependent", CHAIN_IDS[0])] - order = query_groups.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 = _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 = query_groups.DeletionOrder(candidates=candidates, schemas=schemas) - - assert order.order(member_peers=member_peers) == candidates - - def test_mandatory_peer_ids_reads_both_cardinalities(clients: BothClients) -> None: from infrahub_sdk.node import InfrahubNode # noqa: PLC0415 - schema = _schemas( - _node_schema( + schema = node_schemas( + node_schema( "Left", relationships=[ - _mandatory("rights", "ReproRight", cardinality="many"), - _mandatory("anchor", "ReproRight"), - _mandatory("spare", "ReproRight"), + mandatory("rights", "ReproRight", cardinality="many"), + mandatory("anchor", "ReproRight"), + mandatory("spare", "ReproRight"), ], ) )["ReproLeft"] diff --git a/tests/unit/sdk/test_schema_dependencies.py b/tests/unit/sdk/test_schema_dependencies.py new file mode 100644 index 000000000..e19b42f53 --- /dev/null +++ b/tests/unit/sdk/test_schema_dependencies.py @@ -0,0 +1,121 @@ +from __future__ import annotations + +from infrahub_sdk.schema.dependencies import DeletionOrder, PeerLookup +from tests.helpers.schemas import 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_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 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 From a30a4a6459aa59c9293c040f3c3bed689ec1e28a Mon Sep 17 00:00:00 2001 From: Mikhail Yohman Date: Wed, 25 Nov 2026 08:47:57 -0700 Subject: [PATCH 04/11] fix(schema): order nodes around a cycle instead of falling back for the whole kind When two nodes held each other, every node of the cyclic block went back to group order, so nodes outside the cycle could be refused as well. Group the nodes into strongly connected components, order the components dependents first and keep group order only inside each component. Co-Authored-By: Claude Opus 5.5 --- infrahub_sdk/schema/dependencies.py | 21 +++++++++++++++------ tests/unit/sdk/test_schema_dependencies.py | 12 ++++++++++++ 2 files changed, 27 insertions(+), 6 deletions(-) diff --git a/infrahub_sdk/schema/dependencies.py b/infrahub_sdk/schema/dependencies.py index 9d7142c0c..4807a5f92 100644 --- a/infrahub_sdk/schema/dependencies.py +++ b/infrahub_sdk/schema/dependencies.py @@ -134,10 +134,19 @@ def _order_block(self, block: list[str], node_peers: Mapping[str, set[str]]) -> 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 whose mandatory relationships form a cycle cannot be deleted in any order. Group - # order lets the server refuse them while the other nodes are still deleted. - ordered_ids = dependents_first(dependencies=dependencies, order=node_ids) - if ordered_ids is None: - return nodes + # 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 node_id in ordered_ids] + return [(kind_of[node_id], node_id) for key in component_order for node_id in members[key]] diff --git a/tests/unit/sdk/test_schema_dependencies.py b/tests/unit/sdk/test_schema_dependencies.py index e19b42f53..55214f486 100644 --- a/tests/unit/sdk/test_schema_dependencies.py +++ b/tests/unit/sdk/test_schema_dependencies.py @@ -119,3 +119,15 @@ def test_deletion_order_keeps_group_order_when_the_peers_form_a_cycle() -> None: 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)] From 6476cd57bbe2230391f8587ab713502dac45cad0 Mon Sep 17 00:00:00 2001 From: Mikhail Yohman Date: Wed, 25 Nov 2026 08:52:04 -0700 Subject: [PATCH 05/11] fix(schema): match generic peers through used_by, including CoreNode A mandatory relationship to a generic only matched kinds that named the generic in inherit_from. Nodes never name CoreNode there, so a relationship to CoreNode added no dependency and the holder could be deleted after the node it holds. The peer is now resolved against the full schema map: a generic matches the candidate kinds in its used_by, with inherit_from kept for a generic missing from the map. Co-Authored-By: Claude Opus 5.5 --- infrahub_sdk/schema/dependencies.py | 34 +++++++++++++--------- tests/helpers/schemas.py | 7 ++++- tests/unit/sdk/test_schema_dependencies.py | 18 +++++++++++- 3 files changed, 43 insertions(+), 16 deletions(-) diff --git a/infrahub_sdk/schema/dependencies.py b/infrahub_sdk/schema/dependencies.py index 4807a5f92..86b609055 100644 --- a/infrahub_sdk/schema/dependencies.py +++ b/infrahub_sdk/schema/dependencies.py @@ -11,6 +11,7 @@ from typing import TYPE_CHECKING from ..topological_sort import dependents_first, strongly_connected_components +from .main import GenericSchemaAPI if TYPE_CHECKING: from . import MainSchemaTypesAPI @@ -32,19 +33,23 @@ class PeerLookup: relationships: dict[str, bool] -def _mandatory_peer_kinds(schema: MainSchemaTypesAPI, schemas: Mapping[str, MainSchemaTypesAPI]) -> dict[str, set[str]]: - """The name of each mandatory relationship of `schema`, mapped to the kinds in `schemas` its peer can be. +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 matches every kind in `schemas` that inherits from it. + 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 = { - kind - for kind, peer_schema in schemas.items() - if peer == kind or peer in getattr(peer_schema, "inherit_from", []) - } + 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 @@ -58,6 +63,9 @@ class DeletionOrder: 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. """ @@ -67,15 +75,13 @@ def __init__(self, candidates: list[tuple[str, str]], schemas: Mapping[str, Main 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_schemas = {kind: schemas[kind] for kind in self.kinds} + candidate_kinds = set(self.kinds) self.relationships = { - kind: _mandatory_peer_kinds(candidate_schemas[kind], candidate_schemas) for kind in self.kinds + kind: _mandatory_peer_kinds(schema=schemas[kind], schemas=schemas, candidate_kinds=candidate_kinds) + for kind in self.kinds } self.cardinality_many = { - kind: { - name: candidate_schemas[kind].get_relationship(name).cardinality_is_many - for name in self.relationships[kind] - } + 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} diff --git a/tests/helpers/schemas.py b/tests/helpers/schemas.py index 80e83afb4..4de66d6b2 100644 --- a/tests/helpers/schemas.py +++ b/tests/helpers/schemas.py @@ -2,7 +2,7 @@ from typing import Any -from infrahub_sdk.schema import NodeSchemaAPI +from infrahub_sdk.schema import GenericSchemaAPI, NodeSchemaAPI def node_schema( @@ -27,3 +27,8 @@ 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/unit/sdk/test_schema_dependencies.py b/tests/unit/sdk/test_schema_dependencies.py index 55214f486..8a5f91184 100644 --- a/tests/unit/sdk/test_schema_dependencies.py +++ b/tests/unit/sdk/test_schema_dependencies.py @@ -1,7 +1,7 @@ from __future__ import annotations from infrahub_sdk.schema.dependencies import DeletionOrder, PeerLookup -from tests.helpers.schemas import mandatory, node_schema, node_schemas +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" @@ -33,6 +33,22 @@ def test_deletion_order_resolves_a_generic_peer_to_the_kinds_inheriting_it() -> 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"), From 5f0a4f65d1da53a117207c71f8e6fc8021ea6247 Mon Sep 17 00:00:00 2001 From: Mikhail Yohman Date: Wed, 25 Nov 2026 08:56:17 -0700 Subject: [PATCH 06/11] fix(tracking): delete in group order when the deletion order cannot be worked out When the deletion order fails, the members that nothing holds are still deleted, in group order. The ordering failure is kept in ReapResult.ordering_error and raised after the group is written, unless an error stopped the reap, which is raised instead. Co-Authored-By: Claude Opus 5.5 --- infrahub_sdk/query_groups.py | 37 +++++++++++-------- tests/unit/sdk/test_group_context.py | 55 +++++++++++++++++++++++++--- 2 files changed, 72 insertions(+), 20 deletions(-) diff --git a/infrahub_sdk/query_groups.py b/infrahub_sdk/query_groups.py index febdce5c8..8e0d643d0 100644 --- a/infrahub_sdk/query_groups.py +++ b/infrahub_sdk/query_groups.py @@ -100,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]: @@ -113,9 +116,15 @@ 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 @@ -303,7 +312,8 @@ async def delete_unused(self) -> ReapResult: 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, nothing is deleted and the failure stops the reap. + 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 @@ -322,10 +332,7 @@ async def delete_unused(self) -> ReapResult: try: candidates = await self._order_for_deletion(candidates) except Exception as exc: - # Deleting unordered would only trade this failure for refusals; nothing was deleted yet. - result.error = exc - result.unattempted = [member_id for _, member_id in candidates] - return result + result.ordering_error = exc for position, (kind, member_id) in enumerate(candidates): try: @@ -401,10 +408,11 @@ 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: + reap_error = reap.error if reap.error is not None else reap.ordering_error + if reap_error is None: raise # The write usually fails for the reason the reap stopped; report that reason. - raise reap.error from exc + raise reap_error from exc if (failure := reap.failure()) is not None: raise failure @@ -461,7 +469,8 @@ def delete_unused(self) -> ReapResult: 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, nothing is deleted and the failure stops the reap. + 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 @@ -480,10 +489,7 @@ def delete_unused(self) -> ReapResult: try: candidates = self._order_for_deletion(candidates) except Exception as exc: - # Deleting unordered would only trade this failure for refusals; nothing was deleted yet. - result.error = exc - result.unattempted = [member_id for _, member_id in candidates] - return result + result.ordering_error = exc for position, (kind, member_id) in enumerate(candidates): try: @@ -559,10 +565,11 @@ def update_group(self) -> None: ) group.save(allow_upsert=True, update_group_context=False) except Exception as exc: - if reap.error is None: + reap_error = reap.error if reap.error is not None else reap.ordering_error + if reap_error is None: raise # The write usually fails for the reason the reap stopped; report that reason. - raise reap.error from exc + raise reap_error from exc if (failure := reap.failure()) is not None: raise failure diff --git a/tests/unit/sdk/test_group_context.py b/tests/unit/sdk/test_group_context.py index 4df1d4b60..93a089cb5 100644 --- a/tests/unit/sdk/test_group_context.py +++ b/tests/unit/sdk/test_group_context.py @@ -523,6 +523,17 @@ 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"] @@ -673,26 +684,60 @@ async def test_member_held_from_outside_the_group_is_kept_and_reported( @pytest.mark.parametrize("client_type", client_types) -async def test_failed_peer_query_stops_the_reap_and_keeps_every_member( +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 nothing is deleted: every member stays in the group and the failure is raised.""" + """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) == 3 - assert _deleted_ids(requests, CHAIN_IDS) == [] + 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_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 all(member_id in upsert for member_id in CHAIN_IDS) + 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 594f15b8fe0dbb66a61404a9fd1f06898f43d3b5 Mon Sep 17 00:00:00 2001 From: Mikhail Yohman Date: Wed, 25 Nov 2026 09:01:50 -0700 Subject: [PATCH 07/11] test(tracking): run cardinality-many peer queries through both clients Two kinds that hold each other through mandatory cardinality-many relationships are ordered from the answers to the peer queries built from `only`, on the async and sync clients. The test checks that the holders are deleted first and that no ordering failure is raised. Co-Authored-By: Claude Opus 5.5 --- tests/unit/sdk/test_group_context.py | 89 ++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) diff --git a/tests/unit/sdk/test_group_context.py b/tests/unit/sdk/test_group_context.py index 93a089cb5..c544c286c 100644 --- a/tests/unit/sdk/test_group_context.py +++ b/tests/unit/sdk/test_group_context.py @@ -764,3 +764,92 @@ def test_mandatory_peer_ids_reads_both_cardinalities(clients: BothClients) -> No ) 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() From b3178aa5b2cee8a1c01d3dd56687babdc931cb4e Mon Sep 17 00:00:00 2001 From: Mikhail Yohman Date: Wed, 25 Nov 2026 09:06:53 -0700 Subject: [PATCH 08/11] fix(schema): raise instead of dropping members when the kind order is missing DeletionOrder.order() replaced a missing order of the kinds with an empty list, which left every candidate of a known kind out of the order without an error. It now raises, so the cleanup deletes in group order and reports the failure instead. Co-Authored-By: Claude Opus 5.5 --- infrahub_sdk/schema/dependencies.py | 7 ++++++- tests/unit/sdk/test_schema_dependencies.py | 15 +++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/infrahub_sdk/schema/dependencies.py b/infrahub_sdk/schema/dependencies.py index 86b609055..8cc808773 100644 --- a/infrahub_sdk/schema/dependencies.py +++ b/infrahub_sdk/schema/dependencies.py @@ -115,6 +115,9 @@ def order(self, node_peers: Mapping[str, set[str]] | None = None) -> list[tuple[ 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} @@ -122,7 +125,9 @@ def order(self, node_peers: Mapping[str, set[str]] | None = None) -> list[tuple[ 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) or [] + 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]] = [] diff --git a/tests/unit/sdk/test_schema_dependencies.py b/tests/unit/sdk/test_schema_dependencies.py index 8a5f91184..7782c354e 100644 --- a/tests/unit/sdk/test_schema_dependencies.py +++ b/tests/unit/sdk/test_schema_dependencies.py @@ -1,5 +1,8 @@ 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 @@ -147,3 +150,15 @@ def test_deletion_order_orders_the_other_nodes_around_a_cycle() -> None: 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() From d87b5a8c3a14105eca3f93fe9973a0a2ce0edad0 Mon Sep 17 00:00:00 2001 From: Mikhail Yohman Date: Tue, 1 Dec 2026 09:11:32 -0700 Subject: [PATCH 09/11] fix(tracking): refresh the schema once when a member's kind is not cached The deletion order is built from the cached branch schema. A kind loaded after the cache was filled, or left out of a cache filled for some namespaces only, was treated as unknown and deleted last, even when it holds other members. Refresh the schema once in that case. No request is sent when every kind is cached. Co-Authored-By: Claude Opus 5.5 --- infrahub_sdk/query_groups.py | 12 +++++-- tests/unit/sdk/test_group_context.py | 53 ++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+), 2 deletions(-) diff --git a/infrahub_sdk/query_groups.py b/infrahub_sdk/query_groups.py index 8e0d643d0..e9d52a919 100644 --- a/infrahub_sdk/query_groups.py +++ b/infrahub_sdk/query_groups.py @@ -290,11 +290,15 @@ async def _order_for_deletion(self, candidates: list[tuple[str, str]]) -> list[t """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. + 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( @@ -447,11 +451,15 @@ def _order_for_deletion(self, candidates: list[tuple[str, str]]) -> list[tuple[s """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. + 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( diff --git a/tests/unit/sdk/test_group_context.py b/tests/unit/sdk/test_group_context.py index c544c286c..28d168978 100644 --- a/tests/unit/sdk/test_group_context.py +++ b/tests/unit/sdk/test_group_context.py @@ -853,3 +853,56 @@ async def test_reap_reads_cardinality_many_peers_to_order_kinds_that_hold_each_o 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() == [] From e09c69d7c2a022d962798760ca8a5671f2751024 Mon Sep 17 00:00:00 2001 From: Mikhail Yohman Date: Tue, 1 Dec 2026 09:16:19 -0700 Subject: [PATCH 10/11] chore(review): pass match= to pytest.raises and correct two docstrings dependents_first groups keys by the length of the dependency chain below them, so unrelated keys do not always keep their place in `order`. The schema dependencies module describes deletion order only. Co-Authored-By: Claude Opus 5.5 --- infrahub_sdk/schema/dependencies.py | 4 ++-- infrahub_sdk/topological_sort.py | 4 +++- tests/integration/test_tracking_zero_members.py | 8 ++++---- tests/unit/sdk/test_group_context.py | 2 +- 4 files changed, 10 insertions(+), 8 deletions(-) diff --git a/infrahub_sdk/schema/dependencies.py b/infrahub_sdk/schema/dependencies.py index 8cc808773..3c6c6d553 100644 --- a/infrahub_sdk/schema/dependencies.py +++ b/infrahub_sdk/schema/dependencies.py @@ -1,7 +1,7 @@ -"""Dependencies between kinds through their mandatory relationships. +"""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, -and refuses to create a node before the nodes it must hold exist. +so the node that holds it is deleted first. """ from __future__ import annotations diff --git a/infrahub_sdk/topological_sort.py b/infrahub_sdk/topological_sort.py index e8b8b9633..ab12ac259 100644 --- a/infrahub_sdk/topological_sort.py +++ b/infrahub_sdk/topological_sort.py @@ -110,7 +110,9 @@ def visit(key: str) -> None: 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 with no dependency between them keep their place in `order`. Returns None on a cycle. + 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: diff --git a/tests/integration/test_tracking_zero_members.py b/tests/integration/test_tracking_zero_members.py index 21ce65421..83ed8859c 100644 --- a/tests/integration/test_tracking_zero_members.py +++ b/tests/integration/test_tracking_zero_members.py @@ -219,9 +219,9 @@ async def test_unused_owner_and_animal_are_deleted_in_one_run( group = await client.get(kind="CoreStandardGroup", name__value=group_name, include=["members"]) assert len(group.members.peers) == 0 - with pytest.raises(NodeNotFoundError): + with pytest.raises(NodeNotFoundError, match=cat.id): await client.get(kind=TESTING_CAT, id=cat.id) - with pytest.raises(NodeNotFoundError): + with pytest.raises(NodeNotFoundError, match=person.id): await client.get(kind=TESTING_PERSON, id=person.id) @@ -416,7 +416,7 @@ def test_unused_owner_and_animal_are_deleted_in_one_run( group = client_sync.get(kind="CoreStandardGroup", name__value=group_name, include=["members"]) assert len(group.members.peers) == 0 - with pytest.raises(NodeNotFoundError): + with pytest.raises(NodeNotFoundError, match=cat.id): client_sync.get(kind=TESTING_CAT, id=cat.id) - with pytest.raises(NodeNotFoundError): + 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 28d168978..e7538f6df 100644 --- a/tests/unit/sdk/test_group_context.py +++ b/tests/unit/sdk/test_group_context.py @@ -676,7 +676,7 @@ async def test_member_held_from_outside_the_group_is_kept_and_reported( ) httpx_mock.add_response(method="POST", url="http://mock/graphql/main", json=UPSERT_RESPONSE) - with pytest.raises(TrackingGroupCleanupError) as exc_info: + 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] From 516d0a7feae9dd8cd7d35dce57fd23c511d316da Mon Sep 17 00:00:00 2001 From: Mikhail Yohman Date: Tue, 1 Dec 2026 09:20:13 -0700 Subject: [PATCH 11/11] fix(tracking): raise the group write error when only the ordering failed An ordering failure does not stop the deletes, so when the group write then fails it failed for its own reason. Raise the write error, with the ordering failure as its cause, instead of the ordering failure. An error that stopped the deletes is still raised in place of the write error. Co-Authored-By: Claude Opus 5.5 --- infrahub_sdk/query_groups.py | 24 ++++++++++++++---------- tests/unit/sdk/test_group_context.py | 21 +++++++++++++++++++++ 2 files changed, 35 insertions(+), 10 deletions(-) diff --git a/infrahub_sdk/query_groups.py b/infrahub_sdk/query_groups.py index e9d52a919..395c88040 100644 --- a/infrahub_sdk/query_groups.py +++ b/infrahub_sdk/query_groups.py @@ -412,11 +412,13 @@ async def update_group(self) -> None: ) await group.save(allow_upsert=True, update_group_context=False) except Exception as exc: - reap_error = reap.error if reap.error is not None else reap.ordering_error - 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 @@ -573,11 +575,13 @@ def update_group(self) -> None: ) group.save(allow_upsert=True, update_group_context=False) except Exception as exc: - reap_error = reap.error if reap.error is not None else reap.ordering_error - 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/tests/unit/sdk/test_group_context.py b/tests/unit/sdk/test_group_context.py index e7538f6df..5001a0f04 100644 --- a/tests/unit/sdk/test_group_context.py +++ b/tests/unit/sdk/test_group_context.py @@ -709,6 +709,27 @@ async def test_failed_peer_query_deletes_in_group_order_and_raises_after_the_gro 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