reifydb-core 0.10.2

Core database interfaces and data structures for ReifyDB
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
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2026 ReifyDB

use std::{collections::BTreeMap, ops::Bound};

use indexmap::{IndexMap, IndexSet};
use reifydb_codec::row::{bytes::EncodedBytes, ringbuffer::EncodedRingBufferRow};
use reifydb_value::{
	Result, reifydb_assertions,
	value::{datetime::DateTime, partition::Partition, row_number::RowNumber},
};

use crate::{interface::catalog::ringbuffer::RingBufferMetadata, return_internal_error};

const ORDER_PAGE: usize = 64;

pub const FREE_PAGE_SLOTS: u64 = 512;

pub trait RingRead {
	fn metadata(&mut self, partitions: &[Option<Partition>]) -> Result<Vec<Option<RingBufferMetadata>>>;

	fn slots(&mut self, rows: &[(Option<Partition>, RowNumber)]) -> Result<Vec<Option<EncodedBytes>>>;

	fn order_at(&mut self, entries: &[(Option<Partition>, u64)]) -> Result<Vec<Option<RowNumber>>>;

	fn order(
		&mut self,
		partition: Option<Partition>,
		after: Option<u64>,
		limit: usize,
	) -> Result<Vec<(u64, RowNumber)>>;
}

pub trait RingStore: RingRead {
	fn reserve(&mut self, capacity: u64) -> Result<u64>;

	fn free_pages(&mut self, partition: Option<Partition>, pages: &[u64]) -> Result<Vec<Vec<RowNumber>>>;
}

pub trait RingNewest: RingRead {
	fn newest_order(&mut self, partition: Option<Partition>) -> Result<Option<(u64, RowNumber)>>;
}

#[derive(Debug, Clone, PartialEq)]
pub struct Placement {
	pub row: RowNumber,
	pub sequence: u64,
	pub evicted: Option<EncodedBytes>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MetadataWrite {
	Save(Option<Partition>, RingBufferMetadata),
	Remove(Option<Partition>),
	Order(Option<Partition>, u64, Option<RowNumber>),
	Free(Option<Partition>, u64, Option<Vec<RowNumber>>),
}

#[derive(Default)]
struct FreePage {
	stored: Vec<RowNumber>,
	slots: Vec<RowNumber>,
}

struct Tracked {
	loaded: Option<RingBufferMetadata>,
	current: Option<RingBufferMetadata>,
	order: BTreeMap<u64, Option<RowNumber>>,
	free_len: u64,
	free_pages: BTreeMap<u64, FreePage>,
}

pub struct Ring {
	capacity: u64,
	tracked: IndexMap<Option<Partition>, Tracked>,
}

impl Ring {
	pub fn new(capacity: u64) -> Self {
		assert!(capacity > 0, "a ring buffer must hold at least one row");
		Self {
			capacity,
			tracked: IndexMap::new(),
		}
	}

	pub fn preload(&mut self, store: &mut impl RingStore, partitions: &[Option<Partition>]) -> Result<()> {
		let missing: Vec<Option<Partition>> = partitions
			.iter()
			.copied()
			.filter(|partition| !self.tracked.contains_key(partition))
			.collect::<IndexSet<_>>()
			.into_iter()
			.collect();
		if missing.is_empty() {
			return Ok(());
		}
		let loaded = store.metadata(&missing)?;
		for (partition, loaded) in missing.into_iter().zip(loaded) {
			self.tracked.insert(
				partition,
				Tracked {
					loaded,
					current: loaded,
					order: BTreeMap::new(),
					free_len: loaded.map_or(0, |metadata| metadata.filled - metadata.count),
					free_pages: BTreeMap::new(),
				},
			);
		}
		Ok(())
	}

	pub fn metadata(
		&mut self,
		store: &mut impl RingStore,
		partition: Option<Partition>,
	) -> Result<Option<RingBufferMetadata>> {
		self.preload(store, &[partition])?;
		Ok(self.tracked(partition).current)
	}

	fn tracked(&mut self, partition: Option<Partition>) -> &mut Tracked {
		self.tracked.get_mut(&partition).expect("metadata is loaded before it is changed")
	}

	fn set(&mut self, partition: Option<Partition>, metadata: RingBufferMetadata) {
		self.tracked(partition).current = Some(metadata);
	}

	fn load_free_pages(
		&mut self,
		store: &mut impl RingStore,
		partition: Option<Partition>,
		first: u64,
		last: u64,
	) -> Result<()> {
		let tracked = self.tracked(partition);
		let missing: Vec<u64> = (first..=last).filter(|page| !tracked.free_pages.contains_key(page)).collect();
		if missing.is_empty() {
			return Ok(());
		}
		let loaded = store.free_pages(partition, &missing)?;
		let tracked = self.tracked(partition);
		for (page, slots) in missing.into_iter().zip(loaded) {
			reifydb_assertions! {
				assert_eq!(
					slots.len() as u64,
					(tracked.free_len - page * FREE_PAGE_SLOTS).min(FREE_PAGE_SLOTS),
					"a ring's free page must hold exactly the free slots its index range reaches"
				);
			}
			tracked.free_pages.insert(
				page,
				FreePage {
					stored: slots.clone(),
					slots,
				},
			);
		}
		Ok(())
	}

	fn load_top_free_page(&mut self, store: &mut impl RingStore, partition: Option<Partition>) -> Result<()> {
		let free_len = self.tracked(partition).free_len;
		if !free_len.is_multiple_of(FREE_PAGE_SLOTS) {
			let top = free_len / FREE_PAGE_SLOTS;
			self.load_free_pages(store, partition, top, top)?;
		}
		Ok(())
	}

	fn release(&mut self, partition: Option<Partition>, sequence: u64, row: RowNumber) {
		let tracked = self.tracked(partition);
		tracked.order.insert(sequence, None);
		let page = tracked.free_len / FREE_PAGE_SLOTS;
		tracked.free_pages.entry(page).or_default().slots.push(row);
		tracked.free_len += 1;
	}

	#[cfg_attr(not(reifydb_assertions), allow(unused_variables))]
	fn assert_free_len(&mut self, partition: Option<Partition>, metadata: RingBufferMetadata) {
		reifydb_assertions! {
			assert_eq!(
				self.tracked(partition).free_len,
				metadata.filled - metadata.count,
				"a ring's free stack must hold exactly the filled slots no row occupies"
			);
		}
	}

	fn live(
		&mut self,
		store: &mut impl RingStore,
		partition: Option<Partition>,
		after: Option<u64>,
		limit: usize,
	) -> Result<Vec<(u64, RowNumber)>> {
		let mut live = Vec::with_capacity(limit);
		if limit == 0 {
			return Ok(live);
		}
		let page = limit.max(ORDER_PAGE);
		let head = self.tracked(partition).current.map_or(0, |metadata| metadata.head);
		let mut cursor = after.or_else(|| head.checked_sub(1));
		loop {
			let stored = store.order(partition, cursor, page)?;
			let exhausted = stored.len() < page;
			let staged = &self.tracked(partition).order;
			for (sequence, row) in stored {
				cursor = Some(sequence);
				if matches!(staged.get(&sequence), Some(None)) {
					continue;
				}
				live.push((sequence, row));
				if live.len() == limit {
					return Ok(live);
				}
			}
			if exhausted {
				break;
			}
		}
		let lower = after.map_or(Bound::Unbounded, Bound::Excluded);
		for (&sequence, entry) in self.tracked(partition).order.range((lower, Bound::Unbounded)) {
			if let Some(row) = entry {
				live.push((sequence, *row));
				if live.len() == limit {
					break;
				}
			}
		}
		Ok(live)
	}

