linkrs-sync 0.1.0

Synchronization primitives for Linkrs
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
#![cfg(feature = "fulltext")]

use std::sync::Arc;
use std::time::Instant;

use dashmap::DashMap;
use tracing::{debug, warn};

use super::types::{ChangeContext, ChangeData, ChangeType};
use crate::batch::{BatchConfig, BatchProcessor, FulltextBatchProcessor, TransactionBatchBuffer};
use linkrs_fulltext::manager::FulltextIndexManager;
use linkrs_fulltext::ConsistencyState;
use linkrs_fulltext::SyncFailurePolicy;
use linkrs_metrics::StatsManager;

use crate::dead_letter_queue::{DeadLetterEntry, DeadLetterQueue, DeadLetterQueueConfig};
use crate::retry::{default_local_retry_config, with_retry};
use crate::types::{IndexOpKey, IndexOperation};

type FulltextProcessor = FulltextBatchProcessor;

pub struct SyncCoordinator {
    fulltext_manager: Arc<FulltextIndexManager>,
    fulltext_processors: DashMap<(u64, String, String), Arc<FulltextProcessor>>,
    transaction_buffers: DashMap<linkrs_core::types::TransactionId, Arc<TransactionBatchBuffer>>,
    config: BatchConfig,
    dead_letter_queue: Arc<DeadLetterQueue>,
    stats_manager: Option<Arc<StatsManager>>,
}

impl std::fmt::Debug for SyncCoordinator {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut d = f.debug_struct("SyncCoordinator");
        d.field("fulltext_processors_count", &self.fulltext_processors.len());
        d.field("config", &self.config);
        d.finish_non_exhaustive()
    }
}

impl SyncCoordinator {
    pub fn new(fulltext_manager: Arc<FulltextIndexManager>, config: BatchConfig) -> Self {
        let dead_letter_queue = Arc::new(DeadLetterQueue::new(DeadLetterQueueConfig::default()));

        Self {
            fulltext_manager,
            fulltext_processors: DashMap::new(),
            transaction_buffers: DashMap::new(),
            config,
            dead_letter_queue,
            stats_manager: None,
        }
    }

    pub fn with_stats_manager(mut self, stats_manager: Arc<StatsManager>) -> Self {
        self.stats_manager = Some(stats_manager);
        self
    }

    pub fn dead_letter_queue(&self) -> &Arc<DeadLetterQueue> {
        &self.dead_letter_queue
    }

    pub fn fulltext_manager(&self) -> &Arc<FulltextIndexManager> {
        &self.fulltext_manager
    }

    /// Repoint a cached batch processor at a rebuilt engine after publish.
    /// Must be called while holding the index publish fence write guard so
    /// no flush can straddle the engine swap.
    pub async fn repoint_fulltext_processor(
        &self,
        space_id: u64,
        tag_name: &str,
        field_name: &str,
        engine: Arc<dyn linkrs_fulltext::engine::FulltextSearchEngine>,
    ) {
        let key = (space_id, tag_name.to_string(), field_name.to_string());
        if let Some(processor) = self.fulltext_processors.get(&key) {
            processor.set_engine(engine).await;
        }
    }

    fn get_or_create_fulltext_processor(
        &self,
        space_id: u64,
        tag_name: &str,
        field_name: &str,
    ) -> Option<Arc<FulltextProcessor>> {
        let key = (space_id, tag_name.to_string(), field_name.to_string());

        // Use entry API for atomic get-or-create to avoid race conditions
        // where concurrent requests for the same (space, tag, field) could
        // cause duplicate processor creation and multiple background tasks.
        let processor = match self.fulltext_processors.entry(key.clone()) {
            dashmap::mapref::entry::Entry::Occupied(entry) => {
                return Some(entry.get().clone());
            }
            dashmap::mapref::entry::Entry::Vacant(entry) => {
                let engine = self
                    .fulltext_manager
                    .get_engine(space_id, tag_name, field_name)?;
                let fence = self
                    .fulltext_manager
                    .publish_fence_for(space_id, tag_name, field_name);

                let processor = Arc::new(FulltextBatchProcessor::new(
                    space_id,
                    tag_name.to_string(),
                    field_name.to_string(),
                    engine,
                    self.config.clone(),
                    fence,
                ));

                entry.insert(processor.clone());
                processor
            }
        };

        // Only spawn background task if we are the thread that created the processor.
        // Other threads will find the existing entry via the Occupied path above.
        let proc_clone = processor.clone();
        tokio::spawn(async move {
            proc_clone.start_background_task().await;
        });

        Some(processor)
    }

