subscriber.rs 33.5 KB
Newer Older
1
// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
3
// SPDX-License-Identifier: Apache-2.0

4
use std::{collections::HashMap, collections::HashSet, time::Duration};
5
6
7
8

use anyhow::Result;
use dynamo_runtime::{
    component::Component,
9
    config::environment_names::nats as env_nats,
10
    discovery::{DiscoveryEvent, DiscoveryQuery},
11
    prelude::*,
12
    traits::events::{EventPublisher, EventSubscriber},
13
    transports::nats::{NatsQueue, Slug},
14
};
15
use futures::StreamExt;
16
use rand::Rng;
17
18
19
use tokio::sync::{mpsc, oneshot};
use tokio_util::sync::CancellationToken;

20
21
use crate::kv_router::{
    KV_EVENT_SUBJECT, RADIX_STATE_BUCKET, RADIX_STATE_FILE,
22
    indexer::{DumpRequest, GetWorkersRequest, RouterEvent, WorkerKvQueryResponse},
23
24
    protocols::WorkerId,
    router_discovery_query,
25
    worker_query::WorkerQueryClient,
26
27
};

28
29
30
31
32
33
34
/// Delay between snapshot reads to verify stability
const SNAPSHOT_STABILITY_DELAY: Duration = Duration::from_millis(100);
const MAX_SNAPSHOT_STABILITY_ATTEMPTS: usize = 10;

const CHECK_INTERVAL_BASE: Duration = Duration::from_secs(1);
const CHECK_INTERVAL_JITTER_MS: i64 = 100;

35
36
37
38
// Worker query retry configuration
const WORKER_QUERY_MAX_RETRIES: u32 = 8;
const WORKER_QUERY_INITIAL_BACKOFF_MS: u64 = 200;

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
// ============================================================================
// Local KvIndexer-based Recovery
// ============================================================================

/// Recover missed events from all workers with local indexers.
///
/// This function should be called on router startup to catch up on any events
/// that were missed while the router was offline.
///
/// # Arguments
///
/// * `worker_query_client` - Client for querying worker local indexers
/// * `last_received_event_ids` - Map of worker ID to last received event ID
/// * `worker_ids` - List of worker IDs to recover from
/// * `event_tx` - Channel to send recovered events to the indexer
///
/// # Returns
///
/// Total number of events recovered across all workers
pub async fn recover_from_all_workers(
    worker_query_client: &WorkerQueryClient,
    last_received_event_ids: &HashMap<WorkerId, u64>,
    worker_ids: &Vec<WorkerId>,
    event_tx: &mpsc::Sender<RouterEvent>,
) -> usize {
    let mut total_recovered = 0;
    let mut successful_workers = 0;
    let mut failed_workers = 0;

    for &worker_id in worker_ids {
        // Skip workers without local indexer
        if !worker_query_client.has_local_indexer(worker_id) {
            tracing::debug!(
72
                "Skipping recovery - worker {worker_id} does not have local indexer enabled"
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
            );
            continue;
        }

        // If we haven't seen any events from this worker, start from beginning (None)
        // If we've seen events, start from last_known_id + 1
        let start_event_id = last_received_event_ids
            .get(&worker_id)
            .map(|&last_id| last_id + 1);

        match recover_from_worker(
            worker_query_client,
            worker_id,
            start_event_id,
            None, // Get all events after start_event_id
            event_tx,
        )
        .await
        {
            Ok(count) => {
                total_recovered += count;
                if count > 0 {
                    successful_workers += 1;
                }
            }
            Err(_) => {
                failed_workers += 1;
            }
        }
    }

    // Log summary
    if total_recovered > 0 || failed_workers > 0 {
        tracing::info!(
107
            "Startup recovery completed: {total_recovered} events recovered from {successful_workers} workers, {failed_workers} workers failed"
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
        );
    }

    total_recovered
}

