Coverage for src/copytrading_engine/trading/adapters/activation.py: 75%
133 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"""Durable, secret-free activation state for explicit trading Start commands."""
3import json
4import os
5from pathlib import Path
6from typing import Literal
7from uuid import UUID, uuid4
9from pydantic import BaseModel, ConfigDict, Field
11from copytrading_engine.trading.domain.status import TradingRunState
13type ActivationPhase = Literal["starting", "ready", "failed", "stopped", "interrupted"]
14type ActivationQueryPhase = Literal[
15 "not_found", "starting", "ready", "failed", "stopped", "interrupted"
16]
19class ActivationRecord(BaseModel):
20 model_config = ConfigDict(extra="forbid", frozen=True)
22 activation_id: str = Field(pattern=r"^[0-9a-f-]{36}$")
23 candidate_revision: str = Field(pattern=r"^[0-9a-f]{64}$")
24 committed_revision: str | None = Field(default=None, pattern=r"^[0-9a-f]{64}$")
25 committed_activation_id: str | None = Field(default=None, pattern=r"^[0-9a-f-]{36}$")
26 phase: ActivationPhase
27 error_code: str | None = Field(default=None, max_length=64)
30class TradingActivationStatus(BaseModel):
31 """Status returned for one requested activation, including last committed revision."""
33 model_config = ConfigDict(extra="forbid", frozen=True)
35 requested_activation_id: str = Field(pattern=r"^[0-9a-f-]{36}$")
36 activation_id: str | None = Field(default=None, pattern=r"^[0-9a-f-]{36}$")
37 candidate_revision: str | None = Field(default=None, pattern=r"^[0-9a-f]{64}$")
38 committed_revision: str | None = Field(default=None, pattern=r"^[0-9a-f]{64}$")
39 committed_activation_id: str | None = Field(default=None, pattern=r"^[0-9a-f-]{36}$")
40 phase: ActivationQueryPhase
41 runtime_state: TradingRunState
42 error_code: str | None = Field(default=None, max_length=64)
45class TradingActivationJournal:
46 """Atomically persist the last activation transition without storing credentials."""
48 def __init__(self, path: Path) -> None:
49 self._path = path
50 self._record = self._read()
51 # A new process has no running activation, so a saved "starting" or "ready" one ended
52 # with the last process. Only the in-memory view says so: opening must not write,
53 # because a restored copy is checked byte for byte before it is used.
54 if self._record is not None and self._record.phase in {"starting", "ready"}:
55 next_phase: ActivationPhase = (
56 "interrupted" if self._record.phase == "starting" else "stopped"
57 )
58 self._record = self._record.model_copy(update={"phase": next_phase})
60 @property
61 def record(self) -> ActivationRecord | None:
62 return self._record
64 def begin(self, activation_id: str, candidate_revision: str) -> ActivationRecord:
65 canonical_id = str(UUID(activation_id))
66 if self._record is not None and self._record.activation_id == canonical_id: 66 ↛ 67line 66 didn't jump to line 67 because the condition on line 66 was never true
67 if self._record.candidate_revision != candidate_revision:
68 raise ValueError("activation_id_reused_for_different_revision")
69 if self._record.phase == "starting":
70 return self._record
71 raise ValueError("activation_id_already_used")
72 if self._record is not None and self._record.phase == "starting": 72 ↛ 73line 72 didn't jump to line 73 because the condition on line 72 was never true
73 raise ValueError("activation_already_starting")
74 record = ActivationRecord(
75 activation_id=canonical_id,
76 candidate_revision=candidate_revision,
77 committed_revision=(
78 self._record.committed_revision if self._record is not None else None
79 ),
80 committed_activation_id=(
81 self._record.committed_activation_id if self._record is not None else None
82 ),
83 phase="starting",
84 )
85 self._replace(record)
86 return record
88 def mark_ready(self, activation_id: str) -> ActivationRecord:
89 record = self._matching(activation_id)
90 if record.phase == "ready": 90 ↛ 91line 90 didn't jump to line 91 because the condition on line 90 was never true
91 return record
92 if record.phase != "starting": 92 ↛ 93line 92 didn't jump to line 93 because the condition on line 92 was never true
93 raise ValueError("activation_not_starting")
94 record = record.model_copy(
95 update={
96 "phase": "ready",
97 "committed_revision": record.candidate_revision,
98 "committed_activation_id": record.activation_id,
99 }
100 )
101 self._replace(record)
102 return record
104 def adopt(self, activation_id: str, revision: str) -> ActivationRecord:
105 """The running activation now copies `revision`: limits changed while copying."""
106 record = self._matching(activation_id)
107 if record.phase not in {"starting", "ready"}: 107 ↛ 108line 107 didn't jump to line 108 because the condition on line 107 was never true
108 raise ValueError("activation_not_running")
109 update = {"candidate_revision": revision}
110 if record.committed_activation_id == record.activation_id: 110 ↛ 112line 110 didn't jump to line 112 because the condition on line 110 was always true
111 update["committed_revision"] = revision
112 record = record.model_copy(update=update)
113 self._replace(record)
114 return record
116 def mark_failed(self, activation_id: str, error_code: str) -> ActivationRecord:
117 record = self._matching(activation_id)
118 if record.phase == "failed": 118 ↛ 119line 118 didn't jump to line 119 because the condition on line 118 was never true
119 return record
120 if record.phase != "starting": 120 ↛ 121line 120 didn't jump to line 121 because the condition on line 120 was never true
121 raise ValueError("activation_not_starting")
122 record = record.model_copy(update={"phase": "failed", "error_code": error_code})
123 self._replace(record)
124 return record
126 def mark_stopped(self, activation_id: str) -> ActivationRecord:
127 record = self._matching(activation_id)
128 if record.phase in {"failed", "interrupted", "stopped"}: 128 ↛ 129line 128 didn't jump to line 129 because the condition on line 128 was never true
129 return record
130 record = record.model_copy(update={"phase": "stopped"})
131 self._replace(record)
132 return record
134 def status(self, activation_id: str, runtime_state: TradingRunState) -> TradingActivationStatus:
135 requested_id = str(UUID(activation_id))
136 record = self._record
137 if record is None: 137 ↛ 138line 137 didn't jump to line 138 because the condition on line 137 was never true
138 return TradingActivationStatus(
139 requested_activation_id=requested_id,
140 phase="not_found",
141 runtime_state=runtime_state,
142 )
143 matches = record.activation_id == requested_id
144 return TradingActivationStatus(
145 requested_activation_id=requested_id,
146 activation_id=record.activation_id,
147 candidate_revision=record.candidate_revision,
148 committed_revision=record.committed_revision,
149 committed_activation_id=record.committed_activation_id,
150 phase=record.phase if matches else "not_found",
151 runtime_state=runtime_state,
152 error_code=record.error_code if matches else None,
153 )
155 def _matching(self, activation_id: str) -> ActivationRecord:
156 canonical_id = str(UUID(activation_id))
157 if self._record is None or self._record.activation_id != canonical_id: 157 ↛ 158line 157 didn't jump to line 158 because the condition on line 157 was never true
158 raise ValueError("activation_record_not_found")
159 return self._record
161 def _replace(self, record: ActivationRecord) -> None:
162 self._write(record)
163 self._record = record
165 def _read(self) -> ActivationRecord | None:
166 if not self._path.exists():
167 return None
168 if self._path.is_symlink() or self._path.stat().st_size > 64 * 1024: 168 ↛ 169line 168 didn't jump to line 169 because the condition on line 168 was never true
169 raise ValueError("activation_journal_invalid")
170 try:
171 wrapper = json.loads(self._path.read_text(encoding="utf-8"))
172 if not isinstance(wrapper, dict) or wrapper.get("version") != 1: 172 ↛ 173line 172 didn't jump to line 173 because the condition on line 172 was never true
173 raise ValueError("activation_journal_invalid")
174 return ActivationRecord.model_validate(wrapper["record"])
175 except OSError, AttributeError, KeyError, TypeError, json.JSONDecodeError, ValueError:
176 raise ValueError("activation_journal_invalid") from None
178 def _write(self, record: ActivationRecord) -> None:
179 parent = self._path.parent
180 parent.mkdir(mode=0o700, parents=True, exist_ok=True)
181 if parent.is_symlink() or self._path.is_symlink(): 181 ↛ 182line 181 didn't jump to line 182 because the condition on line 181 was never true
182 raise ValueError("activation_journal_invalid")
183 temporary = parent / f".{self._path.name}.{uuid4().hex}.tmp"
184 encoded = json.dumps(
185 {"version": 1, "record": record.model_dump(mode="json")},
186 sort_keys=True,
187 separators=(",", ":"),
188 ).encode("utf-8")
189 descriptor = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
190 try:
191 with os.fdopen(descriptor, "wb") as stream:
192 stream.write(encoded)
193 stream.flush()
194 os.fsync(stream.fileno())
195 os.replace(temporary, self._path)
196 directory_fd = os.open(parent, os.O_RDONLY)
197 try:
198 os.fsync(directory_fd)
199 finally:
200 os.close(directory_fd)
201 except BaseException:
202 try:
203 temporary.unlink(missing_ok=True)
204 except OSError:
205 pass
206 raise