Introduction

Pre-flight simulate a transaction. Halt the moment realized profit drifts from simulation predictions — before drift compounds into real capital loss.

predicted ──▶ simulate ──▶ submit ──▶ realized
    │                                    │
    └──────────────▶ reconcile ◀─────────┘
                        │
                     halt / continue

This book documents the design, mathematical invariants, and architectural boundaries of driftbrake. For installation and working examples, see the repository README.

Resource Directory

ResourceLocation
Source Repositorygithub.com/Xtley001/driftbrake
Rust Packagecrates.io/crates/driftbrake
Python Packagepypi.org/project/driftbrake-py
API Referencedocs.rs/driftbrake
  • Architecture: Workspace boundaries, concurrency patterns, persistence, and non-goals.
  • Whitepaper: Formal invariant proofs, multi-guard mathematics, and security trade-offs.
  • API Reference: Trait signatures, data types, and Python bindings.
  • Benchmark Methodology: Parameter calibration and empirical trade-off sweeps.
  • Technical Post-Mortem: Case study of simulation failure modes observed in production.

Architecture

This document describes the architectural structure of driftbrake: module boundaries, trait contracts, non-blocking asynchronous concurrency, state persistence, and Python bindings. For formal invariant proofs and mathematical derivations, see the whitepaper.

Design Goals

  1. Chain-Agnostic: Core trait boundaries impose zero assumptions regarding block time, consensus mechanisms, EVM version, or ABI encodings.
  2. Strategy-Agnostic: Decouples profit decoding from specific contract layouts, decentralized exchange routers, or liquidation venues.
  3. Focused Scope: Encapsulates simulation pre-flight, reconciliation, and halting. Alerting integrations, wallet management, and price oracles are deliberately excluded (see Non-goals).
  4. Swappable Backends: SimEngine is a pluggable trait. Teams with proprietary simulation infrastructure can integrate their custom backends while utilizing Driftbrake's reconciliation engine.
  5. Crash Resilience: State is persisted to a Write-Ahead Log (WAL) to ensure continuous risk enforcement across bot restarts.

Module Map

driftbrake/
├── core/                  # Chain-agnostic traits, zero REVM/alloy dependencies
│   ├── ProfitDecoder / RealizedProfitDecoder
│   ├── HaltPolicy / HaltDecision / HaltReason
│   └── RevertEvent / HistoryEntry
├── reconcile/             # Multi-guard HaltPolicy implementation
│   ├── Fast guard (consecutive acute drops)
│   ├── Slow guard (rolling mean drift)
│   ├── Revert-Burst & Gas budget guards
│   ├── Volume-Weighted drift guard (VWAR)
│   └── Net capital drawdown guard
├── journal/               # Crash-resilient binary Write-Ahead Log (WAL) with CRC32
├── receipt-poller/        # Receipt polling and profit realization gating
├── revm-backend/          # Concrete SimEngine implementation (in-process REVM forks)
├── driftbrake-py/         # Python bindings (PyO3, Stable ABI3, vectorized parameter sweeps)
├── benchmark/             # Threshold calibration harness and CLI
└── examples/
    └── toy-arbitrage/     # Minimal 2-pool arbitrage strategy wired end-to-end

Core Trait Boundaries

The generalization layer resides in driftbrake-core, which maintains zero dependencies on REVM or RPC clients.

ProfitDecoder

Decodes raw simulation execution traces into a strategy-denominated predicted profit figure:

pub trait ProfitDecoder: Send + Sync {
    /// Decode a raw execution trace or return value into predicted profit (e.g. wei).
    fn decode_predicted(&self, raw: &RawSimOutput) -> Result<PredictedProfit, DecodeError>;
}

Implementations must be pure and synchronous. Network I/O during decoding is prohibited.

RealizedProfitDecoder

Extracts realized profit from confirmed receipts and transaction logs, net of gas expenses:

pub trait RealizedProfitDecoder: Send + Sync {
    /// Decode a confirmed receipt and its logs into realized profit, net of gas cost.
    fn decode_realized(&self, receipt: &TxReceipt, logs: &[Log]) -> Result<RealizedProfit, DecodeError>;
}

Receipt status must be confirmed. Reverted transactions are handled separately and never passed to decode_realized.

HaltPolicy

Evaluates accumulated history to determine whether strategy execution remains safe:

pub trait HaltPolicy: Send + Sync {
    /// Evaluate the full reconciliation history and return a halt decision.
    fn evaluate(&mut self, history: &ReconcileHistory) -> HaltDecision;
}

The default institutional implementation is provided by driftbrake-reconcile.

Simulation Backend (driftbrake-revm-backend)

SimEngine executes candidate transactions against local state forks. Three implementation patterns are critical for production stability:

1. spawn_blocking Isolation

