fix(sdk): merge re-fetched nodes into the client store instead of overwriting

Draft
OG
22d ago
+3788-80

Why

Querying the same node more than once silently dropped data from the client store. The store keyed objects by a random per-object id, so the latest query fully replaced the stored node: a shallow re-fetch (for example a node returned as a related node of another query) lost attributes and relationships loaded by an earlier, deeper query, and left duplicate entries behind (IHS-138).

Closes #413

What changed

Behavioral changes (all called out in the changelog and the store guide):

  • The store keeps one object per node UUID and merges each fetch into it field by field: fields carried by the new fetch overwrite the stored value (even to empty or None), fields it did not request keep their stored value, and cardinality-many member lists are replaced, never unioned. Fixes the reported bug and the symmetric attribute case.
  • Queries return per-query snapshots; the store holds the merged canonical copy. client.get(id) is client.store.get(id) is no longer true after a merge (they still compare equal), and store.get() hands out one living object per node that later fetches update in place. RelatedNode.fetch() caches that store object as the peer.
  • Merging only happens when it is safe. The stored entry is replaced wholesale instead, which is what every write did before 1.24.0, when:
    • the incoming copy was fetched at a different timestamp (at, or live) than the stored one, so data from two points in time is never blended;
    • the stored node has an unsaved local edit on a field the incoming copy carries. The edit stays on the object the caller holds, and the store moves on to server state;
    • the incoming node was built locally (client.create(), with or without an explicit id) rather than returned by a query;
    • the same UUID arrives under a different kind (ConvertObjectType).
  • Every write still populates the store, whatever its at, so .peer keeps resolving for scripts that mix live and historical queries.
  • A successful save()/create()/update() resets in-memory mutation tracking, so saved fields merge with later fetches instead of counting as pending local edits forever. The payload markers stay, so a later save still re-asserts an explicit clear or peer set.
  • Replace remains available on request: per call via merge=False on get/all/filters and store.set(), globally via the new Config.store_merge (INFRAHUB_STORE_MERGE), which restores the pre-1.24 behaviour.

Implementation notes:

  • Every field type carries an is_fetched presence signal (key-presence in the response, so fetched-but-empty is distinguishable from not-queried) and owns its own _merge: Attribute, RelatedNodeBase, RelationshipManagerBase.
  • The merge-or-replace rule lives in one place, NodeStoreBranch._can_merge, and the store records the timestamp per node.
  • Store indexes use reverse maps so set()/_evict() stay O(1) per call, and the presence sets are interned (objects from the same query shape share one frozenset).
  • Design and decision history: dev/specs/ihs-138-store-merge/ (plan sections 12 and 13 and decisions D1-D10 record what changed during implementation and review, and why).

What stayed the same: save payloads are unaffected by the presence flags (serialization keys on mutation, never on presence); merge=False scope is the node entry only; the store remains partitioned by branch.

Suggested review order

  1. infrahub_sdk/node/attribute.py, related_node.py, relationship.py - presence flags and per-type _merge
  2. infrahub_sdk/node/node.py - node-level _merge, raw payload merge, _reset_mutation_tracking
  3. infrahub_sdk/store.py - _can_merge, merge/replace paths, per-node timestamps, reverse indexes
  4. infrahub_sdk/client.py, config.py - merge= threading and store_merge
  5. tests/unit/sdk/test_store_merge.py (126 tests) and tests/integration/test_node.py::TestInfrahubNode::test_store_merge_against_real_responses
  6. Docs: docs/docs/python-sdk/guides/store.mdx, changelog entries

