Skip to content

fix(tracking): delete unused members before the nodes they hold - #1487

Open
FragmentedPacket wants to merge 8 commits into
infrahub-release-1.12from
ai-bug-pipeline-1477-tracking-cleanup-delete-order
Open

FragmentedPacket wants to merge 8 commits into
infrahub-release-1.12from
ai-bug-pipeline-1477-tracking-cleanup-delete-order

Conversation

@FragmentedPacket

@FragmentedPacket FragmentedPacket commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

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 mandatory src_ip and dst_ip point 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 with TrackingGroupCleanupError, 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:

Closes #1477

What changed

Behavioral changes:

  • The cleanup deletes a node before the nodes it holds through a mandatory relationship, so one run removes nodes that depend on each other.
  • If the order cannot be worked out (the schema or the peers cannot be read, or computing the order raises any other error), nothing is deleted. The failure stops the cleanup like any other request failure: every unused member stays in the group, this run's group is written, and the error is raised. The next run tries again.
  • A member that a node outside the group holds is still refused, kept in the group and reported in TrackingGroupCleanupError.
  • Two cases have no valid order, so the cleanup does not stop for them: nodes whose mandatory relationships form a cycle (possible only if a node was edited to point back after both existed) keep group order, and nodes of a kind missing from the schema go last. The server refuses those deletes, the members stay in the group and are reported, and the other members are still deleted.

Implementation notes:

  • The ordering does not depend on tracking groups, so it is split by what it depends on:
    • infrahub_sdk/schema/dependencies.py (new): DeletionOrder builds a dependency graph between the kinds to delete from their mandatory relationships (mandatory_relationship_names). A peer that is a generic matches every kind that inherits from it. 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 existing topological_sort(), strongly_connected_components() and dependents_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.
  • The schema is read with client.schema.all(), which returns the cached branch schema. The cache is already filled by the group lookup, so the order between kinds costs no request. schema.get() is not used per kind, because it downloads the whole branch schema again for every kind that is not in the cache.
  • Kinds that hold nodes of their own kind, or kinds that hold each other, cannot be ordered from the schema alone. For those kinds only, one 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.
  • A kind that is not in the schema has no known dependencies and goes last. Its delete fails with SchemaNotFoundError and is recorded as a refusal, as before.
  • The delete loop, _record_failure() and ReapResult are unchanged. They work on the ordered list.

What stayed the same:

  • No public API change. delete_unused() and update_group() keep their signatures.
  • When the order is worked out, the same members are deleted as before, only in a different order.

How to review

  1. DeletionOrder in infrahub_sdk/schema/dependencies.py and the graph helpers in infrahub_sdk/topological_sort.py: the graph, the handling of cycles and the order inside a kind.
  2. _order_for_deletion() and delete_unused() (async and sync): the ordering failure path that keeps every member.
  3. Tests: tests/unit/sdk/test_schema_dependencies.py and tests/unit/sdk/test_topological_sort.py for the ordering, tests/unit/sdk/test_group_context.py and tests/integration/test_tracking_zero_members.py for the cleanup.

Worth extra scrutiny: whether every relationship with optional: false is one the server enforces when it deletes the peer.

How to test

uv run pytest tests/unit/sdk/test_group_context.py
uv run pytest tests/integration/test_tracking_zero_members.py

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 mandatory owner relationship, 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

  • Backward compatibility: no breaking change.
  • Performance: no extra request in the common case. One peer query per kind that holds nodes of its own kind or of a kind that holds it back, plus one more request per page when that query has more members than the client's page size.
  • Infrahub CI: query_groups.py runs inside Infrahub generators. Running Infrahub's CI against this branch before merging is worth considering.

Checklist

  • Tests added/updated
  • Changelog entry added (changelog/1477.fixed.md)
  • External docs updated (not needed: the tracking guide does not describe the cleanup order or refusals)
  • Internal .md docs updated (none cover this area)

🤖 Generated with Claude Code

View guided diff Turn on auto-fix

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>
@FragmentedPacket
FragmentedPacket requested a review from a team as a code owner November 5, 2026 18:24
@FragmentedPacket FragmentedPacket added the type/bug Something isn't working as expected label Nov 5, 2026
@codecov

codecov Bot commented Nov 5, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.53086% with 4 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
infrahub_sdk/query_groups.py 95.74% 0 Missing and 2 partials ⚠️
infrahub_sdk/schema/dependencies.py 97.43% 1 Missing and 1 partial ⚠️
@@                    Coverage Diff                    @@
##           infrahub-release-1.12    #1487      +/-   ##
=========================================================
+ Coverage                  87.74%   87.97%   +0.23%     
=========================================================
  Files                        155      158       +3     
  Lines                      15539    15813     +274     
  Branches                    2091     2139      +48     
