Skip to content

don't allocate from pools on templates#863

Open
ajtmccarty wants to merge 4 commits intoinfrahub-developfrom
ajtm-03062026-template-pool-handling
Open

don't allocate from pools on templates#863
ajtmccarty wants to merge 4 commits intoinfrahub-developfrom
ajtm-03062026-template-pool-handling

Conversation

@ajtmccarty
Copy link
Contributor

@ajtmccarty ajtmccarty commented Mar 7, 2026

stop trying to process pools for templates b/c we will never provision from pools on a template

Summary by CodeRabbit

  • Bug Fixes

    • Prevented mutation responses from overwriting pool-allocated attributes and relationships for template nodes, ensuring template resources keep their original pool references while non-template nodes continue to apply server-allocated values.
  • Tests

    • Added unit tests (sync & async) verifying template handling preserves pool-backed attributes/relationships and that regular nodes allocate from the pool as expected.

@coderabbitai
Copy link

coderabbitai bot commented Mar 7, 2026

Walkthrough

Adds conditional logic to Node mutation-result handlers to skip processing results for template schemas. An is_template check (using TemplateSchemaAPI) is applied in both async and sync handlers; when true, updates to attributes and resource-pool–related fields are skipped. As a result, pool-allocated attributes and resource allocations on template nodes are not populated from mutation responses. No public API signatures were changed. Lines added: 20.

🚥 Pre-merge checks | ✅ 1 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 40.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ❓ Inconclusive The description is vague and lacks important context about why this change is needed, what specifically changed, and testing approach. Expand description to explain the problem, implementation details (guard logic in mutation handlers), backward compatibility, and testing strategy.
✅ Passed checks (1 passed)
Check name Status Explanation
Title check ✅ Passed The title 'don't allocate from pools on templates' directly summarizes the main change: preventing pool allocation processing for template nodes.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

Tip

Try Coding Plans. Let us write the prompt for your AI agent so you can ship faster (with fewer bugs).
Share your feedback on Discord.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@cloudflare-workers-and-pages
Copy link

cloudflare-workers-and-pages bot commented Mar 7, 2026

Deploying infrahub-sdk-python with  Cloudflare Pages  Cloudflare Pages

Latest commit: cad0ac0
Status: ✅  Deploy successful!
Preview URL: https://bb32bd30.infrahub-sdk-python.pages.dev
Branch Preview URL: https://ajtm-03062026-template-pool.infrahub-sdk-python.pages.dev

View logs

@codecov
Copy link

codecov bot commented Mar 7, 2026

Codecov Report

❌ Patch coverage is 90.00000% with 1 line in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
infrahub_sdk/node/node.py 90.00% 0 Missing and 1 partial ⚠️
@@                 Coverage Diff                  @@
##           infrahub-develop     #863      +/-   ##
====================================================
+ Coverage             80.64%   80.72%   +0.07%     
====================================================
  Files                   118      118              
  Lines                 10246    10256      +10     
  Branches               1534     1538       +4     
====================================================
+ Hits                   8263     8279      +16     
+ Misses                 1455     1452       -3     
+ Partials                528      525       -3     
Flag Coverage Δ
integration-tests 40.33% <20.00%> (-0.02%) ⬇️
python-3.10 51.91% <80.00%> (+0.08%) ⬆️
python-3.11 51.93% <80.00%> (+0.10%) ⬆️
python-3.12 51.93% <80.00%> (+0.10%) ⬆️
python-3.13 51.93% <80.00%> (+0.10%) ⬆️
python-3.14 53.60% <80.00%> (+0.08%) ⬆️
python-filler-3.12 24.01% <0.00%> (-0.03%) ⬇️

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

Files with missing lines Coverage Δ
infrahub_sdk/node/node.py 86.35% <90.00%> (+0.53%) ⬆️

... and 1 file with indirect coverage changes

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

@ajtmccarty ajtmccarty marked this pull request as ready for review March 8, 2026 00:04
@ajtmccarty ajtmccarty requested a review from a team as a code owner March 8, 2026 00:04
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
infrahub_sdk/node/node.py (1)

1093-1107: Consider skipping pool query fields for templates in _generate_mutation_query.

The mutation query currently requests pool allocation fields (attr._generate_mutation_query(), rel._generate_mutation_query()) for all nodes, including templates. Since templates never allocate from pools and _process_mutation_result now skips processing these fields for templates, the server response data for these fields goes unused.

An optional optimization would be to add the same isinstance(self._schema, TemplateSchemaAPI) check here to avoid requesting unnecessary data. This would reduce response payload size for template mutations.

♻️ Optional: Skip pool query fields for templates
 def _generate_mutation_query(self) -> dict[str, Any]:
     query_result: dict[str, Any] = {"ok": None, "object": {"id": None}}
+    is_template = isinstance(self._schema, TemplateSchemaAPI)

     for attr_name in self._attributes:
         attr: Attribute = getattr(self, attr_name)
