reifydb-sub-flow 0.10.2

Flow subsystem for stream processing and data flows
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
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2026 ReifyDB

use std::{
	collections::{BTreeMap, HashMap, HashSet, VecDeque},
	mem::take,
	sync::{
		Arc,
		atomic::{AtomicBool, AtomicI64, Ordering},
	},
};

use reifydb_core::{
	actors::flow::FlowActorMessage,
	common::{CommitVersion, SourceVersion},
	interface::{
		catalog::{flow::FlowId, id::ViewId, object::ObjectId},
		commit::CommitEntry,
	},
	lifecycle::watermark::ConsumerPositions,
};
use reifydb_flow_async::transaction::{LookupAt, LookupVersions, ViewLayers};
use reifydb_runtime::{actor::mailbox::ActorRef, context::clock::Clock, sync::rwlock::RwLock};
use reifydb_value::value::duration::Duration;
use rustc_hash::{FxHashMap, FxHashSet};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FoldShape {
	PerSource,
	Collapsed,
}

#[derive(Clone)]
pub struct ObjectVersionTracker {
	inner: Arc<ObjectVersionTrackerInner>,
}

#[derive(Default)]
struct ObjectVersionTrackerInner {
	versions: RwLock<BTreeMap<ObjectId, CommitVersion>>,
}

impl ObjectVersionTracker {
	pub fn new() -> Self {
		Self {
			inner: Arc::new(ObjectVersionTrackerInner::default()),
		}
	}

	pub fn update(&self, object_id: ObjectId, version: CommitVersion) {
		let mut versions = self.inner.versions.write();
		versions.entry(object_id)
			.and_modify(|v| {
				if version.0 > v.0 {
					*v = version;
				}
			})
			.or_insert(version);
	}

	pub fn all(&self) -> BTreeMap<ObjectId, CommitVersion> {
		let versions = self.inner.versions.read();
		versions.clone()
	}
}

impl Default for ObjectVersionTracker {
	fn default() -> Self {
		Self::new()
	}
}

pub type FlowUpstreams = FxHashMap<FlowId, FxHashSet<ObjectId>>;

#[derive(Clone, Debug)]
struct Completion {
	commit: CommitVersion,
	position: CommitVersion,
	first_source: SourceVersion,
	source: SourceVersion,
	output: CommitOutput,
}

const COMPLETION_HISTORY: usize = 65_536;

#[derive(Clone, Debug, Default)]
pub enum CommitOutput {
	#[default]
	OneSource,
	PerSource(Arc<ViewLayers>),
	PerSourceUntracked,
	PerSourceWithoutViewRows,
}

impl CommitOutput {
	fn reads_inside(&self) -> bool {
		matches!(self, Self::PerSource(_) | Self::PerSourceUntracked)
	}

	fn view_layers(&self) -> Option<Arc<ViewLayers>> {
		match self {
			Self::PerSource(layers) => Some(Arc::clone(layers)),
			Self::OneSource | Self::PerSourceUntracked | Self::PerSourceWithoutViewRows => None,
		}
	}

	pub fn of_layers(layers: ViewLayers) -> Self {
		match layers.is_empty() {
			true => Self::PerSourceWithoutViewRows,
			false => Self::PerSource(Arc::new(layers)),
		}
	}

	fn of(entry: &CommitEntry) -> Self {
		match entry.layers.len() > 1 {
			true => Self::of_layers(ViewLayers::from_entry(entry)),
			false => Self::OneSource,
		}
	}

	fn or(self, landed: Self) -> Self {
		match self {
			Self::OneSource => landed,
			kept => kept,
		}
	}
}

#[derive(Clone)]
struct Landed {
	commit: CommitVersion,
	first: SourceVersion,
	output: CommitOutput,
}

#[derive(Default)]
struct FlowSource {
	source: Option<SourceVersion>,
	landed: Option<Landed>,
}

#[derive(Default)]
struct FlowSources {
	by_flow: HashMap<FlowId, FlowSource>,
}

impl FlowSources {
	fn advance(&mut self, flow_id: FlowId, source: SourceVersion) {
		let current = &mut self.by_flow.entry(flow_id).or_default().source;
		*current = Some(current.map_or(source, |current| current.max(source)));
	}

	fn land(&mut self, flow_id: FlowId, landed: Landed) {
		self.by_flow.entry(flow_id).or_default().landed = Some(landed);
	}

	fn source(&self, flow_id: FlowId) -> Option<SourceVersion> {
		self.by_flow.get(&flow_id).and_then(|flow| flow.source)
	}

	fn landed(&self, flow_id: FlowId, commit: CommitVersion) -> Option<Landed> {
		self.by_flow.get(&flow_id).and_then(|flow| flow.landed.clone()).filter(|landed| landed.commit == commit)
	}

	fn remove(&mut self, flow_id: FlowId) {
		self.by_flow.remove(&flow_id);
	}
}

pub(crate) const FLOW_WAKE_COALESCE_NANOS: i64 = 20_000_000;

#[derive(Clone)]
pub struct FlowWaker {
	actor: ActorRef<FlowActorMessage>,
	pending: Arc<AtomicBool>,
	clock: Clock,
	next_wake_nanos: Arc<AtomicI64>,
	coalesce_nanos: i64,
}

impl FlowWaker {
	pub fn new(actor: ActorRef<FlowActorMessage>, pending: Arc<AtomicBool>, clock: Clock) -> Self {
		Self {
			actor,
			pending,
			clock,
			next_wake_nanos: Arc::new(AtomicI64::new(0)),
			coalesce_nanos: FLOW_WAKE_COALESCE_NANOS,
		}
	}

	pub fn with_coalesce(mut self, coalesce: Duration) -> Self {
		self.coalesce_nanos =
			coalesce.as_nanos().expect("a flow wake coalesce window must be a plain nanosecond duration");
		self
	}

	pub fn wake(&self) {
		let now = self.clock.now().to_nanos();
		let next = self.next_wake_nanos.load(Ordering::Relaxed);
		if now < next {
			let was = self.pending.swap(true, Ordering::SeqCst);
			if !was {
				let _ = self.actor.send_deferred(FlowActorMessage::Wake);
			}
			return;
		}
		let deadline = now.saturating_add(self.coalesce_nanos);
		if self.next_wake_nanos.compare_exchange(next, deadline, Ordering::SeqCst, Ordering::Relaxed).is_err() {
			return;
		}
		self.send();
	}

	pub fn wake_now(&self) {
		let deadline = self.clock.now().to_nanos().saturating_add(self.coalesce_nanos);
		self.next_wake_nanos.store(deadline, Ordering::SeqCst);
		self.send();
	}

	fn send(&self) {
		if self.pending.swap(true, Ordering::SeqCst) {
			return;
		}
		let _ = self.actor.send_deferred(FlowActorMessage::Wake);
	}
}

#[derive(Clone)]
pub struct FlowPositionTracker {
	inner: Arc<RwLock<FlowProgress>>,
}

#[derive(Default)]
struct FlowProgress {
	positions: HashMap<FlowId, CommitVersion>,
	last_commits: HashMap<FlowId, CommitVersion>,
	completions: HashMap<FlowId, VecDeque<Completion>>,
	upstreams: HashMap<FlowId, Arc<FlowUpstreams>>,
	readers: HashMap<FlowId, HashSet<FlowId>>,
	wakers: HashMap<FlowId, FlowWaker>,
	source_counts: HashMap<FlowId, usize>,
	sources: FlowSources,
	lookup_producers: HashMap<FlowId, BTreeMap<ViewId, FlowId>>,
	units: HashMap<FlowId, FlowId>,
	ticks: HashMap<FlowId, u64>,
	fold_shapes: HashMap<FlowId, FoldShape>,
}

impl FlowProgress {
	fn advance_position(&mut self, flow_id: FlowId, version: CommitVersion) -> bool {
		match self.positions.get_mut(&flow_id) {
			Some(current) if version <= *current => false,
			Some(current) => {
				*current = version;
				true
			}
			None => {
				self.positions.insert(flow_id, version);
				true
			}
		}
	}

	fn advance_last_commit(&mut self, flow_id: FlowId, version: CommitVersion) {
		let current = self.last_commits.entry(flow_id).or_insert(version);
		if version > *current {
			*current = version;
		}
	}

	fn advance_source(&mut self, flow_id: FlowId, source: SourceVersion) {
		self.sources.advance(flow_id, source);
	}

	fn record_landed(&mut self, flow_id: FlowId, position: CommitVersion) {
		let landed = self.last_commits.get(&flow_id).copied().unwrap_or(CommitVersion(0));
		self.record_completion(flow_id, landed, position);
		self.prune_completions(flow_id);
	}

	fn reader_floor(&self, flow_id: FlowId) -> Option<CommitVersion> {
		let readers = self.readers.get(&flow_id)?;
		readers.iter().map(|reader| self.positions.get(reader).copied().unwrap_or(CommitVersion(0))).min()
	}

	fn prune_completions(&mut self, flow_id: FlowId) {
		let Some(floor) = self.reader_floor(flow_id) else {
			return;
		};
		let Some(history) = self.completions.get_mut(&flow_id) else {
			return;
		};
		let above = history.partition_point(|entry| entry.commit <= floor);
		history.drain(..above.saturating_sub(1));
	}

	fn record_completion(&mut self, flow_id: FlowId, commit: CommitVersion, position: CommitVersion) {
		let source = self.sources.source(flow_id).unwrap_or(SourceVersion(position.0));
		let landed = self.sources.landed(flow_id, commit);
		let history = self.completions.entry(flow_id).or_default();
		let source = history.back().map_or(source, |last| last.source.max(source));
		let first_source = landed.as_ref().map_or(source, |landed| landed.first).min(source);
		let first_source = history.back().map_or(first_source, |last| last.first_source.max(first_source));
		let output = landed.map_or(CommitOutput::OneSource, |landed| landed.output);
		match history.back_mut() {
			Some(last) if commit < last.commit => return,
			Some(last) if commit == last.commit => {
				last.position = last.position.max(position);
				last.output = take(&mut last.output).or(output);
				return;
			}
			_ => {}
		}
		history.push_back(Completion {
			commit,
			position,
			first_source,
			source,
			output,
		});
		if history.len() > COMPLETION_HISTORY {
			history.pop_front();
		}
	}

	fn complete_through(&self, flow_id: FlowId, read_to: CommitVersion) -> Option<CommitVersion> {
		let history = self.completions.get(&flow_id)?;
		let above = history.partition_point(|entry| entry.commit <= read_to);
		history.get(above.checked_sub(1)?).map(|entry| entry.position)
	}

	fn commit_through_source(&self, flow_id: FlowId, source: SourceVersion) -> Option<CommitVersion> {
		self.completion_through_source(flow_id, source).map(|entry| entry.commit)
	}

	fn completion_through_source(&self, flow_id: FlowId, source: SourceVersion) -> Option<Completion> {
		let history = self.completions.get(&flow_id)?;
		let above = history.partition_point(|entry| entry.first_source <= source);
		history.get(above.checked_sub(1)?).cloned()
	}

