Skip to content

feat: add update_from_dict to update node fields from a dict - #1206

Open
lancamat1 wants to merge 2 commits into
stablefrom
feat/update-node-from-dict
Open

lancamat1 wants to merge 2 commits into
stablefrom
feat/update-node-from-dict

Conversation

@lancamat1

@lancamat1 lancamat1 commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

Why

Creating a node accepts a dict of attributes and relationships, but updating an existing node requires assigning each field one by one — integrations that receive external data as dicts end up hand-rolling Attribute and RelationshipManager rebuilding (as shown in the linked issue).

This PR adds update_from_dict() so an existing node can be updated from a dict in one call, mirroring the data formats accepted at creation time.

Non-goals: hierarchical relationships (parent/children) are not addressed; they are rejected as unknown fields.

Closes #272

What changed

  • New update_from_dict() method on InfrahubNode and InfrahubNodeSync:
    • Attributes accept scalars, dicts with value and optional properties, or from_pool allocations; updated attributes are marked mutated so partial updates via node.update() include them (including clearing an optional attribute with None).
    • Cardinality-one relationships accept an ID, HFID list, dict, or node object; None clears them.
    • Cardinality-many relationships replace the peer list from a list of IDs/dicts/node objects; [] (or None) clears them.
    • Unknown field names raise ValueError before anything is touched, so a typo cannot half-apply an update.
    • Cardinality-many relationships that take peers as fields raise FeatureNotSupportedError before anything is touched.
  • Method declared on the CoreNodeBase protocol so protocol-typed code can call it.
  • No changes to existing save/update payload generation — the method reuses the existing Attribute, RelatedNode, and RelationshipManager machinery.

How to review

  • infrahub_sdk/node/node.py: all the logic is in InfrahubNodeBase.update_from_dict(), shared by the async and sync nodes. Plain attribute values use the existing value setter. Cardinality-one relationships use the existing __setattr__ path. Cardinality-many relationships replace the peers of the existing manager from _get_relationship_many().
  • docs/.../node.mdx is regenerated; changelog/272.added.md is the towncrier fragment.

How to test

uv run pytest tests/unit/sdk/test_node.py -k update_from_dict

14 new test cases (7 scenarios × async/sync) covering attribute scalars, attribute dicts with properties, from_pool without changing the caller's dict, both relationship cardinalities, replacing peers that were not fetched, clearing relationships, and the unknown-field error with payload assertions via _generate_input_data().

Impact & rollout

  • Backward compatibility: purely additive, no changes to existing behavior.

Checklist

  • Tests added/updated
  • Changelog entry added
  • External docs updated (generated SDK reference)

🤖 Generated with Claude Code


Summary by cubic

Add update_from_dict() to InfrahubNode and InfrahubNodeSync to update multiple attributes and relationships from a dict in one call, matching create-time payloads. This simplifies integrations and validates keys up front to prevent partial updates.

  • New Features
    • Attributes accept scalars, { value, ...props }, or from_pool; changes are marked mutated and None clears optional values.
    • Relationships accept an ID, dict, node object, or lists for cardinality-many; None clears ONE and [] or None clears MANY.
    • Unknown fields raise ValueError before any change is applied.
    • Method added to the CoreNodeBase protocol; existing save/update payload generation is unchanged.

Written for commit b3376bc. Summary will update on new commits.

Review in cubic

@lancamat1
lancamat1 requested a review from a team as a code owner July 22, 2026 13:27
@lancamat1 lancamat1 added the type/feature New feature or request label Jul 22, 2026
@github-actions github-actions Bot added the type/documentation Improvements or additions to documentation label Jul 22, 2026

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

All reported issues were addressed across 5 files

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Comment thread infrahub_sdk/node/node.py Resolved
Comment thread infrahub_sdk/node/node.py Outdated

for name, value in data.items():
if name in self._attributes:
attribute = Attribute(name=name, schema=self._schema.get_attribute(name=name), data=value)

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.

is it necessary to create a new Attribute here? can this do self._get_attribute and then attr.value = value? I think that would also inherently handle self._attribute_data

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.

Changed in 66e0613. A plain value now goes through self._get_attribute(name).value = value, so it reuses the existing attribute.

A dict with value and properties (is_protected, source and so on) or with from_pool still builds a new Attribute, because the value setter only takes a bare value and the constructor already parses the rest. That new attribute is now bound to the node with _bind(), which from_pool and only need on current stable. If you would rather have an in-place update on Attribute for the dict case as well, I can add it.