/// Recover missed KV events from a specific worker.
///
/// # Arguments
///
/// * `worker_query_client` - Client for querying worker local indexers
/// * `worker_id` - The worker to recover from
/// * `start_event_id` - First event ID to fetch (inclusive), or None to start from beginning
/// * `end_event_id` - Last event ID to fetch (inclusive), or None for all
/// * `event_tx` - Channel to send recovered events to the indexer
///
/// # Returns
///
/// Number of events recovered, or error if recovery failed
pub async fn recover_from_worker(
    worker_query_client: &WorkerQueryClient,
    worker_id: WorkerId,
    start_event_id: Option<u64>,
    end_event_id: Option<u64>,
    event_tx: &mpsc::Sender<RouterEvent>,
) -> Result<usize> {
    if worker_query_client.has_local_indexer(worker_id) {
        tracing::debug!(
136
            "Attempting recovery from worker {worker_id}, start_event_id: {start_event_id:?}, end_event_id: {end_event_id:?}"
137
138
        );
    } else {
139
        tracing::warn!("Worker {worker_id} does not have local indexer enabled, skipping recovery");
140
141
142
        return Ok(0);
    }

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
    // Query worker for events in range, with retry logic for transient failures
    // (e.g., worker's query service not yet re-subscribed after NATS restart)
    let mut response = None;
    let mut last_error = None;

    for attempt in 0..WORKER_QUERY_MAX_RETRIES {
        match worker_query_client
            .query_worker(worker_id, start_event_id, end_event_id)
            .await
        {
            Ok(resp) => {
                if attempt > 0 {
                    tracing::info!("Worker {worker_id} query succeeded after retry {attempt}");
                }
                response = Some(resp);
                break;
            }
            Err(e) => {
                last_error = Some(e);
                if attempt < WORKER_QUERY_MAX_RETRIES - 1 {
                    let backoff_ms = WORKER_QUERY_INITIAL_BACKOFF_MS * 2_u64.pow(attempt);
                    tracing::warn!(
                        "Worker {worker_id} query failed on attempt {attempt}, retrying after {backoff_ms}ms"
                    );
                    tokio::time::sleep(Duration::from_millis(backoff_ms)).await;
                }
            }
        }
    }

    let response = match response {
        Some(r) => r,
        None => return Err(last_error.unwrap_or_else(|| anyhow::anyhow!("No response"))),
    };
177

178
179
180
    // Handle response variants
    let events = match response {
        WorkerKvQueryResponse::Events(events) => {
181
182
183
184
            tracing::debug!(
                "Got {count} buffered events from worker {worker_id}",
                count = events.len()
            );
185
186
187
188
            events
        }
        WorkerKvQueryResponse::TreeDump(events) => {
            tracing::info!(
189
190
                "Got tree dump from worker {worker_id} (range too old or unspecified), count: {count}",
                count = events.len()
191
192
193
194
195
196
197
198
199
            );
            events
        }
        WorkerKvQueryResponse::TooNew {
            requested_start,
            requested_end,
            newest_available,
        } => {
            tracing::warn!(
200
                "Worker {worker_id} requested range is newer than available data: requested_start: {requested_start:?}, requested_end: {requested_end:?}, newest_available: {newest_available}"
201
202
203
204
205
206
207
208
209
            );
            return Ok(0);
        }
        WorkerKvQueryResponse::InvalidRange { start_id, end_id } => {
            anyhow::bail!("Invalid range: end_id ({end_id}) < start_id ({start_id})");
        }
    };

    let events_count = events.len();
210
211
212

    if events_count == 0 {
        tracing::debug!(
213
            "No events to recover from worker {worker_id}, start_event_id: {start_event_id:?}"
214
215
216
217
218
        );
        return Ok(0);
    }

    tracing::info!(
219
        "Recovered {events_count} events from worker {worker_id}, start_event_id: {start_event_id:?}"
220
221
222
    );

    // Apply recovered events to the indexer
223
    for event in events {
224
        if let Err(e) = event_tx.send(event).await {
225
226
227
            tracing::error!(
                "Failed to send recovered event to indexer for worker {worker_id}: {e}"
            );
228
            anyhow::bail!("Failed to send recovered event: {e}");
229
230
231
232
233
234
235
236
237
238
        }
    }

    Ok(events_count)
}

