oarust 0.20.1

GPU-first semantic computing runtime written in Rust
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
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
//! Preallocated device-resident off-policy replay storage.

use std::{
	ffi::OsString,
	fs,
	io::Write,
	path::{Path, PathBuf},
};

use crate::runtime::ComputeDispatch;
use crate::runtime::SemanticDispatch;
use crate::runtime::{BufferBinding, KernelId, PushConstant};
use crate::{DType, Error, Matrix, OpAttribute, Result, Runtime};

pub use crate::ml::types::ReplayConfig;
use crate::ml::validation::shader_u32;

/// One batch of transitions to append to a [`ReplayBuffer`].
#[derive(Clone)]
pub struct ReplayTransition {
	observation: Matrix,
	action: Matrix,
	next_observation: Matrix,
	reward: Matrix,
	terminated: Matrix,
	truncated: Matrix,
}

impl ReplayTransition {
	/// Construct an unchecked replay transition carrier.
	///
	/// [`ReplayBuffer::append`] validates every field against its configuration.
	pub fn new(
		observation: Matrix,
		action: Matrix,
		next_observation: Matrix,
		reward: Matrix,
		terminated: Matrix,
		truncated: Matrix,
	) -> Self {
		Self {
			observation,
			action,
			next_observation,
			reward,
			terminated,
			truncated,
		}
	}

	/// Return the observations.
	pub const fn observation(&self) -> &Matrix {
		&self.observation
	}

	/// Return the actions.
	pub const fn action(&self) -> &Matrix {
		&self.action
	}

	/// Return the successor observations.
	pub const fn next_observation(&self) -> &Matrix {
		&self.next_observation
	}

	/// Return the scalar rewards.
	pub const fn reward(&self) -> &Matrix {
		&self.reward
	}

	/// Return termination flags.
	pub const fn terminated(&self) -> &Matrix {
		&self.terminated
	}

	/// Return truncation flags.
	pub const fn truncated(&self) -> &Matrix {
		&self.truncated
	}
}

/// Device-resident replay values, optionally including sampled source indices.
pub struct ReplayBatch {
	pub(crate) observation: Matrix,
	pub(crate) action: Matrix,
	pub(crate) next_observation: Matrix,
	pub(crate) reward: Matrix,
	pub(crate) terminated: Matrix,
	pub(crate) truncated: Matrix,
	pub(crate) index: Matrix,
}

impl ReplayBatch {
	/// Return observations with a leading storage or sample axis.
	pub const fn observation(&self) -> &Matrix {
		&self.observation
	}

	/// Return actions with a leading storage or sample axis.
	pub const fn action(&self) -> &Matrix {
		&self.action
	}

	/// Return successor observations with a leading storage or sample axis.
	pub const fn next_observation(&self) -> &Matrix {
		&self.next_observation
	}

	/// Return scalar rewards.
	pub const fn reward(&self) -> &Matrix {
		&self.reward
	}

	/// Return termination flags.
	pub const fn terminated(&self) -> &Matrix {
		&self.terminated
	}

	/// Return truncation flags.
	pub const fn truncated(&self) -> &Matrix {
		&self.truncated
	}

	/// Return sampled source indices; storage batches leave this matrix unused.
	pub const fn index(&self) -> &Matrix {
		&self.index
	}
}

/// Circular fixed-capacity owner for off-policy transitions.
///
/// Batched append and deterministic uniform sampling are recorded on the one
/// owning runtime. Cursor and size are host control metadata and never require a
/// Matrix readback.
pub struct ReplayBuffer {
	config: ReplayConfig,
	storage: ReplayBatch,
	observation_elements: u32,
	action_elements: u32,
	size: core::cell::Cell<usize>,
	cursor: core::cell::Cell<usize>,
}