Comment thread infrahub_sdk/node/node.py Outdated

super().__setattr__(name, value)

def _update_relationship_from_dict(self, name: str, data: Any) -> 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.

basically the same question for this method. is it necessary to create a new RelationshipManager[Sync]? can this use self._get_relationship_many or self._get_relationship_one and then all be handled within the InfrahubNodeBase class instead of different Sync/Async versions?

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.

Yes, it is all in InfrahubNodeBase now and the async/sync versions are gone.

  • cardinality many: self._get_relationship_many(name), then the peers are replaced with extend() on the existing manager. The manager is marked initialized first, because the whole list is replaced and the current peers do not have to be fetched.
  • cardinality one: setattr(self, name, value), the same path as node.rel = x. RelatedNode has no setter for the peer, so I kept that instead of _get_relationship_one.

Relationships that take peers as fields raise FeatureNotSupportedError before anything is changed, the same as add() does.

lancamat1 and others added 2 commits December 4, 2026 15:18
Allow updating several attributes and relationships of an existing
InfrahubNode or InfrahubNodeSync at once from a dict, mirroring the
data format accepted when creating a node. Attribute values accept
scalars, dicts with value and properties, or from_pool allocations;
relationships accept IDs, dicts, node objects, or lists of those for
cardinality-many. None clears a cardinality-one relationship and []
clears a cardinality-many one. Unknown field names raise ValueError
and leave the node unmodified.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Move update_from_dict into InfrahubNodeBase so the async and sync
nodes share one implementation.

- Scalar attribute values go through the existing attribute setter.
  A dict with properties or from_pool still builds a new Attribute,
  because the setter takes a bare value. The new Attribute is now bound
  to its node, and the caller's dict is copied so from_pool is kept.
- Cardinality-many relationships replace the peers of the existing
  manager instead of building a new manager.
- Cardinality-many relationships that take peers as fields raise
  FeatureNotSupportedError before any field changes.

Claude-Session: https://claude.ai/code/session_019U7jtHQEPGWByz5sZjofdD
@lancamat1
lancamat1 force-pushed the feat/update-node-from-dict branch from b3376bc to 66e0613 Compare December 4, 2026 14:21
@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Dec 4, 2026 •

Copy link
Copy Markdown

Deploying infrahub-sdk-python with  Cloudflare Pages  Cloudflare Pages

Latest commit: 66e0613
Status: ✅  Deploy successful!
Preview URL: https://1476e528.infrahub-sdk-python.pages.dev
Branch Preview URL: https://feat-update-node-from-dict.infrahub-sdk-python.pages.dev

View logs

@lancamat1
lancamat1 requested a review from ajtmccarty December 4, 2026 14:22
@codecov

codecov Bot commented Dec 4, 2026 •

Copy link
Copy Markdown

Codecov Report

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

Files with missing lines Patch % Lines
infrahub_sdk/protocols_base.py 0.00% 0 Missing and 1 partial ⚠️
@@            Coverage Diff             @@
##           stable    #1206      +/-   ##
==========================================
- Coverage   88.37%   87.97%   -0.40%     
==========================================
  Files         157      157              
  Lines       16323    15703     -620     
  Branches     2412     2123     -289     
==========================================
- Hits        14425    13815     -610     
- Misses       1326     1330       +4     
+ Partials      572      558      -14     
Flag Coverage Δ
integration-tests 42.89% <0.00%> (-0.76%) ⬇️
python-3.10 63.14% <83.33%> (-0.60%) ⬇️
python-3.11 63.14% <83.33%> (-0.59%) ⬇️
python-3.12 63.15% <83.33%> (-0.58%) ⬇️
python-3.13 63.14% <83.33%> (-0.60%) ⬇️
python-3.14 63.15% <83.33%> (-0.58%) ⬇️
python-3.15 63.15% <83.33%> (-0.58%) ⬇️
python-filler-3.12 23.03% <13.33%> (-0.11%) ⬇️

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 90.41% <100.00%> (-2.26%) ⬇️
infrahub_sdk/protocols_base.py 74.63% <0.00%> (-0.55%) ⬇️

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

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

Labels

type/documentation Improvements or additions to documentation type/feature New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feature: Be able to update different attributes and relationships of a node with a dict

2 participants