Skip to content

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

fix(scan): keep documents of a device approved while pending is cleared

Pouzor696af7fc9672
diff --git a/backend/app/api/routes/scan.py b/backend/app/api/routes/scan.py
index a563816..b6d970f 100644
--- a/backend/app/api/routes/scan.py
+++ b/backend/app/api/routes/scan.py
@@ -14,6 +14,7 @@ from app.core.config import settings
from app.db.database import AsyncSessionLocal, get_db
from app.db.models import (
Design,
+ Document,
Edge,
InventoryDevice,
InventoryDeviceLink,
@@ -541,10 +542,16 @@ async def clear_pending(
_: str = Depends(get_current_user),
) -> dict[str, int]:
from sqlalchemy import delete as sa_delete
- pending_ids = (
- await db.execute(select(InventoryDevice.id).where(InventoryDevice.status == "pending"))
- ).scalars().all()
- await unlink_documents(db, device_ids=list(pending_ids))
+ from sqlalchemy import update as sa_update
+
+ # Unlink by subquery, not by a list of ids read beforehand: a device approved
+ # between that read and the delete would lose its documents without being
+ # deleted. The UPDATE takes SQLite's write lock, so the set it unlinks is the
+ # set the DELETE removes. (#444)
+ pending = select(InventoryDevice.id).where(InventoryDevice.status == "pending")
+ await db.execute(
+ sa_update(Document).where(Document.device_id.in_(pending)).values(device_id=None)
+ )
result = await db.execute(sa_delete(InventoryDevice).where(InventoryDevice.status == "pending"))
await db.commit()
return {"deleted": result.rowcount}
diff --git a/backend/tests/scan/test_scan_routes.py b/backend/tests/scan/test_scan_routes.py
index 8bf5a3c..9d63153 100644
--- a/backend/tests/scan/test_scan_routes.py
+++ b/backend/tests/scan/test_scan_routes.py
@@ -565,3 +565,74 @@ async def test_get_run_returns_status(client: AsyncClient, headers, pending_devi
async def test_get_run_unknown_id_404(client: AsyncClient, headers):
res = await client.get(f"/api/v1/scan/runs/{uuid.uuid4()}", headers=headers)
assert res.status_code == 404
+
+
+async def test_clear_pending_deletes_pending_and_unlinks_their_documents(client: AsyncClient, headers, db_session):
+ from sqlalchemy import select
+
+ from app.db.models import Document
+
+ pending = InventoryDevice(id=str(uuid.uuid4()), ip="10.0.0.1", status="pending")
+ approved = InventoryDevice(id=str(uuid.uuid4()), ip="10.0.0.2", status="approved")
+ db_session.add_all([pending, approved])
+ await db_session.flush()
+ pending_doc = Document(title="p", slug="p", device_id=pending.id, body="# p")
+ approved_doc = Document(title="a", slug="a", device_id=approved.id, body="# a")
+ db_session.add_all([pending_doc, approved_doc])
+ await db_session.commit()
+
+ res = await client.delete("/api/v1/scan/pending", headers=headers)
+ assert res.status_code == 200
+ assert res.json() == {"deleted": 1}
+
+ approved_id, pending_doc_id, approved_doc_id = approved.id, pending_doc.id, approved_doc.id
+ db_session.expire_all()
+ ids = (await db_session.execute(select(InventoryDevice.id))).scalars().all()
+ assert ids == [approved_id]
+ assert (await db_session.get(Document, pending_doc_id)).device_id is None
+ assert (await db_session.get(Document, approved_doc_id)).device_id == approved_id
+
+
+async def test_clear_pending_keeps_documents_of_a_device_approved_mid_clear(client: AsyncClient, headers, db_session):
+ """#444 — an approval landing between the moment the pending set is read and
+ the moment its documents are unlinked must not orphan the approved device's
+ documents. The approval is injected right before the documents UPDATE."""
+ from sqlalchemy import event, select
+
+ from app.db.models import Document
+
+ device = InventoryDevice(id=str(uuid.uuid4()), ip="10.0.0.3", status="pending")
+ db_session.add(device)
+ await db_session.flush()
+ doc = Document(title="d", slug="d", device_id=device.id, body="# d")
+ db_session.add(doc)
+ await db_session.commit()
+ device_id, doc_id = device.id, doc.id
+
+ fired = False
+
+ def approve_before_unlink(conn, cursor, statement, parameters, context, executemany):
+ nonlocal fired
+ if not fired and statement.lstrip().upper().startswith("UPDATE DOCUMENTS"):
+ fired = True
+ cursor.execute(
+ "UPDATE device_inventory SET status = 'approved' WHERE id = ?", (device_id,)
+ )
+
+ sync_engine = db_session.bind.sync_engine
+ event.listen(sync_engine, "before_cursor_execute", approve_before_unlink)
+ try:
+ res = await client.delete("/api/v1/scan/pending", headers=headers)
+ finally:
+ event.remove(sync_engine, "before_cursor_execute", approve_before_unlink)
+
+ assert fired
+ assert res.json() == {"deleted": 0}
+ db_session.expire_all()
+ status = (
+ await db_session.execute(select(InventoryDevice.status).where(InventoryDevice.id == device_id))
+ ).scalar_one()
+ assert status == "approved"
+ assert (await db_session.get(Document, doc_id)).device_id == device_id