    pub async fn on_change(&self, ctx: ChangeContext) -> Result<(), SyncCoordinatorError> {
        let start = Instant::now();
        let operation = self.create_operation(&ctx)?;

        let result = async {
            if let Some(processor) =
                self.get_or_create_fulltext_processor(ctx.space_id, &ctx.tag_name, &ctx.field_name)
            {
                processor.add(operation).await?;
            }
            Ok::<(), SyncCoordinatorError>(())
        }
        .await;

        if let Some(ref sm) = self.stats_manager {
            let latency_ms = start.elapsed().as_millis() as u64;
            sm.record_sync_operation(latency_ms, result.is_ok());
        }

        result
    }

    fn create_operation(
        &self,
        ctx: &ChangeContext,
    ) -> Result<IndexOperation, SyncCoordinatorError> {
        let key = IndexOpKey::new(ctx.space_id, &ctx.tag_name, &ctx.field_name);
        let is_delete = ctx.change_type == ChangeType::Delete;

        match &ctx.data {
            ChangeData::Fulltext(text) => {
                let text = if is_delete { None } else { Some(text.clone()) };
                Ok(IndexOperation::new_fulltext(
                    key,
                    ctx.change_type,
                    ctx.vertex_id.clone(),
                    text,
                ))
            }
            ChangeData::Vector(vector) => {
                let vector = if is_delete {
                    None
                } else {
                    Some(vector.clone())
                };
                Ok(IndexOperation::new_vector(
                    key,
                    ctx.change_type,
                    ctx.vertex_id.clone(),
                    vector,
                ))
            }
        }
    }

    pub async fn on_vertex_change(
        &self,
        space_id: u64,
        tag_name: &str,
        vertex_id: &linkrs_core::Value,
        properties: &[(String, linkrs_core::Value)],
        change_type: ChangeType,
    ) -> Result<(), SyncCoordinatorError> {
        let vid_str = format!("{}", vertex_id);

        for (field_name, value) in properties {
            if self
                .fulltext_manager
                .get_engine(space_id, tag_name, field_name)
                .is_some()
            {
                if let linkrs_core::Value::String(text) = value {
                    let ctx = ChangeContext::new_fulltext(
                        space_id,
                        tag_name,
                        field_name,
                        change_type,
                        vid_str.clone(),
                        text.clone(),
                    );
                    self.on_change(ctx).await?;
                }
            }
        }

        Ok(())
    }

    /// Buffered index operations
    pub fn buffer_operation(
        &self,
        txn_id: linkrs_core::types::TransactionId,
        ctx: ChangeContext,
    ) -> Result<(), SyncCoordinatorError> {
        self.buffer_operation_with_sequence(txn_id, 0, ctx)
    }

    pub fn buffer_operation_with_sequence(
        &self,
        txn_id: linkrs_core::types::TransactionId,
        sequence: u64,
        ctx: ChangeContext,
    ) -> Result<(), SyncCoordinatorError> {
        // Creating Index Operations
        let operation = self.create_operation(&ctx)?;

        // Getting or creating a transaction buffer
        let buffer = self
            .transaction_buffers
            .entry(txn_id)
            .or_insert_with(|| Arc::new(TransactionBatchBuffer::new()))
            .clone();

        // Adding operations to the buffer
        buffer
            .prepare_with_sequence(txn_id, sequence, operation)
            .map_err(SyncCoordinatorError::BatchError)?;

        if let Some(ref sm) = self.stats_manager {
            let total_depth: u64 = self
                .transaction_buffers
                .iter()
                .map(|entry| entry.value().pending_count(*entry.key()) as u64)
                .sum();
            sm.set_sync_queue_depth(total_depth);
        }

        Ok(())
    }

    pub fn current_sequence(&self, txn_id: linkrs_core::types::TransactionId) -> u64 {
        self.transaction_buffers
            .get(&txn_id)
            .map(|buffer| buffer.pending_sequence(txn_id))
            .unwrap_or(0)
    }