Simulating transactions in REVM is CPU-bound synchronous work. Executing simulations directly inside an async task starves Tokio worker threads, delaying mempool ingestion and block-processing routines. RevmBackend executes simulations within tokio::task::spawn_blocking thread pools, preserving async runtime responsiveness.

2. Bounded RPC Concurrency

Simulating multiple candidate transactions per block can saturate RPC rate limits if executed concurrently via unbounded joins. RevmBackend enforces a concurrency semaphore bounded by provider capacity (e.g. buffer_unordered(N)).

3. Block-Time Relative Timeouts

Fixed timeouts fail across diverse networks (e.g. 400ms on Arbitrum vs. 12s on Ethereum mainnet). RevmBackend calculates simulation timeouts dynamically as a configurable fraction of target block time.

Multi-Guard Reconciliation (driftbrake-reconcile)

driftbrake-reconcile implements an institutional multi-guard hierarchy evaluated on every new history entry:

GuardTrigger ConditionOperational Role
Revert-Burst$N$ consecutive on-chain revertsHalts on competitive front-running or stale state
Revert-Gas BudgetCumulative revert gas exceeds budgetCaps unproductive gas burn
Fast Guard$k_f$ consecutive ratios $< T_f$Detects sudden market dislocations or broken price feeds
Slow GuardRolling mean ratio $< T_s$Detects subtle, compounding drift bleed
Volume-WeightedVWAR across window $< T_v$Prevents large trade miscalculations masked by small trades
Net DrawdownRealized profit drops $> D_{\text{max}}$ from peakProtects accumulated portfolio capital

Ratio Direction Invariant

Ratios are computed strictly as $\text{realized} / \text{predicted}$. Computing the inverse $\text{predicted} / \text{realized}$ maps underperformance to values $> 1.0$, which causes guards to flag harmless overperformance while ignoring severe capital losses. This invariant is enforced through regression tests.

State Persistence (driftbrake-journal)

In high-frequency environments, process crashes or server restarts must not erase risk state. driftbrake-journal provides:

  • Append-Only Binary Log: Low-overhead disk logging for trade pairs and revert events.
  • Checksum Verification: Every binary frame includes an IEEE 802.3 CRC32 checksum.
  • Torn-Write Recovery: If a crash occurs mid-write, recovery truncates corrupted trailing bytes to the last verified frame.
  • Single-Writer Lock: File locking prevents multiple concurrent bot processes from corrupting shared state.

Python Integration (driftbrake-py)

To accommodate quantitative research and offline parameter optimization:

  • PyO3 & CPython Stable ABI: Compiled against abi3-py310, ensuring forward compatibility across Python 3.10–3.14+.
  • Vectorized Sweep Engine: run_sweep_raw evaluates parameter grids over historical datasets in compiled Rust with GIL release, testing millions of combinations per second.
  • Native Exceptions: Tripped decisions map directly to StrategyHaltedError.

Non-Goals

The following features are explicitly out of scope:

  • Alerting Integrations: Telegram, Discord, and Slack webhooks belong in external monitoring stacks.
  • Private Key Custody: Transaction signing and nonce tracking belong in execution wallets.
  • Fiat Price Feeds: USD conversion logic requires external oracles and does not belong in core traits.
  • Inventory Unwind: Position unwinding algorithms are specific to portfolio structures and are decoupled from circuit breaking.

Driftbrake: A Reconciliation-Based Halt Mechanism for Simulation-Driven Trading Strategies v0.2

Date: 2026-10-09
Author(s): Driftbrake Project

Note on math rendering. This document uses LaTeX-style notation ($...$ inline, $$...$$ display). GitHub renders math formulas natively; rendered views are also deployed to the project's documentation portal. All formulas include accompanying plain-text specifications and worked numerical examples.


Abstract

Automated trading strategies that execute based on an internal simulation—a local REVM fork, a mempool ordering heuristic, or an off-chain oracle model—face a structural operational risk: simulation drift. Over time, execution conditions diverge from simulated assumptions due to state contention, toxic flow, or stale pricing, leading strategies to execute trades that systematically underperform expectations or revert on-chain. Because individual executions appear unremarkable in isolation, drift often evades static alert thresholds and silently compounds into real capital loss. This paper specifies Driftbrake: an institutional reconciliation framework composed of five statistical and accounting guards that continuously evaluate the relationship between predicted profit, realized profit, and on-chain execution friction. We establish formal invariants for ratio-direction correctness, guard non-redundancy, and crash resilience via Write-Ahead Logging (WAL). Finally, we demonstrate parameter-tuning methodology via empirical false-halt versus missed-catch optimization.


1. Motivation and Background

High-frequency algorithmic trading strategies on EVM networks (MEV searchers, atomic arbitrageurs, liquidation bots) operate on a simulate-then-submit paradigm:

  1. State Forking: The bot forks state at pending block $N$ and evaluates candidate transactions locally.
  2. Profit Estimation: If local execution yields $\hat{p} > 0$, the transaction is signed and broadcast.
  3. Execution: The transaction confirms on-chain, realizing net profit $r$.

This paradigm introduces three failure modes independent of strategy correctness:

  • State Advancing (Latency Drift): State transitions occurring between local fork creation and block inclusion render simulated profit obsolete.
  • Adverse Execution Ordering: Miner/validator bundle reorganization or private order-flow front-running degrades realized fill prices.
  • Model Desynchronization: Stale RPC nodes or discrepancies in local EVM implementations (e.g. storage gas calculation nuances) yield systematically incorrect simulations.

Existing tooling optimizes forward simulation speed (e.g. in-process REVM forks) but lacks backward reconciliation verification. A strategy with sub-millisecond simulation will continuously bleed capital if no mechanism monitors the divergence between simulated predictions and realized outcomes.

Ad hoc safeguards—such as hardcoded consecutive loss rules—fail to address both acute execution shocks and insidious slow drift simultaneously. A robust risk engine requires independent, mathematically verifiable guards operating across distinct temporal and capital dimensions.


2. Design Overview

Driftbrake decouples strategy execution logic from risk enforcement via a pipeline of discrete accounting stages:

  1. Pre-flight Simulation: A candidate transaction is simulated via SimEngine, returning predicted profit $\hat{p}$.
  2. On-chain Submission & Confirmation: The transaction confirms. RealizedProfitDecoder extracts realized profit $r$ net of gas costs.
  3. History Ingestion: Chronological entries (successful trades and on-chain reverts) are appended to ReconcileHistory and persisted to a binary Write-Ahead Log (WAL).
  4. Multi-Guard Evaluation: Five independent guards evaluate the updated history:
    • Revert-Burst Guard: Detects rapid consecutive on-chain reverts or cumulative revert gas burn.
    • Fast Drift Guard: Detects sudden acute degradation in realized-to-predicted ratios over a short window.
    • Slow Drift Guard: Detects creeping underperformance across a rolling window.
    • Volume-Weighted Drift Guard (VWAR): Weights drift by capital magnitude to prevent small trades from masking large losses.
    • Net Drawdown Guard: Monitors absolute capital depletion against high-watermark profit.
  5. Circuit Breaking: If any guard triggers, execution halts immediately.
flowchart TD
    A[Candidate Transaction] --> B[SimEngine: Predicted Profit p_hat]
    B --> C{p_hat > 0?}
    C -->|No| D[Drop Transaction]
    C -->|Yes| E[Broadcast to Network]
    E --> F[Receipt Polled & Confirmed]
    F -->|Revert| G[Append RevertEvent to History & WAL]
    F -->|Success| H[Decode Realized Profit r]
    H --> I[Append Pair to History & WAL]
    G --> J{Evaluate Multi-Guard Policy}
    I --> J
    J -->|Revert Burst / Budget Trip| K[HALT STRATEGY]
    J -->|Fast Drift Trip| K
    J -->|Slow Drift Trip| K
    J -->|Volume-Weighted Trip| K
    J -->|Net Drawdown Trip| K
    J -->|All Guards Pass| L[CONTINUE STRATEGY]

3. Notation

SymbolDefinitionDimension / UnitsDefault
$\hat{p}_i$Predicted profit for transaction $i$Native currency (wei)—
$r_i$Realized profit for transaction $i$, net of gasNative currency (wei)—
$\rho_i$Realized-to-predicted ratio ($r_i / \hat{p}_i$)Dimensionless ($[0, \infty)$)—
$T_f$Fast guard ratio thresholdDimensionless$0.50$
$k_f$Fast guard window sizeInteger count$3$
$T_s$Slow guard mean ratio thresholdDimensionless$0.70$
$k_s$Slow guard rolling window sizeInteger count$20$
$N_{\text{rev}}$Maximum consecutive on-chain revertsInteger count$3$
$G_{\text{max}}$Maximum cumulative revert gas budgetGas units$500,000$
$T_v$Volume-weighted ratio thresholdDimensionless$0.65$
$k_v$Volume-weighted rolling window sizeInteger count$15$
$D_{\text{max}}$Maximum allowable net capital drawdownNative currency (wei)$\infty$ (disabled)
$H_n$History timeline containing $n$ total entriesSequence of events—

4. Mechanism Specification

4.1 Per-Transaction Ratio

For each confirmed transaction $i$ with $\hat{p}_i > 0$:

$$\rho_i = \frac{r_i}{\hat{p}_i} \tag{1}$$

Values of $\rho_i < 1.0$ indicate underperformance; $\rho_i \ge 1.0$ indicates execution equal to or exceeding expectation. Division direction is an inviolable invariant (Property 1).

Worked Example. A transaction simulated $\hat{p}_i = 100{,}000\text{ wei}$ and realized $r_i = 42{,}000\text{ wei}$ net of gas.
$$\rho_i = \frac{42{,}000}{100{,}000} = 0.42$$
Because $0.42 < 0.50$, transaction $i$ is flagged as an underperforming event.

Transactions with $\hat{p}_i \le 0$ are excluded from ratio computation to eliminate undefined division and prevent skewing rolling metrics.


4.2 Fast Guard (Acute Drift)

The fast guard trips if $k_f$ consecutive transactions fall below ratio threshold $T_f$:

$$\text{FastHalt}(H_n) = \begin{cases} \text{true} & \text{if } \forall j \in {n - k_f + 1, \dots, n}, , \rho_j < T_f \ \text{false} & \text{otherwise} \end{cases} \tag{2}$$

Worked Example. Given $T_f = 0.50$ and $k_f = 3$, let recent ratios be $[0.95, 0.90, 0.42, 0.38, 0.25]$.
The last three ratios all satisfy $\rho < 0.50$. FastHalt returns true, triggering immediate strategy shutdown.


4.3 Slow Guard (Creeping Drift)

The slow guard monitors rolling average performance across a wider window $k_s$:

$$\text{SlowHalt}(H_n) = \begin{cases} \text{true} & \text{if } \frac{1}{k_s} \sum_{j=n-k_s+1}^{n} \rho_j < T_s \ \text{false} & \text{otherwise} \end{cases} \tag{3}$$

Worked Example. With $T_s = 0.70$ and $k_s = 20$, assume 20 consecutive trades oscillate between $0.65$ and $0.72$ with a mean of $0.68$.
No single trade triggered the fast guard ($\rho > 0.50$), yet SlowHalt returns true because $0.68 < 0.70$, preventing long-term capital attrition.


4.4 Revert-Burst and Gas Budget Guards

On-chain reverts consume priority gas without generating revenue. Driftbrake isolates reverts from the ratio pool and evaluates them via dedicated operational guards:

  1. Consecutive Revert Burst: $$\text{RevertBurstHalt}(H_n) = \begin{cases} \text{true} & \text{if } \text{consecutive_reverts}(H_n) \ge N_{\text{rev}} \ \text{false} & \text{otherwise} \end{cases} \tag{4}$$

  2. Revert Gas Burn Budget: $$\text{RevertGasHalt}(H_n) = \begin{cases} \text{true} & \text{if } \sum_{j \in \text{recent_reverts}(k)} \text{gas_used}j > G{\text{max}} \ \text{false} & \text{otherwise} \end{cases} \tag{5}$$

Worked Example. A bot encounters 3 consecutive on-chain reverts with gas costs $[120{,}000, 150{,}000, 240{,}000]$.
If $N_{\text{rev}} = 3$, RevertBurstHalt triggers immediately. Even if $N_{\text{rev}} = 5$, total gas burned equals $510{,}000 > 500{,}000$, tripping RevertGasHalt.


4.5 Volume-Weighted Drift Guard (VWAR)

Unweighted ratios $\rho_i$ treat small transactions identically to large transactions. An adversary or market shift could yield ten small trades overperforming by $10%$ alongside one large trade underperforming by $80%$, masking severe losses under a simple arithmetic mean.

Driftbrake defines the Volume-Weighted Average Ratio (VWAR):

$$\rho_{\text{VWAR}}(k_v) = \frac{\sum_{j=n-k_v+1}^n r_j}{\sum_{j=n-k_v+1}^n \hat{p}_j} \tag{6}$$

$$\text{VolumeWeightedHalt}(H_n) = \begin{cases} \text{true} & \text{if } \rho_{\text{VWAR}}(k_v) < T_v \ \text{false} & \text{otherwise} \end{cases} \tag{7}$$

Worked Example. Consider two trades:

  • Trade 1: $\hat{p}_1 = 1{,}000\text{ wei}$, $r_1 = 1{,}200\text{ wei}$ ($\rho_1 = 1.20$)
  • Trade 2: $\hat{p}_2 = 1{,}000{,}000\text{ wei}$, $r_2 = 400{,}000\text{ wei}$ ($\rho_2 = 0.40$)

Arithmetic mean: $(1.20 + 0.40) / 2 = 0.80$ (passes a $0.70$ threshold).
Volume-weighted ratio: $$\rho_{\text{VWAR}} = \frac{1{,}200 + 400{,}000}{1{,}000 + 1{,}000{,}000} \approx 0.4008$$ At $T_v = 0.65$, VolumeWeightedHalt triggers, preventing whale mispricing from passing unnoticed.


4.6 Net Drawdown Guard

The drawdown guard tracks cumulative strategy profit $P_n = \sum_{j=1}^n r_j$ and peak profit $M_n = \max_{0 \le t \le n} P_t$:

$$\Delta_n = M_n - P_n \tag{8}$$

$$\text{DrawdownHalt}(H_n) = \begin{cases} \text{true} & \text{if } \Delta_n > D_{\text{max}} \ \text{false} & \text{otherwise} \end{cases} \tag{9}$$


4.7 Multi-Guard Evaluation Hierarchy

Driftbrake evaluates guards in order of increasing computational complexity and urgency:

$$\text{Halt}(H_n) = \text{RevertBurst} \lor \text{RevertGas} \lor \text{FastHalt} \lor \text{SlowHalt} \lor \text{VWAR} \lor \text{Drawdown} \tag{10}$$

Evaluation short-circuits on the first tripped guard, emitting a structured HaltReason for automated reconciliation.


4.8 Receipt-Gated Realization

Profit is booked if and only if:

  1. Transaction receipt status is confirmed (status == 1).
  2. An event log matching RealizedProfitDecoder is present and decodable.

Reverted receipts never enter the ratio pool; they are ingested into revert accounting. Unconfirmed or pending receipts are never evaluated.


4.9 Crash-Resilient State Persistence (WAL)

To prevent risk state loss across process restarts, ReconcileHistory is backed by an append-only binary Write-Ahead Log (driftbrake-journal):

  • Header: 16-byte fixed header (b"DRFT", format version 1, flags).
  • Framing: Length-prefixed records containing payload and IEEE 802.3 CRC32 checksums.
  • Torn-Write Recovery: During restart recovery, any incomplete or corrupt trailing bytes are detected via CRC mismatch and automatically truncated to the last valid frame.
  • Concurrency: Process-level advisory locks prevent multi-instance write conflicts.

5. Formal Invariants

Property 1 (Ratio-Direction Invariance).
For any transaction $i$ with $\hat{p}_i > 0$, the ratio is strictly defined as $\rho_i = r_i / \hat{p}_i$. The inverse $\hat{p}_i / r_i$ maps underperformance to values $> 1$ and overperformance to $< 1$. This would invert guard inequalities and cause strategies to halt on unexpected windfalls while failing to catch actual losses. Property 1 is enforced via deterministic regression tests in driftbrake-reconcile.

Property 2 (Guard Orthogonality).
The fast guard and slow guard are non-redundant. Let $T_f < T_s$. There exists a history $H_A$ where $\text{FastHalt}(H_A) = \text{false}$ and $\text{SlowHalt}(H_A) = \text{true}$ (gradual decay). There exists a history $H_B$ where $\text{FastHalt}(H_B) = \text{true}$ and $\text{SlowHalt}(H_B) = \text{false}$ (sudden drop after high historical profits). Removing either guard strictly degrades error detection.

Property 3 (Fast Guard Monotonicity).
Holding history $H_n$ constant, the fast guard decision is monotonic with respect to threshold:
$$T_f^{(1)} \le T_f^{(2)} \implies \text{FastHalt}{T_f^{(1)}}(H_n) \le \text{FastHalt}{T_f^{(2)}}(H_n)$$
Increasing $T_f$ monotonically increases sensitivity, strictly bounding false-halt versus missed-catch optimization.

Property 4 (Zero-Division Immunity).
For all transactions with $\hat{p}_i \le 0$, ratio calculation is bypassed. Evaluation over an empty or insufficient history ($n < k_f$) deterministically returns HaltDecision::Continue. No guard evaluation can produce a runtime panic or NaN.

Property 5 (Revert Separation).
Revert events update revert counters and gas burn tracking but never modify ratio history $H_n$. A reverted transaction cannot skew moving average ratios.

Property 6 (WAL Recovery Invariance).
Given a log containing $m$ valid frames and a trailing torn write of length $b > 0$, recovery yields an identical history state to a clean log containing $m$ frames, with the underlying file truncated to size $\sum_{j=1}^m \text{len}(\text{frame}_j) + 16$.


6. Security Considerations

Risk VectorAttack ScenarioMitigation
Slow-Bleed PoisoningAdversary manipulates price pools to keep trades just above $T_f$ while steadily bleeding capitalSlow guard ($T_s$) and Volume-Weighted guard ($T_v$) aggregate rolling underperformance and trip the circuit breaker
Whale MaskingStrategy executes many small profitable trades alongside one massive lossVolume-Weighted Average Ratio (VWAR) weights by capital volume, preventing small-trade masking
Revert FloodingAdversary front-runs transactions, causing consecutive reverts and burning priority gasRevert-Burst ($N_{\text{rev}}$) and Revert-Gas Budget ($G_{\text{max}}$) guards halt strategy before gas drain compounds
Process Restart ExploitationStrategy crashes or restarts, clearing in-memory history and resetting guard windowsJournaledHistory replays state from binary WAL on startup, preserving consecutive revert counts and ratios
Zero / Negative SpoofingAdversary or corrupted RPC produces zero or negative predicted profitGuard policy excludes $\hat{p} \le 0$ from ratio pool, logging distinct simulation anomalies
RPC Thread StarvationSynchronous simulation blocks executor threads, delaying halt evaluationSimEngine executes in dedicated spawn_blocking pools with bounded semaphores