impl ReplayBuffer {
	/// Allocate empty circular replay storage on `runtime`.
	///
	/// # Errors
	///
	/// Returns an error for zero capacity, non-F32/I32 actions, invalid field
	/// ranks or extents, GPU-index overflow, or allocation failure.
	pub fn new(runtime: &Runtime, config: ReplayConfig) -> Result<Self> {
		if config.capacity == 0 || !matches!(config.action_dtype, DType::F32 | DType::I32) {
			return Err(Error::invalid_argument(
				"ReplayBuffer requires positive capacity and F32 or I32 actions",
			));
		}
		let observation_elements = field_elements(&config.observation_shape, false)?;
		let action_elements = field_elements(&config.action_shape, true)?;
		let observation_count = config
			.capacity
			.checked_mul(observation_elements)
			.ok_or_else(|| Error::resource_exhausted("replay observation storage overflows usize"))?;
		let action_count = config
			.capacity
			.checked_mul(action_elements)
			.ok_or_else(|| Error::resource_exhausted("replay action storage overflows usize"))?;
		for (label, count) in [
			("capacity", config.capacity),
			("observation storage", observation_count),
			("action storage", action_count),
		] {
			u32::try_from(count).map_err(|_| {
				Error::resource_exhausted(format!("replay {label} exceeds GPU u32 indexing"))
			})?;
		}
		let observation_elements = u32::try_from(observation_elements)
			.map_err(|_| Error::resource_exhausted("replay observation field exceeds u32"))?;
		let action_elements = u32::try_from(action_elements)
			.map_err(|_| Error::resource_exhausted("replay action field exceeds u32"))?;
		let mut observation_shape = vec![config.capacity];
		observation_shape.extend_from_slice(&config.observation_shape);
		let mut action_shape = vec![config.capacity];
		action_shape.extend_from_slice(&config.action_shape);
		let handle = runtime.handle();
		let storage = ReplayBatch {
			observation: Matrix::allocate(
				&handle,
				observation_shape.clone(),
				observation_count,
				DType::F32,
			)?,
			action: Matrix::allocate(&handle, action_shape, action_count, config.action_dtype)?,
			next_observation: Matrix::allocate(
				&handle,
				observation_shape,
				observation_count,
				DType::F32,
			)?,
			reward: Matrix::allocate(&handle, vec![config.capacity], config.capacity, DType::F32)?,
			terminated: Matrix::allocate(&handle, vec![config.capacity], config.capacity, DType::U8)?,
			truncated: Matrix::allocate(&handle, vec![config.capacity], config.capacity, DType::U8)?,
			index: Matrix::allocate(&handle, vec![config.capacity], config.capacity, DType::U32)?,
		};
		Ok(Self {
			config,
			storage,
			observation_elements,
			action_elements,
			size: core::cell::Cell::new(0),
			cursor: core::cell::Cell::new(0),
		})
	}

	/// Record one batched circular append.
	///
	/// # Errors
	///
	/// Returns an error unless the batch is nonempty, no larger than capacity,
	/// all fields match the configured shape/dtype/runtime contract, source and
	/// retained storage do not alias, and GPU recording succeeds.
	pub fn append(&self, transition: &ReplayTransition) -> Result<()> {
		let cursor = self.cursor.get();
		let batch = append_dispatch(
			transition,
			&self.storage,
			&self.config,
			cursor,
			self.observation_elements,
			self.action_elements,
		)?;
		self.cursor.set((cursor + batch) % self.config.capacity);
		self.size.set(
			self
				.config
				.capacity
				.min(self.size.get().saturating_add(batch)),
		);
		Ok(())
	}

	/// Record deterministic uniform sampling with replacement.
	///
	/// The returned U32 index vector identifies every sampled physical replay
	/// slot exactly.
	///
	/// # Errors
	///
	/// Returns an error while storage is empty, for a zero sample count, on GPU
	/// indexing/allocation failure, or when recording fails.
	pub fn sample(&self, batch_size: usize, seed: u64) -> Result<ReplayBatch> {
		if self.size.get() == 0 || batch_size == 0 {
			return Err(Error::failed_precondition(
				"ReplayBuffer sample requires nonempty storage and a positive batch size",
			));
		}
		sample_dispatch(
			&self.storage,
			&self.config,
			self.size.get(),
			batch_size,
			seed,
			self.observation_elements,
			self.action_elements,
		)
	}

	/// Forget all retained transitions without recording device work.
	///
	/// Existing bytes remain inaccessible until overwritten by later appends.
	pub fn reset(&self) {
		self.size.set(0);
		self.cursor.set(0);
	}

	/// Return whether capacity is completely occupied.
	pub fn is_full(&self) -> bool {
		self.size.get() == self.config.capacity
	}

	/// Return the number of accessible transitions.
	pub fn len(&self) -> usize {
		self.size.get()
	}

	/// Return whether no transition is accessible.
	pub const fn is_empty(&self) -> bool {
		self.size.get() == 0
	}

	/// Return the fixed transition capacity.
	pub const fn capacity(&self) -> usize {
		self.config.capacity
	}

	/// Return the physical slot that receives the next append lane.
	pub fn cursor(&self) -> usize {
		self.cursor.get()
	}

	/// Return the validated replay configuration.
	pub const fn config(&self) -> &ReplayConfig {
		&self.config
	}

