subscriber.rs 25 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, EventTransportKind},
11
    prelude::*,
12
    transports::event_plane::EventSubscriber,
13
    transports::nats::{NatsQueue, Slug},
14
};
15
use futures::StreamExt;
16
use rand::Rng;
17
18
use tokio_util::sync::CancellationToken;

19
use crate::kv_router::{
Yan Ru Pei's avatar
Yan Ru Pei committed
20
    Indexer, KV_EVENT_SUBJECT, KvRouterConfig, RADIX_STATE_BUCKET, RADIX_STATE_FILE,
21
    protocols::{DpRank, RouterEvent, WorkerId},
22
    router_discovery_query,
23
    worker_query::WorkerQueryClient,
24
25
};

26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/// Helper function to create a KV stream name from a component and subject.
///
/// Generates a slugified stream name in the format:
/// `namespace-{namespace}-component-{component}-{subject}`
fn create_kv_stream_name(component: &Component, subject: &str) -> String {
    Slug::slugify(&format!(
        "namespace.{}.component.{}.{}",
        component.namespace().name(),
        component.name(),
        subject
    ))
    .to_string()
    .replace("_", "-")
}

41
42
43
44
45
46
47
/// 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;

48
49
50
51
// ============================================================================
// Discovery Helpers
// ============================================================================

52
53
54
/// Get the instance discovery stream for monitoring worker add/remove events.
/// Waits for at least one instance to be discovered before returning.
async fn get_instance_discovery_stream(
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
    component: &Component,
    cancellation_token: &CancellationToken,
) -> Result<std::pin::Pin<Box<dyn futures::Stream<Item = Result<DiscoveryEvent>> + Send>>> {
    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 stream = discovery_client
        .list_and_watch(generate_discovery_key, Some(cancellation_token.clone()))
        .await?
        .peekable();

    tracing::info!("KV subscriber waiting for at least one worker instance...");
    std::pin::Pin::new(&mut stream).peek().await;

    Ok(Box::pin(stream))
}

76
77
78
79
// ============================================================================
// Snapshot Management
// ============================================================================

80
81
82
83
84
/// 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,
Yan Ru Pei's avatar
Yan Ru Pei committed
85
    indexer: &Indexer,
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
) -> 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 {
Yan Ru Pei's avatar
Yan Ru Pei committed
148
        indexer.apply_event(event).await;
149
150
151
152
153
154
    }
    tracing::info!("Successfully sent all initial events to indexer");

    Ok(())
}

155
156
157
158
159
/// Resources required for snapshot operations
#[derive(Clone)]
struct SnapshotResources {
    nats_client: dynamo_runtime::transports::nats::Client,
    bucket_name: String,
160
    instances_rx: tokio::sync::watch::Receiver<Vec<dynamo_runtime::component::Instance>>,
Yan Ru Pei's avatar
Yan Ru Pei committed
161
    indexer: Indexer,
162
163
164
}

impl SnapshotResources {
165
    /// Perform snapshot upload and purge operations
Yan Ru Pei's avatar
Yan Ru Pei committed
166
    async fn purge_then_snapshot(&self, nats_queue: &mut NatsQueue) -> anyhow::Result<()> {
167
168
169
170
171
        tracing::info!("Purging acknowledged messages and performing snapshot of radix tree");
        let start_time = std::time::Instant::now();

        // Clean up stale workers before snapshot
        let current_instances = self.instances_rx.borrow().clone();
172
        let current_worker_ids: std::collections::HashSet<u64> = current_instances
173
174
175
176
            .iter()
            .map(|instance| instance.instance_id)
            .collect();

Yan Ru Pei's avatar
Yan Ru Pei committed
177
178
179
180
181
        let indexer_worker_ids = self.indexer.get_workers().await;
        for worker_id in indexer_worker_ids {
            if !current_worker_ids.contains(&worker_id) {
                tracing::info!("Removing stale worker {worker_id} from indexer during snapshot");
                self.indexer.remove_worker(worker_id).await;
182
183
184
185
186
187
188
            }
        }

        // 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)
Yan Ru Pei's avatar
Yan Ru Pei committed
189
190
191
        let events = self
            .indexer
            .dump_events()
192
            .await
Yan Ru Pei's avatar
Yan Ru Pei committed
193
            .map_err(|e| anyhow::anyhow!("Failed to dump events for snapshot: {e:?}"))?;
194

195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
        // 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;
            }
212

213
214
215
216
217
            tracing::info!(
                "Successfully uploaded snapshot with {event_count} events to bucket {bucket_name} in {}ms",
                start_time.elapsed().as_millis()
            );
        });
218
219
220

        Ok(())
    }
221
222
223
224
225
}