7. Parameters

ParameterSymbolDefault ValueTuning Guidance
Fast Guard Threshold$T_f$$0.50$Decrease on volatile venues; increase on stable pairs
Fast Guard Window$k_f$$3$3 consecutive failures represents strong acute signal
Slow Guard Threshold$T_s$$0.70$Set to minimum acceptable strategy realization margin
Slow Guard Window$k_s$$20$Balance sample significance against detection lag
Max Consecutive Reverts$N_{\text{rev}}$$3$Bound against toxic flow or competitive front-running
Revert Gas Budget$G_{\text{max}}$$500{,}000\text{ gas}$Bound total non-productive gas burn per window
Volume-Weighted Threshold$T_v$$0.65$Protect capital sizing across asymmetric trade sizes
Volume-Weighted Window$k_v$$15$Rolling trade horizon for capital weighting
Net Drawdown Threshold$D_{\text{max}}$Disabled ($\infty$)Absolute stop-loss buffer from portfolio peak

8. Comparison to Prior Work

CapabilityStandard Sim Tooling (e.g. raw REVM)Ad-Hoc ScriptsDriftbrake v0.2
In-Process Transaction SimulationYesYesYes (via SimEngine)
Chain-Agnostic Profit DecodingNoNoYes (ProfitDecoder)
Acute Drift DetectionNoSingle heuristicYes (Fast Guard)
Creeping Bleed DetectionNoNoYes (Slow Guard)
Capital-Weighted Drift (VWAR)NoNoYes
Dedicated Revert-Burst & Gas GuardNoNoYes
Crash-Resilient WAL PersistenceNoNoYes (driftbrake-journal)
Compiled Python Backtesting EngineNoNoYes (driftbrake-py)
Ratio Invariant Formal ProofsNoNoYes (Properties 1–6)

9. Conclusion

Driftbrake delivers an institutional-grade risk engine for automated EVM trading strategies. By monitoring the empirical divergence between simulated pre-flight estimates and realized on-chain execution, Driftbrake closes the critical verification loop left open by forward-only simulation engines. Through five orthogonal guards, binary Write-Ahead Log persistence, and compiled Python bindings, Driftbrake prevents simulation drift from compounding into catastrophic capital loss.


10. References

  1. REVM: Rust Ethereum Virtual Machine. https://github.com/bluealloy/revm
  2. Tokio Async Runtime: spawn_blocking and resource isolation. https://tokio.rs
  3. IEEE 802.3: Carrier Sense Multiple Access with Collision Detection (CRC32 Specification).
  4. CPython Stable ABI: PEP 384 — Defining a Stable Application Binary Interface.

API Reference

This document specifies the trait contracts, data structures, and persistent storage APIs in driftbrake.


Data Types (driftbrake-core)

PredictedProfit and RealizedProfit

pub struct PredictedProfit(pub i128);
pub struct RealizedProfit(pub i128);

Both values are signed 128-bit integers denominated in the strategy's native unit (e.g. wei).

  • PredictedProfit: Estimated profit returned by pre-flight simulation. Values $\le 0$ are excluded from ratio calculations.
  • RealizedProfit: Actual on-chain profit extracted from confirmed transaction receipts, net of all gas expenses.

RevertEvent and HistoryEntry

pub struct RevertEvent {
    pub tx_hash: [u8; 32],
    pub block_number: u64,
    pub revert_reason: Option<String>,
    pub gas_used: u64,
    pub effective_gas_price: u128,
}

pub enum HistoryEntry {
    Pair(PredictedProfit, RealizedProfit),
    Revert(RevertEvent),
}

HistoryEntry maintains the chronological timeline of execution events. Reverts are tracked separately from the profit ratio pool to prevent skewing moving averages.

HaltDecision and HaltReason

pub enum HaltDecision {
    Continue,
    Halt(HaltReason),
}

pub enum HaltReason {
    FastGuard { window: Vec<f64>, threshold: f64 },
    SlowGuard { mean_ratio: f64, window_size: usize, threshold: f64 },
    RevertBurst { consecutive_reverts: usize, threshold: usize },
    RevertGasBudgetExceeded { total_gas_burned: u64, budget: u64 },
    VolumeWeightedDrift { volume_weighted_ratio: f64, threshold: f64 },
    NetDrawdownExceeded { current_drawdown: i128, max_drawdown: i128 },
    Custom(String),
}

HaltReason provides structured metadata enabling automated incident handling and telemetry logging.


Traits (driftbrake-core)

ProfitDecoder

pub trait ProfitDecoder: Send + Sync {
    fn decode_predicted(&self, raw: &RawSimOutput) -> Result<PredictedProfit, DecodeError>;
}
  • Obligation: Pure decode from RawSimOutput (EVM return data, gas, and revert status) into a PredictedProfit.
  • Constraint: Must not perform asynchronous network I/O or database access.

RealizedProfitDecoder

pub trait RealizedProfitDecoder: Send + Sync {
    fn decode_realized(&self, receipt: &TxReceipt, logs: &[Log]) -> Result<RealizedProfit, DecodeError>;
}
  • Obligation: Extract strategy profits from confirmed transaction logs, subtracting gas costs (receipt.gas_used * receipt.effective_gas_price).
  • Constraint: Must only be invoked on receipts with TxStatus::Confirmed.

HaltPolicy

pub trait HaltPolicy: Send + Sync {
    fn evaluate(&mut self, history: &ReconcileHistory) -> HaltDecision;
}
  • Obligation: Evaluate history and return a HaltDecision.
  • Constraint: Must handle empty and short histories without panicking.

State Persistence (driftbrake-journal)

JournaledHistory

use driftbrake_journal::JournaledHistory;

let mut journal = JournaledHistory::open("path/to/reconcile.wal")?;

// Appends pair to in-memory history and flushes CRC32-verified frame to disk
journal.append(PredictedProfit(1_000_000), RealizedProfit(950_000))?;

// Appends revert event
journal.append_revert(revert_event)?;

// Access underlying history
let history: &ReconcileHistory = journal.history();
  • Torn-Write Protection: Automatically truncates corrupted partial writes at EOF upon initialization.
  • Process Lock: Acquires an exclusive file lock, preventing concurrent process writes.

Python API (driftbrake-py)

Native CPython extension compiled with Stable ABI (abi3-py310).

from driftbrake import ReconcileHistory, ReconcilePolicy, StrategyHaltedError

# Initialize policy
policy = ReconcilePolicy(
    fast_window=3,
    fast_threshold=0.50,
    slow_window=20,
    slow_threshold=0.70,
    max_consecutive_reverts=3,
    max_revert_gas_budget=500_000,
    volume_weighted_window=15,
    volume_weighted_threshold=0.65,
    max_drawdown=10_000_000,
)

history = ReconcileHistory()
history.append(predicted_profit=1_000_000, realized_profit=950_000)

decision = policy.evaluate(history)
if decision.is_halted:
    raise StrategyHaltedError(decision.reason)

Vectorized Backtesting (run_sweep_raw)

from driftbrake import run_sweep_raw

# pairs: list of (predicted_profit, realized_profit)
# fast_windows, fast_thresholds, slow_windows, slow_thresholds: lists of parameters
results = run_sweep_raw(
    pairs,
    fast_windows=[2, 3, 4],
    fast_thresholds=[0.40, 0.50, 0.60],
    slow_windows=[15, 20, 25],
    slow_thresholds=[0.65, 0.70, 0.75],
)
# Returns list of dicts: {'fast_window', 'fast_threshold', 'slow_window', 'slow_threshold', 'halted', 'halt_index', 'reason'}

Benchmark Methodology

This document outlines the parameter selection methodology implemented in driftbrake-benchmark (cargo run --release -p driftbrake-benchmark).

Overview

Guard parameters ($T_f = 0.50, k_f = 3, T_s = 0.70, k_s = 20$) balance two competing operational risks:

  • False Halt: The guard halts on an execution sequence where performance remains acceptable, but normal market noise triggered threshold conditions.
  • Missed Catch: The guard fails to halt on an execution sequence experiencing genuine simulation drift, allowing capital losses to accumulate.

Tightening thresholds (raising $T_f$ or $T_s$, or reducing window sizes) decreases missed catches at the expense of increased false halts. Loosening thresholds reverses the trade-off.

Synthetic Data Regimes

The benchmark evaluates candidate parameter sets against synthetic transaction pairs $(\hat{p}_i, r_i)$ generated across two regimes:

  • Healthy Regime: $r_i = \hat{p}_i \cdot (1 + \varepsilon_i)$ where $\varepsilon_i \sim \mathcal{N}(0, \sigma^2)$ models ordinary execution slippage.
  • Drifted Regime: $r_i = \hat{p}i \cdot (\mu{\text{drift}} + \varepsilon_i)$ where $\mu_{\text{drift}} < 1.0$ models systematic divergence between simulation and on-chain reality.

To ensure deterministic reproducibility across platforms, pseudorandom sequences are generated via an internal Xorshift PRNG rather than non-deterministic system seeds.

Parameter Sweep Procedure

For each candidate configuration tuple $(T_f, k_f, T_s, k_s)$:

  1. Healthy Evaluation: Execute the policy across healthy sequences. Record occurrences and indices of false halts.
  2. Drifted Evaluation: Execute the policy across drifted sequences. Record occurrences and detection latencies (time-to-catch).
  3. Metric Aggregation: Compute the false-halt rate ($P_{\text{FH}}$) and missed-catch rate ($P_{\text{MC}}$).