	fn completion_layers(&self, flow_id: FlowId, commit: CommitVersion) -> Option<Arc<ViewLayers>> {
		let history = self.completions.get(&flow_id)?;
		let at = history.partition_point(|entry| entry.commit < commit);
		history.get(at).filter(|entry| entry.commit == commit).and_then(|entry| entry.output.view_layers())
	}

	fn produces_for_lookup(&self, flow_id: FlowId) -> bool {
		self.lookup_producers.values().any(|views| views.values().any(|producer| *producer == flow_id))
	}

	fn commit_through_commit(&self, flow_id: FlowId, commit: CommitVersion) -> Option<CommitVersion> {
		let history = self.completions.get(&flow_id)?;
		let above = history.partition_point(|entry| entry.commit <= commit);
		history.get(above.checked_sub(1)?).map(|entry| entry.commit)
	}

	fn source_through_commit(&self, flow_id: FlowId, commit: CommitVersion) -> Option<SourceVersion> {
		let history = self.completions.get(&flow_id)?;
		let above = history.partition_point(|entry| entry.commit <= commit);
		history.get(above.checked_sub(1)?).map(|entry| entry.source)
	}

	fn readers_of(&self, producer: FlowId) -> Vec<FlowWaker> {
		let Some(readers) = self.readers.get(&producer) else {
			return Vec::new();
		};
		readers.iter().filter_map(|reader| self.wakers.get(reader).cloned()).collect()
	}

	fn link_reader(&mut self, reader: FlowId, upstreams: FlowUpstreams) {
		for producer in upstreams.keys() {
			self.readers.entry(*producer).or_default().insert(reader);
		}
		self.upstreams.insert(reader, Arc::new(upstreams));
	}

	fn unlink_reader(&mut self, reader: FlowId) {
		let Some(previous) = self.upstreams.remove(&reader) else {
			return;
		};
		for producer in previous.keys() {
			if let Some(readers) = self.readers.get_mut(producer) {
				readers.remove(&reader);
				if readers.is_empty() {
					self.readers.remove(producer);
				}
			}
		}
	}
}

impl FlowPositionTracker {
	pub fn new() -> Self {
		Self {
			inner: Arc::new(RwLock::new(FlowProgress::default())),
		}
	}

	pub fn update(&self, flow_id: FlowId, version: CommitVersion) {
		let readers = {
			let mut progress = self.inner.write();
			if !progress.advance_position(flow_id, version) {
				return;
			}
			progress.record_landed(flow_id, version);
			progress.readers_of(flow_id)
		};
		wake(readers);
	}

	pub fn update_committed(
		&self,
		flow_id: FlowId,
		version: CommitVersion,
		commit: CommitVersion,
		source: SourceVersion,
	) {
		self.update_committed_layers(flow_id, version, commit, source, source);
	}

	pub fn update_committed_layers(
		&self,
		flow_id: FlowId,
		version: CommitVersion,
		commit: CommitVersion,
		first: SourceVersion,
		source: SourceVersion,
	) {
		let output = match first < source {
			true => CommitOutput::PerSourceUntracked,
			false => CommitOutput::OneSource,
		};
		self.update_committed_at(flow_id, version, commit, first, source, output);
	}

	pub fn update_committed_at(
		&self,
		flow_id: FlowId,
		version: CommitVersion,
		commit: CommitVersion,
		first: SourceVersion,
		source: SourceVersion,
		output: CommitOutput,
	) {
		let readers = {
			let mut progress = self.inner.write();
			let output = match output {
				CommitOutput::PerSource(_) if !progress.produces_for_lookup(flow_id) => {
					CommitOutput::PerSourceUntracked
				}
				output => output,
			};
			progress.sources.land(
				flow_id,
				Landed {
					commit,
					first,
					output,
				},
			);
			progress.advance_last_commit(flow_id, commit);
			progress.advance_source(flow_id, source);
			if !progress.advance_position(flow_id, version) {
				return;
			}
			progress.record_landed(flow_id, version);
			progress.readers_of(flow_id)
		};
		wake(readers);
	}

	pub fn record_commit(&self, flow_id: FlowId, commit: CommitVersion) {
		self.inner.write().advance_last_commit(flow_id, commit);
	}

	pub fn record_tick(&self, flow_id: FlowId) {
		*self.inner.write().ticks.entry(flow_id).or_insert(0) += 1;
	}

	pub fn ticks(&self) -> Vec<(FlowId, u64)> {
		self.inner.read().ticks.iter().map(|(flow_id, ticks)| (*flow_id, *ticks)).collect()
	}

	pub fn last_commit(&self, flow_id: FlowId) -> Option<CommitVersion> {
		self.inner.read().last_commits.get(&flow_id).copied()
	}

	pub fn upstream_complete_through(&self, flow_id: FlowId, read_to: CommitVersion) -> Option<CommitVersion> {
		self.inner.read().complete_through(flow_id, read_to)
	}

	pub fn commit_through_source(&self, flow_id: FlowId, source: SourceVersion) -> Option<CommitVersion> {
		self.inner.read().commit_through_source(flow_id, source)
	}

	pub fn commit_through_commit(&self, flow_id: FlowId, commit: CommitVersion) -> Option<CommitVersion> {
		self.inner.read().commit_through_commit(flow_id, commit)
	}

	pub fn source_through_commit(&self, flow_id: FlowId, commit: CommitVersion) -> Option<SourceVersion> {
		self.inner.read().source_through_commit(flow_id, commit)
	}

	pub fn restore_completion(&self, flow_id: FlowId, commit: CommitVersion, source: SourceVersion) {
		let mut progress = self.inner.write();
		progress.advance_source(flow_id, source);
		progress.record_completion(flow_id, commit, CommitVersion(source.0.saturating_sub(1)));
	}

