Skip to main content

oxirs_cluster/stream_integration/
mod.rs

1//! Real-time streaming integration for OxiRS cluster.
2//!
3//! This module bridges external streaming sources (e.g., Kafka, NATS, or any
4//! byte-oriented channel) with the cluster's RDF triple store, providing:
5//!
6//! - **StreamingTripleConsumer**: consumes RDF triples arriving as streaming messages.
7//! - **StreamingMutationLog**: ordered log of mutations with monotonic sequence numbers.
8//! - **StreamSyncCoordinator**: coordinates stream consumption across cluster nodes
9//!   so that each triple is processed exactly once.
10//! - **StreamingCheckpointer**: persists stream consumption offsets for crash recovery.
11
12use crate::error::{ClusterError, Result};
13use serde::{Deserialize, Serialize};
14use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
15use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
16use std::sync::Arc;
17use std::time::{Duration, SystemTime};
18use tokio::sync::{Mutex, RwLock};
19use tracing::{debug, info};
20
21// ─────────────────────────────────────────────
22//  RDF Triple representation for streaming
23// ─────────────────────────────────────────────
24
25/// A simplified RDF triple for streaming ingestion.
26///
27/// Each component is an N-Triples-style string (IRI, blank node, or literal).
28#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
29pub struct StreamTriple {
30    /// Subject (IRI or blank node).
31    pub subject: String,
32    /// Predicate (IRI).
33    pub predicate: String,
34    /// Object (IRI, blank node, or literal).
35    pub object: String,
36    /// Optional named graph IRI.
37    pub graph: Option<String>,
38}
39
40impl StreamTriple {
41    /// Creates a triple without a named graph.
42    pub fn new(
43        subject: impl Into<String>,
44        predicate: impl Into<String>,
45        object: impl Into<String>,
46    ) -> Self {
47        Self {
48            subject: subject.into(),
49            predicate: predicate.into(),
50            object: object.into(),
51            graph: None,
52        }
53    }
54
55    /// Creates a triple within a named graph.
56    pub fn in_graph(
57        subject: impl Into<String>,
58        predicate: impl Into<String>,
59        object: impl Into<String>,
60        graph: impl Into<String>,
61    ) -> Self {
62        Self {
63            subject: subject.into(),
64            predicate: predicate.into(),
65            object: object.into(),
66            graph: Some(graph.into()),
67        }
68    }
69
70    /// Validates the triple (non-empty fields).
71    pub fn validate(&self) -> Result<()> {
72        if self.subject.is_empty() {
73            return Err(ClusterError::Config(
74                "Triple subject cannot be empty".into(),
75            ));
76        }
77        if self.predicate.is_empty() {
78            return Err(ClusterError::Config(
79                "Triple predicate cannot be empty".into(),
80            ));
81        }
82        if self.object.is_empty() {
83            return Err(ClusterError::Config("Triple object cannot be empty".into()));
84        }
85        Ok(())
86    }
87}
88
89impl std::fmt::Display for StreamTriple {
90    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
91        write!(
92            f,
93            "<{}> <{}> {} .",
94            self.subject, self.predicate, self.object
95        )
96    }
97}
98
99// ─────────────────────────────────────────────
100//  Streaming message
101// ─────────────────────────────────────────────
102
103/// The mutation operation type carried in a streaming message.
104#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
105pub enum MutationOp {
106    /// Insert one or more triples.
107    Insert,
108    /// Delete one or more triples.
109    Delete,
110    /// Truncate (clear) a named graph or default graph.
111    Truncate {
112        /// Named graph to clear; `None` for the default graph.
113        graph: Option<String>,
114    },
115}
116
117/// A message arriving from the streaming source.
118#[derive(Debug, Clone, Serialize, Deserialize)]
119pub struct StreamMessage {
120    /// Source stream/topic identifier.
121    pub stream_id: String,
122    /// Monotonically increasing offset within the source stream.
123    pub offset: u64,
124    /// The mutation to apply.
125    pub op: MutationOp,
126    /// Triples affected by this mutation.
127    pub triples: Vec<StreamTriple>,
128    /// Wall-clock timestamp of the message (Unix ms).
129    pub timestamp_ms: u64,
130}
131
132impl StreamMessage {
133    /// Creates a new insert message.
134    pub fn insert(stream_id: impl Into<String>, offset: u64, triples: Vec<StreamTriple>) -> Self {
135        Self {
136            stream_id: stream_id.into(),
137            offset,
138            op: MutationOp::Insert,
139            triples,
140            timestamp_ms: SystemTime::now()
141                .duration_since(SystemTime::UNIX_EPOCH)
142                .unwrap_or(Duration::ZERO)
143                .as_millis() as u64,
144        }
145    }
146
147    /// Creates a new delete message.
148    pub fn delete(stream_id: impl Into<String>, offset: u64, triples: Vec<StreamTriple>) -> Self {
149        Self {
150            stream_id: stream_id.into(),
151            offset,
152            op: MutationOp::Delete,
153            triples,
154            timestamp_ms: SystemTime::now()
155                .duration_since(SystemTime::UNIX_EPOCH)
156                .unwrap_or(Duration::ZERO)
157                .as_millis() as u64,
158        }
159    }
160}
161
162// ─────────────────────────────────────────────
163//  StreamingTripleConsumer
164// ─────────────────────────────────────────────
165
166/// Configuration for the streaming triple consumer.
167#[derive(Debug, Clone, Serialize, Deserialize)]
168pub struct ConsumerConfig {
169    /// Maximum number of messages to buffer in the internal queue.
170    pub max_buffer_size: usize,
171    /// How long to wait for a batch before flushing (in milliseconds).
172    pub flush_interval_ms: u64,
173    /// Maximum number of triples per flush batch.
174    pub batch_size: usize,
175    /// Whether to validate each triple before inserting.
176    pub validate_triples: bool,
177}
178
179impl Default for ConsumerConfig {
180    fn default() -> Self {
181        Self {
182            max_buffer_size: 10_000,
183            flush_interval_ms: 100,
184            batch_size: 500,
185            validate_triples: true,
186        }
187    }
188}
189
190/// Consumer statistics.
191#[derive(Debug, Default)]
192pub struct ConsumerStats {
193    /// Total messages consumed.
194    pub messages_consumed: AtomicU64,
195    /// Total triples inserted.
196    pub triples_inserted: AtomicU64,
197    /// Total triples deleted.
198    pub triples_deleted: AtomicU64,
199    /// Total validation errors.
200    pub validation_errors: AtomicU64,
201    /// Total bytes processed.
202    pub bytes_processed: AtomicU64,
203}
204
205/// Consumes RDF triples from a streaming source and buffers them for batch
206/// application to the cluster store.
207pub struct StreamingTripleConsumer {
208    config: ConsumerConfig,
209    buffer: Arc<Mutex<VecDeque<StreamMessage>>>,
210    stats: Arc<ConsumerStats>,
211    running: Arc<AtomicBool>,
212}
213
214impl StreamingTripleConsumer {
215    /// Creates a new consumer with the given configuration.
216    pub fn new(config: ConsumerConfig) -> Result<Self> {
217        if config.max_buffer_size == 0 {
218            return Err(ClusterError::Config("max_buffer_size must be > 0".into()));
219        }
220        if config.batch_size == 0 {
221            return Err(ClusterError::Config("batch_size must be > 0".into()));
222        }
223        Ok(Self {
224            config,
225            buffer: Arc::new(Mutex::new(VecDeque::new())),
226            stats: Arc::new(ConsumerStats::default()),
227            running: Arc::new(AtomicBool::new(false)),
228        })
229    }
230
231    /// Submits a streaming message to the consumer's buffer.
232    ///
233    /// Returns `Err` if the buffer is full.
234    pub async fn submit(&self, msg: StreamMessage) -> Result<()> {
235        if self.config.validate_triples {
236            for triple in &msg.triples {
237                triple.validate().map_err(|e| {
238                    self.stats.validation_errors.fetch_add(1, Ordering::Relaxed);
239                    e
240                })?;
241            }
242        }
243
244        let mut buf = self.buffer.lock().await;
245        if buf.len() >= self.config.max_buffer_size {
246            return Err(ClusterError::ResourceLimit(
247                "streaming consumer buffer is full".into(),
248            ));
249        }
250
251        let triple_count = msg.triples.len() as u64;
252        self.stats.messages_consumed.fetch_add(1, Ordering::Relaxed);
253        match &msg.op {
254            MutationOp::Insert => {
255                self.stats
256                    .triples_inserted
257                    .fetch_add(triple_count, Ordering::Relaxed);
258            }
259            MutationOp::Delete => {
260                self.stats
261                    .triples_deleted
262                    .fetch_add(triple_count, Ordering::Relaxed);
263            }
264            MutationOp::Truncate { .. } => {}
265        }
266
267        buf.push_back(msg);
268        Ok(())
269    }
270
271    /// Drains up to `batch_size` messages from the buffer.
272    pub async fn drain_batch(&self) -> Vec<StreamMessage> {
273        let mut buf = self.buffer.lock().await;
274        let n = self.config.batch_size.min(buf.len());
275        buf.drain(..n).collect()
276    }
277
278    /// Returns the current buffer occupancy.
279    pub async fn buffer_len(&self) -> usize {
280        self.buffer.lock().await.len()
281    }
282
283    /// Returns consumer statistics.
284    pub fn stats(&self) -> &ConsumerStats {
285        &self.stats
286    }
287
288    /// Marks the consumer as running.
289    pub fn start(&self) {
290        self.running.store(true, Ordering::SeqCst);
291        info!("StreamingTripleConsumer started");
292    }
293
294    /// Marks the consumer as stopped.
295    pub fn stop(&self) {
296        self.running.store(false, Ordering::SeqCst);
297        info!("StreamingTripleConsumer stopped");
298    }
299
300    /// Returns whether the consumer is currently running.
301    pub fn is_running(&self) -> bool {
302        self.running.load(Ordering::SeqCst)
303    }
304}
305
306// ─────────────────────────────────────────────
307//  StreamingMutationLog
308// ─────────────────────────────────────────────
309
310/// A mutation log entry with a globally monotonic sequence number.
311#[derive(Debug, Clone, Serialize, Deserialize)]
312pub struct MutationEntry {
313    /// Globally assigned sequence number (monotonically increasing).
314    pub seq: u64,
315    /// The originating stream message.
316    pub message: StreamMessage,
317    /// Node that assigned this sequence number.
318    pub assigned_by: u64,
319}
320
321/// An ordered log of streaming mutations with strict sequence-number ordering.
322///
323/// Producers append to the log; consumers read entries in order.  Entries
324/// before `committed_seq` are considered durably applied.
325pub struct StreamingMutationLog {
326    /// Entries indexed by sequence number.
327    log: Arc<RwLock<BTreeMap<u64, MutationEntry>>>,
328    /// Monotonic sequence counter.
329    next_seq: AtomicU64,
330    /// The highest sequence number that has been applied/committed.
331    committed_seq: AtomicU64,
332    /// Maximum log capacity before oldest entries are evicted.
333    max_capacity: usize,
334    /// Node that owns this log instance.
335    node_id: u64,
336}
337
338impl StreamingMutationLog {
339    /// Creates a new mutation log owned by the given node.
340    pub fn new(node_id: u64, max_capacity: usize) -> Result<Self> {
341        if max_capacity == 0 {
342            return Err(ClusterError::Config("max_capacity must be > 0".into()));
343        }
344        Ok(Self {
345            log: Arc::new(RwLock::new(BTreeMap::new())),
346            next_seq: AtomicU64::new(1),
347            committed_seq: AtomicU64::new(0),
348            max_capacity,
349            node_id,
350        })
351    }
352
353    /// Appends a stream message, assigning the next monotonic sequence number.
354    ///
355    /// Returns the assigned sequence number.
356    pub async fn append(&self, message: StreamMessage) -> Result<u64> {
357        let seq = self.next_seq.fetch_add(1, Ordering::SeqCst);
358        let entry = MutationEntry {
359            seq,
360            message,
361            assigned_by: self.node_id,
362        };
363
364        let mut log = self.log.write().await;
365
366        // Evict oldest entries if at capacity.
367        while log.len() >= self.max_capacity {
368            if let Some((&oldest_seq, _)) = log.iter().next() {
369                log.remove(&oldest_seq);
370                debug!(oldest_seq, "Evicted oldest mutation log entry");
371            } else {
372                break;
373            }
374        }
375
376        log.insert(seq, entry);
377        Ok(seq)
378    }
379
380    /// Marks entries up to and including `seq` as committed.
381    pub fn commit_up_to(&self, seq: u64) {
382        let current = self.committed_seq.load(Ordering::SeqCst);
383        if seq > current {
384            self.committed_seq.store(seq, Ordering::SeqCst);
385        }
386    }
387
388    /// Reads all entries in the log with sequence numbers in `[from, to]`.
389    pub async fn read_range(&self, from: u64, to: u64) -> Vec<MutationEntry> {
390        let log = self.log.read().await;
391        log.range(from..=to).map(|(_, e)| e.clone()).collect()
392    }
393
394    /// Returns the highest committed sequence number.
395    pub fn committed_seq(&self) -> u64 {
396        self.committed_seq.load(Ordering::SeqCst)
397    }
398
399    /// Returns the next sequence number that will be assigned.
400    pub fn next_seq(&self) -> u64 {
401        self.next_seq.load(Ordering::SeqCst)
402    }
403
404    /// Returns the number of entries currently in the log.
405    pub async fn len(&self) -> usize {
406        self.log.read().await.len()
407    }
408
409    /// Returns `true` if the log is empty.
410    pub async fn is_empty(&self) -> bool {
411        self.log.read().await.is_empty()
412    }
413}
414
415// ─────────────────────────────────────────────
416//  StreamSyncCoordinator
417// ─────────────────────────────────────────────
418
419/// Tracks which offset each node has processed for a given stream.
420#[derive(Debug, Clone, Serialize, Deserialize)]
421pub struct NodeOffset {
422    /// Node identifier.
423    pub node_id: u64,
424    /// Last committed offset for this stream.
425    pub offset: u64,
426    /// Wall-clock timestamp when this offset was last updated (Unix ms).
427    pub updated_at_ms: u64,
428}
429
430/// Coordinates stream consumption across multiple cluster nodes.
431///
432/// Nodes periodically report their current stream offsets.  The coordinator
433/// derives the cluster-wide minimum committed offset (the "safe offset") that
434/// can be safely evicted from the mutation log.
435pub struct StreamSyncCoordinator {
436    /// Per-node offsets, keyed by (stream_id, node_id).
437    offsets: Arc<RwLock<HashMap<(String, u64), NodeOffset>>>,
438    /// Known stream IDs.
439    streams: Arc<RwLock<HashSet<String>>>,
440}
441
442impl StreamSyncCoordinator {
443    /// Creates a new empty coordinator.
444    pub fn new() -> Self {
445        Self {
446            offsets: Arc::new(RwLock::new(HashMap::new())),
447            streams: Arc::new(RwLock::new(HashSet::new())),
448        }
449    }
450
451    /// Reports a node's current stream offset.
452    pub async fn report_offset(&self, stream_id: impl Into<String>, node_id: u64, offset: u64) {
453        let stream_id = stream_id.into();
454        let now_ms = SystemTime::now()
455            .duration_since(SystemTime::UNIX_EPOCH)
456            .unwrap_or(Duration::ZERO)
457            .as_millis() as u64;
458
459        {
460            let mut streams = self.streams.write().await;
461            streams.insert(stream_id.clone());
462        }
463
464        let mut offsets = self.offsets.write().await;
465        offsets.insert(
466            (stream_id, node_id),
467            NodeOffset {
468                node_id,
469                offset,
470                updated_at_ms: now_ms,
471            },
472        );
473    }
474
475    /// Returns the minimum offset seen across all nodes for a given stream.
476    ///
477    /// This represents the offset that every node has confirmed processing.
478    /// Returns `None` if no nodes have reported for this stream.
479    pub async fn min_offset(&self, stream_id: &str) -> Option<u64> {
480        let offsets = self.offsets.read().await;
481        let relevant: Vec<u64> = offsets
482            .iter()
483            .filter(|((s, _), _)| s == stream_id)
484            .map(|(_, no)| no.offset)
485            .collect();
486        if relevant.is_empty() {
487            None
488        } else {
489            relevant.into_iter().min()
490        }
491    }
492
493    /// Returns the maximum offset seen across all nodes for a given stream.
494    pub async fn max_offset(&self, stream_id: &str) -> Option<u64> {
495        let offsets = self.offsets.read().await;
496        let relevant: Vec<u64> = offsets
497            .iter()
498            .filter(|((s, _), _)| s == stream_id)
499            .map(|(_, no)| no.offset)
500            .collect();
501        if relevant.is_empty() {
502            None
503        } else {
504            relevant.into_iter().max()
505        }
506    }
507
508    /// Returns the lag (max - min) for a stream.  A lag of 0 means all nodes
509    /// are in perfect sync.
510    pub async fn lag(&self, stream_id: &str) -> Option<u64> {
511        let min = self.min_offset(stream_id).await?;
512        let max = self.max_offset(stream_id).await?;
513        Some(max.saturating_sub(min))
514    }
515
516    /// Lists all known stream IDs.
517    pub async fn streams(&self) -> Vec<String> {
518        self.streams.read().await.iter().cloned().collect()
519    }
520
521    /// Returns node offsets for a specific stream.
522    pub async fn node_offsets_for(&self, stream_id: &str) -> Vec<NodeOffset> {
523        let offsets = self.offsets.read().await;
524        offsets
525            .iter()
526            .filter(|((s, _), _)| s == stream_id)
527            .map(|(_, no)| no.clone())
528            .collect()
529    }
530}
531
532impl Default for StreamSyncCoordinator {
533    fn default() -> Self {
534        Self::new()
535    }
536}
537
538// ─────────────────────────────────────────────
539//  StreamingCheckpointer
540// ─────────────────────────────────────────────
541
542/// A checkpoint recording the last processed offset for a stream on a node.
543#[derive(Debug, Clone, Serialize, Deserialize)]
544pub struct Checkpoint {
545    /// Stream identifier.
546    pub stream_id: String,
547    /// Cluster node identifier.
548    pub node_id: u64,
549    /// Last durably processed offset.
550    pub offset: u64,
551    /// Timestamp of the checkpoint (Unix ms).
552    pub checkpoint_ms: u64,
553    /// Version counter for optimistic concurrency.
554    pub version: u64,
555}
556
557/// Persists stream consumption checkpoints in memory (production code would
558/// additionally flush to durable storage such as oxirs-tdb).
559///
560/// Supports:
561/// - Atomic checkpoint updates with version validation.
562/// - Listing all checkpoints for a node or stream.
563/// - Bulk restore of checkpoints (for crash recovery).
564pub struct StreamingCheckpointer {
565    /// Checkpoints indexed by (stream_id, node_id).
566    checkpoints: Arc<RwLock<HashMap<(String, u64), Checkpoint>>>,
567    /// Monotonic version counter.
568    version_counter: AtomicU64,
569}
570
571impl StreamingCheckpointer {
572    /// Creates a new empty checkpointer.
573    pub fn new() -> Self {
574        Self {
575            checkpoints: Arc::new(RwLock::new(HashMap::new())),
576            version_counter: AtomicU64::new(1),
577        }
578    }
579
580    /// Saves (or updates) a checkpoint.
581    ///
582    /// If a checkpoint already exists with a higher version, the update is
583    /// rejected to prevent stale writes from overwriting newer state.
584    pub async fn save(
585        &self,
586        stream_id: impl Into<String>,
587        node_id: u64,
588        offset: u64,
589    ) -> Result<Checkpoint> {
590        let stream_id = stream_id.into();
591        let version = self.version_counter.fetch_add(1, Ordering::SeqCst);
592        let now_ms = SystemTime::now()
593            .duration_since(SystemTime::UNIX_EPOCH)
594            .unwrap_or(Duration::ZERO)
595            .as_millis() as u64;
596
597        let cp = Checkpoint {
598            stream_id: stream_id.clone(),
599            node_id,
600            offset,
601            checkpoint_ms: now_ms,
602            version,
603        };
604
605        let mut cps = self.checkpoints.write().await;
606        let key = (stream_id.clone(), node_id);
607
608        // Reject if existing version is newer.
609        if let Some(existing) = cps.get(&key) {
610            if existing.version > version {
611                return Err(ClusterError::Config(format!(
612                    "Checkpoint version conflict: existing {} > new {}",
613                    existing.version, version
614                )));
615            }
616        }
617
618        cps.insert(key, cp.clone());
619        debug!(stream_id = %stream_id, node_id, offset, version, "Checkpoint saved");
620        Ok(cp)
621    }
622
623    /// Loads the checkpoint for a given stream and node.
624    pub async fn load(&self, stream_id: &str, node_id: u64) -> Option<Checkpoint> {
625        let cps = self.checkpoints.read().await;
626        cps.get(&(stream_id.to_string(), node_id)).cloned()
627    }
628
629    /// Lists all checkpoints for a specific node.
630    pub async fn checkpoints_for_node(&self, node_id: u64) -> Vec<Checkpoint> {
631        let cps = self.checkpoints.read().await;
632        cps.values()
633            .filter(|c| c.node_id == node_id)
634            .cloned()
635            .collect()
636    }
637
638    /// Lists all checkpoints for a specific stream.
639    pub async fn checkpoints_for_stream(&self, stream_id: &str) -> Vec<Checkpoint> {
640        let cps = self.checkpoints.read().await;
641        cps.values()
642            .filter(|c| c.stream_id == stream_id)
643            .cloned()
644            .collect()
645    }
646
647    /// Bulk-restores checkpoints (e.g., from durable storage after a restart).
648    pub async fn restore(&self, checkpoints: Vec<Checkpoint>) {
649        let mut cps = self.checkpoints.write().await;
650        for cp in checkpoints {
651            let key = (cp.stream_id.clone(), cp.node_id);
652            cps.insert(key, cp);
653        }
654        info!("Checkpoint store restored");
655    }
656
657    /// Returns the total number of checkpoints stored.
658    pub async fn count(&self) -> usize {
659        self.checkpoints.read().await.len()
660    }
661}
662
663impl Default for StreamingCheckpointer {
664    fn default() -> Self {
665        Self::new()
666    }
667}
668
669// ─────────────────────────────────────────────
670//  Tests
671// ─────────────────────────────────────────────
672
673#[cfg(test)]
674mod tests {
675    use super::*;
676
677    fn sample_triple() -> StreamTriple {
678        StreamTriple::new(
679            "http://example.org/subject",
680            "http://example.org/predicate",
681            "\"hello\"",
682        )
683    }
684
685    fn insert_msg(offset: u64) -> StreamMessage {
686        StreamMessage::insert("stream-rdf", offset, vec![sample_triple()])
687    }
688
689    // ── StreamingTripleConsumer ──────────────
690
691    #[tokio::test]
692    async fn test_consumer_submit_and_drain() {
693        let consumer = StreamingTripleConsumer::new(ConsumerConfig::default()).expect("new");
694        consumer.start();
695        consumer.submit(insert_msg(1)).await.expect("submit 1");
696        consumer.submit(insert_msg(2)).await.expect("submit 2");
697        assert_eq!(consumer.buffer_len().await, 2);
698        let batch = consumer.drain_batch().await;
699        assert_eq!(batch.len(), 2);
700        assert_eq!(consumer.buffer_len().await, 0);
701    }
702
703    #[tokio::test]
704    async fn test_consumer_buffer_overflow() {
705        let cfg = ConsumerConfig {
706            max_buffer_size: 2,
707            batch_size: 10,
708            ..Default::default()
709        };
710        let consumer = StreamingTripleConsumer::new(cfg).expect("new");
711        consumer.submit(insert_msg(1)).await.expect("1");
712        consumer.submit(insert_msg(2)).await.expect("2");
713        // Third submit should fail.
714        assert!(consumer.submit(insert_msg(3)).await.is_err());
715    }
716
717    #[tokio::test]
718    async fn test_consumer_stats_tracking() {
719        let consumer = StreamingTripleConsumer::new(ConsumerConfig::default()).expect("new");
720        consumer.submit(insert_msg(1)).await.expect("submit");
721        assert_eq!(
722            consumer.stats().messages_consumed.load(Ordering::Relaxed),
723            1
724        );
725        assert_eq!(consumer.stats().triples_inserted.load(Ordering::Relaxed), 1);
726    }
727
728    #[tokio::test]
729    async fn test_consumer_validation_rejects_empty_triple() {
730        let consumer = StreamingTripleConsumer::new(ConsumerConfig {
731            validate_triples: true,
732            ..Default::default()
733        })
734        .expect("new");
735        let bad_triple = StreamTriple::new("", "http://pred", "obj");
736        let msg = StreamMessage::insert("s", 1, vec![bad_triple]);
737        assert!(consumer.submit(msg).await.is_err());
738    }
739
740    // ── StreamingMutationLog ─────────────────
741
742    #[tokio::test]
743    async fn test_mutation_log_append_and_read() {
744        let log = StreamingMutationLog::new(1, 1000).expect("new");
745        let seq1 = log.append(insert_msg(1)).await.expect("append 1");
746        let seq2 = log.append(insert_msg(2)).await.expect("append 2");
747        assert_eq!(seq2, seq1 + 1);
748
749        let entries = log.read_range(seq1, seq2).await;
750        assert_eq!(entries.len(), 2);
751    }
752
753    #[tokio::test]
754    async fn test_mutation_log_commit() {
755        let log = StreamingMutationLog::new(1, 1000).expect("new");
756        let seq = log.append(insert_msg(10)).await.expect("append");
757        assert_eq!(log.committed_seq(), 0);
758        log.commit_up_to(seq);
759        assert_eq!(log.committed_seq(), seq);
760    }
761
762    #[tokio::test]
763    async fn test_mutation_log_capacity_eviction() {
764        let log = StreamingMutationLog::new(1, 3).expect("new");
765        for i in 0..5 {
766            log.append(insert_msg(i)).await.expect("append");
767        }
768        // Capacity is 3; older entries should be evicted.
769        assert!(log.len().await <= 3);
770    }
771
772    // ── StreamSyncCoordinator ────────────────
773
774    #[tokio::test]
775    async fn test_sync_coordinator_offsets() {
776        let coord = StreamSyncCoordinator::new();
777        coord.report_offset("rdf-stream", 1, 100).await;
778        coord.report_offset("rdf-stream", 2, 200).await;
779        coord.report_offset("rdf-stream", 3, 150).await;
780
781        assert_eq!(coord.min_offset("rdf-stream").await, Some(100));
782        assert_eq!(coord.max_offset("rdf-stream").await, Some(200));
783        assert_eq!(coord.lag("rdf-stream").await, Some(100));
784    }
785
786    #[tokio::test]
787    async fn test_sync_coordinator_unknown_stream() {
788        let coord = StreamSyncCoordinator::new();
789        assert!(coord.min_offset("nonexistent").await.is_none());
790        assert!(coord.lag("nonexistent").await.is_none());
791    }
792
793    // ── StreamingCheckpointer ────────────────
794
795    #[tokio::test]
796    async fn test_checkpointer_save_load() {
797        let cp = StreamingCheckpointer::new();
798        let saved = cp.save("my-stream", 42, 999).await.expect("save");
799        assert_eq!(saved.offset, 999);
800        assert_eq!(saved.node_id, 42);
801
802        let loaded = cp.load("my-stream", 42).await.expect("load");
803        assert_eq!(loaded.offset, 999);
804    }
805
806    #[tokio::test]
807    async fn test_checkpointer_restore() {
808        let cp = StreamingCheckpointer::new();
809        let checkpoints = vec![
810            Checkpoint {
811                stream_id: "s1".into(),
812                node_id: 1,
813                offset: 50,
814                checkpoint_ms: 0,
815                version: 1,
816            },
817            Checkpoint {
818                stream_id: "s2".into(),
819                node_id: 1,
820                offset: 75,
821                checkpoint_ms: 0,
822                version: 2,
823            },
824        ];
825        cp.restore(checkpoints).await;
826        assert_eq!(cp.count().await, 2);
827        let for_node = cp.checkpoints_for_node(1).await;
828        assert_eq!(for_node.len(), 2);
829    }
830}