Coverage for experience/redis_queue.py: 100%

76 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-22 12:55 +0000

1"""Redis Stream publisher for Aether Quant experience events (V2-13). 

2 

3Publishes one market-decision event per asset per bar to a Redis Stream 

4(XADD) with a bounded maxlen. All Redis failures are caught and logged; 

5trading is never blocked. 

6""" 

7 

8from __future__ import annotations 

9 

10import logging 

11import queue 

12import threading 

13import uuid 

14from datetime import datetime, timezone 

15from typing import Any 

16 

17from execution.secrets import redact_url 

18from execution.secrets_io import secret_env 

19from json_safety import dumps_json_safe 

20 

21from .observation_metrics import compute_observation_summary 

22 

23logger = logging.getLogger(__name__) 

24 

25# V4.9 Priority 5 - bounded depth for ExperienceQueue's optional background 

26# delivery queue (async_enabled=True). Large enough to absorb a real burst 

27# without soft-dropping events under normal operation, small enough that a 

28# permanently-stuck consumer (Redis down for an extended stretch) can't grow 

29# memory unboundedly - once full, push() soft-drops with a logged warning 

30# rather than blocking the caller, same fire-and-forget contract this class 

31# has always had. 

32_BACKGROUND_QUEUE_MAXSIZE = 10_000 

33# Sentinel distinguishing "stop the drain thread" from a real event dict - 

34# a plain None would work today (no call site ever pushes None), but an 

35# explicit sentinel object can never collide with a real payload. 

36_SHUTDOWN_SENTINEL = object() 

37 

38 

39def build_experience_event( 

40 *, 

41 mode: str, 

42 symbol: str, 

43 ticker: str, 

44 signal: str, 

45 action: str, 

46 execution_note: str, 

47 probability_up: float | None, 

48 confidence: float, 

49 target_weight: float, 

50 regime: dict, 

51 moe_gating: dict, 

52 topology: dict, 

53 liquidity: dict, 

54 market_analysis: dict, 

55 portfolio: dict, 

56 sequence_model: dict | None = None, 

57 resolved_predicted_rank_20d: float | None = None, 

58 close_price: float | None = None, 

59 corporate_action: dict | None = None, 

60) -> dict[str, Any]: 

61 """Construct a standardised experience event dict. 

62 

63 Pure function — no side effects, no I/O. Directly testable without 

64 any Redis dependency. 

65 

66 `sequence_model` is the optional Phase 2 causal-TCN sequence-encoder 

67 prediction (`main.py::_run_sequence_model()`, `{"direction", 

68 "magnitude", "volatility"}` or None when the model isn't loaded/failed 

69 for this bar) — informational only, same as everywhere else it's 

70 threaded, but now persisted for offline analysis instead of only 

71 reaching the live dashboard. 

72 

73 `resolved_predicted_rank_20d`/`close_price` (Phase 6 of the 5/10 -> 9/10 

74 roadmap): the SAME resolved rank_20d value main.py already computes 

75 (preferring the sequence model's head, falling back to multitask's — 

76 see risk/position_sizing.py::rank_sizing_multiplier()'s docstring), 

77 plus this bar's close, persisted specifically so 

78 performance/rank_ic_monitor.py's outcome-resolution job can self-join 

79 experience events on (ticker, date + 20 trading days) with no separate 

80 live price feed dependency. Without this, a multitask-fallback rank 

81 prediction (sequence model disabled) never reached the experience 

82 store at all — `sequence_model` above only carries the sequence 

83 model's own prediction, not the resolved value main.py actually used. 

84 

85 `corporate_action` (V4.7, development/Problems.md - corporate-action 

86 modeling): {"split_factor": float, "reference_price": float} when 

87 Lean's own slice.Splits reports a same-bar split event for this 

88 symbol, else None (absent, not a placeholder default - a bar with no 

89 split must never be indistinguishable from one Lean reported an 

90 unparseable/zero split_factor for). Purely observational auditability 

91 - main.py never recomputes an OCC-style strike/multiplier adjustment 

92 from this; Lean/the option-chain data itself owns that fact. 

93 """ 

