Coverage for src/copytrading_engine/host/self_test/service.py: 85%
38 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"""Engine self-test: durable acceptance followed by recoverable local processing."""
3import asyncio
5from copytrading_engine.host.errors import InvalidTransition, UnsupportedSelfTest
6from copytrading_engine.host.self_test.model import (
7 DestinationOutcome,
8 ParseRejected,
9 Stage,
10 SubmitSelfTest,
11 WorkflowView,
12)
13from copytrading_engine.host.self_test.ports import SelfTestParser, WorkflowStore
15_DEFAULT_PROCESS_LIMIT = 100
18class SelfTestService:
19 """Accept and process self-tests using caller-owned ports."""
21 def __init__(self, store: WorkflowStore, parser: SelfTestParser) -> None:
22 self._store = store
23 self._parser = parser
24 self._processing_lock = asyncio.Lock()
26 async def submit(self, command: SubmitSelfTest) -> WorkflowView:
27 """Commit acceptance before returning the stable workflow identity."""
28 acceptance = await self._store.accept_async(command)
29 return acceptance.workflow
31 async def process_pending(self, max_items: int = _DEFAULT_PROCESS_LIMIT) -> None:
32 """Advance at most a bounded batch, leaving remaining jobs for recovery."""
33 if max_items < 0: 33 ↛ 34line 33 didn't jump to line 34 because the condition on line 33 was never true
34 raise ValueError("max_items must not be negative")
35 async with self._processing_lock:
36 command_ids = await self._store.pending_async(limit=max_items)
37 for command_id in command_ids:
38 await self._process_one(command_id)
40 async def _process_one(self, command_id: str) -> None:
41 workflow = await self._store.get_async(command_id)
42 if workflow.stage is Stage.CAPTURED:
43 command = await self._store.load_command_async(command_id)
44 try:
45 parsed = self._parser.parse(command.text)
46 except UnsupportedSelfTest:
47 await self._store.advance_async(
48 command_id,
49 Stage.CAPTURED,
50 Stage.FAILED,
51 (),
52 parse_rejection=ParseRejected(command_id),
53 )
54 return
55 workflow = await self._store.advance_async(
56 command_id,
57 Stage.CAPTURED,
58 Stage.PARSED,
59 (),
60 parsed=parsed,
61 )
63 if workflow.stage is Stage.PARSED: 63 ↛ 78line 63 didn't jump to line 78 because the condition on line 63 was always true
64 command = await self._store.load_command_async(command_id)
65 outcomes = tuple(
66 DestinationOutcome(account_id=destination_id)
67 for destination_id in command.destination_ids
68 )
69 await self._store.load_parsed_async(command_id)
70 await self._store.advance_async(
71 command_id,
72 Stage.PARSED,
73 Stage.COMPLETED,
74 outcomes,
75 )
76 return
78 if workflow.stage not in {Stage.COMPLETED, Stage.FAILED}:
79 raise InvalidTransition("pending workflow is in an unsupported state")