Skip to main content

ftui_runtime/reactive/
observable.rs

1#![forbid(unsafe_code)]
2
3//! Observable value wrapper with change notification and version tracking.
4//!
5//! # Design
6//!
7//! [`Observable<T>`] wraps a value of type `T` in shared, reference-counted
8//! storage (`Rc<RefCell<..>>`). When the value changes (determined by
9//! `PartialEq`), all live subscribers are notified in registration order.
10//!
11//! # Performance
12//!
13//! | Operation    | Complexity               |
14//! |-------------|--------------------------|
15//! | `get()`     | O(1)                     |
16//! | `set()`     | O(S) where S = subscribers |
17//! | `subscribe()` | O(1) amortized          |
18//! | Memory      | ~48 bytes + sizeof(T)    |
19//!
20//! # Failure Modes
21//!
22//! - **Re-entrant set**: Calling `set()` from within a subscriber callback
23//!   will panic (RefCell borrow rules). This is intentional: re-entrant
24//!   mutations indicate a design bug in the subscriber graph.
25//! - **Subscriber leak**: If `Subscription` guards are stored indefinitely
26//!   without being dropped, callbacks accumulate. Dead weak references are
27//!   cleaned lazily during `notify()`.
28
29use std::cell::RefCell;
30use std::rc::{Rc, Weak};
31use tracing::{info, info_span};
32use web_time::Instant;
33
34/// A subscriber callback stored as a strong `Rc` internally, handed out
35/// as `Weak` to the observable.
36type CallbackRc<T> = Rc<dyn Fn(&T)>;
37type CallbackWeak<T> = Weak<dyn Fn(&T)>;
38
39/// Shared interior for [`Observable<T>`].
40struct ObservableInner<T> {
41    value: T,
42    version: u64,
43    /// Subscribers stored as weak references. Dead entries are pruned on notify.
44    subscribers: Vec<CallbackWeak<T>>,
45}
46
47/// A shared, version-tracked value with change notification.
48///
49/// Cloning an `Observable` creates a new handle to the **same** inner state —
50/// both handles see the same value and share subscribers.
51///
52/// # Invariants
53///
54/// 1. `version` increments by exactly 1 on each value-changing mutation.
55/// 2. `set(v)` where `v == current` is a no-op.
56/// 3. Subscribers are notified in registration order.
57/// 4. Dead subscribers (dropped [`Subscription`] guards) are pruned lazily.
58pub struct Observable<T> {
59    inner: Rc<RefCell<ObservableInner<T>>>,
60}
61
62// Manual Clone: shares the same Rc.
63impl<T> Clone for Observable<T> {
64    fn clone(&self) -> Self {
65        Self {
66            inner: Rc::clone(&self.inner),
67        }
68    }
69}
70
71impl<T: std::fmt::Debug> std::fmt::Debug for Observable<T> {
72    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
73        let inner = self.inner.borrow();
74        f.debug_struct("Observable")
75            .field("value", &inner.value)
76            .field("version", &inner.version)
77            .field("subscriber_count", &inner.subscribers.len())
78            .finish()
79    }
80}
81
82impl<T: Clone + PartialEq + 'static> Observable<T> {
83    /// Create a new observable with the given initial value.
84    ///
85    /// The initial version is 0 and no subscribers are registered.
86    #[must_use]
87    pub fn new(value: T) -> Self {
88        Self {
89            inner: Rc::new(RefCell::new(ObservableInner {
90                value,
91                version: 0,
92                subscribers: Vec::new(),
93            })),
94        }
95    }
96
97    /// Get a clone of the current value.
98    #[must_use]
99    pub fn get(&self) -> T {
100        self.inner.borrow().value.clone()
101    }
102
103    /// Access the current value by reference without cloning.
104    ///
105    /// The closure `f` receives an immutable reference to the value.
106    pub fn with<R>(&self, f: impl FnOnce(&T) -> R) -> R {
107        f(&self.inner.borrow().value)
108    }
109
110    /// Set a new value. If the new value differs from the current value
111    /// (by `PartialEq`), the version is incremented and all live subscribers
112    /// are notified.
113    ///
114    /// This method is safe to call re-entrantly from within subscriber callbacks.
115    pub fn set(&self, value: T) {
116        let changed = {
117            let mut inner = self.inner.borrow_mut();
118            if inner.value == value {
119                return;
120            }
121            inner.value = value;
122            inner.version += 1;
123            true
124        };
125        if changed {
126            self.notify();
127        }
128    }
129
130    /// Modify the value in place via a closure. If the value changes
131    /// (compared by `PartialEq` against a snapshot), the version is
132    /// incremented and subscribers are notified.
133    ///
134    /// This method is safe to call re-entrantly from within subscriber callbacks.
135    pub fn update(&self, f: impl FnOnce(&mut T)) {
136        let changed = {
137            let mut inner = self.inner.borrow_mut();
138            let old = inner.value.clone();
139            f(&mut inner.value);
140            if inner.value != old {
141                inner.version += 1;
142                true
143            } else {
144                false
145            }
146        };
147        if changed {
148            self.notify();
149        }
150    }
151
152    /// Subscribe to value changes. The callback is invoked with a reference
153    /// to the new value each time it changes.
154    ///
155    /// Returns a [`Subscription`] guard. Dropping the guard unsubscribes
156    /// the callback (it will not be called after drop, though it may still
157    /// be in the subscriber list until the next `notify()` prunes it).
158    pub fn subscribe(&self, callback: impl Fn(&T) + 'static) -> Subscription {
159        let strong: CallbackRc<T> = Rc::new(callback);
160        let weak = Rc::downgrade(&strong);
161        self.inner.borrow_mut().subscribers.push(weak);
162        // Wrap in a holder struct that can be type-erased as `dyn Any`,
163        // since `Rc<dyn Fn(&T)>` itself cannot directly coerce to `Rc<dyn Any>`.
164        Subscription {
165            _guard: Box::new(strong),
166        }
167    }
168
169    /// Current version number. Increments by 1 on each value-changing
170    /// mutation. Useful for dirty-checking in render loops.
171    #[must_use]
172    pub fn version(&self) -> u64 {
173        self.inner.borrow().version
174    }
175
176    /// Number of currently registered subscribers (including dead ones
177    /// not yet pruned).
178    #[must_use]
179    pub fn subscriber_count(&self) -> usize {
180        self.inner.borrow().subscribers.len()
181    }
182
183    /// Notify live subscribers and prune dead ones.
184    ///
185    /// If a batch scope is active (see [`super::batch::BatchScope`]),
186    /// notifications are deferred until the batch exits.
187    fn notify(&self) {
188        // Collect live callbacks first (to avoid holding the borrow during calls).
189        let callbacks: Vec<CallbackRc<T>> = {
190            let mut inner = self.inner.borrow_mut();
191            // Prune dead weak refs and collect live ones.
192            inner.subscribers.retain(|w| w.strong_count() > 0);
193            inner
194                .subscribers
195                .iter()
196                .filter_map(|w| w.upgrade())
197                .collect()
198        };
199
200        if callbacks.is_empty() {
201            return;
202        }
203
204        let widgets_invalidated = callbacks.len() as u64;
205
206        if super::batch::is_batching() {
207            super::batch::record_rows_changed(1);
208            // Defer each callback to the batch queue.
209            for cb in callbacks {
210                let callback_key = Rc::as_ptr(&cb) as *const () as usize;
211                let source = self.clone();
212                super::batch::defer_or_run_keyed(callback_key, move || {
213                    let latest = source.get();
214                    cb(&latest);
215                });
216            }
217            return;
218        }
219
220        // Borrow the value during callbacks to prevent re-entrant mutations.
221        let inner = self.inner.borrow();
222        let propagation_start = Instant::now();
223        let _span = info_span!(
224            "bloodstream.delta",
225            rows_changed = 1_u64,
226            widgets_invalidated,
227            duration_us = tracing::field::Empty
228        )
229        .entered();
230
231        // Fire immediately.
232        for cb in &callbacks {
233            cb(&inner.value);
234        }
235
236        let duration_us = propagation_start.elapsed().as_micros() as u64;
237        tracing::Span::current().record("duration_us", duration_us);
238        info!(
239            target: crate::telemetry_schema::TARGET_RUNTIME,
240            bloodstream_propagation_duration_us = duration_us,
241            rows_changed = 1_u64,
242            widgets_invalidated,
243            "bloodstream propagation duration histogram"
244        );
245    }
246}
247
248/// RAII guard for a subscriber callback.
249///
250/// Dropping the `Subscription` causes the associated callback to become
251/// unreachable (the strong `Rc` is dropped, so the `Weak` in the
252/// observable's subscriber list will fail to upgrade on the next
253/// notification cycle).
254pub struct Subscription {
255    /// Type-erased strong reference keeping the callback `Rc` alive.
256    /// When this `Box<dyn Any>` is dropped, the inner `Rc<dyn Fn(&T)>`
257    /// is dropped, and the corresponding `Weak` in the subscriber list
258    /// loses its referent.
259    _guard: Box<dyn std::any::Any>,
260}
261
262impl Subscription {
263    /// Combine multiple subscriptions into a single composite subscription.
264    #[must_use]
265    pub fn composite(subscriptions: Vec<Subscription>) -> Self {
266        Self {
267            _guard: Box::new(subscriptions),
268        }
269    }
270}
271
272impl std::fmt::Debug for Subscription {
273    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
274        f.debug_struct("Subscription").finish_non_exhaustive()
275    }
276}
277
278// ---------------------------------------------------------------------------
279// Tests
280// ---------------------------------------------------------------------------
281
282#[cfg(test)]
283mod tests {
284    use super::*;
285    use std::cell::Cell;
286    use std::sync::atomic::{AtomicU64, Ordering};
287    use std::sync::{Arc, Mutex};
288    use tracing::field::{Field, Visit};
289
290    #[derive(Clone, Debug, PartialEq, Eq)]
291    struct TableSnapshot {
292        schema_version: u64,
293        rows: Vec<String>,
294    }
295
296    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
297    enum RenderMode {
298        PartialDelta,
299        FullRerender,
300    }
301
302    fn classify_render_mode(previous: &TableSnapshot, next: &TableSnapshot) -> RenderMode {
303        if previous.schema_version != next.schema_version {
304            RenderMode::FullRerender
305        } else {
306            RenderMode::PartialDelta
307        }
308    }
309
310    #[derive(Default)]
311    struct DeltaSpanVisitor {
312        rows_changed: Option<u64>,
313        widgets_invalidated: Option<u64>,
314    }
315
316    impl Visit for DeltaSpanVisitor {
317        fn record_u64(&mut self, field: &Field, value: u64) {
318            match field.name() {
319                "rows_changed" => self.rows_changed = Some(value),
320                "widgets_invalidated" => self.widgets_invalidated = Some(value),
321                _ => {}
322            }
323        }
324
325        fn record_i64(&mut self, field: &Field, value: i64) {
326            if value < 0 {
327                return;
328            }
329            self.record_u64(field, value as u64);
330        }
331
332        fn record_debug(&mut self, _field: &Field, _value: &dyn std::fmt::Debug) {}
333    }
334
335    struct DeltaSpanSubscriber {
336        next_id: AtomicU64,
337        spans: Arc<Mutex<Vec<(u64, u64)>>>,
338    }
339
340    impl tracing::Subscriber for DeltaSpanSubscriber {
341        fn enabled(&self, _metadata: &tracing::Metadata<'_>) -> bool {
342            true
343        }
344
345        fn new_span(&self, attrs: &tracing::span::Attributes<'_>) -> tracing::span::Id {
346            if attrs.metadata().name() == "bloodstream.delta" {
347                let mut visitor = DeltaSpanVisitor::default();
348                attrs.record(&mut visitor);
349                self.spans.lock().expect("span capture lock").push((
350                    visitor.rows_changed.unwrap_or(0),
351                    visitor.widgets_invalidated.unwrap_or(0),
352                ));
353            }
354            tracing::span::Id::from_u64(self.next_id.fetch_add(1, Ordering::Relaxed))
355        }
356
357        fn record(&self, _span: &tracing::span::Id, _values: &tracing::span::Record<'_>) {}
358
359        fn record_follows_from(&self, _span: &tracing::span::Id, _follows: &tracing::span::Id) {}
360
361        fn event(&self, _event: &tracing::Event<'_>) {}
362
363        fn enter(&self, _span: &tracing::span::Id) {}
364
365        fn exit(&self, _span: &tracing::span::Id) {}
366    }
367
368    fn capture_delta_spans(run: impl FnOnce()) -> Vec<(u64, u64)> {
369        let spans = Arc::new(Mutex::new(Vec::new()));
370        let subscriber = DeltaSpanSubscriber {
371            next_id: AtomicU64::new(1),
372            spans: Arc::clone(&spans),
373        };
374        let _guard = tracing::subscriber::set_default(subscriber);
375        run();
376        spans.lock().expect("span capture lock").clone()
377    }
378
379    #[test]
380    fn get_set_basic() {
381        let obs = Observable::new(42);
382        assert_eq!(obs.get(), 42);
383        assert_eq!(obs.version(), 0);
384
385        obs.set(99);
386        assert_eq!(obs.get(), 99);
387        assert_eq!(obs.version(), 1);
388    }
389
390    #[test]
391    fn no_change_no_version_bump() {
392        let obs = Observable::new(42);
393        obs.set(42); // Same value.
394        assert_eq!(obs.version(), 0);
395    }
396
397    #[test]
398    fn with_access() {
399        let obs = Observable::new(vec![1, 2, 3]);
400        let sum = obs.with(|v| v.iter().sum::<i32>());
401        assert_eq!(sum, 6);
402    }
403
404    #[test]
405    fn update_mutates_in_place() {
406        let obs = Observable::new(vec![1, 2, 3]);
407        obs.update(|v| v.push(4));
408        assert_eq!(obs.get(), vec![1, 2, 3, 4]);
409        assert_eq!(obs.version(), 1);
410    }
411
412    #[test]
413    fn update_no_change_no_bump() {
414        let obs = Observable::new(10);
415        obs.update(|v| {
416            *v = 10; // Same value.
417        });
418        assert_eq!(obs.version(), 0);
419    }
420
421    #[test]
422    fn change_notification() {
423        let obs = Observable::new(0);
424        let count = Rc::new(Cell::new(0u32));
425        let count_clone = Rc::clone(&count);
426
427        let _sub = obs.subscribe(move |_val| {
428            count_clone.set(count_clone.get() + 1);
429        });
430
431        obs.set(1);
432        assert_eq!(count.get(), 1);
433
434        obs.set(2);
435        assert_eq!(count.get(), 2);
436
437        // Same value — no notification.
438        obs.set(2);
439        assert_eq!(count.get(), 2);
440    }
441
442    #[test]
443    fn subscriber_receives_new_value() {
444        let obs = Observable::new(0);
445        let last_seen = Rc::new(Cell::new(0));
446        let last_clone = Rc::clone(&last_seen);
447
448        let _sub = obs.subscribe(move |val| {
449            last_clone.set(*val);
450        });
451
452        obs.set(42);
453        assert_eq!(last_seen.get(), 42);
454
455        obs.set(99);
456        assert_eq!(last_seen.get(), 99);
457    }
458
459    #[test]
460    fn subscription_drop_unsubscribes() {
461        let obs = Observable::new(0);
462        let count = Rc::new(Cell::new(0u32));
463        let count_clone = Rc::clone(&count);
464
465        let sub = obs.subscribe(move |_val| {
466            count_clone.set(count_clone.get() + 1);
467        });
468
469        obs.set(1);
470        assert_eq!(count.get(), 1);
471
472        drop(sub);
473
474        obs.set(2);
475        // Callback should NOT have been called.
476        assert_eq!(count.get(), 1);
477    }
478
479    #[test]
480    fn multiple_subscribers() {
481        let obs = Observable::new(0);
482        let a = Rc::new(Cell::new(0u32));
483        let b = Rc::new(Cell::new(0u32));
484        let a_clone = Rc::clone(&a);
485        let b_clone = Rc::clone(&b);
486
487        let _sub_a = obs.subscribe(move |_| a_clone.set(a_clone.get() + 1));
488        let _sub_b = obs.subscribe(move |_| b_clone.set(b_clone.get() + 1));
489
490        obs.set(1);
491        assert_eq!(a.get(), 1);
492        assert_eq!(b.get(), 1);
493
494        obs.set(2);
495        assert_eq!(a.get(), 2);
496        assert_eq!(b.get(), 2);
497    }
498
499    #[test]
500    fn version_increment() {
501        let obs = Observable::new("hello".to_string());
502        assert_eq!(obs.version(), 0);
503
504        obs.set("world".to_string());
505        assert_eq!(obs.version(), 1);
506
507        obs.set("!".to_string());
508        assert_eq!(obs.version(), 2);
509
510        // Same value, no increment.
511        obs.set("!".to_string());
512        assert_eq!(obs.version(), 2);
513    }
514
515    #[test]
516    fn clone_shares_state() {
517        let obs1 = Observable::new(0);
518        let obs2 = obs1.clone();
519
520        obs1.set(42);
521        assert_eq!(obs2.get(), 42);
522        assert_eq!(obs2.version(), 1);
523
524        obs2.set(99);
525        assert_eq!(obs1.get(), 99);
526        assert_eq!(obs1.version(), 2);
527    }
528
529    #[test]
530    fn clone_shares_subscribers() {
531        let obs1 = Observable::new(0);
532        let count = Rc::new(Cell::new(0u32));
533        let count_clone = Rc::clone(&count);
534
535        let _sub = obs1.subscribe(move |_| count_clone.set(count_clone.get() + 1));
536
537        let obs2 = obs1.clone();
538        obs2.set(1);
539        assert_eq!(count.get(), 1); // Subscriber sees change via clone.
540    }
541
542    #[test]
543    fn subscriber_count() {
544        let obs = Observable::new(0);
545        assert_eq!(obs.subscriber_count(), 0);
546
547        let _s1 = obs.subscribe(|_| {});
548        assert_eq!(obs.subscriber_count(), 1);
549
550        let s2 = obs.subscribe(|_| {});
551        assert_eq!(obs.subscriber_count(), 2);
552
553        drop(s2);
554        // Dead subscriber not yet pruned.
555        assert_eq!(obs.subscriber_count(), 2);
556
557        // Trigger notify to prune dead.
558        obs.set(1);
559        assert_eq!(obs.subscriber_count(), 1);
560    }
561
562    #[test]
563    fn debug_format() {
564        let obs = Observable::new(42);
565        let dbg = format!("{:?}", obs);
566        assert!(dbg.contains("Observable"));
567        assert!(dbg.contains("42"));
568        assert!(dbg.contains("version"));
569    }
570
571    #[test]
572    fn notification_order_is_registration_order() {
573        let obs = Observable::new(0);
574        let log = Rc::new(RefCell::new(Vec::new()));
575
576        let log1 = Rc::clone(&log);
577        let _s1 = obs.subscribe(move |_| log1.borrow_mut().push('A'));
578
579        let log2 = Rc::clone(&log);
580        let _s2 = obs.subscribe(move |_| log2.borrow_mut().push('B'));
581
582        let log3 = Rc::clone(&log);
583        let _s3 = obs.subscribe(move |_| log3.borrow_mut().push('C'));
584
585        obs.set(1);
586        assert_eq!(*log.borrow(), vec!['A', 'B', 'C']);
587    }
588
589    #[test]
590    fn update_with_subscriber() {
591        let obs = Observable::new(vec![1, 2, 3]);
592        let last_len = Rc::new(Cell::new(0usize));
593        let last_clone = Rc::clone(&last_len);
594
595        let _sub = obs.subscribe(move |v: &Vec<i32>| {
596            last_clone.set(v.len());
597        });
598
599        obs.update(|v| v.push(4));
600        assert_eq!(last_len.get(), 4);
601    }
602
603    #[test]
604    fn many_set_calls_version_monotonic() {
605        let obs = Observable::new(0);
606        for i in 1..=100 {
607            obs.set(i);
608        }
609        assert_eq!(obs.version(), 100);
610        assert_eq!(obs.get(), 100);
611    }
612
613    #[test]
614    fn partial_subscriber_drop() {
615        let obs = Observable::new(0);
616        let a = Rc::new(Cell::new(0u32));
617        let b = Rc::new(Cell::new(0u32));
618        let a_clone = Rc::clone(&a);
619        let b_clone = Rc::clone(&b);
620
621        let sub_a = obs.subscribe(move |_| a_clone.set(a_clone.get() + 1));
622        let _sub_b = obs.subscribe(move |_| b_clone.set(b_clone.get() + 1));
623
624        obs.set(1);
625        assert_eq!(a.get(), 1);
626        assert_eq!(b.get(), 1);
627
628        drop(sub_a);
629
630        obs.set(2);
631        assert_eq!(a.get(), 1); // A was unsubscribed.
632        assert_eq!(b.get(), 2); // B still active.
633    }
634
635    #[test]
636    fn single_row_change_propagates_only_to_bound_widgets() {
637        let row_a = Observable::new(vec!["a".to_string()]);
638        let row_b = Observable::new(vec!["b".to_string()]);
639        let a_hits = Rc::new(Cell::new(0u32));
640        let b_hits = Rc::new(Cell::new(0u32));
641        let a_hits_clone = Rc::clone(&a_hits);
642        let b_hits_clone = Rc::clone(&b_hits);
643
644        let _sub_a = row_a.subscribe(move |_| a_hits_clone.set(a_hits_clone.get() + 1));
645        let _sub_b = row_b.subscribe(move |_| b_hits_clone.set(b_hits_clone.get() + 1));
646
647        row_a.set(vec!["a2".to_string()]);
648        assert_eq!(a_hits.get(), 1, "bound row-A widget should be invalidated");
649        assert_eq!(
650            b_hits.get(),
651            0,
652            "unbound row-B widget should remain untouched"
653        );
654    }
655
656    #[test]
657    fn batch_delta_propagates_atomically_without_stale_intermediate_values() {
658        let rows = Observable::new(vec!["r0".to_string()]);
659        let seen = Rc::new(RefCell::new(Vec::<Vec<String>>::new()));
660        let seen_clone = Rc::clone(&seen);
661        let _sub = rows.subscribe(move |current| seen_clone.borrow_mut().push(current.clone()));
662
663        {
664            let _batch = crate::reactive::batch::BatchScope::new();
665            rows.set(vec!["r1".to_string()]);
666            rows.set(vec!["r1".to_string(), "r2".to_string()]);
667            rows.update(|current| current.push("r3".to_string()));
668            assert!(
669                seen.borrow().is_empty(),
670                "callbacks must be deferred until batch exit"
671            );
672        }
673
674        let snapshots = seen.borrow();
675        assert_eq!(
676            snapshots.len(),
677            1,
678            "batched updates should coalesce to one invalidation"
679        );
680        assert_eq!(
681            snapshots[0],
682            vec!["r1".to_string(), "r2".to_string(), "r3".to_string()],
683            "subscriber must observe only final state"
684        );
685    }
686
687    #[test]
688    fn unbound_table_updates_produce_no_bloodstream_delta() {
689        let table_rows = Observable::new(vec!["old".to_string()]);
690        let spans = capture_delta_spans(|| {
691            table_rows.set(vec!["new".to_string()]);
692        });
693        assert!(
694            spans.is_empty(),
695            "unbound table updates should not emit bloodstream deltas"
696        );
697    }
698
699    #[test]
700    fn bloodstream_delta_span_reports_rows_changed_and_widgets_invalidated() {
701        let table_rows = Observable::new(vec!["old".to_string()]);
702        let _sub_a = table_rows.subscribe(|_| {});
703        let _sub_b = table_rows.subscribe(|_| {});
704
705        let spans = capture_delta_spans(|| {
706            table_rows.set(vec!["new".to_string()]);
707        });
708        assert_eq!(
709            spans,
710            vec![(1, 2)],
711            "single-row change should report one row and two invalidated widgets"
712        );
713    }
714
715    #[test]
716    fn schema_change_requires_full_rerender_not_partial_delta() {
717        let table = Observable::new(TableSnapshot {
718            schema_version: 1,
719            rows: vec!["alpha".to_string()],
720        });
721        let previous = Rc::new(RefCell::new(Some(table.get())));
722        let decisions = Rc::new(RefCell::new(Vec::<RenderMode>::new()));
723        let previous_clone = Rc::clone(&previous);
724        let decisions_clone = Rc::clone(&decisions);
725
726        let _sub = table.subscribe(move |next| {
727            let mut prev = previous_clone.borrow_mut();
728            let current_mode =
729                classify_render_mode(prev.as_ref().expect("previous snapshot available"), next);
730            decisions_clone.borrow_mut().push(current_mode);
731            *prev = Some(next.clone());
732        });
733
734        table.set(TableSnapshot {
735            schema_version: 1,
736            rows: vec!["alpha".to_string(), "beta".to_string()],
737        });
738        table.set(TableSnapshot {
739            schema_version: 2,
740            rows: vec!["alpha".to_string(), "beta".to_string()],
741        });
742
743        assert_eq!(
744            *decisions.borrow(),
745            vec![RenderMode::PartialDelta, RenderMode::FullRerender],
746            "schema-version changes must force full rerender semantics"
747        );
748    }
749
750    #[test]
751    fn string_observable() {
752        let obs = Observable::new(String::new());
753        let changes = Rc::new(Cell::new(0u32));
754        let changes_clone = Rc::clone(&changes);
755
756        let _sub = obs.subscribe(move |_| changes_clone.set(changes_clone.get() + 1));
757
758        obs.set("hello".to_string());
759        obs.set("hello".to_string()); // Same, no notify.
760        obs.set("world".to_string());
761
762        assert_eq!(changes.get(), 2);
763        assert_eq!(obs.version(), 2);
764    }
765}