wordval-actor 1.0.5

Wordval actor system: high-performance message foundation for drone ground stations
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
//! 类型化引用 —— [`ActorRef<M>`]:热路径零类型擦除的 Actor 句柄。
//!
//! `ActorRef<M>` 直接持有 `mpsc::Sender<M>`:发送用户消息
//! 不经任何装箱与向下转型;注册表的类型擦除仅发生在控制面
//! (信号送达 / 停止 / find)。

use crate::addr::{ActorId, ActorName};
use crate::mailbox::SlotWriter;
use crate::msg::{ActorMsg, ActorPhase, StopCause, request_stop};
use crate::system::{ActorError, ActorSystem, SystemInner};
use crate::timer::{ClockSource, deadline_after};
use std::fmt;
use std::sync::{Arc, Weak};
use std::time::Duration;
use tokio::sync::{mpsc, oneshot, watch};

/// 一次性应答端口 —— 请求型消息携带它,处理方用 [`Reply::send`] 回填。
///
/// # 示例(消息定义)
///
/// ```
/// use wordval_actor::Reply;
///
/// enum Command {
///     GetSnapshot { reply: Reply<Vec<u8>> },
/// }
/// ```
pub struct Reply<T: ActorMsg> {
    tx: oneshot::Sender<T>,
}

impl<T: ActorMsg> Reply<T> {
    pub(crate) fn new_pair() -> (Reply<T>, oneshot::Receiver<T>) {
        let (tx, rx) = oneshot::channel();
        (Self { tx }, rx)
    }

    /// 回填响应。若请求方已超时放弃则静默丢弃。
    pub fn send(self, value: T) {
        let _ = self.tx.send(value);
    }
}

impl<T: ActorMsg> fmt::Debug for Reply<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("Reply(_)")
    }
}

/// ask 模式错误。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AskError {
    /// 目标邮箱已满(背压),调用方可稍后重试。
    MailboxFull,
    /// 目标已停止、通道关闭,或处理方拿到 [`Reply`] 后未应答就丢弃
    /// (主动放弃应答,比干等超时更快反馈)。
    Closed,
    /// 在超时期限内未收到响应。
    Timeout,
}

impl fmt::Display for AskError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            AskError::MailboxFull => f.write_str("目标邮箱已满"),
            AskError::Closed => f.write_str("目标已停止或放弃应答"),
            AskError::Timeout => f.write_str("请求超时"),
        }
    }
}

impl std::error::Error for AskError {}

/// 已启动 Actor 的类型化引用。
///
/// Clone 廉价(内部均为 Arc 通道句柄),可自由跨任务共享。
/// 持有引用**不会**延长目标 Actor 的生命周期,也不阻止其被停止。
pub struct ActorRef<M: ActorMsg> {
    id: ActorId,
    name: Option<ActorName>,
    ctl: mpsc::Sender<M>,
    /// 相位/停止通道发送端:`try_stop` 经 [`request_stop`] 落 `Stopped`,
    /// 终态由 finalize 写入;watch 保留末值,死后查询照样可读(见
    /// [`phase`](ActorRef::phase))。
    stop: Arc<watch::Sender<ActorPhase>>,
    slot: Option<SlotWriter<M>>,
    /// 系统时钟源:ask 超时与定时器/看门狗同源,虚拟时间测试可确定推进。
    clock: ClockSource,
    /// 所属系统(弱引用:注册表条目内部持有 `ActorRef` 克隆,强引用
    /// 会与 `SystemInner` 成环,使系统永不析构)。经
    /// [`system`](ActorRef::system) 上溯为可用句柄。
    system: Weak<SystemInner>,
}

impl<M: ActorMsg> Clone for ActorRef<M> {
    fn clone(&self) -> Self {
        Self {
            id: self.id,
            name: self.name.clone(),
            ctl: self.ctl.clone(),
            stop: self.stop.clone(),
            slot: self.slot.clone(),
            clock: self.clock.clone(),
            system: self.system.clone(),
        }
    }
}

