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