1use std::collections::BTreeMap;
4use std::num::NonZeroUsize;
5use std::sync::{
6 atomic::{AtomicBool, AtomicU64, Ordering},
7 Arc,
8};
9
10use crate::{RecordsError, RecordsResult};
11
12pub const DEFAULT_STREAM_CHUNK_POINTS: usize = 16_384;
14pub const DEFAULT_STREAM_MEMORY_BUDGET_BYTES: u64 = 256 * 1024 * 1024;
16pub const STREAMING_RECEIPT_SCHEMA: &str = "spatialrust.streaming.receipt";
18pub const STREAMING_RECEIPT_VERSION: u32 = 1;
20
21#[derive(Clone, Copy, Debug, PartialEq, Eq)]
23pub struct MemoryBudget {
24 limit_bytes: u64,
25}
26
27impl MemoryBudget {
28 pub fn new(limit_bytes: u64) -> RecordsResult<Self> {
30 if limit_bytes == 0 {
31 return Err(RecordsError::InvalidConfiguration(
32 "streaming memory budget must be positive".into(),
33 ));
34 }
35 Ok(Self { limit_bytes })
36 }
37
38 #[must_use]
40 pub const fn limit_bytes(self) -> u64 {
41 self.limit_bytes
42 }
43}
44
45impl Default for MemoryBudget {
46 fn default() -> Self {
47 Self { limit_bytes: DEFAULT_STREAM_MEMORY_BUDGET_BYTES }
48 }
49}
50
51#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
53pub enum StreamOrdering {
54 #[default]
56 Source,
57 Deterministic,
59}
60
61#[derive(Clone, Debug, PartialEq, Eq)]
63pub struct StreamOptions {
64 chunk_points: NonZeroUsize,
65 memory_budget: MemoryBudget,
66 prefetch_chunks: usize,
67 ordering: StreamOrdering,
68}
69
70impl StreamOptions {
71 pub fn new(chunk_points: usize, memory_budget: MemoryBudget) -> RecordsResult<Self> {
73 let chunk_points = NonZeroUsize::new(chunk_points).ok_or_else(|| {
74 RecordsError::InvalidConfiguration("stream chunk_points must be positive".into())
75 })?;
76 Ok(Self {
77 chunk_points,
78 memory_budget,
79 prefetch_chunks: 0,
80 ordering: StreamOrdering::Source,
81 })
82 }
83
84 #[must_use]
86 pub const fn with_prefetch_chunks(mut self, prefetch_chunks: usize) -> Self {
87 self.prefetch_chunks = prefetch_chunks;
88 self
89 }
90
91 #[must_use]
93 pub const fn with_ordering(mut self, ordering: StreamOrdering) -> Self {
94 self.ordering = ordering;
95 self
96 }
97
98 #[must_use]
100 pub const fn chunk_points(&self) -> usize {
101 self.chunk_points.get()
102 }
103
104 #[must_use]
106 pub const fn memory_budget(&self) -> MemoryBudget {
107 self.memory_budget
108 }
109
110 #[must_use]
112 pub const fn prefetch_chunks(&self) -> usize {
113 self.prefetch_chunks
114 }
115
116 #[must_use]
118 pub const fn ordering(&self) -> StreamOrdering {
119 self.ordering
120 }
121}
122
123impl Default for StreamOptions {
124 fn default() -> Self {
125 Self {
126 chunk_points: NonZeroUsize::new(DEFAULT_STREAM_CHUNK_POINTS)
127 .expect("default stream chunk size is non-zero"),
128 memory_budget: MemoryBudget::default(),
129 prefetch_chunks: 0,
130 ordering: StreamOrdering::Source,
131 }
132 }
133}
134
135#[derive(Debug)]
136struct MemoryTrackerInner {
137 limit_bytes: u64,
138 current_bytes: AtomicU64,
139 peak_bytes: AtomicU64,
140}
141
142#[derive(Clone, Debug)]
147pub struct MemoryTracker {
148 inner: Arc<MemoryTrackerInner>,
149}
150
151impl MemoryTracker {
152 #[must_use]
154 pub fn new(budget: MemoryBudget) -> Self {
155 Self {
156 inner: Arc::new(MemoryTrackerInner {
157 limit_bytes: budget.limit_bytes,
158 current_bytes: AtomicU64::new(0),
159 peak_bytes: AtomicU64::new(0),
160 }),
161 }
162 }
163
164 pub fn try_reserve(&self, bytes: u64) -> RecordsResult<MemoryReservation> {
166 let limit = self.inner.limit_bytes;
167 let mut current = self.inner.current_bytes.load(Ordering::Acquire);
168 loop {
169 let Some(next) = current.checked_add(bytes).filter(|next| *next <= limit) else {
170 return Err(RecordsError::MemoryBudgetExceeded {
171 requested: bytes,
172 current,
173 limit,
174 });
175 };
176 match self.inner.current_bytes.compare_exchange_weak(
177 current,
178 next,
179 Ordering::AcqRel,
180 Ordering::Acquire,
181 ) {
182 Ok(_) => {
183 self.inner.peak_bytes.fetch_max(next, Ordering::AcqRel);
184 return Ok(MemoryReservation { tracker: self.clone(), bytes });
185 }
186 Err(observed) => current = observed,
187 }
188 }
189 }
190
191 #[must_use]
193 pub fn snapshot(&self) -> MemorySnapshot {
194 MemorySnapshot {
195 current_bytes: self.inner.current_bytes.load(Ordering::Acquire),
196 peak_bytes: self.inner.peak_bytes.load(Ordering::Acquire),
197 limit_bytes: self.inner.limit_bytes,
198 }
199 }
200}
201
202#[derive(Clone, Copy, Debug, PartialEq, Eq)]
204pub struct MemorySnapshot {
205 pub current_bytes: u64,
207 pub peak_bytes: u64,
209 pub limit_bytes: u64,
211}
212
213#[derive(Debug)]
215pub struct MemoryReservation {
216 tracker: MemoryTracker,
217 bytes: u64,
218}
219
220impl MemoryReservation {
221 #[must_use]
223 pub const fn bytes(&self) -> u64 {
224 self.bytes
225 }
226
227 pub fn shrink_to(&mut self, bytes: u64) -> RecordsResult<()> {
229 if bytes > self.bytes {
230 return Err(RecordsError::InvalidConfiguration(format!(
231 "cannot grow a memory reservation from {} to {bytes} bytes",
232 self.bytes
233 )));
234 }
235 let released = self.bytes - bytes;
236 if released > 0 {
237 let previous = self.tracker.inner.current_bytes.fetch_sub(released, Ordering::AcqRel);
238 debug_assert!(previous >= released, "memory reservation accounting underflow");
239 self.bytes = bytes;
240 }
241 Ok(())
242 }
243}
244
245impl Drop for MemoryReservation {
246 fn drop(&mut self) {
247 let previous = self.tracker.inner.current_bytes.fetch_sub(self.bytes, Ordering::AcqRel);
248 debug_assert!(previous >= self.bytes, "memory reservation accounting underflow");
249 }
250}
251
252#[derive(Clone, Debug, Default)]
254pub struct CancellationToken {
255 cancelled: Arc<AtomicBool>,
256}
257
258impl CancellationToken {
259 pub fn cancel(&self) {
261 self.cancelled.store(true, Ordering::Release);
262 }
263
264 #[must_use]
266 pub fn is_cancelled(&self) -> bool {
267 self.cancelled.load(Ordering::Acquire)
268 }
269
270 pub fn check(&self) -> RecordsResult<()> {
272 if self.is_cancelled() {
273 Err(RecordsError::Cancelled)
274 } else {
275 Ok(())
276 }
277 }
278}
279
280#[cfg_attr(feature = "receipt-json", derive(serde::Serialize, serde::Deserialize))]
282#[cfg_attr(feature = "receipt-json", serde(rename_all = "snake_case"))]
283#[cfg_attr(feature = "receipt-json", serde(deny_unknown_fields))]
284#[derive(Clone, Copy, Debug, PartialEq, Eq)]
285pub enum StreamingTransferDirection {
286 HostToDevice,
288 DeviceToHost,
290 DeviceToDevice,
292}
293
294#[cfg_attr(feature = "receipt-json", derive(serde::Serialize, serde::Deserialize))]
296#[cfg_attr(feature = "receipt-json", serde(deny_unknown_fields))]
297#[derive(Clone, Debug, PartialEq, Eq)]
298pub struct StreamingTransferReceipt {
299 pub name: String,
301 pub direction: StreamingTransferDirection,
303 pub bytes: u64,
305}
306
307#[cfg_attr(feature = "receipt-json", derive(serde::Serialize, serde::Deserialize))]
309#[cfg_attr(feature = "receipt-json", serde(deny_unknown_fields))]
310#[derive(Clone, Debug, PartialEq, Eq)]
311pub struct StreamingPhaseReceipt {
312 pub elapsed_ns: u64,
314 pub allocated_bytes: u64,
316}
317
318#[cfg_attr(feature = "receipt-json", derive(serde::Serialize, serde::Deserialize))]
320#[cfg_attr(feature = "receipt-json", serde(deny_unknown_fields))]
321#[derive(Clone, Debug, PartialEq, Eq)]
322pub struct StreamingReceipt {
323 schema: String,
324 version: u32,
325 source_id: String,
326 input_points: u64,
327 output_points: u64,
328 chunks_read: u64,
329 chunks_written: u64,
330 bytes_read: u64,
331 bytes_written: u64,
332 peak_tracked_bytes: u64,
333 spilled_bytes: u64,
334 phases: BTreeMap<String, StreamingPhaseReceipt>,
335 transfers: Vec<StreamingTransferReceipt>,
336}
337
338impl StreamingReceipt {
339 pub fn new(source_id: impl Into<String>) -> RecordsResult<Self> {
341 let source_id = source_id.into();
342 if source_id.trim().is_empty() {
343 return Err(RecordsError::InvalidReceipt("source_id must not be empty".into()));
344 }
345 Ok(Self {
346 schema: STREAMING_RECEIPT_SCHEMA.into(),
347 version: STREAMING_RECEIPT_VERSION,
348 source_id,
349 input_points: 0,
350 output_points: 0,
351 chunks_read: 0,
352 chunks_written: 0,
353 bytes_read: 0,
354 bytes_written: 0,
355 peak_tracked_bytes: 0,
356 spilled_bytes: 0,
357 phases: BTreeMap::new(),
358 transfers: Vec::new(),
359 })
360 }
361
362 pub fn record_input_chunk(&mut self, points: u64, bytes: u64) -> RecordsResult<()> {
364 checked_add(&mut self.input_points, points, "input_points")?;
365 checked_add(&mut self.bytes_read, bytes, "bytes_read")?;
366 checked_add(&mut self.chunks_read, 1, "chunks_read")
367 }
368
369 pub fn record_output_chunk(&mut self, points: u64, bytes: u64) -> RecordsResult<()> {
371 checked_add(&mut self.output_points, points, "output_points")?;
372 checked_add(&mut self.bytes_written, bytes, "bytes_written")?;
373 checked_add(&mut self.chunks_written, 1, "chunks_written")
374 }
375
376 pub fn record_spill(&mut self, bytes: u64) -> RecordsResult<()> {
378 checked_add(&mut self.spilled_bytes, bytes, "spilled_bytes")
379 }
380
381 pub fn capture_memory(&mut self, tracker: &MemoryTracker) {
383 self.peak_tracked_bytes = self.peak_tracked_bytes.max(tracker.snapshot().peak_bytes);
384 }
385
386 pub fn record_phase(
388 &mut self,
389 name: impl Into<String>,
390 elapsed_ns: u64,
391 allocated_bytes: u64,
392 ) -> RecordsResult<()> {
393 let name = name.into();
394 if name.trim().is_empty() {
395 return Err(RecordsError::InvalidReceipt("phase name must not be empty".into()));
396 }
397 self.phases.insert(name, StreamingPhaseReceipt { elapsed_ns, allocated_bytes });
398 Ok(())
399 }
400
401 pub fn record_transfer(
403 &mut self,
404 name: impl Into<String>,
405 direction: StreamingTransferDirection,
406 bytes: u64,
407 ) -> RecordsResult<()> {
408 let name = name.into();
409 if name.trim().is_empty() {
410 return Err(RecordsError::InvalidReceipt("transfer name must not be empty".into()));
411 }
412 self.transfers.push(StreamingTransferReceipt { name, direction, bytes });
413 Ok(())
414 }
415
416 pub fn validate(&self) -> RecordsResult<()> {
418 if self.schema != STREAMING_RECEIPT_SCHEMA || self.version != STREAMING_RECEIPT_VERSION {
419 return Err(RecordsError::InvalidReceipt(format!(
420 "expected {STREAMING_RECEIPT_SCHEMA} v{STREAMING_RECEIPT_VERSION}, found {} v{}",
421 self.schema, self.version
422 )));
423 }
424 if self.source_id.trim().is_empty() {
425 return Err(RecordsError::InvalidReceipt("source_id must not be empty".into()));
426 }
427 if self.phases.keys().any(|name| name.trim().is_empty()) {
428 return Err(RecordsError::InvalidReceipt("phase name must not be empty".into()));
429 }
430 if self.transfers.iter().any(|transfer| transfer.name.trim().is_empty()) {
431 return Err(RecordsError::InvalidReceipt("transfer name must not be empty".into()));
432 }
433 Ok(())
434 }
435
436 #[cfg(feature = "receipt-json")]
438 pub fn to_json(&self) -> RecordsResult<String> {
439 self.validate()?;
440 serde_json::to_string_pretty(self)
441 .map_err(|error| RecordsError::InvalidReceipt(error.to_string()))
442 }
443
444 #[cfg(feature = "receipt-json")]
446 pub fn from_json(json: &str) -> RecordsResult<Self> {
447 let receipt: Self = serde_json::from_str(json)
448 .map_err(|error| RecordsError::InvalidReceipt(error.to_string()))?;
449 receipt.validate()?;
450 Ok(receipt)
451 }
452
453 #[must_use]
455 pub const fn version(&self) -> u32 {
456 self.version
457 }
458
459 #[must_use]
461 pub fn source_id(&self) -> &str {
462 &self.source_id
463 }
464
465 #[must_use]
467 pub const fn input_points(&self) -> u64 {
468 self.input_points
469 }
470
471 #[must_use]
473 pub const fn output_points(&self) -> u64 {
474 self.output_points
475 }
476
477 #[must_use]
479 pub const fn chunks_read(&self) -> u64 {
480 self.chunks_read
481 }
482
483 #[must_use]
485 pub const fn chunks_written(&self) -> u64 {
486 self.chunks_written
487 }
488
489 #[must_use]
491 pub const fn bytes_read(&self) -> u64 {
492 self.bytes_read
493 }
494
495 #[must_use]
497 pub const fn bytes_written(&self) -> u64 {
498 self.bytes_written
499 }
500
501 #[must_use]
503 pub const fn peak_tracked_bytes(&self) -> u64 {
504 self.peak_tracked_bytes
505 }
506
507 #[must_use]
509 pub const fn spilled_bytes(&self) -> u64 {
510 self.spilled_bytes
511 }
512
513 #[must_use]
515 pub const fn phases(&self) -> &BTreeMap<String, StreamingPhaseReceipt> {
516 &self.phases
517 }
518
519 #[must_use]
521 pub fn transfers(&self) -> &[StreamingTransferReceipt] {
522 &self.transfers
523 }
524}
525
526fn checked_add(target: &mut u64, value: u64, name: &str) -> RecordsResult<()> {
527 *target =
528 target.checked_add(value).ok_or_else(|| RecordsError::ReceiptOverflow(name.to_owned()))?;
529 Ok(())
530}
531
532#[derive(Clone, Copy, Debug, PartialEq, Eq)]
534pub struct StreamingWorkload {
535 pub id: &'static str,
537 pub point_count: u64,
539 pub chunk_points: usize,
541 pub memory_budget_bytes: u64,
543}
544
545const STREAMING_WORKLOADS: [StreamingWorkload; 9] = [
546 workload("stream-1m-16k", 1_000_000, 16_384, 64),
547 workload("stream-1m-64k", 1_000_000, 65_536, 64),
548 workload("stream-1m-256k", 1_000_000, 262_144, 128),
549 workload("stream-10m-16k", 10_000_000, 16_384, 64),
550 workload("stream-10m-64k", 10_000_000, 65_536, 64),
551 workload("stream-10m-256k", 10_000_000, 262_144, 128),
552 workload("stream-100m-16k", 100_000_000, 16_384, 64),
553 workload("stream-100m-64k", 100_000_000, 65_536, 64),
554 workload("stream-100m-256k", 100_000_000, 262_144, 128),
555];
556
557const fn workload(
558 id: &'static str,
559 point_count: u64,
560 chunk_points: usize,
561 memory_mib: u64,
562) -> StreamingWorkload {
563 StreamingWorkload {
564 id,
565 point_count,
566 chunk_points,
567 memory_budget_bytes: memory_mib * 1024 * 1024,
568 }
569}
570
571#[must_use]
573pub const fn canonical_streaming_workloads() -> &'static [StreamingWorkload] {
574 &STREAMING_WORKLOADS
575}
576
577#[cfg(test)]
578mod tests {
579 use std::sync::{Arc, Barrier};
580 use std::thread;
581
582 #[cfg(feature = "receipt-json")]
583 use super::STREAMING_RECEIPT_SCHEMA;
584 use super::{
585 canonical_streaming_workloads, CancellationToken, MemoryBudget, MemoryTracker,
586 StreamOptions, StreamingReceipt, StreamingTransferDirection,
587 };
588 use crate::RecordsError;
589
590 #[test]
591 fn memory_budget_is_fail_closed_and_drop_releases() {
592 let tracker = MemoryTracker::new(MemoryBudget::new(100).unwrap());
593 let first = tracker.try_reserve(60).unwrap();
594 assert_eq!(first.bytes(), 60);
595 let error = tracker.try_reserve(41).unwrap_err();
596 assert!(matches!(
597 error,
598 RecordsError::MemoryBudgetExceeded { requested: 41, current: 60, limit: 100 }
599 ));
600 assert_eq!(tracker.snapshot().current_bytes, 60);
601 drop(first);
602 assert_eq!(tracker.snapshot().current_bytes, 0);
603 assert_eq!(tracker.snapshot().peak_bytes, 60);
604 }
605
606 #[test]
607 fn reservation_overflow_preserves_current_and_peak_counts() {
608 let tracker = MemoryTracker::new(MemoryBudget::new(u64::MAX).unwrap());
609 let reservation = tracker.try_reserve(u64::MAX).unwrap();
610 assert!(matches!(
611 tracker.try_reserve(1),
612 Err(RecordsError::MemoryBudgetExceeded {
613 requested: 1,
614 current: u64::MAX,
615 limit: u64::MAX
616 })
617 ));
618 let zero = tracker.try_reserve(0).unwrap();
619 assert_eq!(tracker.snapshot().current_bytes, u64::MAX);
620 assert_eq!(tracker.snapshot().peak_bytes, u64::MAX);
621 drop(zero);
622 drop(reservation);
623 assert_eq!(tracker.snapshot().current_bytes, 0);
624 assert_eq!(tracker.snapshot().peak_bytes, u64::MAX);
625 }
626
627 #[test]
628 fn reservation_can_shrink_but_never_grow() {
629 let tracker = MemoryTracker::new(MemoryBudget::new(100).unwrap());
630 let mut reservation = tracker.try_reserve(80).unwrap();
631 reservation.shrink_to(30).unwrap();
632 assert_eq!(reservation.bytes(), 30);
633 assert_eq!(tracker.snapshot().current_bytes, 30);
634 assert!(reservation.shrink_to(31).is_err());
635 assert_eq!(tracker.snapshot().current_bytes, 30);
636 }
637
638 #[test]
639 fn concurrent_reservations_never_exceed_limit() {
640 let tracker = MemoryTracker::new(MemoryBudget::new(100).unwrap());
641 let barrier = Arc::new(Barrier::new(3));
642 let mut handles = Vec::new();
643 for _ in 0..2 {
644 let tracker = tracker.clone();
645 let barrier = barrier.clone();
646 handles.push(thread::spawn(move || {
647 barrier.wait();
648 let reservation = tracker.try_reserve(60);
649 barrier.wait();
650 reservation
651 }));
652 }
653 barrier.wait();
654 barrier.wait();
655 let reservations =
656 handles.into_iter().map(|handle| handle.join().unwrap()).collect::<Vec<_>>();
657 assert_eq!(reservations.iter().filter(|result| result.is_ok()).count(), 1);
658 assert!(tracker.snapshot().peak_bytes <= 100);
659 }
660
661 #[test]
662 fn cancellation_is_clone_visible() {
663 let token = CancellationToken::default();
664 let worker = token.clone();
665 token.cancel();
666 assert!(worker.is_cancelled());
667 assert!(matches!(worker.check(), Err(RecordsError::Cancelled)));
668 }
669
670 #[test]
671 fn options_reject_zero_chunk_size() {
672 let error = StreamOptions::new(0, MemoryBudget::default()).unwrap_err();
673 assert!(matches!(error, RecordsError::InvalidConfiguration(_)));
674 }
675
676 #[test]
677 fn receipt_accounts_named_work_without_hidden_transfers() {
678 let tracker = MemoryTracker::new(MemoryBudget::new(1024).unwrap());
679 let reservation = tracker.try_reserve(512).unwrap();
680 let mut receipt = StreamingReceipt::new("synthetic://one-chunk").unwrap();
681 receipt.record_input_chunk(10, 120).unwrap();
682 receipt.record_output_chunk(4, 48).unwrap();
683 receipt.record_phase("transform", 99, 512).unwrap();
684 receipt
685 .record_transfer("explicit-upload", StreamingTransferDirection::HostToDevice, 120)
686 .unwrap();
687 receipt.capture_memory(&tracker);
688 drop(reservation);
689 receipt.validate().unwrap();
690 assert_eq!(receipt.input_points(), 10);
691 assert_eq!(receipt.output_points(), 4);
692 assert_eq!(receipt.peak_tracked_bytes(), 512);
693 assert_eq!(receipt.transfers().len(), 1);
694 }
695
696 #[test]
697 fn receipt_counter_overflow_is_denied_without_wrapping() {
698 let mut receipt = StreamingReceipt::new("synthetic://overflow").unwrap();
699 receipt.input_points = u64::MAX;
700 assert!(matches!(
701 receipt.record_input_chunk(1, 0),
702 Err(RecordsError::ReceiptOverflow(name)) if name == "input_points"
703 ));
704 assert_eq!(receipt.input_points(), u64::MAX);
705 }
706
707 #[cfg(feature = "receipt-json")]
708 #[test]
709 fn json_receipt_roundtrip_is_versioned() {
710 let mut receipt = StreamingReceipt::new("copc://autzen").unwrap();
711 receipt.record_input_chunk(32, 384).unwrap();
712 let json = receipt.to_json().unwrap();
713 let value: serde_json::Value = serde_json::from_str(&json).unwrap();
714 assert_eq!(value["schema"], STREAMING_RECEIPT_SCHEMA);
715 assert_eq!(value["version"], 1);
716 assert_eq!(StreamingReceipt::from_json(&json).unwrap(), receipt);
717 }
718
719 #[cfg(feature = "receipt-json")]
720 #[test]
721 fn json_receipt_rejects_unknown_fields_and_versions() {
722 let receipt = StreamingReceipt::new("copc://autzen").unwrap();
723 let mut value = serde_json::to_value(&receipt).unwrap();
724 value["unexpected"] = serde_json::json!(true);
725 assert!(StreamingReceipt::from_json(&value.to_string()).is_err());
726
727 let mut value = serde_json::to_value(&receipt).unwrap();
728 value["version"] = serde_json::json!(2);
729 assert!(StreamingReceipt::from_json(&value.to_string()).is_err());
730 }
731
732 #[test]
733 fn canonical_workloads_cover_scale_and_chunk_matrix() {
734 let workloads = canonical_streaming_workloads();
735 assert_eq!(workloads.len(), 9);
736 for points in [1_000_000, 10_000_000, 100_000_000] {
737 let chunks = workloads
738 .iter()
739 .filter(|workload| workload.point_count == points)
740 .map(|workload| workload.chunk_points)
741 .collect::<Vec<_>>();
742 assert_eq!(chunks, [16_384, 65_536, 262_144]);
743 }
744 }
745}