Coverage for src/copytrading_engine/backup/restore/inspector.py: 82%

60 statements  

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

1"""Immutable SQLite inspection adapter for a validated restore generation.""" 

2 

3from __future__ import annotations 

4 

5import hashlib 

6import re 

7import sqlite3 

8from contextlib import closing 

9from pathlib import Path 

10 

11from copytrading_engine.backup.service import BackupRestoreService 

12from copytrading_engine.execution.adapters.sqlite_ledger import decode_ledger_snapshot 

13from copytrading_engine.execution.application.restore_preflight import ( 

14 RestoreAccountInspection, 

15 RestoreCandidateInspection, 

16) 

17from copytrading_engine.execution.domain.ledger_state import LedgerSnapshot 

18 

19_ACCOUNT_DATABASE = re.compile(r"^accounts/([A-Za-z0-9_-]{1,64})/execution\.sqlite3$") 

20_CANDIDATE_MANIFEST_NAME = ".restore-candidate-manifest.json" 

21 

22 

23class SQLiteRestoreCandidateInspector: 

24 """Inspect local state without creating SQLite files or altering candidate hashes.""" 

25 

26 def __init__(self, backup_restore: BackupRestoreService) -> None: 

27 self._backup_restore = backup_restore 

28 

29 def inspect_candidate(self, candidate_id: str) -> RestoreCandidateInspection: 

30 manifest, candidate = self._backup_restore.resolve_active_restore_candidate(candidate_id) 

31 application_readable = True 

32 application_work_pending = False 

33 try: 

34 application_work_pending = _pending_application_work(candidate / "application.db") 

35 except Exception: # noqa: BLE001 - an unreadable member marks the candidate incomplete 

36 application_readable = False 

37 

38 account_members = { 

39 match.group(1): candidate.joinpath(*member.path.split("/")) 

40 for member in manifest.members 

41 if (match := _ACCOUNT_DATABASE.fullmatch(member.path)) is not None 

42 } 

43 account_inspections: list[RestoreAccountInspection] = [] 

44 incomplete_account_ids: list[str] = [] 

45 for account_id, path in account_members.items(): 

46 try: 

47 snapshot, pending_delivery = _read_account(path) 

48 except Exception: # noqa: BLE001 - an unreadable member marks the candidate incomplete 

49 incomplete_account_ids.append(account_id) 

50 continue 

51 account_inspections.append( 

52 RestoreAccountInspection( 

53 account_id=account_id, 

54 snapshot=snapshot, 

55 pending_delivery=pending_delivery, 

56 ) 

57 ) 

58 

59 candidate_manifest_digest = hashlib.sha256( 

60 (candidate / _CANDIDATE_MANIFEST_NAME).read_bytes() 

61 ).hexdigest() 

62 return RestoreCandidateInspection( 

63 candidate_id=candidate_id, 

64 created_at=manifest.created_at, 

65 environment_ids=manifest.environment_ids, 

66 account_member_ids=tuple(sorted(account_members)), 

67 accounts=tuple(account_inspections), 

68 incomplete_account_ids=tuple(sorted(incomplete_account_ids)), 

69 application_readable=application_readable, 

70 application_work_pending=application_work_pending, 

71 candidate_manifest_sha256=candidate_manifest_digest, 

72 ) 

73 

74 

75def _read_only_connection(path: Path) -> sqlite3.Connection: 

76 connection = sqlite3.connect( 

77 f"{path.as_uri()}?mode=ro&immutable=1", 

78 uri=True, 

79 timeout=2, 

80 isolation_level=None, 

81 ) 

82 try: 

83 connection.execute("PRAGMA query_only = ON") 

84 except BaseException: 

85 connection.close() 

86 raise 

87 return connection 

88 

89 

90def _has_pending(connection: sqlite3.Connection, statement: str) -> bool: 

91 row = connection.execute(statement).fetchone() 

92 if row is None or type(row[0]) is not int: 92 ↛ 93line 92 didn't jump to line 93 because the condition on line 92 was never true

93 raise sqlite3.DatabaseError("candidate queue state is unavailable") 

94 return row[0] != 0 

95 

96 

97def _pending_application_work(path: Path) -> bool: 

98 pending_queries = ( 

99 "SELECT EXISTS(SELECT 1 FROM source_captures WHERE mode='live' AND confirmed=0)", 

100 "SELECT EXISTS(SELECT 1 FROM parser_inbox WHERE result IS NULL)", 

101 "SELECT EXISTS(SELECT 1 FROM parser_signal_deliveries WHERE delivered_at IS NULL)", 

102 "SELECT EXISTS(SELECT 1 FROM parser_notifications WHERE delivered_at IS NULL)", 

103 "SELECT EXISTS(SELECT 1 FROM jobs WHERE status='pending')", 

104 ) 

105 with closing(_read_only_connection(path)) as connection: 

106 return any(_has_pending(connection, statement) for statement in pending_queries) 

107 

108 

109def _read_account(path: Path) -> tuple[LedgerSnapshot, bool]: 

110 with closing(_read_only_connection(path)) as connection: 

111 row = connection.execute("SELECT data FROM snapshot WHERE singleton=1").fetchone() 

112 if row is None or not isinstance(row[0], str): 112 ↛ 113line 112 didn't jump to line 113 because the condition on line 112 was never true

113 raise sqlite3.DatabaseError("account snapshot is unavailable") 

114 snapshot = decode_ledger_snapshot(row[0]) 

115 # A notification the owner has not been sent yet would be sent again after a restore. 

116 pending_notifications = _has_pending( 

117 connection, 

118 "SELECT EXISTS(SELECT 1 FROM notifications WHERE delivered_at IS NULL)", 

119 ) 

120 return snapshot, pending_notifications