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
563
564
565
566
567
568
569
570
571
572
573
574
//! 运行时上下文 —— Actor 的自引用能力(定时器 / watch / 停止 / 子 Actor)。
//!
//! [`ActorContext`] 持有真实的控制通道发送端克隆:`schedule_once` 的
//! 定时消息会经定时器驱动回投进自己的邮箱,链路看门狗
//! (心跳超时 → 自动返航)因此可以落地。

use crate::addr::{ActorId, ActorName};
use crate::msg::{ActorMsg, ActorPhase, ActorSignal, Signal, StopCause, Terminated, request_stop};
use crate::refs::ActorRef;
use crate::system::{ActorError, ActorSystem, SpawnOptions};
use crate::timer::{TimerHandle, WATCHDOG_FIRED, deadline_after, rel_nanos};
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering};
use std::time::Duration;
use tokio::sync::{mpsc, watch};

/// 每次 [`handle`](crate::Actor::handle) 调用时传入的运行时上下文。
///
/// 每个 Actor 世代持有一份,跨消息复用(零逐消息构造)。
pub struct ActorContext<M: ActorMsg> {
    system: ActorSystem,
    id: ActorId,
    name: Option<ActorName>,
    ctl: mpsc::Sender<M>,
    /// 专用信号通道发送端:watch 竞态复核补发 Terminated、看门狗
    /// 触发标记均经此通道绕过用户消息积压。
    sig: mpsc::Sender<Signal>,
    /// 相位/停止通道:`ctx.stop()` 经 [`request_stop`] 落
    /// `Stopped { cause: Requested }`(不覆盖既有终态)。
    stop: Arc<watch::Sender<ActorPhase>>,
    watched: Vec<ActorId>,
    /// 活跃看门狗:定时器句柄 + 覆盖式待投递消息槽。
    watchdog: Option<WatchdogArm<M>>,
    /// 当前武装世代号(全局单调分配;0 表示从未武装)。
    /// 触发标记携带武装时的世代号,消费时与此值比对去陈旧。
    watchdog_arm: u64,
    /// 世代号(首次启动为 1,每次监督重启 +1)。
    generation: u32,
    /// 已发生的监督重启次数(首次启动为 0)。
    restarts: u32,
}

/// 一次看门狗武装:句柄 + 共享原子 deadline + 覆盖式待投递消息槽。
///
/// deadline 以"距 `base` 的纳秒数"存于 `deadline_ns`:喂狗侧一次
/// atomic swap 滑动,驱动侧到点先 swap 哨兵接管触发权再核对 ——
/// 双方以该原子值为唯一线性化点,喂狗与触发天然串行化,
/// 不存在"已滑动仍误报"的窗口,且滑动零命令、零驱动唤醒。
struct WatchdogArm<M: ActorMsg> {
    handle: TimerHandle,
    /// deadline 基准时刻(武装瞬间的系统时钟读数)。
    base: tokio::time::Instant,
    /// 共享 deadline(距 `base` 的纳秒数);[`WATCHDOG_FIRED`] 为驱动已接管触发权。
    deadline_ns: Arc<AtomicU64>,
    msg: Option<M>,
}

impl<M: ActorMsg> WatchdogArm<M> {
    fn arm(
        system: &ActorSystem,
        arm: u64,
        timeout: Duration,
        sig: mpsc::Sender<Signal>,
        msg: M,
    ) -> Self {
        let base = system.now();
        let deadline_ns = Arc::new(AtomicU64::new(rel_nanos(base, deadline_after(base, timeout))));
        let handle = system.inner.timer.schedule_watchdog(
            base,
            deadline_ns.clone(),
            timeout,
            sig,
            Signal::WatchdogFire { arm },
        );
        Self {
            handle,
            base,
            deadline_ns,
            msg: Some(msg),
        }
    }
}

impl<M: ActorMsg> ActorContext<M> {
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn new(
        system: ActorSystem,
        id: ActorId,
        name: Option<ActorName>,
        ctl: mpsc::Sender<M>,
        stop: Arc<watch::Sender<ActorPhase>>,
        sig: mpsc::Sender<Signal>,
        generation: u32,
        restarts: u32,
    ) -> Self {
        Self {
            system,
            id,
            name,
            ctl,
            sig,
            stop,
            watched: Vec::new(),
            watchdog: None,
            watchdog_arm: 0,
            generation,
            restarts,
        }
    }

