forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

undo_stress.rs588 lines, 21.1 KiBHistoryRawDownload
1//! Undo and redo under heavy random use. Every successful edit from the public
2//! edit API is followed by a canonical serialisation of the project, and an
3//! independent model of the undo and redo stacks predicts what every undo, redo
4//! and failed edit must leave behind. Each step is checked against that model:
5//!
6//! * a successful edit pushes one step, and clears the redo stack;
7//! * a refused edit changes nothing and pushes nothing;
8//! * undo and redo restore exactly the state the model recorded;
9//! * the undo history is capped at [`CAP`] steps, the oldest dropped first.
10//!
11//! The seeds are fixed, so a failure names a seed and a step that reproduce it.
12//!
13//! ```text
14//! cargo test --release -p engine --test undo_stress -- --nocapture
15//! ```
16
17use std::collections::VecDeque;
18use std::fs;
19use std::path::Path;
20use std::time::Instant;
21
22use engine::color::ColorParams;
23use engine::eq::EqParams;
24use engine::project::{Clip, Edge, GainKey, Lane, LaneKind, Speed, Title};
25use engine::scale::FitPolicy;
26use engine::scratch::Scratch;
27use engine::text::TextStyle;
28use engine::transform::TransformParams;
29use engine::PlaybackSession;
30
31/// The undo cap the model assumes; the session's own cap is `HISTORY_CAP` in
32/// `project.rs`, and the checks below would fail if the two disagreed.
33const CAP: usize = 100;
34const OPS: usize = 10_000;
35/// Well past `CAP`, so a held history outgrows the cap; more ops add only run time.
36const HELD_OPS: usize = 1_500;
37const SEEDS: [u64; 4] = [0x9E37_79B9_7F4A_7C15, 0x0BAD_C0DE_1234_5678, 0xDEAD_BEEF_F00D_0001, 42];
38
39/// xorshift64: deterministic, no dependency.
40struct Rng(u64);
41
42impl Rng {
43 fn new(seed: u64) -> Self {
44 Self(seed.max(1))
45 }
46
47 fn next(&mut self) -> u64 {
48 let mut x = self.0;
49 x ^= x << 13;
50 x ^= x >> 7;
51 x ^= x << 17;
52 self.0 = x;
53 x
54 }
55
56 fn below(&mut self, n: usize) -> usize {
57 (self.next() % n as u64) as usize
58 }
59
60 fn range(&mut self, lo: u32, hi: u32) -> u32 {
61 lo + (self.next() % u64::from(hi - lo + 1)) as u32
62 }
63
64 fn signed(&mut self, lo: f32, hi: f32) -> f32 {
65 lo + ((self.next() >> 40) as f32 / (1u64 << 24) as f32) * (hi - lo)
66 }
67
68 fn chance(&mut self, percent: u64) -> bool {
69 self.next() % 100 < percent
70 }
71
72 fn pick<T: Copy>(&mut self, items: &[T]) -> T {
73 items[self.below(items.len())]
74 }
75}
76
77/// The project as a byte string. The playhead is never moved by the stress
78/// edits, so it stays at frame 0 and the file is a function of the project alone.
79fn state(s: &PlaybackSession, file: &Path) -> Vec<u8> {
80 s.save_autosave(file).expect("the project saves");
81 fs::read(file).expect("the saved project reads back")
82}
83
84/// What the stacks must hold, predicted from the successes and refusals alone.
85struct Model {
86 undo: VecDeque<Vec<u8>>,
87 redo: Vec<Vec<u8>>,
88 cur: Vec<u8>,
89 pushes: u64,
90 cap: usize,
91}
92
93impl Model {
94 fn new(cur: Vec<u8>, cap: usize) -> Self {
95 Self { undo: VecDeque::new(), redo: Vec::new(), cur, pushes: 0, cap }
96 }
97
98 /// A successful edit: one step, and the redo branch is gone.
99 fn edited(&mut self) {
100 if self.undo.len() == self.cap {
101 self.undo.pop_front();
102 }
103 self.undo.push_back(self.cur.clone());
104 self.redo.clear();
105 self.pushes += 1;
106 }
107}
108
109fn lanes_with_clips(s: &PlaybackSession) -> Vec<Lane> {
110 s.lanes().into_iter().filter(|l| l.kind != LaneKind::Subtitle).collect()
111}
112
113fn any_lane(s: &PlaybackSession, rng: &mut Rng) -> Option<Lane> {
114 let lanes = lanes_with_clips(s);
115 if lanes.is_empty() {
116 None
117 } else {
118 Some(rng.pick(&lanes))
119 }
120}
121
122fn any_clip(s: &PlaybackSession, rng: &mut Rng) -> Option<(Lane, usize)> {
123 let lanes = lanes_with_clips(s);
124 let with: Vec<(Lane, usize)> = lanes
125 .iter()
126 .flat_map(|&l| (0..s.lane_clips(l).len()).map(move |i| (l, i)))
127 .collect();
128 if with.is_empty() {
129 None
130 } else {
131 Some(rng.pick(&with))
132 }
133}
134
135fn timeline_frames(s: &PlaybackSession) -> u32 {
136 (s.timeline_duration() * s.meta().frame_rate).ceil() as u32
137}
138
139/// A fresh clip of the one source the session opens with, `test_av.mp4`
140/// (150 frames of picture and sound).
141fn random_clip(rng: &mut Rng) -> Clip {
142 let in_frame = rng.range(0, 120);
143 let out_frame = in_frame + rng.range(1, 30);
144 Clip {
145 start: 0,
146 in_frame,
147 out_frame,
148 source: 0,
149 fade_in: 0,
150 fade_out: 0,
151 transition_out: 0,
152 transition_kind: Default::default(),
153 visualizer: 0,
154 viz_paint: 0,
155 gain_db: 0.0,
156 gain_keys: Vec::new(),
157 pan: 0,
158 pitch: 0.0,
159 transform_keys: Vec::new(),
160 opacity_keys: Vec::new(),
161 color_keys: Vec::new(),
162 effects: Vec::new(),
163 link: None,
164 eq: None,
165 color: None,
166 transform: None,
167 fit: FitPolicy::Fit,
168 speed: Speed::default(),
169 speed_keys: Vec::new(),
170 reversed: false,
171 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
172 angle: Default::default(),
173 }
174}
175
176const TITLES: [&str; 4] = ["Opening", "Ελληνικά", "Ответ", "Chapter one"];
177
178fn random_title(rng: &mut Rng) -> Title {
179 Title {
180 start: rng.range(0, 200),
181 frames: rng.range(1, 60),
182 text: rng.pick(&TITLES).to_string(),
183 style: TextStyle::default(),
184 fade_in: 0,
185 fade_out: 0,
186 in_anim: Default::default(),
187 out_anim: Default::default(),
188 anim_frames: 0,
189 keys: Vec::new(),
190 }
191}
192
193/// One random edit from the public API. `true` when it succeeded, which is the
194/// only thing the model needs: every success is one undo step.
195fn random_edit(s: &mut PlaybackSession, rng: &mut Rng, last: &mut usize) -> bool {
196 let frames = timeline_frames(s);
197 *last = rng.below(31);
198 match *last {
199 0 => s.cut_at(rng.signed(0.0, s.timeline_duration() as f32 + 0.2) as f64),
200 1 => match any_clip(s, rng) {
201 Some((l, i)) => {
202 let edge = if rng.chance(50) { Edge::Start } else { Edge::End };
203 s.trim_clip(l, i, edge, rng.range(0, frames + 10))
204 }
205 None => false,
206 },
207 2 => match any_clip(s, rng) {
208 Some((from, i)) => {
209 let to = rng.pick(&lanes_with_clips(s).into_iter().filter(|l| l.kind == from.kind).collect::<Vec<_>>());
210 s.move_clip_to(from, i, to, rng.range(0, frames + 10))
211 }
212 None => false,
213 },
214 3 => match any_clip(s, rng) {
215 Some((l, i)) => s.delete_clip(l, i),
216 None => false,
217 },
218 4 => match any_clip(s, rng) {
219 Some((l, i)) => s.lift_clip(l, i),
220 None => false,
221 },
222 5 => match any_lane(s, rng) {
223 // An Ok sweep with nothing to close takes no step, so only a closed gap counts.
224 Some(l) => s.close_all_gaps_on_lane(l).is_ok_and(|r| r.closed > 0),
225 None => false,
226 },
227 6 => match any_clip(s, rng) {
228 Some((l, i)) => s.set_speed(l, i, Speed::from_permille(rng.range(250, 4000) as u16)).is_ok(),
229 None => false,
230 },
231 7 => match any_clip(s, rng) {
232 Some((l, i)) => {
233 if rng.chance(50) {
234 s.set_fade_in(l, i, rng.range(0, 30))
235 } else {
236 s.set_fade_out(l, i, rng.range(0, 30))
237 }
238 }
239 None => false,
240 },
241 8 => match any_clip(s, rng) {
242 Some((l, i)) => s.crossfade(l, i, rng.range(0, 20)),
243 None => false,
244 },
245 9 => match any_clip(s, rng) {
246 Some((l, i)) => s.set_transition_out(l, i, rng.range(0, 20)),
247 None => false,
248 },
249 10 => match any_clip(s, rng) {
250 Some((l, i)) => {
251 let params = rng.chance(80).then(|| ColorParams {
252 brightness: rng.signed(-1.0, 1.0),
253 contrast: rng.signed(0.0, 2.0),
254 saturation: rng.signed(0.0, 2.0),
255 tint: rng.signed(-1.0, 1.0),
256 ..Default::default()
257 });
258 s.set_color(l, i, params)
259 }
260 None => false,
261 },
262 11 => match any_clip(s, rng) {
263 Some((l, i)) => {
264 let params = rng.chance(80).then(|| TransformParams {
265 pos_x: rng.signed(-0.5, 0.5),
266 scale: rng.signed(0.5, 1.5),
267 rotate: rng.signed(-30.0, 30.0),
268 ..TransformParams::default()
269 });
270 s.set_transform(l, i, params)
271 }
272 None => false,
273 },
274 12 => match any_clip(s, rng) {
275 Some((l, i)) => {
276 let params = rng.chance(80).then(|| {
277 let mut eq = EqParams::default_layout();
278 for band in &mut eq.bands {
279 band.gain_db = rng.signed(-6.0, 6.0);
280 }
281 eq
282 });
283 s.set_eq(l, i, params)
284 }
285 None => false,
286 },
287 13 => match any_lane(s, rng) {
288 Some(l) => s.set_lane_gain_db(l, rng.signed(-20.0, 6.0)),
289 None => false,
290 },
291 14 => {
292 let kind = rng.pick(&[LaneKind::Video, LaneKind::Audio]);
293 s.add_lane(kind);
294 true
295 }
296 15 => match any_lane(s, rng) {
297 Some(l) => s.remove_lane(l).is_ok(),
298 None => false,
299 },
300 16 => match any_lane(s, rng) {
301 Some(l) => {
302 let to = rng.below(s.lanes().len());
303 s.move_lane(l, to).is_some()
304 }
305 None => false,
306 },
307 17 => match any_lane(s, rng) {
308 Some(l) => match rng.below(3) {
309 0 => s.set_lane_hidden(l, rng.chance(50)),
310 1 => s.set_lane_muted(l, rng.chance(50)),
311 _ => s.set_lane_locked(l, rng.chance(50)),
312 },
313 None => false,
314 },
315 18 => match (any_clip(s, rng), any_clip(s, rng)) {
316 (Some((a, ai)), Some((b, bi))) => s.group(a, ai, b, bi).is_ok(),
317 _ => false,
318 },
319 19 => match any_clip(s, rng) {
320 Some((l, i)) => s.ungroup(l, i),
321 None => false,
322 },
323 20 => s.add_title(random_title(rng)).is_ok(),
324 21 => {
325 let n = s.titles().len();
326 if n == 0 {
327 false
328 } else {
329 s.set_title(rng.below(n), random_title(rng))
330 }
331 }
332 22 => {
333 let n = s.titles().len();
334 n > 0 && s.remove_title(rng.below(n))
335 }
336 23 => s.add_chapter(rng.range(0, frames.max(1)), rng.pick(&TITLES)).is_ok(),
337 24 => {
338 let n = s.chapters().len();
339 if n == 0 {
340 false
341 } else {
342 let i = rng.below(n);
343 match rng.below(3) {
344 0 => s.remove_chapter(i),
345 1 => s.set_chapter_title(i, rng.pick(&TITLES)),
346 _ => {
347 // Moving to the frame it already holds is an Ok no-op with no step.
348 let to = rng.range(0, frames.max(1));
349 let from = s.chapters()[i].frame;
350 s.move_chapter(i, to).is_ok() && from != to
351 }
352 }
353 }
354 }
355 25 => match any_clip(s, rng) {
356 Some((l, i)) => {
357 let at = rng.range(0, 150);
358 if rng.chance(70) {
359 s.add_gain_key(l, i, GainKey::new(at, rng.signed(-12.0, 12.0)))
360 } else {
361 s.remove_gain_key(l, i, at)
362 }
363 }
364 None => false,
365 },
366 26 => match any_clip(s, rng) {
367 Some((l, i)) => s.set_clip_gain(l, i, rng.signed(-12.0, 12.0)),
368 None => false,
369 },
370 27 => match any_clip(s, rng) {
371 Some((l, i)) => s.set_fit(l, i, rng.pick(&[FitPolicy::Fit, FitPolicy::Fill])),
372 None => false,
373 },
374 28 => match (any_lane(s, rng), any_clip(s, rng)) {
375 (Some(l), Some((_, _))) => {
376 let a = rng.range(0, 40);
377 let b = rng.range(0, 40);
378 s.cut_regions(&[(a, a + rng.range(1, 10)), (b + 60, b + 70)], &[l]).is_ok()
379 }
380 _ => false,
381 },
382 29 => match any_lane(s, rng) {
383 Some(l) => {
384 let n = s.lane_clips(l).len();
385 n >= 2 && s.swap_clips(l, rng.below(n), rng.below(n))
386 }
387 None => false,
388 },
389 _ => {
390 let lanes = lanes_with_clips(s);
391 let lane = rng.pick(&lanes);
392 let secs = rng.signed(0.0, s.timeline_duration() as f32 + 1.0) as f64;
393 s.place_at(lane, secs, random_clip(rng))
394 }
395 }
396}
397
398/// Resident set in KiB, from `/proc`; 0 where that is not there.
399fn rss_kib() -> u64 {
400 fs::read_to_string("/proc/self/status")
401 .ok()
402 .and_then(|s| {
403 s.lines()
404 .find(|l| l.starts_with("VmRSS:"))
405 .and_then(|l| l.split_whitespace().nth(1))
406 .and_then(|n| n.parse().ok())
407 })
408 .unwrap_or(0)
409}
410
411fn open_session() -> PlaybackSession {
412 let asset = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../assets/test_av.mp4");
413 PlaybackSession::open(asset).expect("open the fixture")
414}
415
416/// Walks the undo stack back to the bottom, then the redo stack forward to the
417/// top, checking every state against the model on the way.
418fn drain_and_refill(s: &mut PlaybackSession, model: &mut Model, file: &Path, tag: &str) {
419 let mut step = 0usize;
420 while let Some(prev) = model.undo.pop_back() {
421 assert!(s.undo(), "{tag}: undo {step} refused with {} steps left", model.undo.len() + 1);
422 let back = state(s, file);
423 assert!(back == prev, "{tag}: undo {step} does not restore the recorded state");
424 model.redo.push(std::mem::replace(&mut model.cur, prev));
425 step += 1;
426 }
427 assert!(!s.undo(), "{tag}: undo past the bottom must be refused");
428 assert!(state(s, file) == model.cur, "{tag}: a refused undo changed the project");
429 assert_eq!(s.undo_depth(), 0, "{tag}: the bottom of the history is empty");
430
431 let mut step = 0usize;
432 while let Some(next) = model.redo.pop() {
433 assert!(s.redo(), "{tag}: redo {step} refused");
434 let fwd = state(s, file);
435 assert!(fwd == next, "{tag}: redo {step} does not restore the recorded state");
436 model.undo.push_back(std::mem::replace(&mut model.cur, next));
437 step += 1;
438 }
439 assert!(!s.redo(), "{tag}: redo past the top must be refused");
440 assert!(state(s, file) == model.cur, "{tag}: a refused redo changed the project");
441 assert_eq!(s.redo_depth(), 0, "{tag}: the top of the redo stack is empty");
442}
443
444/// The random run: edits with undo and redo interleaved, checked after every
445/// step against the model. `cap` is `Some(CAP)` for the session's own cap, or
446/// `None` when the history is held and nothing is evicted.
447fn random_run(seed: u64, ops: usize, cap: Option<usize>) -> (Model, PlaybackSession) {
448 let file = Scratch::file(&format!("undo_stress_{seed:x}"), "edith");
449 let mut s = open_session();
450 if cap.is_none() {
451 s.hold_history(true);
452 }
453 let mut model = Model::new(state(&s, &file), cap.unwrap_or(usize::MAX));
454 let mut rng = Rng::new(seed);
455 let mut undos = 0usize;
456 let mut redos = 0usize;
457 let mut refused = 0usize;
458 let mut noops = 0usize;
459
460 for step in 0..ops {
461 let tag = format!("seed {seed:#x} step {step}");
462 let mut edited = false;
463 let mut last_op = usize::MAX;
464 match rng.below(100) {
465 0..=7 => {
466 let expect = model.undo.pop_back();
467 let ok = s.undo();
468 match expect {
469 None => assert!(!ok, "{tag}: undo with an empty model stack succeeded"),
470 Some(prev) => {
471 assert!(ok, "{tag}: undo refused with {} steps modelled", model.undo.len() + 1);
472 model.redo.push(std::mem::replace(&mut model.cur, prev));
473 undos += 1;
474 }
475 }
476 }
477 8..=15 => {
478 let expect = model.redo.pop();
479 let ok = s.redo();
480 match expect {
481 None => assert!(!ok, "{tag}: redo with an empty model stack succeeded"),
482 Some(next) => {
483 assert!(ok, "{tag}: redo refused");
484 model.undo.push_back(std::mem::replace(&mut model.cur, next));
485 redos += 1;
486 }
487 }
488 }
489 _ => {
490 let had_redo = model.redo.len();
491 let mut op = 0usize;
492 let ok = random_edit(&mut s, &mut rng, &mut op);
493 last_op = op;
494 if ok && state(&s, &file) == model.cur {
495 // An edit that changes nothing costs no undo step and keeps
496 // the redo branch: it is settled before anyone sees it.
497 assert_eq!(s.redo_depth(), had_redo, "{tag}: a no-op edit (op {op}) touched the redo stack");
498 noops += 1;
499 } else if ok {
500 model.edited();
501 edited = true;
502 assert_eq!(s.redo_depth(), 0, "{tag}: a new edit left redo steps behind");
503 } else {
504 // A refusal changes nothing: same state, same stacks.
505 assert_eq!(s.redo_depth(), had_redo, "{tag}: a refused edit (op {op}) touched the redo stack");
506 refused += 1;
507 }
508 }
509 }
510 // A success's new state is not known in advance, so it is read here and
511 // becomes the current state; every undo and redo must land on a recorded one.
512 let now = state(&s, &file);
513 if edited {
514 model.cur = now;
515 } else {
516 assert!(now == model.cur, "{tag}: state drifted from the model");
517 }
518 assert_eq!(s.undo_depth(), model.undo.len(), "{tag}: undo depth (last edit kind {last_op})");
519 assert_eq!(s.redo_depth(), model.redo.len(), "{tag}: redo depth");
520 assert_eq!(s.history_pushes(), model.pushes, "{tag}: pushes (last edit kind {last_op})");
521 }
522 eprintln!(
523 "seed {seed:#x}: {ops} steps, {} edits, {noops} no-ops, {refused} refused, {undos} undos, {redos} redos",
524 model.pushes
525 );
526 (model, s)
527}
528
529#[test]
530fn random_edits_undo_and_redo_exactly_for_every_seed() {
531 for seed in SEEDS {
532 let started = Instant::now();
533 let (mut model, mut s) = random_run(seed, OPS, Some(CAP));
534 assert!(model.undo.len() <= CAP, "the modelled history never exceeds the cap");
535 let file = Scratch::file(&format!("undo_stress_drain_{seed:x}"), "edith");
536 drain_and_refill(&mut s, &mut model, &file, &format!("seed {seed:#x} drain"));
537 eprintln!(
538 "seed {seed:#x}: {:.2?}, rss {} MiB",
539 started.elapsed(),
540 rss_kib() / 1024
541 );
542 }
543}
544
545#[test]
546fn undo_past_the_cap_is_a_noop_and_the_oldest_steps_are_dropped() {
547 let file = Scratch::file("undo_stress_cap", "edith");
548 let mut s = open_session();
549 let bottom_at = |n: usize| -> Vec<u8> {
550 // The state after `n` gain edits, from a fresh session that makes just those.
551 let mut t = open_session();
552 for i in 1..=n {
553 assert!(t.set_lane_gain_db(Lane::new(LaneKind::Video, 0), -0.1 * i as f32));
554 }
555 state(&t, &file)
556 };
557 let lane = Lane::new(LaneKind::Video, 0);
558 for i in 1..=CAP + 50 {
559 assert!(s.set_lane_gain_db(lane, -0.1 * i as f32), "gain edit {i} is a success");
560 }
561 assert_eq!(s.undo_depth(), CAP, "the history is capped");
562 assert_eq!(s.history_pushes(), (CAP + 50) as u64, "every edit still counted");
563
564 for _ in 0..CAP {
565 assert!(s.undo());
566 }
567 assert_eq!(s.undo_depth(), 0);
568 assert!(!s.undo(), "undo past the cap is a refused no-op");
569 assert_eq!(s.undo_depth(), 0);
570 // Oldest dropped: the 50 earliest steps are gone, so the bottom is the state after edit 50.
571 assert!(state(&s, &file) == bottom_at(50), "undo stops at the oldest kept step");
572 assert_eq!(s.history_pushes(), (CAP + 50) as u64, "an undo does not roll the count back");
573 assert!(s.redo(), "the oldest kept step is still a redo");
574}
575
576#[test]
577fn held_history_keeps_every_step_and_trims_back_to_the_cap_on_release() {
578 let seed = 7;
579 let (mut model, mut s) = random_run(seed, HELD_OPS, None);
580 let file = Scratch::file("undo_stress_held", "edith");
581 // Every step survived the run, so the whole chain is walkable back.
582 assert!(model.undo.len() > CAP, "held history runs past the cap ({})", model.undo.len());
583 assert_eq!(s.undo_depth(), model.undo.len());
584 s.hold_history(false);
585 model.undo.drain(..model.undo.len().saturating_sub(CAP));
586 assert_eq!(s.undo_depth(), CAP, "releasing trims back to the cap");
587 drain_and_refill(&mut s, &mut model, &file, "held");
588}