// ============================================================================
// Snapshot Management
// ============================================================================

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
/// Download a stable snapshot from object store and send events to the indexer.
/// Retries until two consecutive reads match or max attempts is reached.
async fn download_stable_snapshot(
    nats_client: &dynamo_runtime::transports::nats::Client,
    bucket_name: &str,
    kv_events_tx: &mpsc::Sender<RouterEvent>,
) -> Result<()> {
    let url = url::Url::parse(&format!(
        "nats://{}/{bucket_name}/{RADIX_STATE_FILE}",
        nats_client.addr()
    ))?;

    // Try to get initial snapshot
    let Ok(mut prev_events) = nats_client
        .object_store_download_data::<Vec<RouterEvent>>(&url)
        .await
    else {
        tracing::debug!(
            "Failed to download snapshots. This is normal for freshly started Router replicas."
        );
        return Ok(());
    };

    // Keep trying until we get two consecutive stable reads
    for attempt in 1..=MAX_SNAPSHOT_STABILITY_ATTEMPTS {
        tokio::time::sleep(SNAPSHOT_STABILITY_DELAY).await;

        let curr_events = match nats_client
            .object_store_download_data::<Vec<RouterEvent>>(&url)
            .await
        {
            Ok(events) => events,
            Err(e) => {
                tracing::warn!(
                    "Snapshot read failed on attempt {attempt}, using previous snapshot with {} events: {e:?}",
                    prev_events.len()
                );
                break;
            }
        };

        // Check if snapshot is stable (two consecutive reads match)
        if prev_events == curr_events {
            tracing::info!(
                "Successfully downloaded stable snapshot with {} events from object store (stable after {attempt} attempts)",
                curr_events.len()
            );
            prev_events = curr_events;
            break;
        }

        tracing::debug!(
            "Snapshot changed between reads on attempt {attempt} ({} -> {} events), retrying",
            prev_events.len(),
            curr_events.len()
        );
        prev_events = curr_events;

        if attempt == MAX_SNAPSHOT_STABILITY_ATTEMPTS {
            tracing::warn!(
                "Max stability attempts reached, using latest snapshot with {} events",
                prev_events.len()
            );
        }
    }

    // Send all events to the indexer
    for event in prev_events {
        if let Err(e) = kv_events_tx.send(event).await {
            tracing::warn!("Failed to send initial event to indexer: {e:?}");
        }
    }
    tracing::info!("Successfully sent all initial events to indexer");

    Ok(())
}

316
317
318
319
320
/// Resources required for snapshot operations
#[derive(Clone)]
struct SnapshotResources {
    nats_client: dynamo_runtime::transports::nats::Client,
    bucket_name: String,
321
322
323
    instances_rx: tokio::sync::watch::Receiver<Vec<dynamo_runtime::component::Instance>>,
    get_workers_tx: mpsc::Sender<GetWorkersRequest>,
    snapshot_tx: mpsc::Sender<DumpRequest>,
324
325
326
}