	/// Capture the complete active replay contents, size, and circular write
	/// cursor into a host-owned snapshot.
	///
	/// This is an explicit host-observation boundary: pending GPU appends on
	/// the owning runtime are flushed before reading the active `0..len()`
	/// slots.
	///
	/// # Errors
	///
	/// Returns an error when any storage readback fails or element counts
	/// overflow host indexing.
	pub fn capture_state(&self) -> Result<ReplayBufferState> {
		let size = self.size.get();
		let cursor = self.cursor.get();
		let obs_count = size
			.checked_mul(self.observation_elements as usize)
			.ok_or_else(|| {
				Error::resource_exhausted("replay capture observation size overflows usize")
			})?;
		let act_count = size
			.checked_mul(self.action_elements as usize)
			.ok_or_else(|| Error::resource_exhausted("replay capture action size overflows usize"))?;
		if size == 0 {
			return Ok(ReplayBufferState {
				config: self.config.clone(),
				size: 0,
				cursor: 0,
				observation: Vec::new(),
				action_bytes: Vec::new(),
				next_observation: Vec::new(),
				reward: Vec::new(),
				terminated: Vec::new(),
				truncated: Vec::new(),
			});
		}
		let mut observation = self.storage.observation().read_f32()?;
		observation.truncate(obs_count);
		let action_bytes = match self.config.action_dtype {
			DType::F32 => {
				let values = self.storage.action().read_f32()?;
				let mut bytes = Vec::with_capacity(act_count * 4);
				for &value in &values[..act_count] {
					bytes.extend_from_slice(&value.to_le_bytes());
				}
				bytes
			}
			DType::I32 => {
				let values = self.storage.action().read::<i32>()?;
				let mut bytes = Vec::with_capacity(act_count * 4);
				for &value in &values[..act_count] {
					bytes.extend_from_slice(&value.to_le_bytes());
				}
				bytes
			}
			other => {
				return Err(Error::invalid_argument(format!(
					"unsupported replay action dtype {}",
					other.token()
				)));
			}
		};
		let mut next_observation = self.storage.next_observation().read_f32()?;
		next_observation.truncate(obs_count);
		let mut reward = self.storage.reward().read_f32()?;
		reward.truncate(size);
		let mut terminated = self.storage.terminated().read::<u8>()?;
		terminated.truncate(size);
		let mut truncated = self.storage.truncated().read::<u8>()?;
		truncated.truncate(size);
		Ok(ReplayBufferState {
			config: self.config.clone(),
			size,
			cursor,
			observation,
			action_bytes,
			next_observation,
			reward,
			terminated,
			truncated,
		})
	}

	/// Restore a captured replay snapshot into this buffer fail-closed.
	///
	/// Validates schema equality, circular-cursor invariants, and payload
	/// lengths before uploading active transitions into physical slots `0..len`
	/// and flushing the owning runtime.
	///
	/// # Errors
	///
	/// Returns an error if `state` has a mismatched configuration or malformed
	/// fields, or if device upload or synchronization fails.
	pub fn restore_state(&self, state: &ReplayBufferState) -> Result<()> {
		state.validate()?;
		if state.config != self.config {
			return Err(Error::invalid_argument(
				"replay snapshot configuration does not match destination ReplayBuffer",
			));
		}
		if state.size == 0 {
			self.size.set(0);
			self.cursor.set(0);
			return Ok(());
		}
		let runtime = self.storage.observation().runtime();
		let obs_shape = prefixed_shape(state.size, &self.config.observation_shape);
		let act_shape = prefixed_shape(state.size, &self.config.action_shape);
		let vec_shape = vec![state.size];
		let observation =
			Matrix::new_from_slice_handle(runtime, obs_shape.clone(), &state.observation)?;
		let action = match self.config.action_dtype {
			DType::F32 => {
				let values: Vec<f32> = state
					.action_bytes
					.as_chunks::<4>()
					.0
					.iter()
					.copied()
					.map(f32::from_le_bytes)
					.collect();
				Matrix::new_from_slice_handle(runtime, act_shape, &values)?
			}
			DType::I32 => {
				let values: Vec<i32> = state
					.action_bytes
					.as_chunks::<4>()
					.0
					.iter()
					.copied()
					.map(i32::from_le_bytes)
					.collect();
				Matrix::new_from_slice_handle(runtime, act_shape, &values)?
			}
			other => {
				return Err(Error::invalid_argument(format!(
					"unsupported replay action dtype {}",
					other.token()
				)));
			}
		};
		let next_observation =
			Matrix::new_from_slice_handle(runtime, obs_shape, &state.next_observation)?;
		let reward = Matrix::new_from_slice_handle(runtime, vec_shape.clone(), &state.reward)?;
		let terminated = Matrix::new_from_slice_handle(runtime, vec_shape.clone(), &state.terminated)?;
		let truncated = Matrix::new_from_slice_handle(runtime, vec_shape, &state.truncated)?;
		let transition = ReplayTransition::new(
			observation,
			action,
			next_observation,
			reward,
			terminated,
			truncated,
		);
		append_dispatch(
			&transition,
			&self.storage,
			&self.config,
			0,
			self.observation_elements,
			self.action_elements,
		)?;
		runtime.checkpoint(false)?.wait()?;
		self.size.set(state.size);
		self.cursor.set(state.cursor);
		Ok(())
	}

	/// Atomically persist the active replay contents, size, and cursor to `path`.
	///
	/// # Errors
	///
	/// Returns an error when readback, encoding, temporary write, flush, or
	/// rename fails.
	pub fn save(&self, path: impl AsRef<Path>) -> Result<()> {
		self.capture_state()?.save(path)
	}

	/// Load a persisted replay file from `path` into this buffer fail-closed.
	///
	/// # Errors
	///
	/// Returns [`crate::ErrorKind::CheckpointCorrupt`] for malformed, truncated,
	/// or checksum-invalid files, or another error on schema mismatch or device
	/// restore failure.
	pub fn load_into(&self, path: impl AsRef<Path>) -> Result<()> {
		let state = ReplayBufferState::load(path)?;
		self.restore_state(&state)
	}
}