	pub fn is_lookup_producer(&self, flow_id: FlowId) -> bool {
		self.inner.read().produces_for_lookup(flow_id)
	}

	pub fn restore_completion_at(&self, producer: FlowId, entry: &CommitEntry) {
		let output = CommitOutput::of(entry);
		let mut progress = self.inner.write();
		progress.sources.land(
			producer,
			Landed {
				commit: entry.version.commit,
				first: entry.first_source(),
				output,
			},
		);
		progress.advance_source(producer, entry.version.source);
		progress.record_completion(
			producer,
			entry.version.commit,
			CommitVersion(entry.version.source.0.saturating_sub(1)),
		);
	}

	pub fn lookup_producers_of(&self, flow_id: FlowId) -> BTreeMap<ViewId, FlowId> {
		self.inner.read().lookup_producers.get(&flow_id).cloned().unwrap_or_default()
	}

	pub fn set_lookup_producers(&self, flow_id: FlowId, producers: BTreeMap<ViewId, FlowId>) {
		let mut progress = self.inner.write();
		if producers.is_empty() {
			progress.lookup_producers.remove(&flow_id);
		} else {
			progress.lookup_producers.insert(flow_id, producers);
		}
	}

	pub fn lookup_versions(&self, flow_id: FlowId) -> FlowLookupVersions {
		FlowLookupVersions {
			tracker: self.clone(),
			flow_id,
		}
	}

	pub fn set_upstreams(&self, flow_id: FlowId, upstreams: FlowUpstreams) {
		let mut progress = self.inner.write();
		progress.unlink_reader(flow_id);
		progress.link_reader(flow_id, upstreams);
	}

	pub fn upstreams(&self, flow_id: FlowId) -> Arc<FlowUpstreams> {
		self.inner.read().upstreams.get(&flow_id).cloned().unwrap_or_default()
	}

	pub fn set_fold_shape(&self, flows: impl IntoIterator<Item = FlowId>, shape: FoldShape) {
		let mut progress = self.inner.write();
		for flow_id in flows {
			progress.fold_shapes.insert(flow_id, shape);
		}
	}

	pub fn fold_shape(&self, flow_id: FlowId) -> FoldShape {
		self.inner.read().fold_shapes.get(&flow_id).copied().unwrap_or(FoldShape::PerSource)
	}

	pub fn set_unit(&self, flow_id: FlowId, head: FlowId) {
		self.inner.write().units.insert(flow_id, head);
	}

	pub fn clear_unit(&self, flow_id: FlowId) {
		self.inner.write().units.remove(&flow_id);
	}

	pub fn units(&self) -> Vec<(FlowId, FlowId)> {
		self.inner.read().units.iter().map(|(flow, head)| (*flow, *head)).collect()
	}

	pub fn has_readers(&self, flow_id: FlowId) -> bool {
		self.inner.read().readers.contains_key(&flow_id)
	}

	pub fn set_waker(&self, flow_id: FlowId, waker: FlowWaker) {
		self.inner.write().wakers.insert(flow_id, waker);
	}

	pub fn wake_flows(&self, flow_ids: impl IntoIterator<Item = FlowId>) {
		wake(self.wakers_of(flow_ids));
	}

	pub fn wake_flows_now(&self, flow_ids: impl IntoIterator<Item = FlowId>) {
		for waker in self.wakers_of(flow_ids) {
			waker.wake_now();
		}
	}

	pub fn set_source_count(&self, flow_id: FlowId, count: usize) {
		self.inner.write().source_counts.insert(flow_id, count);
	}

	pub fn registered_flows(&self) -> Vec<FlowId> {
		let mut flows: Vec<FlowId> = self.inner.read().source_counts.keys().copied().collect();
		flows.sort();
		flows
	}

	fn wakers_of(&self, flow_ids: impl IntoIterator<Item = FlowId>) -> Vec<FlowWaker> {
		let progress = self.inner.read();
		flow_ids.into_iter().filter_map(|flow_id| progress.wakers.get(&flow_id).cloned()).collect()
	}

	pub fn remove(&self, flow_id: FlowId) {
		let mut progress = self.inner.write();
		progress.positions.remove(&flow_id);
		progress.last_commits.remove(&flow_id);
		progress.unlink_reader(flow_id);
		progress.wakers.remove(&flow_id);
		progress.source_counts.remove(&flow_id);
		progress.sources.remove(flow_id);
		progress.lookup_producers.remove(&flow_id);
		progress.units.remove(&flow_id);
		progress.ticks.remove(&flow_id);
		progress.fold_shapes.remove(&flow_id);
	}

	pub fn all(&self) -> HashMap<FlowId, CommitVersion> {
		self.inner.read().positions.clone()
	}
}

pub struct FlowLookupVersions {
	tracker: FlowPositionTracker,
	flow_id: FlowId,
}

impl LookupVersions for FlowLookupVersions {
	fn view_version(&self, view: ViewId, source: SourceVersion) -> Option<CommitVersion> {
		let producer = *self.tracker.inner.read().lookup_producers.get(&self.flow_id)?.get(&view)?;
		self.tracker.commit_through_source(producer, source)
	}

	fn view_commit_through(&self, view: ViewId, commit: CommitVersion) -> Option<CommitVersion> {
		let producer = *self.tracker.inner.read().lookup_producers.get(&self.flow_id)?.get(&view)?;
		self.tracker.commit_through_commit(producer, commit)
	}

	fn view_read(&self, view: ViewId, source: SourceVersion) -> Option<LookupAt> {
		let progress = self.tracker.inner.read();
		let producer = *progress.lookup_producers.get(&self.flow_id)?.get(&view)?;
		let entry = progress.completion_through_source(producer, source)?;
		if entry.output.reads_inside() && entry.first_source < entry.source && source < entry.source {
			return Some(LookupAt::Layered {
				view,
				base: CommitVersion(entry.commit.0 - 1),
				commit: entry.commit,
				through: source,
			});
		}
		Some(LookupAt::Commit(entry.commit))
	}