	pub fn place(
		&mut self,
		store: &mut impl RingStore,
		requests: &[(Option<Partition>, usize)],
	) -> Result<Vec<Vec<Placement>>> {
		let partitions: Vec<Option<Partition>> = requests.iter().map(|&(partition, _)| partition).collect();
		assert!(
			distinct(&partitions),
			"one placement call must name each partition once, or a later request would read an evicted slot the earlier one already took"
		);
		self.preload(store, &partitions)?;
		let mut staged = Vec::with_capacity(requests.len());
		let mut evicted_rows: Vec<(Option<Partition>, RowNumber)> = Vec::new();
		for &(partition, count) in requests {
			let placed = self.stage(store, partition, count)?;
			evicted_rows.extend(placed
				.iter()
				.filter(|(_, _, evicts)| *evicts)
				.map(|&(row, _, _)| (partition, row)));
			staged.push((partition, placed));
		}
		let mut evicted = store.slots(&evicted_rows)?.into_iter();
		let mut placements = Vec::with_capacity(staged.len());
		for (partition, placed) in staged {
			let mut partition_placements = Vec::with_capacity(placed.len());
			for (row, sequence, evicts) in placed {
				let evicted = match evicts {
					false => None,
					true => match evicted.next().flatten() {
						Some(bytes) => Some(bytes),
						None => return_internal_error!(
							"Ring buffer partition {:?} order index names slot {:?} as live but the slot is empty. This indicates a corrupt ring index.",
							partition,
							row
						),
					},
				};
				partition_placements.push(Placement {
					row,
					sequence,
					evicted,
				});
			}
			placements.push(partition_placements);
		}
		Ok(placements)
	}

	fn stage(
		&mut self,
		store: &mut impl RingStore,
		partition: Option<Partition>,
		count: usize,
	) -> Result<Vec<(RowNumber, u64, bool)>> {
		assert!(
			count as u64 <= self.capacity,
			"one placement call must not lap the ring, or two rows of the call would share a slot"
		);
		if count == 0 {
			return Ok(Vec::new());
		}
		let mut metadata = match self.metadata(store, partition)? {
			Some(metadata) => metadata,
			None if partition.is_none() => RingBufferMetadata::unpartitioned(),
			None => RingBufferMetadata::reserved(store.reserve(self.capacity)?),
		};
		let free = self.tracked(partition).free_len;
		let pops = free.min(count as u64);
		if pops > 0 {
			self.load_free_pages(
				store,
				partition,
				(free - pops) / FREE_PAGE_SLOTS,
				(free - 1) / FREE_PAGE_SLOTS,
			)?;
		}
		let room = free + (self.capacity - metadata.filled);
		let evictions = (count as u64).saturating_sub(room) as usize;
		let victims = self.live(store, partition, None, evictions)?;
		if victims.len() != evictions {
			return_internal_error!(
				"Ring buffer partition {:?} must evict {} rows but its order index names only {}. This indicates a corrupt ring index.",
				partition,
				evictions,
				victims.len()
			)
		}
		if let Some(&(newest_victim, _)) = victims.last() {
			metadata.head = newest_victim + 1;
		}
		let capacity = self.capacity;
		let tracked = self.tracked(partition);
		let mut victims = victims.into_iter();
		let mut placed: Vec<(RowNumber, u64, bool)> = Vec::with_capacity(count);
		for _ in 0..count {
			let sequence = metadata.next_sequence;
			metadata.next_sequence += 1;
			let (row, evicts) = if tracked.free_len > 0 {
				let page = (tracked.free_len - 1) / FREE_PAGE_SLOTS;
				let popped = tracked.free_pages.get_mut(&page).and_then(|page| page.slots.pop());
				let Some(row) = popped else {
					return_internal_error!(
						"Ring buffer partition {:?} free page {} is shorter than its free count {}. This indicates a corrupt ring index.",
						partition,
						page,
						tracked.free_len
					)
				};
				tracked.free_len -= 1;
				(row, false)
			} else if metadata.filled < capacity {
				let row = RowNumber(metadata.base_rn + metadata.filled);
				metadata.filled += 1;
				(row, false)
			} else {
				let (oldest, row) = victims.next().expect("victims cover every eviction");
				tracked.order.insert(oldest, None);
				(row, true)
			};
			tracked.order.insert(sequence, Some(row));
			if !evicts {
				metadata.count += 1;
			}
			placed.push((row, sequence, evicts));
		}
		self.assert_free_len(partition, metadata);
		self.set(partition, metadata);
		Ok(placed)
	}

	pub fn remove(
		&mut self,
		store: &mut impl RingStore,
		requests: &[(Option<Partition>, Vec<RowNumber>)],
	) -> Result<Vec<Vec<Option<EncodedBytes>>>> {
		let partitions: Vec<Option<Partition>> = requests.iter().map(|(partition, _)| *partition).collect();
		assert!(
			distinct(&partitions),
			"one removal call must name each partition once, or a row would be read and released twice"
		);
		self.preload(store, &partitions)?;
		let capacity = self.capacity;
		let mut held: Vec<(Option<Partition>, RowNumber)> = Vec::new();
		for (partition, rows) in requests {
			if let Some(metadata) = self.tracked(*partition).current {
				held.extend(rows
					.iter()
					.copied()
					.filter(|&row| metadata.holds(row, capacity))
					.map(|row| (*partition, row)));
			}
		}
		let mut stored = store.slots(&held)?.into_iter();
		let mut removals = Vec::with_capacity(requests.len());
		for (partition, rows) in requests {
			let partition = *partition;
			let Some(mut metadata) = self.tracked(partition).current else {
				removals.push(vec![None; rows.len()]);
				continue;
			};
			let removed: Vec<Option<EncodedBytes>> = rows
				.iter()
				.map(|&row| match metadata.holds(row, capacity) {
					true => stored.next().flatten(),
					false => None,
				})
				.collect();
			if removed.iter().any(Option::is_some) {
				self.load_top_free_page(store, partition)?;
			}
			for (&row, bytes) in rows.iter().zip(&removed) {
				if let Some(bytes) = bytes {
					self.release(partition, EncodedRingBufferRow::view(bytes).sequence(), row);
					metadata.count -= 1;
				}
			}
			self.assert_free_len(partition, metadata);
			self.set(partition, metadata);
			removals.push(removed);
		}
		Ok(removals)
	}

	pub fn expire(
		&mut self,
		store: &mut impl RingStore,
		partition: Option<Partition>,
		cutoff: DateTime,
		batch: usize,
	) -> Result<Vec<(RowNumber, EncodedBytes)>> {
		let Some(mut metadata) = self.metadata(store, partition)?.filter(|metadata| !metadata.is_empty())
		else {
			return Ok(Vec::new());
		};
		let mut expired: Vec<(u64, RowNumber, EncodedBytes)> = Vec::new();
		let mut after = None;
		'walk: loop {
			let window = self.live(store, partition, after, batch.max(1))?;
			let Some(&(last, _)) = window.last() else {
				break;
			};
			after = Some(last);
			let rows: Vec<(Option<Partition>, RowNumber)> =
				window.iter().map(|&(_, row)| (partition, row)).collect();
			for ((sequence, row), stored) in window.into_iter().zip(store.slots(&rows)?) {
				let Some(bytes) = stored else {
					return_internal_error!(
						"Ring buffer partition {:?} order index names slot {:?} as live but the slot is empty. This indicates a corrupt ring index.",
						partition,
						row
					)
				};
				if !EncodedRingBufferRow::view(&bytes).time().is_some_and(|time| time < cutoff) {
					break 'walk;
				}
				expired.push((sequence, row, bytes));
			}
		}
		if !expired.is_empty() {
			self.load_top_free_page(store, partition)?;
		}
		for &(sequence, row, _) in &expired {
			self.release(partition, sequence, row);
		}
		if let Some(&(newest_expired, _, _)) = expired.last() {
			metadata.head = newest_expired + 1;
		}
		metadata.count -= expired.len() as u64;
		self.assert_free_len(partition, metadata);
		self.set(partition, metadata);
		Ok(expired.into_iter().map(|(_, row, bytes)| (row, bytes)).collect())
	}

	pub fn writes(&self) -> Vec<MetadataWrite> {
		let mut writes = Vec::new();
		for (&partition, tracked) in &self.tracked {
			let Some(current) = tracked.current.filter(|current| tracked.loaded != Some(*current)) else {
				continue;
			};
			let dropped = partition.is_some() && current.is_empty();
			match (dropped, tracked.loaded) {
				(true, None) => {}
				(true, Some(_)) => writes.push(MetadataWrite::Remove(partition)),
				(false, _) => writes.push(MetadataWrite::Save(partition, current)),
			}
			for (&sequence, &entry) in &tracked.order {
				writes.push(MetadataWrite::Order(partition, sequence, entry));
			}
			if dropped {
				let stored = tracked.loaded.map_or(0, |metadata| metadata.filled - metadata.count);
				for page in 0..stored.div_ceil(FREE_PAGE_SLOTS) {
					writes.push(MetadataWrite::Free(partition, page, None));
				}
				continue;
			}
			for (&page, free) in &tracked.free_pages {
				if free.slots != free.stored {
					reifydb_assertions! {
						assert!(
							free.slots.len() as u64 <= FREE_PAGE_SLOTS,
							"a ring's free page must never hold more than its slot limit"
						);
					}
					let slots = (!free.slots.is_empty()).then(|| free.slots.clone());
					writes.push(MetadataWrite::Free(partition, page, slots));
				}
			}
		}
		writes
	}
}