/// Host-owned snapshot of a [`ReplayBuffer`], including exact circular cursor
/// position and active transition payloads.
#[derive(Clone, Debug, PartialEq)]
pub struct ReplayBufferState {
	config: ReplayConfig,
	size: usize,
	cursor: usize,
	observation: Vec<f32>,
	action_bytes: Vec<u8>,
	next_observation: Vec<f32>,
	reward: Vec<f32>,
	terminated: Vec<u8>,
	truncated: Vec<u8>,
}

const REPLAY_MAGIC: &[u8; 4] = b"OARP";
const REPLAY_VERSION: u32 = 1;
const REPLAY_FNV_OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
const REPLAY_FNV_PRIME: u64 = 0x0100_0000_01b3;

impl ReplayBufferState {
	/// Return the replay schema recorded in this snapshot.
	pub const fn config(&self) -> &ReplayConfig {
		&self.config
	}

	/// Return the number of active transitions in this snapshot.
	pub const fn len(&self) -> usize {
		self.size
	}

	/// Return whether no transition is stored in this snapshot.
	pub const fn is_empty(&self) -> bool {
		self.size == 0
	}

	/// Return the circular physical write cursor recorded in this snapshot.
	pub const fn cursor(&self) -> usize {
		self.cursor
	}

	/// Serialize this snapshot into a self-describing, checksum-protected
	/// binary payload.
	///
	/// # Errors
	///
	/// Returns an error if the snapshot fails internal invariant validation.
	pub fn encode(&self) -> Result<Vec<u8>> {
		self.validate()?;
		let mut bytes = Vec::new();
		bytes.extend_from_slice(REPLAY_MAGIC);
		bytes.extend_from_slice(&REPLAY_VERSION.to_le_bytes());
		bytes.extend_from_slice(&(self.config.capacity as u64).to_le_bytes());
		bytes.extend_from_slice(&(self.size as u64).to_le_bytes());
		bytes.extend_from_slice(&(self.cursor as u64).to_le_bytes());
		let dtype_tag: u8 = match self.config.action_dtype {
			DType::F32 => 0,
			DType::I32 => 1,
			_ => {
				return Err(Error::invalid_argument(
					"replay snapshot only supports F32 or I32 actions",
				));
			}
		};
		bytes.push(dtype_tag);
		bytes.extend_from_slice(&(self.config.observation_shape.len() as u32).to_le_bytes());
		for &extent in &self.config.observation_shape {
			bytes.extend_from_slice(&(extent as u64).to_le_bytes());
		}
		bytes.extend_from_slice(&(self.config.action_shape.len() as u32).to_le_bytes());
		for &extent in &self.config.action_shape {
			bytes.extend_from_slice(&(extent as u64).to_le_bytes());
		}
		for &value in &self.observation {
			bytes.extend_from_slice(&value.to_le_bytes());
		}
		bytes.extend_from_slice(&self.action_bytes);
		for &value in &self.next_observation {
			bytes.extend_from_slice(&value.to_le_bytes());
		}
		for &value in &self.reward {
			bytes.extend_from_slice(&value.to_le_bytes());
		}
		bytes.extend_from_slice(&self.terminated);
		bytes.extend_from_slice(&self.truncated);
		let checksum = replay_fnv64(&bytes);
		bytes.extend_from_slice(&checksum.to_le_bytes());
		Ok(bytes)
	}