How to review

  • Extra scrutiny welcome on the judgement calls: the mutation-tracking reset after save (D7 - correct, but it changes what a second update() sends), the replace-instead-of-refuse rules (D10 - an earlier version refused mismatching writes with a warning and let unsaved edits win, which broke .peer resolution for mixed live/historical scripts and kept abandoned edits alive in long-lived clients such as Infrahub workers), and the same-peer identity gating in RelatedNodeBase._merge (D8).
  • Generated/mechanical: docs/docs/python-sdk/reference/config.mdx and docs/docs/python-sdk/sdk_ref/** are regenerated; the client.py churn is mostly the merge= parameter threaded through all overloads (async and sync).

Rebase onto infrahub-develop

The branch was rebased onto infrahub-develop after it had moved 475 commits ahead. Three files conflicted: infrahub_sdk/config.py (both sides inserted into the same field block, resolved by keeping store_merge alongside the rewritten timeout and the new connect_timeout) and two generated docs files, resolved by regenerating. The source delta is byte-for-byte identical to the pre-rebase branch, so nothing was lost or silently altered in the merge.

Two upstream changes landed in the window and needed a response, both in the final commit:

  • ty 0.0.74 now rejects the dual-flavour test pattern, where the client, the store and the node class are correlated unions the type system cannot tie together. tests/unit/sdk/test_store_merge.py gets a [[tool.ty.overrides]] entry for invalid-argument-type, matching how test_store.py and the other dual-client test files are already handled. This is the one new suppression in the PR.
  • 1.23.0 through 1.23.2 shipped without this behaviour, so the guide, the changelog and the store_merge description now name 1.24.0.

Worth a look while reviewing: _reset_mutation_tracking() (D7) now sits in _process_mutation_result next to the per-request priority forwarding that upstream added to the same method. The two are independent, but they read together.

How to test

uv run pytest tests/unit/sdk/test_store_merge.py -v   # feature suite (126 tests)
uv run pytest tests/unit/                             # full unit suite
uv run pytest tests/integration/test_node.py          # includes the real-server store merge test
uv run invoke lint-code                               # ruff, ty, mypy - all clean

The original reproduction from #413 (deep fetch of an interface, then client.all over circuit endpoints, then store.get(interface.id).device) now returns the device instead of raising AttributeError.

Impact & rollout

  • Backward compatibility: semver-minor shipped as a bug fix with an explicit opt-out (store_merge=False restores replace semantics). The observable behaviour changes are enumerated in changelog/+store-merge-behaviour.changed.md; no API removals, populate_store keeps its bool = True signature. Wherever merging would be unsafe the store falls back to the pre-1.24 replace.
  • Performance: store population measured linear after the reverse-index work (30k inserts 0.03s; the naive implementation was quadratic at 4.9s) and presence-set interning keeps memory flat (10k attributes: 4.2 MB vs 11.4 MB without). Merging every related-node copy costs about 6 us per copy.
  • Config/env changes: new Config.store_merge / INFRAHUB_STORE_MERGE (default True).
  • Deployment notes: targets SDK 1.24.0. Release gate before tagging: run the Ansible collection and infrahubctl integration suites against the pre-release.

Checklist

  • Tests added/updated
  • Changelog entry added (changelog/413.fixed.md, changelog/+store-merge-behaviour.changed.md)
  • External docs updated (if user-facing or ops-facing change)
  • Internal .md docs updated (internal knowledge and AI code tools knowledge)

Summary by cubic

Fixes IHS-138: the SDK store now merges re-fetched nodes by UUID instead of overwriting, preventing data loss and duplicate entries when a shallow re-fetch lands on a previously stored node. Adds per-call merge controls and a global Config.store_merge opt-out.

Bug Fixes

  • Merge-by-field on re-fetch: fetched fields overwrite, unfetched fields stay, cardinality-many lists are replaced, and peers shared across fetches merge per-peer so edge properties survive.
  • Presence signals (Attribute.is_fetched, RelatedNode.is_fetched, RelationshipManagerBase.is_fetched) distinguish fetched-empty from not-requested, so a null cardinality-many response empties the stored members.
  • One canonical store object per UUID; queries return per-query snapshots and merged payloads are deep-copied so the stored baseline never aliases a snapshot; local unsaved edits win and saves reset mutation tracking while keeping sticky payload markers.
  • Writes at a different timestamp, nodes with an unsaved edit on a field the incoming copy carries, and nodes built locally by client.create() replace the stored entry instead of merging; RelatedNode.fetch() caches the store object.
  • Merge is default; per-call merge is appended to method signatures and global Config.store_merge (INFRAHUB_STORE_MERGE) opts out; reverse indexes keep set() O(1).

Migration

  • Default behavior changes in SDK 1.24.0: store merges re-fetches. Use merge=False per call or set Config.store_merge=False to restore full replace semantics.