94 return { 

95 "event_id": str(uuid.uuid4()), 

96 "event_type": "market_decision", 

97 "created_at": datetime.now(tz=timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), 

98 "mode": mode, 

99 "symbol": symbol, 

100 "ticker": ticker, 

101 "signal": signal, 

102 "action": action, 

103 "execution_note": execution_note, 

104 "probability_up": probability_up, 

105 "confidence": confidence, 

106 "target_weight": target_weight, 

107 "regime": regime, 

108 "moe_gating": moe_gating, 

109 "topology": topology, 

110 "liquidity": liquidity, 

111 "market_analysis": market_analysis, 

112 "portfolio": portfolio, 

113 "sequence_model": sequence_model, 

114 "resolved_predicted_rank_20d": resolved_predicted_rank_20d, 

115 "close_price": close_price, 

116 "corporate_action": corporate_action, 

117 } 

118 

119 

120def build_session_summary_event( 

121 *, 

122 mode: str, 

123 session_date: Any, 

124 session_start_equity: float, 

125 session_end_equity: float, 

126 events: list[dict], 

127) -> dict[str, Any]: 

128 """Construct a session_summary experience event (Phase V2-19). 

129 

130 Pure function — no side effects, no I/O. Pushed by main.py at each 

131 session rollover (see main.py::_refresh_risk_state()), reusing 

132 experience.observation_metrics.compute_observation_summary() for every 

133 per-session statistic; computes nothing itself besides session_return. 

134 `session_date` accepts anything with an isoformat() (datetime.date) or 

135 falls back to str(). 

136 """ 

137 session_return = ( 

138 (session_end_equity - session_start_equity) / session_start_equity if session_start_equity else 0.0 

139 ) 

140 return { 

141 "event_id": str(uuid.uuid4()), 

142 "event_type": "session_summary", 

143 "created_at": datetime.now(tz=timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), 

144 "mode": mode, 

145 "session_date": session_date.isoformat() if hasattr(session_date, "isoformat") else str(session_date), 

146 "session_start_equity": session_start_equity, 

147 "session_end_equity": session_end_equity, 

148 "session_return": session_return, 

149 "observation_summary": compute_observation_summary(events), 

150 } 

151 

152 

153def build_option_strategy_outcome_event( 

154 *, 

155 mode: str, 

156 symbol: str, 

157 ticker: str, 

158 strategy_name: str, 

159 realized_pnl: float, 

160 entry_bar: int, 

161 exit_bar: int, 

162 contracts: int, 

163 entry_net_debit_or_credit: float, 

164 exit_net_debit_or_credit: float, 

165 regime: dict, 

166 moe_gating: dict, 

167 topology: dict, 

168 liquidity: dict, 

169) -> dict[str, Any]: 

170 """Construct an option_strategy_outcome experience event (V4.7, 

171 development/Problems.md #29's own framing) - the prerequisite data 

172 source a learned multi-leg strategy-selector model needs that does not 

173 exist anywhere else in this codebase: build_experience_event()'s own 

174 `portfolio.last_realized_pnl` field is symbol_key-keyed only (via 

175 experience/simulated_portfolio.py's SimulatedPortfolio), with no 

176 concept of "strategy" at all, so it can never be disaggregated by 

177 strategy_name after the fact. 

178 

179 Deliberately its OWN event shape (not shoehorned into 

180 build_experience_event()'s portfolio={...} sub-dict, which is keyed 

181 one-per-asset-per-bar) - a strategy close is a distinct, sparser 

182 occurrence than every-bar market_decision events. Pure function - no 

183 side effects, no I/O; pushed via the SAME ExperienceQueue.push() as 

184 every other event type here, no new Redis stream/channel. 

185 

186 regime/moe_gating/topology/liquidity are the SAME per-bar payload 

187 dicts main.py already threads into build_experience_event() at the 

188 bar this position was OPENED - train_strategy_selector.py reads these 

189 back as its feature vector, matching train_topology.py's own 

190 "regime.risk_score, topology.correlation_strength, liquidity score" 

191 extraction pattern (see that trainer's own docstring) rather than 

192 inventing a new feature vocabulary. No Postgres DDL change is needed 

193 for this new event_type - experience/postgres_worker.py::event_to_row() 

194 already stores the full payload generically and falls back 

195 action=event_type when no "action" key is present, so 

196 `WHERE action = 'option_strategy_outcome'` is already index-backed. 

197 """ 