/// Start a unified background task for event consumption and optional snapshot management
pub async fn start_kv_router_background(
    component: Component,
226
    consumer_id: String,
Yan Ru Pei's avatar
Yan Ru Pei committed
227
    indexer: Indexer,
228
    kv_router_config: &KvRouterConfig,
229
) -> Result<()> {
230
231
232
    let cancellation_token = component.drt().primary_token();
    let router_snapshot_threshold = kv_router_config.router_snapshot_threshold;
    let router_reset_states = kv_router_config.router_reset_states;
233
    // Set up NATS connections
234
    let stream_name = create_kv_stream_name(&component, KV_EVENT_SUBJECT);
235
236
    let nats_server = std::env::var(env_nats::NATS_SERVER)
        .unwrap_or_else(|_| "nats://localhost:4222".to_string());
237
238
239
240
241
242

    // 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
243
        consumer_id.clone(),
244
245
246
247
248
249
250
251
252
253
    );
    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
254
255
256
257
258
259
    let event_plane_subject = format!(
        "namespace.{}.component.{}",
        component.namespace().name(),
        component.name()
    );
    let bucket_name = Slug::slugify(&format!("{}-{RADIX_STATE_BUCKET}", event_plane_subject))
260
261
262
263
        .to_string()
        .replace("_", "-");

    // Handle initial state based on router_reset_states flag
264
265
    if !router_reset_states {
        // Try to download initial state from object store with stability check
Yan Ru Pei's avatar
Yan Ru Pei committed
266
        download_stable_snapshot(&nats_client, &bucket_name, &indexer).await?;
267
    } else {
268
269
270
271
272
273
274
        // 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:?}");
        }
    }

275
    // Cleanup orphaned consumers on startup
276
    cleanup_orphaned_consumers(&mut nats_queue, &component, &consumer_id).await;
277

278
279
    // Wait for at least one worker instance before proceeding
    let mut instance_event_stream =
280
        get_instance_discovery_stream(&component, &cancellation_token).await?;
281
282

    // Watch for router deletions to clean up orphaned consumers via discovery
283
284
    let generate_endpoint = component.endpoint("generate");
    let discovery_client = component.drt().discovery();
285
286
    let router_discovery_key =
        router_discovery_query(component.namespace().name(), component.name().to_string());
287
288
    let mut router_event_stream = discovery_client
        .list_and_watch(router_discovery_key, Some(cancellation_token.clone()))
289
        .await?;
290

291
292
    // Get instances_rx for tracking current workers
    let client = generate_endpoint.client().await?;
293
    let instances_rx = client.instance_source.as_ref().clone();
294

Yan Ru Pei's avatar
Yan Ru Pei committed
295
296
297
298
299
300
301
    // Only set up snapshot-related resources if snapshot threshold is configured
    let snapshot_resources = router_snapshot_threshold.map(|_| SnapshotResources {
        nats_client,
        bucket_name,
        instances_rx,
        indexer: indexer.clone(),
    });
302

303
    tokio::spawn(async move {
304
305
306
307
308
309
310
        // 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);
311
312
313
314
315
316
317
318
319
        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
320
                    // TODO: durable consumer cannot cleanup if ungraceful shutdown (crash)
321
322
323
324
325
326
                    if let Err(e) = nats_queue.shutdown(None).await {
                        tracing::warn!("Failed to shutdown NatsQueue: {e}");
                    }
                    break;
                }

327
                // Handle generate endpoint instance deletion events
328
329
                Some(discovery_event_result) = instance_event_stream.next() => {
                    let Ok(discovery_event) = discovery_event_result else {
330
331
332
                        continue;
                    };

333
                    let DiscoveryEvent::Removed(id) = discovery_event else {
334
335
336
                        continue;
                    };

337
338
                    let worker_id = id.instance_id();

339
                    tracing::warn!(
340
                        "DISCOVERY: Generate endpoint instance removed, removing worker {worker_id}"
341
                    );
342

Yan Ru Pei's avatar
Yan Ru Pei committed
343
                    indexer.remove_worker(worker_id).await;
344
345
                }

346
347
348
349
350
351
352
353
354
355
356
357
358
                // 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
Yan Ru Pei's avatar
Yan Ru Pei committed
359
                            indexer.apply_event(event).await;
360
361
362
363
364
365
366
367
368
369
370
                        },
                        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;
                        }
                    }
                }

371
                // Handle periodic stream checking and purging (only if snapshot_resources is provided)