	/// Decode and integrity-check a binary replay snapshot.
	///
	/// # Errors
	///
	/// Returns [`crate::ErrorKind::CheckpointCorrupt`] for bad magic, unknown
	/// version, checksum mismatch, truncation, trailing bytes, or invariant
	/// violations.
	pub fn decode(bytes: &[u8]) -> Result<Self> {
		if bytes.len() < 8 {
			return Err(Error::checkpoint_corrupt("replay snapshot is truncated"));
		}
		let (body, tail) = bytes.split_at(bytes.len() - 8);
		let expected_checksum = u64::from_le_bytes(tail.try_into().expect("8-byte tail"));
		if replay_fnv64(body) != expected_checksum {
			return Err(Error::checkpoint_corrupt(
				"replay snapshot checksum verification failed",
			));
		}
		let mut cursor_pos = 0_usize;
		let magic = take_slice(body, &mut cursor_pos, 4)?;
		if magic != REPLAY_MAGIC {
			return Err(Error::checkpoint_corrupt(
				"replay snapshot has invalid magic",
			));
		}
		let version = take_u32(body, &mut cursor_pos)?;
		if version != REPLAY_VERSION {
			return Err(Error::checkpoint_corrupt(format!(
				"unsupported replay snapshot version {version}"
			)));
		}
		let capacity = usize::try_from(take_u64(body, &mut cursor_pos)?)
			.map_err(|_| Error::checkpoint_corrupt("replay capacity exceeds usize"))?;
		let size = usize::try_from(take_u64(body, &mut cursor_pos)?)
			.map_err(|_| Error::checkpoint_corrupt("replay size exceeds usize"))?;
		let write_cursor = usize::try_from(take_u64(body, &mut cursor_pos)?)
			.map_err(|_| Error::checkpoint_corrupt("replay cursor exceeds usize"))?;
		let dtype_tag = take_slice(body, &mut cursor_pos, 1)?[0];
		let action_dtype = match dtype_tag {
			0 => DType::F32,
			1 => DType::I32,
			_ => {
				return Err(Error::checkpoint_corrupt(format!(
					"unknown replay action dtype tag {dtype_tag}"
				)));
			}
		};
		let obs_rank = take_u32(body, &mut cursor_pos)? as usize;
		if obs_rank == 0 || obs_rank > 7 {
			return Err(Error::checkpoint_corrupt(
				"replay observation rank out of range",
			));
		}
		let mut observation_shape = Vec::with_capacity(obs_rank);
		for _ in 0..obs_rank {
			let extent = usize::try_from(take_u64(body, &mut cursor_pos)?)
				.map_err(|_| Error::checkpoint_corrupt("replay observation extent exceeds usize"))?;
			observation_shape.push(extent);
		}
		let act_rank = take_u32(body, &mut cursor_pos)? as usize;
		if act_rank > 7 {
			return Err(Error::checkpoint_corrupt("replay action rank out of range"));
		}
		let mut action_shape = Vec::with_capacity(act_rank);
		for _ in 0..act_rank {
			let extent = usize::try_from(take_u64(body, &mut cursor_pos)?)
				.map_err(|_| Error::checkpoint_corrupt("replay action extent exceeds usize"))?;
			action_shape.push(extent);
		}
		let config = ReplayConfig {
			capacity,
			observation_shape,
			action_shape,
			action_dtype,
		};
		let obs_elems = field_elements(&config.observation_shape, false)
			.map_err(|_| Error::checkpoint_corrupt("invalid replay observation shape"))?;
		let act_elems = field_elements(&config.action_shape, true)
			.map_err(|_| Error::checkpoint_corrupt("invalid replay action shape"))?;
		let obs_count = size
			.checked_mul(obs_elems)
			.ok_or_else(|| Error::checkpoint_corrupt("replay observation count overflow"))?;
		let act_byte_count = size
			.checked_mul(act_elems)
			.and_then(|count| count.checked_mul(4))
			.ok_or_else(|| Error::checkpoint_corrupt("replay action byte count overflow"))?;
		let obs_bytes = obs_count
			.checked_mul(4)
			.ok_or_else(|| Error::checkpoint_corrupt("replay observation byte count overflow"))?;
		let reward_bytes = size
			.checked_mul(4)
			.ok_or_else(|| Error::checkpoint_corrupt("replay reward byte count overflow"))?;
		let observation = decode_f32_slice(take_slice(body, &mut cursor_pos, obs_bytes)?);
		let action_bytes = take_slice(body, &mut cursor_pos, act_byte_count)?.to_vec();
		let next_observation = decode_f32_slice(take_slice(body, &mut cursor_pos, obs_bytes)?);
		let reward = decode_f32_slice(take_slice(body, &mut cursor_pos, reward_bytes)?);
		let terminated = take_slice(body, &mut cursor_pos, size)?.to_vec();
		let truncated = take_slice(body, &mut cursor_pos, size)?.to_vec();
		if cursor_pos != body.len() {
			return Err(Error::checkpoint_corrupt(
				"replay snapshot has trailing bytes",
			));
		}
		let state = Self {
			config,
			size,
			cursor: write_cursor,
			observation,
			action_bytes,
			next_observation,
			reward,
			terminated,
			truncated,
		};
		state
			.validate()
			.map_err(|error| Error::checkpoint_corrupt(error.message()))?;
		Ok(state)
	}

	/// Atomically write this replay snapshot to `path` (temp file + fsync + rename).
	///
	/// # Errors
	///
	/// Returns an error if encoding, file creation, writing, flushing, or rename fails.
	pub fn save(&self, path: impl AsRef<Path>) -> Result<()> {
		let path = path.as_ref();
		let bytes = self.encode()?;
		let mut tmp_os = OsString::from(path.as_os_str());
		tmp_os.push(".tmp");
		let temporary = PathBuf::from(tmp_os);
		{
			let mut file = fs::File::create(&temporary)
				.map_err(|error| Error::io("create replay temporary", error))?;
			file
				.write_all(&bytes)
				.map_err(|error| Error::io("write replay temporary", error))?;
			file
				.sync_all()
				.map_err(|error| Error::io("flush replay temporary", error))?;
		}
		fs::rename(&temporary, path).map_err(|error| Error::io("commit replay snapshot", error))
	}

	/// Read and integrity-check a persisted replay snapshot from `path`.
	///
	/// # Errors
	///
	/// Returns an I/O error if `path` cannot be read, or
	/// [`crate::ErrorKind::CheckpointCorrupt`] if the file fails validation.
	pub fn load(path: impl AsRef<Path>) -> Result<Self> {
		let path = path.as_ref();
		let bytes = fs::read(path).map_err(|error| Error::io("read replay snapshot", error))?;
		Self::decode(&bytes)
	}