198 return { 

199 "event_id": str(uuid.uuid4()), 

200 "event_type": "option_strategy_outcome", 

201 "created_at": datetime.now(tz=timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), 

202 "mode": mode, 

203 "symbol": symbol, 

204 "ticker": ticker, 

205 "strategy_name": strategy_name, 

206 "realized_pnl": realized_pnl, 

207 "entry_bar": entry_bar, 

208 "exit_bar": exit_bar, 

209 "contracts": contracts, 

210 "entry_net_debit_or_credit": entry_net_debit_or_credit, 

211 "exit_net_debit_or_credit": exit_net_debit_or_credit, 

212 "regime": regime, 

213 "moe_gating": moe_gating, 

214 "topology": topology, 

215 "liquidity": liquidity, 

216 } 

217 

218 

219class ExperienceQueue: 

220 """Fire-and-forget Redis Stream publisher. 

221 

222 All failures (connection errors, XADD errors, missing package) are 

223 caught and logged at WARNING level. push() never raises; the trading 

224 loop is never blocked. 

225 

226 Parameters 

227 ---------- 

228 enabled : kill switch — if False, push() is always a no-op 

229 redis_url : connection URL; overridden by AETHER_REDIS_URL env var 

230 stream_name : Redis key for XADD (default: "aether:experience") 

231 maxlen : approximate cap on stream length (MAXLEN ~) 

232 _client : pre-built Redis client for test injection 

233 async_enabled : V4.9 Priority 5 (development/Problems.md #14's own 

234 follow-up) - when True, push() enqueues onto a bounded 

235 background queue.Queue and returns immediately; a 

236 single daemon thread drains it and performs the real 

237 blocking XADD off the caller's hot path. Default False 

238 reproduces today's exact synchronous-XADD-in-push() 

239 behavior byte-identically - this is the one knob in 

240 this pass where "off" is a real behavior guarantee 

241 (in-order, at-least-attempted delivery every push() 

242 call), not just an unused code path, so the default 

243 matters specifically: a hard process kill while events 

244 sit in the background queue silently loses them, an 

245 honest tradeoff only acceptable for fire-and-forget 

246 telemetry, never core trading logic (which this queue 

247 has never been - see this module's own top docstring). 

248 """ 

249 

250 def __init__( 

251 self, 

252 enabled: bool = True, 

253 redis_url: str = "redis://localhost:6380/0", 

254 stream_name: str = "aether:experience", 

255 maxlen: int = 100_000, 

256 _client=None, 

257 async_enabled: bool = False, 

258 ) -> None: 

259 self.enabled = enabled 

260 self.stream_name = stream_name 

261 self.maxlen = maxlen 

262 self.async_enabled = async_enabled 

263 self._client = None 

264 self._background_queue: queue.Queue | None = None 

265 self._background_thread: threading.Thread | None = None 

266 

267 if not enabled: 

268 return 

269 

270 if _client is not None: 

271 self._client = _client 

272 else: 

273 url = secret_env("REDIS_URL", redis_url) or "redis://localhost:6380/0" 

274 try: 

275 import redis as redis_lib # deferred — not always installed in Lean environments 

276 

277 client = redis_lib.from_url(url, socket_connect_timeout=2, socket_timeout=2) 

278 client.ping() 

279 self._client = client 

280 logger.info( 

281 "ExperienceQueue connected to %s (stream=%s, maxlen=%d)", 

282 redact_url(url), 

283 stream_name, 

284 maxlen, 

285 ) 

286 except Exception as exc: 

287 logger.warning( 

288 "ExperienceQueue: Redis unavailable at %s — experience events will be skipped. (%s)", 

289 redact_url(url), 

290 exc, 

291 ) 

292 

293 if self.async_enabled and self._client is not None: 

294 self._background_queue = queue.Queue(maxsize=_BACKGROUND_QUEUE_MAXSIZE) 

295 self._background_thread = threading.Thread( 

296 target=self._drain_background_queue, 

297 name="ExperienceQueue-drain", 

298 daemon=True, 

299 ) 

300 self._background_thread.start() 

301 

302 def _xadd_sync(self, event: dict) -> bool: 

303 """The actual blocking Redis call - today's whole push() body, 

304 factored out so both the synchronous path (async_enabled=False) 

305 and the background drain thread (async_enabled=True) share the 

306 exact same XADD call and error handling, never two slightly- 

307 different implementations drifting apart.""" 

308 try: 

309 # V5.4.7 (Problems.md #120): sanitize before dumps - a NaN/inf 

310 # float serialized fine here but was rejected by PostgreSQL's 

311 # JSONB on the consumer side, wedging the pipeline; numpy 

312 # scalars raised TypeError and silently dropped the event. 

313 self._client.xadd( 

314 self.stream_name, 

315 {"payload": dumps_json_safe(event)}, 

316 maxlen=self.maxlen, 

317 approximate=True, 

318 ) 

319 return True 

320 except Exception as exc: 

321 logger.warning("ExperienceQueue.push failed: %s", exc) 

322 return False 

323 

324 def _drain_background_queue(self) -> None: 

325 """Runs on the single background daemon thread started in 

326 __init__ when async_enabled - blocks on queue.Queue.get() (cheap, 

327 no busy-polling) until an event or the shutdown sentinel arrives. 

328 One event at a time, in enqueue order, so delivery ordering within 

329 this process is preserved even though it's no longer synchronous 

330 with push().""" 

331 while True: 

332 event = self._background_queue.get() 

333 try: 

334 if event is _SHUTDOWN_SENTINEL: 

335 return 

336 self._xadd_sync(event) 

337 finally: 

338 self._background_queue.task_done() 

339 

340 def push(self, event: dict) -> bool: 

341 """Publish one event dict to the Redis Stream. 

342 

343 Returns True on success, False on any failure. Never raises, never 

344 blocks the caller. 

345 

346 In async mode (async_enabled=True), "success" means the event was 

347 successfully HANDED OFF to the background queue for eventual 

348 delivery, not that the XADD itself has completed or even 

349 succeeded yet - same fire-and-forget contract every existing 

350 caller already treats this return value with (none of them retry 

351 on False). A full background queue soft-drops the event (logged, 

352 never raises) rather than blocking - the same "never block the 

353 trading loop" guarantee the synchronous path has always had. 

354 """ 

355 if not self.enabled or self._client is None: 

356 return False 

357 if self.async_enabled and self._background_queue is not None: 

358 try: 

359 self._background_queue.put_nowait(event) 

360 return True 

361 except queue.Full: 

362 logger.warning("ExperienceQueue.push: background queue full (%d), dropping event", _BACKGROUND_QUEUE_MAXSIZE) 

363 return False 

364 return self._xadd_sync(event) 

365 

366 def flush(self) -> None: 

367 """Blocks until every currently-enqueued background event has been 

368 drained - a no-op when async mode isn't active (nothing to wait 

369 for). Useful for tests and for a caller that wants a delivery 

370 checkpoint (e.g. before process shutdown) rather than trusting the 

371 daemon thread alone; main.py never needs to call this in normal 

372 operation (`daemon=True` already guarantees no hang at interpreter 

373 exit, matching this class's own fire-and-forget philosophy).""" 

374 if self._background_queue is not None: 

375 self._background_queue.join()