Skip to content

Self-hosted homelab infrastructure visualizer — interactive network diagram with live status monitoring

fix(unifi): merge a client into the row another source already owns

Pouzor5bd0c7935d5f
diff --git a/backend/app/api/routes/unifi.py b/backend/app/api/routes/unifi.py
index 6ed8e61..33c475a 100644
--- a/backend/app/api/routes/unifi.py
+++ b/backend/app/api/routes/unifi.py
@@ -179,6 +179,21 @@ async def save_unifi_config(
async def _find_existing(
db: AsyncSession, ieee: str, mac: str | None
) -> InventoryDevice | None:
+ """The inventory row this UniFi record *is*, in precedence order.
+
+ 1. The synthetic ``unifi-{mac}`` ieee, for a row a previous import created.
+ 2. Else the MAC. A MAC is an identity — the same rule the Proxmox import
+ states — so it matches a row another source already claimed, which is
+ the point: a container found by an IP scan and by Proxmox, then reported
+ by the controller as a client, is one machine and must stay one row.
+
+ Restricting the MAC match to rows with no ieee_address, as this did, filed
+ every such machine twice, because the Proxmox import gives its rows a
+ ``pve-…`` ieee. It guarded against nothing: the mesh imports never set
+ ``mac``, so a MAC match cannot reach a Zigbee or Z-Wave row.
+
+ Oldest row wins, so a re-import is stable when two rows somehow share a MAC.
+ """
row = (
await db.execute(select(InventoryDevice).where(InventoryDevice.ieee_address == ieee))
).scalars().first()
@@ -187,15 +202,20 @@ async def _find_existing(
if mac:
row = (
await db.execute(
- select(InventoryDevice).where(
- InventoryDevice.mac == mac,
- InventoryDevice.ieee_address.is_(None),
- )
+ select(InventoryDevice)
+ .where(InventoryDevice.mac == mac)
+ .order_by(InventoryDevice.discovered_at, InventoryDevice.id)
)
).scalars().first()
return row
+def _owns(row: InventoryDevice) -> bool:
+ """True when UniFi is the only source that has ever seen this row."""
+ sources = {s for s in (row.discovery_sources or []) if s}
+ return bool(sources) and sources <= {SOURCE_INFRA, SOURCE_CLIENT}
+
+
async def _persist_devices(
db: AsyncSession,
devices: list[dict[str, Any]],
@@ -244,11 +264,23 @@ async def _persist_devices(
existing.ieee_address = existing.ieee_address or ieee
existing.ip = ip or existing.ip
existing.mac = existing.mac or mac
- existing.hostname = dev.get("hostname") or existing.hostname
- existing.friendly_name = dev.get("label") or existing.friendly_name
- existing.suggested_type = dev.get("type") or existing.suggested_type
- existing.vendor = dev.get("vendor") or existing.vendor
- existing.model = dev.get("model") or existing.model
+ # A row another source owns keeps its own description: the
+ # controller knows a client only as a name and a MAC, so letting it
+ # win would retype a Proxmox LXC as a plain "computer" and replace
+ # the hostname the guest reports with the controller's label. On a
+ # row UniFi created, a re-sync is meant to refresh those.
+ if _owns(existing):
+ existing.hostname = dev.get("hostname") or existing.hostname
+ existing.friendly_name = dev.get("label") or existing.friendly_name
+ existing.suggested_type = dev.get("type") or existing.suggested_type
+ existing.vendor = dev.get("vendor") or existing.vendor
+ existing.model = dev.get("model") or existing.model
+ else:
+ existing.hostname = existing.hostname or dev.get("hostname")
+ existing.friendly_name = existing.friendly_name or dev.get("label")
+ existing.suggested_type = existing.suggested_type or dev.get("type")
+ existing.vendor = existing.vendor or dev.get("vendor")
+ existing.model = existing.model or dev.get("model")
# Status preserved — an approved device stays approved.
# Only reset hidden devices (they came back visible in UniFi).
if existing.status == "hidden":
diff --git a/backend/tests/test_unifi_router.py b/backend/tests/test_unifi_router.py
index 9f4ae22..bb4834e 100644
--- a/backend/tests/test_unifi_router.py
+++ b/backend/tests/test_unifi_router.py
@@ -85,7 +85,15 @@ async def test_find_existing_by_ieee(db_session: AsyncSession) -> None:
assert found is not None
assert found.ieee_address == "unifi-aa:bb:cc:dd:ee:ff"
@pytest.mark.asyncio
-async def test_find_existing_mac_not_stolen_from_ieee_device(db_session: AsyncSession) -> None:
+async def test_find_existing_matches_a_mac_on_a_claimed_row(db_session: AsyncSession) -> None:
+ """A MAC is an identity, so it reaches a row another source already owns.
+
+ This asserted the opposite until the duplicate it caused showed up: the
+ Proxmox import gives every guest a `pve-…` ieee_address, so skipping rows
+ that have one filed each such machine a second time when the controller
+ reported it as a client. The mesh imports never set `mac`, so no Zigbee or
+ Z-Wave row is reachable this way.
+ """
row = InventoryDevice(
ieee_address="scan-device-xyz",
mac="11:22:33:44:55:66",
@@ -96,7 +104,8 @@ async def test_find_existing_mac_not_stolen_from_ieee_device(db_session: AsyncSe
await db_session.commit()
found = await _find_existing(db_session, "unifi-11:22:33:44:55:66", "11:22:33:44:55:66")
- assert found is None
+ assert found is not None
+ assert found.ieee_address == "scan-device-xyz"
# --- approved status preserved ---------------------------------------------
@pytest.mark.asyncio
@@ -241,3 +250,154 @@ async def test_an_ip_scan_row_gains_the_unifi_client_source(
rows = (await db_session.execute(select(InventoryDevice))).scalars().all()
assert len(rows) == 1
assert rows[0].discovery_sources == ["arp", "unifi-client"]
+
+
+# --- dedup against rows another source already owns -------------------------
+
+async def test_merges_into_a_proxmox_row_with_the_same_mac(
+ db_session: AsyncSession,
+) -> None:
+ """Regression: a Proxmox LXC reported as a UniFi client landed twice.
+
+ The MAC fallback skipped rows that had an ieee_address, and every Proxmox
+ guest has one (`pve-…`), so the controller's view of the same machine
+ became a second inventory entry.
+ """
+ row = InventoryDevice(
+ ieee_address="pve-proxmox-129",
+ ip="192.168.1.20",
+ mac="bc:24:11:8d:26:ed",
+ hostname="paperless-ngx",
+ friendly_name="Paperless",
+ suggested_type="lxc",
+ vendor="Proxmox VE",
+ model="LXC",
+ status="approved",
+ discovery_source="proxmox",
+ discovery_sources=["arp", "proxmox"],
+ )
+ db_session.add(row)
+ await db_session.commit()
+
+ await _persist_devices(db_session, [{
+ "ieee_address": "unifi-bc:24:11:8d:26:ed",
+ "mac": "bc:24:11:8d:26:ed",
+ "ip": None,
+ "hostname": "Paperless",
+ "label": "Paperless",
+ "type": "computer",
+ "vendor": "Proxmox Server Solutions GmbH",
+ "properties": [],
+ "source": "unifi-client",
+ }])
+
+ rows = (await db_session.execute(select(InventoryDevice))).scalars().all()
+ assert len(rows) == 1, "the UniFi client must merge, not create a second row"
+ merged = rows[0]
+ assert merged.discovery_sources == ["arp", "proxmox", "unifi-client"]
+ # The guest keeps its identity and its richer description.
+ assert merged.ieee_address == "pve-proxmox-129"
+ assert merged.suggested_type == "lxc"
+ assert merged.hostname == "paperless-ngx"
+ assert merged.ip == "192.168.1.20"
+ assert merged.status == "approved"
+
+
+async def test_merging_twice_changes_nothing_more(db_session: AsyncSession) -> None:
+ row = InventoryDevice(
+ ieee_address="pve-proxmox-129",
+ mac="bc:24:11:8d:26:ed",
+ suggested_type="lxc",
+ status="pending",
+ discovery_source="proxmox",
+ discovery_sources=["proxmox"],
+ )
+ db_session.add(row)
+ await db_session.commit()
+
+ dev = {
+ "ieee_address": "unifi-bc:24:11:8d:26:ed",
+ "mac": "bc:24:11:8d:26:ed",
+ "ip": "192.168.1.20",
+ "hostname": "Paperless",
+ "label": "Paperless",
+ "type": "computer",
+ "vendor": "Ubiquiti",
+ "properties": [],
+ "source": "unifi-client",
+ }
+ first = await _persist_devices(db_session, [dev])
+ second = await _persist_devices(db_session, [dev])
+
+ assert (first.pending_created, second.pending_created) == (0, 0)
+ assert (first.pending_updated, second.pending_updated) == (1, 1)
+ rows = (await db_session.execute(select(InventoryDevice))).scalars().all()
+ assert len(rows) == 1
+ assert rows[0].discovery_sources == ["proxmox", "unifi-client"]
+
+
+async def test_a_unifi_owned_row_is_still_refreshed(db_session: AsyncSession) -> None:
+ """A re-sync must keep updating rows UniFi created — a rename, a new model."""
+ row = InventoryDevice(
+ ieee_address="unifi-00:27:22:e0:00:02",
+ mac="00:27:22:e0:00:02",
+ hostname="USW Ultra",
+ friendly_name="USW Ultra",
+ suggested_type="switch",
+ model="USM8P",
+ status="pending",
+ discovery_source="unifi",
+ discovery_sources=["unifi"],
+ )
+ db_session.add(row)
+ await db_session.commit()
+
+ await _persist_devices(db_session, [{
+ "ieee_address": "unifi-00:27:22:e0:00:02",
+ "mac": "00:27:22:e0:00:02",
+ "ip": "192.168.1.101",
+ "hostname": "Switch Garage",
+ "label": "Switch Garage",
+ "type": "switch",
+ "vendor": "Ubiquiti",
+ "model": "USM8P",
+ "properties": [],
+ "source": "unifi",
+ }])
+
+ updated = (await db_session.execute(select(InventoryDevice))).scalars().first()
+ assert updated is not None
+ assert updated.friendly_name == "Switch Garage"
+ assert updated.ip == "192.168.1.101"
+
+
+async def test_the_oldest_row_wins_when_two_share_a_mac(
+ db_session: AsyncSession,
+) -> None:
+ """Without an order the database picked either row, so a re-import drifted."""
+ from datetime import datetime, timezone
+
+ older = InventoryDevice(
+ ieee_address="pve-proxmox-1",
+ mac="bc:24:11:8d:26:ed",
+ status="pending",
+ discovery_sources=["proxmox"],
+ discovered_at=datetime(2026, 1, 1, tzinfo=timezone.utc),
+ )
+ newer = InventoryDevice(
+ ieee_address="pve-proxmox-2",
+ mac="bc:24:11:8d:26:ed",
+ status="pending",
+ discovery_sources=["proxmox"],
+ discovered_at=datetime(2026, 6, 1, tzinfo=timezone.utc),
+ )
+ db_session.add_all([newer, older])
+ await db_session.commit()
+
+ found = await _find_existing(db_session, "unifi-bc:24:11:8d:26:ed", "bc:24:11:8d:26:ed")
+ assert found is not None
+ assert found.ieee_address == "pve-proxmox-1"