Skip to main content

qx_control/
lib.rs

1//! 控制面契约。
2//!
3//! 所有写操作都先变成带权限、原因和请求 ID 的 `ControlCommand`,由上层执行器
4//! 再决定如何调用策略运行时、OMS 或 Scheduler。本 crate 不提供绕过风控的快捷写入。
5
6use qx_core::{Fnv1a, Order, OrderStatus, QxError, QxResult};
7use serde::{Deserialize, Serialize};
8use std::collections::{BTreeMap, BTreeSet};
9
10#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]
11pub enum Permission {
12    ReadOnly,
13    Research,
14    Trading,
15    Admin,
16}
17
18#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
19pub enum CommandKind {
20    SubmitOrder,
21    SubmitOrderGroup,
22    AmendOrder,
23    PauseStrategy,
24    ResumeStrategy,
25    ChangeRiskLimit,
26    CancelOrder,
27    ReconcileAccount,
28    RetryJob,
29    SwitchVenue,
30    CancelOrderGroup,
31}
32
33impl CommandKind {
34    fn required_permission(&self) -> Permission {
35        match self {
36            Self::RetryJob => Permission::Research,
37            Self::SubmitOrder
38            | Self::SubmitOrderGroup
39            | Self::AmendOrder
40            | Self::ReconcileAccount => Permission::Trading,
41            Self::PauseStrategy
42            | Self::ResumeStrategy
43            | Self::CancelOrder
44            | Self::CancelOrderGroup => Permission::Trading,
45            Self::ChangeRiskLimit | Self::SwitchVenue => Permission::Admin,
46        }
47    }
48
49    /// 这一份构建里**真的有执行者**的命令类型:提交/改单/撤单 worker 按它裁决,其余变体在仓内没有任何
50    /// 派发者,接受了只会以 `Accepted` 永远停在审计里(新增变体默认落在"拒绝"这一侧)。
51    /// 判定式与执行者文件的对应关系由常驻用例 `control_command_kinds_match_executors` 钉住。
52    pub fn executed(&self) -> bool {
53        matches!(
54            self,
55            Self::SubmitOrder
56                | Self::SubmitOrderGroup
57                | Self::AmendOrder
58                | Self::CancelOrder
59                | Self::CancelOrderGroup
60                | Self::PauseStrategy
61                | Self::ResumeStrategy
62        )
63    }
64
65    /// 全部变体,供用例与文档按序遍历(新增变体必须在这里出现,否则用例会红)。
66    pub const ALL: [CommandKind; 11] = [
67        Self::SubmitOrder,
68        Self::SubmitOrderGroup,
69        Self::AmendOrder,
70        Self::PauseStrategy,
71        Self::ResumeStrategy,
72        Self::ChangeRiskLimit,
73        Self::CancelOrder,
74        Self::ReconcileAccount,
75        Self::RetryJob,
76        Self::SwitchVenue,
77        Self::CancelOrderGroup,
78    ];
79}
80
81#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
82#[serde(deny_unknown_fields)]
83pub struct ControlCommand {
84    pub command_id: u64,
85    pub request_id: String,
86    pub operator_id: String,
87    pub reason: String,
88    pub kind: CommandKind,
89    pub target: String,
90    pub payload: BTreeMap<String, String>,
91    pub permission: Permission,
92    pub dry_run: bool,
93}
94
95/// CancelOrder 的路由声明。账户和 venue 必须由实时 worker 再与 EventLog 中的权威订单核对。
96#[derive(Clone, Debug, PartialEq, Eq)]
97pub struct CancelOrderTarget {
98    pub client_order_id: u64,
99    pub account_id: String,
100    pub venue_id: String,
101}
102
103/// CancelOrderGroup resolves its group ID against the worker's durable order-group store.
104#[derive(Clone, Debug, PartialEq, Eq)]
105pub struct CancelOrderGroupTarget {
106    pub group_id: String,
107    pub account_id: String,
108    pub venue_id: String,
109}
110
111fn parse_cancel_order_group_target(
112    command: &ControlCommand,
113) -> Result<CancelOrderGroupTarget, ControlError> {
114    if command.kind != CommandKind::CancelOrderGroup {
115        return Err(ControlError::Invalid(
116            "控制命令不是 CancelOrderGroup".into(),
117        ));
118    }
119    let group_id = command.target.trim();
120    if group_id.is_empty() || group_id.len() > 128 {
121        return Err(ControlError::Invalid(
122            "CancelOrderGroup target 必须是 1 至 128 字符的 group_id".into(),
123        ));
124    }
125    if command.payload.len() != 2
126        || !command.payload.contains_key("account_id")
127        || !command.payload.contains_key("venue_id")
128    {
129        return Err(ControlError::Invalid(
130            "CancelOrderGroup payload 必须且只能包含 account_id 和 venue_id".into(),
131        ));
132    }
133    let account_id = command.payload["account_id"].trim();
134    let venue_id = command.payload["venue_id"].trim();
135    if account_id.is_empty() || venue_id.is_empty() {
136        return Err(ControlError::Invalid(
137            "CancelOrderGroup account_id/venue_id 不能为空".into(),
138        ));
139    }
140    Ok(CancelOrderGroupTarget {
141        group_id: group_id.to_owned(),
142        account_id: account_id.to_owned(),
143        venue_id: venue_id.to_owned(),
144    })
145}
146
147pub fn cancel_order_group_target_from_command(
148    command: &ControlCommand,
149) -> Result<CancelOrderGroupTarget, ControlError> {
150    command.validate()?;
151    parse_cancel_order_group_target(command)
152}
153
154#[derive(Clone, Debug, PartialEq, Eq)]
155pub struct AmendOrderTarget {
156    pub client_order_id: u64,
157    pub account_id: String,
158    pub venue_id: String,
159    pub order: Order,
160}
161
162fn parse_cancel_order_target(command: &ControlCommand) -> Result<CancelOrderTarget, ControlError> {
163    if command.kind != CommandKind::CancelOrder {
164        return Err(ControlError::Invalid("控制命令不是 CancelOrder".into()));
165    }
166    let client_order_id = command
167        .target
168        .parse::<u64>()
169        .ok()
170        .filter(|value| *value > 0)
171        .ok_or_else(|| {
172            ControlError::Invalid("CancelOrder target 必须是正整数 client_order_id".into())
173        })?;
174    if command.payload.len() != 2
175        || !command.payload.contains_key("account_id")
176        || !command.payload.contains_key("venue_id")
177    {
178        return Err(ControlError::Invalid(
179            "CancelOrder payload 必须且只能包含 account_id 和 venue_id".into(),
180        ));
181    }
182    let account_id = command.payload["account_id"].trim();
183    let venue_id = command.payload["venue_id"].trim();
184    if account_id.is_empty() || venue_id.is_empty() {
185        return Err(ControlError::Invalid(
186            "CancelOrder account_id/venue_id 不能为空".into(),
187        ));
188    }
189    Ok(CancelOrderTarget {
190        client_order_id,
191        account_id: account_id.to_owned(),
192        venue_id: venue_id.to_owned(),
193    })
194}
195
196/// Parse the explicit routing identity for a cancellation command. The execution worker must
197/// independently bind this identity to the authoritative order snapshot before contacting a venue.
198pub fn cancel_order_target_from_command(
199    command: &ControlCommand,
200) -> Result<CancelOrderTarget, ControlError> {
201    command.validate()?;
202    parse_cancel_order_target(command)
203}
204
205fn parse_amend_order_target(command: &ControlCommand) -> Result<AmendOrderTarget, ControlError> {
206    if command.kind != CommandKind::AmendOrder {
207        return Err(ControlError::Invalid("控制命令不是 AmendOrder".into()));
208    }
209    let client_order_id = command
210        .target
211        .parse::<u64>()
212        .ok()
213        .filter(|value| *value > 0)
214        .ok_or_else(|| ControlError::Invalid("AmendOrder target 必须是正整数订单 ID".into()))?;
215    if command.payload.len() != 3
216        || !command.payload.contains_key("account_id")
217        || !command.payload.contains_key("venue_id")
218        || !command.payload.contains_key("order_json")
219    {
220        return Err(ControlError::Invalid(
221            "AmendOrder payload 必须且只能包含 account_id、venue_id、order_json".into(),
222        ));
223    }
224    let account_id = command.payload["account_id"].trim();
225    let venue_id = command.payload["venue_id"].trim();
226    if account_id.is_empty() || venue_id.is_empty() {
227        return Err(ControlError::Invalid(
228            "AmendOrder account_id/venue_id 不能为空".into(),
229        ));
230    }
231    let order: Order = serde_json::from_str(&command.payload["order_json"])
232        .map_err(|error| ControlError::Invalid(format!("AmendOrder order_json 非法: {error}")))?;
233    order.validate().map_err(|error| {
234        ControlError::Invalid(format!("AmendOrder order_json 校验失败: {error}"))
235    })?;
236    if order.client_id != client_order_id
237        || order.account_id != account_id
238        || !order
239            .instrument
240            .venue
241            .as_str()
242            .eq_ignore_ascii_case(venue_id)
243        || !matches!(
244            order.status,
245            OrderStatus::Accepted | OrderStatus::Working | OrderStatus::PartiallyFilled
246        )
247    {
248        return Err(ControlError::Invalid(
249            "AmendOrder target、账户、交易所或活动订单状态不匹配".into(),
250        ));
251    }
252    Ok(AmendOrderTarget {
253        client_order_id,
254        account_id: account_id.to_owned(),
255        venue_id: venue_id.to_owned(),
256        order,
257    })
258}
259
260pub fn amend_order_target_from_command(
261    command: &ControlCommand,
262) -> Result<AmendOrderTarget, ControlError> {
263    command.validate()?;
264    parse_amend_order_target(command)
265}
266
267impl ControlCommand {
268    pub fn validate(&self) -> Result<(), ControlError> {
269        if self.request_id.trim().is_empty()
270            || self.operator_id.trim().is_empty()
271            || self.reason.trim().is_empty()
272            || self.target.trim().is_empty()
273        {
274            return Err(ControlError::Invalid("控制命令缺少审计字段".into()));
275        }
276        if !has_permission(self.permission, self.kind.required_permission()) {
277            return Err(ControlError::Forbidden);
278        }
279        if self.kind == CommandKind::CancelOrder {
280            parse_cancel_order_target(self)?;
281        }
282        if self.kind == CommandKind::CancelOrderGroup {
283            parse_cancel_order_group_target(self)?;
284        }
285        if self.kind == CommandKind::AmendOrder {
286            parse_amend_order_target(self)?;
287        }
288        Ok(())
289    }
290
291    /// 校验请求方声明的权限是否真的不超过服务端授予的权限。
292    ///
293    /// `permission` 是审计字段,不是认证凭据;生产入口必须把外部身份解析成
294    /// `granted` 后调用本方法,不能只调用无身份的 `validate`。
295    pub fn validate_as(&self, granted: Permission) -> Result<(), ControlError> {
296        if !has_permission(granted, self.permission)
297            || !has_permission(granted, self.kind.required_permission())
298        {
299            return Err(ControlError::Forbidden);
300        }
301        self.validate()?;
302        self.validate_submission_target()
303    }
304
305    fn validate_submission_target(&self) -> Result<(), ControlError> {
306        if matches!(
307            &self.kind,
308            CommandKind::PauseStrategy | CommandKind::ResumeStrategy
309        ) && self.target == "*"
310        {
311            return Err(ControlError::Invalid(
312                "strategy lifecycle commands require an explicit worker target".into(),
313            ));
314        }
315        Ok(())
316    }
317
318    pub fn digest(&self) -> u64 {
319        let mut h = Fnv1a::new();
320        h.write_u64(self.command_id);
321        h.write_text(&self.request_id);
322        h.write_text(&self.operator_id);
323        h.write_text(&self.reason);
324        h.write_text(&format!("{:?}", self.kind));
325        h.write_text(&self.target);
326        for (key, value) in &self.payload {
327            h.write_text(key);
328            h.write_text(value);
329        }
330        h.write_u64(self.dry_run as u64);
331        h.finish()
332    }
333}
334
335/// 控制命令的审计状态。只有三个变体:受理,以及执行后的两种终态。
336///
337/// 这里**没有** `Rejected`(V13 R1-H 重落 V11 R6-1,那份交付面被合流 c07ad22 覆盖掉了)。
338/// 拒绝发生在受理之前——`submit`/`submit_as` 校验不过就返回 `ControlError`,命令与审计记录
339/// 都不会落盘,所以"已拒绝"从来不是一个能被写出来的审计状态。留着一个零构造者的变体,
340/// 会让每个 `match` 都多一条永不为真的臂,读代码的人得逐个去证它走不到。
341#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]
342pub enum CommandStatus {
343    Accepted,
344    Executed,
345    Failed,
346}
347
348impl CommandStatus {
349    /// 表达式位置上的唯一终态判据:待办筛选、`execute` 的 `AlreadyFinal`、恢复校验与
350    /// 调用方的"这条命令还动得了吗"共用这一颗。
351    pub const fn is_final(self) -> bool {
352        matches!(self, Self::Executed | Self::Failed)
353    }
354}
355
356#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
357pub struct AuditRecord {
358    pub command_id: u64,
359    pub request_id: String,
360    pub operator_id: String,
361    pub command_digest: u64,
362    pub status: CommandStatus,
363    pub result_code: String,
364    pub ts: u64,
365}
366
367pub const CONTROL_AUDIT_RECORD_SCHEMA_VERSION_V1: u32 = 1;
368pub const CONTROL_AUDIT_PAGE_SCHEMA_VERSION_V1: u32 = 1;
369pub const CONTROL_AUDIT_DEFAULT_PAGE_SIZE: usize = 100;
370pub const CONTROL_AUDIT_MAX_PAGE_SIZE: usize = 1_000;
371pub const CONTROL_AUDIT_MAX_PAGE_BYTES: usize = 1_048_576;
372
373/// Versioned public response used by Paper/Live command submission and audit recovery routes.
374#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
375#[serde(try_from = "ControlAuditRecordV1Raw")]
376pub struct ControlAuditRecordV1 {
377    pub schema_version: u32,
378    pub command_id: u64,
379    pub request_id: String,
380    pub operator_id: String,
381    pub command_digest: u64,
382    pub status: CommandStatus,
383    pub result_code: String,
384    pub ts: u64,
385}
386
387#[derive(Deserialize)]
388#[serde(deny_unknown_fields)]
389struct ControlAuditRecordV1Raw {
390    schema_version: u32,
391    command_id: u64,
392    request_id: String,
393    operator_id: String,
394    command_digest: u64,
395    status: CommandStatus,
396    result_code: String,
397    ts: u64,
398}
399
400impl TryFrom<ControlAuditRecordV1Raw> for ControlAuditRecordV1 {
401    type Error = &'static str;
402
403    fn try_from(raw: ControlAuditRecordV1Raw) -> Result<Self, Self::Error> {
404        if raw.schema_version != CONTROL_AUDIT_RECORD_SCHEMA_VERSION_V1 {
405            return Err("unsupported control audit record schema version");
406        }
407        if raw.request_id.trim().is_empty() || raw.operator_id.trim().is_empty() {
408            return Err("control audit record identities must not be empty");
409        }
410        Ok(Self {
411            schema_version: raw.schema_version,
412            command_id: raw.command_id,
413            request_id: raw.request_id,
414            operator_id: raw.operator_id,
415            command_digest: raw.command_digest,
416            status: raw.status,
417            result_code: raw.result_code,
418            ts: raw.ts,
419        })
420    }
421}
422
423impl From<&AuditRecord> for ControlAuditRecordV1 {
424    fn from(record: &AuditRecord) -> Self {
425        Self {
426            schema_version: CONTROL_AUDIT_RECORD_SCHEMA_VERSION_V1,
427            command_id: record.command_id,
428            request_id: record.request_id.clone(),
429            operator_id: record.operator_id.clone(),
430            command_digest: record.command_digest,
431            status: record.status,
432            result_code: record.result_code.clone(),
433            ts: record.ts,
434        }
435    }
436}
437
438/// One audit row with its durable append sequence. The sequence is separate from the legacy
439/// persisted `AuditRecord` so the existing storage/audit-chain wire format remains unchanged.
440#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
441#[serde(deny_unknown_fields)]
442pub struct ControlAuditEntryV1 {
443    pub sequence: u64,
444    pub record: ControlAuditRecordV1,
445}
446
447/// Bounded, snapshot-consistent page returned by `GET /control/audit`.
448#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
449#[serde(try_from = "ControlAuditPageV1Raw")]
450pub struct ControlAuditPageV1 {
451    pub schema_version: u32,
452    pub entries: Vec<ControlAuditEntryV1>,
453    pub next_cursor: Option<String>,
454    pub has_more: bool,
455    pub snapshot_through_sequence: u64,
456    pub oldest_available_sequence: Option<u64>,
457    pub retired_records: u64,
458}
459
460#[derive(Deserialize)]
461#[serde(deny_unknown_fields)]
462struct ControlAuditPageV1Raw {
463    schema_version: u32,
464    entries: Vec<ControlAuditEntryV1>,
465    next_cursor: Option<String>,
466    has_more: bool,
467    snapshot_through_sequence: u64,
468    oldest_available_sequence: Option<u64>,
469    retired_records: u64,
470}
471
472impl TryFrom<ControlAuditPageV1Raw> for ControlAuditPageV1 {
473    type Error = &'static str;
474
475    fn try_from(raw: ControlAuditPageV1Raw) -> Result<Self, Self::Error> {
476        if raw.schema_version != CONTROL_AUDIT_PAGE_SCHEMA_VERSION_V1 {
477            return Err("unsupported control audit page schema version");
478        }
479        if raw.entries.len() > CONTROL_AUDIT_MAX_PAGE_SIZE {
480            return Err("control audit page exceeds the maximum entry count");
481        }
482        if raw.has_more != raw.next_cursor.is_some() {
483            return Err("control audit page has_more and next_cursor disagree");
484        }
485        if raw.has_more && raw.entries.is_empty() {
486            return Err("control audit page cannot continue without an entry");
487        }
488        if raw
489            .entries
490            .windows(2)
491            .any(|pair| pair[0].sequence <= pair[1].sequence)
492        {
493            return Err("control audit page sequences must be strictly decreasing");
494        }
495        if raw
496            .entries
497            .iter()
498            .any(|entry| entry.sequence == 0 || entry.sequence > raw.snapshot_through_sequence)
499        {
500            return Err("control audit entry sequence is outside the page snapshot");
501        }
502        if raw
503            .oldest_available_sequence
504            .is_some_and(|sequence| sequence == 0)
505        {
506            return Err("oldest available control audit sequence must be non-zero");
507        }
508        if raw
509            .oldest_available_sequence
510            .is_some_and(|sequence| sequence > raw.snapshot_through_sequence)
511        {
512            return Err("oldest available sequence is outside the page snapshot");
513        }
514        if let Some(cursor) = raw.next_cursor.as_deref() {
515            let decoded = ControlAuditCursorV1::decode(cursor)?;
516            if decoded.through_sequence != raw.snapshot_through_sequence
517                || raw.entries.last().map(|entry| entry.sequence) != Some(decoded.before_sequence)
518            {
519                return Err("control audit next_cursor does not match its final entry");
520            }
521        }
522        let page = Self {
523            schema_version: raw.schema_version,
524            entries: raw.entries,
525            next_cursor: raw.next_cursor,
526            has_more: raw.has_more,
527            snapshot_through_sequence: raw.snapshot_through_sequence,
528            oldest_available_sequence: raw.oldest_available_sequence,
529            retired_records: raw.retired_records,
530        };
531        if serde_json::to_vec(&page)
532            .map_err(|_| "control audit page serialization failed")?
533            .len()
534            > CONTROL_AUDIT_MAX_PAGE_BYTES
535        {
536            return Err("control audit page exceeds the maximum response byte budget");
537        }
538        Ok(page)
539    }
540}
541
542#[derive(Clone, Copy, PartialEq, Eq, Debug)]
543struct ControlAuditCursorV1 {
544    before_sequence: u64,
545    through_sequence: u64,
546}
547
548impl ControlAuditCursorV1 {
549    fn encode(self) -> String {
550        format!("v1.{}.{}", self.before_sequence, self.through_sequence)
551    }
552
553    fn decode(value: &str) -> Result<Self, &'static str> {
554        let mut parts = value.split('.');
555        if parts.next() != Some("v1") {
556            return Err("unsupported control audit cursor version");
557        }
558        let before_sequence = parts
559            .next()
560            .ok_or("control audit cursor is incomplete")?
561            .parse::<u64>()
562            .map_err(|_| "control audit cursor has an invalid after sequence")?;
563        let through_sequence = parts
564            .next()
565            .ok_or("control audit cursor is incomplete")?
566            .parse::<u64>()
567            .map_err(|_| "control audit cursor has an invalid snapshot sequence")?;
568        if parts.next().is_some() || before_sequence > through_sequence {
569            return Err("control audit cursor is invalid");
570        }
571        Ok(Self {
572            before_sequence,
573            through_sequence,
574        })
575    }
576}
577
578#[derive(Debug, PartialEq, Eq)]
579pub enum ControlError {
580    Invalid(String),
581    Forbidden,
582    PendingLimitReached,
583    DuplicateRequest(String),
584    DuplicateCommand(u64),
585    UnknownCommand(u64),
586    AlreadyFinal(u64),
587}
588
589/// 从已通过控制面校验的 SubmitOrder 载荷解析订单,并再次校验命令身份边界。
590///
591/// 这是控制命令与领域订单之间的唯一解析入口,放在控制面契约层,避免
592/// Runtime、Execution 和 CLI 各自复制一套 `order_json`/target 校验逻辑。
593pub fn order_from_submit_command(command: &ControlCommand) -> QxResult<Order> {
594    command.validate().map_err(|error| {
595        QxError::BusinessViolation(format!("SubmitOrder 控制命令非法: {error:?}"))
596    })?;
597    if command.kind != CommandKind::SubmitOrder {
598        return Err(QxError::BusinessViolation(
599            "控制命令不是 SubmitOrder".into(),
600        ));
601    }
602    let payload = command
603        .payload
604        .get("order_json")
605        .ok_or_else(|| QxError::BusinessViolation("SubmitOrder 缺少 order_json".into()))?;
606    let order: Order = serde_json::from_str(payload)
607        .map_err(|error| QxError::BusinessViolation(format!("order_json 非法: {error}")))?;
608    if command.target != order.client_id.to_string() {
609        return Err(QxError::BusinessViolation(
610            "SubmitOrder target 与 order.client_id 不一致".into(),
611        ));
612    }
613    order.validate().map_err(QxError::BusinessViolation)?;
614    if !matches!(
615        order.status,
616        OrderStatus::PendingSubmit | OrderStatus::Submitted
617    ) {
618        return Err(QxError::BusinessViolation(
619            "SubmitOrder 只接受 PendingSubmit 或 Submitted 订单".into(),
620        ));
621    }
622    Ok(order)
623}
624
625/// Parse and bind an atomic OCO/Bracket intent to an audited control command.
626pub fn order_group_from_submit_command(
627    command: &ControlCommand,
628) -> QxResult<qx_core::OrderGroupIntent> {
629    command.validate().map_err(|error| {
630        QxError::BusinessViolation(format!("SubmitOrderGroup 控制命令非法: {error:?}"))
631    })?;
632    if command.kind != CommandKind::SubmitOrderGroup {
633        return Err(QxError::BusinessViolation(
634            "控制命令不是 SubmitOrderGroup".into(),
635        ));
636    }
637    if command.payload.len() != 1 || !command.payload.contains_key("order_group_json") {
638        return Err(QxError::BusinessViolation(
639            "SubmitOrderGroup payload 必须且只能包含 order_group_json".into(),
640        ));
641    }
642    let group: qx_core::OrderGroupIntent =
643        serde_json::from_str(&command.payload["order_group_json"]).map_err(|error| {
644            QxError::BusinessViolation(format!("order_group_json 非法: {error}"))
645        })?;
646    group.validate().map_err(QxError::BusinessViolation)?;
647    if command.target != group.group_id {
648        return Err(QxError::BusinessViolation(
649            "SubmitOrderGroup target 与 group_id 不一致".into(),
650        ));
651    }
652    Ok(group)
653}
654
655/// 控制面终态命令的保留上界。`commands` / `requests` / `audit` 三格只追加不退场,长跑进程
656/// 每受理一条命令就永久留下三处条目;越过上界按「终态审计写入顺序最早」退场(V13 R1-H 重落 V11 R5-1,
657/// 那份交付面被合流 c07ad22 按上游树整体裁定覆盖掉了)。
658///
659/// 只退**终态**命令:`pending()` 靠 `finalized_command_ids()` 判待办,退掉一条未终态的命令等于
660/// 把一条已受理、还没人执行的命令静默丢掉。三格必须同时删——`from_json` 逐条核对「审计记录
661/// 指向的命令存在」与「每条命令至少一条审计记录」,只删一边,重启恢复就会拒读自己写的历史。
662pub const FINALIZED_COMMAND_RETENTION: usize = 4096;
663/// Maximum number of accepted commands that have not yet reached a terminal audit status.
664/// Pending work is never retired silently; new submissions fail closed until workers make room.
665pub const PENDING_CONTROL_COMMAND_LIMIT: usize = 4096;
666
667/// 退场摘要。控制面的**持久**审计在 `qx-storage`(`AuditFileStore`/`SqliteAuditStore`/
668/// `PostgresAuditStore` + 哈希链),这一份只是内存
669/// 工作集;退场把它压回上界之内,而压掉了多少必须有个能被读到的数——否则「有界」这句话没有
670/// 证据面。读者是 `/metrics` 的 `qx_control_retired_commands_total` 与
671/// `qx_control_retired_audit_records_total` 两条,以及持久化 JSON 里的同名字段。
672#[derive(Clone, Copy, Default, PartialEq, Eq, Debug, Serialize, Deserialize)]
673pub struct RetirementSummary {
674    pub retired_commands: u64,
675    pub retired_audit_records: u64,
676}
677
678#[derive(Clone, Default, Serialize, Deserialize)]
679pub struct ControlPlane {
680    commands: BTreeMap<u64, ControlCommand>,
681    requests: BTreeMap<String, u64>,
682    audit: Vec<AuditRecord>,
683    /// Append sequence stored beside legacy audit rows so the existing audit-chain record shape
684    /// remains unchanged. These fields are validated and migrated together on restore.
685    #[serde(default)]
686    audit_sequences: Vec<u64>,
687    /// Per-command sequence lookup keeps request-id recovery bounded without changing the
688    /// legacy audit rows. It is validated against `audit` and rebuilt for older snapshots.
689    #[serde(default)]
690    audit_command_sequences: BTreeMap<u64, Vec<u64>>,
691    /// Last sequence ever assigned. Retiring rows never rewinds this durable watermark.
692    #[serde(default)]
693    audit_high_watermark: u64,
694    /// Durable O(1) admission and metrics count. Older snapshots reconstruct it from audit state.
695    #[serde(default)]
696    pending_commands_count: u64,
697    #[serde(default)]
698    strategy_lifecycle: BTreeMap<String, StrategyLifecycleRecord>,
699    #[serde(default)]
700    strategy_lifecycle_legacy_incomplete: bool,
701    /// 累计退场量。`#[serde(default)]`:合流之前落盘的控制面 JSON 没有这一格,恢复时必须
702    /// 读得回来,否则一次升级就拒读自己的历史。
703    #[serde(default)]
704    retired: RetirementSummary,
705}
706
707/// Latest successful lifecycle command, retained independently of bounded audit history.
708#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
709#[serde(deny_unknown_fields)]
710pub struct StrategyLifecycleRecord {
711    pub paused: bool,
712    pub command_id: u64,
713    pub ts: u64,
714}
715
716impl ControlPlane {
717    pub fn submit(
718        &mut self,
719        command: ControlCommand,
720        ts: u64,
721    ) -> Result<AuditRecord, ControlError> {
722        command.validate()?;
723        self.submit_validated(command, ts)
724    }
725
726    /// 带服务端授权上下文的提交入口。API/Worker 应优先使用此方法。
727    pub fn submit_as(
728        &mut self,
729        command: ControlCommand,
730        granted: Permission,
731        ts: u64,
732    ) -> Result<AuditRecord, ControlError> {
733        command.validate_as(granted)?;
734        self.submit_validated(command, ts)
735    }
736
737    fn submit_validated(
738        &mut self,
739        command: ControlCommand,
740        ts: u64,
741    ) -> Result<AuditRecord, ControlError> {
742        // Reject new ambiguous commands without making legacy stored commands unreadable.
743        command.validate_submission_target()?;
744        // 只有提交入口裁决"有没有执行者":`ControlCommand::validate` 同时被恢复路径调用,
745        // 把这条规则放进 `validate` 会让历史队列里已存在的旧命令在重启时读不回来。
746        if !command.kind.executed() {
747            return Err(ControlError::Invalid(format!(
748                "{:?} 在当前构建里没有派发者,控制面不接受",
749                command.kind
750            )));
751        }
752        if self.requests.contains_key(&command.request_id) {
753            return Err(ControlError::DuplicateRequest(command.request_id));
754        }
755        if self.commands.contains_key(&command.command_id) {
756            return Err(ControlError::DuplicateCommand(command.command_id));
757        }
758        if self.pending_commands_count >= PENDING_CONTROL_COMMAND_LIMIT as u64 {
759            return Err(ControlError::PendingLimitReached);
760        }
761        let sequence = self.next_audit_sequence()?;
762        let record = AuditRecord {
763            command_id: command.command_id,
764            request_id: command.request_id.clone(),
765            operator_id: command.operator_id.clone(),
766            command_digest: command.digest(),
767            status: CommandStatus::Accepted,
768            result_code: "ACCEPTED_FOR_EXECUTION".into(),
769            ts,
770        };
771        self.requests
772            .insert(command.request_id.clone(), command.command_id);
773        self.commands.insert(command.command_id, command);
774        self.append_audit(sequence, record.clone());
775        self.retire_overflow();
776        Ok(record)
777    }
778
779    pub fn command(&self, command_id: u64) -> Option<&ControlCommand> {
780        self.commands.get(&command_id)
781    }
782
783    pub fn audit(&self) -> &[AuditRecord] {
784        &self.audit
785    }
786
787    /// Return a bounded newest-first page from a stable append-sequence snapshot. The cursor
788    /// freezes the upper sequence on the first request, so new commands cannot extend a scan.
789    pub fn audit_page(
790        &self,
791        cursor: Option<&str>,
792        limit: usize,
793        request_id: Option<&str>,
794    ) -> Result<ControlAuditPageV1, &'static str> {
795        if !(1..=CONTROL_AUDIT_MAX_PAGE_SIZE).contains(&limit) {
796            return Err("control audit page limit is outside the allowed range");
797        }
798        if request_id.is_some() && limit < 2 {
799            return Err("control audit request_id lookup requires a page limit of at least 2");
800        }
801        if cursor.is_some() && request_id.is_some() {
802            return Err("control audit cursor cannot be combined with request_id");
803        }
804        let parsed_cursor = cursor.map(ControlAuditCursorV1::decode).transpose()?;
805        let before_sequence = parsed_cursor.map(|value| value.before_sequence);
806        let through_sequence =
807            parsed_cursor.map_or(self.audit_high_watermark, |value| value.through_sequence);
808        if through_sequence > self.audit_high_watermark {
809            return Err("control audit cursor is ahead of the current durable watermark");
810        }
811        if parsed_cursor.is_some() {
812            let oldest = self.audit_sequences.first().copied();
813            let expired = match oldest {
814                Some(oldest) => oldest >= before_sequence.unwrap_or(0),
815                None => true,
816            };
817            if expired {
818                return Err("control audit cursor has expired because older rows were retired");
819            }
820        }
821
822        let mut rows = if let Some(request_id) = request_id {
823            match self.requests.get(request_id).copied() {
824                None => Vec::new(),
825                Some(command_id) => {
826                    self.audit_command_sequences
827                        .get(&command_id)
828                        .map(|sequences| {
829                            sequences
830                                .iter()
831                                .copied()
832                                .filter(|sequence| {
833                                    *sequence <= through_sequence
834                                        && before_sequence.is_none_or(|before| *sequence < before)
835                                })
836                                .filter_map(|sequence| {
837                                    self.audit_sequences.binary_search(&sequence).ok().map(
838                                        |index| (&self.audit[index], &self.audit_sequences[index]),
839                                    )
840                                })
841                                .rev()
842                                .take(limit + 1)
843                                .collect::<Vec<_>>()
844                        })
845                        .unwrap_or_else(|| {
846                            // Direct Serde deserialization of legacy state may bypass `from_json`
847                            // migration. Preserve correctness there; supported storage readers rebuild
848                            // the index.
849                            self.audit
850                                .iter()
851                                .zip(&self.audit_sequences)
852                                .filter(|(record, sequence)| {
853                                    record.request_id == request_id
854                                        && **sequence <= through_sequence
855                                        && before_sequence.is_none_or(|before| **sequence < before)
856                                })
857                                .rev()
858                                .take(limit + 1)
859                                .collect::<Vec<_>>()
860                        })
861                }
862            }
863        } else {
864            let snapshot_end = self
865                .audit_sequences
866                .partition_point(|sequence| *sequence <= through_sequence);
867            let page_end = before_sequence.map_or(snapshot_end, |before| {
868                snapshot_end.min(
869                    self.audit_sequences
870                        .partition_point(|sequence| *sequence < before),
871                )
872            });
873            let page_start = page_end.saturating_sub(limit + 1);
874            (page_start..page_end)
875                .rev()
876                .map(|index| (&self.audit[index], &self.audit_sequences[index]))
877                .collect::<Vec<_>>()
878        };
879        let mut has_more = rows.len() > limit;
880        rows.truncate(limit);
881        let entries = rows
882            .iter()
883            .map(|(record, sequence)| ControlAuditEntryV1 {
884                sequence: **sequence,
885                record: ControlAuditRecordV1::from(*record),
886            })
887            .collect::<Vec<_>>();
888        let entry_sizes = entries
889            .iter()
890            .map(|entry| serde_json::to_vec(entry).map(|bytes| bytes.len()))
891            .collect::<Result<Vec<_>, _>>()
892            .map_err(|_| "control audit page serialization failed")?;
893        let mut count = entries.len();
894        loop {
895            has_more |= count < entries.len();
896            let next_cursor = has_more.then(|| {
897                ControlAuditCursorV1 {
898                    before_sequence: entries
899                        .get(count.saturating_sub(1))
900                        .map_or(0, |entry| entry.sequence),
901                    through_sequence,
902                }
903                .encode()
904            });
905            let empty_page = ControlAuditPageV1 {
906                schema_version: CONTROL_AUDIT_PAGE_SCHEMA_VERSION_V1,
907                entries: Vec::new(),
908                next_cursor,
909                has_more,
910                snapshot_through_sequence: through_sequence,
911                oldest_available_sequence: self
912                    .audit_sequences
913                    .iter()
914                    .copied()
915                    .find(|sequence| *sequence <= through_sequence),
916                retired_records: self.retired.retired_audit_records,
917            };
918            let base_size = serde_json::to_vec(&empty_page)
919                .map_err(|_| "control audit page serialization failed")?
920                .len()
921                .saturating_sub(2);
922            let entries_size = entry_sizes[..count].iter().sum::<usize>() + count.saturating_sub(1);
923            if base_size.saturating_add(entries_size) <= CONTROL_AUDIT_MAX_PAGE_BYTES {
924                return Ok(ControlAuditPageV1 {
925                    entries: entries[..count].to_vec(),
926                    ..empty_page
927                });
928            }
929            if count <= 1 {
930                return Err("control audit record exceeds the maximum response byte budget");
931            }
932            count -= 1;
933        }
934    }
935
936    fn next_audit_sequence(&self) -> Result<u64, ControlError> {
937        self.audit_high_watermark
938            .checked_add(1)
939            .ok_or_else(|| ControlError::Invalid("control audit sequence exhausted".into()))
940    }
941
942    fn append_audit(&mut self, sequence: u64, record: AuditRecord) {
943        debug_assert_eq!(sequence, self.audit_high_watermark + 1);
944        self.audit_high_watermark = sequence;
945        if record.status.is_final() {
946            self.pending_commands_count = self.pending_commands_count.saturating_sub(1);
947        } else {
948            self.pending_commands_count = self.pending_commands_count.saturating_add(1);
949        }
950        self.audit_command_sequences
951            .entry(record.command_id)
952            .or_default()
953            .push(sequence);
954        self.audit_sequences.push(sequence);
955        self.audit.push(record);
956    }
957
958    pub fn strategy_lifecycle(&self, worker_id: &str) -> Option<&StrategyLifecycleRecord> {
959        self.strategy_lifecycle.get(worker_id)
960    }
961
962    /// Legacy snapshots with retired audit cannot prove the last lifecycle state.
963    /// Start unrecorded workers paused until an explicit resume establishes it.
964    pub fn strategy_pause_state(&self, worker_id: &str) -> Option<bool> {
965        self.strategy_lifecycle(worker_id)
966            .map(|state| state.paused)
967            .or_else(|| self.strategy_lifecycle_legacy_incomplete.then_some(true))
968    }
969
970    /// 待办命令。判据与 `execute` 的 `AlreadyFinal` 同一口径:终态审计记录一旦落下,
971    /// 这条命令就不再是待办。
972    ///
973    /// 终态集合每次现算一遍:调用方是四个 worker 的轮询循环,而 `audit` 只追加不退场,
974    /// 逐条命令回扫整段审计会把每轮轮询打成 O(commands × audit)(V13 R1-D)。
975    pub fn pending(&self) -> impl Iterator<Item = &ControlCommand> {
976        let finalized = self.finalized_command_ids();
977        self.commands
978            .values()
979            .filter(move |command| !finalized.contains(&command.command_id))
980    }
981
982    /// Number of accepted commands awaiting a terminal outcome.
983    pub fn pending_commands_count(&self) -> u64 {
984        self.pending_commands_count
985    }
986
987    /// 已落终态审计记录的 command_id 集合。`execute` 对已终态的命令回 `AlreadyFinal`,
988    /// 所以每条命令至多一条终态记录——“有没有终态记录”与“最新那条是不是终态”同解。
989    fn finalized_command_ids(&self) -> BTreeSet<u64> {
990        self.audit
991            .iter()
992            .filter(|record| record.status.is_final())
993            .map(|record| record.command_id)
994            .collect()
995    }
996
997    /// 累计退场摘要。`/metrics` 读它,运维因此能看见「控制面确实被压回上界之内」。
998    pub fn retirement(&self) -> RetirementSummary {
999        self.retired
1000    }
1001
1002    fn retire_overflow(&mut self) {
1003        self.retire_overflow_with(FINALIZED_COMMAND_RETENTION)
1004    }
1005
1006    /// 上界之外的终态命令按终态审计记录的追加顺序最早退场,命令、请求索引、审计记录三格同时删。
1007    ///
1008    /// 第一句就是规模判据:`finalized ⊆ commands`,所以命令数没越过上界时终态数也不可能越过,
1009    /// 直接返回。少了这句,每次 `submit`/`execute` 都要重扫整段审计并重建一个 `BTreeSet`,
1010    /// 受理 n 条命令的总代价是 O(n²)——那正是 `pending()` 在 R1-D 已经躲开的那种形状。
1011    fn retire_overflow_with(&mut self, retention: usize) {
1012        if self.commands.len() <= retention {
1013            return;
1014        }
1015        let finalized = self.finalized_command_ids();
1016        if finalized.len() <= retention {
1017            return;
1018        }
1019        // 系统时钟可能回拨或节点间有偏移,`ts` 不是追加顺序。审计向量保留了
1020        // ControlPlane 接受记录的先后;按终态记录在此向量中的顺序退场,避免时钟漂移
1021        // 让较新的命令先于较旧命令淘汰。`execute` 保证每条命令至多一条终态记录。
1022        let finalized_in_order: Vec<u64> = self
1023            .audit
1024            .iter()
1025            .filter(|record| record.status.is_final())
1026            .map(|record| record.command_id)
1027            .collect();
1028        let overflow = finalized_in_order.len() - retention;
1029        let victims: BTreeSet<u64> = finalized_in_order.into_iter().take(overflow).collect();
1030        let mut removed_records = 0u64;
1031        let mut retained_audit = Vec::with_capacity(self.audit.len());
1032        let mut retained_sequences = Vec::with_capacity(self.audit_sequences.len());
1033        for (record, sequence) in self.audit.drain(..).zip(self.audit_sequences.drain(..)) {
1034            if victims.contains(&record.command_id) {
1035                removed_records += 1;
1036            } else {
1037                retained_audit.push(record);
1038                retained_sequences.push(sequence);
1039            }
1040        }
1041        self.audit = retained_audit;
1042        self.audit_sequences = retained_sequences;
1043        for command_id in &victims {
1044            if let Some(command) = self.commands.remove(command_id) {
1045                self.requests.remove(&command.request_id);
1046            }
1047            self.audit_command_sequences.remove(command_id);
1048        }
1049        self.retired.retired_commands += victims.len() as u64;
1050        self.retired.retired_audit_records += removed_records;
1051    }
1052
1053    /// 执行器唯一的状态入口:执行结果必须回写审计记录,不能只返回字符串。
1054    pub fn execute<F>(
1055        &mut self,
1056        command_id: u64,
1057        ts: u64,
1058        action: F,
1059    ) -> Result<AuditRecord, ControlError>
1060    where
1061        F: FnOnce(&ControlCommand) -> Result<String, String>,
1062    {
1063        let command = self
1064            .commands
1065            .get(&command_id)
1066            .ok_or(ControlError::UnknownCommand(command_id))?;
1067        let prior = self
1068            .audit
1069            .iter()
1070            .rev()
1071            .find(|record| record.command_id == command_id)
1072            .map(|record| record.status)
1073            .ok_or(ControlError::UnknownCommand(command_id))?;
1074        if prior.is_final() {
1075            return Err(ControlError::AlreadyFinal(command_id));
1076        }
1077        // Reserve the sequence before invoking a potentially side-effecting executor. Sequence
1078        // exhaustion must fail before any external action can succeed without an audit record.
1079        let sequence = self.next_audit_sequence()?;
1080        let (status, result_code) = match action(command) {
1081            Ok(code) => (CommandStatus::Executed, code),
1082            Err(code) => (CommandStatus::Failed, code),
1083        };
1084        let record = AuditRecord {
1085            command_id,
1086            request_id: command.request_id.clone(),
1087            operator_id: command.operator_id.clone(),
1088            command_digest: command.digest(),
1089            status,
1090            result_code,
1091            ts,
1092        };
1093        if status == CommandStatus::Executed && !command.dry_run && command.target != "*" {
1094            let paused = match command.kind {
1095                CommandKind::PauseStrategy => Some(true),
1096                CommandKind::ResumeStrategy => Some(false),
1097                _ => None,
1098            };
1099            if let Some(paused) = paused {
1100                self.strategy_lifecycle.insert(
1101                    command.target.clone(),
1102                    StrategyLifecycleRecord {
1103                        paused,
1104                        command_id,
1105                        ts,
1106                    },
1107                );
1108            }
1109        }
1110        self.append_audit(sequence, record.clone());
1111        self.retire_overflow();
1112        Ok(record)
1113    }
1114
1115    pub fn to_json(&self) -> Result<String, String> {
1116        serde_json::to_string(self).map_err(|error| error.to_string())
1117    }
1118
1119    pub fn from_json(input: &str) -> Result<Self, String> {
1120        let value: serde_json::Value =
1121            serde_json::from_str(input).map_err(|error| error.to_string())?;
1122        let legacy_lifecycle = value.get("strategy_lifecycle").is_none();
1123        let has_audit_sequences = value.get("audit_sequences").is_some();
1124        let has_audit_watermark = value.get("audit_high_watermark").is_some();
1125        let has_audit_command_sequences = value.get("audit_command_sequences").is_some();
1126        let has_pending_commands_count = value.get("pending_commands_count").is_some();
1127        if has_audit_sequences != has_audit_watermark {
1128            return Err("控制面审计序号与水位必须同时存在".into());
1129        }
1130        let legacy_audit_sequences = !has_audit_sequences;
1131        let mut plane: Self = serde_json::from_value(value).map_err(|error| error.to_string())?;
1132        if legacy_audit_sequences {
1133            plane.audit_sequences = (1..=plane.audit.len() as u64).collect();
1134            plane.audit_high_watermark = plane.audit_sequences.last().copied().unwrap_or(0);
1135        }
1136        if plane.audit_sequences.len() != plane.audit.len()
1137            || plane.audit_sequences.contains(&0)
1138            || plane
1139                .audit_sequences
1140                .windows(2)
1141                .any(|pair| pair[0] >= pair[1])
1142            || plane
1143                .audit_sequences
1144                .last()
1145                .is_some_and(|last| *last > plane.audit_high_watermark)
1146        {
1147            return Err("控制面审计追加序号与记录不一致".into());
1148        }
1149        let mut expected_command_sequences = BTreeMap::<u64, Vec<u64>>::new();
1150        for (record, sequence) in plane.audit.iter().zip(&plane.audit_sequences) {
1151            expected_command_sequences
1152                .entry(record.command_id)
1153                .or_default()
1154                .push(*sequence);
1155        }
1156        if legacy_audit_sequences || !has_audit_command_sequences {
1157            plane.audit_command_sequences = expected_command_sequences;
1158        } else if plane.audit_command_sequences != expected_command_sequences {
1159            return Err("控制面按命令审计序号索引与记录不一致".into());
1160        }
1161        if legacy_lifecycle && plane.retired.retired_commands > 0 {
1162            plane.strategy_lifecycle_legacy_incomplete = true;
1163        }
1164        for (command_id, command) in &plane.commands {
1165            if *command_id != command.command_id {
1166                return Err("命令索引与 command_id 不一致".into());
1167            }
1168            command
1169                .validate()
1170                .map_err(|error| format!("恢复的控制命令非法: {error:?}"))?;
1171            if plane.requests.get(&command.request_id) != Some(command_id) {
1172                return Err(format!("命令 {} 缺少一致的 request 索引", command_id));
1173            }
1174        }
1175        for (request_id, command_id) in &plane.requests {
1176            let command = plane
1177                .commands
1178                .get(command_id)
1179                .ok_or_else(|| format!("请求 {} 指向不存在的命令", request_id))?;
1180            if &command.request_id != request_id {
1181                return Err("请求索引与命令不一致".into());
1182            }
1183        }
1184        let mut audit_state = BTreeMap::new();
1185        for record in &plane.audit {
1186            let command = plane
1187                .commands
1188                .get(&record.command_id)
1189                .ok_or_else(|| format!("审计记录指向不存在的命令 {}", record.command_id))?;
1190            if record.request_id != command.request_id
1191                || record.operator_id != command.operator_id
1192                || record.command_digest != command.digest()
1193            {
1194                return Err(format!("命令 {} 的审计摘要不一致", record.command_id));
1195            }
1196            // 状态词表在这里只出现一次:`is_final()`。以前这个 match 把三个终态变体又抄了
1197            // 两遍(模式位置调不进 `is_final`),加变体就得同步改三处,漏一处恢复校验就松。
1198            match audit_state.get(&record.command_id).copied() {
1199                None if !record.status.is_final() => {
1200                    audit_state.insert(record.command_id, record.status);
1201                }
1202                None => {
1203                    return Err(format!("命令 {} 缺少 Accepted 初始记录", record.command_id));
1204                }
1205                Some(prior) if prior.is_final() => {
1206                    return Err(format!("命令 {} 终态后仍有审计记录", record.command_id));
1207                }
1208                Some(_) if record.status.is_final() => {
1209                    audit_state.insert(record.command_id, record.status);
1210                }
1211                Some(_) => {
1212                    return Err(format!("命令 {} 重复 Accepted", record.command_id));
1213                }
1214            }
1215        }
1216        // 每条命令都必须留下审计痕迹。`audit_state` 的键只可能来自上面已核对过"命令存在"
1217        // 的记录,所以这里问"有没有"就够了,不必再抄一遍状态词表。
1218        for command_id in plane.commands.keys() {
1219            if !audit_state.contains_key(command_id) {
1220                return Err(format!("命令 {} 缺少审计记录", command_id));
1221            }
1222        }
1223        let expected_pending_count = audit_state
1224            .values()
1225            .filter(|status| !status.is_final())
1226            .count() as u64;
1227        if has_pending_commands_count && plane.pending_commands_count != expected_pending_count {
1228            return Err("控制面待执行命令计数与终态审计不一致".into());
1229        }
1230        plane.pending_commands_count = expected_pending_count;
1231        // Migrate legacy documents from retained successful commands in execution order.
1232        let mut latest = BTreeMap::new();
1233        for record in &plane.audit {
1234            let command = &plane.commands[&record.command_id];
1235            if record.status != CommandStatus::Executed || command.dry_run || command.target == "*"
1236            {
1237                continue;
1238            }
1239            let paused = match command.kind {
1240                CommandKind::PauseStrategy => true,
1241                CommandKind::ResumeStrategy => false,
1242                _ => continue,
1243            };
1244            latest.insert(
1245                command.target.clone(),
1246                StrategyLifecycleRecord {
1247                    paused,
1248                    command_id: record.command_id,
1249                    ts: record.ts,
1250                },
1251            );
1252        }
1253        for (worker_id, record) in latest {
1254            if let Some(stored) = plane.strategy_lifecycle.get(&worker_id) {
1255                if plane.commands.contains_key(&stored.command_id) && stored != &record {
1256                    return Err(format!(
1257                        "strategy lifecycle state disagrees with audit for {worker_id}"
1258                    ));
1259                }
1260            } else if legacy_lifecycle {
1261                plane.strategy_lifecycle.insert(worker_id, record);
1262            } else {
1263                return Err(format!(
1264                    "strategy lifecycle state is missing for {worker_id}"
1265                ));
1266            }
1267        }
1268        if plane
1269            .strategy_lifecycle
1270            .keys()
1271            .any(|id| id.trim().is_empty() || id == "*")
1272        {
1273            return Err("strategy lifecycle state requires explicit worker IDs".into());
1274        }
1275        for (worker_id, state) in &plane.strategy_lifecycle {
1276            if let Some(command) = plane.commands.get(&state.command_id) {
1277                let kind_matches = if state.paused {
1278                    command.kind == CommandKind::PauseStrategy
1279                } else {
1280                    command.kind == CommandKind::ResumeStrategy
1281                };
1282                if !kind_matches
1283                    || command.dry_run
1284                    || command.target != *worker_id
1285                    || !plane.audit.iter().any(|record| {
1286                        record.command_id == state.command_id
1287                            && record.status == CommandStatus::Executed
1288                            && record.ts == state.ts
1289                    })
1290                {
1291                    return Err(format!(
1292                        "invalid strategy lifecycle binding for {worker_id}"
1293                    ));
1294                }
1295            }
1296        }
1297        Ok(plane)
1298    }
1299}
1300
1301fn has_permission(actual: Permission, required: Permission) -> bool {
1302    let level = |permission| match permission {
1303        Permission::ReadOnly => 0,
1304        Permission::Research => 1,
1305        Permission::Trading => 2,
1306        Permission::Admin => 3,
1307    };
1308    level(actual) >= level(required)
1309}
1310
1311#[cfg(test)]
1312mod tests {
1313    use super::*;
1314
1315    fn protection_order(
1316        client_id: u64,
1317        kind: qx_core::ConditionalOrderKind,
1318        trigger: &str,
1319    ) -> Order {
1320        Order {
1321            client_id,
1322            instrument: qx_core::InstrumentId::parse("BTCUSDT.BINANCE").unwrap(),
1323            side: qx_core::Side::Sell,
1324            qty: qx_core::Quantity::ZERO,
1325            limit: None,
1326            status: OrderStatus::PendingSubmit,
1327            filled: qx_core::Quantity::ZERO,
1328            account_id: "main".into(),
1329            trace: None,
1330            policy: None,
1331            exact_amounts: Some(qx_core::ExactOrderAmounts {
1332                quantity: qx_core::ExactDecimal::parse("0.01").unwrap(),
1333                limit_price: None,
1334                filled: qx_core::ExactDecimal::ZERO,
1335                quote_budget: None,
1336                quote_filled: qx_core::ExactDecimal::ZERO,
1337                market_reference_price: None,
1338                conditional: Some(qx_core::ConditionalOrderIntent {
1339                    kind,
1340                    trigger_price: Some(qx_core::ExactDecimal::parse(trigger).unwrap()),
1341                    trigger_price_type: Some(qx_core::TriggerPriceType::Last),
1342                    trailing_percent: None,
1343                    trailing_amount: None,
1344                    trailing_trigger_price: None,
1345                }),
1346            }),
1347        }
1348    }
1349
1350    #[test]
1351    fn submit_order_group_command_binds_audited_target_and_group_payload() {
1352        let group = qx_core::OrderGroupIntent::new(
1353            "main-btc-protection",
1354            qx_core::OrderGroupKind::Oco,
1355            qx_core::OrderGroupExecution::NativeRequired,
1356            vec![
1357                qx_core::OrderGroupLegIntent {
1358                    role: qx_core::OrderGroupLegRole::TakeProfit,
1359                    order: protection_order(71, qx_core::ConditionalOrderKind::TakeProfit, "70000"),
1360                },
1361                qx_core::OrderGroupLegIntent {
1362                    role: qx_core::OrderGroupLegRole::StopLoss,
1363                    order: protection_order(72, qx_core::ConditionalOrderKind::StopLoss, "60000"),
1364                },
1365            ],
1366        )
1367        .unwrap();
1368        let mut command = command(Permission::Trading);
1369        command.kind = CommandKind::SubmitOrderGroup;
1370        command.target = group.group_id.clone();
1371        command.payload = BTreeMap::from([(
1372            "order_group_json".into(),
1373            serde_json::to_string(&group).unwrap(),
1374        )]);
1375
1376        assert_eq!(order_group_from_submit_command(&command).unwrap(), group);
1377        let mut mismatched = command;
1378        mismatched.target = "another-group".into();
1379        assert!(order_group_from_submit_command(&mismatched).is_err());
1380    }
1381
1382    #[test]
1383    fn cancel_order_group_command_binds_group_and_route_without_extra_payload() {
1384        let mut command = command(Permission::Trading);
1385        command.kind = CommandKind::CancelOrderGroup;
1386        command.target = "main-btc-protection".into();
1387        command.payload = BTreeMap::from([
1388            ("account_id".into(), "main".into()),
1389            ("venue_id".into(), "BINANCE".into()),
1390        ]);
1391        let target = cancel_order_group_target_from_command(&command).unwrap();
1392        assert_eq!(target.group_id, "main-btc-protection");
1393        assert_eq!(target.account_id, "main");
1394        assert_eq!(target.venue_id, "BINANCE");
1395
1396        let mut extra = command.clone();
1397        extra.payload.insert("order_id".into(), "71".into());
1398        assert!(cancel_order_group_target_from_command(&extra).is_err());
1399        let mut empty_group = command;
1400        empty_group.target = "  ".into();
1401        assert!(cancel_order_group_target_from_command(&empty_group).is_err());
1402    }
1403
1404    fn amend_command(order: &Order) -> ControlCommand {
1405        let mut value = command(Permission::Trading);
1406        value.kind = CommandKind::AmendOrder;
1407        value.target = order.client_id.to_string();
1408        value.payload = BTreeMap::from([
1409            ("account_id".into(), order.account_id.clone()),
1410            (
1411                "venue_id".into(),
1412                order.instrument.venue.as_str().to_string(),
1413            ),
1414            ("order_json".into(), serde_json::to_string(order).unwrap()),
1415        ]);
1416        value
1417    }
1418
1419    #[test]
1420    fn amend_order_command_binds_target_route_and_active_order_snapshot() {
1421        let order = Order {
1422            client_id: 7,
1423            instrument: qx_core::InstrumentId::parse("BTC/USDT.BINANCE").unwrap(),
1424            side: qx_core::Side::Buy,
1425            qty: qx_core::Quantity::from_i64(3),
1426            limit: Some(qx_core::Price::from_i64(101)),
1427            status: OrderStatus::PartiallyFilled,
1428            filled: qx_core::Quantity::from_i64(1),
1429            account_id: "main".into(),
1430            trace: None,
1431            policy: None,
1432            exact_amounts: None,
1433        };
1434        let command = amend_command(&order);
1435        let target = amend_order_target_from_command(&command).unwrap();
1436        assert_eq!(target.client_order_id, 7);
1437        assert_eq!(target.account_id, "main");
1438        assert_eq!(target.venue_id, "BINANCE");
1439        assert_eq!(target.order, order);
1440
1441        let mut mismatch = command.clone();
1442        mismatch.target = "8".into();
1443        assert!(amend_order_target_from_command(&mismatch).is_err());
1444        let mut wrong_route = command.clone();
1445        wrong_route.payload.insert("venue_id".into(), "OKX".into());
1446        assert!(amend_order_target_from_command(&wrong_route).is_err());
1447        let mut terminal = order;
1448        terminal.status = OrderStatus::Filled;
1449        assert!(amend_order_target_from_command(&amend_command(&terminal)).is_err());
1450    }
1451
1452    fn command(permission: Permission) -> ControlCommand {
1453        ControlCommand {
1454            command_id: 1,
1455            request_id: "req-1".into(),
1456            operator_id: "operator".into(),
1457            reason: "incident recovery".into(),
1458            // PauseStrategy 有策略 worker 派发者;CancelOrder 也已由交易所执行 worker 派发。
1459            kind: CommandKind::PauseStrategy,
1460            target: "strategy-1".into(),
1461            payload: BTreeMap::new(),
1462            permission,
1463            dry_run: true,
1464        }
1465    }
1466
1467    #[test]
1468    fn control_command_is_audited_and_idempotent() {
1469        let mut plane = ControlPlane::default();
1470        let record = plane.submit(command(Permission::Trading), 10).unwrap();
1471        assert_eq!(record.status, CommandStatus::Accepted);
1472        assert_eq!(plane.audit().len(), 1);
1473        assert_eq!(
1474            plane.submit(command(Permission::Trading), 11),
1475            Err(ControlError::DuplicateRequest("req-1".into()))
1476        );
1477        let mut duplicate_id = command(Permission::Trading);
1478        duplicate_id.request_id = "req-2".into();
1479        assert_eq!(
1480            plane.submit(duplicate_id, 12),
1481            Err(ControlError::DuplicateCommand(1))
1482        );
1483    }
1484
1485    #[test]
1486    fn control_command_wire_rejects_unknown_fields() {
1487        let mut value = serde_json::to_value(command(Permission::Trading)).unwrap();
1488        value["dry_rnu"] = serde_json::Value::Bool(false);
1489        assert!(serde_json::from_value::<ControlCommand>(value).is_err());
1490    }
1491
1492    #[test]
1493    fn versioned_audit_record_matches_the_shared_wire_fixture() {
1494        let fixture: serde_json::Value = serde_json::from_str(include_str!(
1495            "../../../python/tests/fixtures/control-audit-record-v1.json"
1496        ))
1497        .unwrap();
1498        let domain_record: AuditRecord = serde_json::from_value(fixture.clone()).unwrap();
1499        let record = ControlAuditRecordV1::from(&domain_record);
1500        assert_eq!(serde_json::to_value(&record).unwrap(), fixture);
1501        let decoded: ControlAuditRecordV1 =
1502            serde_json::from_value(serde_json::to_value(&record).unwrap()).unwrap();
1503        assert_eq!(decoded, record);
1504
1505        let mut unknown = fixture.clone();
1506        unknown["unregistered"] = serde_json::json!(true);
1507        assert!(serde_json::from_value::<ControlAuditRecordV1>(unknown).is_err());
1508        let mut old_version = fixture;
1509        old_version["schema_version"] = serde_json::json!(2);
1510        assert!(serde_json::from_value::<ControlAuditRecordV1>(old_version).is_err());
1511    }
1512
1513    #[test]
1514    fn insufficient_permission_is_rejected_before_queueing() {
1515        let mut plane = ControlPlane::default();
1516        assert_eq!(
1517            plane.submit(command(Permission::ReadOnly), 10),
1518            Err(ControlError::Forbidden)
1519        );
1520        assert!(plane.audit().is_empty());
1521    }
1522
1523    #[test]
1524    fn declared_permission_cannot_exceed_server_grant() {
1525        let mut plane = ControlPlane::default();
1526        assert_eq!(
1527            plane.submit_as(command(Permission::Trading), Permission::ReadOnly, 10),
1528            Err(ControlError::Forbidden)
1529        );
1530        assert!(plane.audit().is_empty());
1531        assert!(plane
1532            .submit_as(command(Permission::Trading), Permission::Admin, 11)
1533            .is_ok());
1534    }
1535
1536    #[test]
1537    fn execution_is_audited_and_idempotent_after_completion() {
1538        let mut plane = ControlPlane::default();
1539        plane.submit(command(Permission::Trading), 10).unwrap();
1540        assert_eq!(plane.pending().count(), 1);
1541        let record = plane.execute(1, 11, |_| Ok("APPLIED".into())).unwrap();
1542        assert_eq!(record.status, CommandStatus::Executed);
1543        assert_eq!(record.result_code, "APPLIED");
1544        assert_eq!(plane.pending().count(), 0);
1545        assert_eq!(
1546            plane.execute(1, 12, |_| Ok("DUPLICATE".into())),
1547            Err(ControlError::AlreadyFinal(1))
1548        );
1549    }
1550
1551    #[test]
1552    fn restore_rejects_terminal_audit_without_acceptance() {
1553        let command = command(Permission::Trading);
1554        let mut plane = ControlPlane::default();
1555        plane
1556            .requests
1557            .insert(command.request_id.clone(), command.command_id);
1558        plane.commands.insert(command.command_id, command.clone());
1559        let command_digest = command.digest();
1560        plane.audit.push(AuditRecord {
1561            command_id: command.command_id,
1562            request_id: command.request_id,
1563            operator_id: command.operator_id,
1564            command_digest,
1565            status: CommandStatus::Executed,
1566            result_code: "APPLIED".into(),
1567            ts: 10,
1568        });
1569        plane.audit_sequences.push(1);
1570        plane
1571            .audit_command_sequences
1572            .insert(command.command_id, vec![1]);
1573        plane.audit_high_watermark = 1;
1574        let json = plane.to_json().unwrap();
1575        assert!(ControlPlane::from_json(&json).is_err());
1576    }
1577
1578    fn numbered(index: u64) -> ControlCommand {
1579        ControlCommand {
1580            command_id: index,
1581            request_id: format!("req-{index}"),
1582            operator_id: "operator".into(),
1583            reason: "retention probe".into(),
1584            kind: CommandKind::PauseStrategy,
1585            target: "strategy-1".into(),
1586            payload: BTreeMap::new(),
1587            permission: Permission::Trading,
1588            dry_run: true,
1589        }
1590    }
1591
1592    #[test]
1593    fn audit_pages_use_durable_sequences_and_freeze_the_snapshot() {
1594        let mut plane = ControlPlane::default();
1595        for index in 1..=3u64 {
1596            plane.submit(numbered(index), index * 10).unwrap();
1597        }
1598
1599        let first = plane.audit_page(None, 2, None).unwrap();
1600        assert_eq!(
1601            first
1602                .entries
1603                .iter()
1604                .map(|entry| entry.sequence)
1605                .collect::<Vec<_>>(),
1606            [3, 2]
1607        );
1608        assert!(first.has_more);
1609        assert_eq!(first.snapshot_through_sequence, 3);
1610        let cursor = first.next_cursor.clone().unwrap();
1611        assert_eq!(cursor, "v1.2.3");
1612
1613        // New rows after page one do not extend this scan's upper bound.
1614        plane.submit(numbered(4), 40).unwrap();
1615        let restored = ControlPlane::from_json(&plane.to_json().unwrap()).unwrap();
1616        let second = restored.audit_page(Some(&cursor), 2, None).unwrap();
1617        assert_eq!(
1618            second
1619                .entries
1620                .iter()
1621                .map(|entry| entry.sequence)
1622                .collect::<Vec<_>>(),
1623            [1]
1624        );
1625        assert!(!second.has_more);
1626        assert_eq!(second.snapshot_through_sequence, 3);
1627
1628        let request_page = restored.audit_page(None, 2, Some("req-2")).unwrap();
1629        assert_eq!(request_page.entries.len(), 1);
1630        assert!(request_page.next_cursor.is_none());
1631    }
1632
1633    #[test]
1634    fn audit_pages_enforce_a_serialized_byte_budget() {
1635        let mut plane = ControlPlane::default();
1636        let mut large = numbered(1);
1637        large.request_id = "r".repeat(CONTROL_AUDIT_MAX_PAGE_BYTES / 2 + 32);
1638        plane.submit(large, 10).unwrap();
1639        plane.execute(1, 11, |_| Ok("APPLIED".into())).unwrap();
1640
1641        let first = plane.audit_page(None, 2, None).unwrap();
1642        assert_eq!(first.entries.len(), 1);
1643        assert!(first.has_more);
1644        assert!(serde_json::to_vec(&first).unwrap().len() <= CONTROL_AUDIT_MAX_PAGE_BYTES);
1645        let second = plane
1646            .audit_page(first.next_cursor.as_deref(), 2, None)
1647            .unwrap();
1648        assert_eq!(second.entries.len(), 1);
1649        assert!(!second.has_more);
1650        assert!(serde_json::to_vec(&second).unwrap().len() <= CONTROL_AUDIT_MAX_PAGE_BYTES);
1651
1652        let mut too_large = numbered(2);
1653        too_large.request_id = "r".repeat(CONTROL_AUDIT_MAX_PAGE_BYTES + 1);
1654        plane.submit(too_large, 20).unwrap();
1655        assert!(plane
1656            .audit_page(None, 2, None)
1657            .unwrap_err()
1658            .contains("maximum response byte budget"));
1659    }
1660
1661    #[test]
1662    fn audit_cursor_expires_when_retirement_removes_its_unread_window() {
1663        let mut plane = ControlPlane::default();
1664        plane.submit(numbered(1), 10).unwrap();
1665        plane.submit(numbered(2), 20).unwrap();
1666        let first = plane.audit_page(None, 1, None).unwrap();
1667        let cursor = first.next_cursor.unwrap();
1668
1669        plane.execute(1, 30, |_| Ok("APPLIED".into())).unwrap();
1670        plane.execute(2, 40, |_| Ok("APPLIED".into())).unwrap();
1671        plane.retire_overflow_with(0);
1672
1673        assert!(plane.audit_page(Some(&cursor), 1, None).is_err());
1674    }
1675
1676    #[test]
1677    fn audit_sequence_migration_keeps_legacy_control_plane_readable() {
1678        let mut plane = ControlPlane::default();
1679        plane.submit(numbered(1), 10).unwrap();
1680        plane.execute(1, 11, |_| Ok("APPLIED".into())).unwrap();
1681        let mut value: serde_json::Value = serde_json::from_str(&plane.to_json().unwrap()).unwrap();
1682        let object = value
1683            .as_object_mut()
1684            .expect("plane serializes as an object");
1685        object.remove("audit_sequences");
1686        object.remove("audit_high_watermark");
1687        object.remove("pending_commands_count");
1688
1689        let restored = ControlPlane::from_json(&value.to_string()).unwrap();
1690        let page = restored.audit_page(None, 10, None).unwrap();
1691        assert_eq!(
1692            page.entries
1693                .iter()
1694                .map(|entry| entry.sequence)
1695                .collect::<Vec<_>>(),
1696            [2, 1]
1697        );
1698        assert_eq!(page.snapshot_through_sequence, 2);
1699    }
1700
1701    /// 退场只碰终态命令,且命令/请求索引/审计三格同时消失——少删任何一格,
1702    /// `from_json` 的恢复校验就会拒读,所以末尾那一次往返是这颗用例的牙齿。
1703    #[test]
1704    fn retirement_drops_oldest_finalized_commands_whole() {
1705        let mut plane = ControlPlane::default();
1706        for index in 1..=4u64 {
1707            plane.submit(numbered(index), index * 10).unwrap();
1708        }
1709        for index in 1..=4u64 {
1710            plane
1711                .execute(index, index * 10 + 1, |_| Ok("APPLIED".into()))
1712                .unwrap();
1713        }
1714        assert_eq!(plane.retirement(), RetirementSummary::default());
1715
1716        plane.retire_overflow_with(2);
1717
1718        assert_eq!(
1719            plane.retirement(),
1720            RetirementSummary {
1721                retired_commands: 2,
1722                // 每条命令两条记录(Accepted + 终态),退场必须把两条一起带走。
1723                retired_audit_records: 4,
1724            }
1725        );
1726        let remaining: Vec<u64> = plane.audit().iter().map(|r| r.command_id).collect();
1727        // 审计是追加序:四条 Accepted 先全部落盘,四条终态记录再依次跟上,
1728        // 所以幸存者是 [3, 4, 3, 4] 而不是 [3, 3, 4, 4]。写死这个顺序等于把
1729        // 「Accepted 与终态是两次独立 push」这条事实也钉住。
1730        assert_eq!(remaining, vec![3, 4, 3, 4]);
1731        assert!(plane.command(1).is_none() && plane.command(2).is_none());
1732        assert!(plane.command(3).is_some() && plane.command(4).is_some());
1733        assert_eq!(plane.pending().count(), 0);
1734        // 恢复校验逐条核对索引一致性:三格里漏删任何一格,这一句就红。
1735        let json = plane.to_json().unwrap();
1736        let restored = ControlPlane::from_json(&json).unwrap();
1737        assert_eq!(restored.retirement(), plane.retirement());
1738        assert_eq!(restored.audit().len(), 4);
1739    }
1740
1741    #[test]
1742    fn retirement_uses_audit_append_order_when_timestamps_move_backwards() {
1743        let mut plane = ControlPlane::default();
1744        for index in 1..=4u64 {
1745            plane.submit(numbered(index), 100 + index).unwrap();
1746        }
1747        for (command_id, ts) in [(1, 400), (2, 300), (3, 200), (4, 100)] {
1748            plane
1749                .execute(command_id, ts, |_| Ok("APPLIED".into()))
1750                .unwrap();
1751        }
1752
1753        plane.retire_overflow_with(2);
1754
1755        assert!(
1756            plane.command(1).is_none(),
1757            "oldest finalized command must retire first"
1758        );
1759        assert!(
1760            plane.command(2).is_none(),
1761            "second-oldest finalized command must retire"
1762        );
1763        assert!(plane.command(3).is_some());
1764        assert!(plane.command(4).is_some());
1765        assert_eq!(plane.retirement().retired_commands, 2);
1766        assert!(ControlPlane::from_json(&plane.to_json().unwrap()).is_ok());
1767    }
1768
1769    /// 未终态的命令永不退场:把它退掉等于静默丢掉一条已受理、还没人执行的命令。
1770    #[test]
1771    fn retirement_never_drops_a_pending_command() {
1772        let mut plane = ControlPlane::default();
1773        for index in 1..=6u64 {
1774            plane.submit(numbered(index), index).unwrap();
1775        }
1776        for index in 1..=5u64 {
1777            plane
1778                .execute(index, index + 100, |_| Ok("APPLIED".into()))
1779                .unwrap();
1780        }
1781        plane.retire_overflow_with(1);
1782        assert_eq!(plane.retirement().retired_commands, 4);
1783        assert!(plane.command(6).is_some(), "待办命令被退场了");
1784        assert_eq!(plane.pending().count(), 1);
1785        assert_eq!(plane.audit().len(), 3);
1786    }
1787
1788    #[test]
1789    fn pending_command_admission_is_bounded_and_recovers_capacity() {
1790        let mut plane = ControlPlane::default();
1791        for id in 1..=PENDING_CONTROL_COMMAND_LIMIT as u64 {
1792            plane.submit(numbered(id), id).unwrap();
1793        }
1794        assert_eq!(
1795            plane.pending_commands_count(),
1796            PENDING_CONTROL_COMMAND_LIMIT as u64
1797        );
1798        assert_eq!(
1799            plane.submit(numbered(PENDING_CONTROL_COMMAND_LIMIT as u64 + 1), 5000),
1800            Err(ControlError::PendingLimitReached)
1801        );
1802        assert_eq!(plane.audit().len(), PENDING_CONTROL_COMMAND_LIMIT);
1803
1804        plane.execute(1, 5001, |_| Ok("APPLIED".into())).unwrap();
1805        assert_eq!(
1806            plane.pending_commands_count(),
1807            PENDING_CONTROL_COMMAND_LIMIT as u64 - 1
1808        );
1809        plane
1810            .submit(numbered(PENDING_CONTROL_COMMAND_LIMIT as u64 + 1), 5002)
1811            .unwrap();
1812        assert_eq!(
1813            plane.pending_commands_count(),
1814            PENDING_CONTROL_COMMAND_LIMIT as u64
1815        );
1816
1817        let restored = ControlPlane::from_json(&plane.to_json().unwrap()).unwrap();
1818        assert_eq!(
1819            restored.pending_commands_count(),
1820            PENDING_CONTROL_COMMAND_LIMIT as u64
1821        );
1822        let mut legacy: serde_json::Value =
1823            serde_json::from_str(&plane.to_json().unwrap()).unwrap();
1824        legacy
1825            .as_object_mut()
1826            .unwrap()
1827            .remove("pending_commands_count");
1828        assert_eq!(
1829            ControlPlane::from_json(&legacy.to_string())
1830                .unwrap()
1831                .pending_commands_count(),
1832            PENDING_CONTROL_COMMAND_LIMIT as u64
1833        );
1834        legacy["pending_commands_count"] = 0.into();
1835        match ControlPlane::from_json(&legacy.to_string()) {
1836            Ok(_) => panic!("持久计数与未终结命令不一致时必须拒绝恢复"),
1837            Err(error) => assert!(error.contains("待执行命令计数")),
1838        }
1839    }
1840
1841    /// 生产入口真的会触发退场:上界是常量,`submit`/`execute` 每次都过一遍这条判据。
1842    /// 少了这颗,`retire_overflow` 可以接上却永不被越过,「有界」只是写法不是事实。
1843    #[test]
1844    fn production_entries_enforce_the_retention_bound() {
1845        let mut plane = ControlPlane::default();
1846        let bound = FINALIZED_COMMAND_RETENTION as u64;
1847        for index in 1..=bound + 1 {
1848            plane.submit(numbered(index), index).unwrap();
1849            plane
1850                .execute(index, index, |_| Ok("APPLIED".into()))
1851                .unwrap();
1852        }
1853        assert_eq!(plane.retirement().retired_commands, 1);
1854        assert_eq!(plane.retirement().retired_audit_records, 2);
1855        assert!(plane.command(1).is_none(), "最旧那条终态命令没退场");
1856        assert!(plane.command(bound + 1).is_some());
1857        assert!(ControlPlane::from_json(&plane.to_json().unwrap()).is_ok());
1858    }
1859
1860    /// 合流之前落盘的控制面 JSON 没有 `retired` 这一格:恢复必须照样读得回来。
1861    #[test]
1862    fn restore_accepts_a_plane_written_before_the_summary_existed() {
1863        let mut plane = ControlPlane::default();
1864        plane.submit(numbered(1), 10).unwrap();
1865        plane.execute(1, 11, |_| Ok("APPLIED".into())).unwrap();
1866        let mut value: serde_json::Value = serde_json::from_str(&plane.to_json().unwrap()).unwrap();
1867        value
1868            .as_object_mut()
1869            .expect("plane serializes as an object")
1870            .remove("retired");
1871        let legacy = value.to_string();
1872        let restored = ControlPlane::from_json(&legacy).unwrap();
1873        assert_eq!(restored.retirement(), RetirementSummary::default());
1874        assert_eq!(restored.audit().len(), 2);
1875    }
1876}
1877
1878#[cfg(test)]
1879mod durable_lifecycle_tests {
1880    use super::*;
1881
1882    fn command(id: u64, kind: CommandKind, dry_run: bool) -> ControlCommand {
1883        ControlCommand {
1884            command_id: id,
1885            request_id: format!("lifecycle-{id}"),
1886            operator_id: "ops".into(),
1887            reason: "lifecycle recovery".into(),
1888            kind,
1889            target: "worker-a".into(),
1890            payload: BTreeMap::new(),
1891            permission: Permission::Trading,
1892            dry_run,
1893        }
1894    }
1895
1896    fn execute(plane: &mut ControlPlane, id: u64, kind: CommandKind, dry_run: bool, success: bool) {
1897        plane.submit(command(id, kind, dry_run), id).unwrap();
1898        plane
1899            .execute(id, id, |_| {
1900                if success {
1901                    Ok("ok".into())
1902                } else {
1903                    Err("failed".into())
1904                }
1905            })
1906            .unwrap();
1907    }
1908
1909    #[test]
1910    fn durable_lifecycle_survives_audit_retirement_and_restart() {
1911        let mut plane = ControlPlane::default();
1912        execute(&mut plane, 1, CommandKind::PauseStrategy, false, true);
1913        plane.retire_overflow_with(0);
1914        assert!(plane.audit().is_empty());
1915        let restored = ControlPlane::from_json(&plane.to_json().unwrap()).unwrap();
1916        assert!(restored.strategy_lifecycle("worker-a").unwrap().paused);
1917        assert!(restored.strategy_lifecycle("worker-b").is_none());
1918    }
1919
1920    #[test]
1921    fn durable_lifecycle_legacy_retirement_requires_explicit_resume() {
1922        let mut plane = ControlPlane::default();
1923        execute(&mut plane, 1, CommandKind::PauseStrategy, false, true);
1924        plane.retire_overflow_with(0);
1925        let mut value = serde_json::to_value(&plane).unwrap();
1926        value.as_object_mut().unwrap().remove("strategy_lifecycle");
1927        value
1928            .as_object_mut()
1929            .unwrap()
1930            .remove("strategy_lifecycle_legacy_incomplete");
1931        let mut migrated = ControlPlane::from_json(&value.to_string()).unwrap();
1932        assert_eq!(migrated.strategy_pause_state("worker-a"), Some(true));
1933        execute(&mut migrated, 2, CommandKind::ResumeStrategy, false, true);
1934        let restored = ControlPlane::from_json(&migrated.to_json().unwrap()).unwrap();
1935        assert_eq!(restored.strategy_pause_state("worker-a"), Some(false));
1936        assert_eq!(restored.strategy_pause_state("worker-b"), Some(true));
1937    }
1938
1939    #[test]
1940    fn durable_lifecycle_ignores_failed_and_dry_run_commands() {
1941        let mut plane = ControlPlane::default();
1942        execute(&mut plane, 1, CommandKind::PauseStrategy, false, true);
1943        execute(&mut plane, 2, CommandKind::ResumeStrategy, true, true);
1944        execute(&mut plane, 3, CommandKind::ResumeStrategy, false, false);
1945        assert_eq!(plane.strategy_lifecycle("worker-a").unwrap().command_id, 1);
1946        execute(&mut plane, 4, CommandKind::ResumeStrategy, false, true);
1947        let restored = ControlPlane::from_json(&plane.to_json().unwrap()).unwrap();
1948        assert!(!restored.strategy_lifecycle("worker-a").unwrap().paused);
1949    }
1950
1951    #[test]
1952    fn durable_lifecycle_migrates_legacy_and_rejects_conflicting_projection() {
1953        let mut plane = ControlPlane::default();
1954        execute(&mut plane, 1, CommandKind::PauseStrategy, false, true);
1955        let mut value = serde_json::to_value(&plane).unwrap();
1956        value.as_object_mut().unwrap().remove("strategy_lifecycle");
1957        let migrated = ControlPlane::from_json(&value.to_string()).unwrap();
1958        assert!(migrated.strategy_lifecycle("worker-a").unwrap().paused);
1959        let mut value = serde_json::to_value(&migrated).unwrap();
1960        value["strategy_lifecycle"]["worker-a"]["paused"] = false.into();
1961        assert!(ControlPlane::from_json(&value.to_string()).is_err());
1962    }
1963
1964    #[test]
1965    fn durable_lifecycle_rejects_new_wildcard_without_breaking_legacy_reads() {
1966        let mut plane = ControlPlane::default();
1967        let mut wildcard = command(1, CommandKind::PauseStrategy, false);
1968        wildcard.target = "*".into();
1969        assert!(wildcard.validate().is_ok());
1970        assert!(wildcard.validate_as(Permission::Trading).is_err());
1971        assert!(plane.submit(wildcard.clone(), 1).is_err());
1972        // A previously accepted wildcard remains readable but does not invent per-worker state.
1973        let mut legacy = ControlPlane::default();
1974        let accepted = AuditRecord {
1975            command_id: 1,
1976            request_id: wildcard.request_id.clone(),
1977            operator_id: wildcard.operator_id.clone(),
1978            command_digest: wildcard.digest(),
1979            status: CommandStatus::Accepted,
1980            result_code: "accepted".into(),
1981            ts: 1,
1982        };
1983        legacy.requests.insert(wildcard.request_id.clone(), 1);
1984        legacy.commands.insert(1, wildcard);
1985        legacy.audit.push(accepted);
1986        legacy.audit_sequences.push(1);
1987        legacy.audit_command_sequences.insert(1, vec![1]);
1988        legacy.pending_commands_count = 1;
1989        legacy.audit_high_watermark = 1;
1990        assert!(ControlPlane::from_json(&legacy.to_json().unwrap()).is_ok());
1991    }
1992}