    /// 当前世代号(首次启动为 1,每次监督重启 +1)。
    pub fn generation(&self) -> u32 {
        self.generation
    }

    /// 当前恢复窗口内的连续监督重启次数(首次启动为 0)。
    ///
    /// 距上次失败超过 [`crate::RestartPolicy::Transient`] 的 `reset_after`
    /// 后清零 —— 它不是累计值。
    pub fn restarts(&self) -> u32 {
        self.restarts
    }

    /// 当前 Actor 的唯一 ID。
    pub fn id(&self) -> ActorId {
        self.id
    }

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

    /// 所属系统句柄(可克隆、可存入其他任务)。
    pub fn system(&self) -> &ActorSystem {
        &self.system
    }

    /// 当前是否在停机流程中(收到停止/关闭信号但仍在处理收尾消息)。
    ///
    /// 以相位通道判定:停止请求(`ctx.stop()` / `try_stop` / 系统关闭)
    /// 一落值即为 true。注意该判定不区分"停止中"与"已最终退出"。
    pub fn is_stopping(&self) -> bool {
        matches!(&*self.stop.borrow(), ActorPhase::Stopped { .. })
    }

    /// 请求停止自身:处理完当前消息后,事件循环退出 —— 不再交付任何
    /// 用户消息或数据帧(在途控制面信号仍会先抽干送达)。
    ///
    /// 停止位以 `Stopped { cause: Requested }` 落相位通道:
    /// 不覆盖既有终态(真实死因优先),但会覆盖 `Running` / `Restarting`。
    pub fn stop(&self) {
        let _ = request_stop(&self.stop, StopCause::Requested);
    }