impl SnapshotResources {
327
    /// Perform snapshot upload and purge operations
328
329
330
331
332
333
334
335
336
337
338
339
340
341
    async fn purge_then_snapshot(
        &self,
        nats_queue: &mut NatsQueue,
        remove_worker_tx: &mpsc::Sender<WorkerId>,
    ) -> anyhow::Result<()> {
        // Purge before snapshot ensures new/warm-restarted routers won't replay already-acknowledged messages.
        // Since KV events are idempotent, this ordering reduces unnecessary reprocessing while maintaining
        // at-least-once delivery guarantees. The snapshot will capture the clean state after purge.
        tracing::info!("Purging acknowledged messages and performing snapshot of radix tree");
        let start_time = std::time::Instant::now();

        // Clean up stale workers before snapshot
        // Get current worker IDs from instances_rx
        let current_instances = self.instances_rx.borrow().clone();
342
        let current_worker_ids: std::collections::HashSet<u64> = current_instances
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
            .iter()
            .map(|instance| instance.instance_id)
            .collect();

        // Get worker IDs from the indexer
        let (resp_tx, resp_rx) = tokio::sync::oneshot::channel();
        let get_workers_req = GetWorkersRequest { resp: resp_tx };

        if let Err(e) = self.get_workers_tx.send(get_workers_req).await {
            tracing::warn!("Failed to send get_workers request during snapshot: {e:?}");
        } else {
            match resp_rx.await {
                Ok(indexer_worker_ids) => {
                    // Find workers in indexer but not in current instances
                    for worker_id in indexer_worker_ids {
                        if !current_worker_ids.contains(&worker_id) {
                            tracing::info!(
360
                                "Removing stale worker {worker_id} from indexer during snapshot"
361
362
363
                            );
                            if let Err(e) = remove_worker_tx.send(worker_id).await {
                                tracing::warn!(
364
                                    "Failed to send remove_worker for stale worker {worker_id}: {e:?}"
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
                                );
                            }
                        }
                    }
                }
                Err(e) => {
                    tracing::warn!("Failed to receive worker IDs from indexer: {e:?}");
                }
            }
        }

        // First, purge acknowledged messages from the stream
        nats_queue.purge_acknowledged().await?;

        // Now request a snapshot from the indexer (which reflects the post-purge state)
        let (resp_tx, resp_rx) = oneshot::channel();
        let dump_req = DumpRequest { resp: resp_tx };

        self.snapshot_tx
            .send(dump_req)
            .await
            .map_err(|e| anyhow::anyhow!("Failed to send dump request: {e:?}"))?;

        // Wait for the dump response
        let events = resp_rx
            .await
            .map_err(|e| anyhow::anyhow!("Failed to receive dump response: {e:?}"))?;

393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
        // Upload the snapshot to NATS object store in background (non-blocking)
        let nats_client = self.nats_client.clone();
        let bucket_name = self.bucket_name.clone();
        let event_count = events.len();
        tokio::spawn(async move {
            let Ok(url) = url::Url::parse(&format!(
                "nats://{}/{bucket_name}/{RADIX_STATE_FILE}",
                nats_client.addr(),
            )) else {
                tracing::warn!("Failed to parse snapshot URL");
                return;
            };

            if let Err(e) = nats_client.object_store_upload_data(&events, &url).await {
                tracing::warn!("Failed to upload snapshot: {e:?}");
                return;
            }
410

411
412
413
414
415
            tracing::info!(
                "Successfully uploaded snapshot with {event_count} events to bucket {bucket_name} in {}ms",
                start_time.elapsed().as_millis()
            );
        });
416
417
418

        Ok(())
    }
419
420
421
}

