Repository navigation
fix(tracking): delete unused members before the nodes they hold - #1487
FragmentedPacket wants to merge 11 commits into
Conversation
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 <noreply@anthropic.com>
Codecov Report❌ Patch coverage is
@@ Coverage Diff @@
## infrahub-release-1.12 #1487 +/- ##
=========================================================
+ Coverage 87.74% 87.97% +0.22%
=========================================================
Files 155 158 +3
Lines 15539 15819 +280
Branches 2091 2143 +52
=========================================================
+ Hits 13635 13916 +281
+ Misses 1344 1341 -3
- Partials 560 562 +2
Flags with carried forward coverage won't be shown. Click here to find out more.
... and 2 files with indirect coverage changes 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
2 issues found across 4 files
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="infrahub_sdk/query_groups.py">
<violation number="1" location="infrahub_sdk/query_groups.py:282">
P2: `order()` places members whose kinds are missing from the schema last even though their dependency direction is unknown. Treat any unknown kind as an ordering failure before issuing deletes so the reap keeps all candidates.</violation>
<violation number="2" location="infrahub_sdk/query_groups.py:299">
P2: When the peer graph within a kind is cyclic, `_order_block` falls back to group order and deletes anyway. The PR contract says undeterminable ordering should delete nothing and raise. Raise an error here instead, so `delete_unused` records it and stops the reap.</violation>
</file>
Reply with feedback, questions, or to request a fix.
View guided diff | Turn on auto-fix | Re-trigger cubic
| if ordered_ids is None: | ||
| return members |
There was a problem hiding this comment.
P2: When the peer graph within a kind is cyclic, _order_block falls back to group order and deletes anyway. The PR contract says undeterminable ordering should delete nothing and raise. Raise an error here instead, so delete_unused records it and stops the reap.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At infrahub_sdk/query_groups.py, line 299:
<comment>When the peer graph within a kind is cyclic, `_order_block` falls back to group order and deletes anyway. The PR contract says undeterminable ordering should delete nothing and raise. Raise an error here instead, so `delete_unused` records it and stops the reap.</comment>
<file context>
@@ -120,6 +121,207 @@ def failure(self) -> Exception | None:
+ # 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}
</file context>
| if ordered_ids is None: | |
| return members | |
| if ordered_ids is None: | |
| raise DependencyCycleExistsError("Mandatory peers of unused members form a cycle; cannot order deletion") |
There was a problem hiding this comment.
Not changing this to raise. Raising when the peers form a cycle would stop every delete in the run, including members outside the cycle. Since a30a4a6 the nodes are grouped into strongly connected components: only the nodes inside a cycle keep group order, the server refuses those, they stay in the group and are reported, and the other nodes are still deleted in dependency order.
| 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) |
There was a problem hiding this comment.
P2: order() places members whose kinds are missing from the schema last even though their dependency direction is unknown. Treat any unknown kind as an ordering failure before issuing deletes so the reap keeps all candidates.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At infrahub_sdk/query_groups.py, line 282:
<comment>`order()` places members whose kinds are missing from the schema last even though their dependency direction is unknown. Treat any unknown kind as an ordering failure before issuing deletes so the reap keeps all candidates.</comment>
<file context>
@@ -120,6 +121,207 @@ def failure(self) -> Exception | None:
+ 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
+
</file context>
| ordered.extend(candidate for candidate in self.candidates if candidate[0] in self.unknown_kinds) | |
| if self.unknown_kinds: | |
| raise ValueError(f"Unable to order members with unknown kinds: {sorted(self.unknown_kinds)}") |
There was a problem hiding this comment.
Not changing this to raise. A member whose kind is missing from the schema cannot be deleted at all, so it holds its peers whatever the order; deleting it last costs nothing, and its refused delete is recorded and the member stays in the group. Raising would block every other delete in the run. Since d87b5a8 the schema is refreshed once when a kind is missing from the cache, so only kinds the server does not know remain unknown.
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 <noreply@anthropic.com>
Deploying infrahub-sdk-python with
|
| Latest commit: |
516d0a7
|
| Status: | ✅ Deploy successful! |
| Preview URL: | https://908db241.infrahub-sdk-python.pages.dev |
| Branch Preview URL: | https://ai-bug-pipeline-1477-trackin.infrahub-sdk-python.pages.dev |
ogenstad
left a comment
There was a problem hiding this comment.
I think this looks good overall, however it feels like there's too much happening in infrahub_sdk/query_groups.py. To me that file is now doing things that are related to schema operations. The problem you are solving aren't strictly related to query groups, it might be that even end users would want to know how to correctly delete a bunch of nodes and as such I think that the parts that doesn't strictly relate to members could be part of the schema files instead?
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 <noreply@anthropic.com>
|
Thanks, agreed: the ordering has nothing to do with groups. I split it by what each part depends on (70101e0):
No behaviour changed. The I kept |
ogenstad
left a comment
There was a problem hiding this comment.
This review was written by an AI (Claude Code) under the guidance of a human reviewer, who chose the findings and approved the text.
Four comments are blockers: the ordering in a cyclic block, CoreNode peers, the cleanup that stops when the order cannot be worked out, and the missing test for cardinality-many peer queries. The other inline comments are small fixes.
Follow-ups that can be separate pull requests:
- The ordering code that uses the client (
_order_for_deletionin both clients,_mandatory_peer_idsand_member_peersat query_groups.py:124-141) still lives in the group context. A futureclient.delete_nodes()would have to copy it or import private helpers. One method per client that reads the schema, queries peers and returns the order would letdelete_unusedand later callers share it. - The peer query at query_groups.py:291 sends every id with every page request. With 5,000 members and the default page size of 50, that is 101 requests of about 190 KB each. Splitting the ids into chunks the size of a page, or setting
limit=len(ids), avoids this. The async client also sends the query for each kind one after another. dependents_firstandstrongly_connected_componentsraiseKeyErrorwhen a dependency is not a key:dependents_first({"a": {"b"}}, order=["a"]).topological_sortaccepts such keys. This needs fixing before the helpers are reused for import ordering.dependents_firstrunstopological_sort, which first runs a recursive cycle search and discards the result, and then scans every remaining key at each level. A chain of 10,000 nodes costs about 10^8 set operations, and a long chain that contains a cycle can reach Python's recursion limit._mandatory_peer_kindsbuilds the same graph asInfrahubSchemaTopologicalSorter.get_sorted_node_schema(required_relationships_only=True)in transfer/schema_sorter.py, but handles generic peers differently, so a fix to one does not reach the other.DeletionOrder.cardinality_manyand thedict[str, bool]form ofPeerLookup.relationshipsexist only so_mandatory_peer_idscan choose an accessor. The node already carries its schema, sorelationshipscould be alist[str].
| ordered_ids = dependents_first(dependencies=dependencies, order=node_ids) | ||
| if ordered_ids is None: | ||
| return nodes |
There was a problem hiding this comment.
When any two nodes in a cyclic block hold each other, every node in the block goes back to group order, not only the two in the cycle. The comment above says the other nodes are still deleted, but they can be refused too.
Example: kind ReproChain with a mandatory previous to itself. In group order the candidates are a, b, c, x, y. c holds b, b holds a, and x and y hold each other. order() returns [a, b, c, x, y]. The server refuses a and b, deletes c, and refuses x and y, so a and b need another run.
Ordering the strongly connected components of the node graph fixes this: dependents first between components, group order inside a cyclic component. That gives c, b, a, x, y, so only x and y are refused. strongly_connected_components already exists.
Written by an AI under the guidance of a human reviewer.
There was a problem hiding this comment.
Valid point — any cycle in the node graph sent every node of the block back to group order, so nodes outside the cycle could be refused too. Now the nodes are grouped into strongly connected components, the components are ordered dependents first, and only the nodes inside a cycle keep group order, in a30a4a6. Your example (c→b→a, x↔y) is covered by test_deletion_order_orders_the_other_nodes_around_a_cycle and gives c, b, a, x, y.
| kinds = { | ||
| kind | ||
| for kind, peer_schema in schemas.items() | ||
| if peer == kind or peer in getattr(peer_schema, "inherit_from", []) |
There was a problem hiding this comment.
A generic peer is only matched through inherit_from, which never names the implicit CoreNode generic. So a mandatory relationship to CoreNode, the same shape as CoreGeneratorInstance.object, adds no dependency.
Example: ReproNote with a mandatory object to CoreNode, and candidates [(ReproThing, t), (ReproNote, n)]. order() puts t first, the server refuses it because n holds it, and the run raises TrackingGroupCleanupError. In the schema_05 fixture the node kinds have inherit_from: [], while CoreNode.used_by lists them.
GenericSchemaAPI.used_by is the full list of kinds that implement a generic and could replace the inherit_from check.
Written by an AI under the guidance of a human reviewer.
There was a problem hiding this comment.
Valid point — the generic check only looked at inherit_from, and the schemas were cut down to the candidate kinds before the peer was resolved, so a mandatory relationship to CoreNode added no dependency. Now the peer is 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, in 6476cd5. Added test_deletion_order_resolves_a_generic_peer_through_its_used_by with your ReproNote to CoreNode case. ReproNote is itself in CoreNode.used_by, so it now gets a peer lookup and is deleted before ReproThing.
| candidates = self._reap_candidates() | ||
| try: | ||
| candidates = await self._order_for_deletion(candidates) | ||
| except Exception as exc: |
There was a problem hiding this comment.
The comment at line 325 says that deleting unordered "would only trade this failure for refusals". That is true for members that something holds, but not for members that nothing holds. Those are deleted in any order, and before this change they were deleted.
If the order fails the same way on every run, for example a peer query that a proxy rejects, a FieldNotLoadedError or a RecursionError, then no member of that group is ever deleted again, including unrelated BuiltinTag members.
Could this fall back to group order when ordering fails, and still return the error, so that members nothing holds are deleted? The same applies to the sync client at line 482.
Written by an AI under the guidance of a human reviewer.
There was a problem hiding this comment.
Valid point — falling back to nothing deleted meant a failure that repeats on every run blocked every member of the group, including members that nothing holds. Now, in both clients, when the order cannot be worked out the members are deleted in group order: refusals stay in the group, and the ordering error is kept in ReapResult.ordering_error and raised after the group is written. An error that stops the delete loop is still raised first. In 5f0a4f6. Tests: test_failed_peer_query_deletes_in_group_order_and_raises_after_the_group_write (reworked), test_failed_peer_query_keeps_the_refused_member_and_raises_the_ordering_failure and test_reap_result_failure_prefers_the_stopping_error_then_the_ordering_error.
| assert all(member_id in upsert for member_id in CHAIN_IDS) | ||
|
|
||
|
|
||
| def test_mandatory_peer_ids_reads_both_cardinalities(clients: BothClients) -> None: |
There was a problem hiding this comment.
No test sends a peer query for a cardinality-many relationship through filters(only=...), and none uses a sync node. This test builds an async node from inline data, which skips the only marker that makes peer_ids raise FieldNotLoadedError.
Kinds that hold each other through cardinality-many relationships (the Left/Right case) are only tested in DeletionOrder, with peers supplied by hand. If the query built from only did not fill a cardinality-many relationship, peer_ids would raise on every run, and with the behaviour at query_groups.py:324 the cleanup would stop on every run.
Could a test run the Left/Right case through _order_for_deletion with a mocked filters response, for both clients?
Written by an AI under the guidance of a human reviewer.
There was a problem hiding this comment.
Valid point. No test sent a peer query for a cardinality-many relationship through filters(only=...), and none ran it on the sync client. Added test_reap_reads_cardinality_many_peers_to_order_kinds_that_hold_each_other in 594f15b, for both clients. ReproLeft.rights and ReproRight.lefts are mandatory cardinality-many relationships, so the two kinds form a cycle and the cleanup sends one peer query per kind. The mocked answers use the shape the generated query asks for (rights { edges { node { id hfid display_label __typename } } }). The members are in a group order the server would refuse, and the test checks that:
- the delete mutations are sent holders first (left 1, right, left 2)
- the group write is sent
- no error is raised, so no ordering failure was recorded
The only query fills the cardinality-many relationship on both clients, so the production code did not need a change. When the mocked peers are removed, the test fails on both clients because the deletes fall back to group order.
| """ | ||
| if len(candidates) < 2: | ||
| return candidates | ||
| deletion_order = DeletionOrder(candidates=candidates, schemas=await self.client.schema.all(branch=self.branch)) |
There was a problem hiding this comment.
schema.all() returns the cached branch schema without refreshing it. A kind loaded after the cache was filled, or left out because the cache was filled with namespaces=[...], is treated as unknown and deleted last, even when it holds other members. client.delete() later refreshes the cache through schema.get(), so the delete itself succeeds.
Refreshing once with refresh=True when deletion_order.unknown_kinds is not empty would avoid this. The same applies to the sync client at line 446.
Written by an AI under the guidance of a human reviewer.
There was a problem hiding this comment.
Valid point. Now _order_for_deletion() refreshes the schema once, with refresh=True, when DeletionOrder.unknown_kinds is not empty, and rebuilds the order, in both clients, in d87b5a8. No schema request is sent when every kind is cached.
On the cleanup path today, get_group(include=["members"]) already builds each member through schema.get(), which fetches the branch schema when a kind is missing, so the cache is usually complete before the ordering runs. The refresh covers the case where it is not, and any later caller that orders nodes without reading a group first.
Tests, for both clients: test_ordering_refreshes_the_schema_once_when_a_member_kind_is_not_cached (fails without the change) and test_ordering_sends_no_schema_request_when_every_member_kind_is_cached.
| 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 [] |
There was a problem hiding this comment.
The block graph has no cycles, so None should not occur here. If a later change let one through, or [] would drop every candidate of a known kind without an error. Those members would be neither deleted nor kept, so the group update would remove them and they would never be cleaned up. Raising an error here fails safely.
Written by an AI under the guidance of a human reviewer.
There was a problem hiding this comment.
Valid point — or [] would have left every candidate of a known kind out of the order without an error. Now DeletionOrder.order() raises a RuntimeError when the kinds cannot be ordered, the same exception the cycle check in _order_block raises, in b3178aa. delete_unused() catches it, deletes in group order, and raises the failure after the group write, so no member is dropped. Test: test_deletion_order_raises_when_the_kinds_cannot_be_ordered in tests/unit/sdk/test_schema_dependencies.py.
|
|
||
| group = await client.get(kind="CoreStandardGroup", name__value=group_name, include=["members"]) | ||
| assert len(group.members.peers) == 0 | ||
| with pytest.raises(NodeNotFoundError): |
There was a problem hiding this comment.
.agents/rules/python-testing.md says to always pass match= to pytest.raises(). The same applies at lines 224, 419 and 421 here, and at tests/unit/sdk/test_group_context.py:668. Without it, these tests pass on any NodeNotFoundError or TrackingGroupCleanupError.
Written by an AI under the guidance of a human reviewer.
There was a problem hiding this comment.
Done in e09c69d: match= added at the four integration lines (on the node id) and in the unit test (on the cleanup error message).
| 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. |
There was a problem hiding this comment.
"Keys with no dependency between them keep their place in order" does not hold, because keys are grouped by level. dependents_first({"x": set(), "a": {"b"}, "b": set()}, order=["x", "a", "b"]) returns ["a", "x", "b"]. The module docstring of schema/dependencies.py (line 4) also describes creation order, which the module does not implement.
Written by an AI under the guidance of a human reviewer.
There was a problem hiding this comment.
Done in e09c69d. The dependents_first docstring now says keys are grouped by the length of the dependency chain below them and only follow order within a group, so your example returning ["a", "x", "b"] matches it. The module docstring of schema/dependencies.py now describes deletion order only.
…he 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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
There was a problem hiding this comment.
1 issue found across 3 files (changes from recent commits).
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="infrahub_sdk/schema/dependencies.py">
<violation number="1" location="infrahub_sdk/schema/dependencies.py:49">
P2: This lookup still misses generic peers whenever the schema cache is partial. Refresh or otherwise load the complete branch schema before constructing `DeletionOrder`; otherwise a cached schema populated with `namespaces=[...]` omits `CoreNode`, the `used_by` edge is never added, and a held candidate can be attempted before its holder and remain undeleted for another run.</violation>
</file>
Tip: Review your code locally with the cubic CLI to iterate faster.
View guided diff | Turn on auto-fix | Re-trigger cubic
| for name in schema.mandatory_relationship_names: | ||
| peer = schema.get_relationship(name).peer | ||
| kinds = {peer} & candidate_kinds | ||
| peer_schema = schemas.get(peer) |
There was a problem hiding this comment.
P2: This lookup still misses generic peers whenever the schema cache is partial. Refresh or otherwise load the complete branch schema before constructing DeletionOrder; otherwise a cached schema populated with namespaces=[...] omits CoreNode, the used_by edge is never added, and a held candidate can be attempted before its holder and remain undeleted for another run.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At infrahub_sdk/schema/dependencies.py, line 49:
<comment>This lookup still misses generic peers whenever the schema cache is partial. Refresh or otherwise load the complete branch schema before constructing `DeletionOrder`; otherwise a cached schema populated with `namespaces=[...]` omits `CoreNode`, the `used_by` edge is never added, and a held candidate can be attempted before its holder and remain undeleted for another run.</comment>
<file context>
@@ -32,19 +33,23 @@ class PeerLookup:
- 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
</file context>
…e 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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
… 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 <noreply@anthropic.com>
There was a problem hiding this comment.
1 issue found across 4 files (changes from recent commits).
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="infrahub_sdk/query_groups.py">
<violation number="1" location="infrahub_sdk/query_groups.py:411">
P2: `ordering_error` does not stop the reap, but this branch treats it as the primary cause when the group write fails. If ordering fails and the subsequent schema/create/save operation fails independently, both `update_group` methods raise the stale ordering exception instead of the actual group-write error; only use `reap.error` for this override and report `ordering_error` after a successful write.</violation>
</file>
Requires human review: Auto-approval blocked because this review re-detected 1 unresolved issue already reported by Cubic.
Tip: Get a Slack DM when cubic finishes reviewing your PRs. Connect Slack
View guided diff | Turn on auto-fix | Re-trigger cubic
| 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 |
There was a problem hiding this comment.
P2: ordering_error does not stop the reap, but this branch treats it as the primary cause when the group write fails. If ordering fails and the subsequent schema/create/save operation fails independently, both update_group methods raise the stale ordering exception instead of the actual group-write error; only use reap.error for this override and report ordering_error after a successful write.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At infrahub_sdk/query_groups.py, line 411:
<comment>`ordering_error` does not stop the reap, but this branch treats it as the primary cause when the group write fails. If ordering fails and the subsequent schema/create/save operation fails independently, both `update_group` methods raise the stale ordering exception instead of the actual group-write error; only use `reap.error` for this override and report `ordering_error` after a successful write.</comment>
<file context>
@@ -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
</file context>
There was a problem hiding this comment.
Valid point — an ordering failure does not stop the deletes, so a group write that fails afterwards failed for its own reason, and raising the ordering error hid it. Now, in both clients, update_group() raises the write error with the ordering failure as its cause; an error that stopped the deletes is still raised in place of the write error. In 516d0a7. Test: test_failed_write_after_a_failed_peer_query_raises_the_write_error (fails without the change).
…ched 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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
|
Thanks for the review. Every inline comment has a reply on its thread; in short:
The six follow-ups from your review are collected in #1573, including the note that a shared ordering method needs the schema refresh, because its callers may not have read a group first. |
There was a problem hiding this comment.
1 issue found across 4 files (changes from recent commits).
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="infrahub_sdk/topological_sort.py">
<violation number="1" location="infrahub_sdk/topological_sort.py:114">
P2: This docstring now documents that `dependents_first` regroups independent keys by dependency level, so an unrelated key can move ahead of or behind its `order` position. The team expects independent keys to keep their input order, so fix the algorithm rather than document the exception. One option is Kahn's algorithm over the reversed graph, using a heap keyed by `position` to pick the next ready key. (Based on your team's feedback about preserving independent-key order.)</violation>
</file>
Reply with feedback, questions, or to request a fix.
View guided diff | Turn on auto-fix | Re-trigger cubic
| """Sort the keys of `dependencies` so each key comes before the keys it depends on. | ||
|
|
||
| Keys are grouped by the length of the dependency chain below them and returned from the longest | ||
| chain to the shortest; within a group they follow `order`. A key without dependencies can |
There was a problem hiding this comment.
P2: This docstring now documents that dependents_first regroups independent keys by dependency level, so an unrelated key can move ahead of or behind its order position. The team expects independent keys to keep their input order, so fix the algorithm rather than document the exception. One option is Kahn's algorithm over the reversed graph, using a heap keyed by position to pick the next ready key.
(Based on your team's feedback about preserving independent-key order.)
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At infrahub_sdk/topological_sort.py, line 114:
<comment>This docstring now documents that `dependents_first` regroups independent keys by dependency level, so an unrelated key can move ahead of or behind its `order` position. The team expects independent keys to keep their input order, so fix the algorithm rather than document the exception. One option is Kahn's algorithm over the reversed graph, using a heap keyed by `position` to pick the next ready key.
(Based on your team's feedback about preserving independent-key order.) </comment>
<file context>
@@ -110,7 +110,9 @@ def visit(key: str) -> None:
- 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.
"""
</file context>
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 <noreply@anthropic.com>
Why
A generator, or any tracking run with
delete_unused_nodes=True, creates nodes in dependency order: the node that is held first, then the node that holds it through a mandatory relationship. For example, two IP addresses and then a BGP session whose mandatorysrc_ipanddst_ippoint at them. When a later run stops building that session, the cleanup deleted the unused members in the order the group returns them, which is creation order. The server refused to delete the IP addresses while the session still held them, so the run failed withTrackingGroupCleanupError, and only the next run deleted them.Goal: one run deletes every unused node, including unused nodes that hold each other through mandatory relationships, without sending a delete that fails only because of the order.
Non-goals:
developandstable. They do not have the refusal handling from fix(tracking): reconcile tracking groups on runs that save no nodes #1278, and this PR depends on it.Closes #1477
What changed
Behavioral changes:
TrackingGroupCleanupError.Implementation notes:
infrahub_sdk/schema/dependencies.py(new):DeletionOrderbuilds a dependency graph between the kinds to delete from their mandatory relationships (mandatory_relationship_names). A peer that is a generic, such asCoreNode, matches every kind listed in the generic'sused_by(and, as a fallback, every kind that names it ininherit_from). It uses only schema objects, so it can later serve other bulk deletes, or creation order for imports.infrahub_sdk/topological_sort.py: two graph helpers next to the existingtopological_sort(),strongly_connected_components()anddependents_first().infrahub_sdk/query_groups.py: only the parts that need the client, which read the cached schema, run the peer queries and handle a failure.client.schema.all(), which returns the cached branch schema. The cache is already filled by the group lookup, so the order between kinds usually costs no request. If a member's kind is still missing from the cache, the schema is refreshed once.schema.get()is not used per kind, because it downloads the whole branch schema again for every kind that is not in the cache.filters(..., only=[mandatory relationships])query per kind reads the peers, and the nodes are sorted by them. In every other case no query is sent.SchemaNotFoundErrorand is recorded as a refusal, as before._record_failure()andReapResultare unchanged. They work on the ordered list.What stayed the same:
delete_unused()andupdate_group()keep their signatures.How to review
DeletionOrderininfrahub_sdk/schema/dependencies.pyand the graph helpers ininfrahub_sdk/topological_sort.py: the graph, the handling of cycles and the order inside a kind._order_for_deletion()anddelete_unused()(async and sync): the ordering failure path that keeps every member.tests/unit/sdk/test_schema_dependencies.pyandtests/unit/sdk/test_topological_sort.pyfor the ordering,tests/unit/sdk/test_group_context.pyandtests/integration/test_tracking_zero_members.pyfor the cleanup.Worth extra scrutiny: whether every relationship with
optional: falseis one the server enforces when it deletes the peer.How to test
The new integration test
test_unused_owner_and_animal_are_deleted_in_one_run(async and sync) creates a person and then a cat that holds them through the mandatoryownerrelationship, then runs an empty tracking session. With the fix, both are deleted in one run. With the ordering switched off, it fails with the error from the issue: "Cannot delete TestingPerson … It is linked to mandatory relationship owner on node TestingCat".Impact & rollout
query_groups.pyruns inside Infrahub generators. Running Infrahub's CI against this branch before merging is worth considering.Checklist
changelog/1477.fixed.md)🤖 Generated with Claude Code