1use std::sync::Arc;
4pub mod ghost;
5mod wire;
6pub const MAX_TICKS: usize = 1_000_000;
7pub const MAX_EVENTS: usize = 1_000_000;
8pub const MAX_CHECKPOINTS: usize = 8192;
9pub const MAX_FILE_BYTES: usize = 64 * 1024 * 1024;
10pub const MAX_INPUT_BYTES: usize = 4096;
11pub const MAX_EVENT_BYTES: usize = 4096;
12pub const MAX_STATE_BYTES: usize = 64 * 1024;
13#[derive(Clone, Copy, Debug, PartialEq, Eq)]
14pub enum ReplayError {
15 InvalidLimits,
16 InvalidHeader,
17 TickOrder,
18 Capacity,
19 MissingCheckpoint,
20 InvalidData,
21 UnsupportedVersion,
22 Checksum,
23}
24impl std::fmt::Display for ReplayError {
25 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
26 write!(f, "{self:?}")
27 }
28}
29impl std::error::Error for ReplayError {}
30#[derive(Clone, Copy, Debug, PartialEq, Eq)]
31pub struct Header {
32 pub schema: u64,
33 pub version: u32,
34 pub context: u64,
35 pub tick_hz: u16,
36 pub seed: u64,
37}
38impl Header {
39 fn valid(self) -> bool {
40 self.schema != 0 && self.version != 0 && (1..=1000).contains(&self.tick_hz)
41 }
42}
43#[derive(Clone, Copy, Debug)]
44pub struct Limits {
45 pub ticks: usize,
46 pub events: usize,
47 pub checkpoints: usize,
48 pub bytes: usize,
49 pub checkpoint_interval: u64,
50 pub input_bytes: usize,
51 pub event_bytes: usize,
52 pub state_bytes: usize,
53}
54impl Default for Limits {
55 fn default() -> Self {
56 Self {
57 ticks: 19200,
58 events: 32768,
59 checkpoints: 152,
60 bytes: 4 * 1024 * 1024,
61 checkpoint_interval: 128,
62 input_bytes: 1024,
63 event_bytes: 128,
64 state_bytes: MAX_STATE_BYTES,
65 }
66 }
67}
68impl Limits {
69 fn valid(self) -> bool {
70 self.ticks <= MAX_TICKS
71 && self.events <= MAX_EVENTS
72 && (1..=MAX_CHECKPOINTS).contains(&self.checkpoints)
73 && self.bytes <= MAX_FILE_BYTES
74 && self.checkpoint_interval > 0
75 && self.input_bytes <= MAX_INPUT_BYTES
76 && self.event_bytes <= MAX_EVENT_BYTES
77 && (1..=MAX_STATE_BYTES).contains(&self.state_bytes)
78 && self
79 .ticks
80 .checked_mul(32)
81 .and_then(|n| self.events.checked_mul(12).and_then(|e| n.checked_add(e)))
82 .and_then(|n| {
83 self.checkpoints
84 .checked_mul(24)
85 .and_then(|c| n.checked_add(c))
86 })
87 .and_then(|n| n.checked_add(self.bytes))
88 .and_then(|n| n.checked_add(64))
89 .is_some_and(|n| n <= MAX_FILE_BYTES)
90 }
91}
92#[derive(Clone, Copy, Debug, PartialEq, Eq)]
93pub(super) struct Span {
94 start: u32,
95 len: u32,
96}
97impl Span {
98 fn bytes(self, arena: &[u8]) -> &[u8] {
99 &arena[self.start as usize..(self.start + self.len) as usize]
100 }
101}
102#[derive(Clone, Copy, Debug, PartialEq, Eq)]
103pub(super) struct Tick {
104 tick: u64,
105 hash: u64,
106 input: Span,
107 event_start: u32,
108 event_count: u16,
109}
110#[derive(Clone, Copy, Debug, PartialEq, Eq)]
111pub(super) struct Event {
112 kind: u16,
113 data: Span,
114}
115#[derive(Clone, Copy, Debug, PartialEq, Eq)]
116pub(super) struct Checkpoint {
117 tick: u64,
118 hash: u64,
119 state: Span,
120}
121#[derive(Clone, Debug)]
122pub struct Recording {
123 header: Header,
124 ticks: Vec<Tick>,
125 events: Vec<Event>,
126 checkpoints: Vec<Checkpoint>,
127 arena: Vec<u8>,
128}
129impl Recording {
130 pub fn header(&self) -> Header {
131 self.header
132 }
133 pub fn start_tick(&self) -> u64 {
134 self.checkpoints[0].tick
135 }
136 pub fn end_tick(&self) -> u64 {
137 self.ticks.last().map_or(self.start_tick(), |f| f.tick)
138 }
139 pub fn tick_count(&self) -> usize {
140 self.ticks.len()
141 }
142 pub fn event_count(&self) -> usize {
143 self.events.len()
144 }
145 pub fn checkpoint_count(&self) -> usize {
146 self.checkpoints.len()
147 }
148 pub fn payload_bytes(&self) -> usize {
149 self.arena.len()
150 }
151 pub fn events_at(&self, tick: u64) -> EventIter<'_> {
152 let found = self
153 .ticks
154 .binary_search_by_key(&tick, |f| f.tick)
155 .ok()
156 .map(|i| self.ticks[i]);
157 let events = found.map_or(&[][..], |f| {
158 &self.events[f.event_start as usize..f.event_start as usize + f.event_count as usize]
159 });
160 EventIter {
161 events: events.iter(),
162 arena: &self.arena,
163 }
164 }
165 pub fn input_at(&self, tick: u64) -> Option<&[u8]> {
166 self.ticks
167 .binary_search_by_key(&tick, |f| f.tick)
168 .ok()
169 .map(|i| self.ticks[i].input.bytes(&self.arena))
170 }
171}
172#[derive(Clone, Copy, Debug, PartialEq, Eq)]
173pub struct EventInput<'a> {
174 pub kind: u16,
175 pub payload: &'a [u8],
176}
177#[derive(Clone)]
178pub struct EventIter<'a> {
179 events: std::slice::Iter<'a, Event>,
180 arena: &'a [u8],
181}
182impl<'a> Iterator for EventIter<'a> {
183 type Item = EventInput<'a>;
184 fn next(&mut self) -> Option<Self::Item> {
185 self.events.next().map(|e| EventInput {
186 kind: e.kind,
187 payload: e.data.bytes(self.arena),
188 })
189 }
190 fn size_hint(&self) -> (usize, Option<usize>) {
191 self.events.size_hint()
192 }
193}
194impl ExactSizeIterator for EventIter<'_> {}
195pub struct Recorder {
198 data: Recording,
199 limits: Limits,
200}
201impl Recorder {
202 pub fn new(
203 header: Header,
204 limits: Limits,
205 tick: u64,
206 state: &[u8],
207 hash: u64,
208 ) -> Result<Self, ReplayError> {
209 if !header.valid() {
210 return Err(ReplayError::InvalidHeader);
211 }
212 if !limits.valid() {
213 return Err(ReplayError::InvalidLimits);
214 }
215 if state.is_empty() || state.len() > limits.state_bytes || state.len() > limits.bytes {
216 return Err(ReplayError::Capacity);
217 }
218 let mut data = Recording {
219 header,
220 ticks: Vec::with_capacity(limits.ticks),
221 events: Vec::with_capacity(limits.events),
222 checkpoints: Vec::with_capacity(limits.checkpoints),
223 arena: Vec::with_capacity(limits.bytes),
224 };
225 data.arena.extend_from_slice(state);
226 data.checkpoints.push(Checkpoint {
227 tick,
228 hash,
229 state: Span {
230 start: 0,
231 len: state.len() as u32,
232 },
233 });
234 Ok(Self { data, limits })
235 }
236 pub fn needs_checkpoint(&self, tick: u64) -> bool {
237 tick.saturating_sub(self.data.checkpoints.last().unwrap().tick)
238 >= self.limits.checkpoint_interval
239 }
240 pub fn tick_count(&self) -> usize {
241 self.data.ticks.len()
242 }
243 pub fn payload_bytes(&self) -> usize {
244 self.data.arena.len()
245 }
246 pub fn push(
247 &mut self,
248 tick: u64,
249 input: &[u8],
250 events: &[EventInput<'_>],
251 checkpoint: Option<&[u8]>,
252 hash: u64,
253 ) -> Result<(), ReplayError> {
254 if self.data.end_tick().checked_add(1) != Some(tick) {
255 return Err(ReplayError::TickOrder);
256 }
257 if self.needs_checkpoint(tick) && checkpoint.is_none() {
258 return Err(ReplayError::MissingCheckpoint);
259 }
260 if self.data.ticks.len() == self.limits.ticks
261 || input.len() > self.limits.input_bytes
262 || events.len() > 64
263 || events.len() > self.limits.events - self.data.events.len()
264 || events
265 .iter()
266 .any(|e| e.payload.len() > self.limits.event_bytes)
267 || checkpoint.is_some_and(|s| {
268 s.is_empty()
269 || s.len() > self.limits.state_bytes
270 || self.data.checkpoints.len() == self.limits.checkpoints
271 })
272 {
273 return Err(ReplayError::Capacity);
274 }
275 let needed = input.len()
276 + events.iter().map(|e| e.payload.len()).sum::<usize>()
277 + checkpoint.map_or(0, |s| s.len());
278 if needed > self.limits.bytes - self.data.arena.len() {
279 return Err(ReplayError::Capacity);
280 }
281 let mut append = |bytes: &[u8]| {
282 let span = Span {
283 start: self.data.arena.len() as u32,
284 len: bytes.len() as u32,
285 };
286 self.data.arena.extend_from_slice(bytes);
287 span
288 };
289 let input = append(input);
290 let event_start = self.data.events.len() as u32;
291 for event in events {
292 self.data.events.push(Event {
293 kind: event.kind,
294 data: append(event.payload),
295 });
296 }
297 if let Some(state) = checkpoint {
298 self.data.checkpoints.push(Checkpoint {
299 tick,
300 hash,
301 state: append(state),
302 });
303 }
304 self.data.ticks.push(Tick {
305 tick,
306 hash,
307 input,
308 event_start,
309 event_count: events.len() as u16,
310 });
311 Ok(())
312 }
313 pub fn finish(mut self) -> Recording {
314 self.data.ticks.shrink_to_fit();
315 self.data.events.shrink_to_fit();
316 self.data.checkpoints.shrink_to_fit();
317 self.data.arena.shrink_to_fit();
318 self.data
319 }
320}
321pub trait ReplayWorld {
325 type Error;
326 const SCHEMA: u64;
327 const VERSION: u32;
328 const TICK_HZ: u16;
329 fn context(&self) -> Result<u64, Self::Error>;
330 fn restore(&mut self, state: &[u8]) -> Result<(), Self::Error>;
331 fn step(&mut self, input: &[u8], expected: EventIter<'_>) -> Result<(), Self::Error>;
332 fn state_hash(&self) -> Result<u64, Self::Error>;
333}
334#[derive(Clone, Copy, Debug, PartialEq, Eq)]
336pub enum ReplayChecksum {
337 State,
339 Input,
341}
342#[derive(Clone, Copy, Debug, PartialEq, Eq)]
347pub struct ReplayMismatch {
348 pub tick: u64,
349 pub checksum: ReplayChecksum,
350 pub expected: u64,
351 pub actual: u64,
352}
353impl ReplayMismatch {
354 fn error<E>(self) -> PlaybackError<E> {
355 PlaybackError::Desync {
356 tick: self.tick,
357 expected: self.expected,
358 actual: self.actual,
359 }
360 }
361}
362impl std::fmt::Display for ReplayMismatch {
363 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
364 let kind = match self.checksum {
365 ReplayChecksum::State => "state",
366 ReplayChecksum::Input => "input",
367 };
368 write!(
369 f,
370 "replay {kind} mismatch at tick {}: expected {:016x}, actual {:016x}",
371 self.tick, self.expected, self.actual
372 )
373 }
374}
375impl std::error::Error for ReplayMismatch {}
376
377pub fn input_checksum(input: &[u8]) -> u64 {
386 input.iter().fold(0xcbf29ce484222325, |hash, byte| {
387 (hash ^ u64::from(*byte)).wrapping_mul(0x100000001b3)
388 })
389}
390
391#[derive(Clone, Copy, Debug, PartialEq, Eq)]
393pub enum PlaybackStatus {
394 NotStarted,
395 Playing,
396 Seeking {
397 target: u64,
398 },
399 Finished,
402 Faulted,
404}
405#[derive(Clone, Debug, PartialEq, Eq)]
406pub enum PlaybackError<E> {
407 State(E),
408 Incompatible,
409 InvalidTarget,
410 NotStarted,
411 Ended,
412 Seeking,
413 Faulted,
414 Desync {
416 tick: u64,
417 expected: u64,
418 actual: u64,
419 },
420}
421pub struct Playback {
471 recording: Arc<Recording>,
472 position: u64,
473 row: usize,
474 started: bool,
475 poisoned: bool,
476 seek: Option<u64>,
477 fault: Option<ReplayMismatch>,
478}
479impl Playback {
480 pub fn new(recording: Arc<Recording>) -> Self {
481 let position = recording.start_tick();
482 Self {
483 recording,
484 position,
485 row: 0,
486 started: false,
487 poisoned: false,
488 seek: None,
489 fault: None,
490 }
491 }
492 pub fn recording(&self) -> &Recording {
493 &self.recording
494 }
495 pub fn position(&self) -> u64 {
496 self.position
497 }
498 pub fn seeking(&self) -> bool {
499 self.seek.is_some()
500 }
501 pub fn finished(&self) -> bool {
504 self.status() == PlaybackStatus::Finished
505 }
506 pub fn fault(&self) -> Option<(u64, u64, u64)> {
509 self.fault.map(|m| (m.tick, m.expected, m.actual))
510 }
511 pub fn first_mismatch(&self) -> Option<ReplayMismatch> {
515 self.fault
516 }
517 pub fn status(&self) -> PlaybackStatus {
519 if self.poisoned || self.fault.is_some() {
520 PlaybackStatus::Faulted
521 } else if !self.started {
522 PlaybackStatus::NotStarted
523 } else if let Some(target) = self.seek {
524 PlaybackStatus::Seeking { target }
525 } else if self.row == self.recording.ticks.len() {
526 PlaybackStatus::Finished
527 } else {
528 PlaybackStatus::Playing
529 }
530 }
531 pub fn reset(&mut self) {
535 self.position = self.recording.start_tick();
536 self.row = 0;
537 self.started = false;
538 self.poisoned = false;
539 self.seek = None;
540 self.fault = None;
541 }
542 pub fn start<W: ReplayWorld>(&mut self, world: &mut W) -> Result<(), PlaybackError<W::Error>> {
545 let h = self.recording.header;
546 if h.schema != W::SCHEMA
547 || h.version != W::VERSION
548 || h.tick_hz != W::TICK_HZ
549 || h.context != world.context().map_err(PlaybackError::State)?
550 {
551 return Err(PlaybackError::Incompatible);
552 }
553 self.restore_at(world, 0)?;
554 self.started = true;
555 self.seek = None;
556 Ok(())
557 }
558 fn restore_at<W: ReplayWorld>(
559 &mut self,
560 world: &mut W,
561 index: usize,
562 ) -> Result<(), PlaybackError<W::Error>> {
563 let cp = self.recording.checkpoints[index];
564 self.seek = None;
565 self.fault = None;
566 if let Err(e) = world.restore(cp.state.bytes(&self.recording.arena)) {
567 self.poisoned = true;
568 return Err(PlaybackError::State(e));
569 }
570 self.position = cp.tick;
571 self.row = self.recording.ticks.partition_point(|f| f.tick <= cp.tick);
572 self.poisoned = false;
573 self.verify(world, cp.tick, cp.hash)
574 }
575 fn verify<W: ReplayWorld>(
576 &mut self,
577 world: &W,
578 tick: u64,
579 expected: u64,
580 ) -> Result<(), PlaybackError<W::Error>> {
581 let actual = match world.state_hash() {
582 Ok(hash) => hash,
583 Err(e) => {
584 self.poisoned = true;
585 return Err(PlaybackError::State(e));
586 }
587 };
588 if actual != expected {
589 return Err(self.record_mismatch(ReplayMismatch {
590 tick,
591 checksum: ReplayChecksum::State,
592 expected,
593 actual,
594 }));
595 }
596 Ok(())
597 }
598 fn record_mismatch<E>(&mut self, mismatch: ReplayMismatch) -> PlaybackError<E> {
599 self.fault.get_or_insert(mismatch).error()
600 }
601 fn check_fault<E>(&self) -> Result<(), PlaybackError<E>> {
602 if let Some(mismatch) = self.fault {
603 return Err(mismatch.error());
604 }
605 if self.poisoned {
606 return Err(PlaybackError::Faulted);
607 }
608 Ok(())
609 }
610 fn check_step<E>(&self) -> Result<(), PlaybackError<E>> {
611 self.check_fault()?;
612 if !self.started {
613 return Err(PlaybackError::NotStarted);
614 }
615 if self.seek.is_some() {
616 return Err(PlaybackError::Seeking);
617 }
618 Ok(())
619 }
620 pub fn step<W: ReplayWorld>(&mut self, world: &mut W) -> Result<(), PlaybackError<W::Error>> {
621 self.check_step()?;
622 self.step_inner(world)
623 }
624 pub fn step_with_input<W: ReplayWorld>(
633 &mut self,
634 world: &mut W,
635 input: &[u8],
636 ) -> Result<(), PlaybackError<W::Error>> {
637 self.check_step()?;
638 let Some(frame) = self.recording.ticks.get(self.row) else {
639 return Err(PlaybackError::Ended);
640 };
641 let expected = frame.input.bytes(&self.recording.arena);
642 if input != expected {
643 return Err(self.record_mismatch(ReplayMismatch {
644 tick: frame.tick,
645 checksum: ReplayChecksum::Input,
646 expected: input_checksum(expected),
647 actual: input_checksum(input),
648 }));
649 }
650 self.step_inner(world)
651 }
652 fn step_inner<W: ReplayWorld>(&mut self, world: &mut W) -> Result<(), PlaybackError<W::Error>> {
653 self.check_fault()?;
654 let Some(frame) = self.recording.ticks.get(self.row).copied() else {
655 return Err(PlaybackError::Ended);
656 };
657 if let Err(e) = world.step(
658 frame.input.bytes(&self.recording.arena),
659 self.recording.events_at(frame.tick),
660 ) {
661 self.poisoned = true;
662 return Err(PlaybackError::State(e));
663 }
664 self.position = frame.tick;
665 self.row += 1;
666 self.verify(world, frame.tick, frame.hash)
667 }
668 pub fn seek<W: ReplayWorld>(
672 &mut self,
673 world: &mut W,
674 target: u64,
675 ) -> Result<(), PlaybackError<W::Error>> {
676 if !self.started {
677 return Err(PlaybackError::NotStarted);
678 }
679 if target < self.recording.start_tick() || target > self.recording.end_tick() {
680 return Err(PlaybackError::InvalidTarget);
681 }
682 let index = self
683 .recording
684 .checkpoints
685 .partition_point(|c| c.tick <= target)
686 - 1;
687 self.restore_at(world, index)?;
688 self.seek = (self.position < target).then_some(target);
689 Ok(())
690 }
691 pub fn pump_seek<W: ReplayWorld>(
695 &mut self,
696 world: &mut W,
697 budget: usize,
698 ) -> Result<usize, PlaybackError<W::Error>> {
699 let Some(target) = self.seek else {
700 return Ok(0);
701 };
702 let mut steps = 0;
703 while self.position < target && steps < budget.min(MAX_TICKS) {
704 if let Err(e) = self.step_inner(world) {
705 self.seek = None;
706 return Err(e);
707 }
708 steps += 1;
709 }
710 if self.position == target {
711 self.seek = None;
712 }
713 Ok(steps)
714 }
715}
716pub fn derive_seed(seed: u64, tick: u64, channel: u64) -> u64 {
719 let mut x = seed ^ tick.wrapping_mul(0x9e3779b97f4a7c15) ^ channel.rotate_left(29);
720 x = (x ^ (x >> 30)).wrapping_mul(0xbf58476d1ce4e5b9);
721 x = (x ^ (x >> 27)).wrapping_mul(0x94d049bb133111eb);
722 x ^ (x >> 31)
723}
724#[cfg(test)]
725mod tests;