    /// Get the count of buffered operations for a transaction
    pub fn transaction_buffer_count(&self, txn_id: linkrs_core::types::TransactionId) -> usize {
        if let Some(buffer) = self.transaction_buffers.get(&txn_id) {
            buffer.pending_count(txn_id)
        } else {
            0
        }
    }

    /// Prepare phase: validate all target engines are consistent
    pub async fn prepare_transaction(
        &self,
        txn_id: linkrs_core::types::TransactionId,
    ) -> Result<(), SyncCoordinatorError> {
        if let Some(buffer) = self.transaction_buffers.get(&txn_id) {
            let count = buffer.pending_count(txn_id);

            let grouped_ops = buffer
                .peek_operations(txn_id)
                .map_err(SyncCoordinatorError::BatchError)?;

            for (key, _) in &grouped_ops {
                if let Some(engine) =
                    self.fulltext_manager
                        .get_engine(key.space_id, &key.tag_name, &key.field_name)
                {
                    if engine.consistency_state() == ConsistencyState::Inconsistent {
                        return Err(SyncCoordinatorError::InvalidOperation(format!(
                            "Engine for {}.{}.{} is marked Inconsistent. Repair before committing.",
                            key.space_id, key.tag_name, key.field_name
                        )));
                    }
                }
            }

            log::debug!(
                "Transaction {:?} prepared with {} operations across {} indexes (engines consistent)",
                txn_id,
                count,
                grouped_ops.len()
            );
        }
        Ok(())
    }

    /// Commit phase: Apply all operations with batch optimization.
    ///
    /// Uses deferred-commit pattern for atomicity:
    ///   1. Pre-validate all target engines are consistent
    ///   2. Apply all operations without committing (in-memory)
    ///   3. Commit all engines at once
    ///   4. On any failure, mark affected engines as Inconsistent
    pub async fn commit_transaction(
        &self,
        txn_id: linkrs_core::types::TransactionId,
    ) -> Result<(), SyncCoordinatorError> {
        let result = if let Some((_, buffer)) = self.transaction_buffers.remove(&txn_id) {
            let grouped_ops = buffer
                .take_operations(txn_id)
                .map_err(SyncCoordinatorError::BatchError)?;

            // Pre-commit validation: check consistency of all involved engines
            for (key, _) in &grouped_ops {
                if let Some(engine) =
                    self.fulltext_manager
                        .get_engine(key.space_id, &key.tag_name, &key.field_name)
                {
                    if engine.consistency_state() == ConsistencyState::Inconsistent {
                        return Err(SyncCoordinatorError::InvalidOperation(format!(
                            "Engine for {}.{}.{} is marked Inconsistent. Repair required before committing.",
                            key.space_id, key.tag_name, key.field_name
                        )));
                    }
                }
            }

            // Apply fulltext operations WITHOUT committing (deferred commit)
            let mut fulltext_failed = false;
            let mut failed_keys: Vec<IndexOpKey> = Vec::new();

            for (key, operations) in &grouped_ops {
                let retry_config = default_local_retry_config();

                if let Some(processor) = self.get_or_create_fulltext_processor(
                    key.space_id,
                    &key.tag_name,
                    &key.field_name,
                ) {
                    let ops_clone = operations.clone();
                    let retry_config_clone = retry_config.clone();
                    let dlq_clone = self.dead_letter_queue.clone();

                    match with_retry(
                        || async {
                            processor
                                .execute_now_without_commit(ops_clone.clone())
                                .await
                        },
                        &retry_config_clone,
                    )
                    .await
                    {
                        Ok(_) => {
                            debug!("Fulltext batch applied (pending commit)");
                        }
                        Err(e) => {
                            warn!("Fulltext batch failed after retries: {:?}", e);
                            for op in operations {
                                let entry = DeadLetterEntry::new(
                                    op.clone(),
                                    format!("Local index sync failed after retries: {:?}", e),
                                    retry_config_clone.max_retries,
                                );
                                dlq_clone.add(entry);
                            }
                            fulltext_failed = true;
                            failed_keys.push(key.clone());
                        }
                    }
                }
            }

            if fulltext_failed {
                match self.config.failure_policy {
                    SyncFailurePolicy::FailClosed => {
                        return Err(SyncCoordinatorError::BatchError(
                            crate::batch::BatchError::InvalidOperation(format!(
                                "Fulltext commit failed for {} indexes under FailClosed policy",
                                failed_keys.len()
                            )),
                        ));
                    }
                    SyncFailurePolicy::FailOpen => {
                        // Mark failed engines as inconsistent so they can be repaired
                        // (online rebuild driver, or drop and recreate)
                        for key in &failed_keys {
                            if let Some(engine) = self.fulltext_manager.get_engine(
                                key.space_id,
                                &key.tag_name,
                                &key.field_name,
                            ) {
                                engine.mark_inconsistent();
                                warn!(
                                    "Marked engine {}.{}.{} as Inconsistent due to commit failure",
                                    key.space_id, key.tag_name, key.field_name
                                );
                            }
                        }
                        // Still try to commit the successful batch processors
                        self.commit_all().await.ok();
                        return Err(SyncCoordinatorError::BatchError(
                            crate::batch::BatchError::InvalidOperation(format!(
                                "Fulltext commit failed for {} indexes, marked as Inconsistent. Repair with the online rebuild driver, or by dropping and recreating the affected indexes.",
                                failed_keys.len()
                            )),
                        ));
                    }
                }
            }

            // Commit all fulltext engines at once
            self.commit_all().await?;

            log::debug!(
                "Transaction {:?} committed successfully ({} fulltext batches)",
                txn_id,
                grouped_ops.len(),
            );
            if let Some(ref sm) = self.stats_manager {
                let total_depth: u64 = self
                    .transaction_buffers
                    .iter()
                    .map(|entry| entry.value().pending_count(*entry.key()) as u64)
                    .sum();
                sm.set_sync_queue_depth(total_depth);
            }
            Ok(())
        } else {
            Ok(())
        };

        result
    }