pub fn newest(
	store: &mut impl RingNewest,
	partitions: &[Option<Partition>],
) -> Result<Vec<Option<(RowNumber, EncodedBytes)>>> {
	let metadata = store.metadata(partitions)?;
	let guesses: Vec<(usize, Option<Partition>, u64)> = partitions
		.iter()
		.zip(metadata)
		.enumerate()
		.filter_map(|(index, (&partition, metadata))| {
			metadata.filter(|metadata| metadata.count > 0 && metadata.next_sequence > 0)
				.map(|metadata| (index, partition, metadata.next_sequence - 1))
		})
		.collect();
	let entries: Vec<(Option<Partition>, u64)> =
		guesses.iter().map(|&(_, partition, sequence)| (partition, sequence)).collect();
	let guessed = store.order_at(&entries)?;
	let mut rows: Vec<Option<RowNumber>> = vec![None; partitions.len()];
	for ((index, partition, _), row) in guesses.into_iter().zip(guessed) {
		rows[index] = match row {
			Some(row) => Some(row),
			None => store.newest_order(partition)?.map(|(_, row)| row),
		};
	}
	live_slots(store, partitions, &rows)
}

pub fn oldest(
	store: &mut impl RingRead,
	partitions: &[Option<Partition>],
) -> Result<Vec<Option<(RowNumber, EncodedBytes)>>> {
	let metadata = store.metadata(partitions)?;
	let mut rows = Vec::with_capacity(partitions.len());
	for (&partition, metadata) in partitions.iter().zip(metadata) {
		let after = metadata.and_then(|metadata| metadata.head.checked_sub(1));
		rows.push(store.order(partition, after, 1)?.pop().map(|(_, row)| row));
	}
	live_slots(store, partitions, &rows)
}

pub fn oldest_first(store: &mut impl RingRead, partition: Option<Partition>) -> Result<Vec<RowNumber>> {
	let mut rows = Vec::new();
	let mut after = head_cursor(store, partition)?;
	loop {
		let page = store.order(partition, after, ORDER_PAGE)?;
		let exhausted = page.len() < ORDER_PAGE;
		after = page.last().map(|&(sequence, _)| sequence).or(after);
		rows.extend(page.into_iter().map(|(_, row)| row));
		if exhausted {
			return Ok(rows);
		}
	}
}

fn distinct(partitions: &[Option<Partition>]) -> bool {
	partitions.iter().collect::<IndexSet<_>>().len() == partitions.len()
}

fn head_cursor(store: &mut impl RingRead, partition: Option<Partition>) -> Result<Option<u64>> {
	Ok(store.metadata(&[partition])?.pop().flatten().and_then(|metadata| metadata.head.checked_sub(1)))
}

fn live_slots(
	store: &mut impl RingRead,
	partitions: &[Option<Partition>],
	rows: &[Option<RowNumber>],
) -> Result<Vec<Option<(RowNumber, EncodedBytes)>>> {
	let wanted: Vec<(Option<Partition>, RowNumber)> =
		partitions.iter().zip(rows).filter_map(|(&partition, row)| row.map(|row| (partition, row))).collect();
	let mut stored = store.slots(&wanted)?.into_iter();
	let mut live = Vec::with_capacity(rows.len());
	for (&partition, row) in partitions.iter().zip(rows) {
		let Some(row) = *row else {
			live.push(None);
			continue;
		};
		match stored.next().flatten() {
			Some(bytes) => live.push(Some((row, bytes))),
			None => return_internal_error!(
				"Ring buffer partition {:?} order index names slot {:?} as live but the slot is empty. This indicates a corrupt ring index.",
				partition,
				row
			),
		}
	}
	Ok(live)
}

#[cfg(test)]
mod tests {
	use std::{
		collections::HashMap,
		panic::{AssertUnwindSafe, catch_unwind},
	};

	use reifydb_codec::row::shape::{RowFamily, RowShape};
	use reifydb_value::value::value_type::ValueType;

	use super::*;

	#[derive(Default)]
	struct MemoryStore {
		metadata: HashMap<Option<Partition>, RingBufferMetadata>,
		rows: HashMap<(Option<Partition>, RowNumber), EncodedBytes>,
		order: BTreeMap<(Option<Partition>, u64), RowNumber>,
		free: HashMap<(Option<Partition>, u64), Vec<RowNumber>>,
		next_base: u64,
		reads: Vec<(Option<Partition>, RowNumber)>,
		free_reads: usize,
		pages_read: Vec<(Option<Partition>, u64)>,
		metadata_calls: usize,
		slot_calls: usize,
		order_at_calls: usize,
		newest_order_calls: usize,
	}

	impl RingRead for MemoryStore {
		fn metadata(&mut self, partitions: &[Option<Partition>]) -> Result<Vec<Option<RingBufferMetadata>>> {
			self.metadata_calls += 1;
			Ok(partitions.iter().map(|partition| self.metadata.get(partition).copied()).collect())
		}

		fn slots(&mut self, rows: &[(Option<Partition>, RowNumber)]) -> Result<Vec<Option<EncodedBytes>>> {
			self.slot_calls += 1;
			self.reads.extend_from_slice(rows);
			Ok(rows.iter().map(|key| self.rows.get(key).cloned()).collect())
		}

		fn order_at(&mut self, entries: &[(Option<Partition>, u64)]) -> Result<Vec<Option<RowNumber>>> {
			self.order_at_calls += 1;
			Ok(entries.iter().map(|key| self.order.get(key).copied()).collect())
		}

		fn order(
			&mut self,
			partition: Option<Partition>,
			after: Option<u64>,
			limit: usize,
		) -> Result<Vec<(u64, RowNumber)>> {
			Ok(self.entries(partition)
				.filter(|&(sequence, _)| after.is_none_or(|after| sequence > after))
				.take(limit)
				.collect())
		}
	}

	impl RingStore for MemoryStore {
		fn reserve(&mut self, capacity: u64) -> Result<u64> {
			let base = self.next_base.max(100);
			self.next_base = base + capacity;
			Ok(base)
		}

		fn free_pages(&mut self, partition: Option<Partition>, pages: &[u64]) -> Result<Vec<Vec<RowNumber>>> {
			self.free_reads += 1;
			self.pages_read.extend(pages.iter().map(|&page| (partition, page)));
			Ok(pages.iter()
				.map(|&page| self.free.get(&(partition, page)).cloned().unwrap_or_default())
				.collect())
		}
	}

	impl RingNewest for MemoryStore {
		fn newest_order(&mut self, partition: Option<Partition>) -> Result<Option<(u64, RowNumber)>> {
			self.newest_order_calls += 1;
			Ok(self.entries(partition).last())
		}
	}