	fn view_layers(&self, view: ViewId, commit: CommitVersion) -> Option<Arc<ViewLayers>> {
		let progress = self.tracker.inner.read();
		let producer = *progress.lookup_producers.get(&self.flow_id)?.get(&view)?;
		progress.completion_layers(producer, commit)
	}
}

fn wake(readers: Vec<FlowWaker>) {
	for reader in readers {
		reader.wake();
	}
}

impl ConsumerPositions for FlowPositionTracker {
	fn min_position(&self) -> Option<CommitVersion> {
		self.inner.read().positions.values().copied().min()
	}
}

impl Default for FlowPositionTracker {
	fn default() -> Self {
		Self::new()
	}
}

#[cfg(test)]
mod tests {
	use std::{
		mem::forget,
		sync::{
			Arc,
			atomic::{AtomicBool, Ordering},
			mpsc,
		},
	};

	use reifydb_core::{
		actors::flow::FlowActorMessage,
		common::{CommitVersion, SourceVersion},
		interface::catalog::flow::FlowId,
	};
	use reifydb_runtime::{
		actor::{
			context::Context,
			mailbox::ActorRef,
			system::{ActorConfig, ActorSystem},
			traits::{Actor, Directive},
		},
		context::clock::{Clock, MockClock},
	};
	use reifydb_value::value::duration::Duration;
	use rustc_hash::{FxHashMap, FxHashSet};

	use super::{COMPLETION_HISTORY, FlowPositionTracker, FlowProgress, FlowWaker};

	const PRODUCER: FlowId = FlowId(1);
	const READER: FlowId = FlowId(2);

	fn cv(version: u64) -> CommitVersion {
		CommitVersion(version)
	}

	#[test]
	fn a_producer_position_is_not_trusted_until_its_commit_is_read() {
		let mut progress = FlowProgress::default();
		progress.record_completion(PRODUCER, cv(12), cv(10));

		assert_eq!(
			progress.complete_through(PRODUCER, cv(11)),
			None,
			"the commit carrying the output for position 10 is not read yet, so nothing may pass"
		);
		assert_eq!(progress.complete_through(PRODUCER, cv(12)), Some(cv(10)));
	}

	#[test]
	fn a_reader_behind_the_newest_commit_still_resolves_an_older_position() {
		let mut progress = FlowProgress::default();
		progress.record_completion(PRODUCER, cv(10), cv(4));
		progress.record_completion(PRODUCER, cv(20), cv(9));
		progress.record_completion(PRODUCER, cv(30), cv(15));

		assert_eq!(
			progress.complete_through(PRODUCER, cv(25)),
			Some(cv(9)),
			"a reader must get the newest position it has fully read, or an active producer freezes it \
			 forever at its cursor"
		);
		assert_eq!(progress.complete_through(PRODUCER, cv(20)), Some(cv(9)), "an exact commit must resolve");
		assert_eq!(
			progress.complete_through(PRODUCER, cv(9)),
			None,
			"below every recorded commit nothing is proven, and claiming a position would skip output"
		);
	}

	#[test]
	fn pruning_keeps_the_entry_the_slowest_reader_still_needs() {
		let mut progress = FlowProgress::default();
		progress.link_reader(READER, FxHashMap::from_iter([(PRODUCER, FxHashSet::default())]));
		progress.advance_position(READER, cv(25));
		for version in 1..=5u64 {
			progress.advance_last_commit(PRODUCER, cv(version * 10));
			progress.record_landed(PRODUCER, cv(version * 10));
		}

		assert_eq!(
			progress.complete_through(PRODUCER, cv(25)),
			Some(cv(20)),
			"the entry answering the slowest reader must survive, or pruning recreates the freeze it \
			 exists to prevent"
		);
		let oldest = progress.completions.get(&PRODUCER).and_then(|h| h.front()).map(|e| e.commit.0);
		assert_eq!(oldest, Some(20), "everything strictly below that entry can never be asked for again");
	}

	#[test]
	fn a_reader_that_never_advances_holds_the_whole_history() {
		let mut progress = FlowProgress::default();
		progress.link_reader(READER, FxHashMap::from_iter([(PRODUCER, FxHashSet::default())]));
		progress.advance_position(READER, cv(0));
		for version in 1..=40u64 {
			progress.advance_last_commit(PRODUCER, cv(version * 10));
			progress.record_landed(PRODUCER, cv(version * 10));
		}

		assert_eq!(
			progress.completions.get(&PRODUCER).map(|h| h.len()),
			Some(40),
			"a stuck reader must keep its answers reachable, or it can never resolve and never recover"
		);
	}

	#[test]
	fn an_unknown_producer_resolves_to_nothing() {
		let progress = FlowProgress::default();
		assert_eq!(
			progress.complete_through(PRODUCER, cv(100)),
			None,
			"a producer that has never committed proves nothing about what it will emit"
		);
	}

	#[test]
	fn completion_history_keeps_the_newest_pairs_within_its_bound() {
		let mut progress = FlowProgress::default();
		for version in 1..=(COMPLETION_HISTORY as u64 + 10) {
			progress.record_completion(PRODUCER, cv(version * 2), cv(version));
		}

		assert_eq!(
			progress.completions.get(&PRODUCER).map(|h| h.len()),
			Some(COMPLETION_HISTORY),
			"an unbounded history would grow with uptime"
		);
		assert_eq!(
			progress.complete_through(PRODUCER, cv(20)),
			None,
			"a reader that falls off the retained window must not be handed a position it cannot prove"
		);
	}

