refactor(backend): accept any peer sequence in RelationshipManager.update
Why
RelationshipManager.update()'s data parameter declared its collection member as an invariant
list[str | Node | dict | PeerWithRelationshipMetadata]. Because list is invariant in its element
type, a caller holding a narrower list[PeerWithRelationshipMetadata] could not pass it, which
forced a scoped suppression at the call site in core/manager.py:
# invariant list parameter; update() only reads data, so the narrower element type is safe
await rel_manager.update(db=db, data=rel_peers_with_metadata) # type: ignore[arg-type]
That suppression was not cosmetic: arg-type is not in infrahub.core.manager's
disable_error_code list, so the ignore was the only thing blinding mypy to that whole class of
error on a live code path. As the reviewer put it on #9977: "Since we are removing the warning, it's
always better to properly fix the warning."
Goal: type the parameter as a covariant, non-mutating Sequence so the suppression can go and
arg-type checking is restored there.
Non-goals: the unrelated # type: ignore[arg-type] on the **dict splat in core/manager.py,
and the one at menu/repository.py:105 (different root cause — a single CoreMenuItem | None, not a
list). Both deliberately untouched.
Tracking: INBOX-8 · originating review comment: https://github.com/opsmill/infrahub/pull/9977#discussion_r3614911929
What changed
Behavioral changes — one, and it fixes a latent bug rather than altering existing behaviour:
- Passing a non-
listsequence (e.g. atuple) of peers is now correctly iterated as a
collection. Previously such a value would have been wrapped as a single opaque "peer" and raised
ValidationError. No current caller passes a tuple, so nothing observable changes today.
Implementation notes:
-
data's collection member:list[...]→Sequence[...](covariant, exposes no mutators). -
The runtime narrowing was widened in step with the annotation. This is the part worth
reviewing: widening only the annotation would maketuplestatically valid while
isinstance(data, list)still routed it down the single-value branch — an annotation that accepts
an input the runtime mishandles is a worse contract than the invariantlistit replaced.# A str satisfies Sequence but stands for a single peer id, so it must not be iterated. if isinstance(data, str) or not isinstance(data, Sequence):strmust be excluded first:strsatisfiesSequencebut is a legitimate single-value
member of the union (a bare peer id). Without the carve-out, a peer id would be shredded into one
peer per character — silently, since_process_update_itemacceptsstritems.core/ipam/reconciler.py:168
is a live caller that passes exactly that, so this is not hypothetical. -
dictneeds no carve-out (aMappingis not aSequence), nor doNode,
PeerWithRelationshipMetadata, orNone. -
Sequencemoved fromtypingtocollections.abc(it appeared in only two places in the file),
sincetyping.Sequenceis deprecated and this change uses it as anisinstancetarget. The
neighbouringIterable/Iterator/Mappingimports were left alone on purpose — migrating
them would be an unrelated drive-by refactor. -
The
Sequenceannotation is only sound becauseupdate()genuinely never mutates the collection —
verified against the body, which iterateslist_dataonce and never appends/assigns. (The nearby
self._relationships.clear()acts on the manager's own collection, not the caller's argument.)
What stayed the same: no schema changes, no migrations, no GraphQL/REST contract changes, no auth
changes, no new dependencies, no CI changes, no generated files. Behaviour is unchanged for all seven
existing call sites.
How to review
Focus on one line — the widened narrowing in backend/infrahub/core/relationship/model.py. The
str-first ordering is what keeps peer ids from being iterated; everything else is mechanical.
The behaviour matrix this must preserve:
data | Before | After |
|---|---|---|
list[...] | collection | collection |
str | single | single (explicit carve-out) |
dict / Node / PeerWithRelationshipMetadata / None | single | single (not a Sequence) |
tuple[...] | single (wrong) | collection (fixed) |
How to test
# The type error is genuinely gone
uv run mypy backend/infrahub/core/manager.py backend/infrahub/core/relationship/model.py
# New + existing relationship-manager coverage
uv run pytest backend/tests/component/core/test_relationship_manager.py
# Behaviour preservation on the bare-str path (diff/merge + the live ipam caller)
uv run pytest backend/tests/component/core/diff/merge
uv run pytest backend/tests/functional/ipam/test_ipam_rebase_reconcile.py \
backend/tests/functional/ipam/test_ipam_merge_reconcile.py
Evidence from this branch:
| Check | Result |
|---|---|
mypy on both changed modules | clean |
mypy --show-error-codes backend (full, as CI runs it) | clean — 1597 files |
ruff check / ruff format --check | clean |
invoke format, invoke main.lint, uv lock --check | clean |
invoke backend.test-unit | 2151 passed |
test_relationship_manager.py | 36 passed (34 existing, unmodified assertions + 2 new) |
component/core/diff/merge | 27 passed |
functional/ipam rebase+merge reconcile | 4 passed, 1 skipped |
backend.validate-generated, schema.validate-graphqlschema, schema.validate-jsonschema, docs.validate | clean, no drift |
Two checks confirm the change is meaningfully tested rather than vacuously passing:
- Removing the ignore without the fix reproduces the original error — and mypy names the fix
itself:"List" is invariant … Consider using "Sequence" instead, which is covariant. - Reverting only the narrowing (keeping the
Sequenceannotation) makes the new tuple test fail
withValidationError: Invalid data provided to form a relationship, proving the latent bug is
real and the test catches it.
Not run locally: invoke backend.lint (the ty step) fails with 107 unresolved-import
diagnostics, but it fails identically on a pristine origin/develop tree in this environment and
none of the diagnostics touch the changed files — pre-existing and environment-caused, left to CI.
Frontend checks and docs.format were skipped (no frontend files changed; markdownlint-cli2 not
installed locally).
Impact & rollout
- Backward compatibility: fully compatible. The signature is relaxed, so every existing caller
still type-checks and behaves identically. No migration steps. - Performance: negligible — one extra O(1)
isinstanceperupdate()call. - Config/env changes: none.
- Deployment notes: safe to deploy.
Checklist
- Tests added/updated
- Changelog entry added (
changelog/+relationship-update-sequence-param.housekeeping.md) - External docs updated (if user-facing or ops-facing change) — n/a, internal typing change
- Internal .md docs updated — spec/plan/research under
dev/specs/005-manager-update-sequence-type/ - I have reviewed AI generated content
🤖 Generated with Claude Code