    /// 向自身邮箱投递一条消息(非阻塞;邮箱满返回
    /// [`ActorError::MailboxFull`])。
    ///
    /// 常用于状态机自驱动(处理完本条后安排下一步);延迟投递请用
    /// [`schedule_once`](Self::schedule_once)。
    pub fn send_self(&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),
        })
    }

    /// 一次性定时消息:`delay` 后作为普通用户消息投入自己的邮箱。
    ///
    /// 返回的 [`TimerHandle`] 可用于提前取消;句柄丢弃**不会**取消定时器。
    ///
    /// 多数滑动看门狗场景请直接用 [`watchdog`](Self::watchdog),无需手管句柄。
    pub fn schedule_once(&self, delay: Duration, msg: M) -> TimerHandle {
        self.system
            .inner
            .timer
            .schedule_message(delay, self.ctl.clone(), msg)
    }

    /// 周期定时消息:每隔 `interval` 投入一条 `msg` 克隆。
    ///
    /// 弱时钟语义:上次触发后重新计时(不追平错过的周期)。
    /// 目标 Actor 最终退出后条目自动退场,无需手工取消。
    /// `interval` 为零会退化为驱动忙循环,将被钳制为 1ms 并记 warn。
    pub fn schedule_interval(&self, interval: Duration, msg: M) -> TimerHandle
    where
        M: Clone,
    {
        self.system
            .inner
            .timer
            .schedule_interval(interval, self.ctl.clone(), msg)
    }

    /// 滑动看门狗 —— 失控保护的一等 API:每帧调用一次即可。
    ///
    /// - 首次调用:武装定时器,`timeout` 内无后续调用则投递 `msg`;
    /// - 后续调用:滑动重置 deadline —— 一次原子写完成(零跨任务
    ///   命令、零驱动唤醒、零堆操作),并覆盖式更新待投递消息
    ///   (以最近一次调用为准);
    /// - 已触发后再次调用:自动重新武装(无需手工清空状态)。
    ///
    /// 喂狗与触发以共享原子 deadline 为唯一裁决点(驱动到点先以
    /// exchange 接管触发权,再核对 deadline 是否已被推向未来):
    /// 若在触发标记被消费之前已有新帧喂狗(滑动或再武装),该次
    /// 触发被判为陈旧并静默丢弃 —— 不会误投递"刚喂过狗"的报警消息。
    ///
    /// 典型接线:每收到一帧遥测调一次;超时消息(如 `LinkLost`)
    /// 在 `handle` 中执行失控保护动作。
    ///
    /// 触发标记走专用信号通道(与 watch 终止通知同通道),**绕过
    /// 用户消息积压**:即便 `Reliable` 策略下控制通道被慢消息填满,
    /// 触发投递也只会被至多一条正在处理的用户消息延后,失控保护
    /// 时延有界。
    ///
    /// # 语义与选参:度量"处理节奏",而非"到达节奏"
    ///
    /// 喂狗点在 `handle` 内 —— "超时"指 `timeout` 内没有任何消息被
    /// **处理**到喂狗行,而非没有新帧**到达**。邮箱积压、单条消息
    /// 处理过慢、CPU 竞争都可能让已到达的帧来不及喂狗;此时触发
    /// 失控保护是应有语义(会话已无法及时响应),但 `timeout` 必须按
    /// **最坏处理时延**选取(建议 ≥ 10× 正常处理抖动),不能直接取
    /// "帧到达间隔 × 小常数"。
    ///
    /// 重启空窗:监督重启后的新世代**不会自动武装**看门狗(旧世代
    /// 武装随上下文析构取消),保护自重启后首帧喂狗起恢复。若重启
    /// 窗口内也需保持保护,可在 [`on_start`](crate::Actor::on_start) /
    /// [`on_restart`](crate::Actor::on_restart) 中按记录的最近帧到达
    /// 时间戳立即补喂(调用本方法),或在接收侧用
    /// [`schedule_interval`](Self::schedule_interval) 维持独立心跳。
    ///
    /// # 示例(链路看门狗)
    ///
    /// ```
    /// use wordval_actor::{Actor, ActorAction, ActorContext};
    /// use std::time::Duration;
    ///
    /// struct Vehicle;
    /// enum Msg { Frame, LinkLost }
    ///
    /// impl Actor for Vehicle {
    ///     type Message = Msg;
    ///
    ///     async fn handle(&mut self, msg: Msg, ctx: &mut ActorContext<Msg>) -> ActorAction {
    ///         match msg {
    ///             Msg::Frame => {
    ///                 self.apply();
    ///                 ctx.watchdog(Duration::from_secs(3), Msg::LinkLost); // 每帧一行
    ///             }
    ///             Msg::LinkLost => self.failsafe(),
    ///         }
    ///         ActorAction::Continue
    ///     }
    /// }
    /// # impl Vehicle {
    /// #     fn apply(&mut self) {}
    /// #     fn failsafe(&mut self) {}
    /// # }
    /// ```
    pub fn watchdog(&mut self, timeout: Duration, msg: M) {
        let mut msg = Some(msg);
        if let Some(arm) = self.watchdog.as_mut() {
            if !arm.handle.has_fired() {
                // 喂狗 = 一次原子 swap:先存新 deadline,再看旧值是否
                // 已被驱动以哨兵接管 —— 胜负由该原子值的线性化顺序裁决
                let new_rel = rel_nanos(arm.base, deadline_after(self.system.now(), timeout));
                let prev = arm.deadline_ns.swap(new_rel, AtomicOrdering::AcqRel);
                if prev != WATCHDOG_FIRED {
                    arm.msg = msg.take();
                    return; // 滑动成功:零跨任务命令、零驱动唤醒
                }
                // 此分支 msg 必须保持未消费:下面的换代再武装依赖它(见其 expect)
                // 驱动已接管触发权(WatchdogFire 在途):换代再武装,
                // 在途触发在消费时按旧 arm 判陈旧丢弃
            }
        }
        // 首次武装 / 已触发后再武装 / 与触发竞态后的换代再武装:
        // 分配新的武装世代号,一切在途的旧世代触发标记(含异步补投)
        // 在消费时将被丢弃
        if let Some(old) = self.watchdog.take() {
            // 触发竞态下驱动可能已把旧条目按旧 deadline 重新入堆:
            // 显式取消使其立即退场(已触发的条目为 no-op)。
            // 在途旧触发的作废由世代号比对兜底,与取消互为独立防线。
            old.handle.cancel();
        }
        let seq = self.system.inner.next_watchdog_arm();
        let sig = self.sig.clone();
        self.watchdog_arm = seq;
        self.watchdog = Some(WatchdogArm::arm(
            &self.system,
            seq,
            timeout,
            sig,
            msg.take().expect("msg 未被滑动分支消费"),
        ));
    }

    /// 解除看门狗:取消未触发的定时器并清空状态(如主动断链后不再需要保护)。
    ///
    /// 已触发的看门狗无需调用本方法 —— 下次 [`watchdog`](Self::watchdog)
    /// 调用会自动重新武装。解除后,一切在途的触发标记(含陈旧补投)
    /// 均被判为失效,不会再投递超时消息。
    pub fn disarm_watchdog(&mut self) {
        if let Some(arm) = self.watchdog.take() {
            arm.handle.cancel();
            // 换代使在途触发标记失效(消费时按 arm 比对丢弃)
            self.watchdog_arm = self.system.inner.next_watchdog_arm();
        }
    }

    /// 消费一条看门狗触发标记(由事件循环调用)。
    ///
    /// 返回应投递给 [`handle`](crate::Actor::handle) 的超时消息;
    /// 若触发所属的武装世代已被喂狗/解除/再武装取代(陈旧触发),
    /// 返回 `None` 静默丢弃。同一标记最多投递一次。
    pub(crate) fn take_watchdog_fire(&mut self, arm: u64) -> Option<M> {
        if arm != self.watchdog_arm {
            tracing::debug!(
                actor = %self.id,
                arm,
                current = self.watchdog_arm,
                "看门狗触发已陈旧(已被喂狗/再武装/解除取代),丢弃"
            );
            return None;
        }
        self.watchdog.as_mut()?.msg.take()
    }

    /// 监视目标 Actor:其终止时(含 panic / 资源耗尽 / 被停止),
    /// 本 Actor 收到 [`ActorSignal::Terminated`],
    /// 经 [`on_signal`](crate::Actor::on_signal) 送达。
    pub fn watch<T: ActorMsg>(&mut self, target: &ActorRef<T>) {
        self.watch_id(target.id());
    }

    /// 按 ID 监视目标 Actor。
    ///
    /// 幂等:重复 watch 同一目标为 no-op(不重复登记、不重复通知)。
    /// watch 为一次性语义 —— 目标终止通知送达时关系自动解除
    /// (无需 [`unwatch_id`](Self::unwatch_id)),此后可直接重新监视。
    ///
    /// 注册与目标 finalize 之间存在竞态窗口(finalize 先移除注册表
    /// 条目再消费 watch 反向索引):若注册时目标已注销,则区分两条
    /// 互斥路径 —— 登记仍由本端持有(finalize 尚未消费)时补发
    /// [`StopCause::Missing`];登记已被 finalize 消费时真实 Terminated
    /// 已在路上。两条路径保证通知**恰好一次**送达。
    ///
    /// 例外(可收到两次通知):目标终止过程中先
    /// [`unwatch_id`](Self::unwatch_id) 再立即重 watch 同一目标时,
    /// 真实 Terminated 可能已在途(重登记前的投递),而重登记又会因
    /// "目标已注销"补发 Missing —— 两条通知各有所据(目标确实终止 +
    /// 重登记时确实不可见),消费方按幂等处理即可。
    pub fn watch_id(&mut self, target: ActorId) {
        if target == self.id {
            return; // 不允许监视自己
        }
        if self.watched.contains(&target) {
            return; // 幂等:重复 watch 不产生重复登记与重复通知
        }
        self.watched.push(target);
        self.system.inner.register_watch(self.id, target);
        if !self.system.is_alive(target) {
            // 竞态复核:unregister 返回 true 表示登记仍存(finalize 未消费),
            // 由本端补发 Missing;返回 false 表示 finalize 已取走登记,
            // 真实 Terminated 已在路上,不得重复补发
            self.watched.retain(|&t| t != target);
            if self.system.inner.unregister_watch(self.id, target) {
                let notice = ActorSignal::Terminated(Terminated {
                    actor: target,
                    name: None,
                    cause: StopCause::Missing,
                    detail: None,
                });
                // 同步上下文无法 await:转交独立任务带背压补投,
                // 保证通知不因信号通道瞬时满载而丢失(exactly-once 契约)
                let tx = self.sig.clone();
                tokio::spawn(async move {
                    if tx.send(Signal::System(notice)).await.is_err() {
                        tracing::warn!("watch 竞态复核:补发 Terminated 失败(信号通道已关闭)")
                    }
                });
            }
        }
    }

    /// Terminated 送达时的 watcher 侧自愈(由事件循环统一分发调用):
    /// 清除 `ctx.watched` 并解除全局 watching/watched_by 双向登记。
    ///
    /// 目标既已终止且 ID 单调不复用,任何残留登记只余泄漏价值 ——
    /// 无条件解除(含跨世代登记),使 watch 回归真正的一次性语义:
    /// 收到终止后可直接重新 watch,无需先显式 unwatch。
    pub(crate) fn reap_watch(&mut self, target: ActorId) {
        self.watched.retain(|&t| t != target);
        self.system.inner.unregister_watch(self.id, target);
    }

    /// 取消对目标的监视。
    pub fn unwatch<T: ActorMsg>(&mut self, target: &ActorRef<T>) {
        self.unwatch_id(target.id());
    }

    /// 按 ID 取消监视。
    pub fn unwatch_id(&mut self, target: ActorId) {
        self.watched.retain(|&t| t != target);
        self.system.inner.unregister_watch(self.id, target);
    }

    /// 派生子 Actor:自动建立"本 Actor 监视子 Actor"的关系,
    /// 子 Actor 终止时本 Actor 收到 Terminated 信号。
    /// 受监督版本(panic 后自动重建)见
    /// [`spawn_child_supervised`](Self::spawn_child_supervised)。
    ///
    /// 子 Actor 不随父 Actor 停止而级联停止(场景下机体
    /// 会话可能比管理组件生命周期更长;级联策略留给上层)。
    ///
    /// 注意:该 watch 关系直接登记进系统全局索引(不进当前上下文的
    /// `watched` 本地列表),因此**跨监督重启世代存活**:父 Actor
    /// panic 重启后,子 Actor 的终止通知仍会送达新世代(信号通道
    /// 租约跨世代续存)。
    pub fn spawn_child<A: crate::Actor>(
        &self,
        opts: impl Into<SpawnOptions>,
        actor: A,
    ) -> Result<ActorRef<A::Message>, ActorError> {
        let opts = opts.into().with_parent(self.id);
        self.system.spawn(opts, actor)
    }

    /// 受监督派生子 Actor:`spawn_child` 与
    /// [`spawn_supervised`](crate::ActorSystem::spawn_supervised) 的组合 ——
    /// 自动建立"本 Actor 监视子 Actor"关系(同 [`spawn_child`](Self::spawn_child)),
    /// 子 Actor panic 后按策略用 `factory` 重建实例。
    ///
    /// 监视登记与 spawn 原子完成(先登记后启动世代),因此不存在
    /// "spawn 后补 watch"的竞态窗口:子 Actor 最终终止时父 Actor 收到的
    /// Terminated 恒携带真实死因(不会退化为 `Missing`)。
    pub fn spawn_child_supervised<A, F>(
        &self,
        opts: impl Into<SpawnOptions>,
        factory: F,
    ) -> Result<ActorRef<A::Message>, ActorError>
    where
        A: crate::Actor,
        F: Fn() -> A + Send + Sync + 'static,
    {
        let opts = opts.into().with_parent(self.id);
        self.system.spawn_supervised(opts, factory)
    }
}

