lenso-test 0.1.4

Deterministic TestApp harness for native Lenso Plugins.
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
//! Cooperative controls for deterministic native `TestApp` scenarios.
//!
//! A Simulator Gate is private test infrastructure. It only pauses futures
//! that voluntarily wait on it; it does not preempt arbitrary Plugin, network,
//! database, or CPU work.

use std::{cell::RefCell, future::Future, rc::Rc, time::Duration};

use futures::{channel::oneshot, future::LocalBoxFuture, task::SpawnError};
use lenso_kernel::{DeterministicDriver, DriverTask, RuntimeDriver};

use crate::FaultInjector;

/// A deterministic test-only execution environment around one Driver.
#[derive(Clone, Debug, Default)]
pub struct TestSimulator {
    driver: DeterministicDriver,
    faults: FaultInjector,
}

impl TestSimulator {
    /// Creates a Simulator at virtual monotonic instant zero.
    pub fn new() -> Self {
        Self::default()
    }

    /// Creates a named cooperative checkpoint for one test scenario.
    pub fn gate(&self, name: impl Into<String>) -> SimulatorGate {
        SimulatorGate {
            name: name.into(),
            state: Rc::new(RefCell::new(GateState::default())),
        }
    }

    /// Creates a cooperative, test-owned resource availability control.
    ///
    /// Unlike a [`SimulatorGate`], a resource may be frozen and thawed more
    /// than once. Scenario code opts in by awaiting [`SimulatorResource::acquire`]
    /// at the same private resource boundary it uses in production; the
    /// simulator never substitutes a second business implementation.
    pub fn resource(&self, name: impl Into<String>) -> SimulatorResource {
        SimulatorResource {
            name: name.into(),
            state: Rc::new(RefCell::new(ResourceState::default())),
        }
    }

    /// Returns this Simulator's test-owned, explicit fault injector.
    ///
    /// Injected failures stay inert until scenario code checks the exact
    /// boundary. This avoids turning target behavior into an implicit global
    /// fault policy.
    pub fn faults(&self) -> FaultInjector {
        self.faults.clone()
    }

    /// Runs one root future on the deterministic Driver.
    ///
    /// This must remain the outermost Driver run for a scenario. Calling it
    /// from a future already running on this Simulator is recursive and is
    /// rejected by the underlying Driver.
    pub fn run<F: Future>(&self, future: F) -> F::Output {
        self.driver.run(future)
    }

    /// Cooperatively drives currently runnable local work.
    ///
    /// A pump is a scheduling boundary, not a single-step scheduler: the
    /// underlying local executor may poll more than one ready future before
    /// this call returns. Call it only outside a running [`Self::run`] future.
    pub fn pump(&self) {
        self.run(self.driver.yield_now());
    }

    /// Spawns voluntary scenario work on the deterministic local lane.
    pub fn spawn<F>(&self, future: F) -> Result<DriverTask, SpawnError>
    where
        F: Future<Output = ()> + 'static,
    {
        self.driver.spawn_local(Box::pin(future))
    }

    /// Advances virtual time and wakes elapsed deterministic timers.
    pub fn advance(&self, duration: Duration) {
        self.driver.advance(duration);
    }

    /// Returns the current virtual monotonic instant.
    pub fn now(&self) -> Duration {
        self.driver.now()
    }

    /// Waits until a virtual monotonic instant on this Simulator's Driver.
    ///
    /// Deadlines use the same time origin as [`Self::now`]. An elapsed deadline
    /// completes immediately; a future deadline requires [`Self::advance`] and
    /// polling the waiting work, for example with [`Self::pump`]. Sleeping never
    /// advances time automatically. The returned future owns its wait and can
    /// be moved into a Plugin or a spawned task without borrowing the Simulator.
    pub fn sleep_until(&self, deadline: Duration) -> LocalBoxFuture<'static, ()> {
        self.driver.sleep_until(deadline)
    }

    /// Returns the same Driver for generated Host lowering and facility clocks.
    /// External processes and I/O are not virtualized by this Driver.
    pub fn driver(&self) -> DeterministicDriver {
        self.driver.clone()
    }
}

#[derive(Debug, Default)]
struct ResourceState {
    acquisitions: usize,
    frozen: bool,
    thaw_notifiers: Vec<oneshot::Sender<()>>,
}

/// A named, cooperative resource owner that a test can freeze independently.
///
/// This represents ownership/availability only. It deliberately does not
/// provide a global service locator, connection pool, or implicit resource
/// selection mechanism.
#[derive(Clone, Debug)]
pub struct SimulatorResource {
    name: String,
    state: Rc<RefCell<ResourceState>>,
}

impl SimulatorResource {
    /// Returns the stable test-only owner name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Waits until this resource owner is available, then records one access.
    pub async fn acquire(&self) {
        loop {
            let thaw = {
                let mut state = self.state.borrow_mut();
                if state.frozen {
                    let (sender, receiver) = oneshot::channel();
                    state.thaw_notifiers.push(sender);
                    Some(receiver)
                } else {
                    state.acquisitions += 1;
                    None
                }
            };

            let Some(thaw) = thaw else {
                return;
            };
            let _ = thaw.await;
        }
    }