/// Start a unified background task for event consumption and optional snapshot management
422
#[allow(clippy::too_many_arguments)]
423
424
pub async fn start_kv_router_background(
    component: Component,
425
    consumer_id: String,
426
    kv_events_tx: mpsc::Sender<RouterEvent>,
427
428
429
    remove_worker_tx: mpsc::Sender<WorkerId>,
    maybe_get_workers_tx: Option<mpsc::Sender<GetWorkersRequest>>,
    maybe_snapshot_tx: Option<mpsc::Sender<DumpRequest>>,
430
431
432
433
434
435
436
437
    cancellation_token: CancellationToken,
    router_snapshot_threshold: Option<u32>,
    router_reset_states: bool,
) -> Result<()> {
    // Set up NATS connections
    let stream_name = Slug::slugify(&format!("{}.{}", component.subject(), KV_EVENT_SUBJECT))
        .to_string()
        .replace("_", "-");
438
439
    let nats_server = std::env::var(env_nats::NATS_SERVER)
        .unwrap_or_else(|_| "nats://localhost:4222".to_string());
440
441
442
443
444
445

    // Create NatsQueue for event consumption
    let mut nats_queue = NatsQueue::new_with_consumer(
        stream_name.clone(),
        nats_server.clone(),
        std::time::Duration::from_secs(60), // 1 minute timeout
446
        consumer_id.clone(),
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
    );
    nats_queue.connect_with_reset(router_reset_states).await?;

    // Always create NATS client (needed for both reset and snapshots)
    let client_options = dynamo_runtime::transports::nats::Client::builder()
        .server(&nats_server)
        .build()?;
    let nats_client = client_options.connect().await?;

    // Create bucket name for snapshots/state
    let bucket_name = Slug::slugify(&format!("{}-{RADIX_STATE_BUCKET}", component.subject()))
        .to_string()
        .replace("_", "-");

    // Handle initial state based on router_reset_states flag
462
463
464
465
    if !router_reset_states {
        // Try to download initial state from object store with stability check
        download_stable_snapshot(&nats_client, &bucket_name, &kv_events_tx).await?;
    } else {
466
467
468
469
470
471
472
        // Delete the bucket to reset state
        tracing::info!("Resetting router state, deleting bucket: {bucket_name}");
        if let Err(e) = nats_client.object_store_delete_bucket(&bucket_name).await {
            tracing::warn!("Failed to delete bucket (may not exist): {e:?}");
        }
    }

473
    // Cleanup orphaned consumers on startup
474
    cleanup_orphaned_consumers(&mut nats_queue, &component, &consumer_id).await;
475

476
477
    // Get the generate endpoint and watch for instance deletions
    let generate_endpoint = component.endpoint("generate");
478
    let discovery_client = component.drt().discovery();
479
    let generate_discovery_key = DiscoveryQuery::Endpoint {
480
481
482
483
484
        namespace: component.namespace().name().to_string(),
        component: component.name().to_string(),
        endpoint: "generate".to_string(),
    };
    let mut instance_event_stream = discovery_client
485
486
487
488
489
490
491
        .list_and_watch(generate_discovery_key, Some(cancellation_token.clone()))
        .await?;

    // Watch for router deletions to clean up orphaned consumers via discovery
    let router_discovery_key = router_discovery_query(component.namespace().name());
    let mut router_event_stream = discovery_client
        .list_and_watch(router_discovery_key, Some(cancellation_token.clone()))
492
        .await?;
493

494
495
    // Get instances_rx for tracking current workers
    let client = generate_endpoint.client().await?;
496
    let instances_rx = client.instance_source.as_ref().clone();
497
498
499
500
501
502
503

    // Only set up snapshot-related resources if snapshot_tx, get_workers_tx, and threshold are provided
    let snapshot_resources = if let (Some(get_workers_tx), Some(snapshot_tx), Some(_)) = (
        maybe_get_workers_tx,
        maybe_snapshot_tx,
        router_snapshot_threshold,
    ) {
504
505
506
        Some(SnapshotResources {
            nats_client,
            bucket_name,
507
508
509
            instances_rx,
            get_workers_tx,
            snapshot_tx,
510
511
512
513
514
        })
    } else {
        None
    };

515
    tokio::spawn(async move {
516
517
518
519
520
521
522
        // Create interval with jitter
        let jitter_ms =
            rand::rng().random_range(-CHECK_INTERVAL_JITTER_MS..=CHECK_INTERVAL_JITTER_MS);
        let interval_duration = Duration::from_millis(
            (CHECK_INTERVAL_BASE.as_millis() as i64 + jitter_ms).max(1) as u64,
        );
        let mut check_interval = tokio::time::interval(interval_duration);
523
524
525
526
527
528
529
530
531
        check_interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);

        loop {
            tokio::select! {
                biased;

                _ = cancellation_token.cancelled() => {
                    tracing::debug!("KV Router background task received cancellation signal");
                    // Clean up the queue and remove the durable consumer
532
                    // TODO: durable consumer cannot cleanup if ungraceful shutdown (crash)
533
534
535
536
537
538
                    if let Err(e) = nats_queue.shutdown(None).await {
                        tracing::warn!("Failed to shutdown NatsQueue: {e}");
                    }
                    break;
                }

539
                // Handle generate endpoint instance deletion events
540
541
                Some(discovery_event_result) = instance_event_stream.next() => {
                    let Ok(discovery_event) = discovery_event_result else {
542
543
544
                        continue;
                    };

545
                    let DiscoveryEvent::Removed(worker_id) = discovery_event else {
546
547
548
                        continue;
                    };

549
                    tracing::warn!(
550
                        "DISCOVERY: Generate endpoint instance removed, removing worker {worker_id}"
551
                    );
552
553

                    if let Err(e) = remove_worker_tx.send(worker_id).await {
554
                        tracing::warn!("Failed to send worker removal for worker {worker_id}: {e}");
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
                // Handle event consumption
                result = nats_queue.dequeue_task(None) => {
                    match result {
                        Ok(Some(bytes)) => {
                            let event: RouterEvent = match serde_json::from_slice(&bytes) {
                                Ok(event) => event,
                                Err(e) => {
                                    tracing::warn!("Failed to deserialize RouterEvent: {e:?}");
                                    continue;
                                }
                            };

                            // Forward the RouterEvent to the indexer
                            if let Err(e) = kv_events_tx.send(event).await {
                                tracing::warn!(
                                    "failed to send kv event to indexer; shutting down: {e:?}"
                                );
                                break;
                            }
                        },
                        Ok(None) => {
                            tracing::trace!("Dequeue timeout, continuing");
                        },
                        Err(e) => {
                            tracing::error!("Failed to dequeue task: {e:?}");
                            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
                        }
                    }
                }

588
                // Handle periodic stream checking and purging (only if snapshot_resources is provided)
589
                _ = check_interval.tick() => {
590
                    let Some(resources) = snapshot_resources.as_ref() else {
591
592
593
594
595
596
597
598
599
600
                        continue;
                    };

                    // Check total messages in the stream
                    let Ok(message_count) = nats_queue.get_stream_messages().await else {
                        tracing::warn!("Failed to get stream message count");
                        continue;
                    };

                    let threshold = router_snapshot_threshold.unwrap_or(u32::MAX) as u64;
601

602
603
604
605
                    if message_count <= threshold {
                        continue;
                    }

606
                    tracing::info!("Stream has {message_count} messages (threshold: {threshold}), performing purge and snapshot");
607

608
                    match resources.purge_then_snapshot(
609
                        &mut nats_queue,
610
                        &remove_worker_tx,
611
612
                    ).await {
                        Ok(_) => tracing::info!("Successfully performed purge and snapshot"),
613
                        Err(e) => tracing::debug!("Could not perform purge and snapshot: {e:?}"),
614
615
616
                    }
                }

617
618
619
                // Handle router deletion events via discovery
                Some(router_event_result) = router_event_stream.next() => {
                    let Ok(router_event) = router_event_result else {
620
621
622
                        continue;
                    };

623
624
                    let DiscoveryEvent::Removed(router_instance_id) = router_event else {
                        // We only care about removals for cleaning up consumers
625
626
627
                        continue;
                    };

628
629
                    // The consumer UUID is the instance_id in hex format
                    let consumer_to_delete = router_instance_id.to_string();
630

631
                    tracing::info!(
632
                        "DISCOVERY: Router instance {router_instance_id} removed, attempting to delete orphaned consumer: {consumer_to_delete}"
633
                    );
634

635
636
637
                    // Delete the consumer (allow race condition if multiple routers try to delete)
                    if let Err(e) = nats_queue.shutdown(Some(consumer_to_delete.clone())).await {
                        tracing::warn!("Failed to delete consumer {consumer_to_delete}: {e}");
638
                    } else {
639
                        tracing::info!("Successfully deleted orphaned consumer: {consumer_to_delete}");
640
641
642
643
644
645
646
647
648
649
650
651
652
653
                    }
                }
            }
        }

        // Clean up the queue and remove the durable consumer
        if let Err(e) = nats_queue.shutdown(None).await {
            tracing::warn!("Failed to shutdown NatsQueue: {e}");
        }
    });

    Ok(())
}

654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
/// Start a simplified background task for event consumption using NATS Core.
///
/// This is used when local indexer mode is enabled. Unlike `start_kv_router_background`,
/// this function:
/// - Uses NATS Core pub/sub instead of JetStream
/// - Does not support snapshots, purging, or durable consumers
/// - On worker Added: dumps worker's local indexer into router
/// - On worker Removed: removes worker from router indexer
///
/// This is appropriate when workers have local indexers enabled.
pub async fn start_kv_router_background_nats_core(
    component: Component,
    kv_events_tx: mpsc::Sender<RouterEvent>,
    remove_worker_tx: mpsc::Sender<WorkerId>,
    cancellation_token: CancellationToken,
    worker_query_client: WorkerQueryClient,
) -> Result<()> {
    // Subscribe to KV events using NATS Core
    let mut subscriber = component.subscribe(KV_EVENT_SUBJECT).await?;
673
    let kv_event_subject = format!("{}.{}", component.subject(), KV_EVENT_SUBJECT);
674
675

    tracing::info!(
676
677
        subject = %kv_event_subject,
        "KV Router using NATS Core subscription (local_indexer mode)"
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
    );

    // Get the generate endpoint and watch for instance events (add/remove)
    let discovery_client = component.drt().discovery();
    let generate_discovery_key = DiscoveryQuery::Endpoint {
        namespace: component.namespace().name().to_string(),
        component: component.name().to_string(),
        endpoint: "generate".to_string(),
    };
    let mut instance_event_stream = discovery_client
        .list_and_watch(generate_discovery_key, Some(cancellation_token.clone()))
        .await?;

    tokio::spawn(async move {
        // Track last received event ID per worker for gap detection
        let mut last_event_ids: HashMap<WorkerId, u64> = HashMap::new();

        loop {
            tokio::select! {
                biased;

                _ = cancellation_token.cancelled() => {
                    tracing::debug!("KV Router NATS Core background task received cancellation signal");
                    break;
                }

                // Handle generate endpoint instance add/remove events
                Some(discovery_event_result) = instance_event_stream.next() => {
                    let Ok(discovery_event) = discovery_event_result else {
                        continue;
                    };

                    match discovery_event {
                        DiscoveryEvent::Added(_instance) => {
                            // Extract worker_id from the instance
                            let worker_id = _instance.instance_id();

                            tracing::info!(
716
                                "DISCOVERY: Worker {worker_id} added, dumping local indexer into router"
717
718
719
720
721
722
723
724
725
726
727
728
729
730
                            );

                            // Query worker's local indexer and dump all events
                            match recover_from_worker(
                                &worker_query_client,
                                worker_id,
                                None, // Start from beginning
                                None, // Get all events
                                &kv_events_tx,
                            )
                            .await
                            {
                                Ok(count) => {
                                    tracing::info!(
731
                                        "Successfully dumped worker {worker_id}'s local indexer, recovered {count} events"
732
733
734
735
                                    );
                                }
                                Err(e) => {
                                    tracing::warn!(
736
                                        "Failed to dump worker {worker_id}'s local indexer (may not have local indexer enabled): {e}"
737
738
739
740
741
742
                                    );
                                }
                            }
                        }
                        DiscoveryEvent::Removed(worker_id) => {
                            tracing::warn!(
743
                                "DISCOVERY: Worker {worker_id} removed, removing from router indexer"
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
                            );

                            if let Err(e) = remove_worker_tx.send(worker_id).await {
                                tracing::warn!("Failed to send worker removal for worker {worker_id}: {e}");
                            }
                        }
                    }
                }

                // Handle event consumption from NATS Core subscription
                Some(msg) = subscriber.next() => {
                    let event: RouterEvent = match serde_json::from_slice(&msg.payload) {
                        Ok(event) => event,
                        Err(e) => {
                            tracing::warn!("Failed to deserialize RouterEvent from NATS Core: {e:?}");
                            continue;
                        }
                    };

                    let worker_id = event.worker_id;
                    let event_id = event.event.event_id;

                    // Gap detection: check if event ID is monotonically increasing per worker
                    // Note: event_id <= last_id is duplicate/out-of-order, apply anyway (idempotent)
                    if let Some(&last_id) = last_event_ids.get(&worker_id)
                        && event_id > last_id + 1
                    {
                        // Gap detected - recover missing events before processing current
                        let gap_start = last_id + 1;
                        let gap_end = event_id - 1;
774
                        let gap_size = gap_end - gap_start + 1;
775
                        tracing::warn!(
776
                            "Event ID gap detected for worker {worker_id}, recovering events [{gap_start}, {gap_end}], gap_size: {gap_size}"
777
778
779
780
781
782
783
784
785
786
787
788
789
                        );

                        // Note: While recovering, new events may queue in the NATS subscriber's
                        // internal buffer. We don't explicitly buffer them here for simplicity.
                        // The subscriber will process them in order after recovery completes.
                        if let Err(e) = recover_from_worker(
                            &worker_query_client,
                            worker_id,
                            Some(gap_start),
                            Some(gap_end),
                            &kv_events_tx,
                        ).await {
                            tracing::error!(
790
                                "Failed to recover gap events for worker {worker_id} (gap_start: {gap_start}, gap_end: {gap_end}); proceeding with current event anyway: {e}"
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
                            );
                            // Note: If recovery fails, we still apply the current event.
                            // The tree will have a gap, but it's better than dropping the event.
                        }
                    }
                    // First event from this worker is always valid - we accept whatever ID it has.
                    // This handles initial startup and worker restarts without requiring event 0.

                    // Update last seen event ID (use max to handle out-of-order)
                    last_event_ids
                        .entry(worker_id)
                        .and_modify(|id| *id = (*id).max(event_id))
                        .or_insert(event_id);

                    // Forward the RouterEvent to the indexer
                    if let Err(e) = kv_events_tx.send(event).await {
                        tracing::warn!(
                            "failed to send kv event to indexer; shutting down: {e:?}"
                        );
                        break;
                    }
                }
            }
        }

        tracing::debug!("KV Router NATS Core background task exiting");
    });

    Ok(())
}

822
/// Cleanup orphaned NATS consumers that no longer have corresponding router entries
823
824
825
async fn cleanup_orphaned_consumers(
    nats_queue: &mut NatsQueue,
    component: &Component,
826
    consumer_id: &str,
827
828
829
830
831
) {
    let Ok(consumers) = nats_queue.list_consumers().await else {
        return;
    };

832
833
834
835
836
837
838
    // Get active routers from discovery
    let discovery = component.drt().discovery();
    let Ok(router_instances) = discovery
        .list(router_discovery_query(component.namespace().name()))
        .await
    else {
        tracing::debug!("Failed to list router instances from discovery, skipping cleanup");
839
840
841
        return;
    };

842
843
    // Build set of active router instance IDs
    let active_instance_ids: HashSet<String> = router_instances
844
        .iter()
845
        .map(|instance| instance.instance_id().to_string())
846
847
848
        .collect();

    for consumer in consumers {
849
        if consumer == consumer_id {
850
851
852
            // Never delete myself (extra/redundant safeguard)
            continue;
        }
853
        if !active_instance_ids.contains(&consumer) {
854
            tracing::info!("Cleaning up orphaned consumer: {consumer}");
855
856
857
858
            let _ = nats_queue.shutdown(Some(consumer)).await;
        }
    }
}