/// 世代结束即取消看门狗条目:句柄析构不取消是用户定时器
/// (`schedule_once` / `schedule_interval`)的显式语义,而看门狗由框架
/// 托管(用户只调 [`ActorContext::watchdog`])—— 不随世代退场会在驱动内
/// 滞留至超时时刻,长超时场景下条目与信号通道发送端克隆长期空占,
/// 并空醒驱动一次。在途触发标记的失效仍由武装世代号比对兜底。
impl<M: ActorMsg> Drop for ActorContext<M> {
    fn drop(&mut self) {
        if let Some(arm) = self.watchdog.take() {
            arm.handle.cancel();
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::timer::WATCHDOG_FIRED;
    use std::sync::atomic::Ordering as AO;

    /// 回归:驱动已以哨兵接管触发权、但 fired 尚未置位的竞态窗口内
    /// 调用 `watchdog()`,必须走"换代再武装"而非 panic。
    #[tokio::test]
    async fn refeed_in_driver_claim_window_rearms_without_panic() {
        let system = ActorSystem::new();
        let (ctl_tx, _ctl_rx) = mpsc::channel::<u32>(8);
        let (stop_tx, _stop_rx) = watch::channel(ActorPhase::Running);
        let (sig_tx, _sig_rx) = mpsc::channel::<Signal>(8);
        let mut ctx: ActorContext<u32> = ActorContext::new(
            system.clone(),
            ActorId::new(1),
            None,
            ctl_tx,
            Arc::new(stop_tx),
            sig_tx,
            1,
            0,
        );

        ctx.watchdog(Duration::from_secs(60), 7u32);
        let old_arm = ctx.watchdog_arm;
        {
            let arm = ctx.watchdog.as_ref().expect("已武装");
            arm.deadline_ns.store(WATCHDOG_FIRED, AO::Relaxed);
            assert!(!arm.handle.has_fired(), "前置:fired 未置位");
        }

        // 窗口内喂狗:换代再武装,携带最新消息
        ctx.watchdog(Duration::from_secs(60), 8u32);
        assert_ne!(ctx.watchdog_arm, old_arm, "必须换代,旧在途触发作废");
        assert_eq!(
            system.inner.timer.active_entries().await,
            1,
            "换代再武装必须收敛旧条目(驱动内仅余新条目)"
        );
        assert_eq!(
            ctx.take_watchdog_fire(old_arm),
            None,
            "旧世代触发应判陈旧丢弃"
        );
        assert_eq!(
            ctx.take_watchdog_fire(ctx.watchdog_arm),
            Some(8u32),
            "新世代触发应投递最新消息"
        );
        system.shutdown().await;
    }

    /// 回归:看门狗武装与滑动在极端 `Duration` 下不得溢出 panic
    /// (deadline 经 `deadline_after` 钳制为远期时刻)。
    #[tokio::test]
    async fn watchdog_extreme_timeout_does_not_panic() {
        let system = ActorSystem::new();
        let (ctl_tx, _ctl_rx) = mpsc::channel::<u32>(8);
        let (stop_tx, _stop_rx) = watch::channel(ActorPhase::Running);
        let (sig_tx, _sig_rx) = mpsc::channel::<Signal>(8);
        let mut ctx: ActorContext<u32> = ActorContext::new(
            system.clone(),
            ActorId::new(1),
            None,
            ctl_tx,
            Arc::new(stop_tx),
            sig_tx,
            1,
            0,
        );
        ctx.watchdog(Duration::MAX, 7u32); // 武装路径
        ctx.watchdog(Duration::MAX, 8u32); // 滑动路径
        ctx.disarm_watchdog();
        system.shutdown().await;
    }

    /// 回归:世代上下文析构必须取消看门狗条目 —— 条目不得滞留驱动
    /// 直至超时时刻(长超时场景可见),也不得空醒驱动。
    #[tokio::test]
    async fn watchdog_entry_retires_when_ctx_dropped() {
        let system = ActorSystem::new();
        let (ctl_tx, _ctl_rx) = mpsc::channel::<u32>(8);
        let (stop_tx, _stop_rx) = watch::channel(ActorPhase::Running);
        let (sig_tx, _sig_rx) = mpsc::channel::<Signal>(8);
        let mut ctx: ActorContext<u32> = ActorContext::new(
            system.clone(),
            ActorId::new(1),
            None,
            ctl_tx,
            Arc::new(stop_tx),
            sig_tx,
            1,
            0,
        );
        ctx.watchdog(Duration::from_secs(3600), 7u32);
        assert_eq!(
            system.inner.timer.active_entries().await,
            1,
            "武装后看门狗条目应在驱动内"
        );
        drop(ctx);
        assert_eq!(
            system.inner.timer.active_entries().await,
            0,
            "ctx 析构必须取消看门狗条目(不得滞留至超时)"
        );
        system.shutdown().await;
    }
}