    /// Freezes future cooperative acquisitions of this specific owner.
    ///
    /// Returns true only for the transition from available to frozen.
    #[must_use]
    pub fn freeze(&self) -> bool {
        let mut state = self.state.borrow_mut();
        if state.frozen {
            return false;
        }
        state.frozen = true;
        true
    }

    /// Makes this owner available and releases all currently blocked accessors.
    ///
    /// Returns true only for the transition from frozen to available.
    #[must_use]
    pub fn thaw(&self) -> bool {
        let notifiers = {
            let mut state = self.state.borrow_mut();
            if !state.frozen {
                return false;
            }
            state.frozen = false;
            std::mem::take(&mut state.thaw_notifiers)
        };
        for notifier in notifiers {
            let _ = notifier.send(());
        }
        true
    }

    /// Returns the number of completed cooperative acquisitions.
    pub fn acquisition_count(&self) -> usize {
        self.state.borrow().acquisitions
    }

    /// Returns whether this owner is currently frozen.
    pub fn is_frozen(&self) -> bool {
        self.state.borrow().frozen
    }
}

#[derive(Debug, Default)]
struct GateState {
    reached: usize,
    released: bool,
    reached_notifiers: Vec<oneshot::Sender<()>>,
    release_notifiers: Vec<oneshot::Sender<()>>,
}

/// A named checkpoint that a test explicitly releases.
#[derive(Clone, Debug)]
pub struct SimulatorGate {
    name: String,
    state: Rc<RefCell<GateState>>,
}

impl SimulatorGate {
    /// Returns the stable test-only checkpoint name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Waits until the test releases this checkpoint.
    pub async fn wait(&self) {
        let release = {
            let mut state = self.state.borrow_mut();
            state.reached += 1;
            for notifier in state.reached_notifiers.drain(..) {
                let _ = notifier.send(());
            }
            if state.released {
                None
            } else {
                let (sender, receiver) = oneshot::channel();
                state.release_notifiers.push(sender);
                Some(receiver)
            }
        };

        if let Some(release) = release {
            let _ = release.await;
        }
    }

    /// Waits until at least one operation has reached this checkpoint.
    pub async fn reached(&self) {
        let notification = {
            let mut state = self.state.borrow_mut();
            if state.reached > 0 {
                None
            } else {
                let (sender, receiver) = oneshot::channel();
                state.reached_notifiers.push(sender);
                Some(receiver)
            }
        };

        if let Some(notification) = notification {
            let _ = notification.await;
        }
    }

    /// Releases every operation currently waiting at this checkpoint.
    ///
    /// Returns true only for the transition from blocked to released.
    #[must_use]
    pub fn release(&self) -> bool {
        let notifiers = {
            let mut state = self.state.borrow_mut();
            if state.released {
                return false;
            }
            state.released = true;
            std::mem::take(&mut state.release_notifiers)
        };
        for notifier in notifiers {
            let _ = notifier.send(());
        }
        true
    }

    /// Returns how many voluntary waits have reached this checkpoint.
    pub fn reached_count(&self) -> usize {
        self.state.borrow().reached
    }

    /// Returns whether the test has released this checkpoint.
    pub fn is_released(&self) -> bool {
        self.state.borrow().released
    }
}

#[cfg(test)]
mod tests {
    use std::{cell::RefCell, rc::Rc};

    use futures::FutureExt;
    use lenso_kernel::TaskOutcome;

    use super::*;

    #[test]
    fn gate_blocks_work_until_the_test_releases_it() {
        let simulator = TestSimulator::new();
        let gate = simulator.gate("provider.before-response");
        let task = simulator
            .spawn({
                let gate = gate.clone();
                async move {
                    gate.wait().await;
                }
            })
            .unwrap();

        simulator.run(gate.reached());
        assert_eq!(gate.name(), "provider.before-response");
        assert_eq!(gate.reached_count(), 1);
        assert!(!gate.is_released());
        assert!(gate.release());
        assert!(!gate.release());
        assert_eq!(simulator.run(task), TaskOutcome::Completed);
    }

    #[test]
    fn gates_allow_test_chosen_completion_order() {
        let simulator = TestSimulator::new();
        let first = simulator.gate("operation.first");
        let second = simulator.gate("operation.second");
        let completed = Rc::new(RefCell::new(Vec::new()));

        let first_task = simulator
            .spawn({
                let first = first.clone();
                let completed = completed.clone();
                async move {
                    first.wait().await;
                    completed.borrow_mut().push("first");
                }
            })
            .unwrap();
        let second_task = simulator
            .spawn({
                let second = second.clone();
                let completed = completed.clone();
                async move {
                    second.wait().await;
                    completed.borrow_mut().push("second");
                }
            })
            .unwrap();

        simulator.run(async {
            first.reached().await;
            second.reached().await;
        });
        assert!(second.release());
        assert_eq!(simulator.run(second_task), TaskOutcome::Completed);
        assert_eq!(&*completed.borrow(), &["second"]);

        assert!(first.release());
        assert_eq!(simulator.run(first_task), TaskOutcome::Completed);
        assert_eq!(&*completed.borrow(), &["second", "first"]);
    }

    #[test]
    fn cancelling_one_blocked_operation_does_not_release_its_peer() {
        let simulator = TestSimulator::new();
        let cancelled = simulator.gate("operation.cancelled");
        let peer = simulator.gate("operation.peer");
        let cancelled_task = simulator
            .spawn({
                let cancelled = cancelled.clone();
                async move {
                    cancelled.wait().await;
                }
            })
            .unwrap();
        let peer_task = simulator
            .spawn({
                let peer = peer.clone();
                async move {
                    peer.wait().await;
                }
            })
            .unwrap();

        simulator.run(async {
            cancelled.reached().await;
            peer.reached().await;
        });
        cancelled_task.cancel();
        assert_eq!(simulator.run(cancelled_task), TaskOutcome::Cancelled);
        assert!(!peer.is_released());

        assert!(peer.release());
        assert_eq!(simulator.run(peer_task), TaskOutcome::Completed);
    }

    #[test]
    fn advancing_virtual_time_wakes_elapsed_work_when_the_test_pumps() {
        let simulator = TestSimulator::new();
        let completed = Rc::new(RefCell::new(false));
        let sleep = simulator.sleep_until(Duration::from_millis(5));
        let task = simulator
            .spawn({
                let completed = completed.clone();
                async move {
                    sleep.await;
                    *completed.borrow_mut() = true;
                }
            })
            .unwrap();

        simulator.pump();
        assert!(!*completed.borrow());
        simulator.advance(Duration::from_millis(4));
        simulator.pump();
        assert!(!*completed.borrow());
        simulator.advance(Duration::from_millis(1));
        assert_eq!(simulator.now(), Duration::from_millis(5));
        assert!(!*completed.borrow());
        simulator.pump();
        assert!(*completed.borrow());
        assert_eq!(simulator.run(task), TaskOutcome::Completed);
    }

    #[test]
    fn sleeping_at_or_before_now_completes_without_advancing_time() {
        let simulator = TestSimulator::new();
        simulator.advance(Duration::from_millis(5));

        for deadline in [Duration::from_millis(4), simulator.now()] {
            assert_eq!(simulator.sleep_until(deadline).now_or_never(), Some(()));
        }
        assert_eq!(simulator.now(), Duration::from_millis(5));
    }

    #[test]
    fn dropping_and_cancelling_sleepers_does_not_complete_peer_work() {
        let simulator = TestSimulator::new();
        let completed = Rc::new(RefCell::new(Vec::new()));
        let deadline = Duration::from_millis(5);
        drop(simulator.sleep_until(deadline));

        let cancelled = simulator
            .spawn({
                let sleep = simulator.sleep_until(deadline);
                let completed = completed.clone();
                async move {
                    sleep.await;
                    completed.borrow_mut().push("cancelled");
                }
            })
            .unwrap();
        let peer = simulator
            .spawn({
                let sleep = simulator.sleep_until(deadline);
                let completed = completed.clone();
                async move {
                    sleep.await;
                    completed.borrow_mut().push("peer");
                }
            })
            .unwrap();

        simulator.pump();
        cancelled.cancel();
        assert_eq!(simulator.run(cancelled), TaskOutcome::Cancelled);
        simulator.advance(Duration::from_millis(4));
        simulator.pump();
        assert!(completed.borrow().is_empty());

        simulator.advance(Duration::from_millis(1));
        assert_eq!(simulator.run(peer), TaskOutcome::Completed);
        assert_eq!(&*completed.borrow(), &["peer"]);
    }

    #[test]
    fn freezing_one_resource_owner_does_not_block_another() {
        let simulator = TestSimulator::new();
        let auth_store = simulator.resource("auth-store");
        let object_store = simulator.resource("object-store");
        assert!(auth_store.freeze());
        assert!(!auth_store.freeze());

        let blocked = simulator
            .spawn({
                let auth_store = auth_store.clone();
                async move {
                    auth_store.acquire().await;
                }
            })
            .unwrap();
        let independent = simulator
            .spawn({
                let object_store = object_store.clone();
                async move {
                    object_store.acquire().await;
                }
            })
            .unwrap();

        simulator.pump();
        assert_eq!(auth_store.acquisition_count(), 0);
        assert_eq!(object_store.acquisition_count(), 1);
        assert_eq!(simulator.run(independent), TaskOutcome::Completed);
        assert!(auth_store.is_frozen());

        assert!(auth_store.thaw());
        assert!(!auth_store.thaw());
        assert_eq!(simulator.run(blocked), TaskOutcome::Completed);
        assert_eq!(auth_store.acquisition_count(), 1);
    }
}