    pub async fn commit_all(&self) -> Result<(), SyncCoordinatorError> {
        let processors: Vec<Arc<FulltextProcessor>> = self
            .fulltext_processors
            .iter()
            .map(|e| e.value().clone())
            .collect();

        for processor in &processors {
            processor.commit_all().await.map_err(|e| {
                SyncCoordinatorError::BatchError(crate::batch::BatchError::InvalidOperation(
                    format!("commit_all failed: {:?}", e),
                ))
            })?;
        }

        Ok(())
    }

    /// Rollback transaction: discard buffered operations
    pub fn rollback_transaction(
        &self,
        txn_id: linkrs_core::types::TransactionId,
    ) -> Result<(), SyncCoordinatorError> {
        if let Some(buffer) = self.transaction_buffers.get(&txn_id) {
            buffer.rollback(txn_id)?;
        }
        self.transaction_buffers.remove(&txn_id);
        Ok(())
    }

    pub fn truncate_transaction(
        &self,
        txn_id: linkrs_core::types::TransactionId,
        sequence: u64,
    ) -> Result<(), SyncCoordinatorError> {
        if let Some(buffer) = self.transaction_buffers.get(&txn_id) {
            buffer
                .truncate_operations(txn_id, sequence)
                .map_err(SyncCoordinatorError::BatchError)?;
        }
        Ok(())
    }

    pub async fn stop_background_tasks(&self) {
        let processors: Vec<Arc<FulltextProcessor>> = self
            .fulltext_processors
            .iter()
            .map(|e| e.value().clone())
            .collect();

        for processor in &processors {
            processor.stop_background_task().await;
        }
    }

    pub async fn start_background_tasks(&self) {
        let processors: Vec<Arc<FulltextProcessor>> = self
            .fulltext_processors
            .iter()
            .map(|e| e.value().clone())
            .collect();

        for processor in &processors {
            let p = processor.clone();
            tokio::spawn(async move {
                p.start_background_task().await;
            });
        }
    }

    /// Recover operations from the dead letter queue.
    pub async fn recover_dead_letter(&self) -> Result<RecoveryResult, SyncCoordinatorError> {
        let dead_letter_entries = self.dead_letter_queue.get_all();
        let mut result = RecoveryResult {
            total: dead_letter_entries.len(),
            ..Default::default()
        };

        for (index, entry) in dead_letter_entries.iter().enumerate() {
            match self.recover_operation(&entry.operation).await {
                Ok(()) => {
                    self.dead_letter_queue.mark_recovered(index);
                    result.recovered += 1;
                }
                Err(e) => {
                    warn!(
                        "Failed to recover dead letter entry at index {}: {:?}",
                        index, e
                    );
                    result.failed += 1;
                }
            }
        }

        result.total_attempted = result.total;
        Ok(result)
    }