impl<M: ActorMsg> fmt::Debug for ActorRef<M> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ActorRef")
            .field("id", &self.id)
            .field("name", &self.name)
            .field("data_port", &self.slot.is_some())
            .finish()
    }
}

pub(crate) fn new_ref<M: ActorMsg>(
    id: ActorId,
    name: Option<ActorName>,
    ctl: mpsc::Sender<M>,
    stop: Arc<watch::Sender<ActorPhase>>,
    slot: Option<SlotWriter<M>>,
    clock: ClockSource,
    system: Weak<SystemInner>,
) -> ActorRef<M> {
    ActorRef {
        id,
        name,
        ctl,
        stop,
        slot,
        clock,
        system,
    }
}

impl<M: ActorMsg> ActorRef<M> {
    /// 目标 Actor 的唯一 ID。
    pub fn id(&self) -> ActorId {
        self.id
    }

    /// 目标 Actor 的名称(若以命名方式 spawn)。
    pub fn name(&self) -> Option<&ActorName> {
        self.name.as_ref()
    }

    /// 所属系统句柄(系统已销毁时返回 `None`)。
    ///
    /// 可在持有 `ActorRef` 的任意任务中回访系统(`find` / `is_alive` /
    /// `shutdown` 等),无需另存一份 `ActorSystem`。返回的是**派生句柄**,
    /// 不参与"未 shutdown 泄漏检测"计数。
    pub fn system(&self) -> Option<ActorSystem> {
        self.system.upgrade().map(ActorSystem::from_inner)
    }

    /// 目标 Actor 是否仍可能存活(相位派生的近似探测)。
    ///
    /// 以相位通道为准:停止请求落值(`try_stop` / `ctx.stop()` / 系统关闭)
    /// 或最终退出后即返回 false。注意停止请求落值不等于事件循环已退出
    /// (收尾消息可能仍在处理),精确的"已最终退出"判定请用
    /// [`ActorSystem::is_alive`](crate::ActorSystem::is_alive)。
    #[must_use = "存活探测结果不应被静默忽略"]
    pub fn is_alive(&self) -> bool {
        // 直接借用相位(`phase()` 会克隆:终态 panic 详情为 String 时堆分配)
        self.stop.borrow().is_alive()
    }

    /// 目标 Actor 当前生命周期相位。
    ///
    /// watch 通道保留末值:Actor 最终退出后本方法仍返回终态
    /// `Stopped { cause, detail }`(含 panic 详情),无需额外的
    /// 终止登记表。
    pub fn phase(&self) -> ActorPhase {
        self.stop.borrow().clone()
    }

    /// 订阅相位变化。
    ///
    /// 返回的接收端初值即当前相位;Actor 死后补订阅同样能读到
    /// 终态(通道保留末值,不丢历史终值)。与一次性的
    /// [`Terminated`](crate::Terminated) 通知互补:通知描述"刚刚终止"
    /// 的事件,本订阅提供任意时刻可查询的持续状态。
    ///
    /// 注意:发送端由系统条目与全部 `ActorRef` 存活句柄持有,Actor 死后
    /// 通道**不关闭** —— `changed()` 读到终态后继续等待既不会再有变化、
    /// 也不会返回 `Err`。`while rx.changed().await.is_ok()` 这类依赖
    /// "通道关闭退出"的写法会永久悬挂;需要等待退出请改读
    /// [`phase`](Self::phase) 轮询,或首轮读到 `Stopped { .. }` 即退出循环。
    pub fn watch_phase(&self) -> watch::Receiver<ActorPhase> {
        self.stop.subscribe()
    }

