Skip to content

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

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

FragmentedPacket wants to merge 11 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), the members are deleted in group order. Refused deletes are recorded and those members stay in the group, this run's group is written, and the ordering error is raised. A failure that repeats on every run therefore does not stop members that nothing holds from being deleted. An error that stops the deletes themselves is still raised first.
  • 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 among themselves while the nodes around them are still ordered, and nodes of a kind the server does not know 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, such as CoreNode, matches every kind listed in the generic's used_by (and, as a fallback, every kind that names it in inherit_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 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 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.
  • 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 96.47059% with 6 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
infrahub_sdk/query_groups.py 92.72% 2 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.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     
Flag Coverage Δ
integration-tests 42.92% <43.52%> (+0.44%) ⬆️
python-3.10 63.08% <80.00%> (+0.49%) ⬆️
python-3.11 63.08% <80.00%> (+0.49%) ⬆️
python-3.12 63.06% <80.00%> (+0.48%) ⬆️
python-3.13 63.08% <80.00%> (+0.51%) ⬆️
python-3.14 63.08% <80.00%> (+0.51%) ⬆️
python-3.15 63.07% <80.00%> (+0.49%) ⬆️
python-filler-3.12 23.03% <16.47%> (-0.10%) ⬇️

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/schema/dependencies.py 97.43% <97.43%> (ø)
infrahub_sdk/query_groups.py 95.01% <92.72%> (+1.12%) ⬆️

... and 2 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")

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.

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.

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

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.

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

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.

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

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.

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.

Done in e09c69d: match= added at the four integration lines (on the node id) and in the unit test (on the cleanup error message).

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

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.

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.

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

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

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

FragmentedPacket and others added 2 commits December 1, 2026 09:11
…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>
@FragmentedPacket

Copy link
Copy Markdown
Contributor Author

Thanks for the review. Every inline comment has a reply on its thread; in short:

  • Cycle inside a block: only the nodes in the cycle keep group order now, the rest are ordered around it (a30a4a6).
  • CoreNode peers: a generic peer is matched through the generic's used_by, with inherit_from as a fallback (6476cd5).
  • Cleanup when the order cannot be worked out: the members are deleted in group order, refusals stay in the group, and the ordering error is raised after the group write (5f0a4f6).
  • Cardinality-many peer queries: a test now runs the Left/Right case through filters(only=...) for both clients (594f15b). No production change was needed.
  • Stale schema cache: the schema is refreshed once when a member's kind is not cached (d87b5a8).
  • or [] in order(): it raises instead (b3178aa).
  • match= in pytest.raises and the two docstrings: e09c69d.

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.

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

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

View Feedback

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