	#[test]
	fn a_repeated_or_regressing_commit_does_not_extend_the_history() {
		let mut progress = FlowProgress::default();
		progress.record_completion(PRODUCER, cv(20), cv(9));
		progress.record_completion(PRODUCER, cv(20), cv(11));
		progress.record_completion(PRODUCER, cv(15), cv(12));

		assert_eq!(
			progress.completions.get(&PRODUCER).map(|h| h.len()),
			Some(1),
			"the lookup scans for the largest commit at or below a bound, so the history must stay sorted"
		);
		assert_eq!(
			progress.complete_through(PRODUCER, cv(20)),
			Some(cv(11)),
			"consuming further without emitting anything new is still progress the reader may use"
		);
		assert_eq!(
			progress.complete_through(PRODUCER, cv(19)),
			None,
			"a commit that went backwards must not lower the bound a reader already resolved"
		);
	}

	#[test]
	fn a_layered_commit_answers_every_source_from_its_first_layer_on() {
		// A source inside a layered commit mapped to the commit before it reads a state without that layer's
		// rows.
		let tracker = FlowPositionTracker::new();
		tracker.update_committed(PRODUCER, cv(10), cv(10), SourceVersion(10));
		tracker.update_committed_layers(PRODUCER, cv(30), cv(31), SourceVersion(21), SourceVersion(30));

		assert_eq!(tracker.commit_through_source(PRODUCER, SourceVersion(20)), Some(cv(10)));
		assert_eq!(tracker.commit_through_source(PRODUCER, SourceVersion(21)), Some(cv(31)));
		assert_eq!(tracker.commit_through_source(PRODUCER, SourceVersion(25)), Some(cv(31)));
		assert_eq!(
			tracker.source_through_commit(PRODUCER, cv(31)),
			Some(SourceVersion(30)),
			"completion still runs through the last layer"
		);
	}

	#[test]
	fn a_checkpoint_carrying_no_output_records_at_the_commit_that_last_landed() {
		let tracker = FlowPositionTracker::new();
		tracker.update_committed(PRODUCER, cv(34), cv(22), SourceVersion(34));
		tracker.update_committed(PRODUCER, cv(38), cv(0), SourceVersion(38));

		assert_eq!(
			tracker.upstream_complete_through(PRODUCER, cv(38)),
			Some(cv(38)),
			"an empty slice commits at version none, and taking that literally drops the advance and \
			 pins every reader at the last version that carried rows"
		);
	}

	#[test]
	fn a_position_published_without_a_commit_still_reaches_readers() {
		let tracker = FlowPositionTracker::new();
		tracker.update_committed(PRODUCER, cv(4), cv(10), SourceVersion(4));
		tracker.update(PRODUCER, cv(7));

		assert_eq!(
			tracker.upstream_complete_through(PRODUCER, cv(10)),
			Some(cv(7)),
			"a producer that consumed further and emitted nothing has nothing left to land, so a reader \
			 at its last commit must not be held back"
		);
	}

	struct WakeRecorder {
		received: mpsc::Sender<&'static str>,
	}

	impl Actor for WakeRecorder {
		type State = ();
		type Message = FlowActorMessage;

		fn init(&self, _ctx: &Context<Self::Message>) {}

		fn handle(&self, _state: &mut (), msg: Self::Message, _ctx: &Context<Self::Message>) -> Directive {
			let kind = match msg {
				FlowActorMessage::Wake => "wake",
				FlowActorMessage::Sample => "sample",
				FlowActorMessage::Tick => "tick",
				_ => "other",
			};
			self.received.send(kind).expect("the test still listens for flow messages");
			Directive::Continue
		}

		fn config(&self) -> ActorConfig {
			ActorConfig::new()
		}
	}

	fn next_message(received: &mpsc::Receiver<&'static str>) -> &'static str {
		received.recv_timeout(Duration::from_seconds_const(10).to_std())
			.expect("the recorder must receive the next message")
	}

	fn send_marker(reader: &ActorRef<FlowActorMessage>, marker: FlowActorMessage) {
		assert!(reader.send(marker).is_ok(), "send marker");
	}

	#[test]
	fn upstream_steps_to_a_reader_with_a_pending_wake_merge_into_one_message() {
		// An upstream step must not queue a second wake on a reader already woken, or the flow pool floods.
		let clock = Clock::testing();
		let actor_system = ActorSystem::testing(clock.clone());
		let (sender, received) = mpsc::channel();
		let reader = actor_system
			.spawner()
			.spawn_flow(
				"wake-recorder",
				WakeRecorder {
					received: sender,
				},
			)
			.actor_ref()
			.clone();
		let pending = Arc::new(AtomicBool::new(false));
		let tracker = FlowPositionTracker::new();
		tracker.set_upstreams(READER, FxHashMap::from_iter([(PRODUCER, FxHashSet::default())]));
		tracker.set_waker(READER, FlowWaker::new(reader.clone(), Arc::clone(&pending), clock));

		tracker.update(PRODUCER, CommitVersion(1));
		tracker.update(PRODUCER, CommitVersion(2));
		tracker.update_committed(PRODUCER, CommitVersion(3), CommitVersion(3), SourceVersion(3));
		send_marker(&reader, FlowActorMessage::Sample);
		assert_eq!(next_message(&received), "wake", "the first upstream step must wake the reader");
		assert_eq!(
			next_message(&received),
			"sample",
			"upstream steps before the reader drains must merge into the first wake"
		);

		pending.store(false, Ordering::SeqCst);
		tracker.update_committed(PRODUCER, CommitVersion(4), CommitVersion(4), SourceVersion(4));
		send_marker(&reader, FlowActorMessage::Tick);
		assert_eq!(
			next_message(&received),
			"wake",
			"a step after the reader cleared its wake must wake it again, or it never sees that step"
		);
		assert_eq!(next_message(&received), "tick", "exactly one wake must follow the cleared flag");
	}

	fn coalescing_harness()
	-> (Clock, FlowPositionTracker, ActorRef<FlowActorMessage>, Arc<AtomicBool>, mpsc::Receiver<&'static str>) {
		let clock = Clock::Mock(MockClock::from_millis(0));
		let actor_system = ActorSystem::testing(Clock::testing());
		let (sender, received) = mpsc::channel();
		let reader = actor_system
			.spawner()
			.spawn_flow(
				"wake-recorder",
				WakeRecorder {
					received: sender,
				},
			)
			.actor_ref()
			.clone();
		forget(actor_system);
		let pending = Arc::new(AtomicBool::new(false));
		let tracker = FlowPositionTracker::new();
		tracker.set_upstreams(READER, FxHashMap::from_iter([(PRODUCER, FxHashSet::default())]));
		tracker.set_waker(READER, FlowWaker::new(reader.clone(), Arc::clone(&pending), clock.clone()));
		(clock, tracker, reader, pending, received)
	}

	#[test]
	fn a_folding_reader_merges_wakes_while_pending_and_is_woken_after_every_drain() {
		// a wake dropped after the reader cleared pending leaves it stranded until an unrelated drain.
		let (clock, tracker, reader, pending, received) = coalescing_harness();

		tracker.update(PRODUCER, CommitVersion(1));
		assert_eq!(next_message(&received), "wake", "the first upstream step must wake a folding reader");

		tracker.update(PRODUCER, CommitVersion(2));
		send_marker(&reader, FlowActorMessage::Sample);
		assert_eq!(
			next_message(&received),
			"sample",
			"a step while the first wake is still pending must merge into it, or the reader never folds"
		);

		pending.store(false, Ordering::SeqCst);
		tracker.update(PRODUCER, CommitVersion(3));
		send_marker(&reader, FlowActorMessage::Tick);
		assert_eq!(
			next_message(&received),
			"wake",
			"a step inside the window after the reader drained must wake it, or it stalls until an unrelated drain"
		);
		assert_eq!(next_message(&received), "tick", "exactly one wake must follow the drained flag");

		clock.as_mock().expect("the harness drives a mock clock").advance_millis(21);
		pending.store(false, Ordering::SeqCst);
		tracker.update(PRODUCER, CommitVersion(4));
		assert_eq!(next_message(&received), "wake", "a step after the window elapses must wake the reader");
	}

	#[test]
	fn the_full_wake_ignores_the_coalesce_window() {
		// The periodic full wake is the liveness backstop that makes dropping a wake safe, so it must never
		// itself be dropped.
		let (_clock, tracker, reader, pending, received) = coalescing_harness();

		tracker.update(PRODUCER, CommitVersion(1));
		assert_eq!(next_message(&received), "wake", "the first upstream step must wake a folding reader");

		pending.store(false, Ordering::SeqCst);
		tracker.wake_flows_now([READER]);
		send_marker(&reader, FlowActorMessage::Sample);
		assert_eq!(
			next_message(&received),
			"wake",
			"the full wake must reach a reader inside its coalesce window, or liveness rests on nothing"
		);
		assert_eq!(next_message(&received), "sample", "exactly one wake must follow the full wake");
	}

	#[test]
	fn a_flow_has_readers_only_while_another_flow_lists_it_upstream() {
		// The committer split keys off this flag, so it must follow every upstream link and unlink exactly.
		let tracker = FlowPositionTracker::new();
		assert!(!tracker.has_readers(PRODUCER), "an unlinked flow must have no readers");

		tracker.set_upstreams(READER, FxHashMap::from_iter([(PRODUCER, FxHashSet::default())]));
		assert!(tracker.has_readers(PRODUCER), "a linked producer must have readers");
		assert!(!tracker.has_readers(READER), "the reader itself is read by nobody");

		tracker.set_upstreams(READER, FxHashMap::default());
		assert!(!tracker.has_readers(PRODUCER), "relinking the reader without the producer must clear it");

		tracker.set_upstreams(READER, FxHashMap::from_iter([(PRODUCER, FxHashSet::default())]));
		tracker.remove(READER);
		assert!(!tracker.has_readers(PRODUCER), "removing the last reader must clear it");
	}
}

#[cfg(test)]
mod lookup_tests {
	use std::collections::BTreeMap;

	use reifydb_core::{
		common::{CommitVersion, SourceVersion},
		interface::catalog::{flow::FlowId, id::ViewId},
	};
	use reifydb_flow_async::transaction::LookupVersions;
	use rustc_hash::{FxHashMap, FxHashSet};

	use super::FlowPositionTracker;

	const PRODUCER: FlowId = FlowId(1);
	const READER: FlowId = FlowId(2);
	const PRICES: ViewId = ViewId(7);

	fn cv(version: u64) -> CommitVersion {
		CommitVersion(version)
	}

	fn sv(version: u64) -> SourceVersion {
		SourceVersion(version)
	}

	fn sources(tracker: &FlowPositionTracker, flow: FlowId) -> Vec<u64> {
		tracker.inner
			.read()
			.completions
			.get(&flow)
			.map(|h| h.iter().map(|e| e.source.0).collect())
			.unwrap_or_default()
	}