    /// 非阻塞发送用户消息。
    ///
    /// 邮箱满时返回 [`ActorError::MailboxFull`](背压),由调用方决策重试/降载;
    /// 目标已停止返回 [`ActorError::Closed`]。
    pub fn try_send(&self, msg: M) -> Result<(), ActorError> {
        self.ctl.try_send(msg).map_err(|e| match e {
            mpsc::error::TrySendError::Full(_) => ActorError::MailboxFull(self.id),
            mpsc::error::TrySendError::Closed(_) => ActorError::Closed(self.id),
        })
    }

    /// 异步发送用户消息:邮箱满时等待空位(背压)。
    pub async fn send(&self, msg: M) -> Result<(), ActorError> {
        self.ctl
            .send(msg)
            .await
            .map_err(|_| ActorError::Closed(self.id))
    }

    /// 写入数据端口(仅 [`LossTolerant`](crate::MailboxPolicy::LossTolerant) 策略 Actor 具备)。
    ///
    /// 覆盖式写入,永不阻塞、永不失败排队;返回 false 表示无数据端口
    /// 或读端已消失(Actor 已终止)。
    #[must_use = "返回 false 表示无数据端口或读端已消失"]
    pub fn send_data(&self, msg: M) -> bool {
        match &self.slot {
            Some(w) => w.send(msg),
            None => false,
        }
    }

    /// 获取数据端口写端的克隆(供多个生产者共享,如链路解码任务)。
    pub fn data_port(&self) -> Option<SlotWriter<M>> {
        self.slot.clone()
    }

    /// 是否具备数据端口。
    pub fn has_data_port(&self) -> bool {
        self.slot.is_some()
    }

    /// 通过控制面请求停止(优雅:Actor 处理完当前消息后,在下一轮循环前退出)。
    ///
    /// 与 [`ActorSystem::stop`](crate::ActorSystem::stop) 等价,不阻塞。
    /// 返回是否存在存活的监听端(监督者仍持相位接收端时发送成功;
    /// `false` 表示目标已最终退出,此时相位通道仍会落值但无监听端)。
    #[must_use = "返回是否成功送达停止请求(false 表示目标已退出)"]
    pub fn try_stop(&self) -> bool {
        request_stop(&self.stop, StopCause::Requested)
    }

    /// 请求停止并等待目标最终退出。
    ///
    /// 内部经 [`system`](Self::system) 上溯系统句柄后等价于
    /// [`ActorSystem::stop_and_wait`](crate::ActorSystem::stop_and_wait);
    /// 系统已销毁(弱引用上溯失败)时返回 false(无退出信号可等待)。
    ///
    /// 无限期等待:目标卡死在长 `handle` / `on_stop` 中时本调用将
    /// 永久挂起;需要上限请用
    /// [`stop_and_wait_timeout`](Self::stop_and_wait_timeout)。
    ///
    /// # Panics
    ///
    /// 自调用防护同 [`ActorSystem::stop_and_wait`](crate::ActorSystem::stop_and_wait):
    /// 在目标 Actor 自身的 `handle` 内对自己调用会**立即 panic**。
    pub async fn stop_and_wait(&self) -> bool {
        crate::system::assert_not_self_call(self.id, "stop_and_wait");
        match self.system() {
            Some(system) => system.stop_and_wait(self.id).await,
            None => false,
        }
    }

    /// [`stop_and_wait`](Self::stop_and_wait) 的限时版本:超过 `timeout`
    /// 未观察到最终退出返回 [`ActorError::Timeout`](停止请求本身已送达);
    /// 系统已销毁时返回 `Ok(false)`(目标条目已不存在,无信号可等)。
    ///
    /// # Panics
    ///
    /// 自调用防护同 [`stop_and_wait`](Self::stop_and_wait)。
    pub async fn stop_and_wait_timeout(
        &self,
        timeout: Duration,
    ) -> Result<bool, ActorError> {
        crate::system::assert_not_self_call(self.id, "stop_and_wait_timeout");
        match self.system() {
            Some(system) => system.stop_and_wait_timeout(self.id, timeout).await,
            None => Ok(false),
        }
    }

