Skip to content

Hardening P1-P4: eyes, brakes, adverse selection, Bayesian brain - #8

Open
arena-ai-coding-agent[bot] wants to merge 3 commits into
mainfrom
arena/01a0f487-bot-crowdintel
Open

arena-ai-coding-agent[bot] wants to merge 3 commits into
mainfrom
arena/01a0f487-bot-crowdintel

Conversation

@arena-ai-coding-agent

@arena-ai-coding-agent arena-ai-coding-agent Bot commented Oct 1, 2026 •

Copy link
Copy Markdown

Four protective layers over the ultra-low-latency hot path (tick-to-wire < 50 µs objective; layered steady-path overhead ≈ +0.33 µs p50, far inside the +5 µs P99 budget). No existing module removed or renamed — pure extension.

P1 Eyes — private user WSS accounting (AccountEvent), lock-free PositionTracker (net qty, VWAP entry, open qty per order), pre-fire reservation checks, periodic REST reconciliation with kill-switch latch on drift.
P2 Brakes — always-on RiskManager: market/portfolio exposure caps, stop-loss on liquidation mark vs VWAP, hedge on the complement token with real-time unrealized P&L, daily-loss kill switch that freezes and cancels.
P3 Adverse selection — VolatilityGate (spread width + mid-change rate regimes) driven dynamic pre-signed ladder TTL, >5%/100 ms mid-jump shock cooldown, slippage gate vs current mid (rejects stale/toxic slots pre-signature).
P4 Brain — closed-form Bayesian engine (Beta-Binomial from mid-seeded prior, Dirichlet-Multinomial, sigmoid log-LR shifts): posterior update ≈ 41 ns p50 / read ≈ 39 ns p50, no heap/virtuals. Cold-thread NDJSON evidence ingestion + hot-reloadable source reliability; trusted evidence (prior 0.40 → 0.557) emits exactly one BAYES_SIGNAL through the same pipeline as alpha (brakes/TTL/slippage all apply); sub-floor reliability is gated and journaled.

Paper trading honesty — BOT_MODE=mock now synthesizes venue fills for accepted mock orders into the account queue and feeds a tight, continuously refreshed book: tracker, brakes and brain observe real flow end to end (30 s smoke: 149 orders/149 fills, 1 BAYES_SIGNAL, 0 tracker anomalies, sell-before-fill correctly gated).

Verification: 4/4 ctest green; check_latency.py 7/7 budgets pass; docs updated (CONFIGURATION P4 table, PERF baseline F3/F4 sections, README status).


Summary by cubic

Adds four protective layers over the ultra-low-latency hot path, with no existing module removed or renamed: private user-channel accounting with venue reconciliation (P1), an always-on risk manager with stop-loss/hedging and a daily-loss kill switch (P2), an adverse-selection volatility gate with dynamic ladder TTL and shock cooldowns (P3), and a closed-form Bayesian signal engine with NDJSON evidence ingestion (P4). Layered overhead is ~+0.33 µs p50, inside the +5 µs P99 budget.

P1-P3: accounting, brakes, adverse selection

  • Private user WebSocket normalizes to fixed-point account events; a lock-free position tracker handles reservations, VWAP entry, and periodic REST reconciliation that latches a kill switch on drift.
  • Risk manager caps exposure, triggers stop-loss on liquidation mark vs VWAP, hedges on the complement token, and freezes and cancels on daily loss.
  • Volatility gate tightens pre-signed ladder TTL, cooldowns >5%/100 ms mid jumps, and rejects stale/toxic slots against the current mid before signing.

P4: Bayesian brain and paper trading

  • Closed-form Bayesian engine (Beta-Binomial mid-seeded prior, Dirichlet-Multinomial, sigmoid log-LR shifts): ~41 ns update / ~39 ns read, no heap, no virtuals; trusted evidence emits exactly one BAYES_SIGNAL through the same pipeline as alpha.
  • Cold-thread NDJSON evidence ingestion with hot-reloadable source reliability; below-floor reliability is gated and journaled.
  • BOT_MODE=mock now synthesizes venue fills and a continuously refreshed book so tracker, brakes, and brain observe real flow end to end.

Verification: 4/4 ctest green, 7/7 latency budgets pass, docs updated.

Written for commit 1d25514. Summary will update on new commits.

Review in cubic

Adlgr87 and others added 3 commits October 1, 2026 00:36
- WsMarketListener: optional subscribe_token override so a second isolated
  connection feeds the complement-token book (single-writer per book).
- main: create hedge OrderBookL2 + listener when BOT_HEDGE_TOKEN_ID is set;
  wire layers.hedge_book; clean stop.
- tests: engine_hedge_on_dip integration (dip -> one hedge buy on complement,
  hedge fill builds net_hedge, no duplicate hedge, nothing realized).
- docs: baseline updated with post-F2 benchmark comparison (no hot-path
  degradation: pool-hit p99 ~0.74us vs ~0.81us baseline, sandbox noise).

Local sandbox note: secp256k1 built from PyPI coincurve 17.0.0 vendored source
(GitHub unreachable); production/CI pins remain authoritative.

Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>
…ldown

- core/include/volatility_gate.hpp: cold sampler classifies book regime
  (spread width / mid-change rate) and publishes effective ladder TTL,
  size permille, and pause through atomics; hot loop owns the >5%/<100ms
  shock FSM with 250ms cooldown; slippage-vs-mid gate (BOT_POOL_MAX_DEV_BPS).
- Pool acquire_at_most gains optional dynamic TTL cap (default-arg, bench
  and legacy callers keep static TTL).
- Engine: continuous mid observation, regime transitions journaled
  (VOLATILITY_ENTER/EXIT), shocks journaled once (POOL_STALE_DROP), paused
  signals consumed+discarded (VOLATILITY_PAUSED), slippage abort pre-sign
  (STALE_PRICE_ABORT), size shrink + dynamic TTL at dispatch.
- main: gate wired through layers; presign thread feeds the sampler at
  ~100Hz.
- tests: vol_gate units (regimes, shocks, slippage), pool dynamic TTL,
  engine acceptance (6% jump <100ms -> stale order suppressed, journaled,
  flow resumes after cooldown at refreshed prices).
- bench: new lane decision+pool+layers+mock-submit through all P1-P3 layers
  (p50 784ns / p99 1162ns vs bare 465/836: ~+0.33us, 15x under the +5us
  budget); check_latency budget row added.
- docs: CONFIGURATION gains P1/P2/P3 knob tables; README deployment status.

Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>
BayesianEngine (core/include/bayesian_engine.hpp): Beta-Binomial slots
seeded from mid (N0 pseudo-count), Dirichlet-Multinomial multi-outcome rows,
log-LR shifts via sigmoid; update ~41ns p50 / read ~39ns p50 (RDTSC lanes),
no heap, no virtuals, bounded fixed arrays.

Evidence_ingress (core/src/evidence_ingress.hpp): cold-thread NDJSON
replay/tail (count and lr x1e6 event formats), id:weight source table parser,
recalibration file hot reload. SourceReliability floor gates evidence in the
hot drain (BAYES_LOW_RELIABILITY journal), per-source dedup ring for the 32
most recent evidence hashes.

ExecutionEngine brain drain: bounded SPSC pop each tick (anti-stall cap),
one-shot prior seeding from mid, divergence trigger emits a synthetic
AlphaSignal through the SAME pipeline as alpha (brakes, pool TTL, slippage
gate all still apply), one emission per evidence batch via generation tag.

Paper trading honesty (user deliverable): MockCLOBClient synthesizes venue
FILLs for accepted mock orders into the account queue, so P1 tracker, P2
brakes and P4 brain observe identical flow to live; mock feed now publishes
a tight continuously-refreshed book (~100bps slip, mid pinned, NORMAL
regime) alternating BUY/SELL hints. 30s smoke: 149 orders/149 fills, 1
BAYES_SIGNAL, tracker anomalies=0, sell-before-fill correctly gated
(no_inventory), realized paper P&L tracked.

Tests: bayes_math (exact posterior 0.5568, LR shift, Dirichlet 0.30/0.45/0.25,
guards) + engine_brain_acceptance (seed once, low-reliability gate emits
nothing, trusted evidence -> exactly one BAYES_SIGNAL, no repeat without new
evidence). 4/4 ctest green; layered lane p50 ~754ns p99 ~1.1us (< +5us
budget); docs/CONFIGURATION P4 table, BASELINE F4 section, README status.

Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>
@coderabbitai

coderabbitai Bot commented Oct 1, 2026 •

Copy link
Copy Markdown

Important

Review skipped

This PR was authored by a bot without an assigned CodeRabbit review seat. Ask an organization administrator to assign a seat to the bot. See the seat-assignment guide. After the seat is assigned, request a review again.

⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Advanced

Run ID: c9b8bcbe-c922-46b5-8769-efc79a4e67f1

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Autopilot is currently an internal CodeRabbit preview.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@Adlgr87
Adlgr87 enabled auto-merge (rebase) October 1, 2026 09:31
@Adlgr87
Adlgr87 disabled auto-merge October 1, 2026 09:31
@coderabbitai

coderabbitai Bot commented Oct 1, 2026

Copy link
Copy Markdown

Autopilot could not be updated. Open Coding to check access and billing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant