Coverage for audit/postgres_audit.py: 100%

33 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-22 12:55 +0000

1"""Read-only query helpers over the audit_log table (development/Problems.md #42). 

2 

3Shared by `aq audit-log` (aq_cli.py) and monitoring/api_server.py's 

4`GET /api/audit-log` route - one place owns the SELECT shape so the CLI and 

5the webui can never drift apart on what a row looks like. Write path lives 

6in audit/postgres_worker.py (the Redis-Stream-draining worker); this module 

7never inserts anything. 

8""" 

9 

10from __future__ import annotations 

11 

12from datetime import datetime, timezone 

13from typing import Any 

14 

15from .hash_chain import canonical_timestamp 

16 

17_COLUMNS = ( 

18 "event_id", 

19 "created_at", 

20 "event_type", 

21 "actor", 

22 "prev_hash", 

23 "hash", 

24 "payload", 

25) 

26 

27 

28def _row_to_dict(row: tuple) -> dict[str, Any]: 

29 out = dict(zip(_COLUMNS, row, strict=False)) 

30 out["created_at"] = canonical_timestamp(out["created_at"]) # the text the row was hashed as (Problems #339) 

31 return out 

32 

33 

34def fetch_recent_events( 

35 conn, 

36 event_type: str | None = None, 

37 since: datetime | None = None, 

38 limit: int = 100, 

39) -> list[dict]: 

40 """Newest-first page of audit_log rows, optionally filtered. `since` 

41 defaults to the Unix epoch (no filter) rather than requiring callers to 

42 special-case None, matching retraining/postgres_registry.py's 

43 fetch_recent_retraining_events() convention.""" 

44 if since is None: 

45 since = datetime.fromtimestamp(0, tz=timezone.utc) 

46 query = f"SELECT {', '.join(_COLUMNS)} FROM audit_log WHERE created_at > %(since)s" 

47 params: dict[str, Any] = {"since": since, "limit": limit} 

48 if event_type is not None: 

49 query += " AND event_type = %(event_type)s" 

50 params["event_type"] = event_type 

51 query += " ORDER BY id DESC LIMIT %(limit)s;" 

52 rows = _select(conn, query, params) 

53 return [_row_to_dict(row) for row in rows] 

54 

55 

56def _select(conn, query: str, params: dict | None = None) -> list: 

57 """Run a read; a database no audit worker has written to has no `audit_log` table yet (Problems #339, found on a real Postgres), which reads as no entries, not a crash. 

58 Any other database error still raises.""" 

59 try: 

60 with conn.cursor() as cur: 

61 cur.execute(query, params) if params is not None else cur.execute(query) 

62 return cur.fetchall() 

63 except Exception as exc: 

64 if type(exc).__name__ != "UndefinedTable": 

65 raise 

66 conn.rollback() 

67 return [] 

68 

69 

70def fetch_all_events_ordered(conn) -> list[dict]: 

71 """Every audit_log row, oldest-first - the shape audit.hash_chain.verify_chain() 

72 expects. Only ever used by `aq audit-log --verify`; not paginated 

73 (verification is meaningless over a partial chain).""" 

74 rows = _select(conn, f"SELECT {', '.join(_COLUMNS)} FROM audit_log ORDER BY id ASC;") 

75 return [_row_to_dict(row) for row in rows]