    /// ask 模式(请求-响应):用 `build` 构造携带应答端口的请求消息,
    /// 等待响应或超时。
    ///
    /// [`Reply`] 由目标 Actor 调用 [`Reply::send`] 回填;
    /// 超时后响应若晚到会被静默丢弃。
    ///
    /// 请求消息经 `try_send` 投递:邮箱满时立即返回
    /// [`AskError::MailboxFull`](不排队);需要等待空位的版本见
    /// [`ask_send`](Self::ask_send)。
    ///
    /// 超时走系统注入时钟(与定时器/看门狗同源):
    /// `ActorSystem::with_clock` 注入虚拟时钟时 ask 超时同样受控。
    ///
    /// # Panics
    ///
    /// 在目标 Actor 自身的 `handle` 内对本 Actor 调用会**立即 panic**(自调用
    /// 防护):响应需由该 Actor 的事件循环处理产生,而事件循环正阻塞在本
    /// 调用上,必然等满超时或死锁 —— 立即失败优于静默等待。经
    /// `tokio::spawn` 转手的调用不被识别(子任务无世代身份),仍会等满超时。
    pub async fn ask<Req, Resp>(
        &self,
        build: impl FnOnce(Reply<Resp>) -> Req,
        timeout: Duration,
    ) -> Result<Resp, AskError>
    where
        Req: Into<M>,
        Resp: ActorMsg,
    {
        crate::system::assert_not_self_call(self.id, "ask");
        let (reply, rx) = Reply::new_pair();
        let deadline = deadline_after(self.clock.now(), timeout);
        self.try_send(build(reply).into())
            .map_err(|e| match e {
                ActorError::MailboxFull(_) => AskError::MailboxFull,
                _ => AskError::Closed,
            })?;
        self.wait_reply(rx, deadline).await
    }

    /// [`ask`](Self::ask) 的等待版:邮箱满时不立即失败,而是排队等待
    /// 空位(背压),适合高峰期指令下行不希望调用方自旋重试的场景。
    ///
    /// `timeout` 是**整体上界**,覆盖入队背压等待与应答等待两段:
    /// 邮箱长期无空位(目标卡死/长任务占住)时同样返回
    /// [`AskError::Timeout`],不会无限挂起。
    ///
    /// # Panics
    ///
    /// 自调用防护同 [`ask`](Self::ask):在目标 `handle` 内对自身调用立即 panic。
    pub async fn ask_send<Req, Resp>(
        &self,
        build: impl FnOnce(Reply<Resp>) -> Req,
        timeout: Duration,
    ) -> Result<Resp, AskError>
    where
        Req: Into<M>,
        Resp: ActorMsg,
    {
        crate::system::assert_not_self_call(self.id, "ask_send");
        let (reply, rx) = Reply::new_pair();
        let deadline = deadline_after(self.clock.now(), timeout);
        tokio::select! {
            biased;
            sent = self.send(build(reply).into()) => sent.map_err(|_| AskError::Closed)?,
            _ = self.clock.sleep_until(deadline) => return Err(AskError::Timeout),
        }
        self.wait_reply(rx, deadline).await
    }