372
                _ = check_interval.tick() => {
373
                    let Some(resources) = snapshot_resources.as_ref() else {
374
375
376
377
378
379
380
381
382
383
                        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;
384

385
386
387
388
                    if message_count <= threshold {
                        continue;
                    }

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

391
                    match resources.purge_then_snapshot(
392
393
394
                        &mut nats_queue,
                    ).await {
                        Ok(_) => tracing::info!("Successfully performed purge and snapshot"),
395
                        Err(e) => tracing::debug!("Could not perform purge and snapshot: {e:?}"),
396
397
398
                    }
                }

399
400
401
                // Handle router deletion events via discovery
                Some(router_event_result) = router_event_stream.next() => {
                    let Ok(router_event) = router_event_result else {
402
403
404
                        continue;
                    };

405
                    let DiscoveryEvent::Removed(id) = router_event else {
406
                        // We only care about removals for cleaning up consumers
407
408
409
                        continue;
                    };

410
411
                    let router_instance_id = id.instance_id();

412
                    // The consumer ID is the instance_id as a string
413
                    let consumer_to_delete = router_instance_id.to_string();
414

415
                    tracing::info!(
416
                        "DISCOVERY: Router instance {router_instance_id} removed, attempting to delete orphaned consumer: {consumer_to_delete}"
417
                    );
418

419
420
421
                    // 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}");
422
                    } else {
423
                        tracing::info!("Successfully deleted orphaned consumer: {consumer_to_delete}");
424
425
426
427
428
429
430
431
432
433
434
435
436
437
                    }
                }
            }
        }

        // 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(())
}

438
/// Start a simplified background task for event consumption using the event plane.
439
440
441
///
/// This is used when local indexer mode is enabled. Unlike `start_kv_router_background`,
/// this function:
442
/// - Uses the event plane (NATS Core or ZMQ) instead of JetStream
443
444
445
446
/// - 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
///
447
448
449
/// This function first recovers state from all currently registered workers before
/// spawning the background task, ensuring the router is ready before returning.
///
450
/// This is appropriate when workers have local indexers enabled.
451
pub async fn start_kv_router_background_event_plane(
452
    component: Component,
Yan Ru Pei's avatar
Yan Ru Pei committed
453
    indexer: Indexer,
454
    transport_kind: EventTransportKind,
455
) -> Result<()> {
456
    let cancellation_token = component.drt().primary_token();
457
458
    // WorkerQueryClient handles its own discovery loop for lifecycle + initial recovery.
    // No blocking wait — recovery happens asynchronously as endpoints are discovered.
Yan Ru Pei's avatar
Yan Ru Pei committed
459
    let worker_query_client = WorkerQueryClient::spawn(component.clone(), indexer.clone()).await?;
460

461
462
463
464
465
466
467
468
469
470
    // Subscribe to KV events using the selected event plane transport
    let mut subscriber =
        EventSubscriber::for_component_with_transport(&component, KV_EVENT_SUBJECT, transport_kind)
            .await?
            .typed::<RouterEvent>();
    let kv_event_subject = format!(
        "namespace.{}.component.{}.{}",
        component.namespace().name(),
        component.name(),
        KV_EVENT_SUBJECT
471
472
    );

473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
    match transport_kind {
        EventTransportKind::Nats => {
            tracing::info!(
                subject = %kv_event_subject,
                "KV Router using NATS Core subscription (local_indexer mode)"
            );
        }
        EventTransportKind::Zmq => {
            tracing::info!(
                subject = %kv_event_subject,
                "KV Router using ZMQ event plane subscription (local_indexer mode)"
            );
        }
    }

488
    tokio::spawn(async move {
489
490
491
        // Track last received event ID per (worker, dp_rank) for gap detection
        // Each dp_rank has its own monotonic event ID sequence
        let mut last_event_ids: HashMap<(WorkerId, DpRank), u64> = HashMap::new();
492
493
494
495
496
497

        loop {
            tokio::select! {
                biased;

                _ = cancellation_token.cancelled() => {
498
                    tracing::debug!("KV Router event plane background task received cancellation signal");
499
500
501
                    break;
                }

502
503
504
505
                // Handle event consumption from event plane subscription
                Some(result) = subscriber.next() => {
                    let (envelope, event) = match result {
                        Ok((envelope, event)) => (envelope, event),
506
                        Err(e) => {
507
                            tracing::warn!("Failed to receive RouterEvent from event plane: {e:?}");
508
509
510
511
512
                            continue;
                        }
                    };

                    let worker_id = event.worker_id;
513
                    let dp_rank = event.event.dp_rank;
514
                    let event_id = event.event.event_id;
515
                    let event_key = (worker_id, dp_rank);
516

517
518
519
520
521
522
                    tracing::trace!(
                        "Received event from publisher {} (seq {})",
                        envelope.publisher_id,
                        envelope.sequence
                    );

523
                    // Gap detection: check if event ID is monotonically increasing per (worker, dp_rank)
524
                    // Note: event_id <= last_id is duplicate/out-of-order, apply anyway (idempotent)
525
                    if let Some(&last_id) = last_event_ids.get(&event_key)
526
527
528
529
                        && event_id > last_id + 1
                    {
                        let gap_start = last_id + 1;
                        let gap_end = event_id - 1;
530
                        let gap_size = gap_end - gap_start + 1;
531
                        tracing::warn!(
532
                            "Event ID gap detected for worker {worker_id} dp_rank {dp_rank}, recovering events [{gap_start}, {gap_end}], gap_size: {gap_size}"
533
534
                        );

535
                        if let Err(e) = worker_query_client
536
                            .recover_from_worker(worker_id, dp_rank, Some(gap_start), Some(gap_end))
537
538
                            .await
                        {
539
                            tracing::error!(
540
                                "Failed to recover gap events for worker {worker_id} dp_rank {dp_rank} (gap_start: {gap_start}, gap_end: {gap_end}); proceeding with current event anyway: {e}"
541
542
543
544
545
546
                            );
                        }
                    }

                    // Update last seen event ID (use max to handle out-of-order)
                    last_event_ids
547
                        .entry(event_key)
548
549
550
551
                        .and_modify(|id| *id = (*id).max(event_id))
                        .or_insert(event_id);

                    // Forward the RouterEvent to the indexer
Yan Ru Pei's avatar
Yan Ru Pei committed
552
                    indexer.apply_event(event).await;
553
554
555
556
                }
            }
        }

557
        tracing::debug!("KV Router event plane background task exiting");
558
559
560
561
562
    });

    Ok(())
}