+        if is_template and attr.is_from_pool_attribute():
+            continue
         query_result["object"].update(attr._generate_mutation_query())

     for rel_name in self._relationships:
         rel = getattr(self, rel_name)
         if not isinstance(rel, RelatedNode):
             continue
+        if is_template and rel.is_resource_pool:
+            continue

         query_result["object"].update(rel._generate_mutation_query())

     return query_result
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@infrahub_sdk/node/node.py` around lines 1093 - 1107, The mutation builder
_generate_mutation_query currently includes pool-allocation fields from
Attribute and RelatedNode for every node; add a guard using
isinstance(self._schema, TemplateSchemaAPI) to detect templates and skip calling
attr._generate_mutation_query() and rel._generate_mutation_query() when true so
template mutations do not request pool fields (keep building id/ok fields as
before); update the loops over self._attributes and self._relationships to
conditionally call the per-field _generate_mutation_query only for non-template
schemas, referencing Attribute, RelatedNode, _process_mutation_result, and
TemplateSchemaAPI to mirror the processing skip.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@infrahub_sdk/node/node.py`:
- Around line 1093-1107: The mutation builder _generate_mutation_query currently
includes pool-allocation fields from Attribute and RelatedNode for every node;
add a guard using isinstance(self._schema, TemplateSchemaAPI) to detect
templates and skip calling attr._generate_mutation_query() and
rel._generate_mutation_query() when true so template mutations do not request
pool fields (keep building id/ok fields as before); update the loops over
self._attributes and self._relationships to conditionally call the per-field
_generate_mutation_query only for non-template schemas, referencing Attribute,
RelatedNode, _process_mutation_result, and TemplateSchemaAPI to mirror the
processing skip.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 4ba990b2-fb44-412e-9443-1b8dbb2f5fa3

📥 Commits

Reviewing files that changed from the base of the PR and between f737549 and c36bef8.

📒 Files selected for processing (1)
  • infrahub_sdk/node/node.py

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

🧹 Nitpick comments (2)
tests/unit/sdk/pool/test_template_skip_pool_allocation.py (2)

40-41: Consider a more precise assertion for template attribute preservation.

The assertion != 42 confirms the allocated value wasn't applied, but doesn't verify the expected state. Based on how Attribute handles from_pool data (defaults value to None), asserting the actual expected value would make test failures more informative.

💡 Suggested improvement
-        assert node.vlan_id.value != 42
+        assert node.vlan_id.value is None  # Pool reference preserved, not allocated

Apply the same change at line 54 for the sync variant.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/unit/sdk/pool/test_template_skip_pool_allocation.py` around lines 40 -
41, The test currently asserts node.vlan_id.value != 42 which only checks it
wasn't set; change it to assert the precise expected value produced by
Attribute.from_pool (i.e. assert node.vlan_id.value is None) so failures are
clearer; update the same assertion in the sync variant (the second test around
line 54) as well.

185-216: Fixtures don't need to be async.

These fixtures don't use await internally, so they can be defined as regular sync functions. This is a minor style consideration.

💡 Optional simplification
 `@pytest.fixture`
-async def vlan_template_schema() -> TemplateSchemaAPI:
+def vlan_template_schema() -> TemplateSchemaAPI:
     return TemplateSchemaAPI(
         ...
     )


 `@pytest.fixture`
-async def device_template_schema() -> TemplateSchemaAPI:
+def device_template_schema() -> TemplateSchemaAPI:
     return TemplateSchemaAPI(
         ...
     )
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/unit/sdk/pool/test_template_skip_pool_allocation.py` around lines 185 -
216, The fixtures vlan_template_schema and device_template_schema are declared
async but do not await anything; change them to regular synchronous pytest
fixtures by removing the async keyword (keep the `@pytest.fixture` decorator and
return TemplateSchemaAPI instances as before) so functions vlan_template_schema
and device_template_schema become normal def fixtures returning
TemplateSchemaAPI constructed with AttributeSchemaAPI and RelationshipSchemaAPI
values.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@tests/unit/sdk/pool/test_template_skip_pool_allocation.py`:
- Around line 40-41: The test currently asserts node.vlan_id.value != 42 which
only checks it wasn't set; change it to assert the precise expected value
produced by Attribute.from_pool (i.e. assert node.vlan_id.value is None) so
failures are clearer; update the same assertion in the sync variant (the second
test around line 54) as well.
- Around line 185-216: The fixtures vlan_template_schema and
device_template_schema are declared async but do not await anything; change them
to regular synchronous pytest fixtures by removing the async keyword (keep the
`@pytest.fixture` decorator and return TemplateSchemaAPI instances as before) so
functions vlan_template_schema and device_template_schema become normal def
fixtures returning TemplateSchemaAPI constructed with AttributeSchemaAPI and
RelationshipSchemaAPI values.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 15727e0c-08cd-4264-bf3c-d36048110f18

📥 Commits

Reviewing files that changed from the base of the PR and between c36bef8 and cad0ac0.

📒 Files selected for processing (1)
  • tests/unit/sdk/pool/test_template_skip_pool_allocation.py

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants