Repository navigation
0.144.0: Yet more tests and refactors. - #37
Conversation
Without --all-features the tests behind feature gates (trade_aggregation) are not built, so cargo-mutants reports all mutants in that code as missed.
Each pub wrapper only discarded the realized pnl of its pub(crate) twin, had no callers and therefore no tests (cargo-mutants could replace their bodies). Keep a single pub(crate) function each, returning the realized pnl. Breaking: Account::change_position and Account::fill_best are no longer public.
…cancellation - StopOrder::cancelled_event replaces 18 copies of the StopOrderEvent::Cancelled literal in Exchange and PortfolioExchange. - PendingStops::take_all replaces drain_all and the 4 callers that each sized a Vec before draining into it. It keeps the store's capacity, which try_insert enforces. - PendingStops::remove and get_by_id share one lookup. cargo-mutants found that no test cancelled a stop: remove could drop the wrong stop and cancel_all_stop_orders could return nothing. New tests cover cancel by OrderId and UserOrderId, NotFound, cancel-all, its rate limit and take_all.
VolumeCandle copied the fields, the constructor checks, the price validation and the fill condition of Candle. It now wraps a Candle and only adds the participation caps. Candle::limit_order_filled lost a match with two equal arms, and the candle! macro is removed: it could not compile (private fields, no timestamp). cargo-mutants found that only the buy side of VolumeCandle was tested, through one exchange test: the sell side, the market state, the timestamp, the price range used to elect stops and Candle::can_fill_bids were not. The new unit tests cover both sides, the bar extremes, zero participation and validation. Breaking: VolumeCandle serializes its prices under a nested "candle" key. Its Display output now uses the Candle format.
- The constructor built the buy and the sell levels with two copies of the same loop, with Vec::push under allow attributes. into_cumulative_levels now merges each sorted flow in place (dedup_by plus a prefix sum) and shrinks it. - limit_order_filled had a copy per side. It now picks the opposite flow and its level, then shares the fill. The low/high early return is gone: no taker trade is priced outside the low/high, so rposition finds no level in that case anyway. - deplete_cumulative_levels relies on the levels being non-decreasing (now debug-asserted) and subtracts directly instead of flooring at zero. cargo-mutants found that a second fill from the same candle was not tested, so the depletion could add volume, and that price_range (used to elect stops) could return None. New tests cover successive fills, exhaustion, fills at the traded price, the range and Display.
… bounds check_market_buy_order and check_market_sell_order were mirror copies. A single check_market_order now works out the quantity the order opens and the margin it releases (both zero when it only adds to the position), then compares once. The maintenance check and isolated_liquidation_price use Position::side instead of two mirrored branches and a quantity comparison. margin_exceeds_risk is folded in. cargo-mutants found no test at the exact balance limit, and no test of a flip: the opened quantity could be order/position instead of order - position. New tests cover exactly the available balance (admitted) and one unit more (rejected) for open, add and flip on both sides, a pure reduce, and limit-order admission.
…ing paths Bugs found while removing the duplicated amend code of Exchange and PortfolioExchange: - amend_limit_order acquired a rate-limit slot itself and then a second one through submit_limit_order. An amend at the last free slot failed with RateLimitReached. - Exchange::amend_limit_order cancelled an already-filled order through the rate-limited cancel_limit_order(..).expect(..), so it panicked when the amend had taken the last slot. Both amends now rest the replacement through a new rest_limit_order_no_rate_limit, which submit_limit_order also uses after it takes its slot. Shared helpers replace repeated code: - LimitOrder::would_take_liquidity (marketable and not post-only) replaces 7 hand-written forms of that condition. The amend pre-check is gone: the resting path rejects the same orders, and the original order is restored. - AmendLimitOrderError::order_not_on_book picks OrderNoLongerActive or OrderIdNotFound for both venues. PortfolioExchange::amend_limit_order now reports a rejected replacement as AmendLimitOrder(SubmitLimitOrder(..)), like Exchange. Before, only WouldExecuteImmediately was wrapped that way. Tests: the last rate-limit slot (Exchange and Portfolio), already-filled amend at the last slot, inactive vs unknown ids, a crossing post-only replacement, and a GTC amend (cargo-mutants found that all amend tests used post-only orders).
…st resting GTC validate_order_notional had its own copy of the max-notional check for reduce-only orders. It now calls NotionalFilter::validate_order_notional and only ignores NotionalTooLow for reduce-only orders. NotionalFilter::new ensures min <= max, so an order below the minimum is never above the maximum. cargo-mutants found that only post-only limit orders were tested against the notional filter, and no test checked that max_notional is inclusive. New tests cover a resting GTC order at both inclusive bounds and one step outside, on Exchange and PortfolioExchange, plus a unit table for plain and reduce-only orders.
…nd unquoted marks update_market skipped stop election and limit fills on a delisted market. But delist_market cancels all of the market's orders, and every submit, amend and stop path rejects a delisted market, so the skip could never matter (cargo-mutants could negate it). The invariant is now asserted instead. MarketSlot::unrealized_pnl drops its zero-position check: Position::unrealized_pnl_marked already returns zero for a neutral position. Tests: - A delisted market reports its forced stop cancel, rejects every order entry point, and ignores a crossing candle. - MarketSlot::unrealized_pnl is zero without a two-sided book. - CrossMarginRiskEngine::estimated_liquidation_price returns None for a neutral position and for a non-positive reference price.
cargo-mutants found that no test checked equality at these thresholds: - Isolated reconcile: equity exactly at the maintenance margin is not liquidated (it is an InitialMarginDeficit), one step below is. - Cross: mark-to-market equity exactly at the maintenance requirement is not liquidated, one step below is. - Cross estimated liquidation price: a price of exactly 0 is None. - Trade: a buy trade at the limit price does not fill a sell order (same as for buys), and a sell trade cannot fill asks. PortfolioExchange::force_liquidate_portfolio picked the close price with two mirrored branches. MarketSlot::liquidation_close now computes the side and the opposite quote, falling back to the entry price on an empty side. A table test covers both sides and every empty-side combination (>= vs > was not tested).
Exchange::restore_stop_order_event_capacity, PortfolioExchange::reset_stop_events and the Clone impls of PendingStops and SortedOrders each restored a Vec capacity by hand, like utils::reserve_to_capacity. They now call it. reserve_to_capacity passes capacity.saturating_sub(len) to reserve_exact, which does nothing when the capacity already fits, so it needs no branch. push_stop_event calls it directly instead of through a separate cold function. cargo-mutants found that only some of these copies were tested, and that some mutants changed nothing observable (== vs != on the capacity check, < vs <=). A unit test now covers growth, kept contents and an existing capacity.
Mutants that changed nothing pointed at code which can be simpler: - execution_rules::clamp_reduce_only_market_order replaces the copies in Exchange and PortfolioExchange::submit_market_order. It sets the clamped quantity unconditionally (it is never larger), like LimitOrder::clamp_to_reduce_only_room now does with min. - capped_clearance_fee is max(min(fee, equity_left), 0). - Position::funding_cashflow loses its zero-quantity/zero-rate early return: the product is zero then anyway. - StopOrder::trail_to compares through one side-aware closure instead of two mirrored matches. Position::notional_at_price keeps its zero-price guard: for inverse contracts the notional is quantity / price, and a new test shows it must not divide by zero (cargo-mutants could remove the guard).
- #[mutants::skip] on the unreachable limit_order_filled of Bba and MarkPriceUpdate: the venues only call it for updates with CAN_FILL_LIMIT_ORDERS. - .cargo/mutants.toml exclude_re for six provably equivalent mutants: Zero via Default, the zero-equity edge in apply_to_equity, equal prices in trail_to, the num_reduce_only fast path and the reduce-only clamp kept as defence in depth in apply_limit_fill. Each entry gives its reason. The entries match the name without the line number, so they survive unrelated edits. After this, missed.txt lists only real test gaps.
SummaryThe PR consolidates the IssuesNone |
SummaryThe PR refactors the exchange internals: merges the IssuesNone |
No description provided.