False Halt Rate
     ^
     |                                        *  (Permissive thresholds:
     |                                     *      minimal false halts,
     |                                  *         delayed drift detection)
     |                              *
     |                        *  <- Shipped defaults (0.50 / 0.70)
     |                  *
     |            *
     |       *
     |  *                                      (Strict thresholds:
     +------------------------------------->     rapid drift detection,
                Missed Catch Rate                 frequent false halts)

Running the Benchmark

# Run default parameter sweep
cargo run --release -p driftbrake-benchmark

# Run custom noise and drift scenarios
cargo run --release -p driftbrake-benchmark -- --noise 0.15 --drift-mean 0.40

Calibrating on Historical Data

When deploying Driftbrake to a new blockchain or strategy profile:

  1. Collect Historical Pairs: Record at least 500 confirmed $(\hat{p}, r)$ transactions under standard operating conditions.
  2. Measure Natural Variance: Calculate sample standard deviation $\sigma_{\text{slippage}}$ and historical realization ratios.
  3. Run Backtest Grid: Use driftbrake-py's run_sweep_raw to simulate candidate threshold grids against your historical series.
  4. Select Risk Point: Choose parameters matching your operational risk appetite (e.g. prioritizing capital preservation vs. minimizing manual reset interventions).

Phantom Profit: Three Production Simulation Bugs

This document details three structural failure modes observed in production simulate-then-submit trading systems. Unlike application-level logic errors, these issues manifest as silent capital decay while individual transaction logs appear nominally successful.

Pipeline Architecture

Algorithmic execution loops (MEV searchers, atomic arbitrageurs, liquidators) follow a four-stage lifecycle:

  1. Fork State: Replicate current blockchain state via local EVM or JSON-RPC.
  2. Pre-flight Simulate: Execute candidate transactions against forked state to verify profitability.
  3. Broadcast: Submit profitable transactions to block builders or public mempools.
  4. Confirm: Ingest transaction receipts upon block inclusion.

When execution conditions change between simulation and inclusion, this lifecycle produces simulation drift.

Failure Mode 1: Backward Ratio Calculation

Reconciliation evaluates realized profit against simulated expectation. The natural formulation is:

$$\rho = \frac{\text{realized}}{\text{predicted}}$$

Values $\rho < 1.0$ indicate underperformance; values $\rho \ge 1.0$ indicate performance meeting or exceeding prediction.

Inverting this formula yields:

$$\rho_{\text{inv}} = \frac{\text{predicted}}{\text{realized}}$$

Under inversion, underperformance yields $\rho_{\text{inv}} > 1.0$, while profitable outperformance yields $\rho_{\text{inv}} < 1.0$. If downstream guards evaluate ratio < threshold without inverting comparison operators, two catastrophic conditions occur:

  • Profitable trades that exceeded simulation are incorrectly flagged as anomalies.
  • Trades that severely underperformed pass through without triggering circuit breakers.

Because both formulas output positive floating-point numbers, inversion produces plausible log outputs that bypass casual inspection. Driftbrake enforces ratio direction as an invariant protected by automated regression tests.

Failure Mode 2: Worker-Thread Starvation

In asynchronous Rust runtimes (e.g. Tokio), CPU-bound operations executed inside async functions block the underlying worker thread.

Both in-process REVM execution and synchronous JSON-RPC calls occupy CPU threads for multiple milliseconds. Executing these routines directly within an async fn prevents the worker thread from yielding to concurrent tasks. This starves the main block-listener loop, increasing latency between block observation and candidate transaction submission.

Remediation

Wrap CPU-intensive simulation routines in tokio::task::spawn_blocking. This offloads heavy computation to a dedicated thread pool, preserving asynchronous runtime throughput.

Failure Mode 3: RPC Provider Rate-Limit Saturation

A volatile block can yield 50 or more simultaneous trading candidates. Attempting to simulate all candidates concurrently via unbounded futures (join_all) causes immediate request bursts.

External RPC providers enforce aggressive rate limits. Unbounded concurrency triggers HTTP 429 throttling during high-opportunity blocks—precisely when execution speed is most critical.

Remediation

Enforce bounded concurrency via provider-calibrated semaphores (e.g. buffer_unordered(N)). Bounding concurrent requests to provider limits eliminates throttling while maintaining maximum sustainable throughput.

Multi-Guard Reconciliation

Resolving execution bugs ensures mechanical reliability but does not prevent market-driven simulation drift. Price oracle delays, mempool bundle competition, and execution slippage require automated reconciliation:

  • Acute Shocks: Handled via the Fast Guard ($k_f$ consecutive underperformances).
  • Creeping Decay: Handled via the Slow Guard (rolling mean across $k_s$ transactions).
  • Asymmetric Capital Sizing: Handled via Volume-Weighted Drift (VWAR).
  • Toxic Flow & Front-Running: Handled via Revert-Burst and Revert-Gas Budget guards.

Continuously evaluating the gap between predicted and realized profit guarantees that operational divergence is intercepted before capital bleed compounds.