Coverage for src/copytrading_engine/execution/adapters/ownership_probe.py: 91%
52 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-16 16:55 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-16 16:55 +0000
1"""Read-only account-state guard for removing a stopped app configuration."""
3import json
4import sqlite3
5from contextlib import closing
6from dataclasses import dataclass
7from pathlib import Path
9from copytrading_engine.execution.adapters.sqlite_ledger import (
10 EXECUTION_SCHEMA,
11 decode_ledger_snapshot,
12)
13from copytrading_engine.execution.domain.ledger_state import is_earlier_version
14from copytrading_engine.execution.domain.order_lifecycle import is_terminal
15from copytrading_engine.shared.sqlite import verify_schema
18@dataclass(frozen=True)
19class UnsettledOwnership:
20 """Work a stopped account still has in flight, named so the owner can settle it. Shares it
21 holds are not work: a removed account keeps them at the broker, and CopyTrading stops
22 tracking them."""
24 # Stocks with an order CopyTrading placed that has not finished, A to Z.
25 order_symbols: tuple[str, ...] = ()
26 # A post still being copied.
27 needs_review: bool = False
30def unsettled_ownership(account_dir: Path) -> UnsettledOwnership | None:
31 """The work an account still has in flight, or None when it has none; never create or
32 modify its DB.
34 Missing state is empty. Existing state with an unknown schema, invalid identity, or
35 unreadable snapshot raises so the caller can keep the account configuration.
36 Call only after the account owner has stopped writing this directory.
37 """
38 path = account_dir / "execution.sqlite3"
39 if path.is_symlink(): 39 ↛ 40line 39 didn't jump to line 40 because the condition on line 39 was never true
40 raise RuntimeError("Execution database symlink cannot be inspected safely")
41 if not path.exists():
42 return None
43 if not path.is_file(): 43 ↛ 44line 43 didn't jump to line 44 because the condition on line 43 was never true
44 raise RuntimeError("Execution database path is not a file")
45 try:
46 with closing(sqlite3.connect(path.as_uri() + "?mode=ro", uri=True, timeout=5)) as db:
47 db.execute("BEGIN")
48 verify_schema(db, EXECUTION_SCHEMA)
49 row = db.execute("SELECT data FROM snapshot WHERE singleton=1").fetchone()
50 if row is None:
51 return None
52 older = _older_snapshot(row[0])
53 if older is not None:
54 return _older_ownership(older)
55 ledger = decode_ledger_snapshot(row[0])
56 identity = db.execute(
57 "SELECT environment,account_id FROM identity WHERE singleton=1"
58 ).fetchone()
59 if (
60 identity is None
61 or identity[0] not in {"paper", "live"}
62 or ledger.account_id is None
63 or ledger.account_id != identity[1]
64 or ledger.environment != identity[0]
65 ):
66 raise RuntimeError("Execution snapshot account identity is invalid")
67 return _held(
68 order_symbols={
69 order.symbol for order in ledger.orders.values() if not order.terminal
70 },
71 needs_review=any(
72 message.status == "queued" for message in ledger.messages.values()
73 ),
74 )
75 except (sqlite3.Error, ValueError) as error:
76 raise RuntimeError("Execution ownership state is unreadable") from error
79def _held(*, order_symbols: set[str], needs_review: bool) -> UnsettledOwnership | None:
80 if not order_symbols and not needs_review:
81 return None
82 return UnsettledOwnership(order_symbols=tuple(sorted(order_symbols)), needs_review=needs_review)
85def _older_snapshot(data: str) -> dict | None:
86 """The snapshot of an earlier ledger version, which is never migrated, or None when it is
87 the current one."""
88 snapshot = json.loads(data)
89 if not isinstance(snapshot, dict): 89 ↛ 90line 89 didn't jump to line 90 because the condition on line 89 was never true
90 raise ValueError("Execution snapshot is not an object")
91 return snapshot if is_earlier_version(snapshot.get("schema_version")) else None
94def _older_ownership(snapshot: dict) -> UnsettledOwnership | None:
95 """The work a ledger an earlier CopyTrading wrote still has in flight: an open order or a post
96 being copied. Read by name only, since its format is not this version's; anything unreadable
97 counts as needing review."""
98 try:
99 return _held(
100 order_symbols={
101 str(order["symbol"])
102 for order in snapshot.get("orders", {}).values()
103 if not is_terminal(order["status"])
104 },
105 needs_review=any(
106 m["status"] == "queued" for m in snapshot.get("messages", {}).values()
107 ),
108 )
109 except KeyError, TypeError, ValueError, AttributeError:
110 return UnsettledOwnership(needs_review=True)