Hardening round 2: healthcheck, audit anchor, return_4h, exec config, signals

Sei interventi MEDIA priorità sul sistema. 323 test pass, mypy strict
pulito, ruff clean.

1. Docker HEALTHCHECK + cerbero-bite healthcheck:
   - nuovo subcommand che esce 0 se kill_switch=0 e last_health_check
     entro --max-staleness-s (default 600s);
   - HEALTHCHECK direttiva nel Dockerfile (60s interval, 5s timeout,
     start_period 120s, retries 3);
   - healthcheck definition nel docker-compose.yml.

2. Audit hash chain anti-truncation:
   - migration 0002: nuova colonna system_state.last_audit_hash;
   - AuditLog accetta callback on_append, dependencies.py la wire al
     repository.set_last_audit_hash;
   - Orchestrator.boot verifica che il tail file matcha l'anchor
     persistito; mismatch → kill switch CRITICAL.

3. return_4h bootstrap da deribit get_historical:
   - quando dvol_history è vuoto _fetch_return_4h cade su
     deribit.historical_close (1h candle 4h fa);
   - alert LOW se anche il fallback fallisce.

4. execution.environment + execution.eur_to_usd in strategy.yaml:
   - ExecutionConfig promosso a typed schema con i due campi
     consumati al boot;
   - CLI start preferisce i valori da config; CLI flag overridano
     solo quando differenti dai default.

5. Cycle correlation ID:
   - structlog.contextvars.bind_contextvars in run_entry/run_monitor/
     run_health propaga cycle_id e cycle nei log strutturati.

6. SIGTERM/SIGINT clean shutdown:
   - run_forever installa loop.add_signal_handler per SIGTERM e
     SIGINT; il segnale set()ta un asyncio.Event che termina il
     blocco principale, scheduler.shutdown e ctx.aclose finalizzano.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-04-28 00:37:39 +02:00
parent 411b747e93
commit b5b96f959c
15 changed files with 477 additions and 24 deletions
+34 -11
View File
@@ -154,13 +154,19 @@ def _option_type_from_name(name: str) -> PutOrCall:
async def _fetch_return_4h(ctx: RuntimeContext, *, now: datetime) -> Decimal:
"""Compute ETH 4h return from the locally stored dvol_history snapshots.
"""Compute ETH 4h return.
The orchestrator records a snapshot at the start of every monitor
cycle (see :func:`run_monitor_cycle`); this helper reads the most
recent snapshot at least 3.5h old and computes ``(now / past) - 1``.
Returns 0 if no historical sample is available — in that branch the
orchestrator emits a LOW alert about insufficient history.
Resolution order:
1. local ``dvol_history`` snapshot at least 3h30 old (recorded by
previous monitor cycles);
2. Deribit ``get_historical`` 1h candles 4h ago — bootstrap when
SQLite has no recent sample (first cycle after a fresh
container, or after long downtime).
Returns ``0`` only when both sources fail; in that case the
monitor cycle emits a LOW alert and exit_decision falls back to
HOLD on the adverse-move trigger.
"""
cutoff = now - timedelta(hours=3, minutes=30)
floor = now - timedelta(hours=8)
@@ -174,13 +180,30 @@ async def _fetch_return_4h(ctx: RuntimeContext, *, now: datetime) -> Decimal:
).fetchone()
finally:
conn.close()
if row is None:
return Decimal("0")
past_spot = Decimal(str(row[1]))
if past_spot == 0:
if row is not None:
past_spot = Decimal(str(row[1]))
if past_spot != 0:
spot_now = await ctx.deribit.index_price_eth()
return spot_now / past_spot - Decimal("1")
# Fallback: ask Deribit for the 4h candle close.
try:
past_close = await ctx.deribit.historical_close(
instrument="ETH-PERPETUAL",
start=now - timedelta(hours=5),
end=now - timedelta(hours=3, minutes=30),
resolution="1h",
)
except Exception: # pragma: no cover — defensive, surface as LOW alert
past_close = None
if past_close is None or past_close == 0:
await ctx.alert_manager.low(
source="monitor_cycle",
message="no return_4h sample available (history empty + bootstrap failed)",
)
return Decimal("0")
spot_now = await ctx.deribit.index_price_eth()
return spot_now / past_spot - Decimal("1")
return spot_now / past_close - Decimal("1")
# ---------------------------------------------------------------------------