wse 3.1.0

WebSocket engine for reactive user interfaces: topics with message recovery, presence, clustering without a broker, JWT, end-to-end encryption and signed messages.
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
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
use ahash::AHashSet;
use pyo3::prelude::*;
use pyo3::types::{PyDict, PyList};
use std::collections::{BTreeMap, HashMap, VecDeque};
use std::sync::Mutex;
use std::time::Instant;

use super::pylock::lock;
use super::queue::INITIAL_CAPACITY_CAP;

/// A dedup window must hold at least one id.
fn check_window(window_size: usize) -> PyResult<()> {
    if window_size == 0 {
        return Err(pyo3::exceptions::PyValueError::new_err(
            "window_size must be at least 1",
        ));
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// RustSequencer -- simple version, kept for backward compatibility
// ---------------------------------------------------------------------------

/// Simple event sequencer with deduplication.
///
/// Assigns monotonically increasing sequence numbers and tracks recently
/// seen event IDs to detect duplicates. Old entries are evicted either when
/// the window is full (size-based) or via explicit `cleanup` (age-based).
///
/// Uses `ahash::AHashSet` for O(1) lookups with a fast non-cryptographic
/// hash, and a `VecDeque` to maintain insertion order for eviction.
///
/// Safe to share between threads, also on free-threaded Python: every call
/// runs under the sequencer's lock, so no two callers get the same number.
#[pyclass(frozen)]
pub struct RustSequencer {
    state: Mutex<SequencerState>,
}

/// The mutable part of [`RustSequencer`], behind its lock.
struct SequencerState {
    sequence: u64,
    seen_ids: AHashSet<String>,
    seen_ids_order: VecDeque<(String, Instant)>,
    window_size: usize,
}

impl SequencerState {
    fn new(window_size: usize) -> Self {
        Self {
            sequence: 0,
            seen_ids: AHashSet::with_capacity(window_size.min(INITIAL_CAPACITY_CAP)),
            seen_ids_order: VecDeque::with_capacity(window_size.min(INITIAL_CAPACITY_CAP)),
            window_size,
        }
    }

    fn next_seq(&mut self) -> u64 {
        self.sequence += 1;
        self.sequence
    }

    fn is_duplicate(&mut self, event_id: &str) -> bool {
        if self.seen_ids.contains(event_id) {
            return true;
        }

        // Evict oldest if at capacity.
        if self.seen_ids.len() >= self.window_size
            && let Some((oldest_id, _)) = self.seen_ids_order.pop_front()
        {
            self.seen_ids.remove(&oldest_id);
        }

        let owned = event_id.to_owned();
        self.seen_ids.insert(owned.clone());
        self.seen_ids_order.push_back((owned, Instant::now()));
        false
    }

    fn cleanup(&mut self, max_age_secs: f64) {
        let now = Instant::now();
        while let Some((id, timestamp)) = self.seen_ids_order.front() {
            let age = now.duration_since(*timestamp).as_secs_f64();
            if age > max_age_secs {
                let id = id.clone();
                self.seen_ids_order.pop_front();
                self.seen_ids.remove(&id);
            } else {
                // All remaining entries are newer.
                break;
            }
        }
    }
}

#[pymethods]
impl RustSequencer {
    /// Create a new sequencer.
    ///
    /// # Arguments
    /// * `window_size` - Maximum number of event IDs to track for dedup.
    #[new]
    fn new(window_size: usize) -> PyResult<Self> {
        check_window(window_size)?;
        Ok(Self {
            state: Mutex::new(SequencerState::new(window_size)),
        })
    }

    /// Increment the sequence counter and return the new value.
    fn next_seq(&self, py: Python<'_>) -> u64 {
        lock(py, &self.state).next_seq()
    }

    /// Return the current sequence number without incrementing.
    fn get_current_seq(&self, py: Python<'_>) -> u64 {
        lock(py, &self.state).sequence
    }

    /// Check if `event_id` is a duplicate.
    ///
    /// If the ID has been seen before, returns `true`.
    /// If not, records it and returns `false`. When the set exceeds
    /// `window_size`, the oldest entry is evicted to make room.
    fn is_duplicate(&self, py: Python<'_>, event_id: &str) -> bool {
        lock(py, &self.state).is_duplicate(event_id)
    }

    /// Remove all entries older than `max_age_secs` seconds.
    ///
    /// Scans from the front of the ordered deque (oldest first) and removes
    /// entries whose timestamp is older than the cutoff. Stops as soon as
    /// it encounters an entry within the age window since the deque is
    /// ordered by insertion time.
    fn cleanup(&self, py: Python<'_>, max_age_secs: f64) {
        lock(py, &self.state).cleanup(max_age_secs);
    }

    /// Return the number of event IDs currently tracked.
    fn seen_count(&self, py: Python<'_>) -> usize {
        lock(py, &self.state).seen_ids.len()
    }
}

// ---------------------------------------------------------------------------
// RustEventSequencer -- full parity with Python EventSequencer
// ---------------------------------------------------------------------------

/// A buffered event waiting for its turn to be delivered in-order.
/// Mirrors the Python `SequencedEvent` dataclass.
struct BufferedEvent {
    // The sequence is the BTreeMap key, so it is not duplicated in the value.
    timestamp: Instant,
    payload: Py<PyAny>,
}

/// Buffered events the sequencer let go of while its lock was held.
///
/// They are dropped only after the lock is released: dropping the last reference
/// to an event runs Python code (`__del__`, weakref callbacks), and that code
/// could call back into the same sequencer and wait for the lock forever.
type Released = Vec<BufferedEvent>;

/// Full-featured event sequencer with deduplication, per-topic ordering,
/// out-of-order buffering, and gap detection.
///
/// This is the Rust counterpart of the Python `EventSequencer` class from
/// `wse_event_sequencer.py`, providing complete API parity.
///
/// Safe to share between threads, also on free-threaded Python: every call
/// runs under the sequencer's lock.
#[pyclass(frozen)]
pub struct RustEventSequencer {
    state: Mutex<EventSequencerState>,
}

/// The mutable part of [`RustEventSequencer`], behind its lock.
struct EventSequencerState {
    /// Global monotonically-increasing sequence counter.
    sequence: u64,
    /// Fast set of recently seen event IDs for dedup.
    seen_ids: AHashSet<String>,
    /// Ordered queue for evicting oldest seen IDs.
    seen_ids_queue: VecDeque<String>,
    /// Maximum number of event IDs to track.
    window_size: usize,
    /// Maximum gap between expected and received sequence before reset.
    max_out_of_order: u64,

    /// Per-topic: the next expected sequence number.
    expected_sequences: HashMap<String, u64>,
    /// Per-topic: buffered future events keyed by sequence number.
    buffered_events: HashMap<String, BTreeMap<u64, BufferedEvent>>,
    /// Per-topic: last time any event was processed. Drives idle-TTL eviction of
    /// the ordering cursor so cleanup does NOT drop a live in-order topic's
    /// cursor merely because its reorder buffer is momentarily empty.
    last_activity: HashMap<String, Instant>,

    // Stats
    duplicate_count: u64,
    out_of_order_count: u64,
    dropped_count: u64,
}

impl EventSequencerState {
    fn new(window_size: usize, max_out_of_order: u64) -> Self {
        Self {
            sequence: 0,
            seen_ids: AHashSet::with_capacity(window_size.min(INITIAL_CAPACITY_CAP)),
            seen_ids_queue: VecDeque::with_capacity(window_size.min(INITIAL_CAPACITY_CAP)),
            window_size,
            max_out_of_order,
            expected_sequences: HashMap::new(),
            buffered_events: HashMap::new(),
            last_activity: HashMap::new(),
            duplicate_count: 0,
            out_of_order_count: 0,
            dropped_count: 0,
        }
    }

    fn next_seq(&mut self) -> u64 {
        self.sequence += 1;
        self.sequence
    }

    fn is_duplicate(&mut self, event_id: &str) -> bool {
        if self.seen_ids.contains(event_id) {
            self.duplicate_count += 1;
            return true;
        }

        // Evict the oldest when the queue is at capacity.
        if self.seen_ids_queue.len() >= self.window_size
            && let Some(old_id) = self.seen_ids_queue.pop_front()
        {
            self.seen_ids.remove(&old_id);
        }

        let owned = event_id.to_owned();
        self.seen_ids.insert(owned.clone());
        self.seen_ids_queue.push_back(owned);

        false
    }

    fn process_sequenced_event<'py>(
        &mut self,
        py: Python<'py>,
        topic: &str,
        sequence: u64,
        event: Bound<'py, PyAny>,
        released: &mut Released,
    ) -> PyResult<Bound<'py, PyAny>> {
        let topic_owned = topic.to_owned();

        // Record activity so cleanup's idle-TTL eviction keeps this topic's
        // ordering cursor alive while it is live (allocates the key only the
        // first time the topic is seen).
        match self.last_activity.get_mut(topic) {
            Some(ts) => *ts = Instant::now(),
            None => {
                self.last_activity
                    .insert(topic_owned.clone(), Instant::now());
            }
        }

        // Initialize topic tracking on first event.
        if !self.expected_sequences.contains_key(&topic_owned) {
            self.expected_sequences
                .insert(topic_owned.clone(), sequence + 1);
            if let Some(stale) = self.buffered_events.insert(topic_owned, BTreeMap::new()) {
                released.extend(stale.into_values());
            }

            let result = PyList::new(py, [event.clone()])?;
            return Ok(result.into_any());
        }

        let expected = *self.expected_sequences.get(&topic_owned).unwrap();

        if sequence == expected {
            // This is the expected sequence -- deliver it and any consecutive buffered.
            let mut events_to_deliver: Vec<Bound<'py, PyAny>> = Vec::new();
            events_to_deliver.push(event.clone());

            let mut next_expected = sequence + 1;

            if let Some(buffer) = self.buffered_events.get_mut(&topic_owned) {
                while buffer.contains_key(&next_expected) {
                    let buffered = buffer.remove(&next_expected).unwrap();
                    events_to_deliver.push(buffered.payload.into_bound(py));
                    next_expected += 1;
                }
            }

            self.expected_sequences.insert(topic_owned, next_expected);

            let result = PyList::new(py, events_to_deliver)?;
            Ok(result.into_any())
        } else if sequence > expected {
            // Future event -- either buffer or reset.
            self.out_of_order_count += 1;

            if sequence - expected > self.max_out_of_order {
                // Gap too large -- drop intermediates, reset, deliver current.
                self.dropped_count += sequence - expected - 1;
                self.expected_sequences
                    .insert(topic_owned.clone(), sequence + 1);
                if let Some(buffer) = self.buffered_events.get_mut(&topic_owned) {
                    released.extend(std::mem::take(buffer).into_values());
                }

                let result = PyList::new(py, [event.clone()])?;
                Ok(result.into_any())
            } else {
                // Buffer the event for later delivery.
                let buffered = BufferedEvent {
                    timestamp: Instant::now(),
                    payload: event.clone().unbind(),
                };

                if let Some(replaced) = self
                    .buffered_events
                    .entry(topic_owned)
                    .or_default()
                    .insert(sequence, buffered)
                {
                    released.push(replaced);
                }

                Ok(py.None().into_bound(py))
            }
        } else {
            // Old event -- drop it.
            self.dropped_count += 1;
            Ok(py.None().into_bound(py))
        }
    }

    fn reset_sequence(&mut self, topic: Option<&str>, released: &mut Released) {
        match topic {
            Some(t) => {
                self.expected_sequences.remove(t);
                if let Some(buffer) = self.buffered_events.remove(t) {
                    released.extend(buffer.into_values());
                }
                self.last_activity.remove(t);
            }
            None => {
                self.expected_sequences.clear();
                released.extend(
                    self.buffered_events
                        .drain()
                        .flat_map(|(_, buffer)| buffer.into_values()),
                );
                self.last_activity.clear();
            }
        }
    }

    fn get_sequence_stats<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyDict>> {
        let stats = PyDict::new(py);
        let topic_stats = PyDict::new(py);
        let mut total_buffered: usize = 0;

        for (topic, &expected) in &self.expected_sequences {
            let empty_tree = BTreeMap::new();
            let buffered = self.buffered_events.get(topic).unwrap_or(&empty_tree);
            total_buffered += buffered.len();

            let topic_dict = PyDict::new(py);
            topic_dict.set_item("expected", expected)?;
            topic_dict.set_item("buffered", buffered.len())?;

            // Compute gaps.
            let gaps = PyList::empty(py);
            if !buffered.is_empty() {
                let sequences: Vec<u64> = buffered.keys().copied().collect();
                let mut last = expected;
                for &seq in &sequences {
                    if seq - last > 1 {
                        let gap = PyDict::new(py);
                        gap.set_item("start", last + 1)?;
                        gap.set_item("end", seq - 1)?;
                        gap.set_item("size", seq - last - 1)?;
                        gaps.append(gap)?;
                    }
                    last = seq;
                }
            }
            topic_dict.set_item("gaps", gaps)?;

            // buffered_sequences
            let buffered_seqs: Vec<u64> = buffered.keys().copied().collect();
            let buffered_seqs_list = PyList::new(py, &buffered_seqs)?;
            topic_dict.set_item("buffered_sequences", buffered_seqs_list)?;

            topic_stats.set_item(topic, topic_dict)?;
        }

        stats.set_item("current_sequence", self.sequence)?;
        stats.set_item("duplicate_count", self.duplicate_count)?;
        stats.set_item("out_of_order_count", self.out_of_order_count)?;
        stats.set_item("dropped_count", self.dropped_count)?;
        stats.set_item("topics", topic_stats)?;
        stats.set_item("total_topics", self.expected_sequences.len())?;
        stats.set_item("total_buffered", total_buffered)?;
        stats.set_item("seen_ids_count", self.seen_ids.len())?;

        Ok(stats)
    }

    fn get_buffer_stats<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyDict>> {
        let stats = PyDict::new(py);
        let topics_dict = PyDict::new(py);
        let now = Instant::now();

        let total_buffered: usize = self
            .buffered_events
            .values()
            .map(|events| events.len())
            .sum();

        for (topic, &expected) in &self.expected_sequences {
            if let Some(buffered) = self.buffered_events.get(topic)
                && !buffered.is_empty()
            {
                let sequences: Vec<u64> = buffered.keys().copied().collect();
                let gap_size = sequences.first().map_or(0, |&first| first - expected);

                let oldest_age = buffered
                    .values()
                    .map(|e| now.duration_since(e.timestamp).as_secs_f64())
                    .fold(0.0_f64, f64::max);

                let topic_dict = PyDict::new(py);
                topic_dict.set_item("expected_sequence", expected)?;
                topic_dict.set_item("buffered_count", buffered.len())?;
                let seqs_list = PyList::new(py, &sequences)?;
                topic_dict.set_item("buffered_sequences", seqs_list)?;
                topic_dict.set_item("gap_size", gap_size)?;
                topic_dict.set_item("oldest_buffered_age", oldest_age)?;

                topics_dict.set_item(topic, topic_dict)?;
            }
        }

        stats.set_item("total_topics", self.expected_sequences.len())?;
        stats.set_item("total_buffered", total_buffered)?;
        stats.set_item("topics", topics_dict)?;

        Ok(stats)
    }

    fn cleanup(&mut self, released: &mut Released) {
        let now = Instant::now();

        // Topic ordering state (cursor + reorder buffer) is retired only after a
        // topic has been idle this long -- never merely because its reorder
        // buffer drained (the healthy in-order case).
        const TTL_SECS: f64 = 300.0;

        // Drop buffered (out-of-order) events older than the TTL; reclaims memory
        // for gaps that never filled, without touching the cursor.
        for events in self.buffered_events.values_mut() {
            let to_remove: Vec<u64> = events
                .iter()
                .filter(|(_, e)| now.duration_since(e.timestamp).as_secs_f64() > TTL_SECS)
                .map(|(&seq, _)| seq)
                .collect();

            for seq in to_remove {
                if let Some(expired) = events.remove(&seq) {
                    released.push(expired);
                }
                self.dropped_count += 1;
            }
        }

        // Evict per-topic ordering state ONLY for topics idle past the TTL.
        // The old trigger ("reorder buffer is empty") dropped a live in-order
        // topic's expected-sequence cursor, resetting gap detection: the next
        // event was then treated as a brand-new topic start, so a real gap went
        // unnoticed and a stale/duplicate sequence could roll the cursor
        // backwards into a reset storm.
        let idle_topics: Vec<String> = self
            .expected_sequences
            .keys()
            .filter(|t| {
                self.last_activity
                    .get(*t)
                    .is_none_or(|ts| now.duration_since(*ts).as_secs_f64() > TTL_SECS)
            })
            .cloned()
            .collect();
        for topic in idle_topics {
            self.expected_sequences.remove(&topic);
            if let Some(buffer) = self.buffered_events.remove(&topic) {
                released.extend(buffer.into_values());
            }
            self.last_activity.remove(&topic);
        }

        // Trim seen_ids if significantly over window_size.
        let threshold = (self.window_size as f64 * 1.5) as usize;
        if self.seen_ids.len() > threshold {
            let keep_count = self.window_size;
            let drain_count = self.seen_ids_queue.len().saturating_sub(keep_count);

            for _ in 0..drain_count {
                if let Some(old_id) = self.seen_ids_queue.pop_front() {
                    self.seen_ids.remove(&old_id);
                }
            }
        }
    }
}

