Coverage for src/copytrading_engine/control/sqlite.py: 85%

43 statements  

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

1"""The control audit trail in `application.db`, bounded to the newest entries.""" 

2 

3import datetime as dt 

4import sqlite3 

5from pathlib import Path 

6from typing import Final 

7 

8from copytrading_engine.control.audit import Actor, AuditEntry 

9from copytrading_engine.control.policy import Tier 

10from copytrading_engine.shared.sqlite import SchemaComponent, SQLiteUnit, ensure_schema 

11 

12AUDIT_RETENTION: Final = 10_000 

13_ACTORS: Final[dict[object, Actor]] = {"agent": "agent", "owner": "owner"} 

14_TIERS: Final[dict[object, Tier | None]] = { 

15 None: None, 

16 "read": "read", 

17 "safer": "safer", 

18 "approval": "approval", 

19} 

20 

21CONTROL_AUDIT_SCHEMA = SchemaComponent( 

22 "control_audit", 

23 1, 

24 """ 

25CREATE TABLE IF NOT EXISTS control_audit ( 

26 seq INTEGER PRIMARY KEY AUTOINCREMENT, 

27 at TEXT NOT NULL, 

28 actor TEXT NOT NULL CHECK (actor IN ('agent','owner')), 

29 caller_pid INTEGER, 

30 caller_path TEXT, 

31 operation TEXT NOT NULL, 

32 tier TEXT CHECK (tier IS NULL OR tier IN ('read','safer','approval')), 

33 outcome TEXT NOT NULL, 

34 proposal_id TEXT 

35); 

36""", 

37) 

38 

39 

40class SQLiteControlAudit: 

41 def __init__(self, unit: SQLiteUnit, retention: int = AUDIT_RETENTION) -> None: 

42 if retention < 1: 42 ↛ 43line 42 didn't jump to line 43 because the condition on line 42 was never true

43 raise ValueError("The audit trail must keep at least one entry") 

44 self._unit = unit 

45 self._retention = retention 

46 

47 @classmethod 

48 async def open(cls, path: Path, retention: int = AUDIT_RETENTION) -> SQLiteControlAudit: 

49 unit = await SQLiteUnit.open(path) 

50 try: 

51 await unit.run(lambda db: ensure_schema(db, CONTROL_AUDIT_SCHEMA), write=True) 

52 return cls(unit, retention) 

53 except BaseException: 

54 await unit.close() 

55 raise 

56 

57 async def record(self, entry: AuditEntry) -> None: 

58 def write(db: sqlite3.Connection) -> None: 

59 db.execute( 

60 "INSERT INTO control_audit" 

61 "(at,actor,caller_pid,caller_path,operation,tier,outcome,proposal_id)" 

62 " VALUES (?,?,?,?,?,?,?,?)", 

63 ( 

64 entry.at.isoformat(), 

65 entry.actor, 

66 entry.caller_pid, 

67 entry.caller_path, 

68 entry.operation, 

69 entry.tier, 

70 entry.outcome, 

71 entry.proposal_id, 

72 ), 

73 ) 

74 db.execute( 

75 "DELETE FROM control_audit WHERE seq <= (SELECT MAX(seq) FROM control_audit) - ?", 

76 (self._retention,), 

77 ) 

78 

79 await self._unit.run(write, write=True) 

80 

81 async def recent(self, limit: int) -> tuple[AuditEntry, ...]: 

82 def read(db: sqlite3.Connection) -> tuple[AuditEntry, ...]: 

83 rows = db.execute( 

84 "SELECT at,actor,caller_pid,caller_path,operation,tier,outcome,proposal_id" 

85 " FROM control_audit ORDER BY seq DESC LIMIT ?", 

86 (limit,), 

87 ).fetchall() 

88 return tuple(_entry(row) for row in rows) 

89 

90 return await self._unit.run(read) 

91 

92 async def close(self) -> None: 

93 await self._unit.close() 

94 

95 

96def _entry(row: tuple[object, ...]) -> AuditEntry: 

97 at, actor, pid, path, operation, tier, outcome, proposal_id = row 

98 if not ( 98 ↛ 108line 98 didn't jump to line 108 because the condition on line 98 was never true

99 isinstance(at, str) 

100 and actor in _ACTORS 

101 and (pid is None or isinstance(pid, int)) 

102 and (path is None or isinstance(path, str)) 

103 and isinstance(operation, str) 

104 and tier in _TIERS 

105 and isinstance(outcome, str) 

106 and (proposal_id is None or isinstance(proposal_id, str)) 

107 ): 

108 raise ValueError("Stored control audit entry is invalid") 

109 return AuditEntry( 

110 at=dt.datetime.fromisoformat(at), 

111 actor=_ACTORS[actor], 

112 caller_pid=pid, 

113 caller_path=path, 

114 operation=operation, 

115 tier=_TIERS[tier], 

116 outcome=outcome, 

117 proposal_id=proposal_id, 

118 )