563
/// Cleanup orphaned NATS consumers that no longer have corresponding router entries
564
565
566
async fn cleanup_orphaned_consumers(
    nats_queue: &mut NatsQueue,
    component: &Component,
567
    consumer_id: &str,
568
569
570
571
572
) {
    let Ok(consumers) = nats_queue.list_consumers().await else {
        return;
    };

573
574
575
    // Get active routers from discovery
    let discovery = component.drt().discovery();
    let Ok(router_instances) = discovery
576
577
578
579
        .list(router_discovery_query(
            component.namespace().name(),
            component.name().to_string(),
        ))
580
581
582
        .await
    else {
        tracing::debug!("Failed to list router instances from discovery, skipping cleanup");
583
584
585
        return;
    };

586
587
    // Build set of active router instance IDs
    let active_instance_ids: HashSet<String> = router_instances
588
        .iter()
589
        .map(|instance| instance.instance_id().to_string())
590
591
592
        .collect();

    for consumer in consumers {
593
        if consumer == consumer_id {
594
595
596
            // Never delete myself (extra/redundant safeguard)
            continue;
        }
597
        if !active_instance_ids.contains(&consumer) {
598
            tracing::info!("Cleaning up orphaned consumer: {consumer}");
599
600
601
602
            let _ = nats_queue.shutdown(Some(consumer)).await;
        }
    }
}
603
604
605
606
607

/// Helper to decide which subscriber (JetStream or Event Plane) to start based on config
pub async fn start_subscriber(
    component: Component,
    kv_router_config: &KvRouterConfig,
Yan Ru Pei's avatar
Yan Ru Pei committed
608
    indexer: Indexer,
609
610
611
612
613
614
615
616
617
618
619
620
621
622
) -> Result<()> {
    let transport_kind = EventTransportKind::from_env_or_default();

    // Start subscriber - durable_kv_events flag determines the mode:
    // - durable_kv_events=false (default): Use NATS Core / generic event plane (requires workers to have local_indexer enabled)
    // - durable_kv_events=true: Use JetStream for durability and multi-replica consistency
    if kv_router_config.durable_kv_events {
        if transport_kind == EventTransportKind::Zmq {
            tracing::warn!(
                "--durable-kv-events requires NATS, but ZMQ event plane is configured; falling back to JetStream anyway"
            );
        }
        tracing::info!("Using JetStream subscription (--durable-kv-events enabled)");

623
624
        let consumer_id = component.drt().discovery().instance_id().to_string();
        start_kv_router_background(component, consumer_id, indexer, kv_router_config).await
625
626
627
628
629
630
631
632
633
634
635
636
637
638
    } else {
        if transport_kind == EventTransportKind::Zmq {
            if kv_router_config.router_snapshot_threshold.is_some()
                || kv_router_config.router_reset_states
            {
                tracing::warn!(
                    "ZMQ event plane does not support KV snapshots or state reset; ignoring snapshot/reset settings"
                );
            }
            tracing::info!("Using ZMQ event plane subscription (local_indexer mode)");
        } else {
            tracing::info!("Using NATS Core subscription (local_indexer mode)");
        }

639
        start_kv_router_background_event_plane(component, indexer, transport_kind).await
640
641
    }
}