    /// 等待应答或到达 `deadline`(ask / ask_send 共用)。
    ///
    /// deadline 由调用方计算:`ask_send` 的入队背压等待与应答等待共享
    /// 同一整体上界,而非各自起算(否则 timeout 只约束后半段)。
    async fn wait_reply<Resp: ActorMsg>(
        &self,
        rx: oneshot::Receiver<Resp>,
        deadline: tokio::time::Instant,
    ) -> Result<Resp, AskError> {
        tokio::select! {
            biased;
            resp = rx => match resp {
                Ok(value) => Ok(value),
                Err(_cancelled) => Err(AskError::Closed),
            },
            _ = self.clock.sleep_until(deadline) => Err(AskError::Timeout),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::timer::ClockSource;

    fn dummy_ref(ctl: mpsc::Sender<u32>, stop: watch::Sender<ActorPhase>) -> ActorRef<u32> {
        new_ref(
            ActorId::new(1),
            None,
            ctl,
            Arc::new(stop),
            None,
            ClockSource::Tokio,
            Weak::new(),
        )
    }

    #[tokio::test]
    async fn try_send_and_closed() {
        // 单元级验证:通道接收端存活时可发送,被 drop 后报 Closed;
        // is_alive 由相位派生(终态落值后才为 false)
        let (ctl_tx, mut ctl_rx) = mpsc::channel::<u32>(4);
        let (stop_tx, _stop_rx) = watch::channel(ActorPhase::Running);
        let aref = dummy_ref(ctl_tx, stop_tx);
        assert!(aref.is_alive(), "相位 Running 时 is_alive 为 true");
        assert_eq!(aref.try_send(1), Ok(()));
        assert!(matches!(ctl_rx.recv().await, Some(1)));
        drop(ctl_rx);
        assert!(matches!(aref.try_send(2), Err(ActorError::Closed(_))));
        assert!(matches!(aref.send(3).await, Err(ActorError::Closed(_))));
        // 相位落终态(模拟最终退出):is_alive 随之翻 false
        let _ = aref.try_stop();
        assert!(
            matches!(aref.phase(), ActorPhase::Stopped { cause: StopCause::Requested, detail: None }),
            "try_stop 后相位应为 Stopped {{ Requested }}"
        );
        assert!(!aref.is_alive(), "终态落值后 is_alive 为 false");
    }

    #[tokio::test]
    async fn ask_against_closed_mailbox() {
        let (ctl_tx, ctl_rx) = mpsc::channel::<Req>(4);
        let (stop_tx, _stop_rx) = watch::channel(ActorPhase::Running);
        drop(ctl_rx);
        let aref: ActorRef<Req> = new_ref(
            ActorId::new(2),
            None,
            ctl_tx,
            Arc::new(stop_tx),
            None,
            ClockSource::Tokio,
            Weak::new(),
        );
        let res = aref
            .ask::<Req, Vec<u8>>(|reply| Req { reply }, Duration::from_millis(50))
            .await;
        assert_eq!(res.err(), Some(AskError::Closed));
    }

    /// 自调用防护:世代任务内对**自身** ask 立即 panic,
    /// 而非等满 timeout(此处超时设为 60s,防护失效则测试挂起可见)。
    #[tokio::test]
    async fn ask_self_call_panics_fast() {
        let (ctl_tx, _ctl_rx) = mpsc::channel::<u32>(4);
        let (stop_tx, _stop_rx) = watch::channel(ActorPhase::Running);
        let aref = dummy_ref(ctl_tx, stop_tx);
        let id = aref.id();
        let handle = tokio::spawn(crate::system::GENERATION_ACTOR.scope(id, async move {
            let _ = aref
                .ask::<u32, u32>(|_reply| 0, Duration::from_secs(60))
                .await;
        }));
        let err = handle.await.expect_err("世代任务内的自 ask 必须立即 panic");
        let payload = err.into_panic();
        let msg = payload
            .downcast_ref::<String>()
            .expect("assert 消息应为 String 载荷");
        assert!(msg.contains("自调用"), "诊断须点明自调用,实际:{msg}");
    }

    /// 防护不得误伤:世代任务内对**其他** Actor 的 ask 正常放行。
    #[tokio::test]
    async fn ask_other_actor_from_generation_task_is_allowed() {
        let (ctl_tx, mut ctl_rx) = mpsc::channel::<u32>(4);
        let (stop_tx, _stop_rx) = watch::channel(ActorPhase::Running);
        let aref = dummy_ref(ctl_tx, stop_tx); // id = #1
        let handle = tokio::spawn(
            crate::system::GENERATION_ACTOR.scope(ActorId::new(999), async move {
                // 闭包丢弃 Reply(未应答)→ 请求方得到 Closed
                aref.ask::<u32, u32>(|_reply| 7, Duration::from_millis(200)).await
            }),
        );
        assert_eq!(ctl_rx.recv().await, Some(7), "消息须正常投递");
        let res = handle.await.expect("对他 Actor 的 ask 不得 panic");
        assert_eq!(res.err(), Some(AskError::Closed), "未应答 → Closed");
    }

    /// `ActorRef::system()` 生命周期:系统存活时可上溯,句柄(含内部
    /// 持有者)全部销毁后返回 None。
    #[tokio::test]
    async fn system_handle_lifecycle() {
        struct Nop;
        impl crate::Actor for Nop {
            type Message = u32;
            async fn handle(
                &mut self,
                _m: u32,
                _c: &mut crate::ActorContext<u32>,
            ) -> crate::ActorAction {
                crate::ActorAction::Continue
            }
        }
        let system = crate::ActorSystem::new();
        let aref = system.spawn_anonymous(Nop).unwrap();
        {
            let up = aref.system().expect("系统存活时派生句柄必须可上溯");
            assert!(up.is_alive(aref.id()), "上溯句柄应可寻址到自身");
        } // 派生句柄在此释放:它不延长系统存活

        system.shutdown().await;
        drop(system);
        // 监督者任务在 finalize 后退出并释放其内部句柄;轮询等待
        for _ in 0..100 {
            if aref.system().is_none() {
                break;
            }
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
        assert!(
            aref.system().is_none(),
            "系统(含内部持有者)全部销毁后派生句柄必须返回 None"
        );
    }

    /// `ActorRef::stop_and_wait` / `stop_and_wait_timeout` 的委托语义:
    /// - 系统存活:限时版观察到目标最终退出 → `Ok(true)`;条目注销后
    ///   无限期版返回 `false`(无可等待目标);
    /// - 系统已销毁(孤立引用,`Weak::new()`):两方法分别返回
    ///   `false` / `Ok(false)`,不 panic 不挂起。
    #[tokio::test]
    async fn ref_stop_and_wait_delegates_and_handles_dead_system() {
        struct Nop;
        impl crate::Actor for Nop {
            type Message = u32;
            async fn handle(
                &mut self,
                _m: u32,
                _c: &mut crate::ActorContext<u32>,
            ) -> crate::ActorAction {
                crate::ActorAction::Continue
            }
        }
        let system = crate::ActorSystem::new();
        let aref = system.spawn_anonymous(Nop).unwrap();

        assert_eq!(
            aref.stop_and_wait_timeout(Duration::from_secs(5)).await,
            Ok(true),
            "限时等待应观察到目标最终退出"
        );
        // finalize 顺序契约:注册表摘除先于 exit 信号(send(true) 是
        // finalize 最后一步)→ 此刻条目必已不存在
        assert!(!system.is_alive(aref.id()), "目标条目应已注销");
        assert!(
            !aref.stop_and_wait().await,
            "条目已注销,无限期版应返回 false(无退出信号可等待)"
        );

        // 孤立引用:弱引用上溯失败,不得 panic / 挂起
        let (ctl_tx, _ctl_rx) = mpsc::channel::<u32>(4);
        let (stop_tx, _stop_rx) = watch::channel(ActorPhase::Running);
        let orphan = dummy_ref(ctl_tx, stop_tx);
        assert!(!orphan.stop_and_wait().await, "系统已销毁时应返回 false");
        assert_eq!(
            orphan.stop_and_wait_timeout(Duration::from_millis(10)).await,
            Ok(false),
            "系统已销毁时限时版应返回 Ok(false)"
        );
        system.shutdown().await;
    }

    #[allow(dead_code)] // 仅验证构造与类型匹配,通道已关闭故 reply 字段不会被消费
    struct Req {
        reply: Reply<Vec<u8>>,
    }
    // 注意:ActorMsg 由 blanket impl 自动覆盖;Req → M 的转换由核心 From<T> for T 提供。
}