	fn validate(&self) -> Result<()> {
		if self.config.capacity == 0 || !matches!(self.config.action_dtype, DType::F32 | DType::I32) {
			return Err(Error::invalid_argument(
				"replay snapshot requires positive capacity and F32 or I32 actions",
			));
		}
		let obs_elems = field_elements(&self.config.observation_shape, false)?;
		let act_elems = field_elements(&self.config.action_shape, true)?;
		if self.size > self.config.capacity || self.cursor >= self.config.capacity {
			return Err(Error::invalid_argument(
				"replay snapshot size or cursor exceeds configured capacity",
			));
		}
		if self.size < self.config.capacity && self.cursor != self.size {
			return Err(Error::invalid_argument(
				"unwrapped replay snapshot cursor must equal size",
			));
		}
		let expected_obs = self
			.size
			.checked_mul(obs_elems)
			.ok_or_else(|| Error::resource_exhausted("replay snapshot observation count overflow"))?;
		let expected_act_bytes = self
			.size
			.checked_mul(act_elems)
			.and_then(|count| count.checked_mul(4))
			.ok_or_else(|| Error::resource_exhausted("replay snapshot action byte count overflow"))?;
		if self.observation.len() != expected_obs
			|| self.next_observation.len() != expected_obs
			|| self.action_bytes.len() != expected_act_bytes
			|| self.reward.len() != self.size
			|| self.terminated.len() != self.size
			|| self.truncated.len() != self.size
		{
			return Err(Error::invalid_argument(
				"replay snapshot payload lengths do not match schema and size",
			));
		}
		Ok(())
	}
}

fn replay_fnv64(bytes: &[u8]) -> u64 {
	bytes.iter().fold(REPLAY_FNV_OFFSET, |hash, byte| {
		(hash ^ u64::from(*byte)).wrapping_mul(REPLAY_FNV_PRIME)
	})
}

fn take_slice<'a>(bytes: &'a [u8], pos: &mut usize, len: usize) -> Result<&'a [u8]> {
	let end = pos
		.checked_add(len)
		.ok_or_else(|| Error::checkpoint_corrupt("replay snapshot offset overflow"))?;
	if end > bytes.len() {
		return Err(Error::checkpoint_corrupt("replay snapshot is truncated"));
	}
	let slice = &bytes[*pos..end];
	*pos = end;
	Ok(slice)
}

fn take_u32(bytes: &[u8], pos: &mut usize) -> Result<u32> {
	let slice = take_slice(bytes, pos, 4)?;
	Ok(u32::from_le_bytes([slice[0], slice[1], slice[2], slice[3]]))
}

fn take_u64(bytes: &[u8], pos: &mut usize) -> Result<u64> {
	let slice = take_slice(bytes, pos, 8)?;
	Ok(u64::from_le_bytes([
		slice[0], slice[1], slice[2], slice[3], slice[4], slice[5], slice[6], slice[7],
	]))
}

fn decode_f32_slice(bytes: &[u8]) -> Vec<f32> {
	bytes
		.as_chunks::<4>()
		.0
		.iter()
		.copied()
		.map(f32::from_le_bytes)
		.collect()
}

// ---------------------------------------------------------------------------
// Private dispatch helpers
// ---------------------------------------------------------------------------

fn append_dispatch(
	transition: &ReplayTransition,
	storage: &ReplayBatch,
	config: &ReplayConfig,
	cursor: usize,
	observation_elements: u32,
	action_elements: u32,
) -> Result<usize> {
	const OPERATION: &str = "oa::ml::replay::append_batch";
	if transition.reward().dtype() != DType::F32 || transition.reward().shape().len() != 1 {
		return Err(Error::invalid_argument(format!(
			"{OPERATION} requires F32 reward [batch]"
		)));
	}
	let batch = transition.reward().shape()[0];
	if batch == 0 || batch > config.capacity {
		return Err(Error::invalid_argument(format!(
			"{OPERATION} batch must be in 1..=capacity"
		)));
	}
	let observation_shape = prefixed_shape(batch, &config.observation_shape);
	let action_shape = prefixed_shape(batch, &config.action_shape);
	let vector_shape = [batch];
	let fields = [
		(
			transition.observation(),
			DType::F32,
			observation_shape.as_slice(),
		),
		(
			transition.action(),
			config.action_dtype,
			action_shape.as_slice(),
		),
		(
			transition.next_observation(),
			DType::F32,
			observation_shape.as_slice(),
		),
		(transition.reward(), DType::F32, vector_shape.as_slice()),
		(transition.terminated(), DType::U8, vector_shape.as_slice()),
		(transition.truncated(), DType::U8, vector_shape.as_slice()),
	];
	for (matrix, dtype, shape) in &fields {
		if matrix.dtype() != *dtype || matrix.shape() != *shape {
			return Err(Error::invalid_argument(format!(
				"{OPERATION} transition does not match the configured replay schema"
			)));
		}
		if !transition.observation().runtime().same_as(matrix.runtime()) {
			return Err(Error::invalid_argument(format!(
				"{OPERATION} transition fields must belong to one runtime"
			)));
		}
	}
	let destinations = storage_fields(storage);
	for destination in destinations {
		if !transition
			.observation()
			.runtime()
			.same_as(destination.runtime())
		{
			return Err(Error::invalid_argument(format!(
				"{OPERATION} transition and replay buffer must belong to one runtime"
			)));
		}
		if fields
			.iter()
			.any(|(source, _, _)| source.storage().same_as(destination.storage()))
		{
			return Err(Error::invalid_argument(format!(
				"{OPERATION} transition fields must not alias replay storage"
			)));
		}
	}
	let cursor = shader_u32(cursor, "cursor", OPERATION)?;
	let capacity = shader_u32(config.capacity, "capacity", OPERATION)?;
	let batch_u32 = shader_u32(batch, "batch", OPERATION)?;
	let observation_count = batch_u32.checked_mul(observation_elements).ok_or_else(|| {
		Error::resource_exhausted(format!("{OPERATION} observation count exceeds u32"))
	})?;
	let action_count = batch_u32
		.checked_mul(action_elements)
		.ok_or_else(|| Error::resource_exhausted(format!("{OPERATION} action count exceeds u32")))?;
	let inputs = [
		transition.observation(),
		transition.action(),
		transition.next_observation(),
		transition.reward(),
		transition.terminated(),
		transition.truncated(),
		storage.observation(),
		storage.action(),
		storage.next_observation(),
		storage.reward(),
		storage.terminated(),
		storage.truncated(),
	];
	let outputs = storage_fields(storage);
	let buffers = [
		BufferBinding::read(transition.observation().storage()),
		BufferBinding::read(transition.action().storage()),
		BufferBinding::read(transition.next_observation().storage()),
		BufferBinding::read(transition.reward().storage()),
		BufferBinding::read(transition.terminated().storage()),
		BufferBinding::read(transition.truncated().storage()),
		BufferBinding::write(storage.observation().storage()),
		BufferBinding::write(storage.action().storage()),
		BufferBinding::write(storage.next_observation().storage()),
		BufferBinding::write(storage.reward().storage()),
		BufferBinding::write(storage.terminated().storage()),
		BufferBinding::write(storage.truncated().storage()),
	];
	let push_constants = [
		PushConstant::U32(cursor),
		PushConstant::U32(capacity),
		PushConstant::U32(batch_u32),
		PushConstant::U32(observation_elements),
		PushConstant::U32(action_elements),
	];
	let attributes = unsigned_attributes(&[
		("cursor", cursor),
		("capacity", capacity),
		("batch", batch_u32),
		("observation_elements", observation_elements),
		("action_elements", action_elements),
	]);
	let kernel = KernelId::MlReplayAppendBatchF32;
	{
		let inputs: &[&Matrix] = &inputs;
		let outputs: &[&Matrix] = &outputs;
		let attributes: &[OpAttribute] = &attributes;
		let dispatch = ComputeDispatch {
			kernel,
			buffers: &buffers,
			push_constants: &push_constants,
			workgroups: kernel.linear_workgroups(observation_count.max(action_count).max(batch_u32)),
			indirect: None,
		};
		let contract = dispatch.kernel.semantic_contract().ok_or_else(|| {
			Error::internal(format!(
				"lowering-only kernel {} cannot own one semantic ML operation",
				dispatch.kernel.report_name()
			))
		})?;
		let runtime = inputs
			.first()
			.ok_or_else(|| Error::internal("semantic ML dispatch requires an input"))?
			.runtime();
		runtime.record_semantic(
			dispatch,
			SemanticDispatch {
				contract,
				inputs,
				outputs,
				attributes,
			},
		)
	}?;
	Ok(batch)
}

#[allow(
	clippy::too_many_arguments,
	reason = "replay sampling keeps capacity, sample geometry, seed, and field widths explicit"
)]
fn sample_dispatch(
	storage: &ReplayBatch,
	config: &ReplayConfig,
	size: usize,
	batch: usize,
	seed: u64,
	observation_elements: u32,
	action_elements: u32,
) -> Result<ReplayBatch> {
	const OPERATION: &str = "oa::ml::replay::sample";
	let size = shader_u32(size, "size", OPERATION)?;
	let batch_u32 = shader_u32(batch, "batch", OPERATION)?;
	let observation_count = batch
		.checked_mul(observation_elements as usize)
		.ok_or_else(|| Error::resource_exhausted("replay sample observation size overflows usize"))?;
	let action_count = batch
		.checked_mul(action_elements as usize)
		.ok_or_else(|| Error::resource_exhausted("replay sample action size overflows usize"))?;
	let observation_count_u32 = shader_u32(observation_count, "observation count", OPERATION)?;
	let action_count_u32 = shader_u32(action_count, "action count", OPERATION)?;
	let mut observation_shape = vec![batch];
	observation_shape.extend_from_slice(&config.observation_shape);
	let mut action_shape = vec![batch];
	action_shape.extend_from_slice(&config.action_shape);
	let runtime = storage.observation().runtime();
	let result = ReplayBatch {
		observation: Matrix::allocate(
			runtime,
			observation_shape.clone(),
			observation_count,
			DType::F32,
		)?,
		action: Matrix::allocate(runtime, action_shape, action_count, config.action_dtype)?,
		next_observation: Matrix::allocate(runtime, observation_shape, observation_count, DType::F32)?,
		reward: Matrix::allocate(runtime, vec![batch], batch, DType::F32)?,
		terminated: Matrix::allocate(runtime, vec![batch], batch, DType::U8)?,
		truncated: Matrix::allocate(runtime, vec![batch], batch, DType::U8)?,
		index: Matrix::allocate(runtime, vec![batch], batch, DType::U32)?,
	};
	let inputs = storage_fields(storage);
	let outputs = [
		result.observation(),
		result.action(),
		result.next_observation(),
		result.reward(),
		result.terminated(),
		result.truncated(),
		result.index(),
	];
	let buffers = [
		BufferBinding::read(storage.observation().storage()),
		BufferBinding::read(storage.action().storage()),
		BufferBinding::read(storage.next_observation().storage()),
		BufferBinding::read(storage.reward().storage()),
		BufferBinding::read(storage.terminated().storage()),
		BufferBinding::read(storage.truncated().storage()),
		BufferBinding::write(result.observation().storage()),
		BufferBinding::write(result.action().storage()),
		BufferBinding::write(result.next_observation().storage()),
		BufferBinding::write(result.reward().storage()),
		BufferBinding::write(result.terminated().storage()),
		BufferBinding::write(result.truncated().storage()),
		BufferBinding::write(result.index().storage()),
	];
	let push_constants = [
		PushConstant::U32(size),
		PushConstant::U32(batch_u32),
		PushConstant::U32(observation_elements),
		PushConstant::U32(action_elements),
		PushConstant::U32(seed as u32),
		PushConstant::U32((seed >> 32) as u32),
	];
	let attributes = [
		OpAttribute::UnsignedInteger {
			name: "size".into(),
			value: u64::from(size),
		},
		OpAttribute::UnsignedInteger {
			name: "batch".into(),
			value: u64::from(batch_u32),
		},
		OpAttribute::UnsignedInteger {
			name: "observation_elements".into(),
			value: u64::from(observation_elements),
		},
		OpAttribute::UnsignedInteger {
			name: "action_elements".into(),
			value: u64::from(action_elements),
		},
		OpAttribute::UnsignedInteger {
			name: "seed".into(),
			value: seed,
		},
	];
	let kernel = KernelId::MlReplaySampleF32;
	{
		let inputs: &[&Matrix] = &inputs;
		let outputs: &[&Matrix] = &outputs;
		let attributes: &[OpAttribute] = &attributes;
		let dispatch = ComputeDispatch {
			kernel,
			buffers: &buffers,
			push_constants: &push_constants,
			workgroups: kernel
				.linear_workgroups(observation_count_u32.max(action_count_u32).max(batch_u32)),
			indirect: None,
		};
		let contract = dispatch.kernel.semantic_contract().ok_or_else(|| {
			Error::internal(format!(
				"lowering-only kernel {} cannot own one semantic ML operation",
				dispatch.kernel.report_name()
			))
		})?;
		let runtime = inputs
			.first()
			.ok_or_else(|| Error::internal("semantic ML dispatch requires an input"))?
			.runtime();
		runtime.record_semantic(
			dispatch,
			SemanticDispatch {
				contract,
				inputs,
				outputs,
				attributes,
			},
		)
	}?;
	Ok(result)
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

fn storage_fields(batch: &ReplayBatch) -> [&Matrix; 6] {
	[
		batch.observation(),
		batch.action(),
		batch.next_observation(),
		batch.reward(),
		batch.terminated(),
		batch.truncated(),
	]
}

fn prefixed_shape(first: usize, suffix: &[usize]) -> Vec<usize> {
	let mut shape = Vec::with_capacity(suffix.len() + 1);
	shape.push(first);
	shape.extend_from_slice(suffix);
	shape
}

fn unsigned_attributes(values: &[(&'static str, u32)]) -> Vec<OpAttribute> {
	values
		.iter()
		.map(|(name, value)| OpAttribute::UnsignedInteger {
			name: (*name).into(),
			value: u64::from(*value),
		})
		.collect()
}

fn field_elements(shape: &[usize], allow_scalar: bool) -> Result<usize> {
	if (!allow_scalar && shape.is_empty()) || shape.len() > 7 || shape.contains(&0) {
		return Err(Error::invalid_argument(
			"replay fields require positive rank-1..=7 observations and rank-0..=7 actions",
		));
	}
	shape.iter().try_fold(1_usize, |count, extent| {
		count
			.checked_mul(*extent)
			.ok_or_else(|| Error::resource_exhausted("replay field size overflows usize"))
	})
}