Skip to main content

nautilus_live/execution/
reconciliation.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! Reconciliation snapshots, outcomes, state-independent decisions, and targeted report collection.
17//!
18//! Shared types describe prepared checks and report results. Functions compare reports,
19//! validate fill groups, replay inferred-fill history, and calculate reconciliation quantities.
20//! Targeted requests collect order status and missing fills for the manager and live node.
21//! The manager owns cache-dependent decisions; the live node owns recurring task lifecycles.
22
23use std::{borrow::Cow, time::Duration};
24#[cfg(feature = "node")]
25use std::{cell::RefCell, rc::Rc};
26
27use indexmap::{IndexMap, IndexSet};
28use nautilus_common::{
29    clients::ExecutionClient,
30    enums::LogLevel,
31    live::dst,
32    messages::execution::{
33        TradingCommand,
34        report::{
35            GenerateFillReports, GenerateOrderStatusReport, GenerateOrderStatusReports,
36            GeneratePositionStatusReports,
37        },
38    },
39};
40use nautilus_core::{UUID4, UnixNanos};
41use nautilus_execution::reconciliation::{
42    create_position_reconciliation_venue_order_id, inferred_reconciliation_trade_ids,
43    should_reconciliation_update,
44};
45use nautilus_model::{
46    enums::{LiquiditySide, OrderSide, OrderStatus, OrderType, TimeInForce},
47    events::{OrderCanceled, OrderEventAny, OrderFilled},
48    identifiers::{
49        AccountId, ClientId, ClientOrderId, InstrumentId, PositionId, StrategyId, TradeId, Venue,
50        VenueOrderId,
51    },
52    instruments::{Instrument, InstrumentAny},
53    orders::{Order, OrderAny},
54    position::Position,
55    reports::{FillReport, OrderStatusReport, PositionStatusReport},
56    types::{Money, Price, Quantity},
57};
58use rust_decimal::Decimal;
59
60#[cfg(feature = "node")]
61use super::client::{CollectedReport, LiveExecutionClient, ReportCollector};
62
63/// Composite key identifying a position context by instrument and account.
64///
65/// Used to scope per-position reconciliation state (retry counters, activity
66/// throttles, venue report lookups) so that multiple accounts holding the same
67/// instrument do not share the same tracking entry.
68pub type InstrumentAccountKey = (InstrumentId, AccountId);
69pub(super) type AccountInstrumentStrategyKey = (AccountId, InstrumentId, StrategyId);
70pub(super) type FillKey = (AccountId, InstrumentId, TradeId);
71
72/// Execution clients responsible for reporting one cached entity.
73#[derive(Debug, Clone, PartialEq, Eq)]
74pub enum ReportClientCoverage {
75    /// Every identified client provides the required report coverage.
76    Resolved(IndexSet<ClientId>),
77    /// Identified clients cannot provide the required report coverage.
78    Unavailable(IndexSet<ClientId>),
79    /// No responsible client could be identified.
80    Unresolved,
81}
82
83/// Metadata for an external order that needs to be registered with the execution client.
84#[derive(Debug, Clone)]
85pub struct ExternalOrderMetadata {
86    pub client_order_id: ClientOrderId,
87    pub venue_order_id: VenueOrderId,
88    pub instrument_id: InstrumentId,
89    pub strategy_id: StrategyId,
90    pub ts_init: UnixNanos,
91}
92
93/// Result of reconciliation containing events, external orders, and unresolved position diagnostics.
94#[derive(Debug, Default)]
95pub struct ReconciliationResult {
96    /// Order events generated during reconciliation.
97    pub events: Vec<OrderEventAny>,
98    /// External orders that need to be registered with execution clients.
99    pub external_orders: Vec<ExternalOrderMetadata>,
100    /// Diagnostics for in-scope nonzero venue positions unrecovered after event processing.
101    pub unresolved_positions: Vec<String>,
102}
103
104/// Result of inflight order checks containing terminal events and intermediate queries.
105#[derive(Debug, Default)]
106pub struct InflightCheckResult {
107    /// Terminal events (rejection/cancellation) for orders that exceeded max retries.
108    pub events: Vec<OrderEventAny>,
109    /// Intermediate venue queries for orders still within retry budget.
110    pub queries: Vec<TradingCommand>,
111}
112
113/// Events and targeted queries produced by open-order reconciliation.
114#[derive(Debug, Default)]
115pub(crate) struct OpenOrderReconciliationResult {
116    pub events: Vec<OrderEventAny>,
117    pub targeted_queries: Vec<TargetedOrderQuery>,
118}
119
120/// Order snapshot and client coverage for a targeted status query.
121#[derive(Debug, Clone)]
122pub(crate) struct TargetedOrderQuery {
123    pub(super) client_order_id: ClientOrderId,
124    pub(super) responsible_clients: IndexSet<ClientId>,
125    pub(super) command: GenerateOrderStatusReport,
126    pub(super) report: Option<OrderStatusReport>,
127    pub(super) filled_qty: Quantity,
128}
129
130impl TargetedOrderQuery {
131    /// Returns the order identifier for the targeted query.
132    pub(crate) const fn client_order_id(&self) -> ClientOrderId {
133        self.client_order_id
134    }
135}
136
137/// Targeted status query result with fills and coverage completeness.
138#[derive(Debug)]
139pub(crate) struct TargetedOrderReportResult {
140    pub(super) client_order_id: ClientOrderId,
141    pub(super) client_id: Option<ClientId>,
142    pub(super) report: Option<OrderStatusReport>,
143    pub(super) fills: Vec<FillReport>,
144    pub(super) coverage_complete: bool,
145}
146
147#[cfg(feature = "node")]
148impl TargetedOrderReportResult {
149    /// Returns whether an order status report is present.
150    pub(crate) const fn has_report(&self) -> bool {
151        self.report.is_some()
152    }
153}
154
155/// Order status report paired with its source execution client.
156#[derive(Debug)]
157pub(crate) struct SourcedOrderStatusReport {
158    pub client_id: ClientId,
159    pub report: OrderStatusReport,
160}
161
162/// Snapshot and command for one continuous open-order reconciliation check.
163#[derive(Debug, Clone)]
164pub(crate) struct OpenOrderReportCheck {
165    pub command: GenerateOrderStatusReports,
166    pub filtered_orders: Vec<OrderAny>,
167    pub client_coverage: IndexMap<ClientOrderId, ReportClientCoverage>,
168}
169
170/// Prepare-time state and command for one continuous position reconciliation check.
171#[derive(Debug, Clone)]
172pub struct PositionReportCheck {
173    /// The bulk position query.
174    pub command: GeneratePositionStatusReports,
175    /// Responsible clients by instrument and account.
176    pub client_coverage: IndexMap<InstrumentAccountKey, ReportClientCoverage>,
177    /// Activity revisions captured before the query.
178    pub activity_revisions: IndexMap<InstrumentAccountKey, u64>,
179}
180
181/// Fill report request for one instrument, account, and execution client.
182#[derive(Debug)]
183pub struct PositionFillReportQuery {
184    /// The instrument and account to reconcile.
185    pub key: InstrumentAccountKey,
186    /// The responsible execution client.
187    pub client_id: ClientId,
188    /// The authoritative fill query.
189    pub command: GenerateFillReports,
190}
191
192/// Fill queries and discrepancy keys for a position reconciliation check.
193#[derive(Debug)]
194pub struct PositionFillReportPlan {
195    /// Authoritative fill queries that are safe to run.
196    pub queries: Vec<PositionFillReportQuery>,
197    /// Position keys that still differ from the venue snapshot.
198    pub discrepancy_keys: IndexSet<InstrumentAccountKey>,
199}
200
201/// Whether a fill is attributable and free of inferred-fill or reconciled-position overlap.
202#[derive(Debug)]
203pub enum PositionFillReportPreparation {
204    /// The report can be applied to the cached execution state.
205    Ready,
206    /// An active inferred fill prevents authoritative replay.
207    InferredOverlap,
208    /// A position reconciled from a venue position report already includes the fill.
209    SnapshotOverlap,
210    /// A hedge fill cannot be assigned to an unambiguous position.
211    Unattributed,
212}
213
214/// Cached and venue position quantities and report shape for comparison.
215pub(super) struct PositionQuantityComparison {
216    pub(super) cached_positions: Vec<Position>,
217    pub(super) cached_signed_qty: Decimal,
218    pub(super) cached_long_qty: Decimal,
219    pub(super) cached_short_qty: Decimal,
220    pub(super) venue_signed_qty: Decimal,
221    pub(super) venue_long_qty: Decimal,
222    pub(super) venue_short_qty: Decimal,
223    pub(super) nonflat_count: usize,
224    pub(super) venue_report: Option<PositionStatusReport>,
225    pub(super) venue_has_side_reports: bool,
226}
227
228impl PositionQuantityComparison {
229    /// Checks net quantities and, when both venue sides are reported, side quantities.
230    pub(super) fn quantities_match(&self, tolerance: Decimal) -> bool {
231        let net_qty_matches = (self.cached_signed_qty - self.venue_signed_qty).abs() <= tolerance;
232        let side_qty_matches = (self.cached_long_qty - self.venue_long_qty).abs() <= tolerance
233            && (self.cached_short_qty - self.venue_short_qty).abs() <= tolerance;
234
235        net_qty_matches && (!self.venue_has_side_reports || side_qty_matches)
236    }
237
238    /// Classifies venue reports as a single unambiguous position or multiple legs.
239    pub(super) fn report_shape(&self) -> PositionReportShape {
240        if self.nonflat_count > 1 || self.venue_has_side_reports {
241            PositionReportShape::MultiLeg
242        } else {
243            PositionReportShape::Unambiguous
244        }
245    }
246}
247
248/// Cached fill identities, missing orders, and netting lifecycle boundaries.
249pub(super) struct RetainedFillState {
250    pub(super) fill_keys: IndexSet<FillKey>,
251    pub(super) missing_order_ids: IndexSet<(AccountId, InstrumentId, ClientOrderId)>,
252    pub(super) missing_venue_order_ids: IndexSet<(AccountId, InstrumentId, VenueOrderId)>,
253    pub(super) netting_lifecycle_starts: IndexMap<AccountInstrumentStrategyKey, UnixNanos>,
254}
255
256/// Tracks pending fill identities and their generated reconciliation events.
257#[derive(Default)]
258pub(super) struct ReconciliationFillQueue {
259    pub(super) pending_fill_keys: IndexSet<FillKey>,
260    pub(super) event_fill_keys: IndexMap<UUID4, FillKey>,
261}
262
263impl ReconciliationFillQueue {
264    /// Queues a fill event and records its identity for deduplication.
265    pub(super) fn push(
266        &mut self,
267        events: &mut Vec<OrderEventAny>,
268        fill: OrderFilled,
269        fill_key: FillKey,
270    ) {
271        self.pending_fill_keys.insert(fill_key);
272        self.event_fill_keys.insert(fill.event_id, fill_key);
273        events.push(OrderEventAny::Filled(fill));
274    }
275}
276
277/// Information about an inflight order check.
278#[derive(Debug, Clone)]
279pub(super) struct InflightCheck {
280    pub command_ids: Vec<UUID4>,
281    pub submitted_at: dst::time::Instant,
282    pub retry_count: u32,
283    // `Instant` debug output is runtime-specific and intentionally only useful
284    // as an opaque monotonic offset.
285    pub last_query_at: Option<dst::time::Instant>,
286}
287
288#[derive(Debug, Clone, Copy, PartialEq, Eq)]
289pub(super) enum PositionReportShape {
290    Unambiguous,
291    MultiLeg,
292}
293
294/// Retry count and report shape for position reconciliation.
295#[derive(Debug, Clone, Copy)]
296pub(super) struct PositionReconciliationState {
297    pub(super) report_shape: PositionReportShape,
298    pub(super) retries: u32,
299}
300
301/// Requests targeted order status and missing fills from responsible clients.
302pub(crate) async fn request_targeted_order_reports(
303    queries: Vec<TargetedOrderQuery>,
304    clients: &[&dyn ExecutionClient],
305    query_delay: Duration,
306) -> Vec<TargetedOrderReportResult> {
307    let mut results = Vec::with_capacity(queries.len());
308    let mut request_count = 0usize;
309
310    for mut query in queries {
311        let mut report = None;
312        let mut fills = Vec::new();
313        let mut report_client_id = None;
314        let mut coverage_complete = true;
315
316        for client_id in &query.responsible_clients {
317            let client_id = *client_id;
318
319            let Some(client) = clients
320                .iter()
321                .find(|client| client.client_id() == client_id)
322            else {
323                coverage_complete = false;
324                log::warn!(
325                    "Cannot run targeted order status query for {}: execution client {client_id} is unavailable",
326                    query.client_order_id,
327                );
328                continue;
329            };
330
331            if request_count > 0 && !query_delay.is_zero() {
332                dst::time::sleep(query_delay).await;
333            }
334
335            request_count += 1;
336
337            let response = if let Some(report) = query.report.take() {
338                Ok(Some(report))
339            } else {
340                client.generate_order_status_report(&query.command).await
341            };
342
343            if let Some(candidate) =
344                targeted_report_response(&query, client_id, response, &mut coverage_complete)
345            {
346                if order_report_has_missing_fills(
347                    &candidate,
348                    query.filled_qty,
349                    client.requires_authoritative_fills(),
350                ) {
351                    let command = targeted_fill_command(&query, &candidate);
352
353                    match client.generate_fill_reports(command).await {
354                        Ok(reports) => {
355                            fills = reports
356                                .into_iter()
357                                .filter(|fill| targeted_fill_matches(&candidate, fill))
358                                .collect();
359                        }
360                        Err(e) => log::warn!(
361                            "Failed fill report query from {client_id} for {}: {e}",
362                            query.client_order_id,
363                        ),
364                    }
365                }
366
367                report = Some(candidate);
368                report_client_id = Some(client_id);
369                break;
370            }
371        }
372
373        results.push(TargetedOrderReportResult {
374            client_order_id: query.client_order_id(),
375            client_id: report_client_id,
376            report,
377            fills,
378            coverage_complete,
379        });
380    }
381
382    results
383}
384
385/// Returns whether all targeted queries complete within their shared collection budget.
386///
387/// Accepted statuses and fills remain in `results` across later expiry or cancellation.
388#[cfg(feature = "node")]
389pub(crate) async fn collect_targeted_order_reports(
390    queries: Vec<TargetedOrderQuery>,
391    clients: Vec<LiveExecutionClient>,
392    query_delay: Duration,
393    deadline: dst::time::Instant,
394    results: Rc<RefCell<Vec<TargetedOrderReportResult>>>,
395) -> bool {
396    let mut collectors = IndexMap::new();
397    let mut request_count = 0usize;
398
399    for mut query in queries {
400        collectors.clear();
401
402        let Some(result) = collect_targeted_order_status(
403            &mut query,
404            &clients,
405            query_delay,
406            deadline,
407            &mut request_count,
408        )
409        .await
410        else {
411            return false;
412        };
413
414        let requires_authoritative_fills = result.client_id.is_some_and(|client_id| {
415            clients.iter().any(|client| {
416                client.client_id() == client_id && client.requires_authoritative_fills()
417            })
418        });
419
420        let fill_query = result
421            .report
422            .as_ref()
423            .filter(|report| {
424                order_report_has_missing_fills(
425                    report,
426                    query.filled_qty,
427                    requires_authoritative_fills,
428                )
429            })
430            .map(|report| (targeted_fill_command(&query, report), report.clone()));
431        let client_id = result.client_id;
432        let result_index = results.borrow().len();
433        results.borrow_mut().push(result);
434
435        if let Some((command, report)) = fill_query {
436            let client_id = client_id.expect("matched status has a reporting client");
437
438            if dst::time::Instant::now() >= deadline {
439                return false;
440            }
441
442            let receipt = async {
443                let collector =
444                    ReportCollector::for_client(&mut collectors, &clients, client_id).await?;
445                collector.fill_reports(command).await
446            }
447            .await;
448
449            let Some(response) = accept_collected_report(receipt, deadline) else {
450                return false;
451            };
452
453            match response {
454                Ok(fills) => {
455                    results.borrow_mut()[result_index].fills = fills
456                        .into_iter()
457                        .filter(|fill| targeted_fill_matches(&report, fill))
458                        .collect();
459                }
460                Err(e) => log::warn!(
461                    "Failed fill report query from {client_id} for {}: {e}",
462                    query.client_order_id
463                ),
464            }
465        }
466    }
467
468    true
469}
470
471#[cfg(feature = "node")]
472async fn collect_targeted_order_status(
473    query: &mut TargetedOrderQuery,
474    clients: &[LiveExecutionClient],
475    query_delay: Duration,
476    deadline: dst::time::Instant,
477    request_count: &mut usize,
478) -> Option<TargetedOrderReportResult> {
479    let mut coverage_complete = true;
480
481    for client_id in &query.responsible_clients {
482        let client_id = *client_id;
483        let Some(client) = clients
484            .iter()
485            .find(|client| client.client_id() == client_id)
486        else {
487            coverage_complete = false;
488            log::warn!(
489                "Cannot run targeted order status query for {}: execution client {client_id} is unavailable",
490                query.client_order_id
491            );
492            continue;
493        };
494
495        if *request_count > 0 && !query_delay.is_zero() {
496            dst::time::sleep(query_delay).await;
497        }
498
499        if dst::time::Instant::now() >= deadline {
500            return None;
501        }
502
503        *request_count += 1;
504
505        let response = if let Some(report) = query.report.take() {
506            Ok(Some(report))
507        } else {
508            let receipt = client.collect_order_status_report(&query.command).await;
509
510            accept_collected_report(receipt, deadline)?
511        };
512
513        if let Some(report) =
514            targeted_report_response(query, client_id, response, &mut coverage_complete)
515        {
516            return Some(TargetedOrderReportResult {
517                client_order_id: query.client_order_id(),
518                client_id: Some(client_id),
519                report: Some(report),
520                fills: Vec::new(),
521                coverage_complete,
522            });
523        }
524    }
525
526    Some(TargetedOrderReportResult {
527        client_order_id: query.client_order_id(),
528        client_id: None,
529        report: None,
530        fills: Vec::new(),
531        coverage_complete,
532    })
533}
534
535#[cfg(feature = "node")]
536fn accept_collected_report<T>(
537    receipt: anyhow::Result<CollectedReport<T>>,
538    deadline: dst::time::Instant,
539) -> Option<anyhow::Result<T>> {
540    if dst::time::Instant::now() >= deadline {
541        return None;
542    }
543
544    Some(receipt.and_then(CollectedReport::finish))
545}
546
547fn targeted_report_response(
548    query: &TargetedOrderQuery,
549    client_id: ClientId,
550    response: anyhow::Result<Option<OrderStatusReport>>,
551    coverage_complete: &mut bool,
552) -> Option<OrderStatusReport> {
553    match response {
554        Ok(Some(report)) if targeted_report_matches(query, &report) => Some(report),
555        Ok(Some(candidate)) => {
556            *coverage_complete = false;
557            log::warn!(
558                "Ignoring mismatched targeted order status report from {client_id} for {}: client_order_id={:?}, venue_order_id={}, instrument_id={}",
559                query.client_order_id,
560                candidate.client_order_id,
561                candidate.venue_order_id,
562                candidate.instrument_id,
563            );
564            None
565        }
566        Ok(None) => None,
567        Err(e) => {
568            *coverage_complete = false;
569            log::warn!(
570                "Failed targeted order status query from {client_id} for {}: {e}",
571                query.client_order_id
572            );
573            None
574        }
575    }
576}
577
578fn targeted_fill_command(
579    query: &TargetedOrderQuery,
580    report: &OrderStatusReport,
581) -> GenerateFillReports {
582    let mut command = GenerateFillReports::new(
583        UUID4::new(),
584        query.command.ts_init,
585        Some(report.instrument_id),
586        Some(report.venue_order_id),
587        None,
588        None,
589        None,
590        Some(query.command.command_id),
591    );
592    command.log_receipt_level = LogLevel::Debug;
593    command
594}
595
596fn targeted_fill_matches(report: &OrderStatusReport, fill: &FillReport) -> bool {
597    fill.account_id == report.account_id
598        && fill.instrument_id == report.instrument_id
599        && fill.venue_order_id == report.venue_order_id
600        && report.order_side.is_none_or(|side| fill.order_side == side)
601}
602
603/// Checks whether cached order status, filled quantity, and report fields match.
604pub(super) fn is_exact_order_match(order: &OrderAny, report: &OrderStatusReport) -> bool {
605    order.status() == report.order_status
606        && order.filled_qty() == report.filled_qty
607        && !should_reconciliation_update(order, report)
608}
609
610fn targeted_report_matches(query: &TargetedOrderQuery, report: &OrderStatusReport) -> bool {
611    let instrument_matches = query
612        .command
613        .instrument_id
614        .is_none_or(|instrument_id| report.instrument_id == instrument_id);
615    let order_matches = report.client_order_id == Some(query.client_order_id)
616        || query
617            .command
618            .venue_order_id
619            .is_some_and(|venue_order_id| report.venue_order_id == venue_order_id);
620
621    instrument_matches && order_matches
622}
623
624/// Checks whether a report needs authoritative fills before status reconciliation.
625pub(super) fn order_report_has_missing_fills(
626    report: &OrderStatusReport,
627    cached_filled_qty: Quantity,
628    requires_authoritative_fills: bool,
629) -> bool {
630    report.filled_qty > cached_filled_qty
631        && (requires_authoritative_fills
632            || matches!(
633                report.order_status,
634                OrderStatus::Canceled | OrderStatus::Expired
635            ))
636}
637
638/// Preserves later confirmed amendments for clients requiring authoritative fills.
639pub(super) fn preserve_order_amendment<'a>(
640    order: &OrderAny,
641    report: &'a OrderStatusReport,
642    requires_authoritative_fills: bool,
643) -> Cow<'a, OrderStatusReport> {
644    if !requires_authoritative_fills || !should_reconciliation_update(order, report) {
645        return Cow::Borrowed(report);
646    }
647
648    if !order.events().iter().any(|event| {
649        matches!(event, OrderEventAny::Updated(updated) if updated.ts_event > report.ts_last)
650    }) {
651        return Cow::Borrowed(report);
652    }
653
654    let mut current = report.clone();
655    current.quantity = order.quantity();
656    current.price = order.price();
657    current.trigger_price = order.trigger_price();
658    Cow::Owned(current)
659}
660
661/// Builds an order report from fills sharing the same order and venue position.
662///
663/// # Errors
664///
665/// Returns an error if fills are empty or inconsistent, instrument metadata does not match, or
666/// aggregate quantities or prices cannot be represented.
667pub(super) fn create_orphan_fill_order_report(
668    fills: &[&FillReport],
669    instrument: &InstrumentAny,
670) -> anyhow::Result<OrderStatusReport> {
671    let Some(first) = fills.first() else {
672        anyhow::bail!("fill group is empty");
673    };
674
675    let venue_position_id = first
676        .venue_position_id
677        .ok_or_else(|| anyhow::anyhow!("venue position ID is missing"))?;
678
679    for fill in fills.iter().skip(1) {
680        anyhow::ensure!(
681            fill.account_id == first.account_id,
682            "account ID differs across fill group"
683        );
684        anyhow::ensure!(
685            fill.instrument_id == first.instrument_id,
686            "instrument ID differs across fill group"
687        );
688        anyhow::ensure!(
689            fill.venue_order_id == first.venue_order_id,
690            "venue order ID differs across fill group"
691        );
692        anyhow::ensure!(
693            fill.client_order_id == first.client_order_id,
694            "client order ID differs across fill group"
695        );
696        anyhow::ensure!(
697            fill.order_side == first.order_side,
698            "order side differs across fill group"
699        );
700        anyhow::ensure!(
701            fill.venue_position_id == first.venue_position_id,
702            "venue position ID differs across fill group"
703        );
704    }
705
706    anyhow::ensure!(
707        first.instrument_id == instrument.id(),
708        "instrument metadata does not match fill group"
709    );
710
711    let (quantity, notional) = fills.iter().try_fold(
712        (Decimal::ZERO, Decimal::ZERO),
713        |(quantity, notional), fill| {
714            let fill_quantity = fill.last_qty.as_decimal();
715
716            let quantity = quantity.checked_add(fill_quantity).ok_or_else(|| {
717                anyhow::anyhow!("fill quantity overflow while aggregating fill group")
718            })?;
719
720            let fill_notional = fill_quantity
721                .checked_mul(fill.last_px.as_decimal())
722                .ok_or_else(|| {
723                    anyhow::anyhow!("fill notional overflow while aggregating fill group")
724                })?;
725
726            let notional = notional.checked_add(fill_notional).ok_or_else(|| {
727                anyhow::anyhow!("fill notional overflow while aggregating fill group")
728            })?;
729
730            Ok::<_, anyhow::Error>((quantity, notional))
731        },
732    )?;
733
734    anyhow::ensure!(
735        quantity > Decimal::ZERO,
736        "fill group quantity is not positive"
737    );
738
739    let order_qty = Quantity::from_decimal_dp(quantity, instrument.size_precision())?;
740    let avg_px = notional
741        .checked_div(quantity)
742        .ok_or_else(|| anyhow::anyhow!("fill group average price is not representable"))?;
743
744    let ts_accepted = fills
745        .iter()
746        .map(|fill| fill.ts_event)
747        .min()
748        .expect("non-empty fill group");
749
750    let ts_last = fills
751        .iter()
752        .map(|fill| fill.ts_event)
753        .max()
754        .expect("non-empty fill group");
755
756    let ts_init = fills
757        .iter()
758        .map(|fill| fill.ts_init)
759        .max()
760        .expect("non-empty fill group");
761
762    let report = OrderStatusReport::new(
763        first.account_id,
764        first.instrument_id,
765        first.client_order_id,
766        first.venue_order_id,
767        first.order_side.into(),
768        OrderType::Market,
769        TimeInForce::Gtc,
770        OrderStatus::Filled,
771        order_qty,
772        order_qty,
773        ts_accepted,
774        ts_last,
775        ts_init,
776        None,
777    )
778    .with_avg_px(avg_px)
779    .with_venue_position_id(venue_position_id);
780
781    Ok(report)
782}
783
784/// Checks whether a fill belongs in the retained position projection.
785pub(super) fn should_project_fill(
786    fill: &OrderFilled,
787    retained_fill_state: &RetainedFillState,
788    reported_fill_keys: &IndexSet<FillKey>,
789    order_only_ids: &IndexSet<VenueOrderId>,
790    order_only_fill_keys: &IndexSet<FillKey>,
791) -> bool {
792    let fill_key = (fill.account_id, fill.instrument_id, fill.trade_id);
793    if retained_fill_state.fill_keys.contains(&fill_key)
794        || order_only_ids.contains(&fill.venue_order_id)
795        || order_only_fill_keys.contains(&fill_key)
796    {
797        return true;
798    }
799
800    let order_missing = retained_fill_state.missing_order_ids.contains(&(
801        fill.account_id,
802        fill.instrument_id,
803        fill.client_order_id,
804    )) || retained_fill_state.missing_venue_order_ids.contains(&(
805        fill.account_id,
806        fill.instrument_id,
807        fill.venue_order_id,
808    ));
809
810    if order_missing && !reported_fill_keys.contains(&fill_key) {
811        return true;
812    }
813
814    retained_fill_state
815        .netting_lifecycle_starts
816        .get(&(fill.account_id, fill.instrument_id, fill.strategy_id))
817        .is_some_and(|ts_opened| fill.ts_event < *ts_opened)
818}
819
820/// Sorts reconciliation events by event time while keeping each venue order's lifecycle events
821/// ahead of the fills generated after them.
822///
823/// Fills sort by their own event time. A report's acceptance time can postdate its own
824/// fills when the venue reports a last update time or the adapter uses the reconciliation time,
825/// so any other event sorts no later than the earliest fill that follows it for the same client
826/// and venue order. Events of other venue orders, including a replaced order that shares the
827/// client order ID, keep their own times.
828pub(super) fn sort_reconciliation_events(events: &mut Vec<OrderEventAny>) {
829    let mut earliest_later_fill: IndexMap<(ClientOrderId, Option<VenueOrderId>), UnixNanos> =
830        IndexMap::new();
831    let mut keys = vec![UnixNanos::default(); events.len()];
832
833    for (index, event) in events.iter().enumerate().rev() {
834        let venue_order = (event.client_order_id(), event.venue_order_id());
835        let ts_event = event.ts_event();
836
837        keys[index] = if matches!(event, OrderEventAny::Filled(_)) {
838            let earliest = earliest_later_fill.entry(venue_order).or_insert(ts_event);
839            *earliest = (*earliest).min(ts_event);
840            ts_event
841        } else {
842            earliest_later_fill
843                .get(&venue_order)
844                .map_or(ts_event, |fill_ts| ts_event.min(*fill_ts))
845        };
846    }
847
848    let mut keyed: Vec<(UnixNanos, OrderEventAny)> =
849        keys.into_iter().zip(events.drain(..)).collect();
850    keyed.sort_by_key(|(key, _)| *key);
851    events.extend(keyed.into_iter().map(|(_, event)| event));
852}
853
854/// Checks active fill history for deterministic inferred reconciliation IDs.
855///
856/// Replays the order only when an active reconciliation fill has the inferred ID format.
857///
858/// # Errors
859///
860/// Returns an error if the order requires replay and its cached history cannot be replayed.
861pub(super) fn has_active_inferred_fill(order: &OrderAny) -> anyhow::Result<bool> {
862    Ok(!inferred_reconciliation_trade_ids(order)?.is_empty())
863}
864
865/// Calculates inferred-fill commission using the responsible execution client.
866///
867/// # Errors
868///
869/// Returns an error if the client is unavailable or commission calculation fails.
870pub(super) fn resolve_inferred_fill_commission(
871    fill_qty: Quantity,
872    price_and_liquidity: Option<(Price, LiquiditySide)>,
873    instrument: &InstrumentAny,
874    client: Option<&dyn ExecutionClient>,
875) -> anyhow::Result<Option<Money>> {
876    let Some(client) = client else {
877        anyhow::bail!("responsible execution client is unavailable");
878    };
879
880    let Some((last_px, liquidity_side)) = price_and_liquidity else {
881        return Ok(None);
882    };
883
884    client.calculate_commission(instrument, fill_qty, last_px, liquidity_side)
885}
886
887/// Resolves position-report coverage by account, falling back to venue clients.
888pub(crate) fn resolve_position_report_client_coverage(
889    key: InstrumentAccountKey,
890    clients: &[&dyn ExecutionClient],
891) -> ReportClientCoverage {
892    let client_ids = responsible_client_ids(Some(key.1), key.0.venue, clients);
893
894    if client_ids.is_empty() {
895        ReportClientCoverage::Unresolved
896    } else if clients.iter().any(|client| {
897        client_ids.contains(&client.client_id()) && !client.provides_bulk_position_coverage(key.0)
898    }) {
899        ReportClientCoverage::Unavailable(client_ids)
900    } else {
901        ReportClientCoverage::Resolved(client_ids)
902    }
903}
904
905/// Returns the account's clients, falling back to clients handling the venue.
906pub(super) fn responsible_client_ids(
907    account_id: Option<AccountId>,
908    venue: Venue,
909    clients: &[&dyn ExecutionClient],
910) -> IndexSet<ClientId> {
911    if let Some(account_id) = account_id {
912        let account_clients = clients
913            .iter()
914            .filter(|client| client.account_id() == account_id)
915            .map(|client| client.client_id())
916            .collect::<IndexSet<_>>();
917
918        if !account_clients.is_empty() {
919            return account_clients;
920        }
921    }
922
923    clients
924        .iter()
925        .filter(|client| client.handles_order_venue(venue))
926        .map(|client| client.client_id())
927        .collect()
928}
929
930/// Returns the quantity-weighted average of positive position entry prices.
931pub(super) fn position_avg_px<'a>(
932    positions: impl IntoIterator<Item = &'a Position>,
933) -> Option<Decimal> {
934    let mut total_value = Decimal::ZERO;
935    let mut total_qty = Decimal::ZERO;
936
937    for position in positions {
938        let qty = position.signed_decimal_qty().abs();
939        if position.avg_px_open > Decimal::ZERO && qty > Decimal::ZERO {
940            total_value += position.avg_px_open * qty;
941            total_qty += qty;
942        }
943    }
944
945    if total_qty > Decimal::ZERO {
946        Some(total_value / total_qty)
947    } else {
948        None
949    }
950}
951
952/// Aggregates signed quantities into net, long, and absolute short totals.
953pub(super) fn position_qty_aggregates(
954    signed_quantities: impl Iterator<Item = Decimal>,
955) -> (Decimal, Decimal, Decimal) {
956    signed_quantities.fold(
957        (Decimal::ZERO, Decimal::ZERO, Decimal::ZERO),
958        |(net, long, short), qty| {
959            if qty > Decimal::ZERO {
960                (net + qty, long + qty, short)
961            } else {
962                (net + qty, long, short + qty.abs())
963            }
964        },
965    )
966}
967
968/// Returns the reports without duplicates, logging a warning for each one removed.
969///
970/// Reports are duplicates when they match apart from the locally assigned report ID and
971/// initialization timestamp. Keeps the first occurrence of each report in input order.
972pub(super) fn distinct_position_reports(
973    reports: Vec<PositionStatusReport>,
974) -> Vec<PositionStatusReport> {
975    let mut distinct_reports: Vec<PositionStatusReport> = Vec::with_capacity(reports.len());
976
977    for report in reports {
978        let is_duplicate = distinct_reports.iter().any(|distinct| {
979            let mut normalized = distinct.clone();
980            normalized.report_id = report.report_id;
981            normalized.ts_init = report.ts_init;
982            normalized == report
983        });
984
985        if is_duplicate {
986            log::warn!("Duplicate position report for {}", report.instrument_id);
987            continue;
988        }
989
990        distinct_reports.push(report);
991    }
992
993    distinct_reports
994}
995
996/// Builds a filled market-order report that moves a position by `quantity` on `order_side`.
997#[expect(clippy::too_many_arguments)]
998pub(super) fn create_position_reconciliation_report(
999    instrument: &InstrumentAny,
1000    account_id: AccountId,
1001    order_side: OrderSide,
1002    quantity: Quantity,
1003    avg_px: Decimal,
1004    venue_position_id: Option<PositionId>,
1005    tag: Option<&str>,
1006    ts_now: UnixNanos,
1007    venue_ts_last: UnixNanos,
1008) -> OrderStatusReport {
1009    let instrument_id = instrument.id();
1010    let fill_price = Price::from_decimal_dp(avg_px, instrument.price_precision()).ok();
1011    let venue_order_id = create_position_reconciliation_venue_order_id(
1012        account_id,
1013        instrument_id,
1014        order_side,
1015        OrderType::Market,
1016        quantity,
1017        fill_price,
1018        venue_position_id,
1019        tag,
1020        venue_ts_last,
1021    );
1022
1023    let mut report = OrderStatusReport::new(
1024        account_id,
1025        instrument_id,
1026        None,
1027        venue_order_id,
1028        order_side.into(),
1029        OrderType::Market,
1030        TimeInForce::Gtc,
1031        OrderStatus::Filled,
1032        quantity,
1033        quantity,
1034        ts_now,
1035        ts_now,
1036        ts_now,
1037        None,
1038    )
1039    .with_avg_px(avg_px);
1040
1041    if let Some(venue_position_id) = venue_position_id {
1042        report = report.with_venue_position_id(venue_position_id);
1043    }
1044
1045    report
1046}
1047
1048/// Builds a reconciliation cancel for an order resolved without a venue status report.
1049pub(super) fn create_reconciliation_canceled(order: &OrderAny, ts_now: UnixNanos) -> OrderEventAny {
1050    OrderEventAny::Canceled(OrderCanceled::new(
1051        order.trader_id(),
1052        order.strategy_id(),
1053        order.instrument_id(),
1054        order.client_order_id(),
1055        UUID4::new(),
1056        ts_now,
1057        ts_now,
1058        true, // reconciliation
1059        order.venue_order_id(),
1060        order.account_id(),
1061        None,
1062    ))
1063}
1064
1065#[cfg(test)]
1066pub(super) mod tests {
1067    use std::cell::RefCell;
1068
1069    use nautilus_core::Params;
1070    use nautilus_execution::reconciliation::inferred_fill_price_and_liquidity;
1071    use nautilus_model::{
1072        accounts::AccountAny,
1073        enums::{OmsType, PositionSide},
1074        identifiers::Venue,
1075        instruments::stubs::crypto_perpetual_ethusdt,
1076        orders::{OrderTestBuilder, stubs::TestOrderEventStubs},
1077        types::{AccountBalance, Currency, MarginBalance, quantity::QUANTITY_MAX},
1078    };
1079    use proptest::prelude::*;
1080    use rstest::rstest;
1081    use rust_decimal_macros::dec;
1082
1083    use super::*;
1084
1085    #[cfg(feature = "node")]
1086    mod targeted_collection {
1087        use std::{
1088            cell::Cell,
1089            sync::{
1090                Arc,
1091                atomic::{AtomicUsize, Ordering},
1092            },
1093        };
1094
1095        use futures_util::FutureExt;
1096        use nautilus_common::clients::ExecutionReportTask;
1097
1098        use super::*;
1099
1100        type CollectionEvent = (&'static str, ClientId, dst::time::Instant);
1101
1102        #[derive(Debug, Clone, Default)]
1103        struct CollectionState {
1104            events: Rc<RefCell<Vec<CollectionEvent>>>,
1105            commands: Rc<RefCell<Vec<GenerateFillReports>>>,
1106            started: Arc<AtomicUsize>,
1107            status_finished: Rc<Cell<usize>>,
1108            fill_finished: Rc<Cell<usize>>,
1109        }
1110
1111        #[derive(Debug)]
1112        struct CollectionClient {
1113            id: ClientId,
1114            report: Option<OrderStatusReport>,
1115            fills: Vec<FillReport>,
1116            state: CollectionState,
1117            worker: bool,
1118            release_at: usize,
1119            release: Arc<tokio::sync::Notify>,
1120        }
1121
1122        impl CollectionClient {
1123            fn status_task(&self) -> ExecutionReportTask<Option<OrderStatusReport>> {
1124                self.state
1125                    .events
1126                    .borrow_mut()
1127                    .push(("status", self.id, dst::time::Instant::now()));
1128                let state = self.state.clone();
1129                let started = self.state.started.clone();
1130                let report = self.report.clone();
1131                let release_at = self.release_at;
1132                let release = self.release.clone();
1133
1134                ExecutionReportTask::new(
1135                    async move {
1136                        if started.fetch_add(1, Ordering::SeqCst) + 1 == release_at {
1137                            release.notified().await;
1138                        }
1139
1140                        Ok(report)
1141                    },
1142                    move |report| {
1143                        state.status_finished.set(state.status_finished.get() + 1);
1144                        Ok(report)
1145                    },
1146                )
1147            }
1148
1149            fn fill_task(&self, cmd: &GenerateFillReports) -> ExecutionReportTask<Vec<FillReport>> {
1150                self.state
1151                    .events
1152                    .borrow_mut()
1153                    .push(("fills", self.id, dst::time::Instant::now()));
1154                self.state.commands.borrow_mut().push(cmd.clone());
1155                let state = self.state.clone();
1156                let started = self.state.started.clone();
1157                let reports = self.fills.clone();
1158                let release_at = self.release_at;
1159                let release = self.release.clone();
1160
1161                ExecutionReportTask::new(
1162                    async move {
1163                        if started.fetch_add(1, Ordering::SeqCst) + 1 == release_at {
1164                            release.notified().await;
1165                        }
1166
1167                        Ok(reports)
1168                    },
1169                    move |reports| {
1170                        state.fill_finished.set(state.fill_finished.get() + 1);
1171                        Ok(reports)
1172                    },
1173                )
1174            }
1175        }
1176
1177        #[async_trait::async_trait(?Send)]
1178        impl ExecutionClient for CollectionClient {
1179            fn is_connected(&self) -> bool {
1180                true
1181            }
1182
1183            fn client_id(&self) -> ClientId {
1184                self.id
1185            }
1186
1187            fn account_id(&self) -> AccountId {
1188                AccountId::from("TEST-001")
1189            }
1190
1191            fn venue(&self) -> Venue {
1192                Venue::from("BINANCE")
1193            }
1194
1195            fn oms_type(&self) -> OmsType {
1196                OmsType::Netting
1197            }
1198
1199            fn get_account(&self) -> Option<AccountAny> {
1200                None
1201            }
1202
1203            fn start(&mut self) -> anyhow::Result<()> {
1204                Ok(())
1205            }
1206
1207            fn stop(&mut self) -> anyhow::Result<()> {
1208                Ok(())
1209            }
1210
1211            fn generate_account_state(
1212                &self,
1213                _: Vec<AccountBalance>,
1214                _: Vec<MarginBalance>,
1215                _: bool,
1216                _: UnixNanos,
1217                _: Option<nautilus_core::Params>,
1218            ) -> anyhow::Result<()> {
1219                Ok(())
1220            }
1221
1222            fn generate_order_status_report_task(
1223                &self,
1224                _: &GenerateOrderStatusReport,
1225            ) -> Option<ExecutionReportTask<Option<OrderStatusReport>>> {
1226                self.worker.then(|| self.status_task())
1227            }
1228
1229            async fn generate_order_status_report(
1230                &self,
1231                _: &GenerateOrderStatusReport,
1232            ) -> anyhow::Result<Option<OrderStatusReport>> {
1233                let task = self.status_task();
1234                task.collection.await;
1235                (task.finish)()
1236            }
1237
1238            fn generate_fill_reports_task(
1239                &self,
1240                cmd: &GenerateFillReports,
1241            ) -> Option<ExecutionReportTask<Vec<FillReport>>> {
1242                self.worker.then(|| self.fill_task(cmd))
1243            }
1244
1245            async fn generate_fill_reports(
1246                &self,
1247                cmd: GenerateFillReports,
1248            ) -> anyhow::Result<Vec<FillReport>> {
1249                let task = self.fill_task(&cmd);
1250                task.collection.await;
1251                (task.finish)()
1252            }
1253        }
1254
1255        fn query() -> TargetedOrderQuery {
1256            TargetedOrderQuery {
1257                client_order_id: ClientOrderId::from("O-TARGETED"),
1258                responsible_clients: IndexSet::from([ClientId::from("A")]),
1259                command: GenerateOrderStatusReport::new(
1260                    UUID4::new(),
1261                    UnixNanos::from(123),
1262                    Some(InstrumentId::from("ETHUSDT-PERP.BINANCE")),
1263                    Some(ClientOrderId::from("O-TARGETED")),
1264                    Some(VenueOrderId::from("V-TARGETED")),
1265                    None,
1266                    None,
1267                ),
1268                report: None,
1269                filled_qty: Quantity::from("0.0"),
1270            }
1271        }
1272
1273        fn report() -> OrderStatusReport {
1274            let mut report = OrderStatusReport::new(
1275                AccountId::from("TEST-001"),
1276                InstrumentId::from("ETHUSDT-PERP.BINANCE"),
1277                Some(ClientOrderId::from("O-TARGETED")),
1278                VenueOrderId::from("V-TARGETED"),
1279                Some(OrderSide::Buy),
1280                OrderType::Limit,
1281                TimeInForce::Gtc,
1282                OrderStatus::Canceled,
1283                Quantity::from("3.0"),
1284                Quantity::from("1.0"),
1285                UnixNanos::from(11),
1286                UnixNanos::from(22),
1287                UnixNanos::from(33),
1288                None,
1289            );
1290            report.report_id = UUID4::from("00000000-0000-4000-8000-000000000011");
1291            report
1292        }
1293
1294        fn fill() -> FillReport {
1295            let mut report = FillReport::new(
1296                AccountId::from("TEST-001"),
1297                InstrumentId::from("ETHUSDT-PERP.BINANCE"),
1298                VenueOrderId::from("V-TARGETED"),
1299                TradeId::from("T-TARGETED"),
1300                OrderSide::Buy,
1301                Quantity::from("1.0"),
1302                Price::from("101.0"),
1303                Money::from("0.25 USDT"),
1304                LiquiditySide::Taker,
1305                Some(ClientOrderId::from("O-TARGETED")),
1306                None,
1307                UnixNanos::from(21),
1308                UnixNanos::from(31),
1309                None,
1310            );
1311            report.report_id = UUID4::from("00000000-0000-4000-8000-000000000022");
1312            report
1313        }
1314
1315        fn client(state: &CollectionState, worker: bool, release_at: usize) -> CollectionClient {
1316            CollectionClient {
1317                id: ClientId::from("A"),
1318                report: Some(report()),
1319                fills: vec![fill()],
1320                state: state.clone(),
1321                worker,
1322                release_at,
1323                release: Arc::new(tokio::sync::Notify::new()),
1324            }
1325        }
1326
1327        #[cfg_attr(
1328            all(feature = "simulation", madsim),
1329            allow(
1330                clippy::unused_async,
1331                reason = "the Tokio clock requires an awaitable advance operation"
1332            )
1333        )]
1334        async fn advance(duration: Duration) {
1335            #[cfg(all(feature = "simulation", madsim))]
1336            madsim::time::advance(duration);
1337            #[cfg(not(all(feature = "simulation", madsim)))]
1338            tokio::time::advance(duration).await;
1339        }
1340
1341        #[rstest]
1342        #[cfg_attr(
1343            not(all(feature = "simulation", madsim)),
1344            tokio::test(start_paused = true)
1345        )]
1346        #[cfg_attr(all(feature = "simulation", madsim), madsim::test)]
1347        async fn test_targeted_collection_preserves_schedule_and_first_match(
1348            #[values(false, true)] worker: bool,
1349        ) {
1350            let state = CollectionState::default();
1351            let mut a = client(&state, worker, 0);
1352            a.report = None;
1353            let mut b = client(&state, worker, 0);
1354            b.id = ClientId::from("B");
1355            let mut c = client(&state, worker, 0);
1356            c.id = ClientId::from("C");
1357            let clients = vec![a, b, c]
1358                .into_iter()
1359                .map(|c| LiveExecutionClient::new(Box::new(c)))
1360                .collect::<Vec<_>>();
1361            let mut query = query();
1362            query.responsible_clients = IndexSet::from([
1363                ClientId::from("MISSING"),
1364                ClientId::from("A"),
1365                ClientId::from("B"),
1366                ClientId::from("C"),
1367            ]);
1368            let command_id = query.command.command_id;
1369            let results = Rc::new(RefCell::new(Vec::new()));
1370            let start = dst::time::Instant::now();
1371            assert!(
1372                collect_targeted_order_reports(
1373                    vec![query.clone(), query],
1374                    clients,
1375                    Duration::from_millis(10),
1376                    start + Duration::from_secs(1),
1377                    results.clone()
1378                )
1379                .await
1380            );
1381
1382            let events = state
1383                .events
1384                .borrow()
1385                .iter()
1386                .map(|(kind, id, ts)| {
1387                    let elapsed = ts.duration_since(start);
1388                    // Simulated worker wakeups add nanoseconds to millisecond pacing
1389                    #[cfg(all(feature = "simulation", madsim))]
1390                    let elapsed = Duration::from_millis(elapsed.as_millis().try_into().unwrap());
1391                    (*kind, *id, elapsed)
1392                })
1393                .collect::<Vec<_>>();
1394
1395            assert_eq!(
1396                events,
1397                vec![
1398                    ("status", ClientId::from("A"), Duration::ZERO),
1399                    ("status", ClientId::from("B"), Duration::from_millis(10)),
1400                    ("fills", ClientId::from("B"), Duration::from_millis(10)),
1401                    ("status", ClientId::from("A"), Duration::from_millis(20)),
1402                    ("status", ClientId::from("B"), Duration::from_millis(30)),
1403                    ("fills", ClientId::from("B"), Duration::from_millis(30))
1404                ]
1405            );
1406            let results = results.borrow();
1407            assert_eq!(results.len(), 2);
1408
1409            for result in results.iter() {
1410                assert_eq!(result.client_order_id, ClientOrderId::from("O-TARGETED"));
1411                assert_eq!(result.client_id, Some(ClientId::from("B")));
1412                assert_eq!(result.report, Some(report()));
1413                assert!(!result.coverage_complete);
1414            }
1415
1416            assert_eq!(results[0].fills, vec![fill()]);
1417            assert_eq!(results[1].fills, vec![fill()]);
1418
1419            for cmd in state.commands.borrow().iter() {
1420                assert_eq!(cmd.correlation_id, Some(command_id));
1421                assert_eq!(cmd.ts_init, UnixNanos::from(123));
1422                assert_eq!(cmd.instrument_id, Some(fill().instrument_id));
1423                assert_eq!(cmd.venue_order_id, Some(fill().venue_order_id));
1424                assert_eq!(cmd.start, None);
1425                assert_eq!(cmd.end, None);
1426                assert_eq!(cmd.params, None);
1427                assert_eq!(cmd.causation_id, None);
1428                assert_eq!(cmd.log_receipt_level, LogLevel::Debug);
1429            }
1430        }
1431
1432        #[rstest]
1433        #[case::before(-1)]
1434        #[case::exact(0)]
1435        #[case::after(1)]
1436        #[cfg_attr(
1437            not(all(feature = "simulation", madsim)),
1438            tokio::test(start_paused = true)
1439        )]
1440        #[cfg_attr(all(feature = "simulation", madsim), madsim::test)]
1441        async fn test_targeted_collection_strict_stage_deadline(#[case] offset: i64) {
1442            let state = CollectionState::default();
1443            let c = LiveExecutionClient::new(Box::new(client(&state, true, 0)));
1444            let deadline = dst::time::Instant::now() + Duration::from_secs(1);
1445
1446            let receipt = c
1447                .collect_order_status_report(&query().command)
1448                .await
1449                .unwrap();
1450
1451            let boundary = if offset < 0 {
1452                deadline.checked_sub(Duration::from_nanos(1)).unwrap()
1453            } else {
1454                deadline + Duration::from_nanos(offset.unsigned_abs())
1455            };
1456
1457            advance(boundary.saturating_duration_since(dst::time::Instant::now())).await;
1458            assert_eq!(dst::time::Instant::now(), boundary);
1459            assert_eq!(
1460                accept_collected_report(Ok(receipt), deadline).map(|result| result.unwrap()),
1461                (offset < 0).then(|| Some(report()))
1462            );
1463            assert_eq!(state.status_finished.get(), usize::from(offset < 0));
1464            assert_eq!(state.fill_finished.get(), 0);
1465        }
1466
1467        #[rstest]
1468        #[case::account("account")]
1469        #[case::instrument("instrument")]
1470        #[case::venue_order("venue_order")]
1471        #[case::side("side")]
1472        #[cfg_attr(
1473            not(all(feature = "simulation", madsim)),
1474            tokio::test(start_paused = true)
1475        )]
1476        #[cfg_attr(all(feature = "simulation", madsim), madsim::test)]
1477        async fn test_targeted_collection_filters_fill_scope(#[case] field: &str) {
1478            let state = CollectionState::default();
1479            let mut c = client(&state, true, 0);
1480            let mut other = fill();
1481            match field {
1482                "account" => other.account_id = AccountId::from("OTHER-002"),
1483                "instrument" => other.instrument_id = InstrumentId::from("BTCUSDT-PERP.BINANCE"),
1484                "venue_order" => other.venue_order_id = VenueOrderId::from("V-OTHER"),
1485                "side" => other.order_side = OrderSide::Sell,
1486                _ => unreachable!(),
1487            }
1488
1489            c.fills.push(other);
1490            let results = Rc::new(RefCell::new(Vec::new()));
1491            assert!(
1492                collect_targeted_order_reports(
1493                    vec![query()],
1494                    vec![LiveExecutionClient::new(Box::new(c))],
1495                    Duration::ZERO,
1496                    dst::time::Instant::now() + Duration::from_secs(1),
1497                    results.clone()
1498                )
1499                .await
1500            );
1501            assert_eq!(results.borrow()[0].fills, vec![fill()]);
1502        }
1503
1504        #[rstest]
1505        #[case::status(1)]
1506        #[case::fills(2)]
1507        #[cfg_attr(
1508            not(all(feature = "simulation", madsim)),
1509            tokio::test(start_paused = true)
1510        )]
1511        #[cfg_attr(all(feature = "simulation", madsim), madsim::test)]
1512        async fn test_targeted_collection_preserves_original_budget(#[case] release_at: usize) {
1513            let state = CollectionState::default();
1514            let c = client(&state, true, release_at);
1515            let release = c.release.clone();
1516            let clients = vec![LiveExecutionClient::new(Box::new(c))];
1517            let results = Rc::new(RefCell::new(Vec::new()));
1518            let deadline = dst::time::Instant::now() + Duration::from_millis(100);
1519            let mut request = Box::pin(collect_targeted_order_reports(
1520                vec![query()],
1521                clients,
1522                Duration::ZERO,
1523                deadline,
1524                results.clone(),
1525            ));
1526            advance(Duration::from_millis(60)).await;
1527
1528            while state.started.load(Ordering::SeqCst) < release_at {
1529                assert!(request.as_mut().now_or_never().is_none());
1530                tokio::task::yield_now().await;
1531            }
1532
1533            advance(Duration::from_millis(40)).await;
1534            release.notify_one();
1535            assert!(!request.await);
1536            assert_eq!(state.status_finished.get(), usize::from(release_at == 2));
1537            assert_eq!(state.fill_finished.get(), 0);
1538            let results = results.borrow();
1539            assert_eq!(results.len(), usize::from(release_at == 2));
1540
1541            if release_at == 2 {
1542                assert_eq!(results[0].report, Some(report()));
1543                assert!(results[0].fills.is_empty());
1544            }
1545        }
1546    }
1547
1548    #[rstest]
1549    #[tokio::test]
1550    async fn test_targeted_reports_missing_client_marks_coverage_incomplete(
1551        #[values(false, true)] missing_first: bool,
1552    ) {
1553        let client = CommissionStubClient::new(CommissionOutcome::NoOverride);
1554        let missing_id = ClientId::from("MISSING");
1555        let mut responsible_clients = vec![client.client_id(), missing_id];
1556
1557        if missing_first {
1558            responsible_clients.reverse();
1559        }
1560
1561        let client_order_id = ClientOrderId::from("O-MISSING-CLIENT");
1562
1563        let query = TargetedOrderQuery {
1564            client_order_id,
1565            responsible_clients: responsible_clients.into_iter().collect(),
1566            command: GenerateOrderStatusReport::new(
1567                UUID4::new(),
1568                UnixNanos::from(123),
1569                Some(InstrumentId::from("ETHUSDT-PERP.BINANCE")),
1570                Some(client_order_id),
1571                Some(VenueOrderId::from("V-MISSING-CLIENT")),
1572                None,
1573                None,
1574            ),
1575            report: None,
1576            filled_qty: Quantity::from("0.0"),
1577        };
1578
1579        let results = request_targeted_order_reports(vec![query], &[&client], Duration::ZERO).await;
1580
1581        assert_eq!(results.len(), 1);
1582        let result = &results[0];
1583        assert_eq!(result.client_order_id, client_order_id);
1584        assert_eq!(result.client_id, None);
1585        assert_eq!(result.report, None);
1586        assert!(result.fills.is_empty());
1587        assert!(!result.coverage_complete);
1588    }
1589
1590    /// Configured result of a stub commission calculation.
1591    #[derive(Clone)]
1592    pub(crate) enum CommissionOutcome {
1593        Value(Money),
1594        NoOverride,
1595        Failure,
1596    }
1597
1598    /// Execution client that records commission inputs and returns a configured result.
1599    pub(crate) struct CommissionStubClient {
1600        outcome: CommissionOutcome,
1601        seen: RefCell<Option<(Quantity, Price, LiquiditySide)>>,
1602        pub(crate) requires_authoritative_fills: bool,
1603    }
1604
1605    impl CommissionStubClient {
1606        /// Creates a client with the specified commission result.
1607        pub(crate) fn new(outcome: CommissionOutcome) -> Self {
1608            Self {
1609                outcome,
1610                seen: RefCell::new(None),
1611                requires_authoritative_fills: false,
1612            }
1613        }
1614
1615        /// Returns the last recorded commission inputs.
1616        pub(crate) fn seen(&self) -> Option<(Quantity, Price, LiquiditySide)> {
1617            *self.seen.borrow()
1618        }
1619
1620        /// Clears the recorded commission inputs.
1621        pub(crate) fn clear_seen(&self) {
1622            *self.seen.borrow_mut() = None;
1623        }
1624    }
1625
1626    #[async_trait::async_trait(?Send)]
1627    impl ExecutionClient for CommissionStubClient {
1628        fn requires_authoritative_fills(&self) -> bool {
1629            self.requires_authoritative_fills
1630        }
1631
1632        fn is_connected(&self) -> bool {
1633            true
1634        }
1635
1636        fn client_id(&self) -> ClientId {
1637            ClientId::from("STUB")
1638        }
1639
1640        fn account_id(&self) -> AccountId {
1641            AccountId::from("STUB-001")
1642        }
1643
1644        fn venue(&self) -> Venue {
1645            Venue::from("STUB")
1646        }
1647
1648        fn oms_type(&self) -> OmsType {
1649            OmsType::Netting
1650        }
1651
1652        fn get_account(&self) -> Option<AccountAny> {
1653            None
1654        }
1655
1656        fn generate_account_state(
1657            &self,
1658            _balances: Vec<AccountBalance>,
1659            _margins: Vec<MarginBalance>,
1660            _reported: bool,
1661            _ts_event: UnixNanos,
1662            _info: Option<Params>,
1663        ) -> anyhow::Result<()> {
1664            Ok(())
1665        }
1666
1667        fn start(&mut self) -> anyhow::Result<()> {
1668            Ok(())
1669        }
1670
1671        fn stop(&mut self) -> anyhow::Result<()> {
1672            Ok(())
1673        }
1674
1675        fn calculate_commission(
1676            &self,
1677            _instrument: &InstrumentAny,
1678            last_qty: Quantity,
1679            last_px: Price,
1680            liquidity_side: LiquiditySide,
1681        ) -> anyhow::Result<Option<Money>> {
1682            *self.seen.borrow_mut() = Some((last_qty, last_px, liquidity_side));
1683
1684            match &self.outcome {
1685                CommissionOutcome::Value(money) => Ok(Some(*money)),
1686                CommissionOutcome::NoOverride => Ok(None),
1687                CommissionOutcome::Failure => {
1688                    anyhow::bail!("commission is not representable as Money")
1689                }
1690            }
1691        }
1692    }
1693
1694    fn commission_fixtures() -> (OrderAny, OrderStatusReport, InstrumentAny) {
1695        let instrument = crypto_perpetual_ethusdt();
1696        let order = OrderTestBuilder::new(OrderType::Limit)
1697            .instrument_id(instrument.id())
1698            .side(OrderSide::Buy)
1699            .quantity(Quantity::from("10.0"))
1700            .price(Price::from("100.00"))
1701            .build();
1702        let report = OrderStatusReport::new(
1703            AccountId::from("STUB-001"),
1704            instrument.id(),
1705            Some(order.client_order_id()),
1706            VenueOrderId::from("V-1"),
1707            OrderSide::Buy.into(),
1708            OrderType::Limit,
1709            TimeInForce::Gtc,
1710            OrderStatus::Filled,
1711            Quantity::from("10.0"),
1712            Quantity::from("10.0"),
1713            UnixNanos::from(1),
1714            UnixNanos::from(1),
1715            UnixNanos::from(1),
1716            None,
1717        )
1718        .with_avg_px(dec!(100.0));
1719
1720        (order, report, InstrumentAny::CryptoPerpetual(instrument))
1721    }
1722
1723    #[rstest]
1724    fn test_create_orphan_fill_order_report_preserves_aggregate_fields() {
1725        let (instrument, fills) = orphan_fill_fixtures();
1726        let reports = fills.iter().collect::<Vec<_>>();
1727
1728        let report = create_orphan_fill_order_report(&reports, &instrument).unwrap();
1729        let expected = OrderStatusReport::new(
1730            AccountId::from("STUB-001"),
1731            instrument.id(),
1732            Some(ClientOrderId::from("O-ORPHAN")),
1733            VenueOrderId::from("V-ORPHAN"),
1734            OrderSide::Buy.into(),
1735            OrderType::Market,
1736            TimeInForce::Gtc,
1737            OrderStatus::Filled,
1738            Quantity::from("4.000"),
1739            Quantity::from("4.000"),
1740            UnixNanos::from(10),
1741            UnixNanos::from(30),
1742            UnixNanos::from(50),
1743            Some(report.report_id),
1744        )
1745        .with_avg_px(dec!(115))
1746        .with_venue_position_id(PositionId::from("P-ORPHAN"));
1747
1748        assert_eq!(report, expected);
1749    }
1750
1751    #[rstest]
1752    #[case::empty("empty", "fill group is empty")]
1753    #[case::missing_position("missing_position", "venue position ID is missing")]
1754    #[case::account("account", "account ID differs across fill group")]
1755    #[case::instrument("instrument", "instrument ID differs across fill group")]
1756    #[case::venue_order("venue_order", "venue order ID differs across fill group")]
1757    #[case::client_order("client_order", "client order ID differs across fill group")]
1758    #[case::side("side", "order side differs across fill group")]
1759    #[case::position("position", "venue position ID differs across fill group")]
1760    #[case::metadata("metadata", "instrument metadata does not match fill group")]
1761    #[case::zero("zero", "fill group quantity is not positive")]
1762    fn test_create_orphan_fill_order_report_rejects_invalid_group(
1763        #[case] invalid_field: &str,
1764        #[case] expected: &str,
1765    ) {
1766        let (instrument, mut fills) = orphan_fill_fixtures();
1767
1768        match invalid_field {
1769            "empty" => fills.clear(),
1770            "missing_position" => fills[0].venue_position_id = None,
1771            "account" => fills[1].account_id = AccountId::from("OTHER-002"),
1772            "instrument" => fills[1].instrument_id = InstrumentId::from("OTHER.TEST"),
1773            "venue_order" => fills[1].venue_order_id = VenueOrderId::from("V-OTHER"),
1774            "client_order" => fills[1].client_order_id = Some(ClientOrderId::from("O-OTHER")),
1775            "side" => fills[1].order_side = OrderSide::Sell,
1776            "position" => fills[1].venue_position_id = Some(PositionId::from("P-OTHER")),
1777            "metadata" => {
1778                for fill in &mut fills {
1779                    fill.instrument_id = InstrumentId::from("OTHER.TEST");
1780                }
1781            }
1782            "zero" => {
1783                for fill in &mut fills {
1784                    fill.last_qty = Quantity::zero(3);
1785                }
1786            }
1787            _ => unreachable!(),
1788        }
1789
1790        let reports = fills.iter().collect::<Vec<_>>();
1791
1792        let error = create_orphan_fill_order_report(&reports, &instrument).unwrap_err();
1793
1794        assert_eq!(error.to_string(), expected);
1795    }
1796
1797    #[rstest]
1798    fn test_create_orphan_fill_order_report_rejects_aggregate_quantity_overflow() {
1799        let (instrument, mut fills) = orphan_fill_fixtures();
1800        let max_qty = Quantity::new(QUANTITY_MAX, 0);
1801
1802        for fill in &mut fills {
1803            fill.last_qty = max_qty;
1804            fill.last_px = Price::from("1.00");
1805        }
1806
1807        let expected =
1808            Quantity::from_decimal_dp(max_qty.as_decimal() * dec!(2), instrument.size_precision())
1809                .unwrap_err();
1810        let reports = fills.iter().collect::<Vec<_>>();
1811
1812        let error = create_orphan_fill_order_report(&reports, &instrument).unwrap_err();
1813
1814        assert_eq!(error.to_string(), expected.to_string());
1815    }
1816
1817    fn orphan_fill_fixtures() -> (InstrumentAny, Vec<FillReport>) {
1818        let instrument = InstrumentAny::CryptoPerpetual(crypto_perpetual_ethusdt());
1819
1820        let fills = [("1.000", "100.00", 30, 40), ("3.000", "120.00", 10, 50)]
1821            .into_iter()
1822            .enumerate()
1823            .map(|(index, (qty, px, ts_event, ts_init))| {
1824                FillReport::new(
1825                    AccountId::from("STUB-001"),
1826                    instrument.id(),
1827                    VenueOrderId::from("V-ORPHAN"),
1828                    TradeId::new(format!("T-{index}")),
1829                    OrderSide::Buy,
1830                    Quantity::from(qty),
1831                    Price::from(px),
1832                    Money::from("0.10 USDT"),
1833                    LiquiditySide::Taker,
1834                    Some(ClientOrderId::from("O-ORPHAN")),
1835                    Some(PositionId::from("P-ORPHAN")),
1836                    UnixNanos::from(ts_event),
1837                    UnixNanos::from(ts_init),
1838                    None,
1839                )
1840            })
1841            .collect();
1842
1843        (instrument, fills)
1844    }
1845
1846    #[rstest]
1847    #[case::venue_format("T-VENUE-1")]
1848    #[case::uuid_v5_format("2d89666b-1a1e-5a75-b193-4eb3b454c757")]
1849    fn test_has_active_inferred_fill_ignores_venue_trade_ids(#[case] trade_id: &str) {
1850        let instrument = InstrumentAny::CryptoPerpetual(crypto_perpetual_ethusdt());
1851        let mut order = OrderTestBuilder::new(OrderType::Market)
1852            .instrument_id(instrument.id())
1853            .side(OrderSide::Buy)
1854            .quantity(Quantity::from("1.000"))
1855            .build();
1856        let submitted = TestOrderEventStubs::submitted(&order, AccountId::from("TEST-001"));
1857        order.apply(submitted).unwrap();
1858
1859        let trade_id = TradeId::from(trade_id);
1860
1861        let OrderEventAny::Filled(mut fill) = TestOrderEventStubs::filled(
1862            &order,
1863            &instrument,
1864            Some(trade_id),
1865            None,
1866            Some(Price::from("100.00")),
1867            Some(Quantity::from("1.000")),
1868            None,
1869            None,
1870            None,
1871            None,
1872        ) else {
1873            unreachable!();
1874        };
1875
1876        fill.reconciliation = true;
1877        order.apply(OrderEventAny::Filled(fill)).unwrap();
1878
1879        assert!(order.trade_ids().contains(&&trade_id));
1880        assert!(!has_active_inferred_fill(&order).unwrap());
1881    }
1882
1883    #[rstest]
1884    fn test_resolve_inferred_fill_commission_without_client_fails_closed() {
1885        let (order, report, instrument) = commission_fixtures();
1886
1887        let price_and_liquidity = inferred_fill_price_and_liquidity(&order, &report, &instrument);
1888
1889        let error = resolve_inferred_fill_commission(
1890            Quantity::from("5.0"),
1891            price_and_liquidity,
1892            &instrument,
1893            None,
1894        )
1895        .expect_err("a missing responsible client must defer the fill");
1896
1897        assert_eq!(
1898            error.to_string(),
1899            "responsible execution client is unavailable"
1900        );
1901    }
1902
1903    #[rstest]
1904    fn test_resolve_inferred_fill_commission_without_price_uses_generic_path() {
1905        let instrument = crypto_perpetual_ethusdt();
1906        let order = OrderTestBuilder::new(OrderType::Market)
1907            .instrument_id(instrument.id())
1908            .side(OrderSide::Buy)
1909            .quantity(Quantity::from("10.0"))
1910            .build();
1911
1912        let report = OrderStatusReport::new(
1913            AccountId::from("STUB-001"),
1914            instrument.id(),
1915            Some(order.client_order_id()),
1916            VenueOrderId::from("V-1"),
1917            OrderSide::Buy.into(),
1918            OrderType::Market,
1919            TimeInForce::Gtc,
1920            OrderStatus::Filled,
1921            Quantity::from("10.0"),
1922            Quantity::from("10.0"),
1923            UnixNanos::from(1),
1924            UnixNanos::from(1),
1925            UnixNanos::from(1),
1926            None,
1927        );
1928        let client =
1929            CommissionStubClient::new(CommissionOutcome::Value(Money::new(1.0, Currency::USDT())));
1930        let instrument = InstrumentAny::CryptoPerpetual(instrument);
1931
1932        let price_and_liquidity = inferred_fill_price_and_liquidity(&order, &report, &instrument);
1933
1934        let commission = resolve_inferred_fill_commission(
1935            Quantity::from("5.0"),
1936            price_and_liquidity,
1937            &instrument,
1938            Some(&client),
1939        )
1940        .expect("an unresolvable price is not a failure");
1941
1942        assert_eq!(commission, None, "no price means no venue commission");
1943    }
1944
1945    #[rstest]
1946    fn test_resolve_inferred_fill_commission_returns_venue_value() {
1947        let (order, report, instrument) = commission_fixtures();
1948        let expected = Money::new(2.5, Currency::USDT());
1949        let client = CommissionStubClient::new(CommissionOutcome::Value(expected));
1950
1951        let price_and_liquidity = inferred_fill_price_and_liquidity(&order, &report, &instrument);
1952
1953        let commission = resolve_inferred_fill_commission(
1954            Quantity::from("5.0"),
1955            price_and_liquidity,
1956            &instrument,
1957            Some(&client),
1958        )
1959        .expect("a representable commission succeeds");
1960
1961        assert_eq!(commission, Some(expected));
1962        assert_eq!(
1963            client.seen(),
1964            Some((
1965                Quantity::from("5.0"),
1966                Price::from("100.00"),
1967                LiquiditySide::NoLiquiditySide,
1968            )),
1969            "the resolver passes the inferred fill quantity, resolved price, and liquidity side"
1970        );
1971    }
1972
1973    #[rstest]
1974    fn test_resolve_inferred_fill_commission_honors_no_override() {
1975        let (order, report, instrument) = commission_fixtures();
1976        let client = CommissionStubClient::new(CommissionOutcome::NoOverride);
1977
1978        let price_and_liquidity = inferred_fill_price_and_liquidity(&order, &report, &instrument);
1979
1980        let commission = resolve_inferred_fill_commission(
1981            Quantity::from("5.0"),
1982            price_and_liquidity,
1983            &instrument,
1984            Some(&client),
1985        )
1986        .expect("no override is not a failure");
1987
1988        assert_eq!(commission, None);
1989    }
1990
1991    #[rstest]
1992    fn test_resolve_inferred_fill_commission_propagates_failure() {
1993        let (order, report, instrument) = commission_fixtures();
1994        let client = CommissionStubClient::new(CommissionOutcome::Failure);
1995
1996        let price_and_liquidity = inferred_fill_price_and_liquidity(&order, &report, &instrument);
1997
1998        let result = resolve_inferred_fill_commission(
1999            Quantity::from("5.0"),
2000            price_and_liquidity,
2001            &instrument,
2002            Some(&client),
2003        );
2004
2005        assert_eq!(
2006            result.unwrap_err().to_string(),
2007            "commission is not representable as Money"
2008        );
2009    }
2010
2011    #[rstest]
2012    #[case::account(true, false, true, true, "resolved")]
2013    #[case::account_unavailable(true, false, false, true, "unavailable")]
2014    #[case::venue(false, true, true, true, "resolved")]
2015    #[case::venue_unavailable(false, true, false, true, "unavailable")]
2016    #[case::unmatched(false, false, true, true, "unresolved")]
2017    #[case::no_clients(false, false, true, false, "unresolved")]
2018    fn test_resolve_position_report_client_coverage(
2019        #[case] account_matches: bool,
2020        #[case] venue_matches: bool,
2021        #[case] available: bool,
2022        #[case] include_client: bool,
2023        #[case] expected: &str,
2024    ) {
2025        let key = (InstrumentId::from("ETH.TEST"), AccountId::from("TEST-001"));
2026
2027        let client = CoverageStubClient {
2028            id: ClientId::from("COVERAGE"),
2029            account_id: if account_matches {
2030                key.1
2031            } else {
2032                AccountId::from("OTHER-001")
2033            },
2034            venue: if venue_matches {
2035                key.0.venue
2036            } else {
2037                Venue::from("OTHER")
2038            },
2039            available,
2040        };
2041
2042        let clients: Vec<&dyn ExecutionClient> = if include_client {
2043            vec![&client]
2044        } else {
2045            vec![]
2046        };
2047
2048        let expected = match expected {
2049            "resolved" => ReportClientCoverage::Resolved(IndexSet::from([client.id])),
2050            "unavailable" => ReportClientCoverage::Unavailable(IndexSet::from([client.id])),
2051            "unresolved" => ReportClientCoverage::Unresolved,
2052            _ => unreachable!(),
2053        };
2054
2055        let result = resolve_position_report_client_coverage(key, &clients);
2056
2057        assert_eq!(result, expected);
2058    }
2059
2060    #[rstest]
2061    #[case::account_available(true, false)]
2062    #[case::account_unavailable(false, true)]
2063    fn test_position_coverage_prefers_account_clients(
2064        #[case] account_available: bool,
2065        #[case] venue_available: bool,
2066    ) {
2067        let key = (InstrumentId::from("ETH.TEST"), AccountId::from("TEST-001"));
2068
2069        let account_client = CoverageStubClient {
2070            id: ClientId::from("ACCOUNT"),
2071            account_id: key.1,
2072            venue: Venue::from("OTHER"),
2073            available: account_available,
2074        };
2075
2076        let venue_client = CoverageStubClient {
2077            id: ClientId::from("VENUE"),
2078            account_id: AccountId::from("OTHER-001"),
2079            venue: key.0.venue,
2080            available: venue_available,
2081        };
2082
2083        let expected_clients = IndexSet::from([account_client.id]);
2084
2085        let expected = if account_available {
2086            ReportClientCoverage::Resolved(expected_clients)
2087        } else {
2088            ReportClientCoverage::Unavailable(expected_clients)
2089        };
2090
2091        let result =
2092            resolve_position_report_client_coverage(key, &[&venue_client, &account_client]);
2093
2094        assert_eq!(result, expected);
2095    }
2096
2097    struct CoverageStubClient {
2098        id: ClientId,
2099        account_id: AccountId,
2100        venue: Venue,
2101        available: bool,
2102    }
2103
2104    #[async_trait::async_trait(?Send)]
2105    impl ExecutionClient for CoverageStubClient {
2106        fn is_connected(&self) -> bool {
2107            true
2108        }
2109
2110        fn client_id(&self) -> ClientId {
2111            self.id
2112        }
2113
2114        fn account_id(&self) -> AccountId {
2115            self.account_id
2116        }
2117
2118        fn venue(&self) -> Venue {
2119            self.venue
2120        }
2121
2122        fn oms_type(&self) -> OmsType {
2123            OmsType::Netting
2124        }
2125
2126        fn get_account(&self) -> Option<AccountAny> {
2127            None
2128        }
2129
2130        fn provides_bulk_position_coverage(&self, _instrument_id: InstrumentId) -> bool {
2131            self.available
2132        }
2133
2134        fn generate_account_state(
2135            &self,
2136            _balances: Vec<AccountBalance>,
2137            _margins: Vec<MarginBalance>,
2138            _reported: bool,
2139            _ts_event: UnixNanos,
2140            _info: Option<Params>,
2141        ) -> anyhow::Result<()> {
2142            Ok(())
2143        }
2144
2145        fn start(&mut self) -> anyhow::Result<()> {
2146            Ok(())
2147        }
2148
2149        fn stop(&mut self) -> anyhow::Result<()> {
2150            Ok(())
2151        }
2152    }
2153
2154    #[rstest]
2155    #[case::empty(vec![], None)]
2156    #[case::flat(vec![(0, dec!(100))], None)]
2157    #[case::weighted(vec![(1, dec!(100)), (3, dec!(120))], Some(dec!(115)))]
2158    #[case::short(vec![(-1, dec!(100)), (-3, dec!(120))], Some(dec!(115)))]
2159    #[case::ignored(vec![(1, dec!(0)), (2, dec!(-10)), (3, dec!(120))], Some(dec!(120)))]
2160    fn test_position_avg_px(
2161        #[case] entries: Vec<(i32, Decimal)>,
2162        #[case] expected: Option<Decimal>,
2163    ) {
2164        let instrument = InstrumentAny::CryptoPerpetual(crypto_perpetual_ethusdt());
2165        let order = OrderTestBuilder::new(OrderType::Market)
2166            .instrument_id(instrument.id())
2167            .side(OrderSide::Buy)
2168            .quantity(Quantity::from("1.000"))
2169            .build();
2170        let fill = TestOrderEventStubs::filled(
2171            &order,
2172            &instrument,
2173            None,
2174            Some(PositionId::from("P-AVG")),
2175            Some(Price::from("100.00")),
2176            Some(Quantity::from("1.000")),
2177            None,
2178            None,
2179            None,
2180            None,
2181        );
2182        let position = Position::new(&instrument, fill.into());
2183
2184        let positions = entries
2185            .into_iter()
2186            .map(|(qty, px)| {
2187                let mut position = position.clone();
2188                position.signed_qty = Decimal::from(qty);
2189                position.quantity = Quantity::from_decimal_dp(Decimal::from(qty.abs()), 3).unwrap();
2190                position.avg_px_open = px;
2191                position
2192            })
2193            .collect::<Vec<_>>();
2194
2195        let result = position_avg_px(&positions);
2196
2197        assert_eq!(result, expected);
2198    }
2199
2200    #[rstest]
2201    #[case::empty(vec![], (dec!(0), dec!(0), dec!(0)))]
2202    #[case::zero(vec![0, 0], (dec!(0), dec!(0), dec!(0)))]
2203    #[case::long(vec![2, 3], (dec!(5), dec!(5), dec!(0)))]
2204    #[case::short(vec![-2, -3], (dec!(-5), dec!(0), dec!(5)))]
2205    #[case::mixed(vec![2, -5, 1], (dec!(-2), dec!(3), dec!(5)))]
2206    #[case::offset(vec![3, -3], (dec!(0), dec!(3), dec!(3)))]
2207    fn test_position_qty_aggregates(
2208        #[case] quantities: Vec<i32>,
2209        #[case] expected: (Decimal, Decimal, Decimal),
2210    ) {
2211        let result = position_qty_aggregates(quantities.into_iter().map(Decimal::from));
2212
2213        assert_eq!(result, expected);
2214    }
2215
2216    proptest! {
2217        #[rstest]
2218        fn prop_position_quantities_match_tolerance_and_side_exposure(
2219            long in 100i64..1_000_000,
2220            short in 100i64..1_000_000,
2221            long_delta in -10i64..=10,
2222            short_delta in -10i64..=10,
2223            tolerance in 0i64..=20,
2224            scale in 0u32..=6,
2225            side_reports in any::<bool>(),
2226        ) {
2227            let venue_net = long + long_delta - short - short_delta;
2228            let (venue_long, venue_short) = if side_reports {
2229                (long + long_delta, short + short_delta)
2230            } else {
2231                (venue_net.max(0), (-venue_net).max(0))
2232            };
2233            let comparison = PositionQuantityComparison {
2234                cached_positions: Vec::new(),
2235                cached_signed_qty: Decimal::new(long - short, scale),
2236                cached_long_qty: Decimal::new(long, scale),
2237                cached_short_qty: Decimal::new(short, scale),
2238                venue_signed_qty: Decimal::new(venue_net, scale),
2239                venue_long_qty: Decimal::new(venue_long, scale),
2240                venue_short_qty: Decimal::new(venue_short, scale),
2241                nonflat_count: if side_reports { 2 } else { 1 },
2242                venue_report: None,
2243                venue_has_side_reports: side_reports,
2244            };
2245            let mut largest_error = (long_delta - short_delta).abs();
2246
2247            if side_reports {
2248                largest_error = largest_error.max(long_delta.abs()).max(short_delta.abs());
2249            }
2250
2251            prop_assert_eq!(
2252                comparison.quantities_match(Decimal::new(tolerance, scale)),
2253                largest_error <= tolerance,
2254            );
2255            prop_assert!(comparison.quantities_match(Decimal::new(largest_error, scale)));
2256
2257            if largest_error > 0 {
2258                prop_assert!(!comparison.quantities_match(Decimal::new(largest_error - 1, scale)));
2259            }
2260        }
2261    }
2262
2263    proptest! {
2264        #[rstest]
2265        fn prop_position_qty_aggregates_preserves_sign_and_net(
2266            values in proptest::collection::vec(-1_000_000i64..=1_000_000, 0..32),
2267        ) {
2268            let quantities = values.iter().map(|v| Decimal::new(*v, 3)).collect::<Vec<_>>();
2269            let (net, long, short) = position_qty_aggregates(quantities.iter().copied());
2270            let reversed = position_qty_aggregates(quantities.iter().map(|v| -*v));
2271            let expected_net = Decimal::new(values.iter().sum(), 3);
2272
2273            prop_assert_eq!(net, expected_net);
2274            prop_assert_eq!(net, long - short);
2275            prop_assert!(long >= Decimal::ZERO);
2276            prop_assert!(short >= Decimal::ZERO);
2277            prop_assert_eq!(reversed, (-net, short, long));
2278        }
2279    }
2280
2281    #[rstest]
2282    fn test_distinct_position_reports_removes_non_adjacent_duplicates() {
2283        let report = |side: PositionSide, quantity: &str, venue_position_id: &str, ts_init: u64| {
2284            PositionStatusReport::new(
2285                AccountId::from("BINANCE-001"),
2286                InstrumentId::from("ETHUSDT-PERP.BINANCE"),
2287                side,
2288                Quantity::from(quantity),
2289                UnixNanos::from(1_000),
2290                UnixNanos::from(ts_init),
2291                None,
2292                Some(PositionId::from(venue_position_id)),
2293                Some(dec!(3000)),
2294            )
2295        };
2296
2297        let long = report(PositionSide::Long, "2.0", "P-LONG", 2_000);
2298        let short = report(PositionSide::Short, "3.0", "P-SHORT", 2_001);
2299        let long_duplicate = report(PositionSide::Long, "2.0", "P-LONG", 2_002);
2300        let short_duplicate = report(PositionSide::Short, "3.0", "P-SHORT", 2_003);
2301
2302        let result = distinct_position_reports(vec![
2303            long.clone(),
2304            short.clone(),
2305            long_duplicate,
2306            short_duplicate,
2307        ]);
2308
2309        assert_eq!(result, vec![long, short]);
2310    }
2311
2312    #[rstest]
2313    fn test_sort_reconciliation_events_accepts_before_earlier_fills() {
2314        let first = market_order("O-FIRST", OrderSide::Buy);
2315        let second = market_order("O-SECOND", OrderSide::Sell);
2316        let mut events = vec![
2317            accepted_at(&second, "V-SECOND", 900),
2318            filled_at(&second, "V-SECOND", "T-SECOND", 200),
2319            accepted_at(&first, "V-FIRST", 900),
2320            filled_at(&first, "V-FIRST", "T-FIRST", 100),
2321            canceled_at(&first, "V-FIRST", 950),
2322        ];
2323
2324        sort_reconciliation_events(&mut events);
2325
2326        assert_eq!(
2327            event_sequence(&events),
2328            vec![
2329                "O-FIRST V-FIRST accepted",
2330                "O-FIRST V-FIRST filled",
2331                "O-SECOND V-SECOND accepted",
2332                "O-SECOND V-SECOND filled",
2333                "O-FIRST V-FIRST canceled",
2334            ]
2335        );
2336    }
2337
2338    #[rstest]
2339    fn test_sort_reconciliation_events_keeps_other_venue_order_fill_times() {
2340        let order = market_order("O-REPLACED", OrderSide::Buy);
2341        let mut events = vec![
2342            accepted_at(&order, "V-NEW", 900),
2343            filled_at(&order, "V-NEW", "T-NEW", 950),
2344            filled_at(&order, "V-OLD", "T-OLD", 100),
2345        ];
2346
2347        sort_reconciliation_events(&mut events);
2348
2349        assert_eq!(
2350            event_sequence(&events),
2351            vec![
2352                "O-REPLACED V-OLD filled",
2353                "O-REPLACED V-NEW accepted",
2354                "O-REPLACED V-NEW filled",
2355            ]
2356        );
2357    }
2358
2359    #[rstest]
2360    fn test_sort_reconciliation_events_keeps_fills_after_earlier_terminal_time() {
2361        let canceled_order = market_order("O-CANCELED", OrderSide::Buy);
2362        let filled_order = market_order("O-FILLED", OrderSide::Sell);
2363        let mut events = vec![
2364            accepted_at(&canceled_order, "V-CANCELED", 100),
2365            filled_at(&canceled_order, "V-CANCELED", "T-CANCELED", 500),
2366            canceled_at(&canceled_order, "V-CANCELED", 100),
2367            accepted_at(&filled_order, "V-FILLED", 200),
2368            filled_at(&filled_order, "V-FILLED", "T-FILLED", 300),
2369        ];
2370
2371        sort_reconciliation_events(&mut events);
2372
2373        assert_eq!(
2374            event_sequence(&events),
2375            vec![
2376                "O-CANCELED V-CANCELED accepted",
2377                "O-CANCELED V-CANCELED canceled",
2378                "O-FILLED V-FILLED accepted",
2379                "O-FILLED V-FILLED filled",
2380                "O-CANCELED V-CANCELED filled",
2381            ]
2382        );
2383    }
2384
2385    fn market_order(client_order_id: &str, side: OrderSide) -> OrderAny {
2386        OrderTestBuilder::new(OrderType::Market)
2387            .instrument_id(crypto_perpetual_ethusdt().id())
2388            .client_order_id(ClientOrderId::from(client_order_id))
2389            .side(side)
2390            .quantity(Quantity::from("1.000"))
2391            .build()
2392    }
2393
2394    fn accepted_at(order: &OrderAny, venue_order_id: &str, ts: u64) -> OrderEventAny {
2395        let mut event = TestOrderEventStubs::accepted(
2396            order,
2397            AccountId::from("SIM-001"),
2398            VenueOrderId::from(venue_order_id),
2399        );
2400
2401        if let OrderEventAny::Accepted(accepted) = &mut event {
2402            accepted.ts_event = UnixNanos::from(ts);
2403        }
2404
2405        event
2406    }
2407
2408    fn filled_at(order: &OrderAny, venue_order_id: &str, trade_id: &str, ts: u64) -> OrderEventAny {
2409        let instrument = InstrumentAny::CryptoPerpetual(crypto_perpetual_ethusdt());
2410        let mut event = TestOrderEventStubs::filled(
2411            order,
2412            &instrument,
2413            Some(TradeId::from(trade_id)),
2414            None,
2415            Some(Price::from("100.00")),
2416            Some(Quantity::from("1.000")),
2417            None,
2418            None,
2419            Some(UnixNanos::from(ts)),
2420            Some(AccountId::from("SIM-001")),
2421        );
2422
2423        if let OrderEventAny::Filled(filled) = &mut event {
2424            filled.venue_order_id = VenueOrderId::from(venue_order_id);
2425        }
2426
2427        event
2428    }
2429
2430    fn canceled_at(order: &OrderAny, venue_order_id: &str, ts: u64) -> OrderEventAny {
2431        let mut event = TestOrderEventStubs::canceled(
2432            order,
2433            AccountId::from("SIM-001"),
2434            Some(VenueOrderId::from(venue_order_id)),
2435        );
2436
2437        if let OrderEventAny::Canceled(canceled) = &mut event {
2438            canceled.ts_event = UnixNanos::from(ts);
2439        }
2440
2441        event
2442    }
2443
2444    fn event_sequence(events: &[OrderEventAny]) -> Vec<String> {
2445        events
2446            .iter()
2447            .map(|event| {
2448                let kind = match event {
2449                    OrderEventAny::Accepted(_) => "accepted",
2450                    OrderEventAny::Filled(_) => "filled",
2451                    OrderEventAny::Canceled(_) => "canceled",
2452                    _ => "other",
2453                };
2454                let venue_order_id = event
2455                    .venue_order_id()
2456                    .expect("test events carry a venue order ID");
2457
2458                format!("{} {venue_order_id} {kind}", event.client_order_id())
2459            })
2460            .collect()
2461    }
2462}