	impl MemoryStore {
		fn entries(
			&self,
			partition: Option<Partition>,
		) -> impl DoubleEndedIterator<Item = (u64, RowNumber)> + '_ {
			self.order
				.iter()
				.filter(move |((owner, _), _)| *owner == partition)
				.map(|(&(_, sequence), &row)| (sequence, row))
		}
	}

	fn row(sequence: u64, time: Option<i64>) -> EncodedBytes {
		let shape = RowShape::testing(RowFamily::RingBuffer, &[ValueType::Int4]);
		let mut builder = shape.allocate_ringbuffer();
		builder.set_sequence(sequence);
		if let Some(time) = time {
			builder.set_time(DateTime::from_millis(time));
		}
		builder.freeze().into_bytes()
	}

	fn sequence_of(bytes: &EncodedBytes) -> u64 {
		EncodedRingBufferRow::view(bytes).sequence()
	}

	fn insert(
		store: &mut MemoryStore,
		capacity: u64,
		partition: Option<Partition>,
		times: &[i64],
	) -> Vec<Placement> {
		let mut ring = Ring::new(capacity);
		let placed = ring.place(store, &[(partition, times.len())]).unwrap().remove(0);
		for (placement, &time) in placed.iter().zip(times) {
			store.rows.insert((partition, placement.row), row(placement.sequence, Some(time)));
		}
		apply(store, &ring);
		placed
	}

	fn apply(store: &mut MemoryStore, ring: &Ring) {
		for write in ring.writes() {
			match write {
				MetadataWrite::Save(partition, metadata) => {
					store.metadata.insert(partition, metadata);
				}
				MetadataWrite::Remove(partition) => {
					store.metadata.remove(&partition);
				}
				MetadataWrite::Order(partition, sequence, Some(row)) => {
					store.order.insert((partition, sequence), row);
				}
				MetadataWrite::Order(partition, sequence, None) => {
					store.order.remove(&(partition, sequence));
				}
				MetadataWrite::Free(partition, page, None) => {
					store.free.remove(&(partition, page));
				}
				MetadataWrite::Free(partition, page, Some(slots)) => {
					store.free.insert((partition, page), slots);
				}
			}
		}
	}

	fn delete(store: &mut MemoryStore, capacity: u64, partition: Option<Partition>, rows: &[RowNumber]) {
		let mut ring = Ring::new(capacity);
		ring.remove(store, &[(partition, rows.to_vec())]).unwrap();
		for row in rows {
			store.rows.remove(&(partition, *row));
		}
		apply(store, &ring);
	}

	#[test]
	fn an_insert_into_a_full_partition_overwrites_the_oldest_slot_in_place() {
		// Mutation: appending a fresh row number gives downstream Remove + Insert instead of one Update.
		let mut store = MemoryStore::default();
		let first = insert(&mut store, 1, Some(Partition(1)), &[10]);
		let second = insert(&mut store, 1, Some(Partition(1)), &[20]);
		assert_eq!(second.len(), 1);
		assert_eq!(second[0].row, first[0].row, "the slot keeps its row number");
		assert_eq!(second[0].sequence, first[0].sequence + 1, "#sequence advances by one per write");
		let evicted = second[0].evicted.as_ref().expect("an overwrite names the evicted row as its pre");
		assert_eq!(sequence_of(evicted), first[0].sequence);
		assert_eq!(store.metadata[&Some(Partition(1))].count, 1, "an overwrite keeps the live count");
	}

	#[test]
	fn with_capacity_three_the_overwrite_pre_is_the_oldest_row() {
		// Mutation: overwriting the newest slot would evict the row a reader still expects to see.
		let mut store = MemoryStore::default();
		let placed = insert(&mut store, 3, None, &[1, 2, 3]);
		let wrapped = insert(&mut store, 3, None, &[4]);
		assert_eq!(wrapped[0].row, placed[0].row, "the fourth write lands in the first slot");
		assert_eq!(sequence_of(wrapped[0].evicted.as_ref().unwrap()), placed[0].sequence);
		assert_eq!(store.metadata[&None].count, 3);
	}

	#[test]
	fn a_delete_reads_only_the_slots_of_its_own_partition() {
		// Mutation: walking every partition shows up as reads of partition 2's slots.
		let mut store = MemoryStore::default();
		let a = insert(&mut store, 4, Some(Partition(1)), &[1, 2, 3, 4]);
		insert(&mut store, 4, Some(Partition(2)), &[1, 2, 3, 4]);
		store.reads.clear();

		delete(&mut store, 4, Some(Partition(1)), &[a[2].row]);
		assert_eq!(store.reads, vec![(Some(Partition(1)), a[2].row)]);
		assert_eq!(store.metadata[&Some(Partition(1))].count, 3);
		assert_eq!(store.metadata[&Some(Partition(2))].count, 4);
	}

	#[test]
	fn a_delete_of_a_row_outside_the_partition_range_reads_nothing() {
		// Mutation: reading a foreign row number could count another partition's row as removed.
		let mut store = MemoryStore::default();
		insert(&mut store, 2, Some(Partition(1)), &[1, 2]);
		store.reads.clear();
		let mut ring = Ring::new(2);
		let removed = ring.remove(&mut store, &[(Some(Partition(1)), vec![RowNumber(1)])]).unwrap().remove(0);
		assert_eq!(removed, vec![None]);
		assert!(store.reads.is_empty());
		assert!(ring.writes().is_empty(), "nothing removed, nothing to write");
	}

	#[test]
	fn an_emptied_partition_drops_its_metadata_and_returns_with_a_fresh_range() {
		// Mutation: reusing the old range after removal would repeat (rn, #sequence) pairs.
		let mut store = MemoryStore::default();
		let first = insert(&mut store, 2, Some(Partition(1)), &[1]);
		delete(&mut store, 2, Some(Partition(1)), &[first[0].row]);
		assert!(!store.metadata.contains_key(&Some(Partition(1))));
		let again = insert(&mut store, 2, Some(Partition(1)), &[2]);
		assert_ne!(again[0].row, first[0].row);
	}

	#[test]
	fn an_emptied_unpartitioned_ring_keeps_its_sequence() {
		// Mutation: dropping the metadata would restart #sequence on the same row numbers.
		let mut store = MemoryStore::default();
		let first = insert(&mut store, 2, None, &[1]);
		delete(&mut store, 2, None, &[first[0].row]);
		assert_eq!(store.metadata[&None].count, 0);
		let again = insert(&mut store, 2, None, &[2]);
		assert_eq!(again[0].sequence, first[0].sequence + 1);
	}

	#[test]
	fn rows_in_distinct_partitions_never_share_a_row_number() {
		// Mutation: a shared base would make an rn name two rows across partitions.
		let mut store = MemoryStore::default();
		let a = insert(&mut store, 3, Some(Partition(1)), &[1, 2, 3]);
		let b = insert(&mut store, 3, Some(Partition(2)), &[1, 2, 3]);
		for left in &a {
			assert!(b.iter().all(|right| right.row != left.row));
		}
	}

	#[test]
	fn expiry_walks_from_the_oldest_slot_and_stops_at_the_first_live_row() {
		// Mutation: scanning all slots would also expire the old-stamped row behind a live one.
		let mut store = MemoryStore::default();
		let placed = insert(&mut store, 4, None, &[10, 20, 30, 15]);
		store.reads.clear();
		let mut ring = Ring::new(4);
		let expired = ring.expire(&mut store, None, DateTime::from_millis(25), 1).unwrap();
		let rows: Vec<RowNumber> = expired.iter().map(|(row, _)| *row).collect();
		assert_eq!(rows, vec![placed[0].row, placed[1].row]);
		assert_eq!(store.reads.len(), 3, "reads stop at the first live row");
		assert_eq!(ring.metadata(&mut store, None).unwrap().unwrap().count, 2);
	}

	#[test]
	fn expiry_skips_holes_and_starts_at_the_oldest_live_sequence_after_a_wrap() {
		// Mutation: starting at slot 0 instead of the head would expire the newest row first.
		let mut store = MemoryStore::default();
		let placed = insert(&mut store, 3, None, &[10, 20, 30]);
		let wrapped = insert(&mut store, 3, None, &[40]);
		delete(&mut store, 3, None, &[placed[1].row]);
		let mut ring = Ring::new(3);
		let expired = ring.expire(&mut store, None, DateTime::from_millis(35), 8).unwrap();
		let rows: Vec<RowNumber> = expired.iter().map(|(row, _)| *row).collect();
		assert_eq!(rows, vec![placed[2].row], "slot 1 is a hole, slot 2 holds 30, slot 0 holds the live 40");
		assert_ne!(rows[0], wrapped[0].row);
	}

	#[test]
	fn the_newest_row_follows_the_sequence_not_the_highest_row_number() {
		// Mutation: taking the highest row number answers with an older row after a wrap.
		let mut store = MemoryStore::default();
		insert(&mut store, 2, Some(Partition(1)), &[10, 20]);
		let wrapped = insert(&mut store, 2, Some(Partition(1)), &[30]);
		let (row, bytes) = newest(&mut store, &[Some(Partition(1))]).unwrap()[0].clone().unwrap();
		assert_eq!(row, wrapped[0].row);
		assert_eq!(sequence_of(&bytes), wrapped[0].sequence);
	}

	#[test]
	fn the_newest_row_skips_a_deleted_newest_slot() {
		// Mutation: stopping at the newest slot returns nothing although an older row is live.
		let mut store = MemoryStore::default();
		let placed = insert(&mut store, 3, None, &[10, 20]);
		delete(&mut store, 3, None, &[placed[1].row]);
		let (row, _) = newest(&mut store, &[None]).unwrap()[0].clone().unwrap();
		assert_eq!(row, placed[0].row);
	}

	#[test]
	fn the_oldest_row_is_the_first_live_slot_from_the_head_after_a_wrap() {
		// Mutation: taking the lowest row number arms the expiry timer on the newest row.
		let mut store = MemoryStore::default();
		let placed = insert(&mut store, 3, None, &[10, 20, 30]);
		insert(&mut store, 3, None, &[40]);
		delete(&mut store, 3, None, &[placed[1].row]);
		let (row, bytes) = oldest(&mut store, &[None]).unwrap()[0].clone().unwrap();
		assert_eq!(row, placed[2].row, "slot 0 now holds the newest row and slot 1 is a hole");
		assert_eq!(sequence_of(&bytes), placed[2].sequence);
	}

	#[test]
	fn an_insert_after_a_delete_fills_the_free_slot_instead_of_evicting_a_live_row() {
		// Mutation: placing at seq % cap evicts the live row under the cursor and leaves the ring under
		// capacity.
		let mut store = MemoryStore::default();
		let placed = insert(&mut store, 2, None, &[1, 2]);
		delete(&mut store, 2, None, &[placed[0].row]);
		let next = insert(&mut store, 2, None, &[3]);
		assert_eq!(next[0].row, placed[0].row, "the freed slot is reused");
		assert!(next[0].evicted.is_none(), "a free slot exists, so nothing live may be evicted");
		assert_eq!(store.metadata[&None].count, 2, "the ring is full again");
		assert!(store.rows.contains_key(&(None, placed[1].row)), "the surviving row stays live");
	}

	#[test]
	fn a_full_ring_evicts_the_oldest_live_sequence_not_the_slot_under_a_cursor() {
		// Mutation: evicting by slot position instead of sequence drops the newer of the two live rows.
		let mut store = MemoryStore::default();
		let placed = insert(&mut store, 2, None, &[1, 2]);
		delete(&mut store, 2, None, &[placed[0].row]);
		let refill = insert(&mut store, 2, None, &[3]);
		let overflow = insert(&mut store, 2, None, &[4]);
		assert_eq!(overflow[0].row, placed[1].row, "slot 2 holds the oldest live sequence");
		let evicted = overflow[0].evicted.as_ref().expect("a full ring evicts");
		assert_eq!(sequence_of(evicted), placed[1].sequence);
		assert_ne!(overflow[0].row, refill[0].row);
		assert_eq!(store.metadata[&None].count, 2);
	}

	#[test]
	fn a_batch_larger_than_the_free_room_evicts_only_the_shortfall_oldest_first() {
		// Mutation: evicting before using free slots or fresh room drops rows the ring still has room for.
		let mut store = MemoryStore::default();
		let placed = insert(&mut store, 4, None, &[1, 2, 3]);
		delete(&mut store, 4, None, &[placed[1].row]);
		let batch = insert(&mut store, 4, None, &[4, 5, 6]);
		let evicted: Vec<u64> = batch.iter().filter_map(|p| p.evicted.as_ref()).map(sequence_of).collect();
		assert_eq!(
			evicted,
			vec![placed[0].sequence],
			"one free slot and one fresh slot leave a single eviction"
		);
		assert_eq!(store.metadata[&None].count, 4);
		let order: Vec<u64> = store.entries(None).map(|(sequence, _)| sequence).collect();
		assert_eq!(order, vec![placed[2].sequence, batch[0].sequence, batch[1].sequence, batch[2].sequence]);
	}

	#[test]
	fn an_emptied_partition_leaves_no_order_or_free_rows_behind() {
		// Mutation: keeping the index of a dropped partition makes a fresh range evict ghost slots.
		let mut store = MemoryStore::default();
		let placed = insert(&mut store, 2, Some(Partition(1)), &[1, 2]);
		delete(&mut store, 2, Some(Partition(1)), &[placed[0].row]);
		assert_eq!(store.free[&(Some(Partition(1)), 0)], vec![placed[0].row]);
		delete(&mut store, 2, Some(Partition(1)), &[placed[1].row]);
		assert!(!store.metadata.contains_key(&Some(Partition(1))));
		assert_eq!(store.entries(Some(Partition(1))).count(), 0);
		assert!(store.free.keys().all(|(owner, _)| *owner != Some(Partition(1))));
	}

	#[test]
	fn expiry_frees_the_slots_it_drains_so_the_next_insert_does_not_evict() {
		// Mutation: expiring without releasing slots makes the next insert evict a live row.
		let mut store = MemoryStore::default();
		let placed = insert(&mut store, 2, None, &[10, 20]);
		let mut ring = Ring::new(2);
		ring.expire(&mut store, None, DateTime::from_millis(15), 8).unwrap();
		store.rows.remove(&(None, placed[0].row));
		apply(&mut store, &ring);
		let next = insert(&mut store, 2, None, &[30]);
		assert_eq!(next[0].row, placed[0].row);
		assert!(next[0].evicted.is_none());
		assert_eq!(store.metadata[&None].count, 2);
	}

	#[test]
	fn eviction_moves_the_head_to_the_oldest_live_sequence() {
		// Mutation: a head left at 0 makes every eviction walk the whole deleted order history.
		let mut store = MemoryStore::default();
		insert(&mut store, 3, None, &[1, 2, 3]);
		let wrapped = insert(&mut store, 3, None, &[4, 5]);
		let oldest_live = store.entries(None).next().map(|(sequence, _)| sequence).unwrap();
		assert_eq!(store.metadata[&None].head, oldest_live, "two evictions advance the head past both victims");
		assert_eq!(wrapped.len(), 2);
	}

	#[test]
	fn a_delete_of_the_head_row_keeps_the_head_a_safe_lower_bound() {
		// Mutation: a head moved past a live row would hide that row from eviction and scans.
		let mut store = MemoryStore::default();
		let placed = insert(&mut store, 3, None, &[1, 2, 3]);
		insert(&mut store, 3, None, &[4]);
		let head = store.metadata[&None].head;
		delete(&mut store, 3, None, &[placed[1].row]);
		assert_eq!(store.metadata[&None].head, head, "a delete never moves the head");
		let (row, _) = oldest(&mut store, &[None]).unwrap()[0].clone().unwrap();
		assert_eq!(row, placed[2].row, "the oldest live row is still found from the head");
		let next = insert(&mut store, 3, None, &[5]);
		assert!(next[0].evicted.is_none(), "the freed slot is used first");
		let overflow = insert(&mut store, 3, None, &[6]);
		assert_eq!(sequence_of(overflow[0].evicted.as_ref().unwrap()), placed[2].sequence);
	}

	#[test]
	fn a_ring_with_no_free_slots_never_reads_the_free_row() {
		// Without this skip an append-only ring pays one storage read per commit for a list known to be empty.
		let mut store = MemoryStore::default();
		insert(&mut store, 2, None, &[1, 2]);
		insert(&mut store, 2, None, &[3]);
		assert_eq!(store.free_reads, 0);
	}

	#[test]
	fn a_ring_with_a_freed_slot_still_reads_and_reuses_it() {
		// The skip must never hide a real free slot, otherwise an insert evicts a live row while a slot is
		// free.
		let mut store = MemoryStore::default();
		let placed = insert(&mut store, 3, None, &[1, 2, 3]);
		delete(&mut store, 3, None, &[placed[1].row]);
		let reads_before_reuse = store.free_reads;
		let reused = insert(&mut store, 3, None, &[4]);
		assert_eq!(store.free_reads, reads_before_reuse + 1);
		assert_eq!(reused[0].row, placed[1].row);
		assert!(reused[0].evicted.is_none());
	}

	fn writes_of(ring: &Ring) -> Vec<(u64, Option<usize>)> {
		ring.writes()
			.into_iter()
			.filter_map(|write| match write {
				MetadataWrite::Free(_, page, slots) => Some((page, slots.map(|slots| slots.len()))),
				_ => None,
			})
			.collect()
	}

	fn stack(store: &MemoryStore, partition: Option<Partition>) -> Vec<RowNumber> {
		let mut pages: Vec<u64> =
			store.free.keys().filter(|(owner, _)| *owner == partition).map(|(_, page)| *page).collect();
		pages.sort_unstable();
		pages.into_iter().flat_map(|page| store.free[&(partition, page)].iter().copied()).collect()
	}

	fn assert_free_matches_count(store: &MemoryStore, partition: Option<Partition>) {
		// Every page below the top must be full and the top partial, or the page arithmetic points at nothing.
		let metadata = store.metadata[&partition];
		let free = metadata.filled - metadata.count;
		assert_eq!(stack(store, partition).len() as u64, free);
		for page in 0..free.div_ceil(FREE_PAGE_SLOTS) {
			let expected = (free - page * FREE_PAGE_SLOTS).min(FREE_PAGE_SLOTS) as usize;
			assert_eq!(store.free[&(partition, page)].len(), expected, "page {page} of {free} free");
		}
		let keys = store.free.keys().filter(|(owner, _)| *owner == partition).count() as u64;
		assert_eq!(keys, free.div_ceil(FREE_PAGE_SLOTS));
	}

	fn full(capacity: u64, partition: Option<Partition>) -> (MemoryStore, Vec<Placement>) {
		let mut store = MemoryStore::default();
		let times: Vec<i64> = (0..capacity as i64).collect();
		let placed = insert(&mut store, capacity, partition, &times);
		(store, placed)
	}

	fn rows_of(placed: &[Placement]) -> Vec<RowNumber> {
		placed.iter().map(|placement| placement.row).collect()
	}

	#[test]
	fn reuse_is_last_freed_first_within_one_batch_and_across_commits() {
		// Row numbers are user visible, so any other reuse order changes results.
		let (mut store, placed) = full(6, None);
		let rows = rows_of(&placed);
		delete(&mut store, 6, None, &[rows[1], rows[4]]);
		delete(&mut store, 6, None, &[rows[2]]);
		assert_eq!(stack(&store, None), vec![rows[1], rows[4], rows[2]]);

		let batch = insert(&mut store, 6, None, &[10, 11]);
		assert_eq!(rows_of(&batch), vec![rows[2], rows[4]], "within one batch, last freed first");
		let next = insert(&mut store, 6, None, &[12]);
		assert_eq!(rows_of(&next), vec![rows[1]], "across commits, last freed first");
		assert!(store.free.is_empty());
	}

	#[test]
	fn reuse_stays_last_freed_first_across_a_page_boundary() {
		// A page popped in the wrong order would hand out older slots while newer ones sit free.
		let capacity = FREE_PAGE_SLOTS + 3;
		let (mut store, placed) = full(capacity, None);
		let rows = rows_of(&placed);
		delete(&mut store, capacity, None, &rows);
		let times: Vec<i64> = (0..6).collect();
		let reused = insert(&mut store, capacity, None, &times);
		let mut expected: Vec<RowNumber> = rows.clone();
		expected.reverse();
		assert_eq!(rows_of(&reused), expected[..6].to_vec());
		assert_free_matches_count(&store, None);
	}

	#[test]
	fn a_push_then_pop_in_one_session_writes_no_free_key_and_reads_none() {
		// A leak here grows storage on a slot that is immediately busy again.
		let (mut store, placed) = full(4, None);
		let mut ring = Ring::new(4);
		ring.remove(&mut store, &[(None, vec![placed[1].row])]).unwrap();
		let again = ring.place(&mut store, &[(None, 1)]).unwrap().remove(0);
		assert_eq!(again[0].row, placed[1].row);
		assert!(writes_of(&ring).is_empty(), "the stack is back where it started");
		assert_eq!(store.free_reads, 0, "a top page starting at its first index needs no read");
	}

	#[test]
	fn a_push_then_pop_on_a_stored_page_leaves_the_page_unwritten() {
		// The page content is unchanged, so rewriting it would be a write with no effect.
		let (mut store, placed) = full(4, None);
		delete(&mut store, 4, None, &[placed[0].row]);
		store.pages_read.clear();
		let mut ring = Ring::new(4);
		ring.remove(&mut store, &[(None, vec![placed[1].row])]).unwrap();
		ring.place(&mut store, &[(None, 1)]).unwrap();
		assert!(writes_of(&ring).is_empty());
		assert_eq!(
			store.pages_read,
			vec![(None, 0)],
			"the page is read once for the push, then cached for the pop"
		);
	}

	#[test]
	fn a_no_free_ring_never_reads_a_page_even_when_it_evicts() {
		// The skip is what keeps an append-only ring free of a read on every commit.
		let (mut store, _) = full(600, None);
		let times: Vec<i64> = (0..3).collect();
		insert(&mut store, 600, None, &times);
		assert!(store.pages_read.is_empty());
		assert!(store.free.is_empty());
	}

	#[test]
	fn a_commit_touches_only_the_pages_its_pushes_and_pops_reach() {
		// A rewrite of untouched pages would bring back the cost of rewriting the whole list.
		let capacity = FREE_PAGE_SLOTS * 3;
		let (mut store, placed) = full(capacity, None);
		let rows = rows_of(&placed);
		delete(&mut store, capacity, None, &rows[..(FREE_PAGE_SLOTS as usize * 2 + 10)]);
		store.pages_read.clear();

		let mut ring = Ring::new(capacity);
		ring.place(&mut store, &[(None, 3)]).unwrap();
		assert_eq!(store.pages_read, vec![(None, 2)], "only the top page is read");
		assert_eq!(writes_of(&ring), vec![(2, Some(7))], "only the top page is written");

		store.pages_read.clear();
		let mut ring = Ring::new(capacity);
		ring.remove(&mut store, &[(None, vec![rows[FREE_PAGE_SLOTS as usize * 2 + 20]])]).unwrap();
		assert_eq!(store.pages_read, vec![(None, 2)]);
		assert_eq!(writes_of(&ring), vec![(2, Some(11))]);
	}

	#[test]
	fn a_pop_batch_across_pages_reads_them_in_one_call_and_each_page_once() {
		// A read per slot or per pop would make a batch insert pay one round trip per row.
		let capacity = FREE_PAGE_SLOTS * 3;
		let (mut store, placed) = full(capacity, None);
		let rows = rows_of(&placed);
		delete(&mut store, capacity, None, &rows[..(FREE_PAGE_SLOTS as usize * 2 + 10)]);
		store.free_reads = 0;
		store.pages_read.clear();

		let mut ring = Ring::new(capacity);
		ring.place(&mut store, &[(None, FREE_PAGE_SLOTS as usize + 20)]).unwrap();
		assert_eq!(store.free_reads, 1);
		assert_eq!(store.pages_read, vec![(None, 0), (None, 1), (None, 2)]);
		assert_eq!(writes_of(&ring), vec![(0, Some(502)), (1, None), (2, None)]);
	}

	#[test]
	fn many_changes_in_one_session_read_and_write_each_page_at_most_once() {
		// Repeated reads would miss the session's own changes, and repeated writes would waste the commit.
		let capacity = FREE_PAGE_SLOTS * 2;
		let (mut store, placed) = full(capacity, None);
		let rows = rows_of(&placed);
		delete(&mut store, capacity, None, &rows[..(FREE_PAGE_SLOTS as usize + 5)]);
		store.pages_read.clear();

		let mut ring = Ring::new(capacity);
		for _ in 0..4 {
			ring.place(&mut store, &[(None, 2)]).unwrap();
		}
		ring.remove(&mut store, &[(None, vec![rows[FREE_PAGE_SLOTS as usize + 6]])]).unwrap();
		ring.place(&mut store, &[(None, 2)]).unwrap();
		let mut read = store.pages_read.clone();
		read.sort();
		read.dedup();
		assert_eq!(read.len(), store.pages_read.len(), "no page is read twice: {:?}", store.pages_read);
		let written: Vec<u64> = writes_of(&ring).iter().map(|(page, _)| *page).collect();
		let mut unique = written.clone();
		unique.dedup();
		assert_eq!(written, unique, "no page is written twice");
	}

	#[test]
	fn pushing_past_a_page_boundary_starts_a_new_page_with_no_read_and_never_overfills() {
		// A slot past the page limit would break the index arithmetic every later session relies on.
		let capacity = FREE_PAGE_SLOTS + 2;
		let (mut store, placed) = full(capacity, None);
		let rows = rows_of(&placed);
		delete(&mut store, capacity, None, &rows[..FREE_PAGE_SLOTS as usize]);
		assert_eq!(store.free[&(None, 0)].len() as u64, FREE_PAGE_SLOTS);
		store.pages_read.clear();

		delete(&mut store, capacity, None, &[rows[FREE_PAGE_SLOTS as usize]]);
		assert!(store.pages_read.is_empty(), "the new page starts at its first index, so nothing is read");
		assert_eq!(store.free[&(None, 0)].len() as u64, FREE_PAGE_SLOTS);
		assert_eq!(store.free[&(None, 1)], vec![rows[FREE_PAGE_SLOTS as usize]]);
		assert!(store.free.values().all(|page| page.len() as u64 <= FREE_PAGE_SLOTS));
		assert_free_matches_count(&store, None);
	}

	#[test]
	fn popping_back_across_a_page_boundary_removes_the_empty_page_and_keeps_the_rest() {
		// A kept empty page would disagree with the free count and leak a key.
		let capacity = FREE_PAGE_SLOTS + 2;
		let (mut store, placed) = full(capacity, None);
		let rows = rows_of(&placed);
		delete(&mut store, capacity, None, &rows[..(FREE_PAGE_SLOTS as usize + 1)]);
		let popped = insert(&mut store, capacity, None, &[10, 11]);
		assert_eq!(popped[0].row, rows[FREE_PAGE_SLOTS as usize]);
		assert_eq!(popped[1].row, rows[FREE_PAGE_SLOTS as usize - 1]);
		assert!(!store.free.contains_key(&(None, 1)), "the emptied page key is removed");
		assert_eq!(store.free[&(None, 0)].len() as u64, FREE_PAGE_SLOTS - 1);
		assert_free_matches_count(&store, None);
	}

	#[test]
	fn the_free_pages_agree_with_the_free_count_through_every_step() {
		// A drifted stack either overwrites a live row or leaks a slot forever.
		let capacity = FREE_PAGE_SLOTS + 40;
		let (mut store, placed) = full(capacity, None);
		let rows = rows_of(&placed);
		for chunk in rows[..(FREE_PAGE_SLOTS as usize + 30)].chunks(97) {
			delete(&mut store, capacity, None, chunk);
			assert_free_matches_count(&store, None);
		}
		for _ in 0..6 {
			let times: Vec<i64> = (0..80).collect();
			insert(&mut store, capacity, None, &times);
			assert_free_matches_count(&store, None);
		}
	}

	#[test]
	fn an_emptied_partition_removes_every_free_page_and_a_new_range_starts_clean() {
		// A page left behind would hand slots of the old range to the partition's next life.
		let partition = Some(Partition(1));
		let capacity = FREE_PAGE_SLOTS * 2 + 10;
		let (mut store, placed) = full(capacity, partition);
		let rows = rows_of(&placed);
		delete(&mut store, capacity, partition, &rows[..rows.len() - 1]);
		assert_eq!(store.free.len(), 3);
		store.pages_read.clear();
		delete(&mut store, capacity, partition, &[rows[rows.len() - 1]]);
		assert!(store.free.is_empty(), "every page of the emptied partition goes");

		let again = insert(&mut store, capacity, partition, &[1]);
		assert!(!rows.contains(&again[0].row), "freed slots of the old range must not come back");
	}

	#[test]
	fn emptying_a_million_slot_partition_writes_about_one_key_per_page() {
		// One key per slot would hit the one million write limit and make the last delete fail for good.
		let partition = Some(Partition(1));
		let capacity = 1_000_000u64;
		let mut store = MemoryStore::default();
		store.metadata.insert(
			partition,
			RingBufferMetadata {
				base_rn: 100,
				next_sequence: capacity,
				count: 1,
				filled: capacity,
				head: capacity - 1,
			},
		);
		let row_number = RowNumber(100 + capacity - 1);
		store.rows.insert((partition, row_number), row(capacity - 1, None));
		store.order.insert((partition, capacity - 1), row_number);
		store.free.insert(
			(partition, (capacity - 2) / FREE_PAGE_SLOTS),
			vec![RowNumber(100); ((capacity - 1) % FREE_PAGE_SLOTS) as usize],
		);
		let mut ring = Ring::new(capacity);
		ring.remove(&mut store, &[(partition, vec![row_number])]).unwrap();
		let writes = ring.writes();
		let pages = writes.iter().filter(|write| matches!(write, MetadataWrite::Free(_, _, None))).count();
		assert_eq!(pages as u64, (capacity - 1).div_ceil(FREE_PAGE_SLOTS));
		assert_eq!(pages, 1954);
		assert!(writes.len() < 2_000, "got {} writes", writes.len());
	}

	#[test]
	fn a_full_reuse_of_the_top_page_writes_a_removal_not_an_empty_page() {
		// An empty page row would read back as a present page with no slots and hide a corrupt count.
		let (mut store, placed) = full(4, None);
		delete(&mut store, 4, None, &[placed[0].row]);
		let mut ring = Ring::new(4);
		ring.place(&mut store, &[(None, 1)]).unwrap();
		assert_eq!(writes_of(&ring), vec![(0, None)]);
	}

	#[test]
	fn a_page_shorter_than_the_free_count_fails_instead_of_evicting_a_live_row() {
		// Falling through to fresh slots or eviction would overwrite a row while the index is corrupt.
		let (mut store, placed) = full(4, None);
		delete(&mut store, 4, None, &[placed[0].row]);
		store.free.remove(&(None, 0));
		let mut ring = Ring::new(4);
		let result = catch_unwind(AssertUnwindSafe(|| ring.place(&mut store, &[(None, 1)])));
		assert!(!matches!(result, Ok(Ok(_))), "a corrupt free stack must not place a row");
	}

	#[test]
	fn a_place_across_partitions_reads_metadata_once_and_evicted_slots_once() {
		// A read per partition makes an insert over many partitions pay one round trip each.
		let (a, b, fresh) = (Some(Partition(1)), Some(Partition(2)), Some(Partition(3)));
		let mut store = MemoryStore::default();
		let in_a = insert(&mut store, 2, a, &[1, 2]);
		let in_b = insert(&mut store, 2, b, &[1, 2]);
		store.metadata_calls = 0;
		store.slot_calls = 0;
		let mut ring = Ring::new(2);
		let placed = ring.place(&mut store, &[(a, 1), (fresh, 2), (b, 1)]).unwrap();
		assert_eq!(store.metadata_calls, 1);
		assert_eq!(store.slot_calls, 1);
		assert_eq!(placed.len(), 3, "one answer per request, in request order");
		assert_eq!(placed[0][0].row, in_a[0].row);
		assert_eq!(sequence_of(placed[0][0].evicted.as_ref().unwrap()), in_a[0].sequence);
		assert_eq!(placed[1].len(), 2);
		assert!(
			placed[1].iter().all(|placement| placement.evicted.is_none()),
			"a fresh partition evicts nothing"
		);
		assert_eq!(placed[2][0].row, in_b[0].row);
		assert_eq!(sequence_of(placed[2][0].evicted.as_ref().unwrap()), in_b[0].sequence);
	}

	#[test]
	fn a_batched_place_matches_one_place_per_partition() {
		// The batch must leave the same rows and index behind as separate calls, or row numbers drift.
		let (a, b) = (Some(Partition(1)), Some(Partition(2)));
		let mut batched = MemoryStore::default();
		insert(&mut batched, 3, a, &[1, 2, 3]);
		insert(&mut batched, 3, b, &[1]);
		let mut single = MemoryStore::default();
		insert(&mut single, 3, a, &[1, 2, 3]);
		insert(&mut single, 3, b, &[1]);

		let mut ring = Ring::new(3);
		let together = ring.place(&mut batched, &[(a, 2), (b, 2)]).unwrap();
		apply(&mut batched, &ring);
		let mut apart = Vec::new();
		for (partition, count) in [(a, 2), (b, 2)] {
			let mut ring = Ring::new(3);
			apart.push(ring.place(&mut single, &[(partition, count)]).unwrap().remove(0));
			apply(&mut single, &ring);
		}
		assert_eq!(together, apart);
		assert_eq!(batched.metadata, single.metadata);
		assert_eq!(batched.order, single.order);
		assert_eq!(batched.free, single.free);
	}

	#[test]
	fn a_remove_across_partitions_reads_metadata_once_and_slots_once() {
		// A read per partition makes a delete over many partitions pay one round trip each.
		let (a, b, missing) = (Some(Partition(1)), Some(Partition(2)), Some(Partition(3)));
		let mut store = MemoryStore::default();
		let in_a = insert(&mut store, 3, a, &[1, 2, 3]);
		let in_b = insert(&mut store, 3, b, &[1, 2]);
		store.metadata_calls = 0;
		store.slot_calls = 0;
		let mut ring = Ring::new(3);
		let removed = ring
			.remove(
				&mut store,
				&[
					(a, vec![in_a[1].row, in_b[0].row]),
					(missing, vec![in_a[0].row]),
					(b, vec![in_b[1].row]),
				],
			)
			.unwrap();
		assert_eq!(store.metadata_calls, 1);
		assert_eq!(store.slot_calls, 1);
		assert_eq!(sequence_of(removed[0][0].as_ref().unwrap()), in_a[1].sequence);
		assert!(removed[0][1].is_none(), "a row of another partition is never removed from this one");
		assert_eq!(removed[1], vec![None], "a partition with no metadata holds nothing");
		assert_eq!(sequence_of(removed[2][0].as_ref().unwrap()), in_b[1].sequence);
		for (partition, row) in [(a, in_a[1].row), (b, in_b[1].row)] {
			store.rows.remove(&(partition, row));
		}
		apply(&mut store, &ring);
		assert_eq!(store.metadata[&a].count, 2);
		assert_eq!(store.metadata[&b].count, 1);
		assert_eq!(store.free[&(a, 0)], vec![in_a[1].row]);
		assert_eq!(store.free[&(b, 0)], vec![in_b[1].row]);
	}

	#[test]
	fn a_place_naming_one_partition_twice_is_refused() {
		// The second request would read an evicted slot before the first request's row is written.
		let (mut store, _) = full(2, None);
		let mut ring = Ring::new(2);
		let result = catch_unwind(AssertUnwindSafe(|| ring.place(&mut store, &[(None, 1), (None, 1)])));
		assert!(result.is_err());
	}

	#[test]
	fn a_remove_naming_one_partition_twice_is_refused() {
		// A row named in both requests would be released twice and corrupt the free stack.
		let (mut store, placed) = full(2, None);
		let mut ring = Ring::new(2);
		let rows = vec![placed[0].row];
		let result = catch_unwind(AssertUnwindSafe(|| {
			ring.remove(&mut store, &[(None, rows.clone()), (None, rows.clone())])
		}));
		assert!(result.is_err());
	}

	#[test]
	fn a_preload_reads_every_partition_in_one_call_and_expiry_reads_no_more_metadata() {
		// An expiry pass over many partitions must not pay one metadata read each.
		let (a, b) = (Some(Partition(1)), Some(Partition(2)));
		let mut store = MemoryStore::default();
		insert(&mut store, 2, a, &[10, 20]);
		insert(&mut store, 2, b, &[10, 20]);
		store.metadata_calls = 0;
		let mut ring = Ring::new(2);
		ring.preload(&mut store, &[a, b, a]).unwrap();
		assert_eq!(store.metadata_calls, 1);
		for partition in [a, b] {
			assert_eq!(ring.expire(&mut store, partition, DateTime::from_millis(15), 8).unwrap().len(), 1);
		}
		ring.preload(&mut store, &[a, b]).unwrap();
		assert_eq!(store.metadata_calls, 1, "tracked partitions are never read again");
	}

	#[test]
	fn a_batched_newest_equals_newest_per_partition() {
		// Each slot of a batched answer must match the one-partition answer, or a lookup joins the wrong row.
		let mut store = MemoryStore::default();
		let (inserted, updated, deleted, expired, evicted, emptied, missing) = (
			Some(Partition(1)),
			Some(Partition(2)),
			Some(Partition(3)),
			Some(Partition(4)),
			Some(Partition(5)),
			Some(Partition(6)),
			Some(Partition(7)),
		);
		let in_inserted = insert(&mut store, 3, inserted, &[1, 2]);
		let in_updated = insert(&mut store, 3, updated, &[1, 2]);
		let changed = row(in_updated[1].sequence, Some(99));
		store.rows.insert((updated, in_updated[1].row), changed.clone());
		let in_deleted = insert(&mut store, 3, deleted, &[1, 2]);
		delete(&mut store, 3, deleted, &[in_deleted[1].row]);
		let in_expired = insert(&mut store, 3, expired, &[10, 20, 30]);
		let mut ring = Ring::new(3);
		for (row, _) in ring.expire(&mut store, expired, DateTime::from_millis(25), 8).unwrap() {
			store.rows.remove(&(expired, row));
		}
		apply(&mut store, &ring);
		insert(&mut store, 2, evicted, &[1, 2]);
		let in_evicted = insert(&mut store, 2, evicted, &[3]);
		let in_emptied = insert(&mut store, 2, emptied, &[1]);
		delete(&mut store, 2, emptied, &[in_emptied[0].row]);
		let in_unpartitioned = insert(&mut store, 2, None, &[1, 2]);

		let partitions = [inserted, updated, deleted, expired, evicted, emptied, missing, None, inserted];
		let batched = newest(&mut store, &partitions).unwrap();
		let single: Vec<Option<(RowNumber, EncodedBytes)>> = partitions
			.iter()
			.map(|&partition| newest(&mut store, &[partition]).unwrap()[0].clone())
			.collect();
		assert_eq!(batched, single);
		let rows: Vec<Option<RowNumber>> =
			batched.iter().map(|found| found.as_ref().map(|(row, _)| *row)).collect();
		assert_eq!(
			rows,
			vec![
				Some(in_inserted[1].row),
				Some(in_updated[1].row),
				Some(in_deleted[0].row),
				Some(in_expired[2].row),
				Some(in_evicted[0].row),
				None,
				None,
				Some(in_unpartitioned[1].row),
				Some(in_inserted[1].row),
			]
		);
		assert_eq!(batched[1].as_ref().unwrap().1, changed, "an update is read back with its new bytes");
	}

	#[test]
	fn the_newest_of_a_partition_whose_newest_row_was_deleted_falls_back_to_the_order_scan() {
		// Without the fallback a deleted newest row hides the older live rows of its partition.
		let mut store = MemoryStore::default();
		let (deleted, kept) = (Some(Partition(1)), Some(Partition(2)));
		let placed = insert(&mut store, 3, deleted, &[10, 20]);
		delete(&mut store, 3, deleted, &[placed[1].row]);
		let in_kept = insert(&mut store, 3, kept, &[10, 20]);
		store.newest_order_calls = 0;
		let found = newest(&mut store, &[deleted, kept]).unwrap();
		assert_eq!(found[0].as_ref().unwrap().0, placed[0].row);
		assert_eq!(found[1].as_ref().unwrap().0, in_kept[1].row);
		assert_eq!(store.newest_order_calls, 1, "only the partition whose guessed order key is gone scans");
	}

	#[test]
	fn a_batched_newest_reads_every_partition_in_one_metadata_and_one_slot_read() {
		// A read per partition makes a lookup over many partitions pay one round trip each.
		let mut store = MemoryStore::default();
		insert(&mut store, 3, Some(Partition(1)), &[1, 2]);
		insert(&mut store, 3, Some(Partition(2)), &[1]);
		insert(&mut store, 3, None, &[1, 2, 3]);
		store.metadata_calls = 0;
		store.slot_calls = 0;
		store.order_at_calls = 0;
		store.newest_order_calls = 0;
		store.reads.clear();
		let found = newest(&mut store, &[Some(Partition(1)), Some(Partition(2)), None, Some(Partition(9))])
			.unwrap();
		assert_eq!(found.iter().filter(|found| found.is_some()).count(), 3);
		assert_eq!(store.metadata_calls, 1);
		assert_eq!(store.order_at_calls, 1);
		assert_eq!(store.slot_calls, 1);
		assert_eq!(store.newest_order_calls, 0, "every guessed order key exists, so nothing scans");
		assert_eq!(store.reads.len(), 3, "a partition with no metadata reads no slot");
	}
}