=========================================================
+ Hits                       13635    13912     +277     
+ Misses                      1344     1340       -4     
- Partials                     560      561       +1     
Flag Coverage Δ
integration-tests 42.95% <45.67%> (+0.47%) ⬆️
python-3.10 63.05% <80.24%> (+0.47%) ⬆️
python-3.11 63.06% <80.24%> (+0.48%) ⬆️
python-3.12 63.06% <80.24%> (+0.48%) ⬆️
python-3.13 63.05% <80.24%> (+0.48%) ⬆️
python-3.14 63.06% <80.24%> (+0.49%) ⬆️
python-3.15 63.05% <80.24%> (+0.48%) ⬆️
python-filler-3.12 23.04% <17.28%> (-0.09%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
infrahub_sdk/topological_sort.py 95.34% <100.00%> (+3.51%) ⬆️
infrahub_sdk/query_groups.py 94.90% <95.74%> (+1.00%) ⬆️
infrahub_sdk/schema/dependencies.py 97.43% <97.43%> (ø)

... and 3 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread infrahub_sdk/query_groups.py Outdated
Comment on lines +299 to +300
if ordered_ids is None:
return members

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>
Suggested change
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")

Comment thread infrahub_sdk/query_groups.py Outdated
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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>
Suggested change
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)}")

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>
@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Nov 5, 2026 •

Copy link
Copy Markdown

Deploying infrahub-sdk-python with  Cloudflare Pages  Cloudflare Pages

Latest commit: b3178aa
Status: ✅  Deploy successful!
Preview URL: https://a742ec73.infrahub-sdk-python.pages.dev
Branch Preview URL: https://ai-bug-pipeline-1477-trackin.infrahub-sdk-python.pages.dev

View logs

@ogenstad ogenstad left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>
@FragmentedPacket

Copy link
Copy Markdown
Contributor Author

Thanks, agreed: the ordering has nothing to do with groups. I split it by what each part depends on (70101e0):

  • infrahub_sdk/schema/dependencies.py (new): DeletionOrder, which orders nodes for deletion from the mandatory relationships in the schema. It takes (kind, id) pairs and schema objects only, and it reads the mandatory relationships from mandatory_relationship_names.
  • infrahub_sdk/topological_sort.py: the two graph helpers it needs, strongly_connected_components() and dependents_first(), next to topological_sort().
  • infrahub_sdk/query_groups.py: only the parts that need the client, which read the cached schema, run the only peer query for kinds that hold their own kind, and stop the cleanup when the order cannot be worked out. Its additions went from about 270 lines to about 85.

No behaviour changed. The DeletionOrder tests moved to tests/unit/sdk/test_schema_dependencies.py.

I kept DeletionOrder internal for now (not exported or documented). A way for users to delete many nodes in the right order needs its own API design, for example client.delete_nodes() in async and sync versions, and this PR is a fix on the release branch. Would you like an issue for that? InfrahubSchemaTopologicalSorter in transfer/schema_sorter.py builds the same graph for creation order during imports, so it could move into schema/dependencies.py as part of that work.

@ogenstad ogenstad left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_deletion in both clients, _mandatory_peer_ids and _member_peers at query_groups.py:124-141) still lives in the group context. A future client.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 let delete_unused and 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_first and strongly_connected_components raise KeyError when a dependency is not a key: dependents_first({"a": {"b"}}, order=["a"]). topological_sort accepts such keys. This needs fixing before the helpers are reused for import ordering.
  • dependents_first runs topological_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_kinds builds the same graph as InfrahubSchemaTopologicalSorter.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_many and the dict[str, bool] form of PeerLookup.relationships exist only so _mandatory_peer_ids can choose an accessor. The node already carries its schema, so relationships could be a list[str].

Comment thread infrahub_sdk/schema/dependencies.py Outdated
Comment on lines +139 to +141
ordered_ids = dependents_first(dependencies=dependencies, order=node_ids)
if ordered_ids is None:
return nodes

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread infrahub_sdk/schema/dependencies.py Outdated
kinds = {
kind
for kind, peer_schema in schemas.items()
if peer == kind or peer in getattr(peer_schema, "inherit_from", [])

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread infrahub_sdk/schema/dependencies.py Outdated
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 []

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

.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.

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"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.

FragmentedPacket and others added 2 commits November 25, 2026 08:47
…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>

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>

FragmentedPacket and others added 3 commits November 25, 2026 08:56
…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>

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 existing issue remains and 1 new 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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

type/bug Something isn't working as expected

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants