Coverage for audit/postgres_worker.py: 100%

224 statements  

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

1"""PostgreSQL persistence worker for the audit log (development/Problems.md #42). 

2 

3Reads from the Redis Stream ``aether:audit`` via XREADGROUP consumer group 

4semantics (identical mechanics to experience/postgres_worker.py) and 

5batch-inserts each event into the ``audit_log`` table, computing each row's 

6hash-chain link (audit/hash_chain.py) at insert time - chaining happens in 

7durable-write order, not push order, so out-of-order Redis delivery can 

8never produce a chain that doesn't match on-disk row order. 

9 

10Design decisions (mirrors experience/postgres_worker.py exactly): 

11- Sync-only: no asyncio; event volume does not justify async complexity. 

12- Embedded DDL: no Alembic; ensure_schema() is idempotent and called on startup. 

13- ON CONFLICT (event_id) DO NOTHING: safe idempotent re-delivery. 

14- Messages are NOT acked until PG commit succeeds — safe at-least-once delivery. 

15- Malformed JSON → dead-letter stream, immediate XACK, log WARNING. 

16- _redis_client and _pg_conn constructor params for test injection. 

17""" 

18 

19from __future__ import annotations 

20 

21import argparse 

22import json 

23import logging 

24import os 

25import time 

26from typing import Any 

27 

28from execution.secrets import redact_url 

29from execution.secrets_io import secret_env 

30 

31from .hash_chain import GENESIS_HASH, canonical_timestamp, compute_entry_hash 

32from .status_export import build_audit_status_view, write_status_file 

33 

34logger = logging.getLogger(__name__) 

35 

36MAX_REPLAY_FAILURES = 5 

37 

38 

39def _is_connection_error(exc: BaseException) -> bool: 

40 """A failure of the link to Postgres or Redis, which a retry is meant to outlast, as opposed to one caused by the data.""" 

41 if isinstance(exc, (ConnectionError, OSError)): 

42 return True 

43 name = type(exc).__name__ 

44 return name in {"OperationalError", "InterfaceError", "AdminShutdown", "ConnectionError", "TimeoutError", "BusyLoadingError"} or "connection" in str(exc).lower() 

45 

46# --------------------------------------------------------------------------- 

47# Schema DDL — embedded constant, no migration files 

48# --------------------------------------------------------------------------- 

49 

50_CREATE_TABLE_SQL = """ 

51CREATE TABLE IF NOT EXISTS audit_log ( 

52 id BIGSERIAL PRIMARY KEY, 

53 event_id UUID UNIQUE NOT NULL, 

54 created_at TIMESTAMPTZ NOT NULL, 

55 ingested_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), 

56 event_type VARCHAR(30) NOT NULL, 

57 actor VARCHAR(30) NOT NULL, 

58 prev_hash CHAR(64) NOT NULL, 

59 hash CHAR(64) NOT NULL, 

60 payload JSONB NOT NULL 

61); 

62""" 

63 

64_CREATE_INDEXES_SQL = [ 

65 "CREATE INDEX IF NOT EXISTS ix_audit_created_at ON audit_log (created_at);", 

66 "CREATE INDEX IF NOT EXISTS ix_audit_event_type ON audit_log (event_type);", 

67 "CREATE INDEX IF NOT EXISTS ix_audit_payload ON audit_log USING GIN (payload);", 

68] 

69 

70_INSERT_SQL = """ 

71INSERT INTO audit_log 

72 (event_id, created_at, event_type, actor, prev_hash, hash, payload) 

73VALUES 

74 (%(event_id)s, %(created_at)s, %(event_type)s, %(actor)s, 

75 %(prev_hash)s, %(hash)s, %(payload)s) 

76ON CONFLICT (event_id) DO NOTHING; 

77""" 

78 

79_LATEST_HASH_SQL = "SELECT hash FROM audit_log ORDER BY id DESC LIMIT 1;" 

80 

81# --------------------------------------------------------------------------- 

82# Pure transformation — testable without any I/O 

83# --------------------------------------------------------------------------- 

84 

85 

86def event_to_row(event: dict, prev_hash: str) -> dict[str, Any]: 

87 """Extract INSERT params from an audit event dict plus the chain-tail 

88 hash it links to. Pure function - computes this row's own hash via 

89 audit.hash_chain.compute_entry_hash(), never mutates `event`.""" 

90 created_at = canonical_timestamp(event["created_at"]) # hashed as it reads back from TIMESTAMPTZ (Problems #339) 

91 entry_hash = compute_entry_hash(prev_hash, event["event_type"], created_at, event["payload"]) 

92 return { 

93 "event_id": event["event_id"], 

94 "created_at": created_at, 

95 "event_type": event["event_type"], 

96 "actor": event.get("actor", "system"), 

97 "prev_hash": prev_hash, 

98 "hash": entry_hash, 

99 "payload": json.dumps(event["payload"]), 

100 } 

101 

102 

103# --------------------------------------------------------------------------- 

104# Schema helper 

105# --------------------------------------------------------------------------- 

106 

107 

108def ensure_schema(conn) -> None: 

109 """Create audit_log table and indexes if they do not exist. Idempotent.""" 

110 with conn.cursor() as cur: 

111 cur.execute(_CREATE_TABLE_SQL) 

112 for idx_sql in _CREATE_INDEXES_SQL: 

113 cur.execute(idx_sql) 

114 conn.commit() 

115 logger.info("ensure_schema: audit_log ready.") 

116 

117 

118def fetch_latest_hash(conn) -> str: 

119 """The chain tail: the most recently inserted row's hash, or GENESIS_HASH 

120 if the table is empty. Callers hold this fixed across one run_once() 

121 batch and thread it forward row-by-row (see PostgresWorker.run_once()) 

122 so a batch of N events chains correctly among themselves before any of 

123 them are committed.""" 

124 with conn.cursor() as cur: 

125 cur.execute(_LATEST_HASH_SQL) 

126 row = cur.fetchone() 

127 return row[0] if row else GENESIS_HASH 

128 

129 

130# --------------------------------------------------------------------------- 

131# Worker 

132# --------------------------------------------------------------------------- 

133 

134 

135class PostgresWorker: 

136 """Drains aether:audit Redis Stream into PostgreSQL audit_log. 

137 

138 Parameters — identical shape to experience.postgres_worker.PostgresWorker; 

139 see that class's docstring for the full parameter list. Differs only in 

140 stream_name/group_name defaults and in computing+persisting the 

141 hash-chain link for every row (see event_to_row()/fetch_latest_hash()). 

142 """ 

143 

144 def __init__( 

145 self, 

146 *, 

147 redis_url: str = "redis://localhost:6380/0", 

148 postgres_dsn: str, 

149 stream_name: str = "aether:audit", 

150 group_name: str = "aether-audit-workers", 

151 consumer_name: str = "worker-1", 

152 batch_size: int = 100, 

153 deadletter_stream: str = "aether:audit:deadletter", 

154 backoff_max: int = 60, 

155 _redis_client=None, 

156 _pg_conn=None, 

157 ) -> None: 

158 self.stream_name = stream_name 

159 self.group_name = group_name 

160 self.consumer_name = consumer_name 

161 self.batch_size = batch_size 

162 self.deadletter_stream = deadletter_stream 

163 self.backoff_max = backoff_max 

164 

165 if _redis_client is not None: 

166 self._redis = _redis_client 

167 else: 

168 import redis as redis_lib 

169 url = secret_env("REDIS_URL", redis_url) 

170 self._redis = redis_lib.from_url(url, socket_connect_timeout=5, socket_timeout=5) 

171 # V5.4.7 (#120): warn instead of crash-looping when Redis is 

172 # down at container start; run()'s backoff loop retries. 

173 try: 

174 self._redis.ping() 

175 logger.info("AuditPostgresWorker: Redis connected at %s", redact_url(url)) 

176 except Exception as exc: 

177 logger.warning("AuditPostgresWorker: Redis not reachable yet (%s) - will retry in run loop.", exc) 

178 

179 if _pg_conn is not None: 

180 self._conn = _pg_conn 

181 else: 

182 import psycopg 

183 dsn = secret_env("POSTGRES_DSN", postgres_dsn) 

184 self._conn = psycopg.connect(dsn, autocommit=False) 

185 logger.info("AuditPostgresWorker: PostgreSQL connected.") 

186 

187 ensure_schema(self._conn) 

188 self._ensure_consumer_group() 

189 # a previous worker with this consumer name may have died holding messages it never acknowledged: read those first 

190 self._replay_pending = True 

191 self._replay_failures = 0 

192 

193 def _ensure_consumer_group(self) -> None: 

194 try: 

195 self._redis.xgroup_create( 

196 self.stream_name, self.group_name, id="0", mkstream=True 

197 ) 

198 logger.info("Consumer group '%s' created on '%s'.", self.group_name, self.stream_name) 

199 except Exception as exc: 

200 if "BUSYGROUP" in str(exc): 

201 logger.debug("Consumer group '%s' already exists.", self.group_name) 

202 else: 

203 raise 

204 

205 def _reconnect_pg(self, postgres_dsn: str) -> None: 

206 import psycopg 

207 try: 

208 self._conn.close() 

209 except Exception: 

210 pass 

211 dsn = secret_env("POSTGRES_DSN", postgres_dsn) 

212 self._conn = psycopg.connect(dsn, autocommit=False) 

213 ensure_schema(self._conn) 

214 logger.info("AuditPostgresWorker: PostgreSQL reconnected.") 

215 

216 def run_once(self) -> int: 

217 """Read one batch, hash-chain it, persist, ack. Returns count of 

218 events persisted. Raises on PostgreSQL failure. 

219 

220 A message read and not acknowledged stays in this consumer's pending list, and `xreadgroup(">")` never delivers it again (Problems #340: found by stopping a real 

221 Postgres under a running worker; the events read during the outage were never written). So after any failure, and when the worker starts, it first reads its own 

222 pending entries (id "0") until none are left, then carries on with new ones. Inserting is idempotent (`ON CONFLICT (event_id) DO NOTHING`), and the chain is taken from the 

223 database's latest hash on each batch, so a replay cannot fork it. A batch that keeps failing for a reason that is not the connection is dead-lettered after 

224 `MAX_REPLAY_FAILURES` tries instead of wedging the pipeline.""" 

225 replaying = self._replay_pending 

226 results = None 

227 if replaying: 

228 results = self._redis.xreadgroup(self.group_name, self.consumer_name, {self.stream_name: "0"}, count=self.batch_size) 

229 if not results or not results[0][1]: 

230 self._replay_pending = replaying = False # nothing of ours is still pending 

231 results = None 

232 if results is None: 

233 results = self._redis.xreadgroup( 

234 self.group_name, 

235 self.consumer_name, 

236 {self.stream_name: ">"}, 

237 count=self.batch_size, 

238 # block omitted (not 0 - that means "block forever" in Redis, 

239 # not "don't block") so this returns immediately; run() provides 

240 # the idle sleep. 

241 ) 

242 if not results: 

243 return 0 

244 

245 _, messages = results[0] 

246 # whatever is read and not acknowledged is ours to retry, so a failure anywhere below leaves the flag set 

247 self._replay_pending = True 

248 try: 

249 persisted = self._persist_batch(messages) 

250 except Exception as exc: 

251 if replaying and not _is_connection_error(exc): 

252 self._replay_failures += 1 

253 if self._replay_failures >= MAX_REPLAY_FAILURES: 

254 self._dead_letter_pending(messages, exc) 

255 raise 

256 self._replay_failures = 0 

257 return persisted 

258 

259 def _dead_letter_pending(self, messages: list, exc: Exception) -> None: 

260 for msg_id, fields in messages: 

261 raw = fields.get(b"payload") or fields.get("payload", b"") 

262 self._redis.xadd(self.deadletter_stream, {"payload": raw, "error": f"replayed {MAX_REPLAY_FAILURES} times: {exc}", "original_id": str(msg_id)}) 

263 self._redis.xack(self.stream_name, self.group_name, msg_id) 

264 self._replay_failures = 0 

265 logger.error("AuditPostgresWorker: %d pending messages dead-lettered after %d failed replays: %s", len(messages), MAX_REPLAY_FAILURES, exc) 

266 

267 def _persist_batch(self, messages: list) -> int: 

268 rows: list[dict] = [] 

269 ids_good: list = [] 

270 ids_deadletter: list = [] 

271 raw_by_id: dict = {} 

272 running_hash = fetch_latest_hash(self._conn) 

273 

274 for msg_id, fields in messages: 

275 raw = fields.get(b"payload") or fields.get("payload", b"") 

276 raw_by_id[msg_id] = raw if isinstance(raw, (bytes, bytearray)) else str(raw).encode("utf-8") 

277 try: 

278 event = json.loads(raw) 

279 row = event_to_row(event, running_hash) 

280 rows.append(row) 

281 running_hash = row["hash"] # chain the NEXT event in this batch to THIS one 

282 ids_good.append(msg_id) 

283 except Exception as exc: 

284 logger.warning("Malformed message %s → dead-letter. Error: %s", msg_id, exc) 

285 self._redis.xadd( 

286 self.deadletter_stream, 

287 {"payload": raw, "error": str(exc), "original_id": str(msg_id)}, 

288 ) 

289 ids_deadletter.append(msg_id) 

290 

291 if ids_deadletter: 

292 self._redis.xack(self.stream_name, self.group_name, *ids_deadletter) 

293 

294 # V5.4.7 (Problems.md #120): a single poison row used to fail the 

295 # whole executemany, roll back every good row, and leave the batch 

296 # pending forever (xreadgroup(">") never re-delivers) - wedging 

297 # the pipeline on one bad payload. Unlike the experience worker, 

298 # this chain CANNOT skip a failed middle row: every row's hash 

299 # chains to its predecessor's, so once one row cannot be inserted 

300 # every LATER row in the batch would fork the tamper-evident chain. 

301 # Fallback therefore inserts per-row IN ORDER and stops at the 

302 # first failure - that row and everything after it dead-letters 

303 # (payloads preserved verbatim), everything before it commits. 

304 if rows: 

305 try: 

306 with self._conn.cursor() as cur: 

307 cur.executemany(_INSERT_SQL, rows) 

308 self._conn.commit() 

309 self._redis.xack(self.stream_name, self.group_name, *ids_good) 

310 logger.info("AuditPostgresWorker: persisted %d events.", len(rows)) 

311 except Exception as batch_exc: 

312 # V5.4.7 (#120) - poison row vs postgres down: first-row 

313 # failure means the connection/statement, not the data - 

314 # re-raise so everything stays pending (old contract). A 

315 # batch whose head inserts fine takes the per-row path, 

316 # which for this hash-chained stream STOPS at the first 

317 # poison row and dead-letters it plus every LATER row 

318 # (their hashes chain off a parent that never landed - 

319 # inserting them would fork the tamper-evident chain). 

320 try: 

321 with self._conn.cursor() as cur: 

322 cur.execute(_INSERT_SQL, rows[0]) 

323 self._conn.commit() 

324 except Exception: 

325 self._conn.rollback() 

326 raise 

327 self._redis.xack(self.stream_name, self.group_name, ids_good[0]) 

328 persisted = 1 

329 for msg_id, row in zip(ids_good[1:], rows[1:], strict=False): 

330 try: 

331 with self._conn.cursor() as cur: 

332 cur.execute(_INSERT_SQL, row) 

333 self._conn.commit() 

334 self._redis.xack(self.stream_name, self.group_name, msg_id) 

335 persisted += 1 

336 except Exception as row_exc: 

337 self._conn.rollback() 

338 logger.warning( 

339 "Poison row %s → dead-letter; stopping - later rows " 

340 "chain off this one's hash. Error: %s", msg_id, row_exc 

341 ) 

342 break 

343 for msg_id in ids_good[persisted:]: 

344 raw = raw_by_id.get(msg_id) 

345 self._redis.xadd( 

346 self.deadletter_stream, 

347 { 

348 "payload": raw if raw is not None else b"", 

349 "error": f"chained after poison row: {batch_exc}", 

350 "original_id": str(msg_id), 

351 }, 

352 ) 

353 self._redis.xack(self.stream_name, self.group_name, msg_id) 

354 logger.info( 

355 "AuditPostgresWorker: per-row fallback persisted %d/%d events.", 

356 persisted, len(rows), 

357 ) 

358 return persisted 

359 # Refresh the webui/API dashboard snapshot right after a real 

360 # persist (not on every idle poll) - a stale audit trail 

361 # defeats its own purpose, so this stays close to real-time 

362 # rather than a periodic cron export. Best-effort: a dashboard 

363 # export failure must never lose already-committed audit rows. 

364 try: 

365 write_status_file(build_audit_status_view(self._conn)) 

366 except Exception as exc: 

367 logger.warning("AuditPostgresWorker: dashboard export failed: %s", exc) 

368 

369 return len(rows) 

370 

371 def run(self, postgres_dsn: str = "") -> None: 

372 """Continuous loop with exponential backoff on errors.""" 

373 backoff = 1 

374 logger.info("AuditPostgresWorker: entering run loop.") 

375 while True: 

376 try: 

377 count = self.run_once() 

378 if count == 0: 

379 time.sleep(1) # idle poll interval 

380 else: 

381 backoff = 1 

382 except KeyboardInterrupt: 

383 logger.info("AuditPostgresWorker: shutdown requested.") 

384 break 

385 except Exception as exc: 

386 logger.error("Worker error — %s. Retrying in %ds.", exc, backoff) 

387 time.sleep(backoff) 

388 backoff = min(backoff * 2, self.backoff_max) 

389 if postgres_dsn and "connection" in str(exc).lower(): 

390 try: 

391 self._reconnect_pg(postgres_dsn) 

392 except Exception as reconn_exc: 

393 logger.error("Reconnect failed: %s", reconn_exc) 

394 

395 def close(self) -> None: 

396 try: 

397 self._redis.close() 

398 except Exception: 

399 pass 

400 try: 

401 self._conn.close() 

402 except Exception: 

403 pass 

404 

405 

406# --------------------------------------------------------------------------- 

407# Entry point 

408# --------------------------------------------------------------------------- 

409 

410 

411def main() -> None: 

412 logging.basicConfig( 

413 level=logging.INFO, 

414 format="%(asctime)s [%(levelname)s] %(name)s — %(message)s", 

415 ) 

416 parser = argparse.ArgumentParser(description="Aether Quant audit-log persistence worker") 

417 parser.add_argument("--once", action="store_true", help="Read one batch and exit") 

418 parser.add_argument( 

419 "--stream", 

420 default=os.environ.get("AETHER_AUDIT_STREAM", "aether:audit"), 

421 ) 

422 parser.add_argument( 

423 "--group", 

424 default=os.environ.get("AETHER_AUDIT_GROUP", "aether-audit-workers"), 

425 ) 

426 parser.add_argument( 

427 "--batch-size", 

428 type=int, 

429 default=int(os.environ.get("AETHER_AUDIT_BATCH_SIZE", "100")), 

430 ) 

431 args = parser.parse_args() 

432 

433 redis_url = secret_env("REDIS_URL", "redis://localhost:6380/0") 

434 postgres_dsn = secret_env("POSTGRES_DSN", "") 

435 

436 worker = PostgresWorker( 

437 redis_url=redis_url, 

438 postgres_dsn=postgres_dsn, 

439 stream_name=args.stream, 

440 group_name=args.group, 

441 batch_size=args.batch_size, 

442 ) 

443 try: 

444 if args.once: 

445 count = worker.run_once() 

446 logger.info("--once: persisted %d events.", count) 

447 else: 

448 worker.run(postgres_dsn=postgres_dsn) 

449 finally: 

450 worker.close() 

451 

452 

453if __name__ == "__main__": 

454 main()