Skip to main content

qx_execution/
lib.rs

1//! 统一执行层边界。
2//!
3//! Venue 只返回 `VenueEvent`,执行层负责把这些事件转换成运行时标准事实,
4//! 再通过本 crate `application` 子模块的执行端口交给 EventLog、订单状态和 Ledger。Paper、
5//! Binance 以及未来连接器都必须复用这里的事实转换,不能在 CLI 中各写一套。
6//! 本 crate 不依赖任何具体运行时或存储后端。
7
8pub mod algo_execution;
9pub mod application;
10mod spread_group_barrier;
11pub use algo_execution::{
12    AlgoExecutionState, AlgoExecutionStatus, AlgoExecutionStep, AlgoParentOrder,
13    ALGO_EXECUTION_STATE_SCHEMA_VERSION,
14};
15pub use application::*;
16use qx_control::{cancel_order_target_from_command, order_from_submit_command, ControlCommand};
17use qx_core::{DecimalRounding, ExactDecimal, FeeModel};
18use qx_guanxing::QuoteTick;
19use qx_risk::OrderRiskPosition;
20pub use qx_zhenlu::algo::{
21    plan_twap, plan_vwap, AlgoChildSlice, AlgoExecutionError, VwapVolumeBucket, MAX_ALGO_CHILDREN,
22};
23use qx_zhenlu::{
24    OrderGroupStore, PaperVenue, RiskContext, SpreadOrderGroup, SpreadOrderGroupStatus,
25    SpreadOrderGroupStore, Venue, VenueEvent,
26};
27
28pub fn spread_group_barrier(
29    store: Option<&dyn SpreadOrderGroupStore>,
30    command: &ControlCommand,
31) -> Result<(), String> {
32    spread_group_barrier::check_spread_group_barrier(store, command)
33}
34
35pub struct RiskExecutionContext<'a> {
36    pub risk: &'a RiskContext,
37    pub position: &'a OrderRiskPosition,
38}
39
40/// Required inputs for the shared order submission boundary. The group store stays
41/// explicit so a caller cannot accidentally bypass the multi-leg barrier.
42pub struct SubmitOrderWithRiskRequest<'a, V: Venue, P: ExecutionEventPort> {
43    pub command: &'a ControlCommand,
44    pub venue: &'a mut V,
45    pub pipeline: &'a mut P,
46    pub worker_id: &'a str,
47    pub now: u64,
48    pub source_seq: &'a mut u64,
49    pub context: &'a RiskExecutionContext<'a>,
50    pub spread_store: Option<&'a dyn SpreadOrderGroupStore>,
51}
52
53/// Required Paper execution inputs. Every safety and pricing decision is a named,
54/// mandatory field; this type intentionally has no `Default` implementation.
55pub struct PaperSubmitRequest<'a, P: ExecutionEventPort + application::LedgerProbe> {
56    pub command: &'a ControlCommand,
57    pub pipeline: &'a mut P,
58    pub now: u64,
59    pub risk: Option<RiskContext>,
60    pub position: Option<OrderRiskPosition>,
61    pub market_quote: Option<QuoteTick>,
62    pub fee_model: Box<dyn FeeModel + Send>,
63    pub allow_synthetic_quote: bool,
64    pub spread_store: Option<&'a dyn SpreadOrderGroupStore>,
65}
66
67/// 把当前账户快照适配为应用层 RiskPort,便于回测、Paper 和实盘执行器
68/// 替换风控实现而不改动 `ExecutionGateway` 的订单副作用边界。
69pub struct RiskContextPort<'a> {
70    pub risk: &'a RiskContext,
71    pub position: &'a OrderRiskPosition,
72}
73
74/// 直接适配 `qx-risk::OrderRiskContext` 的应用层端口。
75///
76/// `RiskContextPort` 保留 qx-zhenlu 的兼容快照入口;新执行器可以直接注入
77/// canonical context,避免回测、Paper 和实盘再各自复制一份规格/保证金/
78/// 投影持仓转换逻辑。
79pub struct CanonicalRiskPort<'a> {
80    pub context: &'a qx_risk::OrderRiskContext,
81}
82
83/// 将现有 Venue 事实适配为应用层 VenuePort。它只做事实类型转换,不写
84/// EventLog/OMS;真正的副作用仍由 `ExecutionGateway`(`PortExecutionService`)统一编排。
85pub struct VenuePortAdapter<V: Venue> {
86    venue: V,
87    accept_any_venue: bool,
88}
89
90/// 把仍使用旧版 `Venue` trait 的连接器借用到统一 `VenuePort`,使只持有可变
91/// 借用的执行入口(Paper worker、多腿编排)也走同一个 `ExecutionGateway`。
92pub struct BorrowedVenuePort<'a, V: Venue + ?Sized> {
93    venue: &'a mut V,
94    accept_any_venue: bool,
95}
96
97impl<'a, V: Venue + ?Sized> BorrowedVenuePort<'a, V> {
98    pub fn new(venue: &'a mut V) -> Self {
99        Self {
100            venue,
101            accept_any_venue: false,
102        }
103    }
104
105    pub fn new_for_any_venue(venue: &'a mut V) -> Self {
106        Self {
107            venue,
108            accept_any_venue: true,
109        }
110    }
111}
112
113impl<V: Venue> VenuePortAdapter<V> {
114    pub fn new(venue: V) -> Self {
115        Self {
116            venue,
117            accept_any_venue: false,
118        }
119    }
120
121    /// Paper/模拟路由可以把多个底层 Instrument Venue 映射到同一个虚拟
122    /// Venue;实盘适配器必须继续使用 `new`,保持严格路由校验。
123    pub fn new_for_any_venue(venue: V) -> Self {
124        Self {
125            venue,
126            accept_any_venue: true,
127        }
128    }
129
130    pub fn into_inner(self) -> V {
131        self.venue
132    }
133
134    pub fn venue(&self) -> &V {
135        &self.venue
136    }
137}
138
139fn venue_events_to_application(events: Vec<VenueEvent>) -> Vec<ExecutionEvent> {
140    events
141        .into_iter()
142        .map(|event| match event {
143            VenueEvent::Accepted {
144                client_order_id,
145                venue_order_id,
146                ..
147            } => ExecutionEvent::Accepted {
148                client_order_id,
149                venue_order_id,
150            },
151            VenueEvent::Rejected {
152                client_order_id,
153                reason,
154                ..
155            } => ExecutionEvent::Rejected {
156                client_order_id,
157                reason,
158            },
159            VenueEvent::Fill(fill) => ExecutionEvent::Fill(fill),
160            VenueEvent::FeeAdjustment {
161                account_id,
162                venue_id,
163                order_id,
164                instrument,
165                fees,
166                ..
167            } => ExecutionEvent::FeeAdjustment {
168                account_id,
169                venue_id,
170                order_id,
171                instrument,
172                fees,
173            },
174            VenueEvent::Cancelled {
175                client_order_id, ..
176            } => ExecutionEvent::Cancelled { client_order_id },
177        })
178        .collect()
179}
180
181fn venue_group_submission_to_application(
182    submission: qx_zhenlu::VenueOrderGroupSubmission,
183) -> OrderGroupSubmission {
184    OrderGroupSubmission {
185        venue_group_id: submission.venue_group_id,
186        group_status: submission.group_status,
187        events: venue_events_to_application(submission.events),
188    }
189}
190
191impl<V: Venue> VenuePort for VenuePortAdapter<V> {
192    fn venue_id(&self) -> &str {
193        self.venue.id()
194    }
195
196    fn capabilities(&self) -> qx_zhenlu::venue_capabilities::VenueCapabilities {
197        *self.venue.capabilities()
198    }
199
200    fn execution_readiness(&self) -> Result<(), String> {
201        self.venue
202            .execution_readiness()
203            .map_err(|error| format!("Venue {} 尚未就绪: {error:?}", self.venue_id()))
204    }
205
206    fn validate_submit_order_group(
207        &mut self,
208        group: &qx_core::OrderGroupState,
209    ) -> Result<(), String> {
210        self.venue
211            .validate_order_group(group)
212            .map_err(|error| format!("Venue 订单组预检失败: {error:?}"))
213    }
214
215    fn submit_order_group(
216        &mut self,
217        group: &qx_core::OrderGroupState,
218        ts: u64,
219    ) -> Result<OrderGroupSubmission, String> {
220        self.venue
221            .submit_order_group(group, ts)
222            .map(venue_group_submission_to_application)
223            .map_err(|error| format!("Venue 订单组提交结果未知: {error:?}"))
224    }
225
226    fn submit_order(
227        &mut self,
228        order: qx_core::Order,
229        ts: u64,
230    ) -> Result<Vec<ExecutionEvent>, String> {
231        self.validate_submit_capabilities(&order)?;
232        self.venue
233            .submit(order, ts)
234            .map(venue_events_to_application)
235            .map_err(|error| format!("Venue submit 失败: {error:?}"))
236    }
237
238    fn cancel_order(
239        &mut self,
240        client_order_id: u64,
241        ts: u64,
242    ) -> Result<Vec<ExecutionEvent>, String> {
243        self.capabilities().validate_cancel()?;
244        self.venue
245            .cancel(client_order_id, ts)
246            .map(venue_events_to_application)
247            .map_err(|error| format!("Venue cancel 失败: {error:?}"))
248    }
249
250    fn validate_amend_order(
251        &mut self,
252        current: &qx_core::Order,
253        amended: &qx_core::Order,
254    ) -> Result<(), String> {
255        self.venue
256            .validate_amendment(current, amended)
257            .map_err(|error| format!("Venue amend preflight 失败: {error:?}"))
258    }
259
260    fn amend_order(
261        &mut self,
262        current: &qx_core::Order,
263        amended: &qx_core::Order,
264        ts: u64,
265    ) -> Result<Vec<ExecutionEvent>, String> {
266        self.venue
267            .amend(current, amended, ts)
268            .map(venue_events_to_application)
269            .map_err(|error| format!("Venue amend 结果未知: {error:?}"))
270    }
271}
272
273impl<V: Venue + ?Sized> VenuePort for BorrowedVenuePort<'_, V> {
274    fn venue_id(&self) -> &str {
275        self.venue.id()
276    }
277
278    fn capabilities(&self) -> qx_zhenlu::venue_capabilities::VenueCapabilities {
279        *self.venue.capabilities()
280    }
281
282    fn execution_readiness(&self) -> Result<(), String> {
283        self.venue
284            .execution_readiness()
285            .map_err(|error| format!("Venue {} 尚未就绪: {error:?}", self.venue_id()))
286    }
287
288    fn validate_submit_order_group(
289        &mut self,
290        group: &qx_core::OrderGroupState,
291    ) -> Result<(), String> {
292        self.venue
293            .validate_order_group(group)
294            .map_err(|error| format!("Venue 订单组预检失败: {error:?}"))
295    }
296
297    fn submit_order_group(
298        &mut self,
299        group: &qx_core::OrderGroupState,
300        ts: u64,
301    ) -> Result<OrderGroupSubmission, String> {
302        self.venue
303            .submit_order_group(group, ts)
304            .map(venue_group_submission_to_application)
305            .map_err(|error| format!("Venue 订单组提交结果未知: {error:?}"))
306    }
307
308    fn submit_order(
309        &mut self,
310        order: qx_core::Order,
311        ts: u64,
312    ) -> Result<Vec<ExecutionEvent>, String> {
313        self.validate_submit_capabilities(&order)?;
314        self.venue
315            .submit(order, ts)
316            .map(venue_events_to_application)
317            .map_err(|error| format!("Venue submit 失败: {error:?}"))
318    }
319
320    fn cancel_order(
321        &mut self,
322        client_order_id: u64,
323        ts: u64,
324    ) -> Result<Vec<ExecutionEvent>, String> {
325        self.capabilities().validate_cancel()?;
326        self.venue
327            .cancel(client_order_id, ts)
328            .map(venue_events_to_application)
329            .map_err(|error| format!("Venue cancel 失败: {error:?}"))
330    }
331
332    fn validate_amend_order(
333        &mut self,
334        current: &qx_core::Order,
335        amended: &qx_core::Order,
336    ) -> Result<(), String> {
337        self.venue
338            .validate_amendment(current, amended)
339            .map_err(|error| format!("Venue amend preflight 失败: {error:?}"))
340    }
341
342    fn amend_order(
343        &mut self,
344        current: &qx_core::Order,
345        amended: &qx_core::Order,
346        ts: u64,
347    ) -> Result<Vec<ExecutionEvent>, String> {
348        self.venue
349            .amend(current, amended, ts)
350            .map(venue_events_to_application)
351            .map_err(|error| format!("Venue amend 结果未知: {error:?}"))
352    }
353}
354
355impl<V: Venue + ?Sized> VenueRouterPort for BorrowedVenuePort<'_, V> {
356    fn capabilities_for(
357        &self,
358        venue_id: &str,
359    ) -> Option<qx_zhenlu::venue_capabilities::VenueCapabilities> {
360        (self.accept_any_venue
361            || venue_id.trim().is_empty()
362            || venue_id.eq_ignore_ascii_case(self.venue_id()))
363        .then(|| self.capabilities())
364    }
365
366    fn execution_readiness_for(&self, venue_id: &str) -> Result<(), String> {
367        if self.accept_any_venue
368            || venue_id.trim().is_empty()
369            || venue_id.eq_ignore_ascii_case(self.venue_id())
370        {
371            VenuePort::execution_readiness(self)
372        } else {
373            Err(format!(
374                "Venue readiness 路由不匹配: requested={venue_id} configured={}",
375                self.venue_id()
376            ))
377        }
378    }
379
380    fn submit_order(
381        &mut self,
382        venue_id: &str,
383        order: qx_core::Order,
384        ts: u64,
385    ) -> Result<Vec<ExecutionEvent>, String> {
386        if self.accept_any_venue
387            || venue_id.trim().is_empty()
388            || venue_id.eq_ignore_ascii_case(self.venue_id())
389        {
390            VenuePort::submit_order(self, order, ts)
391        } else {
392            Err(format!(
393                "Venue 路由不匹配: requested={venue_id} configured={}",
394                self.venue_id()
395            ))
396        }
397    }
398
399    fn cancel_order(
400        &mut self,
401        venue_id: &str,
402        client_order_id: u64,
403        ts: u64,
404    ) -> Result<Vec<ExecutionEvent>, String> {
405        if self.accept_any_venue
406            || venue_id.trim().is_empty()
407            || venue_id.eq_ignore_ascii_case(self.venue_id())
408        {
409            VenuePort::cancel_order(self, client_order_id, ts)
410        } else {
411            Err(format!(
412                "Venue 路由不匹配: requested={venue_id} configured={}",
413                self.venue_id()
414            ))
415        }
416    }
417}
418
419impl<V: Venue> VenueRouterPort for VenuePortAdapter<V> {
420    fn capabilities_for(
421        &self,
422        venue_id: &str,
423    ) -> Option<qx_zhenlu::venue_capabilities::VenueCapabilities> {
424        (self.accept_any_venue
425            || venue_id.trim().is_empty()
426            || venue_id.eq_ignore_ascii_case(self.venue_id()))
427        .then(|| self.capabilities())
428    }
429
430    fn execution_readiness_for(&self, venue_id: &str) -> Result<(), String> {
431        if self.accept_any_venue
432            || venue_id.trim().is_empty()
433            || venue_id.eq_ignore_ascii_case(self.venue_id())
434        {
435            VenuePort::execution_readiness(self)
436        } else {
437            Err(format!(
438                "Venue readiness 路由不匹配: requested={venue_id} configured={}",
439                self.venue_id()
440            ))
441        }
442    }
443
444    fn submit_order(
445        &mut self,
446        venue_id: &str,
447        order: qx_core::Order,
448        ts: u64,
449    ) -> Result<Vec<ExecutionEvent>, String> {
450        if self.accept_any_venue
451            || venue_id.trim().is_empty()
452            || venue_id.eq_ignore_ascii_case(self.venue_id())
453        {
454            VenuePort::submit_order(self, order, ts)
455        } else {
456            Err(format!(
457                "Venue 路由不匹配: requested={venue_id} configured={}",
458                self.venue_id()
459            ))
460        }
461    }
462
463    fn cancel_order(
464        &mut self,
465        venue_id: &str,
466        client_order_id: u64,
467        ts: u64,
468    ) -> Result<Vec<ExecutionEvent>, String> {
469        if self.accept_any_venue
470            || venue_id.trim().is_empty()
471            || venue_id.eq_ignore_ascii_case(self.venue_id())
472        {
473            VenuePort::cancel_order(self, client_order_id, ts)
474        } else {
475            Err(format!(
476                "Venue 路由不匹配: requested={venue_id} configured={}",
477                self.venue_id()
478            ))
479        }
480    }
481}
482
483impl RiskPort for RiskContextPort<'_> {
484    fn evaluate_order(&self, order: &qx_core::Order) -> Result<RiskVerdict, String> {
485        let decision = self.risk.evaluate_order(order, self.position);
486        if decision.allowed {
487            Ok(RiskVerdict::Allow)
488        } else {
489            Ok(RiskVerdict::Reject {
490                reason: format!(
491                    "RiskContext {}: {}",
492                    decision.rule_set_version,
493                    decision.violations.join("; ")
494                ),
495            })
496        }
497    }
498}
499
500impl RiskPort for CanonicalRiskPort<'_> {
501    fn evaluate_order(&self, order: &qx_core::Order) -> Result<RiskVerdict, String> {
502        let decision = qx_risk::RiskEngine::evaluate_order(self.context, order);
503        if decision.allowed {
504            Ok(RiskVerdict::Allow)
505        } else {
506            Ok(RiskVerdict::Reject {
507                reason: format!(
508                    "CanonicalRiskEngine {}: {}",
509                    decision.rule_set_version,
510                    decision.violations.join("; ")
511                ),
512            })
513        }
514    }
515}
516
517/// 完全基于 Application Ports 的单腿执行器。
518///
519/// 这是回测、Paper、CCXT 及未来券商适配器共用的最小副作用边界:订单先
520/// 注册到 `OrderStore`,再调用 `VenuePort`,最后把标准执行事实写入
521/// `ExecutionEventPort`。它不依赖 `LiveEventPipeline` 或 `Venue`,便于在
522/// 不同运行时、进程和语言绑定中复用同一套未知结果保护。
523pub struct PortExecutionService<'a, V: VenuePort, P: ExecutionEventPort> {
524    venue: &'a mut V,
525    events: &'a mut P,
526    worker_id: &'a str,
527    now: u64,
528    source_seq: &'a mut u64,
529    registration_correlation: Option<String>,
530    cancel_operation_id: Option<String>,
531    instrument_spec: Option<TradingInstrumentSpec>,
532    spread_store: Option<&'a dyn SpreadOrderGroupStore>,
533    order_group_store: Option<&'a mut dyn OrderGroupStore>,
534    submission_group_id: Option<String>,
535}
536
537#[derive(Clone, Debug, PartialEq, Eq)]
538pub struct PortExecutionResult {
539    pub message: String,
540    pub event_count: usize,
541}
542
543/// 统一执行网关名称。新运行时、Paper、回测和语言绑定应依赖这个端口化
544/// 入口;保留 `PortExecutionService` 作为兼容的具体类型名,避免已有适配器
545/// 在迁移期间被迫同时修改。
546pub type ExecutionGateway<'a, V, P> = PortExecutionService<'a, V, P>;
547
548impl<'a, V: VenuePort, P: ExecutionEventPort> PortExecutionService<'a, V, P> {
549    pub fn new(
550        venue: &'a mut V,
551        events: &'a mut P,
552        worker_id: &'a str,
553        now: u64,
554        source_seq: &'a mut u64,
555    ) -> Self {
556        Self {
557            venue,
558            events,
559            worker_id,
560            now,
561            source_seq,
562            registration_correlation: None,
563            cancel_operation_id: None,
564            instrument_spec: None,
565            spread_store: None,
566            order_group_store: None,
567            submission_group_id: None,
568        }
569    }
570
571    /// 绑定多腿订单组快照存储:只有注入组存储的提交路径才可能提交带
572    /// `spread_group_id` 的腿,其余路径对这类命令一律 fail-closed(见
573    /// [`spread_group_barrier`])。屏障判定住在网关而不是 CLI,是为了让任何
574    /// 绕过 CLI 的调用方(回测、语言绑定、未来执行器)也无法跳过它。
575    pub fn with_spread_group_store(mut self, store: &'a dyn SpreadOrderGroupStore) -> Self {
576        self.spread_store = Some(store);
577        self
578    }
579
580    pub fn with_order_group_store(mut self, store: &'a mut dyn OrderGroupStore) -> Self {
581        self.order_group_store = Some(store);
582        self
583    }
584
585    pub fn with_instrument_spec(mut self, spec: TradingInstrumentSpec) -> Self {
586        self.instrument_spec = Some(spec);
587        self
588    }
589
590    /// 统一的控制命令提交入口。命令解析、订单校验、风险(如调用方继续使用
591    /// `submit_with_risk`)和 Venue 副作用均在同一个端口化服务中完成。
592    pub fn submit_command(
593        &mut self,
594        command: &ControlCommand,
595    ) -> Result<PortExecutionResult, String> {
596        spread_group_barrier(self.spread_store, command)?;
597        let order = order_from_submit_command(command)
598            .map_err(|error| format!("SubmitOrder 订单载荷非法: {error:?}"))?;
599        self.registration_correlation = Some(format!("control:{}", command.command_id));
600        self.submission_group_id = command.payload.get("spread_group_id").cloned();
601        let result = self.submit(order);
602        self.registration_correlation = None;
603        self.submission_group_id = None;
604        result
605    }
606
607    pub fn submit_command_with_risk<R: RiskPort>(
608        &mut self,
609        command: &ControlCommand,
610        risk: &R,
611    ) -> Result<PortExecutionResult, String> {
612        spread_group_barrier(self.spread_store, command)?;
613        let order = order_from_submit_command(command)
614            .map_err(|error| format!("SubmitOrder 订单载荷非法: {error:?}"))?;
615        self.registration_correlation = Some(format!("control:{}", command.command_id));
616        self.submission_group_id = command.payload.get("spread_group_id").cloned();
617        let result = self.submit_with_risk(order, risk);
618        self.registration_correlation = None;
619        self.submission_group_id = None;
620        result
621    }
622
623    pub fn submit(&mut self, order: qx_core::Order) -> Result<PortExecutionResult, String> {
624        self.validate_order(&order)?;
625        if self.events.orders().iter().any(|existing| {
626            existing.account_id == order.account_id
627                && self.events.has_pending_amendment(existing.client_id)
628        }) {
629            return Err("账户存在改单结果未知的订单,必须先对账,禁止新增订单".into());
630        }
631        self.venue.validate_submit_capabilities(&order)?;
632        let existing_order = self
633            .events
634            .orders()
635            .into_iter()
636            .find(|existing| existing.client_id == order.client_id);
637        if let Some(existing) = existing_order.as_ref() {
638            if !existing.same_submission_identity(&order) {
639                return Err(format!(
640                    "client_order_id {} 已绑定到不同的账户、标的、方向、数量或执行策略,拒绝复用",
641                    order.client_id
642                ));
643            }
644            if existing.status.is_terminal()
645                || matches!(
646                    existing.status,
647                    qx_core::OrderStatus::Accepted
648                        | qx_core::OrderStatus::Working
649                        | qx_core::OrderStatus::PartiallyFilled
650                        | qx_core::OrderStatus::Filled
651                )
652            {
653                return Ok(PortExecutionResult {
654                    message: format!(
655                        "ALREADY_APPLIED_FROM_EVENT_LOG status={:?}",
656                        existing.status
657                    ),
658                    event_count: 0,
659                });
660            }
661            // `CancelPending` 必须和 `Submitted`/`Unknown` 同一档:状态迁移表里
662            // `CancelPending` 只能走到 `Cancelled`/`Filled`/`Unknown`,`Submitted` 非法,
663            // 所以对一条撤单在途的订单补发 `venue.submit_order` 只会用同一个
664            // `client_order_id` 再下一单,不是"重试"。
665            // 正式的 LiveEventPipeline 会在网络副作用前把新订单持久化为 Submitted。
666            // 其它 OrderStore 可能仍保留 PendingSubmit;该状态同样不能证明远端未收到,
667            // 因而已有 PendingSubmit/Submitted 都必须先对账,不能把重试当作恢复。
668            if matches!(
669                existing.status,
670                qx_core::OrderStatus::Submitted
671                    | qx_core::OrderStatus::PendingSubmit
672                    | qx_core::OrderStatus::CancelPending
673                    | qx_core::OrderStatus::Unknown
674            ) {
675                self.append(
676                    ExecutionEvent::ReconcileRequired {
677                        client_order_id: existing.client_id,
678                    },
679                    format!("{}:ambiguous-submit:{}", self.worker_id, existing.client_id),
680                )?;
681                return Err(format!(
682                    "订单 {} 状态为 {:?},先决条件不满足:已有远端事实但未确认,或撤单在途,必须先对账,禁止自动补单",
683                    existing.client_id, existing.status
684                ));
685            }
686        }
687        if existing_order.is_none() {
688            // A known disconnected/snapshotting venue is a safe local refusal. Check it before
689            // creating a PendingSubmit record so callers can retry after the connector recovers.
690            self.venue.execution_readiness()?;
691            if let Some(group_id) = self.submission_group_id.as_deref() {
692                let store = self.spread_store.ok_or_else(|| {
693                    format!(
694                        "FAIL_CLOSED: 多腿订单组 {group_id} 未绑定组状态存储,拒绝提交订单 {}",
695                        order.client_id
696                    )
697                })?;
698                store.begin_leg_submission(group_id, order.client_id)?;
699            }
700            self.events.register_order(
701                order.clone(),
702                self.now,
703                Some(
704                    self.registration_correlation.clone().unwrap_or_else(|| {
705                        format!("{}:submit:{}", self.worker_id, order.client_id)
706                    }),
707                ),
708            )?;
709        }
710
711        let registered = self
712            .events
713            .orders()
714            .into_iter()
715            .find(|existing| existing.client_id == order.client_id)
716            .ok_or_else(|| "订单注册后无法读取订单".to_string())?;
717        let facts = match self.venue.submit_order(registered, self.now) {
718            Ok(facts) if facts.is_empty() => {
719                self.mark_reconcile(order.client_id, "empty-venue-response")?;
720                return Err("Venue 未返回任何订单事实,结果未知,必须先对账".into());
721            }
722            Ok(facts) => facts,
723            Err(error) => {
724                self.mark_reconcile(order.client_id, "submit-error")?;
725                return Err(format!(
726                    "Venue submit 失败/结果未知: {error};订单已标记为待对账"
727                ));
728            }
729        };
730        // 提交同步回包与用户流回报必须过同一道闸门(形状契约 + 产品规格精度),
731        // 否则"越界回报只能转待对账"就只剩半条纪律:同一笔成交走被推下来的路径
732        // 会被拦下、不记账,走提交回包却直接入账。
733        if let Err(violation) = gate_submit_facts(&order, &facts, self.instrument_spec.as_ref()) {
734            self.mark_reconcile(order.client_id, violation.reason_tag())?;
735            return Err(violation.to_string());
736        }
737        let event_count = facts.len();
738        let has_reconcile = facts
739            .iter()
740            .any(|fact| matches!(fact, ExecutionEvent::ReconcileRequired { .. }));
741        // 关联号必须含客户单号 **且** 含回报自身身份:EventLog 以
742        // `correlation_id:source_seq` 去重,而每条命令都从 0 重新计数,只用
743        // `(worker, venue)` 会让后一笔订单的 Accepted/ReconcileRequired 被判为
744        // 重放而静默丢弃;只用客户单号又会让同一订单的第二笔成交被吞掉。
745        let venue_prefix = match self
746            .registration_correlation
747            .as_deref()
748            .filter(|correlation_id| !correlation_id.trim().is_empty())
749        {
750            Some(correlation_id) => format!(
751                "{correlation_id}:venue:{}:{}",
752                self.venue.venue_id(),
753                order.client_id
754            ),
755            None => format!(
756                "{}:venue:{}:{}",
757                self.worker_id,
758                self.venue.venue_id(),
759                order.client_id
760            ),
761        };
762        for fact in facts {
763            let correlation_id = fact_correlation(&venue_prefix, &fact);
764            self.append(fact, correlation_id)?;
765        }
766        if has_reconcile {
767            return Err("Venue 返回待对账事实,禁止继续自动提交".into());
768        }
769        Ok(PortExecutionResult {
770            message: format!("SUBMITTED venue_events={event_count}"),
771            event_count,
772        })
773    }
774
775    /// 风控前置的统一提交入口。RiskPort 拒绝发生在订单登记、Venue 副作用和
776    /// EventLog 事实追加之前;因此拒单不会留下“已提交但未执行”的伪订单。两条通道
777    /// 不混用(V13 §9.12 #172):端口给出拒绝才播报「拒绝订单」并带违规清单,端口
778    /// 给不出裁决才播报「执行失败」。
779    pub fn submit_with_risk<R: RiskPort>(
780        &mut self,
781        order: qx_core::Order,
782        risk: &R,
783    ) -> Result<PortExecutionResult, String> {
784        self.validate_order(&order)?;
785        match risk
786            .evaluate_order(&order)
787            .map_err(|error| format!("账户级 RiskPort 执行失败: {error}"))?
788        {
789            RiskVerdict::Allow => {}
790            RiskVerdict::Reject { reason } => {
791                return Err(format!("账户级 RiskPort 拒绝订单: {reason}"))
792            }
793        }
794        self.submit(order)
795    }
796
797    /// Submit an OCO/Bracket exactly once through the shared execution boundary.
798    /// Each leg intent is registered before the single native group RPC; any
799    /// ambiguous outcome fences the group for reconciliation and is never retried.
800    pub fn submit_order_group<R: RiskPort>(
801        &mut self,
802        intent: qx_core::OrderGroupIntent,
803        risk: &R,
804    ) -> Result<PortExecutionResult, String> {
805        let group = qx_core::OrderGroupState::from_intent(intent)?;
806        self.venue.validate_submit_order_group(&group)?;
807        for leg in &group.legs {
808            self.validate_order(&leg.order)?;
809            match risk
810                .evaluate_order(&leg.order)
811                .map_err(|error| format!("订单组账户级风控执行失败: {error}"))?
812            {
813                RiskVerdict::Allow => {}
814                RiskVerdict::Reject { reason } => {
815                    return Err(format!(
816                        "订单组 {:?} 子腿 {} 被账户级风控拒绝: {reason}",
817                        leg.role, leg.order.client_id
818                    ));
819                }
820            }
821        }
822        self.venue.execution_readiness()?;
823        if self.order_group_store.is_none() {
824            return Err("FAIL_CLOSED: 原生订单组提交路径未注入订单组持久化存储".into());
825        }
826        let existing_orders = self.events.orders();
827        if let Some(existing) = group.legs.iter().find_map(|leg| {
828            existing_orders
829                .iter()
830                .find(|order| order.client_id == leg.order.client_id)
831        }) {
832            return Err(format!(
833                "订单组子腿 {} 已在 OMS 中,必须先恢复或对账,禁止重放组提交",
834                existing.client_id
835            ));
836        }
837        {
838            let store = self
839                .order_group_store
840                .as_deref_mut()
841                .ok_or_else(|| "订单组存储不可用".to_string())?;
842            store.create(&group)?;
843            if !store.begin_submission(&group.intent.group_id)? {
844                return Err(format!(
845                    "订单组 {} 已启动过提交或需对账,禁止重放 Venue 副作用",
846                    group.intent.group_id
847                ));
848            }
849        }
850        for leg in &group.legs {
851            if let Err(error) = self.events.register_order(
852                leg.order.clone(),
853                self.now,
854                Some(format!(
855                    "{}:group:{}:register:{}",
856                    self.worker_id, group.intent.group_id, leg.order.client_id
857                )),
858            ) {
859                if let Some(store) = self.order_group_store.as_deref_mut() {
860                    let _ = store.require_reconciliation(&group.intent.group_id);
861                }
862                return Err(format!(
863                    "订单组 {} 子腿 {} 注册失败,订单组已围栏待对账: {error}",
864                    group.intent.group_id, leg.order.client_id
865                ));
866            }
867        }
868        {
869            let orders = self.events.orders();
870            let store = self
871                .order_group_store
872                .as_deref_mut()
873                .ok_or_else(|| "订单组存储不可用".to_string())?;
874            for leg in &group.legs {
875                let snapshot = orders
876                    .iter()
877                    .find(|order| order.client_id == leg.order.client_id)
878                    .ok_or_else(|| {
879                        format!("已注册订单组子腿 {} 无法从 OMS 读取", leg.order.client_id)
880                    })?;
881                store.apply_order_snapshot(&group.intent.group_id, snapshot, None)?;
882            }
883        }
884
885        let submission = match self.venue.submit_order_group(&group, self.now) {
886            Ok(submission) => submission,
887            Err(error) => {
888                self.mark_group_reconcile(&group, "group-submit-unknown")?;
889                return Err(format!("Venue 订单组提交结果未知,已围栏待对账: {error}"));
890            }
891        };
892        if let Some(venue_group_id) = submission.venue_group_id {
893            let result = self
894                .order_group_store
895                .as_deref_mut()
896                .ok_or_else(|| "订单组存储不可用".to_string())?
897                .record_venue_group_id(&group.intent.group_id, venue_group_id);
898            if let Err(error) = result {
899                self.mark_group_reconcile(&group, "venue-group-id-conflict")?;
900                return Err(format!("交易所订单组 ID 无法持久化,已围栏待对账: {error}"));
901            }
902        }
903        let group_status = submission.group_status;
904        let facts = submission.events;
905        if let Some(group_status) = group_status {
906            if group_status == qx_core::OrderGroupStatus::Active && facts.is_empty() {
907                self.order_group_store
908                    .as_deref_mut()
909                    .ok_or_else(|| "订单组存储不可用".to_string())?
910                    .activate_native_group(&group.intent.group_id)?;
911                return Ok(PortExecutionResult {
912                    message: format!(
913                        "ORDER_GROUP_ACTIVE group_id={} venue_resource=accepted_without_child_orders",
914                        group.intent.group_id
915                    ),
916                    event_count: 0,
917                });
918            }
919            self.mark_group_reconcile(&group, "native-group-state-requires-reconcile")?;
920            return Err(format!(
921                "Venue 原生订单组状态 {:?} 尚不能安全归约到子订单,已围栏待对账",
922                group_status
923            ));
924        }
925        let mut per_leg = Vec::with_capacity(group.legs.len());
926        for leg in &group.legs {
927            let leg_facts: Vec<_> = facts
928                .iter()
929                .filter(|fact| execution_event_client_order_id(fact) == Some(leg.order.client_id))
930                .cloned()
931                .collect();
932            if let Err(error) = validate_submit_events(&leg.order, &leg_facts) {
933                self.mark_group_reconcile(&group, "invalid-group-facts")?;
934                return Err(format!(
935                    "Venue 订单组子腿 {} 回报无效,订单组已围栏待对账: {error}",
936                    leg.order.client_id
937                ));
938            }
939            if let Err(error) =
940                gate_submit_facts(&leg.order, &leg_facts, self.instrument_spec.as_ref())
941            {
942                self.mark_group_reconcile(&group, error.reason_tag())?;
943                return Err(error.to_string());
944            }
945            per_leg.push((leg.order.client_id, leg_facts));
946        }
947        if facts
948            .iter()
949            .any(|fact| execution_event_client_order_id(fact).is_none())
950        {
951            self.mark_group_reconcile(&group, "unattributed-group-fact")?;
952            return Err("Venue 订单组返回无法归属子腿的事实,已围栏待对账".into());
953        }
954
955        let event_count = facts.len();
956        let mut has_reconcile = false;
957        for (client_order_id, leg_facts) in per_leg {
958            let venue_prefix = format!(
959                "{}:venue:{}:{}:group:{}",
960                self.worker_id,
961                self.venue.venue_id(),
962                client_order_id,
963                group.intent.group_id
964            );
965            for fact in leg_facts {
966                has_reconcile |= matches!(fact, ExecutionEvent::ReconcileRequired { .. });
967                let correlation_id = fact_correlation(&venue_prefix, &fact);
968                self.append(fact, correlation_id)?;
969            }
970        }
971        let orders = self.events.orders();
972        {
973            let store = self
974                .order_group_store
975                .as_deref_mut()
976                .ok_or_else(|| "订单组存储不可用".to_string())?;
977            if has_reconcile {
978                store.require_reconciliation(&group.intent.group_id)?;
979            }
980            for leg in &group.legs {
981                let snapshot = orders
982                    .iter()
983                    .find(|order| order.client_id == leg.order.client_id)
984                    .ok_or_else(|| {
985                        format!("订单组子腿 {} 回报后无法从 OMS 读取", leg.order.client_id)
986                    })?;
987                let venue_order_id = facts.iter().find_map(|fact| match fact {
988                    ExecutionEvent::Accepted {
989                        client_order_id,
990                        venue_order_id,
991                    } if *client_order_id == leg.order.client_id => Some(venue_order_id.clone()),
992                    _ => None,
993                });
994                if has_reconcile {
995                    store.record_order_snapshot_during_reconciliation(
996                        &group.intent.group_id,
997                        snapshot,
998                        venue_order_id,
999                    )?;
1000                } else if store.load(&group.intent.group_id)?.is_some_and(|current| {
1001                    current.status == qx_core::OrderGroupStatus::ReconcileRequired
1002                }) {
1003                    // A complete response can transiently look unresolved while its legs are
1004                    // reduced one at a time (for example Rejected before peer Accepted).
1005                    // Reapply each known venue fact through the barrier-aware reducer so the
1006                    // final group state reflects the whole response instead of a leg-order race.
1007                    store.reconcile_order_snapshot(
1008                        &group.intent.group_id,
1009                        snapshot,
1010                        venue_order_id,
1011                    )?;
1012                } else {
1013                    store.apply_order_snapshot(&group.intent.group_id, snapshot, venue_order_id)?;
1014                }
1015            }
1016        }
1017        if has_reconcile {
1018            return Err("Venue 订单组回报要求对账,已禁止继续自动执行".into());
1019        }
1020        Ok(PortExecutionResult {
1021            message: format!(
1022                "ORDER_GROUP_SUBMITTED group_id={} venue_events={event_count}",
1023                group.intent.group_id
1024            ),
1025            event_count,
1026        })
1027    }
1028
1029    fn mark_group_reconcile(
1030        &mut self,
1031        group: &qx_core::OrderGroupState,
1032        reason: &str,
1033    ) -> Result<(), String> {
1034        for leg in &group.legs {
1035            self.mark_reconcile(leg.order.client_id, reason)?;
1036        }
1037        let orders = self.events.orders();
1038        let store = self
1039            .order_group_store
1040            .as_deref_mut()
1041            .ok_or_else(|| "订单组存储不可用".to_string())?;
1042        store.require_reconciliation(&group.intent.group_id)?;
1043        for leg in &group.legs {
1044            let snapshot = orders
1045                .iter()
1046                .find(|order| order.client_id == leg.order.client_id)
1047                .ok_or_else(|| {
1048                    format!("待对账订单组子腿 {} 无法从 OMS 读取", leg.order.client_id)
1049                })?;
1050            store.record_order_snapshot_during_reconciliation(
1051                &group.intent.group_id,
1052                snapshot,
1053                None,
1054            )?;
1055        }
1056        Ok(())
1057    }
1058
1059    /// Fail closed on frozen market-spec identity, lot size, minimum quantity,
1060    /// and price tick before risk registration or any venue side effect.
1061    pub fn validate_order(&self, order: &qx_core::Order) -> Result<(), String> {
1062        order
1063            .validate()
1064            .map_err(|error| format!("订单校验失败: {error}"))?;
1065        if let Some(spec) = &self.instrument_spec {
1066            if order.instrument != spec.instrument {
1067                return Err(format!(
1068                    "订单 market spec 标的与订单不匹配: order={} spec={}",
1069                    order.instrument, spec.instrument
1070                ));
1071            }
1072            if let Some(amounts) = order.exact_amounts {
1073                spec.validate_exact_order_precision(amounts.quantity, amounts.limit_price)
1074                    .map_err(|error| format!("精确订单不满足 market spec: {error}"))?;
1075            } else {
1076                spec.validate_order(order.qty.raw(), order.limit.map(|price| price.raw()))
1077                    .map_err(|error| format!("订单不满足 market spec: {error}"))?;
1078            }
1079        }
1080        Ok(())
1081    }
1082
1083    /// Submit with a stable caller correlation id. Algorithm children use
1084    /// `parent_id/child_index` so an event-log replay can identify the same
1085    /// child after restart without inventing a second execution path.
1086    pub fn submit_with_risk_and_correlation<R: RiskPort>(
1087        &mut self,
1088        order: qx_core::Order,
1089        risk: &R,
1090        correlation_id: impl Into<String>,
1091    ) -> Result<PortExecutionResult, String> {
1092        self.registration_correlation = Some(correlation_id.into());
1093        let result = self.submit_with_risk(order, risk);
1094        self.registration_correlation = None;
1095        result
1096    }
1097
1098    /// Read the authoritative OMS snapshot for a client order id.
1099    pub fn order(&self, client_order_id: u64) -> Option<qx_core::Order> {
1100        self.events
1101            .orders()
1102            .into_iter()
1103            .find(|order| order.client_id == client_order_id)
1104    }
1105
1106    pub fn cancel(&mut self, client_order_id: u64) -> Result<PortExecutionResult, String> {
1107        self.venue.capabilities().validate_cancel()?;
1108        if self.events.has_pending_amendment(client_order_id) {
1109            return Err(format!(
1110                "订单 {client_order_id} 存在改单结果未知的操作,必须先对账后才能撤单"
1111            ));
1112        }
1113        let order = self
1114            .order(client_order_id)
1115            .ok_or_else(|| format!("订单不存在: {client_order_id}"))?;
1116        match order.status {
1117            qx_core::OrderStatus::Cancelled => {
1118                return Ok(PortExecutionResult {
1119                    message: "ALREADY_CANCELLED".into(),
1120                    event_count: 0,
1121                });
1122            }
1123            qx_core::OrderStatus::Filled
1124            | qx_core::OrderStatus::Rejected
1125            | qx_core::OrderStatus::Expired => {
1126                return Err(format!(
1127                    "订单 {} 已处于终态 {:?},不能撤销",
1128                    client_order_id, order.status
1129                ));
1130            }
1131            qx_core::OrderStatus::PendingSubmit => {
1132                return Err(format!(
1133                    "订单 {} 尚未提交到交易所,不能撤销",
1134                    client_order_id
1135                ));
1136            }
1137            qx_core::OrderStatus::CancelPending => {
1138                return Err(format!("订单 {} 已有撤单在途,必须先对账", client_order_id));
1139            }
1140            qx_core::OrderStatus::Unknown => {
1141                return Err(format!(
1142                    "订单 {} 状态未知,必须先对账后才能撤单",
1143                    client_order_id
1144                ));
1145            }
1146            qx_core::OrderStatus::Submitted
1147            | qx_core::OrderStatus::Accepted
1148            | qx_core::OrderStatus::Working
1149            | qx_core::OrderStatus::PartiallyFilled => {}
1150        }
1151        self.venue.execution_readiness()?;
1152        let operation_id = self.cancel_operation_id.clone().unwrap_or_else(|| {
1153            format!("{}:cancel:{}:{}", self.worker_id, client_order_id, self.now)
1154        });
1155        let append_outcome = self.append_with_outcome(
1156            ExecutionEvent::CancelPending { client_order_id },
1157            format!("{operation_id}:pending:{client_order_id}"),
1158        )?;
1159        if append_outcome == EventAppendOutcome::Duplicate {
1160            return Err(format!(
1161                "订单 {} 的撤单意图已由同一操作持久化,禁止重复调用 Venue;必须先对账",
1162                client_order_id
1163            ));
1164        }
1165        let facts = match self.venue.cancel_order(client_order_id, self.now) {
1166            Ok(facts) if facts.is_empty() => {
1167                self.mark_reconcile_for_operation(
1168                    client_order_id,
1169                    "empty-cancel-response",
1170                    &operation_id,
1171                )?;
1172                return Err("Venue 未返回取消事实,结果未知,必须先对账".into());
1173            }
1174            Ok(facts) => facts,
1175            Err(error) => {
1176                self.mark_reconcile_for_operation(client_order_id, "cancel-error", &operation_id)?;
1177                return Err(format!(
1178                    "Venue cancel 失败/结果未知: {error};订单已标记为待对账"
1179                ));
1180            }
1181        };
1182        if let Err(error) = validate_cancel_events(client_order_id, &facts) {
1183            self.mark_reconcile_for_operation(
1184                client_order_id,
1185                "invalid-cancel-response",
1186                &operation_id,
1187            )?;
1188            return Err(format!(
1189                "Venue 返回非法撤单事实,结果未知,必须先对账: {error}"
1190            ));
1191        }
1192        let event_count = facts.len();
1193        let has_cancelled = facts.iter().any(|fact| {
1194            matches!(
1195                fact,
1196                ExecutionEvent::Cancelled {
1197                    client_order_id: id
1198                } if *id == client_order_id
1199            )
1200        });
1201        let has_reconcile = facts
1202            .iter()
1203            .any(|fact| matches!(fact, ExecutionEvent::ReconcileRequired { .. }));
1204        for fact in facts {
1205            let prefix = format!("{operation_id}:response:{client_order_id}");
1206            let correlation = fact_correlation(&prefix, &fact);
1207            self.append(fact, correlation)?;
1208        }
1209        if has_reconcile {
1210            return Err("Venue 返回撤单待对账事实,禁止重复撤单".into());
1211        }
1212        if !has_cancelled {
1213            return Err(format!(
1214                "订单 {client_order_id} 在撤单竞态中已全部成交,成交事实已入账"
1215            ));
1216        }
1217        Ok(PortExecutionResult {
1218            message: format!("CANCELLED venue_events={event_count}"),
1219            event_count,
1220        })
1221    }
1222
1223    /// Apply an audited CancelOrder command only after binding its declared routing scope to the
1224    /// authoritative OMS order. The venue never receives an account or instrument supplied only
1225    /// by the caller.
1226    pub fn cancel_command(
1227        &mut self,
1228        command: &ControlCommand,
1229    ) -> Result<PortExecutionResult, String> {
1230        let target = cancel_order_target_from_command(command)
1231            .map_err(|error| format!("CancelOrder 命令无效: {error:?}"))?;
1232        let order = self
1233            .order(target.client_order_id)
1234            .ok_or_else(|| format!("订单不存在: {}", target.client_order_id))?;
1235        if order.account_id != target.account_id
1236            || !order
1237                .instrument
1238                .venue
1239                .as_str()
1240                .eq_ignore_ascii_case(&target.venue_id)
1241            || !self.venue.venue_id().eq_ignore_ascii_case(&target.venue_id)
1242        {
1243            return Err("CancelOrder 路由账户/交易所与 OMS 订单或执行 Venue 不一致".into());
1244        }
1245        self.cancel_operation_id = Some(format!(
1246            "control:cancel:{}:{}",
1247            command.command_id, target.client_order_id
1248        ));
1249        let result = self.cancel(target.client_order_id);
1250        self.cancel_operation_id = None;
1251        result
1252    }
1253
1254    /// Apply a durable control-plane amendment. The adapter is preflighted before the
1255    /// pending fact is written; after that fact exists a retry is forbidden until a
1256    /// reconciler proves the exchange result.
1257    pub fn amend_command(
1258        &mut self,
1259        command: &ControlCommand,
1260    ) -> Result<PortExecutionResult, String> {
1261        let target = qx_control::amend_order_target_from_command(command)
1262            .map_err(|error| format!("AmendOrder 命令无效: {error:?}"))?;
1263        let current = self
1264            .order(target.client_order_id)
1265            .ok_or_else(|| format!("订单不存在: {}", target.client_order_id))?;
1266        if current.account_id != target.account_id
1267            || !current
1268                .instrument
1269                .venue
1270                .as_str()
1271                .eq_ignore_ascii_case(&target.venue_id)
1272            || !self.venue.venue_id().eq_ignore_ascii_case(&target.venue_id)
1273        {
1274            return Err("AmendOrder 路由账户/交易所与 OMS 订单或执行 Venue 不一致".into());
1275        }
1276        if self.events.has_pending_amendment(current.client_id) {
1277            return Err(format!(
1278                "订单 {} 存在改单结果未知的操作,禁止重发;必须先对账",
1279                current.client_id
1280            ));
1281        }
1282        if current.filled != target.order.filled
1283            || current.status != target.order.status
1284            || current.instrument != target.order.instrument
1285            || current.side != target.order.side
1286            || current.account_id != target.order.account_id
1287            || current.trace != target.order.trace
1288            || current.policy != target.order.policy
1289        {
1290            return Err("AmendOrder 请求基于过期或身份不一致的订单快照".into());
1291        }
1292        self.venue.validate_amend_order(&current, &target.order)?;
1293        self.events.refresh_order_state()?;
1294        let refreshed = self
1295            .order(target.client_order_id)
1296            .ok_or_else(|| format!("订单在改单预检期间从 OMS 消失: {}", target.client_order_id))?;
1297        if refreshed != current {
1298            return Err(format!(
1299                "订单 {} 在改单预检期间出现新成交或状态变化,拒绝基于旧快照改单",
1300                target.client_order_id
1301            ));
1302        }
1303        let operation_id = format!(
1304            "control:amend:{}:{}",
1305            command.command_id, target.client_order_id
1306        );
1307        let pending = self.append_with_outcome(
1308            ExecutionEvent::OrderAmendmentPending {
1309                operation_id: operation_id.clone(),
1310                order: Box::new(target.order.clone()),
1311            },
1312            format!("{operation_id}:pending:{}", target.client_order_id),
1313        )?;
1314        if pending == EventAppendOutcome::Duplicate {
1315            return Err(format!(
1316                "订单 {} 的改单意图已持久化,禁止重复触达 Venue;必须先对账",
1317                target.client_order_id
1318            ));
1319        }
1320        let facts = match self.venue.amend_order(&current, &target.order, self.now) {
1321            Ok(facts) => facts,
1322            Err(error) => {
1323                self.mark_reconcile_for_operation(
1324                    target.client_order_id,
1325                    "amend-error",
1326                    &operation_id,
1327                )?;
1328                return Err(format!(
1329                    "Venue amend 失败/结果未知: {error};订单已标记为待对账"
1330                ));
1331            }
1332        };
1333        if facts.iter().any(|fact| match fact {
1334            ExecutionEvent::Fill(fill) => fill.order_id != target.client_order_id,
1335            ExecutionEvent::FillWithSpec { fill, .. } => fill.order_id != target.client_order_id,
1336            ExecutionEvent::FeeAdjustment { order_id, .. } => *order_id != target.client_order_id,
1337            ExecutionEvent::Cancelled { client_order_id }
1338            | ExecutionEvent::CancelPending { client_order_id }
1339            | ExecutionEvent::ReconcileRequired { client_order_id } => {
1340                *client_order_id != target.client_order_id
1341            }
1342            ExecutionEvent::Accepted { .. }
1343            | ExecutionEvent::Rejected { .. }
1344            | ExecutionEvent::OrderAmendmentPending { .. }
1345            | ExecutionEvent::OrderAmended { .. }
1346            | ExecutionEvent::MarketQuote { .. } => true,
1347        }) {
1348            self.mark_reconcile_for_operation(
1349                target.client_order_id,
1350                "invalid-amend-response",
1351                &operation_id,
1352            )?;
1353            return Err("Venue amend 返回了非法或其他订单的事实,结果未知,必须先对账".into());
1354        }
1355
1356        // The adapter reports success only after an authoritative fetch confirms the
1357        // requested terms. Commit those terms before any concurrent fill facts so the
1358        // OMS reduces fills against the amended total quantity.
1359        self.append(
1360            ExecutionEvent::OrderAmended {
1361                operation_id: operation_id.clone(),
1362                order: Box::new(target.order.clone()),
1363            },
1364            format!("{operation_id}:confirmed:{}", target.client_order_id),
1365        )?;
1366        let fact_count = facts.len();
1367        let has_reconcile = facts
1368            .iter()
1369            .any(|fact| matches!(fact, ExecutionEvent::ReconcileRequired { .. }));
1370        for fact in facts {
1371            let correlation = fact_correlation(
1372                &format!("{operation_id}:response:{}", target.client_order_id),
1373                &fact,
1374            );
1375            self.append(fact, correlation)?;
1376        }
1377        if has_reconcile {
1378            return Err("改单已确认但成交回报要求对账,账户进入待对账状态".into());
1379        }
1380        Ok(PortExecutionResult {
1381            message: format!("AMENDED venue_events={fact_count}"),
1382            event_count: fact_count + 1,
1383        })
1384    }
1385
1386    fn mark_reconcile(&mut self, client_order_id: u64, reason: &str) -> Result<(), String> {
1387        self.append(
1388            ExecutionEvent::ReconcileRequired { client_order_id },
1389            format!("{}:{reason}:{client_order_id}", self.worker_id),
1390        )
1391    }
1392
1393    fn mark_reconcile_for_operation(
1394        &mut self,
1395        client_order_id: u64,
1396        reason: &str,
1397        operation_id: &str,
1398    ) -> Result<(), String> {
1399        self.append(
1400            ExecutionEvent::ReconcileRequired { client_order_id },
1401            format!("{operation_id}:reconcile:{reason}:{client_order_id}"),
1402        )
1403    }
1404
1405    fn append(&mut self, event: ExecutionEvent, correlation_id: String) -> Result<(), String> {
1406        self.append_with_outcome(event, correlation_id).map(|_| ())
1407    }
1408
1409    fn append_with_outcome(
1410        &mut self,
1411        event: ExecutionEvent,
1412        correlation_id: String,
1413    ) -> Result<EventAppendOutcome, String> {
1414        *self.source_seq = self.source_seq.saturating_add(1);
1415        let event_ts = match &event {
1416            ExecutionEvent::Fill(fill) | ExecutionEvent::FillWithSpec { fill, .. } => fill.ts,
1417            _ => self.now,
1418        };
1419        let event = match (self.instrument_spec.as_ref(), event) {
1420            (Some(spec), ExecutionEvent::Fill(fill)) => ExecutionEvent::FillWithSpec {
1421                fill,
1422                spec: Box::new(spec.clone()),
1423            },
1424            (_, event) => event,
1425        };
1426        self.events
1427            .append_execution_event_with_outcome(ExecutionEventEnvelope {
1428                event,
1429                event_ts,
1430                receive_ts: self.now,
1431                source_seq: *self.source_seq,
1432                correlation_id,
1433            })
1434    }
1435}
1436
1437/// Explicit recovery result for a spread group whose confirmed exposure needs
1438/// to be offset. The worker never submits a hedge for an unknown original
1439/// leg; that case remains `ReconcileRequired` and must be resolved by the
1440/// venue reconciliation flow first.
1441#[derive(Clone, Debug)]
1442pub struct HedgeRecoveryOutcome {
1443    pub group: SpreadOrderGroup,
1444    pub attempted: usize,
1445    pub completed: bool,
1446    pub errors: Vec<String>,
1447}
1448
1449const HEDGE_RECOVERY_LEASE_MS: u64 = 30_000;
1450
1451pub trait HedgeOrderValidator {
1452    fn validate(&self, order: &Order) -> Result<(), String>;
1453
1454    /// 补偿提交必须与正常提交带着同一份冻结产品规格:这个 guard 就是运行时按
1455    /// `worker.instrument_spec_path` 解析出来的那个来源(见 qx-cli 的 `RecoveryGuard`),
1456    /// 所以补偿腿既不会被按乘数 1 记账,也不会绕过提交侧精度闸门。
1457    /// 返回 `Ok(None)` 只表示该 worker 没有配置规格(现货 `contract_size=1` 的既有口径),
1458    /// **解析失败**(文件缺失、币种与账簿不符等)必须返回 `Err`,由 worker 转待对账。
1459    fn instrument_spec(&self, _order: &Order) -> Result<Option<TradingInstrumentSpec>, String> {
1460        Ok(None)
1461    }
1462}
1463
1464impl<F> HedgeOrderValidator for F
1465where
1466    F: Fn(&Order) -> Result<(), String>,
1467{
1468    fn validate(&self, order: &Order) -> Result<(), String> {
1469        self(order)
1470    }
1471}
1472
1473/// Restart-safe single-node hedge recovery worker.
1474///
1475/// Compensation client ids are deterministic for `(group_id, leg_id)`, so a
1476/// retry after a process restart reuses the same order identity. The event
1477/// port remains the source of truth for the compensation order status; the
1478/// group snapshot only records that all confirmed exposure has been hedged.
1479pub struct HedgeRecoveryWorker<'a, R: VenueRouterPort, P: ExecutionEventPort> {
1480    router: &'a mut R,
1481    events: &'a mut P,
1482    store: &'a mut dyn SpreadOrderGroupStore,
1483    group: SpreadOrderGroup,
1484    worker_id: &'a str,
1485    claim_owner: String,
1486    now: u64,
1487    source_seq: &'a mut u64,
1488    account_venue_scope: Option<(Option<String>, Option<String>)>,
1489}
1490
1491const MAX_HEDGE_ATTEMPTS: u32 = 3;
1492
1493impl<'a, R: VenueRouterPort, P: ExecutionEventPort> HedgeRecoveryWorker<'a, R, P> {
1494    pub fn new(
1495        group: SpreadOrderGroup,
1496        store: &'a mut dyn SpreadOrderGroupStore,
1497        router: &'a mut R,
1498        events: &'a mut P,
1499        worker_id: &'a str,
1500        now: u64,
1501        source_seq: &'a mut u64,
1502    ) -> qx_core::QxResult<Self> {
1503        group.validate_persisted()?;
1504        Ok(Self {
1505            router,
1506            events,
1507            store,
1508            group,
1509            worker_id,
1510            claim_owner: format!("{}:{}:{}", worker_id, std::process::id(), now),
1511            now,
1512            source_seq,
1513            account_venue_scope: None,
1514        })
1515    }
1516
1517    /// Scope a live recovery pass to the exact account and venue served by this worker.
1518    pub fn for_account_venue(mut self, account_id: &str, venue_id: &str) -> Result<Self, String> {
1519        let account_id = account_id.trim();
1520        let venue_id = venue_id.trim();
1521        if account_id.is_empty() || venue_id.is_empty() {
1522            return Err("实盘多腿恢复必须绑定 account_id 与 venue_id".into());
1523        }
1524        self.account_venue_scope = Some((
1525            Some(account_id.to_string()),
1526            Some(venue_id.to_ascii_uppercase()),
1527        ));
1528        Ok(self)
1529    }
1530
1531    pub fn for_account(mut self, account_id: &str) -> Result<Self, String> {
1532        let account_id = account_id.trim();
1533        if account_id.is_empty() {
1534            return Err("实盘多腿恢复必须绑定 account_id".into());
1535        }
1536        self.account_venue_scope = Some((Some(account_id.to_string()), None));
1537        Ok(self)
1538    }
1539
1540    fn load_group(&mut self) -> Result<(), String> {
1541        if let Some(saved) = self.store.load(&self.group.group_id)? {
1542            if saved.strategy_id != self.group.strategy_id
1543                || saved.legs.len() != self.group.legs.len()
1544                || saved
1545                    .legs
1546                    .iter()
1547                    .zip(&self.group.legs)
1548                    .any(|(left, right)| {
1549                        left.leg_id != right.leg_id
1550                            || left.venue_id != right.venue_id
1551                            || left.order.account_id != right.order.account_id
1552                            || left.order.instrument != right.order.instrument
1553                    })
1554            {
1555                return Err("Hedge 恢复快照与请求的策略、腿或 Venue 路由不一致".into());
1556            }
1557            self.group = saved;
1558        }
1559        Ok(())
1560    }
1561
1562    /// Execute all confirmed compensation targets once, then persist Hedged
1563    /// only when the event port confirms every deterministic hedge order is
1564    /// Filled. Active orders are left pending and are never submitted twice.
1565    pub fn execute(self) -> Result<HedgeRecoveryOutcome, String> {
1566        self.execute_with_validator(None)
1567    }
1568
1569    /// 在实际补偿单提交前注入账户级风控校验。恢复 worker 本身不依赖
1570    /// `qx-risk` 的具体快照来源,由运行时按当前 Venue/账户提供校验器;
1571    /// 未提供时仍保留库级 `Order::validate` 和 reduce-only 约束。
1572    pub fn execute_with_validator(
1573        mut self,
1574        validator: Option<&dyn HedgeOrderValidator>,
1575    ) -> Result<HedgeRecoveryOutcome, String> {
1576        self.load_group()?;
1577        match self.group.status {
1578            SpreadOrderGroupStatus::HedgeRequired => {}
1579            SpreadOrderGroupStatus::Hedged => {
1580                return Ok(HedgeRecoveryOutcome {
1581                    group: self.group,
1582                    attempted: 0,
1583                    completed: true,
1584                    errors: Vec::new(),
1585                });
1586            }
1587            SpreadOrderGroupStatus::ReconcileRequired => {
1588                return Ok(HedgeRecoveryOutcome {
1589                    group: self.group,
1590                    attempted: 0,
1591                    completed: false,
1592                    errors: vec![
1593                        "原始多腿订单组存在未知 Venue 状态,必须先完成对账,禁止自动对冲".into(),
1594                    ],
1595                });
1596            }
1597            status => {
1598                return Ok(HedgeRecoveryOutcome {
1599                    group: self.group,
1600                    attempted: 0,
1601                    completed: false,
1602                    errors: vec![format!(
1603                        "订单组当前为 {status:?},只有 HedgeRequired 才能执行恢复"
1604                    )],
1605                });
1606            }
1607        }
1608
1609        let mut targets = self.group.compensation_targets();
1610        if let Some((account_id, venue_id)) = &self.account_venue_scope {
1611            targets.retain(|target| {
1612                account_id
1613                    .as_deref()
1614                    .is_none_or(|account_id| target.account_id == account_id)
1615                    && venue_id
1616                        .as_deref()
1617                        .is_none_or(|venue_id| target.venue_id.eq_ignore_ascii_case(venue_id))
1618            });
1619        }
1620        if targets.is_empty() {
1621            // A crash can happen after the final compensation fill and progress
1622            // snapshot are durable, but before the group status is changed to
1623            // Hedged. On restart there are no outstanding targets, so finish
1624            // that state transition under the same group claim used by normal
1625            // recovery. An account-scoped worker must still verify the whole
1626            // group before it can close the group-wide state.
1627            if self.group.all_confirmed_exposure_hedged() {
1628                let Some(claim_token) = self.store.try_claim(
1629                    &self.group.group_id,
1630                    &self.claim_owner,
1631                    self.now,
1632                    HEDGE_RECOVERY_LEASE_MS,
1633                )?
1634                else {
1635                    return Ok(HedgeRecoveryOutcome {
1636                        group: self.group,
1637                        attempted: 0,
1638                        completed: false,
1639                        errors: vec!["订单组正在由其他恢复 owner 处理,跳过本轮".into()],
1640                    });
1641                };
1642                if !self.store.verify_claim(
1643                    &self.group.group_id,
1644                    &self.claim_owner,
1645                    claim_token,
1646                    self.now,
1647                )? {
1648                    return Ok(HedgeRecoveryOutcome {
1649                        group: self.group,
1650                        attempted: 0,
1651                        completed: false,
1652                        errors: vec!["多腿恢复 claim 已过期或已被其他 owner 接管".into()],
1653                    });
1654                }
1655                self.group
1656                    .mark_hedged()
1657                    .map_err(|error| format!("标记多腿订单组已对冲失败: {error:?}"))?;
1658                self.store
1659                    .save_claimed(&self.group, &self.claim_owner, claim_token, self.now)?;
1660                self.store
1661                    .release_claim(&self.group.group_id, &self.claim_owner, claim_token)?;
1662                return Ok(HedgeRecoveryOutcome {
1663                    group: self.group,
1664                    attempted: 0,
1665                    completed: true,
1666                    errors: Vec::new(),
1667                });
1668            }
1669            return Ok(HedgeRecoveryOutcome {
1670                group: self.group,
1671                attempted: 0,
1672                completed: false,
1673                errors: Vec::new(),
1674            });
1675        }
1676        let Some(claim_token) = self.store.try_claim(
1677            &self.group.group_id,
1678            &self.claim_owner,
1679            self.now,
1680            HEDGE_RECOVERY_LEASE_MS,
1681        )?
1682        else {
1683            return Ok(HedgeRecoveryOutcome {
1684                group: self.group,
1685                attempted: 0,
1686                completed: false,
1687                errors: vec!["订单组正在由其他恢复 owner 处理,跳过本轮".into()],
1688            });
1689        };
1690        let mut attempted = 0;
1691        let mut errors = Vec::new();
1692        let mut all_filled = true;
1693        for target in targets {
1694            if !self.store.verify_claim(
1695                &self.group.group_id,
1696                &self.claim_owner,
1697                claim_token,
1698                self.now,
1699            )? {
1700                errors.push("多腿恢复 claim 已过期或已被其他 owner 接管".into());
1701                all_filled = false;
1702                break;
1703            }
1704            let source_leg = self
1705                .group
1706                .leg(&target.leg_id)
1707                .map_err(|error| format!("读取补偿来源腿失败: {error:?}"))?;
1708            if source_leg.venue_id.trim().is_empty() {
1709                errors.push(format!(
1710                    "补偿腿 {} 缺少 Venue 路由,拒绝使用默认交易所",
1711                    target.leg_id
1712                ));
1713                all_filled = false;
1714                continue;
1715            }
1716            let client_id = compensation_client_id(&self.group, &target.leg_id, target.attempt);
1717            let existing = self
1718                .events
1719                .orders()
1720                .into_iter()
1721                .find(|order| order.client_id == client_id);
1722            let order = build_compensation_order(&self.group, source_leg, &target, client_id)?;
1723            if let Some(existing) = existing {
1724                if !same_compensation_order(&existing, &order) {
1725                    errors.push(format!(
1726                        "补偿 client_order_id={} 已被其他订单占用,拒绝覆盖",
1727                        client_id
1728                    ));
1729                    self.group.require_reconciliation();
1730                    all_filled = false;
1731                    continue;
1732                }
1733                if existing.status == OrderStatus::Filled {
1734                    if !existing.filled_decimal().is_positive() {
1735                        errors.push(format!(
1736                            "补偿订单 {} 报告 Filled 但成交数量为零,必须对账",
1737                            client_id
1738                        ));
1739                        self.group.require_reconciliation();
1740                        all_filled = false;
1741                        continue;
1742                    }
1743                    self.group
1744                        .record_compensation_fill_exact(&target.leg_id, existing.filled_decimal())
1745                        .map_err(|error| format!("恢复补偿成交进度失败: {error:?}"))?;
1746                    if existing
1747                        .filled_decimal()
1748                        .checked_cmp(target.quantity_decimal())
1749                        .is_some_and(|ordering| ordering.is_lt())
1750                    {
1751                        let next_attempt = self
1752                            .group
1753                            .advance_compensation_attempt(&target.leg_id)
1754                            .map_err(|error| format!("推进补偿尝试序号失败: {error:?}"))?;
1755                        if next_attempt >= MAX_HEDGE_ATTEMPTS {
1756                            self.group.require_reconciliation();
1757                            errors.push(format!(
1758                                "补偿腿 {} 已达到 {} 次尝试上限,剩余敞口转人工对账",
1759                                target.leg_id, MAX_HEDGE_ATTEMPTS
1760                            ));
1761                        }
1762                    }
1763                    continue;
1764                }
1765                if matches!(
1766                    existing.status,
1767                    OrderStatus::PendingSubmit
1768                        | OrderStatus::Submitted
1769                        | OrderStatus::Accepted
1770                        | OrderStatus::Working
1771                        | OrderStatus::PartiallyFilled
1772                        | OrderStatus::CancelPending
1773                ) {
1774                    all_filled = false;
1775                    continue;
1776                }
1777                if matches!(
1778                    existing.status,
1779                    OrderStatus::Cancelled | OrderStatus::Expired
1780                ) {
1781                    if existing.filled_decimal().is_positive() {
1782                        self.group
1783                            .record_compensation_fill_exact(
1784                                &target.leg_id,
1785                                existing.filled_decimal(),
1786                            )
1787                            .map_err(|error| format!("归约终态补偿部分成交失败: {error:?}"))?;
1788                    }
1789                    let next_attempt = self
1790                        .group
1791                        .advance_compensation_attempt(&target.leg_id)
1792                        .map_err(|error| format!("推进补偿尝试序号失败: {error:?}"))?;
1793                    if next_attempt >= MAX_HEDGE_ATTEMPTS {
1794                        self.group.require_reconciliation();
1795                        errors.push(format!(
1796                            "补偿腿 {} 已达到 {} 次尝试上限,剩余敞口转人工对账",
1797                            target.leg_id, MAX_HEDGE_ATTEMPTS
1798                        ));
1799                    }
1800                    errors.push(format!(
1801                        "补偿订单 {} 已终止于 {:?},剩余敞口将在下一恢复轮处理",
1802                        client_id, existing.status
1803                    ));
1804                    all_filled = false;
1805                    continue;
1806                }
1807                errors.push(format!(
1808                    "补偿订单 {} 状态 {:?} 不能安全重试,必须对账",
1809                    client_id, existing.status
1810                ));
1811                self.group.require_reconciliation();
1812                all_filled = false;
1813                continue;
1814            }
1815
1816            let mut leg_spec: Option<TradingInstrumentSpec> = None;
1817            if let Some(validator) = validator {
1818                if let Err(error) = validator.validate(&order) {
1819                    errors.push(format!(
1820                        "补偿腿 {} 未通过账户级风控,拒绝自动对冲: {error}",
1821                        target.leg_id
1822                    ));
1823                    all_filled = false;
1824                    continue;
1825                }
1826                // 规格解析必须先于登记与提交:没有冻结规格就既过不了精度闸门,也
1827                // 会让衍生腿被按乘数 1 记账。解析失败是配置问题而不是未知结果,
1828                // 所以留组于 HedgeRequired 等下一轮,而不是留下一条假的待对账事实。
1829                match validator.instrument_spec(&order) {
1830                    Ok(spec) => leg_spec = spec,
1831                    Err(error) => {
1832                        errors.push(format!(
1833                            "补偿腿 {} 未解析到产品规格,拒绝自动对冲: {error}",
1834                            target.leg_id
1835                        ));
1836                        all_filled = false;
1837                        continue;
1838                    }
1839                }
1840            }
1841            let Some(capabilities) = self.router.capabilities_for(&source_leg.venue_id) else {
1842                errors.push(format!(
1843                    "补偿腿 {} 的 Venue {} 未声明能力或路由不存在,拒绝注册",
1844                    target.leg_id, source_leg.venue_id
1845                ));
1846                all_filled = false;
1847                continue;
1848            };
1849            if let Err(error) = capabilities.validate_submit(&order, &source_leg.venue_id) {
1850                errors.push(format!("补偿腿 {} 能力校验失败: {error}", target.leg_id));
1851                all_filled = false;
1852                continue;
1853            }
1854            if let Err(error) = self.router.execution_readiness_for(&source_leg.venue_id) {
1855                errors.push(format!("补偿腿 {} Venue 尚未就绪: {error}", target.leg_id));
1856                all_filled = false;
1857                continue;
1858            }
1859            self.events
1860                .register_order(
1861                    order.clone(),
1862                    self.now,
1863                    Some(format!(
1864                        "{}:hedge:{}:{}:register",
1865                        self.worker_id, self.group.group_id, target.leg_id
1866                    )),
1867                )
1868                .map_err(|error| format!("注册补偿订单 {} 失败: {error}", client_id))?;
1869            attempted += 1;
1870            let facts =
1871                match self
1872                    .router
1873                    .submit_order(&source_leg.venue_id, order.clone(), self.now)
1874                {
1875                    Ok(facts) if facts.is_empty() => {
1876                        errors.push(format!(
1877                            "补偿腿 {} 未返回事实,结果未知,必须对账",
1878                            target.leg_id
1879                        ));
1880                        self.group.require_reconciliation();
1881                        all_filled = false;
1882                        continue;
1883                    }
1884                    Ok(facts) => facts,
1885                    Err(error) => {
1886                        errors.push(format!(
1887                            "补偿腿 {} 提交失败/结果未知: {error}",
1888                            target.leg_id
1889                        ));
1890                        self.group.require_reconciliation();
1891                        all_filled = false;
1892                        continue;
1893                    }
1894                };
1895            // 补偿提交也是提交:回包必须过与 `PortExecutionService::submit` 同一道
1896            // 闸门。这里绕过闸门,"越界回报只能转待对账"就只剩半条纪律。
1897            if let Err(violation) = gate_submit_facts(&order, &facts, leg_spec.as_ref()) {
1898                errors.push(format!("补偿腿 {} {violation}", target.leg_id));
1899                self.append_fact(
1900                    ExecutionEvent::ReconcileRequired {
1901                        client_order_id: client_id,
1902                    },
1903                    format!(
1904                        "{}:hedge:{}:{}:{}",
1905                        self.worker_id,
1906                        self.group.group_id,
1907                        target.leg_id,
1908                        violation.reason_tag()
1909                    ),
1910                    None,
1911                )?;
1912                self.group.require_reconciliation();
1913                all_filled = false;
1914                continue;
1915            }
1916            let hedge_prefix = format!(
1917                "{}:hedge:{}:{}",
1918                self.worker_id, self.group.group_id, target.leg_id
1919            );
1920            for fact in facts {
1921                let correlation_id = fact_correlation(&hedge_prefix, &fact);
1922                self.append_fact(fact, correlation_id, leg_spec.as_ref())?;
1923            }
1924            let persisted_hedge = self
1925                .events
1926                .orders()
1927                .into_iter()
1928                .find(|candidate| candidate.client_id == client_id);
1929            match persisted_hedge {
1930                Some(hedge)
1931                    if hedge.status == OrderStatus::Filled
1932                        && hedge.filled_decimal().is_positive() =>
1933                {
1934                    self.group
1935                        .record_compensation_fill_exact(&target.leg_id, hedge.filled_decimal())
1936                        .map_err(|error| format!("归约补偿成交进度失败: {error:?}"))?;
1937                    if hedge
1938                        .filled_decimal()
1939                        .checked_cmp(target.quantity_decimal())
1940                        .is_some_and(|ordering| ordering.is_lt())
1941                    {
1942                        let next_attempt = self
1943                            .group
1944                            .advance_compensation_attempt(&target.leg_id)
1945                            .map_err(|error| format!("推进补偿尝试序号失败: {error:?}"))?;
1946                        if next_attempt >= MAX_HEDGE_ATTEMPTS {
1947                            self.group.require_reconciliation();
1948                            errors.push(format!(
1949                                "补偿腿 {} 已达到 {} 次尝试上限,剩余敞口转人工对账",
1950                                target.leg_id, MAX_HEDGE_ATTEMPTS
1951                            ));
1952                        }
1953                    }
1954                }
1955                Some(hedge)
1956                    if matches!(hedge.status, OrderStatus::Cancelled | OrderStatus::Expired) =>
1957                {
1958                    if hedge.filled_decimal().is_positive() {
1959                        self.group
1960                            .record_compensation_fill_exact(&target.leg_id, hedge.filled_decimal())
1961                            .map_err(|error| format!("归约终态补偿部分成交失败: {error:?}"))?;
1962                    }
1963                    let next_attempt = self
1964                        .group
1965                        .advance_compensation_attempt(&target.leg_id)
1966                        .map_err(|error| format!("推进补偿尝试序号失败: {error:?}"))?;
1967                    if next_attempt >= MAX_HEDGE_ATTEMPTS {
1968                        self.group.require_reconciliation();
1969                        errors.push(format!(
1970                            "补偿腿 {} 已达到 {} 次尝试上限,剩余敞口转人工对账",
1971                            target.leg_id, MAX_HEDGE_ATTEMPTS
1972                        ));
1973                    }
1974                    all_filled = false;
1975                }
1976                Some(hedge)
1977                    if matches!(hedge.status, OrderStatus::Rejected | OrderStatus::Unknown) =>
1978                {
1979                    self.group.require_reconciliation();
1980                    errors.push(format!(
1981                        "补偿订单 {} 进入 {:?},必须人工对账",
1982                        client_id, hedge.status
1983                    ));
1984                    all_filled = false;
1985                }
1986                _ => all_filled = false,
1987            }
1988        }
1989
1990        if all_filled
1991            && errors.is_empty()
1992            && self.group.all_confirmed_exposure_hedged()
1993            && self.group.status == SpreadOrderGroupStatus::HedgeRequired
1994        {
1995            self.group
1996                .mark_hedged()
1997                .map_err(|error| format!("标记多腿订单组已对冲失败: {error:?}"))?;
1998        }
1999        self.store
2000            .save_claimed(&self.group, &self.claim_owner, claim_token, self.now)?;
2001        self.store
2002            .release_claim(&self.group.group_id, &self.claim_owner, claim_token)?;
2003        let completed =
2004            self.group.status == SpreadOrderGroupStatus::Hedged && all_filled && errors.is_empty();
2005        Ok(HedgeRecoveryOutcome {
2006            group: self.group,
2007            attempted,
2008            completed,
2009            errors,
2010        })
2011    }
2012
2013    /// 追加一条补偿路径事实。`spec` 与 `PortExecutionService::append` 同源:成交必须
2014    /// 自带它那份冻结规格落库,否则账簿会退回 `LegacyMultiplier(1)`,衍生腿的仓位与
2015    /// 保证金按乘数 1 计算,对冲方向对、数量却差一个合约面值。
2016    fn append_fact(
2017        &mut self,
2018        event: ExecutionEvent,
2019        correlation_id: String,
2020        spec: Option<&TradingInstrumentSpec>,
2021    ) -> Result<(), String> {
2022        *self.source_seq = self.source_seq.saturating_add(1);
2023        let event_ts = match &event {
2024            ExecutionEvent::Fill(fill) | ExecutionEvent::FillWithSpec { fill, .. } => fill.ts,
2025            _ => self.now,
2026        };
2027        let event = match (spec, event) {
2028            (Some(spec), ExecutionEvent::Fill(fill)) => ExecutionEvent::FillWithSpec {
2029                fill,
2030                spec: Box::new(spec.clone()),
2031            },
2032            (_, event) => event,
2033        };
2034        self.events.append_execution_event(ExecutionEventEnvelope {
2035            event,
2036            event_ts,
2037            receive_ts: self.now,
2038            source_seq: *self.source_seq,
2039            correlation_id,
2040        })
2041    }
2042}
2043
2044fn build_compensation_order(
2045    group: &SpreadOrderGroup,
2046    source_leg: &qx_zhenlu::SpreadOrderLeg,
2047    target: &qx_zhenlu::SpreadCompensationTarget,
2048    client_id: u64,
2049) -> Result<Order, String> {
2050    let mut policy = source_leg.order.policy.unwrap_or_default();
2051    policy.reduce_only = true;
2052    let exact_amounts = target.qty_exact.map(|quantity| qx_core::ExactOrderAmounts {
2053        quantity,
2054        limit_price: None,
2055        filled: qx_core::ExactDecimal::ZERO,
2056        quote_budget: None,
2057        quote_filled: qx_core::ExactDecimal::ZERO,
2058        market_reference_price: source_leg.order.market_reference_price_decimal(),
2059        conditional: None,
2060    });
2061    let order = Order {
2062        client_id,
2063        instrument: target.instrument.clone(),
2064        side: target.side,
2065        qty: if exact_amounts.is_some() {
2066            qx_core::Quantity::ZERO
2067        } else {
2068            target.qty
2069        },
2070        limit: None,
2071        status: OrderStatus::PendingSubmit,
2072        filled: Quantity::ZERO,
2073        account_id: target.account_id.clone(),
2074        trace: Some(OrderTrace {
2075            run_id: None,
2076            strategy_id: Some(group.strategy_id.clone()),
2077            signal_id: None,
2078            intent_id: None,
2079            rule_version: Some("spread-hedge-v1".into()),
2080        }),
2081        policy: Some(policy),
2082        exact_amounts,
2083    };
2084    order.validate()?;
2085    Ok(order)
2086}
2087
2088fn same_compensation_order(left: &Order, right: &Order) -> bool {
2089    left.same_submission_identity(right)
2090}
2091
2092fn compensation_client_id(group: &SpreadOrderGroup, leg_id: &str, attempt: u32) -> u64 {
2093    let mut hash = 0xcbf29ce484222325_u64;
2094    let attempt_bytes = attempt.to_le_bytes();
2095    for byte in group
2096        .group_id
2097        .as_bytes()
2098        .iter()
2099        .chain([0_u8].iter())
2100        .chain(leg_id.as_bytes().iter())
2101        .chain([0_u8].iter())
2102        .chain(attempt_bytes.iter())
2103    {
2104        hash ^= u64::from(*byte);
2105        hash = hash.wrapping_mul(0x100000001b3_u64);
2106    }
2107    let mut candidate = hash | (1_u64 << 63);
2108    if candidate == 0 {
2109        candidate = 1_u64 << 63;
2110    }
2111    while group
2112        .legs
2113        .iter()
2114        .any(|leg| leg.order.client_id == candidate)
2115    {
2116        candidate = candidate.wrapping_add(1);
2117    }
2118    candidate
2119}
2120
2121/// 提交**同步返回**的事实进入账本前的统一闸门:先形状契约,再产品规格精度。
2122///
2123/// 两处提交入口(`PortExecutionService::submit` 与对冲补偿 worker)必须共用它。
2124/// 各写一份就会重演"越界回报只能转待对账"只剩半条纪律:同一笔成交走用户流被
2125/// `ingest_venue_events_with_pipeline` 拦下、不记账,走提交回包却直接入账。
2126/// 规格为 `None` 时只过形状闸门 —— 没有冻结规格就没有可核对的 tick/step,
2127/// 与归约入口一样绝不凭空造一份。
2128enum SubmitFactViolation {
2129    /// 事实与订单不匹配(归属、数量、空回报、混入行情)。
2130    Shape(String),
2131    /// 成交落在冻结产品规格的 tick/step 之外。
2132    Precision(qx_core::QxError),
2133}
2134
2135impl SubmitFactViolation {
2136    /// 写进 `ReconcileRequired` 关联号的原因段,保持两类未知结果可分别检索。
2137    fn reason_tag(&self) -> &'static str {
2138        match self {
2139            Self::Shape(_) => "invalid-submit-response",
2140            Self::Precision(_) => "submit-fill-out-of-spec",
2141        }
2142    }
2143}
2144
2145impl std::fmt::Display for SubmitFactViolation {
2146    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2147        match self {
2148            Self::Shape(error) => {
2149                write!(f, "Venue 返回非法下单事实,结果未知,必须先对账: {error}")
2150            }
2151            Self::Precision(error) => write!(
2152                f,
2153                "Venue 提交返回的成交回报违反产品规格,结果未知,必须先对账: {error:?}"
2154            ),
2155        }
2156    }
2157}
2158
2159fn gate_submit_facts(
2160    order: &Order,
2161    facts: &[ExecutionEvent],
2162    spec: Option<&TradingInstrumentSpec>,
2163) -> Result<(), SubmitFactViolation> {
2164    validate_submit_events(order, facts).map_err(SubmitFactViolation::Shape)?;
2165    // 规格优先取回报自带的那份:`append` 落库并交给账簿的就是它,校验另一份是假同源。
2166    let violation = facts.iter().find_map(|fact| {
2167        let (fill, embedded) = match fact {
2168            ExecutionEvent::Fill(fill) => (fill.as_ref(), None),
2169            ExecutionEvent::FillWithSpec { fill, spec } => (fill.as_ref(), Some(&**spec)),
2170            _ => return None,
2171        };
2172        let spec = embedded.or(spec)?;
2173        validate_fill_against_spec(fill, spec)
2174    });
2175    match violation {
2176        Some(error) => Err(SubmitFactViolation::Precision(error)),
2177        None => Ok(()),
2178    }
2179}
2180
2181/// 成交事实的稳定身份段。
2182///
2183/// 身份必须取自成交内容本身,不能用进程内的 `source_seq`:一次性 Paper 命令
2184/// 每个进程都从 1 重新计数,同一订单的第二笔成交会撞上第一笔已落库的事实、被
2185/// EventLog 静默去重,订单停在 Accepted 而资金不动,调用方却收到 `fills=2`。
2186/// 字段选择与 `qx-runtime` 的 `fill_key` 同源,因此同一批回报重放仍然幂等。
2187fn fill_tag(fill: &qx_core::Fill) -> String {
2188    format!(
2189        "fill:{}:{}:{}:{}:{}:{}{}",
2190        fill.order_id,
2191        fill.ts,
2192        fill.qty.raw(),
2193        fill.price.raw(),
2194        fill.fee.raw(),
2195        fill.venue_order_id.clone().unwrap_or_default(),
2196        fill.exact_identity_suffix(),
2197    )
2198}
2199
2200fn validate_fill_against_spec(
2201    fill: &qx_core::Fill,
2202    spec: &TradingInstrumentSpec,
2203) -> Option<qx_core::QxError> {
2204    match fill.exact_amounts {
2205        Some(amounts) => spec
2206            .validate_exact_fill(amounts.quantity, amounts.price)
2207            .err(),
2208        None => spec.validate_fill(fill.qty.raw(), fill.price.raw()).err(),
2209    }
2210}
2211
2212/// 一条 Venue 回报在其关联号中的稳定身份段。
2213fn fact_tag(fact: &ExecutionEvent) -> String {
2214    match fact {
2215        ExecutionEvent::Accepted {
2216            client_order_id, ..
2217        } => format!("accepted:{client_order_id}"),
2218        ExecutionEvent::Rejected {
2219            client_order_id,
2220            reason,
2221        } => {
2222            format!("rejected:{client_order_id}:{reason}")
2223        }
2224        ExecutionEvent::CancelPending { client_order_id } => {
2225            format!("cancel-pending:{client_order_id}")
2226        }
2227        ExecutionEvent::OrderAmendmentPending {
2228            operation_id,
2229            order,
2230        } => format!("amend-pending:{}:{}", order.client_id, operation_id),
2231        ExecutionEvent::OrderAmended {
2232            operation_id,
2233            order,
2234        } => format!("amended:{}:{}", order.client_id, operation_id),
2235        ExecutionEvent::Cancelled { client_order_id } => format!("cancelled:{client_order_id}"),
2236        ExecutionEvent::FeeAdjustment {
2237            account_id,
2238            venue_id,
2239            order_id,
2240            instrument,
2241            fees,
2242        } => {
2243            let mut fees = fees.clone();
2244            fees.sort_by(|left, right| {
2245                left.currency
2246                    .as_deref()
2247                    .unwrap_or_default()
2248                    .cmp(right.currency.as_deref().unwrap_or_default())
2249                    .then_with(|| left.amount.raw().cmp(&right.amount.raw()))
2250            });
2251            let identity = fees
2252                .iter()
2253                .map(|fee| {
2254                    format!(
2255                        "{}={}#{}",
2256                        fee.currency.as_deref().unwrap_or_default(),
2257                        fee.amount.raw(),
2258                        {
2259                            let mut trade_ids = fee.source_trade_ids.clone();
2260                            trade_ids.sort();
2261                            trade_ids.join(";")
2262                        }
2263                    )
2264                })
2265                .collect::<Vec<_>>()
2266                .join(",");
2267            format!("fee-adjustment:{account_id}:{venue_id}:{order_id}:{instrument}:{identity}")
2268        }
2269        ExecutionEvent::ReconcileRequired { client_order_id } => {
2270            format!("reconcile:{client_order_id}")
2271        }
2272        ExecutionEvent::Fill(fill) | ExecutionEvent::FillWithSpec { fill, .. } => {
2273            fill_tag(fill.as_ref())
2274        }
2275        ExecutionEvent::MarketQuote { instrument, quote } => {
2276            format!("market:{instrument}:{}:{}", quote.source_seq, quote.ts)
2277        }
2278    }
2279}
2280
2281fn execution_event_client_order_id(event: &ExecutionEvent) -> Option<u64> {
2282    match event {
2283        ExecutionEvent::Accepted {
2284            client_order_id, ..
2285        }
2286        | ExecutionEvent::Rejected {
2287            client_order_id, ..
2288        }
2289        | ExecutionEvent::CancelPending { client_order_id }
2290        | ExecutionEvent::Cancelled { client_order_id }
2291        | ExecutionEvent::ReconcileRequired { client_order_id } => Some(*client_order_id),
2292        ExecutionEvent::Fill(fill) | ExecutionEvent::FillWithSpec { fill, .. } => {
2293            Some(fill.order_id)
2294        }
2295        ExecutionEvent::FeeAdjustment { order_id, .. } => Some(*order_id),
2296        ExecutionEvent::OrderAmendmentPending { order, .. }
2297        | ExecutionEvent::OrderAmended { order, .. } => Some(order.client_id),
2298        ExecutionEvent::MarketQuote { .. } => None,
2299    }
2300}
2301
2302/// 在调用方的来源前缀(worker/venue/group/leg)后追加回报身份。
2303///
2304/// `RuntimePipeline::ingest` 对 Accepted/Cancelled/ReconcileRequired/
2305/// FillWithSpec 按 correlation 去重——重启后 `source_seq` 会重新计数,只靠它
2306/// 挡不住重放。因此前缀必须唯一到"这一批回报属于哪条腿",再叠加事实自身的
2307/// 身份;否则第二个订单/第二条腿会撞上第一个已落库的事实而被静默丢弃。
2308fn fact_correlation(prefix: &str, fact: &ExecutionEvent) -> String {
2309    format!("{prefix}:{}", fact_tag(fact))
2310}
2311
2312/// 将 Venue 返回的订单事实统一归约到执行事件端口(EventLog/Ledger 管线)。
2313///
2314/// `source_seq` 由调用方持有;重复回报仍由端口的幂等语义去重。Paper、Live 与
2315/// 任何自定义运行时共用这一条实现,不允许再按后端分叉。
2316pub fn ingest_venue_events<P: ExecutionEventPort>(
2317    pipeline: &mut P,
2318    events: impl IntoIterator<Item = VenueEvent>,
2319    worker_id: &str,
2320    receive_ts: u64,
2321    source_seq: &mut u64,
2322) -> Result<usize, String> {
2323    ingest_venue_events_with_pipeline(pipeline, events, worker_id, receive_ts, source_seq, None)
2324        .map_err(|error| format!("Venue 执行回报事实归约失败: {error}"))
2325}
2326
2327/// 将含有冻结产品规格的 Venue 成交归约为衍生品记账事实。
2328///
2329/// 规格不会被写进 `Filled` 事件本身;完整的衍生品 LedgerEntry 会随同一批
2330/// `LedgerApplied` 事实写入 EventLog,因此重启后的 ReplayVerifier 仍可准确重建。
2331pub fn ingest_venue_events_with_spec<P: ExecutionEventPort>(
2332    pipeline: &mut P,
2333    events: impl IntoIterator<Item = VenueEvent>,
2334    worker_id: &str,
2335    receive_ts: u64,
2336    source_seq: &mut u64,
2337    spec: &TradingInstrumentSpec,
2338) -> Result<usize, String> {
2339    ingest_venue_events_with_pipeline(
2340        pipeline,
2341        events,
2342        worker_id,
2343        receive_ts,
2344        source_seq,
2345        Some(spec),
2346    )
2347    .map_err(|error| format!("带产品规格的 Venue 成交事实归约失败: {error}"))
2348}
2349
2350fn ingest_venue_events_with_pipeline<P: ExecutionEventPort>(
2351    pipeline: &mut P,
2352    events: impl IntoIterator<Item = VenueEvent>,
2353    worker_id: &str,
2354    receive_ts: u64,
2355    source_seq: &mut u64,
2356    spec: Option<&TradingInstrumentSpec>,
2357) -> Result<usize, String> {
2358    let mut event_count = 0_usize;
2359    let mut rejections = Vec::new();
2360    for event in events {
2361        event_count += 1;
2362        *source_seq = source_seq.saturating_add(1);
2363        let (event, event_ts, correlation_id) = match event {
2364            VenueEvent::Accepted {
2365                client_order_id,
2366                venue_order_id,
2367                ts,
2368            } => (
2369                ExecutionEvent::Accepted {
2370                    client_order_id,
2371                    venue_order_id,
2372                },
2373                ts,
2374                format!("{worker_id}:accepted:{client_order_id}"),
2375            ),
2376            VenueEvent::Rejected {
2377                client_order_id,
2378                reason,
2379                ts,
2380            } => (
2381                ExecutionEvent::Rejected {
2382                    client_order_id,
2383                    reason,
2384                },
2385                ts,
2386                format!("{worker_id}:rejected:{client_order_id}"),
2387            ),
2388            VenueEvent::Fill(fill) => {
2389                let fill = *fill;
2390                let event_ts = fill.ts;
2391                let fill_order_id = fill.order_id;
2392                let seq = *source_seq;
2393                // 成交回报的关联号取自成交内容:`source_seq` 是进程内计数,
2394                // 重启后重新计数会让同一订单的第二笔成交撞上第一笔已落库事实
2395                // 而被静默去重(订单停在 Accepted、资金不动)。
2396                let content_correlation = format!("{worker_id}:{}", fill_tag(&fill));
2397                // 精度闸门:带冻结产品规格的回报若落在 tick/step 之外,就是与规格冲突的
2398                // 事实,只能转成待对账(不记账、不改状态),并把原因回传给 worker。
2399                let violation = spec.and_then(|spec| validate_fill_against_spec(&fill, spec));
2400                if let Some(error) = violation {
2401                    rejections.push(format!(
2402                        "订单 {fill_order_id} 成交回报违反产品规格: {error:?}"
2403                    ));
2404                    (
2405                        ExecutionEvent::ReconcileRequired {
2406                            client_order_id: fill_order_id,
2407                        },
2408                        event_ts,
2409                        format!("{worker_id}:precision:{fill_order_id}:{seq}"),
2410                    )
2411                } else {
2412                    let event = match spec {
2413                        Some(spec) => ExecutionEvent::FillWithSpec {
2414                            fill: Box::new(fill),
2415                            spec: Box::new(spec.clone()),
2416                        },
2417                        None => ExecutionEvent::Fill(Box::new(fill)),
2418                    };
2419                    (event, event_ts, content_correlation)
2420                }
2421            }
2422            VenueEvent::Cancelled {
2423                client_order_id,
2424                ts,
2425            } => (
2426                ExecutionEvent::Cancelled { client_order_id },
2427                ts,
2428                format!("{worker_id}:cancelled:{client_order_id}"),
2429            ),
2430            VenueEvent::FeeAdjustment {
2431                account_id,
2432                venue_id,
2433                order_id,
2434                instrument,
2435                fees,
2436                ts,
2437            } => {
2438                let fact = ExecutionEvent::FeeAdjustment {
2439                    account_id,
2440                    venue_id,
2441                    order_id,
2442                    instrument,
2443                    fees,
2444                };
2445                let correlation = fact_correlation(worker_id, &fact);
2446                (fact, ts, correlation)
2447            }
2448        };
2449        pipeline.append_execution_event(ExecutionEventEnvelope {
2450            event,
2451            event_ts,
2452            receive_ts,
2453            source_seq: *source_seq,
2454            correlation_id,
2455        })?;
2456    }
2457    if !rejections.is_empty() {
2458        return Err(format!(
2459            "成交回报精度越界,已转为待对账事实: {}",
2460            rejections.join("; ")
2461        ));
2462    }
2463    Ok(event_count)
2464}
2465
2466/// 提交一条已通过控制面审计的 SubmitOrder:框架唯一的订单提交入口。
2467///
2468/// 这里不负责账户/Venue 拓扑授权,也不负责 ControlPlane 的 Accepted/终态回写;
2469/// 它只负责订单事实注册、未知结果保护、Venue submit 和标准回报归约。这样
2470/// Paper、Binance 和未来执行 worker 可以共享同一副作用边界。
2471///
2472/// `spread_store` 是多腿订单组快照来源:带 `spread_group_id` 的命令必须由注入了
2473/// 组存储的提交路径执行,否则 [`spread_group_barrier`] 以 fail-closed 拒绝。
2474///
2475/// 账户级风控走 `context`(快照与市场规格),供 Paper/CCXT/Binance worker 统一使用;
2476/// Venue 仍只接收通过预检的订单。
2477pub fn submit_order_with_risk<V: Venue, P: ExecutionEventPort>(
2478    request: SubmitOrderWithRiskRequest<'_, V, P>,
2479) -> Result<String, String> {
2480    let SubmitOrderWithRiskRequest {
2481        command,
2482        venue,
2483        pipeline,
2484        worker_id,
2485        now,
2486        source_seq,
2487        context,
2488        spread_store,
2489    } = request;
2490    spread_group_barrier(spread_store, command)?;
2491    let mut venue = BorrowedVenuePort::new(venue);
2492    let mut gateway = ExecutionGateway::new(&mut venue, pipeline, worker_id, now, source_seq);
2493    if let Some(store) = spread_store {
2494        gateway = gateway.with_spread_group_store(store);
2495    }
2496    let result = if let Some(spec) = context.risk.instrument_spec.clone() {
2497        gateway
2498            .with_instrument_spec(spec)
2499            .submit_command_with_risk(
2500                command,
2501                &RiskContextPort {
2502                    risk: context.risk,
2503                    position: context.position,
2504                },
2505            )?
2506    } else {
2507        gateway.submit_command_with_risk(
2508            command,
2509            &RiskContextPort {
2510                risk: context.risk,
2511                position: context.position,
2512            },
2513        )?
2514    };
2515    Ok(result.message)
2516}
2517
2518/// 把“结果未知,必须先对账”写成运行时事实的端口适配器(对账判定唯一口径在 qx-genglu 的 `order_reconcile_verdict`,本端口只落事实、不复制判定)。
2519///
2520/// Paper、CCXT 与 Binance worker 共用同一条写入路径:`source_seq` 由端口独占推进,
2521/// correlation id 形如 `<worker>:<tag>:<client_order_id>`(`tag` 默认 `reconcile`,
2522/// 各 worker 用自己的分类标签以保持既有审计口径)。`reason` 不会进入事件载荷
2523/// (EventLog schema 不变),但必须非空,并在写入失败时随错误一起返回,避免
2524/// “未知结果”连原因都留不下。
2525pub struct EventLogReconcilePort<'a, P: EventAppender> {
2526    pipeline: &'a mut P,
2527    worker_id: &'a str,
2528    now: u64,
2529    source_seq: &'a mut u64,
2530    event_ts: u64,
2531    tag: &'static str,
2532}
2533
2534impl<'a, P: EventAppender> EventLogReconcilePort<'a, P> {
2535    pub fn new(pipeline: &'a mut P, worker_id: &'a str, now: u64, source_seq: &'a mut u64) -> Self {
2536        Self {
2537            pipeline,
2538            worker_id,
2539            now,
2540            source_seq,
2541            event_ts: now,
2542            tag: "reconcile",
2543        }
2544    }
2545
2546    /// 事件时间取远端回报时间,`now` 仍是本地接收时间。
2547    pub fn at_event_ts(mut self, event_ts: u64) -> Self {
2548        self.event_ts = event_ts;
2549        self
2550    }
2551
2552    /// 覆盖 correlation id 的分类标签,保持各 worker 既有口径不变。
2553    pub fn with_tag(mut self, tag: &'static str) -> Self {
2554        self.tag = tag;
2555        self
2556    }
2557
2558    /// 把「结果未知,必须先对账」落成运行时事实。私有在 trait 里时编译器不会把它当
2559    /// 公共面,现在 trait 已删(全仓无 `dyn ReconcilePort`、无 `T: ReconcilePort` 约束,
2560    /// 三个调用点都拿具体类型 `EventLogReconcilePort` 直接调),所以方法必须显式 `pub`。
2561    pub fn require_reconcile(&mut self, client_order_id: u64, reason: &str) -> Result<(), String> {
2562        let reason = reason.trim();
2563        if reason.is_empty() {
2564            return Err(format!(
2565                "标记订单 {client_order_id} 待对账失败: 缺少未知结果的原因"
2566            ));
2567        }
2568        *self.source_seq = self.source_seq.saturating_add(1);
2569        let source_seq = *self.source_seq;
2570        self.pipeline
2571            .append_execution_event(ExecutionEventEnvelope {
2572                event: ExecutionEvent::ReconcileRequired { client_order_id },
2573                event_ts: self.event_ts,
2574                receive_ts: self.now,
2575                source_seq,
2576                correlation_id: format!("{}:{}:{client_order_id}", self.worker_id, self.tag),
2577            })
2578            .map_err(|error| format!("{error};待对账原因: {reason}"))
2579    }
2580}
2581
2582/// Paper 执行的统一单轨入口:风控预检、行情门禁与事实写入语义只由执行端口决定。
2583///
2584/// 具体 EventLog 后端(文件/分段、SQLite、PostgreSQL)由调用方按运行时配置打开并
2585/// 注入,本 crate 不再感知任何后端与特性开关,因此 Paper、Live 与自定义运行时共用
2586/// 同一条判定链。`allow_synthetic_quote` 是**唯一**的伪造价开关,只允许离线 smoke
2587/// fixture 显式传 `true`;生产 worker 必须保持 `false` 并提供 `Some(market_quote)`。
2588/// `fee_model` 同理:成本口径由调用方显式给出,不留"默认零费"的口子(V11 §4.1)。
2589pub fn execute_paper_submit_effect<P: ExecutionEventPort + application::LedgerProbe>(
2590    request: PaperSubmitRequest<'_, P>,
2591) -> Result<String, String> {
2592    let PaperSubmitRequest {
2593        command,
2594        pipeline,
2595        now,
2596        risk,
2597        position,
2598        market_quote,
2599        fee_model,
2600        allow_synthetic_quote,
2601        spread_store,
2602    } = request;
2603    // 多腿屏障由网关统一裁决:带 `spread_group_id` 的腿若提交路径没有注入组存储,
2604    // 无法证明组干净,直接 fail-closed(见 [`spread_group_barrier`])。
2605    spread_group_barrier(spread_store, command)?;
2606    let order = order_from_submit_command(command)
2607        .map_err(|error| format!("Paper SubmitOrder 订单载荷非法: {error:?}"))?;
2608    // fail-closed:风控上下文与持仓快照必须成对提供。`(None, None)` 过去会跳过
2609    // 账户级预检直接下单,等价于风控缺失时 fail-open,现已禁止。消息保留
2610    // `FAIL_CLOSED:` 前缀,供 CLI 与监控按前缀分类拒绝原因。
2611    let (risk_context, position_snapshot) = match (risk.as_ref(), position.as_ref()) {
2612        (Some(risk), Some(position)) => (risk, position),
2613        _ => {
2614            return Err(
2615                "FAIL_CLOSED: risk context missing: RiskContext and OrderRiskPosition required"
2616                    .into(),
2617            )
2618        }
2619    };
2620    // fail-closed:撮合行情必须来自 EventLog 的真实行情事实;缺行情时不再伪造
2621    // `100` 盘口价。`allow_synthetic_quote` 只允许离线 smoke fixture 显式开启。
2622    if market_quote.is_none() && !allow_synthetic_quote {
2623        return Err("FAIL_CLOSED: market quote missing: EventLog quote is required".into());
2624    }
2625    let quote = market_quote.unwrap_or_else(|| {
2626        // WARN: 合成盘口仅供 Paper smoke fixture 使用(显式 opt-in)。生产路径
2627        // 必须传入最新行情事实,否则上面的分支已经以 fail-closed 拒绝撮合。
2628        let ask = order.limit.unwrap_or_else(|| Price::from_i64(100));
2629        let bid = Price::from_raw(ask.raw().saturating_sub(qx_core::SCALE));
2630        QuoteTick::new(
2631            now.saturating_add(1),
2632            bid,
2633            Quantity::from_i64(1_000),
2634            ask,
2635            Quantity::from_i64(1_000),
2636            1,
2637        )
2638    });
2639    validate_paper_quote(&quote)?;
2640    let mut venue = PaperVenue::new("paper", fee_model);
2641    if order.exact_amounts.is_some() {
2642        let spec = risk_context.instrument_spec.clone().ok_or_else(|| {
2643            "FAIL_CLOSED: Paper exact order 缺少冻结 market spec 和结算币种".to_string()
2644        })?;
2645        venue
2646            .set_instrument_spec(spec)
2647            .map_err(|error| format!("Paper 冻结 market spec 配置失败: {error:?}"))?;
2648    }
2649    let mut source_seq = 0_u64;
2650    // Paper 与 worker/实盘共用同一副作用编排(`ExecutionGateway` = `PortExecutionService`):
2651    // 空的 Venue 回报同样要转成"未知结果 → 待对账",不允许第二套实现各自解释。
2652    let risk_port = RiskContextPort {
2653        risk: risk_context,
2654        position: position_snapshot,
2655    };
2656    let submit_result = {
2657        let mut venue_port = BorrowedVenuePort::new(&mut venue);
2658        let mut gateway = ExecutionGateway::new(
2659            &mut venue_port,
2660            pipeline,
2661            "paper-execution",
2662            now,
2663            &mut source_seq,
2664        );
2665        if let Some(store) = spread_store {
2666            gateway = gateway.with_spread_group_store(store);
2667        }
2668        let message = match risk_context.instrument_spec.clone() {
2669            Some(spec) => {
2670                gateway
2671                    .with_instrument_spec(spec)
2672                    .submit_command_with_risk(command, &risk_port)?
2673                    .message
2674            }
2675            None => {
2676                gateway
2677                    .submit_command_with_risk(command, &risk_port)?
2678                    .message
2679            }
2680        };
2681        message
2682    };
2683    if submit_result.starts_with("ALREADY_APPLIED_FROM_EVENT_LOG") {
2684        return Ok(submit_result);
2685    }
2686    let quote_seq = if quote.source_seq == 0 {
2687        1
2688    } else {
2689        quote.source_seq
2690    };
2691    pipeline.append_execution_event(ExecutionEventEnvelope {
2692        event: ExecutionEvent::MarketQuote {
2693            instrument: order.instrument.clone(),
2694            quote,
2695        },
2696        event_ts: now.saturating_add(1),
2697        receive_ts: now.saturating_add(1),
2698        source_seq: quote_seq,
2699        correlation_id: format!("paper-execution:market:{}:{quote_seq}", order.instrument),
2700    })?;
2701    let fills = venue
2702        .try_on_quote(&order.instrument, quote)
2703        .map_err(|error| format!("Paper 精确撮合失败: {error:?}"))?;
2704    let fill_count = fills.len();
2705    if let Some(spec) = risk_context.instrument_spec.as_ref() {
2706        ingest_venue_events_with_spec(
2707            pipeline,
2708            fills,
2709            "paper-execution",
2710            quote.ts,
2711            &mut source_seq,
2712            spec,
2713        )?;
2714    } else {
2715        ingest_venue_events(
2716            pipeline,
2717            fills,
2718            "paper-execution",
2719            quote.ts,
2720            &mut source_seq,
2721        )?;
2722    }
2723    Ok(format!(
2724        "PAPER_EXECUTED fills={} ledger_entries={}",
2725        fill_count,
2726        pipeline.ledger_entry_count()
2727    ))
2728}
2729
2730fn validate_paper_quote(quote: &QuoteTick) -> Result<(), String> {
2731    let project = |raw: i128, exact: Option<ExactDecimal>, label: &str| match exact {
2732        Some(value) => {
2733            if !value.is_positive() {
2734                return Err(format!("Paper {label} 精确值必须为正数"));
2735            }
2736            let projected = value
2737                .checked_mul_at_scale(ExactDecimal::ONE, 9, DecimalRounding::TowardZero)
2738                .and_then(|value| value.to_raw(9).ok());
2739            if projected != Some(raw) {
2740                return Err(format!("Paper {label} 精确值与兼容投影不一致"));
2741            }
2742            Ok(value)
2743        }
2744        None if raw > 0 => ExactDecimal::from_parts(raw, 9)
2745            .map_err(|error| format!("Paper {label} 兼容值非法: {error}")),
2746        None => Err(format!("Paper {label} 缺少正数行情")),
2747    };
2748    let bid = project(quote.bid.raw(), quote.bid_exact, "bid")?;
2749    let ask = project(quote.ask.raw(), quote.ask_exact, "ask")?;
2750    if bid.checked_cmp(ask).is_none_or(|ordering| ordering.is_gt()) {
2751        return Err("Paper 行情买卖价交叉或无法比较".into());
2752    }
2753    project(quote.bid_qty.raw(), quote.bid_qty_exact, "bid quantity")?;
2754    project(quote.ask_qty.raw(), quote.ask_qty_exact, "ask quantity")?;
2755    Ok(())
2756}
2757
2758#[cfg(test)]
2759mod tests;