From fb9b48f25983bd3f214c6defc1fec062c8c5b2d7 Mon Sep 17 00:00:00 2001 From: serversdown Date: Fri, 23 Oct 2026 16:22:28 -0400 Subject: [PATCH] feat(sfm): device_commands audit table -- one row per change attempt Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SyJ2ip3Krb6dtdv2cXua44 --- sfm/audit.py | 16 ++++++ sfm/database.py | 92 +++++++++++++++++++++++++++++++++++ sfm/server.py | 11 +++++ tests/test_device_commands.py | 41 ++++++++++++++++ 4 files changed, 160 insertions(+) create mode 100644 sfm/audit.py create mode 100644 tests/test_device_commands.py diff --git a/sfm/audit.py b/sfm/audit.py new file mode 100644 index 0000000..69084b0 --- /dev/null +++ b/sfm/audit.py @@ -0,0 +1,16 @@ +"""The SDM side of the device audit: DeviceAccess calls this sink, which writes +SeismoDb.device_commands. Kept here so sfm.device_access never imports the DB.""" +from __future__ import annotations + +from typing import Any, Callable + + +class DbAudit: + def __init__(self, get_db: Callable[[], Any]) -> None: + self._get_db = get_db + + def begin(self, **fields: Any) -> str: + return self._get_db().begin_device_command(**fields) + + def finish(self, command_id: str, **fields: Any) -> None: + self._get_db().finish_device_command(command_id, **fields) diff --git a/sfm/database.py b/sfm/database.py index b2ebf08..dbc31f5 100644 --- a/sfm/database.py +++ b/sfm/database.py @@ -34,6 +34,7 @@ Usage from __future__ import annotations import datetime +import json import logging import sqlite3 import uuid @@ -126,6 +127,24 @@ CREATE TABLE IF NOT EXISTS monitor_log ( CREATE INDEX IF NOT EXISTS idx_monitor_log_serial ON monitor_log(serial); CREATE INDEX IF NOT EXISTS idx_monitor_log_start ON monitor_log(start_time); CREATE INDEX IF NOT EXISTS idx_monitor_log_session ON monitor_log(session_id); + +CREATE TABLE IF NOT EXISTS device_commands ( + id TEXT PRIMARY KEY, + ts TEXT NOT NULL, -- when the attempt began (UTC ISO) + finished_ts TEXT, + serial TEXT NOT NULL, + series INTEGER NOT NULL, + address TEXT NOT NULL, + action TEXT NOT NULL, -- e.g. "start monitoring" + tier TEXT NOT NULL, -- "change" | "destructive" + request TEXT, -- JSON: parameters + the planned frames (hex) + ack TEXT, -- JSON: ack summary + verified TEXT, -- "ok" | "mismatch" | "not_checked" + outcome TEXT NOT NULL, -- "pending" | "sent" | "skipped" | "failed" + error TEXT, + caller TEXT -- "webapp" | "terra-view" | "script" | ... +); +CREATE INDEX IF NOT EXISTS idx_device_commands_serial ON device_commands(serial, ts); """ @@ -372,6 +391,79 @@ class SeismoDb: ).fetchall() return [dict(r) for r in rows] + # ── Device command audit ────────────────────────────────────────────────── + + def begin_device_command( + self, + *, + serial: str, + series: int, + address: str, + action: str, + tier: str, + request: dict, + caller: str, + ) -> str: + """Write a ``pending`` audit row BEFORE anything is sent. Returns its id.""" + cid = self._new_id() + ts = datetime.datetime.now(datetime.timezone.utc).isoformat() + with self._connect() as conn: + conn.execute( + """ + INSERT INTO device_commands + (id, ts, serial, series, address, action, tier, + request, outcome, caller) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?) + """, + (cid, ts, serial, series, address, action, tier, + json.dumps(request), caller), + ) + return cid + + def finish_device_command( + self, + command_id: str, + *, + outcome: str, + verified: Optional[str], + ack: Optional[dict], + error: Optional[str], + ) -> None: + """Record the result of a command begun with begin_device_command().""" + ts = datetime.datetime.now(datetime.timezone.utc).isoformat() + with self._connect() as conn: + conn.execute( + "UPDATE device_commands SET finished_ts=?, outcome=?, verified=?, " + "ack=?, error=? WHERE id=?", + (ts, outcome, verified, + json.dumps(ack) if ack is not None else None, + error, command_id), + ) + + def query_device_commands( + self, + serial: Optional[str] = None, + limit: int = 100, + ) -> list[dict]: + """Return audit rows, newest first, with request/ack parsed from JSON.""" + with self._connect() as conn: + if serial: + rows = conn.execute( + "SELECT * FROM device_commands WHERE serial=? " + "ORDER BY ts DESC LIMIT ?", (serial, limit)).fetchall() + else: + rows = conn.execute( + "SELECT * FROM device_commands ORDER BY ts DESC LIMIT ?", + (limit,)).fetchall() + out = [] + for r in rows: + d = dict(r) + for k in ("request", "ack"): + if d[k] is not None: + d[k] = json.loads(d[k]) + out.append(d) + return out + # ── Events ──────────────────────────────────────────────────────────────── def insert_events( diff --git a/sfm/server.py b/sfm/server.py index b228ff1..0d7c3e4 100644 --- a/sfm/server.py +++ b/sfm/server.py @@ -3080,6 +3080,17 @@ def db_sessions( return {"count": len(rows), "sessions": rows} +@app.get("/db/device_commands") +def db_device_commands( + serial: Optional[str] = Query(None, description="Filter by unit serial"), + limit: int = Query(100, description="Max rows to return"), +) -> dict: + """ + The audit trail of changes SFM attempted on units, newest first. + """ + return {"commands": _get_db().query_device_commands(serial, limit)} + + # ── Entry point ──────────────────────────────────────────────────────────────── if __name__ == "__main__": diff --git a/tests/test_device_commands.py b/tests/test_device_commands.py new file mode 100644 index 0000000..ac15255 --- /dev/null +++ b/tests/test_device_commands.py @@ -0,0 +1,41 @@ +"""The device_commands audit table: one row per change attempt, pending -> result.""" +from __future__ import annotations + +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from sfm.audit import DbAudit # noqa: E402 +from sfm.database import SeismoDb # noqa: E402 + +ROW = dict(serial="UM20147", series=4, address="serial:/dev/ttyACM0", + action="start monitoring", tier="change", + request={"plan": {"steps": [{"sub": "0x96"}]}}, caller="test") + + +def test_a_command_is_pending_until_finished(tmp_path): + db = SeismoDb(tmp_path / "s.db") + cid = db.begin_device_command(**ROW) + row = db.query_device_commands(serial="UM20147")[0] + assert (row["id"], row["outcome"], row["verified"]) == (cid, "pending", None) + assert row["request"]["plan"]["steps"][0]["sub"] == "0x96" + db.finish_device_command(cid, outcome="sent", verified="ok", + ack={"subs": ["0x69"]}, error=None) + row = db.query_device_commands(serial="UM20147")[0] + assert (row["outcome"], row["verified"], row["ack"]) == ("sent", "ok", {"subs": ["0x69"]}) + assert row["finished_ts"] + + +def test_the_table_survives_reopening(tmp_path): + SeismoDb(tmp_path / "s.db").begin_device_command(**ROW) + assert len(SeismoDb(tmp_path / "s.db").query_device_commands()) == 1 + + +def test_db_audit_is_a_thin_sink(tmp_path): + db = SeismoDb(tmp_path / "s.db") + audit = DbAudit(lambda: db) + cid = audit.begin(**ROW) + audit.finish(cid, outcome="failed", verified="mismatch", ack=None, error="unit reads idle") + row = db.query_device_commands()[0] + assert (row["outcome"], row["verified"], row["error"]) == ("failed", "mismatch", "unit reads idle")