	#[test]
	fn commit_through_source_answers_by_source_not_by_position() {
		// Keyed by position, source 14 would read C20 and miss the source-12 rows committed at C30.
		let tracker = FlowPositionTracker::new();
		tracker.update_committed(PRODUCER, cv(5), cv(10), sv(5));
		tracker.update_committed(PRODUCER, cv(8), cv(20), sv(8));
		tracker.update_committed(PRODUCER, cv(15), cv(30), sv(12));

		assert_eq!(tracker.commit_through_source(PRODUCER, sv(5)), Some(cv(10)));
		assert_eq!(tracker.commit_through_source(PRODUCER, sv(9)), Some(cv(20)));
		assert_eq!(
			tracker.commit_through_source(PRODUCER, sv(14)),
			Some(cv(30)),
			"source 12 landed at C30, so a lookup at source 14 must read C30"
		);
		assert_eq!(
			tracker.commit_through_source(PRODUCER, sv(4)),
			None,
			"no commit covers source 4, so the lookup must not be handed a version"
		);
	}

	#[test]
	fn commit_through_commit_answers_the_last_commit_at_or_below_a_version() {
		// A lookup below its lease floor may read at the floor only if this finds no commit after its own.
		let tracker = FlowPositionTracker::new();
		tracker.update_committed(PRODUCER, cv(5), cv(10), sv(5));
		tracker.update_committed(PRODUCER, cv(8), cv(20), sv(8));

		assert_eq!(tracker.commit_through_commit(PRODUCER, cv(19)), Some(cv(10)));
		assert_eq!(tracker.commit_through_commit(PRODUCER, cv(20)), Some(cv(20)));
		assert_eq!(tracker.commit_through_commit(PRODUCER, cv(9)), None, "no commit at or below 9");
	}

	#[test]
	fn a_tick_between_two_sourced_commits_never_lowers_a_completion_source() {
		// A tick must keep the last slice's source, otherwise the history unsorts and source lookups miss rows.
		let tracker = FlowPositionTracker::new();
		tracker.update_committed(PRODUCER, cv(10), cv(20), sv(10));
		tracker.record_commit(PRODUCER, cv(25));
		tracker.update(PRODUCER, cv(12));
		tracker.update_committed(PRODUCER, cv(15), cv(30), sv(15));

		let recorded = sources(&tracker, PRODUCER);
		assert_eq!(recorded, vec![10, 10, 15], "each landing must keep or raise the source");
		assert!(recorded.is_sorted(), "sources must never decrease across a tick");
		assert_eq!(
			tracker.commit_through_source(PRODUCER, sv(12)),
			Some(cv(25)),
			"the tick commit holds everything through source 10 plus the tick's own output"
		);
		assert_eq!(tracker.commit_through_source(PRODUCER, sv(15)), Some(cv(30)));
		assert_eq!(tracker.commit_through_source(PRODUCER, sv(9)), None);
	}

	#[test]
	fn a_lower_source_after_a_higher_one_is_clamped_not_recorded() {
		// A lower stamp after a higher one must never unsort the history, otherwise the answer misses rows.
		let tracker = FlowPositionTracker::new();
		tracker.update_committed(PRODUCER, cv(10), cv(20), sv(10));
		tracker.update_committed(PRODUCER, cv(11), cv(30), sv(7));

		assert_eq!(sources(&tracker, PRODUCER), vec![10, 10]);
		assert_eq!(tracker.commit_through_source(PRODUCER, sv(10)), Some(cv(30)));
	}

	#[test]
	fn an_equal_commit_keeps_its_first_source() {
		// An empty slice must keep the commit's first source, otherwise a lookup between the two sources finds
		// no commit.
		let tracker = FlowPositionTracker::new();
		tracker.update_committed(PRODUCER, cv(10), cv(20), sv(10));
		tracker.update_committed(PRODUCER, cv(14), cv(0), sv(14));

		assert_eq!(sources(&tracker, PRODUCER), vec![10]);
		assert_eq!(tracker.commit_through_source(PRODUCER, sv(12)), Some(cv(20)));
		assert_eq!(tracker.commit_through_source(PRODUCER, sv(14)), Some(cv(20)));
	}

	#[test]
	fn lookup_versions_resolve_the_view_through_its_producer() {
		// The operator only knows the view; without the producer map it cannot find whose commits to read.
		let tracker = FlowPositionTracker::new();
		tracker.update_committed(PRODUCER, cv(8), cv(20), sv(8));
		tracker.set_lookup_producers(READER, BTreeMap::from([(PRICES, PRODUCER)]));
		let versions = tracker.lookup_versions(READER);

		assert_eq!(versions.view_version(PRICES, sv(9)), Some(cv(20)));
		assert_eq!(versions.view_version(ViewId(8), sv(9)), None, "an unmapped view has no producer");
		assert_eq!(
			tracker.lookup_versions(PRODUCER).view_version(PRICES, sv(9)),
			None,
			"the map is per reading flow"
		);

		tracker.remove(READER);
		assert_eq!(versions.view_version(PRICES, sv(9)), None, "a removed reader keeps no producer map");
	}

	#[test]
	fn pruning_for_a_lookup_reader_keeps_the_entry_its_next_source_needs() {
		// Pruning must keep the newest entry at or below the reader, otherwise IP2 fires on a version that
		// exists.
		let tracker = FlowPositionTracker::new();
		tracker.set_upstreams(READER, FxHashMap::from_iter([(PRODUCER, FxHashSet::default())]));
		tracker.update(READER, cv(25));
		for step in 1..=5u64 {
			tracker.update_committed(PRODUCER, cv(step * 10), cv(step * 10), sv(step * 10));
		}

		assert_eq!(tracker.commit_through_source(PRODUCER, sv(26)), Some(cv(20)));
		assert_eq!(tracker.commit_through_source(PRODUCER, sv(50)), Some(cv(50)));
	}
}