#[pymethods]
impl RustEventSequencer {
    /// Create a new event sequencer.
    ///
    /// # Arguments
    /// * `window_size` - Maximum number of event IDs to track for dedup (default 10000).
    /// * `max_out_of_order` - Maximum gap before resetting topic sequence (default 100).
    #[new]
    #[pyo3(signature = (window_size=10000, max_out_of_order=100))]
    fn new(window_size: usize, max_out_of_order: u64) -> PyResult<Self> {
        check_window(window_size)?;
        Ok(Self {
            state: Mutex::new(EventSequencerState::new(window_size, max_out_of_order)),
        })
    }

    /// Increment the sequence counter and return the new value.
    fn next_seq(&self, py: Python<'_>) -> u64 {
        lock(py, &self.state).next_seq()
    }

    /// Return the current sequence number without incrementing.
    fn get_current_sequence(&self, py: Python<'_>) -> u64 {
        lock(py, &self.state).sequence
    }

    /// Check if an event is a duplicate within the dedup window.
    ///
    /// If the ID has been seen before, increments `duplicate_count` and
    /// returns `true`. Otherwise records the ID and returns `false`.
    /// When the seen queue reaches `window_size`, the oldest entry is evicted
    /// from both the queue and the set before inserting the new one.
    ///
    /// Matches Python behavior: deque(maxlen=window_size) auto-evicts on
    /// append, then the set is cleaned via discard of the current front.
    fn is_duplicate(&self, py: Python<'_>, event_id: &str) -> bool {
        lock(py, &self.state).is_duplicate(event_id)
    }

