refactor(backend): accept any peer sequence in RelationshipManager.update

Merged
SA
3mo ago
+43-5

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-list sequence (e.g. a tuple) 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 make tuple statically 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 invariant list it 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):
    

    str must be excluded first: str satisfies Sequence but 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_item accepts str items. core/ipam/reconciler.py:168
    is a live caller that passes exactly that, so this is not hypothetical.

  • dict needs no carve-out (a Mapping is not a Sequence), nor do Node,
    PeerWithRelationshipMetadata, or None.

  • Sequence moved from typing to collections.abc (it appeared in only two places in the file),
    since typing.Sequence is deprecated and this change uses it as an isinstance target. The
    neighbouring Iterable/Iterator/Mapping imports were left alone on purpose — migrating
    them would be an unrelated drive-by refactor.

  • The Sequence annotation is only sound because update() genuinely never mutates the collection —
    verified against the body, which iterates list_data once 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:

dataBeforeAfter
list[...]collectioncollection
strsinglesingle (explicit carve-out)
dict / Node / PeerWithRelationshipMetadata / Nonesinglesingle (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:

CheckResult
mypy on both changed modulesclean
mypy --show-error-codes backend (full, as CI runs it)clean — 1597 files
ruff check / ruff format --checkclean
invoke format, invoke main.lint, uv lock --checkclean
invoke backend.test-unit2151 passed
test_relationship_manager.py36 passed (34 existing, unmodified assertions + 2 new)
component/core/diff/merge27 passed
functional/ipam rebase+merge reconcile4 passed, 1 skipped
backend.validate-generated, schema.validate-graphqlschema, schema.validate-jsonschema, docs.validateclean, no drift

Two checks confirm the change is meaningfully tested rather than vacuously passing:

  1. 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.
  2. Reverting only the narrowing (keeping the Sequence annotation) makes the new tuple test fail
    with ValidationError: 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) isinstance per update() 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