    /// Recover operations from the dead letter queue by retrying each one.
    ///
    /// This retries each failed operation through the normal batch processing pipeline.
    /// Successfully retried operations are marked as recovered in the DLQ.
    pub async fn retry_dead_letter(
        &self,
        max_entries: Option<usize>,
    ) -> Result<RecoveryResult, SyncCoordinatorError> {
        let all_entries = self.dead_letter_queue.get_all();
        let mut result = RecoveryResult::default();
        let mut processed = 0;

        for (index, entry) in all_entries.iter().enumerate() {
            if entry.recovered {
                continue;
            }
            if let Some(limit) = max_entries {
                if processed >= limit {
                    break;
                }
            }
            result.total += 1;

            match self.recover_operation(&entry.operation).await {
                Ok(()) => {
                    self.dead_letter_queue.mark_recovered(index);
                    result.recovered += 1;
                }
                Err(e) => {
                    warn!("Dead letter retry failed at index {}: {:?}", index, e);
                    result.failed += 1;
                }
            }
            processed += 1;
        }

        result.total_attempted = processed;
        Ok(result)
    }

    /// Recover operations from specific indexes
    pub async fn recover_operations_for_indexes(
        &self,
        space_id: u64,
        tag_name: &str,
        field_name: &str,
    ) -> Result<RecoveryResult, SyncCoordinatorError> {
        let target_key = IndexOpKey::new(space_id, tag_name, field_name);
        let entries = self.dead_letter_queue.get_all();
        let mut result = RecoveryResult::default();

        for (index, entry) in entries.iter().enumerate() {
            let matches = entry.operation.key == target_key;

            if matches {
                result.total += 1;
                match self.recover_operation(&entry.operation).await {
                    Ok(()) => {
                        self.dead_letter_queue.mark_recovered(index);
                        result.recovered += 1;
                    }
                    Err(e) => {
                        warn!(
                            "Failed to recover operation for {}.{}.{}: {:?}",
                            space_id, tag_name, field_name, e
                        );
                        result.failed += 1;
                    }
                }
            }
        }

        result.total_attempted = result.total;
        Ok(result)
    }

    /// Recover a single operation
    async fn recover_operation(
        &self,
        operation: &IndexOperation,
    ) -> Result<(), SyncCoordinatorError> {
        let key = &operation.key;
        if let Some(processor) =
            self.get_or_create_fulltext_processor(key.space_id, &key.tag_name, &key.field_name)
        {
            match operation.change_type {
                ChangeType::Insert => {
                    processor.add(operation.clone()).await.map_err(|e| {
                        SyncCoordinatorError::BatchError(
                            crate::batch::BatchError::InvalidOperation(format!(
                                "Recovery failed: {:?}",
                                e
                            )),
                        )
                    })?;
                }
                ChangeType::Update | ChangeType::Delete => {
                    processor
                        .execute_now(vec![operation.clone()])
                        .await
                        .map_err(|e| {
                            SyncCoordinatorError::BatchError(
                                crate::batch::BatchError::InvalidOperation(format!(
                                    "Recovery failed: {:?}",
                                    e
                                )),
                            )
                        })?;
                }
            }
        }

        Ok(())
    }
}

/// Result of a recovery operation
#[derive(Debug, Default)]
pub struct RecoveryResult {
    pub total: usize,
    pub recovered: usize,
    pub failed: usize,
    pub total_attempted: usize,
}

impl RecoveryResult {
    pub fn total(&self) -> usize {
        self.total
    }

    pub fn recovered(&self) -> usize {
        self.recovered
    }

    pub fn failed(&self) -> usize {
        self.failed
    }

    pub fn is_complete(&self) -> bool {
        self.failed == 0
    }
}

/// Error types for the sync coordinator
#[derive(Debug, thiserror::Error)]
pub enum SyncCoordinatorError {
    #[error("Batch error: {0}")]
    BatchError(crate::batch::BatchError),

    #[error("Invalid operation: {0}")]
    InvalidOperation(String),

    #[error("Operation not supported: {0}")]
    NotSupported(String),

    #[error("Recovery error: {0}")]
    RecoveryError(String),
}

impl From<crate::batch::BatchError> for SyncCoordinatorError {
    fn from(e: crate::batch::BatchError) -> Self {
        SyncCoordinatorError::BatchError(e)
    }
}