42b0fbe1ab
Componente runtime/ che cabla core+clients+state+safety in un engine autonomo notify-only: nessuna conferma manuale, ordini combo piazzati direttamente quando le regole passano. 311 test pass, copertura totale 94%, runtime/ 90%, mypy strict pulito, ruff clean. Moduli: - runtime/alert_manager.py: escalation tree LOW/MEDIUM/HIGH/CRITICAL → audit + Telegram + kill switch. - runtime/dependencies.py: build_runtime() costruisce RuntimeContext con tutti i client MCP, repository, audit log, kill switch, alert manager. - runtime/entry_cycle.py: flusso settimanale (snapshot parallelo spot/dvol/funding/macro/holdings/equity → validate_entry → compute_bias → options_chain → select_strikes → liquidity_gate → sizing_engine → combo_builder.build → place_combo_order → notify_position_opened). - runtime/monitor_cycle.py: loop 12h con dvol_history per il return_4h, exit_decision.evaluate, close auto-execute. - runtime/health_check.py: probe parallelo MCP + SQLite + environment match; 3 strikes consecutivi → kill switch HIGH. - runtime/recovery.py: riconciliazione SQLite vs broker all'avvio; mismatch → kill switch CRITICAL. - runtime/scheduler.py: AsyncIOScheduler builder con cron entry (lun 14:00), monitor (02/14), health (5min). - runtime/orchestrator.py: façade boot() + run_entry/monitor/health + install_scheduler + run_forever, con env check vs strategy. CLI: - start: avvia engine bloccante (asyncio.run + scheduler). - dry-run --cycle entry|monitor|health: esegue un singolo ciclo per debug/test in produzione. - stop: documenta lo shutdown via SIGTERM al container. Documentazione: - docs/06-operational-flow.md riscritto per il modello notify-only auto-execute (no conferma manuale, no memory, no brain-bridge). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
175 lines
5.1 KiB
Python
175 lines
5.1 KiB
Python
"""Integration tests for the recovery loop."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from datetime import UTC, datetime, timedelta
|
|
from decimal import Decimal
|
|
from pathlib import Path
|
|
from uuid import uuid4
|
|
|
|
import pytest
|
|
from pytest_httpx import HTTPXMock
|
|
|
|
from cerbero_bite.config import golden_config
|
|
from cerbero_bite.config.mcp_endpoints import load_endpoints
|
|
from cerbero_bite.runtime import build_runtime
|
|
from cerbero_bite.runtime.recovery import recover_state
|
|
from cerbero_bite.state import PositionRecord, transaction
|
|
from cerbero_bite.state import connect as connect_state
|
|
|
|
pytestmark = pytest.mark.httpx_mock(assert_all_responses_were_requested=False)
|
|
|
|
|
|
def _now() -> datetime:
|
|
return datetime(2026, 4, 27, 14, 0, tzinfo=UTC)
|
|
|
|
|
|
def _build_ctx(tmp_path: Path):
|
|
return build_runtime(
|
|
cfg=golden_config(),
|
|
endpoints=load_endpoints(env={}),
|
|
token="t",
|
|
db_path=tmp_path / "state.sqlite",
|
|
audit_path=tmp_path / "audit.log",
|
|
retry_max=1,
|
|
clock=_now,
|
|
)
|
|
|
|
|
|
def _make_record(*, status: str, proposal_id, opened: datetime | None = None) -> PositionRecord:
|
|
base_now = _now()
|
|
return PositionRecord(
|
|
proposal_id=proposal_id,
|
|
spread_type="bull_put",
|
|
expiry=base_now + timedelta(days=18),
|
|
short_strike=Decimal("2475"),
|
|
long_strike=Decimal("2350"),
|
|
short_instrument="ETH-15MAY26-2475-P",
|
|
long_instrument="ETH-15MAY26-2350-P",
|
|
n_contracts=2,
|
|
spread_width_usd=Decimal("125"),
|
|
spread_width_pct=Decimal("0.04"),
|
|
credit_eth=Decimal("0.030"),
|
|
credit_usd=Decimal("90"),
|
|
max_loss_usd=Decimal("160"),
|
|
spot_at_entry=Decimal("3000"),
|
|
dvol_at_entry=Decimal("50"),
|
|
delta_at_entry=Decimal("-0.12"),
|
|
eth_price_at_entry=Decimal("3000"),
|
|
proposed_at=base_now - timedelta(hours=1),
|
|
opened_at=opened,
|
|
status=status,
|
|
created_at=base_now - timedelta(hours=1),
|
|
updated_at=base_now - timedelta(hours=1),
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_recovery_promotes_awaiting_fill_when_broker_shows_position(
|
|
tmp_path: Path, httpx_mock: HTTPXMock
|
|
) -> None:
|
|
ctx = _build_ctx(tmp_path)
|
|
pid = uuid4()
|
|
record = _make_record(status="awaiting_fill", proposal_id=pid)
|
|
conn = connect_state(ctx.db_path)
|
|
try:
|
|
with transaction(conn):
|
|
ctx.repository.create_position(conn, record)
|
|
finally:
|
|
conn.close()
|
|
|
|
httpx_mock.add_response(
|
|
url="http://mcp-deribit:9011/tools/get_positions",
|
|
json=[
|
|
{"instrument": "ETH-15MAY26-2475-P", "size": 2},
|
|
{"instrument": "ETH-15MAY26-2350-P", "size": 2},
|
|
],
|
|
)
|
|
|
|
await recover_state(ctx, now=_now())
|
|
|
|
conn = connect_state(ctx.db_path)
|
|
try:
|
|
positions = ctx.repository.list_positions(conn)
|
|
finally:
|
|
conn.close()
|
|
assert positions[0].status == "open"
|
|
assert positions[0].opened_at is not None
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_recovery_cancels_awaiting_fill_when_broker_lacks_legs(
|
|
tmp_path: Path, httpx_mock: HTTPXMock
|
|
) -> None:
|
|
ctx = _build_ctx(tmp_path)
|
|
pid = uuid4()
|
|
record = _make_record(status="awaiting_fill", proposal_id=pid)
|
|
conn = connect_state(ctx.db_path)
|
|
try:
|
|
with transaction(conn):
|
|
ctx.repository.create_position(conn, record)
|
|
finally:
|
|
conn.close()
|
|
|
|
httpx_mock.add_response(
|
|
url="http://mcp-deribit:9011/tools/get_positions",
|
|
json=[],
|
|
)
|
|
httpx_mock.add_response(
|
|
url="http://mcp-telegram:9017/tools/notify_system_error",
|
|
json={"ok": True},
|
|
is_reusable=True,
|
|
)
|
|
|
|
await recover_state(ctx, now=_now())
|
|
|
|
conn = connect_state(ctx.db_path)
|
|
try:
|
|
positions = ctx.repository.list_positions(conn)
|
|
finally:
|
|
conn.close()
|
|
assert positions[0].status == "cancelled"
|
|
assert positions[0].close_reason == "recovery_no_fill"
|
|
# discrepancies → kill switch armed
|
|
assert ctx.kill_switch.is_armed() is True
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_recovery_alerts_on_open_position_missing_on_broker(
|
|
tmp_path: Path, httpx_mock: HTTPXMock
|
|
) -> None:
|
|
ctx = _build_ctx(tmp_path)
|
|
pid = uuid4()
|
|
record = _make_record(
|
|
status="open", proposal_id=pid, opened=_now() - timedelta(days=1)
|
|
)
|
|
conn = connect_state(ctx.db_path)
|
|
try:
|
|
with transaction(conn):
|
|
ctx.repository.create_position(conn, record)
|
|
finally:
|
|
conn.close()
|
|
|
|
httpx_mock.add_response(
|
|
url="http://mcp-deribit:9011/tools/get_positions",
|
|
json=[],
|
|
)
|
|
httpx_mock.add_response(
|
|
url="http://mcp-telegram:9017/tools/notify_system_error",
|
|
json={"ok": True},
|
|
is_reusable=True,
|
|
)
|
|
|
|
await recover_state(ctx, now=_now())
|
|
assert ctx.kill_switch.is_armed() is True
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_recovery_noop_when_no_in_flight_positions(
|
|
tmp_path: Path, httpx_mock: HTTPXMock
|
|
) -> None:
|
|
ctx = _build_ctx(tmp_path)
|
|
# No HTTP stubs needed because get_positions is not even called.
|
|
await recover_state(ctx, now=_now())
|
|
assert ctx.kill_switch.is_armed() is False
|