    /// Process an event with a sequence number, maintaining per-topic order.
    ///
    /// Returns:
    /// - A list of dicts if events can be delivered (the current event plus
    ///   any buffered events that are now in order).
    /// - `None` if the event was buffered or dropped.
    ///
    /// Behavior:
    /// - First event on a topic initializes tracking and is delivered immediately.
    /// - If `sequence == expected`: deliver it and flush consecutive buffered events.
    /// - If `sequence > expected` but within `max_out_of_order`: buffer for later.
    /// - If `sequence > expected` beyond `max_out_of_order`: reset topic, deliver current.
    /// - If `sequence < expected`: drop (old/duplicate event).
    #[pyo3(signature = (topic, sequence, event))]
    fn process_sequenced_event<'py>(
        &self,
        py: Python<'py>,
        topic: &str,
        sequence: u64,
        event: Bound<'py, PyAny>,
    ) -> PyResult<Bound<'py, PyAny>> {
        let mut released = Released::new();
        let result = {
            let mut state = lock(py, &self.state);
            state.process_sequenced_event(py, topic, sequence, event, &mut released)
        };
        drop(released); // after the lock, see `Released`
        result
    }

    /// Reset sequence tracking for a specific topic or all topics.
    ///
    /// # Arguments
    /// * `topic` - If provided, reset only that topic. If `None`, reset all.
    #[pyo3(signature = (topic=None))]
    fn reset_sequence(&self, py: Python<'_>, topic: Option<&str>) {
        let mut released = Released::new();
        lock(py, &self.state).reset_sequence(topic, &mut released);
        drop(released); // after the lock, see `Released`
    }

    /// Get detailed sequence statistics.
    ///
    /// Returns a dict with: current_sequence, duplicate_count,
    /// out_of_order_count, dropped_count, topics (per-topic stats with
    /// expected/buffered/gaps/buffered_sequences), total_topics,
    /// total_buffered, seen_ids_count.
    fn get_sequence_stats<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyDict>> {
        lock(py, &self.state).get_sequence_stats(py)
    }

    /// Get statistics about buffered events (frontend compatible).
    ///
    /// Returns a dict with: total_topics, total_buffered, and per-topic
    /// buffer info (expected_sequence, buffered_count, buffered_sequences,
    /// gap_size, oldest_buffered_age).
    fn get_buffer_stats<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyDict>> {
        lock(py, &self.state).get_buffer_stats(py)
    }

    /// Clean up buffered events older than 5 minutes and trim seen_ids.
    ///
    /// - Removes buffered events whose age exceeds 300 seconds.
    /// - Evicts the ordering state of topics idle for longer than 300 seconds.
    /// - Trims the seen_ids set if it exceeds 1.5x the window_size.
    fn cleanup(&self, py: Python<'_>) {
        let mut released = Released::new();
        lock(py, &self.state).cleanup(&mut released);
        drop(released); // after the lock, see `Released`
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::time::Duration;

    // cleanup() must not drop the expected-sequence cursor of a live in-order
    // topic just because its reorder buffer is empty: gap detection would
    // reset, the next event would look like a fresh topic start, and a real
    // gap would go unnoticed (a stale sequence could even roll the cursor back).
    #[test]
    fn cleanup_keeps_cursor_for_active_in_order_topic() {
        let mut seq = EventSequencerState::new(100, 100);
        // Healthy in-order topic: cursor advanced, reorder buffer EMPTY,
        // activity just now.
        seq.expected_sequences.insert("room".to_string(), 42);
        seq.buffered_events
            .insert("room".to_string(), BTreeMap::new());
        seq.last_activity.insert("room".to_string(), Instant::now());

        seq.cleanup(&mut Released::new());

        assert_eq!(
            seq.expected_sequences.get("room"),
            Some(&42),
            "an active in-order topic's ordering cursor must survive cleanup"
        );
    }

    // The cursor IS reclaimed once a topic has been idle past the TTL, so the
    // maps stay bounded across many ephemeral topics.
    #[test]
    fn cleanup_evicts_idle_topic_cursor() {
        let mut seq = EventSequencerState::new(100, 100);
        seq.expected_sequences.insert("stale".to_string(), 7);
        seq.buffered_events
            .insert("stale".to_string(), BTreeMap::new());
        let old = Instant::now()
            .checked_sub(Duration::from_secs(600))
            .expect("instant 600s in the past is representable");
        seq.last_activity.insert("stale".to_string(), old);

        seq.cleanup(&mut Released::new());

        assert!(
            !seq.expected_sequences.contains_key("stale"),
            "a topic idle past the TTL must have its cursor evicted"
        );
        assert!(!seq.last_activity.contains_key("stale"));
        assert!(!seq.buffered_events.contains_key("stale"));
    }
}