worker.rs 65 KB
Newer Older
1
use super::{CircuitBreaker, CircuitBreakerConfig, WorkerError, WorkerResult};
Chang Su's avatar
Chang Su committed
2
use crate::grpc::SglangSchedulerClient;
3
use crate::metrics::RouterMetrics;
4
use async_trait::async_trait;
5
6
use futures;
use serde_json;
7
8
use std::fmt;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
9
use std::sync::{Arc, LazyLock};
Chang Su's avatar
Chang Su committed
10
use tokio::sync::Mutex;
11

12
// Shared HTTP client for worker operations (health checks, server info, etc.)
13
static WORKER_CLIENT: LazyLock<reqwest::Client> = LazyLock::new(|| {
14
15
16
    reqwest::Client::builder()
        .timeout(std::time::Duration::from_secs(30)) // Default timeout, overridden per request
        .build()
17
        .expect("Failed to create worker HTTP client")
18
19
20
21
22
23
24
25
26
27
28
});

/// Core worker abstraction that represents a backend service
#[async_trait]
pub trait Worker: Send + Sync + fmt::Debug {
    /// Get the worker's URL
    fn url(&self) -> &str;

    /// Get the worker's type (Regular, Prefill, or Decode)
    fn worker_type(&self) -> WorkerType;

29
30
31
    /// Get the worker's connection mode (HTTP or gRPC)
    fn connection_mode(&self) -> ConnectionMode;

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
    /// Check if the worker is currently healthy
    fn is_healthy(&self) -> bool;

    /// Set the worker's health status
    fn set_healthy(&self, healthy: bool);

    /// Perform an async health check on the worker
    async fn check_health_async(&self) -> WorkerResult<()>;

    /// Synchronous health check wrapper (for compatibility)
    fn check_health(&self) -> WorkerResult<()> {
        // Use a small runtime for synchronous contexts
        tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .map_err(|e| WorkerError::HealthCheckFailed {
                url: self.url().to_string(),
                reason: format!("Failed to create runtime: {}", e),
            })?
            .block_on(self.check_health_async())
    }

    /// Get the current load (number of active requests)
    fn load(&self) -> usize;

    /// Increment the load counter
    fn increment_load(&self);

    /// Decrement the load counter
    fn decrement_load(&self);

63
64
65
66
67
68
    /// Reset the load counter to 0 (for sync/recovery)
    fn reset_load(&self) {
        // Default implementation - does nothing
        // Workers that track load should override this
    }

69
70
71
72
73
74
75
76
77
78
79
    /// Get the number of processed requests
    fn processed_requests(&self) -> usize;

    /// Increment the processed requests counter
    fn increment_processed(&self);

    /// Get worker-specific metadata
    fn metadata(&self) -> &WorkerMetadata;

    /// Clone the worker (for trait objects)
    fn clone_worker(&self) -> Box<dyn Worker>;
80

81
82
83
84
85
86
87
88
89
90
    /// Get the circuit breaker for this worker
    fn circuit_breaker(&self) -> &CircuitBreaker;

    /// Check if the worker is available (healthy + circuit closed/half-open)
    fn is_available(&self) -> bool {
        self.is_healthy() && self.circuit_breaker().can_execute()
    }

    /// Record the outcome of a request to this worker
    fn record_outcome(&self, success: bool) {
91
92
93
94
95
96
        // Record outcome-level metric with worker label
        let outcome_str = if success { "success" } else { "failure" };
        RouterMetrics::record_cb_outcome(self.url(), outcome_str);

        // Record into circuit breaker and infer state change for metrics
        let before = self.circuit_breaker().state();
97
        self.circuit_breaker().record_outcome(success);
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
        let after = self.circuit_breaker().state();

        if before != after {
            let from = match before {
                crate::core::CircuitState::Closed => "closed",
                crate::core::CircuitState::Open => "open",
                crate::core::CircuitState::HalfOpen => "half_open",
            };
            let to = match after {
                crate::core::CircuitState::Closed => "closed",
                crate::core::CircuitState::Open => "open",
                crate::core::CircuitState::HalfOpen => "half_open",
            };
            RouterMetrics::record_cb_state_transition(self.url(), from, to);
        }

        let state_code = match self.circuit_breaker().state() {
            crate::core::CircuitState::Closed => 0u8,
            crate::core::CircuitState::Open => 1u8,
            crate::core::CircuitState::HalfOpen => 2u8,
        };
        RouterMetrics::set_cb_state(self.url(), state_code);
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
    // === DP-aware methods ===

    /// Check if this worker is DP-aware
    fn is_dp_aware(&self) -> bool {
        false
    }

    /// Get the base URL without any DP rank suffix
    fn base_url(&self) -> &str {
        self.url()
    }

    /// Get DP rank if this is a DP-aware worker
    fn dp_rank(&self) -> Option<usize> {
        None
    }

    /// Get DP size if this worker is part of a DP group
    fn dp_size(&self) -> Option<usize> {
        None
    }

    /// Transform a request for DP-aware routing
    async fn prepare_request(&self, req: serde_json::Value) -> WorkerResult<serde_json::Value> {
        Ok(req)
    }

    /// Get the actual endpoint URL for requests
    fn endpoint_url(&self, route: &str) -> String {
        format!("{}{}", self.base_url(), route)
    }

    /// Check if this worker can handle a specific request
    fn can_handle(&self, _req: &serde_json::Value) -> bool {
        true
    }
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

    // === Multi-router support ===

    // TODO: - Enhanced Worker Discovery
    // The Worker trait should handle async discovery of metadata from the worker itself
    // rather than having service discovery or other components query /get_server_info.
    // This keeps service discovery decoupled from worker-specific APIs.
    //
    // Proposed additions:
    // - async fn discover_metadata(&mut self) -> Result<(), Error>
    //   Query /get_server_info and populate metadata labels with model_id, priority, cost, etc.
    // - async fn validate_configuration(&self) -> Result<(), Error>
    //   Ensure worker has required configuration for its mode (e.g., tokenizer for gRPC)
    // - Make worker creation async to allow metadata discovery during initialization
    //
    // This way service discovery just calls router.add_worker() and the worker
    // handles its own metadata discovery internally.

    /// Get the model ID this worker serves
    fn model_id(&self) -> &str {
        self.metadata()
            .labels
            .get("model_id")
            .map(|s| s.as_str())
            .unwrap_or("unknown")
    }

    /// Get the priority of this worker (higher value = higher priority)
    fn priority(&self) -> u32 {
        self.metadata()
            .labels
            .get("priority")
            .and_then(|s| s.parse().ok())
            .unwrap_or(50) // Default priority is 50 (mid-range)
    }

    /// Get the cost factor of this worker (1.0 = baseline)
    fn cost(&self) -> f32 {
        self.metadata()
            .labels
            .get("cost")
            .and_then(|s| s.parse().ok())
            .unwrap_or(1.0)
    }

    /// Get the tokenizer path for this worker (gRPC mode only)
    fn tokenizer_path(&self) -> Option<&str> {
        self.metadata()
            .labels
            .get("tokenizer_path")
            .map(|s| s.as_str())
    }

    /// Get the reasoning parser type for this worker (gRPC mode only)
    fn reasoning_parser(&self) -> Option<&str> {
        self.metadata()
            .labels
            .get("reasoning_parser")
            .map(|s| s.as_str())
    }

    /// Get the tool parser type for this worker (gRPC mode only)
    fn tool_parser(&self) -> Option<&str> {
        self.metadata()
            .labels
            .get("tool_parser")
            .map(|s| s.as_str())
    }

    /// Get the chat template for this worker (gRPC mode only)
    fn chat_template(&self) -> Option<&str> {
        self.metadata()
            .labels
            .get("chat_template")
            .map(|s| s.as_str())
    }
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
/// Connection mode for worker communication
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ConnectionMode {
    /// HTTP/REST connection
    Http,
    /// gRPC connection
    Grpc {
        /// Optional port for gRPC endpoint (if different from URL)
        port: Option<u16>,
    },
}

impl fmt::Display for ConnectionMode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ConnectionMode::Http => write!(f, "HTTP"),
            ConnectionMode::Grpc { port } => match port {
                Some(p) => write!(f, "gRPC(port:{})", p),
                None => write!(f, "gRPC"),
            },
        }
    }
}

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
/// Worker type classification
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum WorkerType {
    /// Regular worker for standard routing
    Regular,
    /// Prefill worker for PD disaggregated mode
    Prefill {
        /// Bootstrap port for communication with decode workers
        bootstrap_port: Option<u16>,
    },
    /// Decode worker for PD disaggregated mode
    Decode,
}

impl fmt::Display for WorkerType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            WorkerType::Regular => write!(f, "Regular"),
            WorkerType::Prefill { bootstrap_port } => match bootstrap_port {
                Some(port) => write!(f, "Prefill(bootstrap:{})", port),
                None => write!(f, "Prefill"),
            },
            WorkerType::Decode => write!(f, "Decode"),
        }
    }
}

/// Health check configuration
#[derive(Debug, Clone)]
pub struct HealthConfig {
    /// Timeout for health checks in seconds
    pub timeout_secs: u64,
    /// Interval between health checks in seconds
    pub check_interval_secs: u64,
    /// Health check endpoint path
    pub endpoint: String,
296
297
298
299
    /// Number of consecutive failures before marking unhealthy
    pub failure_threshold: u32,
    /// Number of consecutive successes before marking healthy
    pub success_threshold: u32,
300
301
302
303
304
305
306
307
}

impl Default for HealthConfig {
    fn default() -> Self {
        Self {
            timeout_secs: 5,
            check_interval_secs: 30,
            endpoint: "/health".to_string(),
308
309
            failure_threshold: 3,
            success_threshold: 2,
310
311
312
313
314
315
316
317
318
319
320
        }
    }
}

/// Metadata associated with a worker
#[derive(Debug, Clone)]
pub struct WorkerMetadata {
    /// Worker URL
    pub url: String,
    /// Worker type
    pub worker_type: WorkerType,
321
322
    /// Connection mode
    pub connection_mode: ConnectionMode,
323
324
325
326
327
328
329
    /// Additional labels/tags
    pub labels: std::collections::HashMap<String, String>,
    /// Health check configuration
    pub health_config: HealthConfig,
}

/// Basic worker implementation
Chang Su's avatar
Chang Su committed
330
#[derive(Clone)]
331
332
333
334
335
pub struct BasicWorker {
    metadata: WorkerMetadata,
    load_counter: Arc<AtomicUsize>,
    processed_counter: Arc<AtomicUsize>,
    healthy: Arc<AtomicBool>,
336
337
    consecutive_failures: Arc<AtomicUsize>,
    consecutive_successes: Arc<AtomicUsize>,
338
    circuit_breaker: CircuitBreaker,
Chang Su's avatar
Chang Su committed
339
340
341
342
343
344
345
346
347
348
349
350
351
    /// Optional gRPC client for gRPC workers
    grpc_client: Option<Arc<Mutex<SglangSchedulerClient>>>,
}

impl fmt::Debug for BasicWorker {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("BasicWorker")
            .field("metadata", &self.metadata)
            .field("healthy", &self.healthy.load(Ordering::Relaxed))
            .field("circuit_breaker", &self.circuit_breaker)
            .field("has_grpc_client", &self.grpc_client.is_some())
            .finish()
    }
352
353
354
355
}

impl BasicWorker {
    pub fn new(url: String, worker_type: WorkerType) -> Self {
356
357
358
359
360
361
362
363
        Self::with_connection_mode(url, worker_type, ConnectionMode::Http)
    }

    pub fn with_connection_mode(
        url: String,
        worker_type: WorkerType,
        connection_mode: ConnectionMode,
    ) -> Self {
364
365
366
        let metadata = WorkerMetadata {
            url: url.clone(),
            worker_type,
367
            connection_mode,
368
369
370
371
372
373
374
375
376
            labels: std::collections::HashMap::new(),
            health_config: HealthConfig::default(),
        };

        Self {
            metadata,
            load_counter: Arc::new(AtomicUsize::new(0)),
            processed_counter: Arc::new(AtomicUsize::new(0)),
            healthy: Arc::new(AtomicBool::new(true)),
377
378
            consecutive_failures: Arc::new(AtomicUsize::new(0)),
            consecutive_successes: Arc::new(AtomicUsize::new(0)),
379
            circuit_breaker: CircuitBreaker::new(),
Chang Su's avatar
Chang Su committed
380
            grpc_client: None,
381
382
383
384
385
386
387
388
389
390
391
392
        }
    }

    pub fn with_labels(mut self, labels: std::collections::HashMap<String, String>) -> Self {
        self.metadata.labels = labels;
        self
    }

    pub fn with_health_config(mut self, config: HealthConfig) -> Self {
        self.metadata.health_config = config;
        self
    }
393

394
395
396
397
398
    pub fn with_circuit_breaker_config(mut self, config: CircuitBreakerConfig) -> Self {
        self.circuit_breaker = CircuitBreaker::with_config(config);
        self
    }

Chang Su's avatar
Chang Su committed
399
400
401
402
403
404
    /// Set the gRPC client for gRPC workers
    pub fn with_grpc_client(mut self, client: SglangSchedulerClient) -> Self {
        self.grpc_client = Some(Arc::new(Mutex::new(client)));
        self
    }

405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
    pub fn normalised_url(&self) -> WorkerResult<&str> {
        if self.url().contains("@") {
            // Need to extract the URL from "http://host:port@dp_rank"
            let parts: Vec<&str> = self.url().split('@').collect();
            if parts.len() != 2 {
                return Err(WorkerError::InvalidUrl {
                    url: self.url().to_string(),
                });
            }
            // Ensure the second part (the dp_rank) can be parsed as an integer
            match parts[1].parse::<usize>() {
                Ok(_) => Ok(parts[0]),
                Err(_) => Err(WorkerError::InvalidUrl {
                    url: self.url().to_string(),
                }),
            }
        } else {
            Ok(self.url())
        }
    }
425
426
427
428
429
430
431
432
433
434
435
436
}

#[async_trait]
impl Worker for BasicWorker {
    fn url(&self) -> &str {
        &self.metadata.url
    }

    fn worker_type(&self) -> WorkerType {
        self.metadata.worker_type.clone()
    }

437
438
439
440
    fn connection_mode(&self) -> ConnectionMode {
        self.metadata.connection_mode.clone()
    }

441
442
443
444
445
446
    fn is_healthy(&self) -> bool {
        self.healthy.load(Ordering::Acquire)
    }

    fn set_healthy(&self, healthy: bool) {
        self.healthy.store(healthy, Ordering::Release);
447
        RouterMetrics::set_worker_health(self.url(), healthy);
448
449
450
451
452
    }

    async fn check_health_async(&self) -> WorkerResult<()> {
        use std::time::Duration;

Chang Su's avatar
Chang Su committed
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
        let health_result = match &self.metadata.connection_mode {
            ConnectionMode::Http => {
                // Perform HTTP health check
                let url = self.normalised_url()?;
                let health_url = format!("{}{}", url, self.metadata.health_config.endpoint);
                let timeout = Duration::from_secs(self.metadata.health_config.timeout_secs);

                // Use the shared client with a custom timeout for this request
                match WORKER_CLIENT.get(&health_url).timeout(timeout).send().await {
                    Ok(response) => response.status().is_success(),
                    Err(_) => false,
                }
            }
            ConnectionMode::Grpc { .. } => {
                // Perform gRPC health check
                if let Some(grpc_client) = &self.grpc_client {
                    let mut client = grpc_client.lock().await;
                    match client.health_check().await {
                        Ok(response) => {
                            tracing::debug!(
                                "gRPC health check succeeded for {}: healthy={}",
                                self.metadata.url,
                                response.healthy
                            );
                            response.healthy
                        }
                        Err(e) => {
                            tracing::warn!(
                                "gRPC health check RPC failed for {}: {:?}",
                                self.metadata.url,
                                e
                            );
                            false
                        }
                    }
                } else {
                    tracing::error!("No gRPC client available for worker {}", self.metadata.url);
                    false
                }
            }
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
        };

        if health_result {
            // Health check succeeded
            self.consecutive_failures.store(0, Ordering::Release);
            let successes = self.consecutive_successes.fetch_add(1, Ordering::AcqRel) + 1;

            // Mark healthy if we've reached the success threshold
            if !self.is_healthy()
                && successes >= self.metadata.health_config.success_threshold as usize
            {
                self.set_healthy(true);
                self.consecutive_successes.store(0, Ordering::Release);
            }
            Ok(())
        } else {
            // Health check failed
            self.consecutive_successes.store(0, Ordering::Release);
            let failures = self.consecutive_failures.fetch_add(1, Ordering::AcqRel) + 1;

            // Mark unhealthy if we've reached the failure threshold
            if self.is_healthy()
                && failures >= self.metadata.health_config.failure_threshold as usize
            {
517
                self.set_healthy(false);
518
                self.consecutive_failures.store(0, Ordering::Release);
519
            }
520
521

            Err(WorkerError::HealthCheckFailed {
Chang Su's avatar
Chang Su committed
522
                url: self.metadata.url.clone(),
523
524
                reason: format!("Health check failed (consecutive failures: {})", failures),
            })
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
        }
    }

    fn load(&self) -> usize {
        self.load_counter.load(Ordering::Relaxed)
    }

    fn increment_load(&self) {
        self.load_counter.fetch_add(1, Ordering::Relaxed);
    }

    fn decrement_load(&self) {
        self.load_counter
            .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| {
                current.checked_sub(1)
            })
            .ok();
    }

544
545
546
547
    fn reset_load(&self) {
        self.load_counter.store(0, Ordering::Relaxed);
    }

548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
    fn processed_requests(&self) -> usize {
        self.processed_counter.load(Ordering::Relaxed)
    }

    fn increment_processed(&self) {
        self.processed_counter.fetch_add(1, Ordering::Relaxed);
    }

    fn metadata(&self) -> &WorkerMetadata {
        &self.metadata
    }

    fn clone_worker(&self) -> Box<dyn Worker> {
        Box::new(self.clone())
    }
563
564
565
566

    fn circuit_breaker(&self) -> &CircuitBreaker {
        &self.circuit_breaker
    }
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
/// A DP-aware worker that handles data-parallel routing
#[derive(Debug, Clone)]
pub struct DPAwareWorker {
    /// The underlying basic worker
    base_worker: BasicWorker,
    /// DP rank for this worker
    dp_rank: usize,
    /// Total DP size
    dp_size: usize,
    /// Base URL without DP suffix
    base_url: String,
}

impl DPAwareWorker {
    /// Create a new DP-aware worker of any type
    pub fn new(base_url: String, dp_rank: usize, dp_size: usize, worker_type: WorkerType) -> Self {
        // Create URL with DP rank suffix for identification
        let worker_url = format!("{}@{}", base_url, dp_rank);
        let base_worker = BasicWorker::new(worker_url, worker_type);

        Self {
            base_worker,
            dp_rank,
            dp_size,
            base_url,
        }
    }
}

#[async_trait]
impl Worker for DPAwareWorker {
    fn url(&self) -> &str {
        self.base_worker.url()
    }

    fn worker_type(&self) -> WorkerType {
        self.base_worker.worker_type()
    }

608
609
610
611
    fn connection_mode(&self) -> ConnectionMode {
        self.base_worker.connection_mode()
    }

612
613
614
615
616
617
618
619
620
    fn is_healthy(&self) -> bool {
        self.base_worker.is_healthy()
    }

    fn set_healthy(&self, healthy: bool) {
        self.base_worker.set_healthy(healthy);
    }

    async fn check_health_async(&self) -> WorkerResult<()> {
621
622
        // Delegate to the base worker's health check logic
        self.base_worker.check_health_async().await
623
624
625
626
627
628
629
630
631
632
633
634
635
636
    }

    fn load(&self) -> usize {
        self.base_worker.load()
    }

    fn increment_load(&self) {
        self.base_worker.increment_load();
    }

    fn decrement_load(&self) {
        self.base_worker.decrement_load();
    }

637
638
639
640
    fn reset_load(&self) {
        self.base_worker.reset_load();
    }

641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
    fn processed_requests(&self) -> usize {
        self.base_worker.processed_requests()
    }

    fn increment_processed(&self) {
        self.base_worker.increment_processed();
    }

    fn metadata(&self) -> &WorkerMetadata {
        self.base_worker.metadata()
    }

    fn clone_worker(&self) -> Box<dyn Worker> {
        Box::new(self.clone())
    }

657
658
659
660
    fn circuit_breaker(&self) -> &CircuitBreaker {
        self.base_worker.circuit_breaker()
    }

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
    // DP-aware specific implementations

    fn is_dp_aware(&self) -> bool {
        true
    }

    fn base_url(&self) -> &str {
        &self.base_url
    }

    fn dp_rank(&self) -> Option<usize> {
        Some(self.dp_rank)
    }

    fn dp_size(&self) -> Option<usize> {
        Some(self.dp_size)
    }

    async fn prepare_request(&self, mut req: serde_json::Value) -> WorkerResult<serde_json::Value> {
        // Inject data_parallel_rank into the request
        if let Some(map) = req.as_object_mut() {
            map.insert(
                "data_parallel_rank".to_string(),
                serde_json::json!(self.dp_rank),
            );
            Ok(req)
        } else {
            Err(WorkerError::InvalidConfiguration {
                message: "Request must be a JSON object for DP-aware routing".to_string(),
            })
        }
    }

    fn endpoint_url(&self, route: &str) -> String {
        // Use base URL for actual requests
        format!("{}{}", self.base_url, route)
    }
}

700
701
702
703
704
705
706
707
708
/// Worker factory for creating workers of different types
pub struct WorkerFactory;

impl WorkerFactory {
    /// Create a regular worker
    pub fn create_regular(url: String) -> Box<dyn Worker> {
        Box::new(BasicWorker::new(url, WorkerType::Regular))
    }

709
710
711
712
713
714
715
716
717
718
719
    /// Create a regular worker with custom circuit breaker configuration
    pub fn create_regular_with_config(
        url: String,
        circuit_breaker_config: CircuitBreakerConfig,
    ) -> Box<dyn Worker> {
        Box::new(
            BasicWorker::new(url, WorkerType::Regular)
                .with_circuit_breaker_config(circuit_breaker_config),
        )
    }

720
721
722
723
724
725
726
727
    /// Create a prefill worker with optional bootstrap port
    pub fn create_prefill(url: String, bootstrap_port: Option<u16>) -> Box<dyn Worker> {
        Box::new(BasicWorker::new(
            url,
            WorkerType::Prefill { bootstrap_port },
        ))
    }

728
729
730
731
732
733
734
735
736
737
738
739
    /// Create a prefill worker with custom circuit breaker configuration
    pub fn create_prefill_with_config(
        url: String,
        bootstrap_port: Option<u16>,
        circuit_breaker_config: CircuitBreakerConfig,
    ) -> Box<dyn Worker> {
        Box::new(
            BasicWorker::new(url, WorkerType::Prefill { bootstrap_port })
                .with_circuit_breaker_config(circuit_breaker_config),
        )
    }

740
741
742
743
744
    /// Create a decode worker
    pub fn create_decode(url: String) -> Box<dyn Worker> {
        Box::new(BasicWorker::new(url, WorkerType::Decode))
    }

745
746
747
748
749
750
751
752
753
754
755
    /// Create a decode worker with custom circuit breaker configuration
    pub fn create_decode_with_config(
        url: String,
        circuit_breaker_config: CircuitBreakerConfig,
    ) -> Box<dyn Worker> {
        Box::new(
            BasicWorker::new(url, WorkerType::Decode)
                .with_circuit_breaker_config(circuit_breaker_config),
        )
    }

756
    /// Create workers from URLs with automatic type detection
757
    #[allow(clippy::type_complexity)]
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
    pub fn create_from_urls(
        regular_urls: Vec<String>,
        prefill_urls: Vec<(String, Option<u16>)>,
        decode_urls: Vec<String>,
    ) -> (
        Vec<Box<dyn Worker>>,
        Vec<Box<dyn Worker>>,
        Vec<Box<dyn Worker>>,
    ) {
        let regular_workers: Vec<Box<dyn Worker>> =
            regular_urls.into_iter().map(Self::create_regular).collect();

        let prefill_workers: Vec<Box<dyn Worker>> = prefill_urls
            .into_iter()
            .map(|(url, port)| Self::create_prefill(url, port))
            .collect();

        let decode_workers: Vec<Box<dyn Worker>> =
            decode_urls.into_iter().map(Self::create_decode).collect();

        (regular_workers, prefill_workers, decode_workers)
    }
780

781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
    /// Create a gRPC worker
    pub fn create_grpc(url: String, worker_type: WorkerType, port: Option<u16>) -> Box<dyn Worker> {
        Box::new(BasicWorker::with_connection_mode(
            url,
            worker_type,
            ConnectionMode::Grpc { port },
        ))
    }

    /// Create a gRPC worker with custom circuit breaker configuration
    pub fn create_grpc_with_config(
        url: String,
        worker_type: WorkerType,
        port: Option<u16>,
        circuit_breaker_config: CircuitBreakerConfig,
    ) -> Box<dyn Worker> {
        Box::new(
            BasicWorker::with_connection_mode(url, worker_type, ConnectionMode::Grpc { port })
                .with_circuit_breaker_config(circuit_breaker_config),
        )
    }

803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
    /// Create a regular worker with custom labels (for multi-router support)
    pub fn create_regular_with_labels(
        url: String,
        labels: std::collections::HashMap<String, String>,
        circuit_breaker_config: CircuitBreakerConfig,
    ) -> Box<dyn Worker> {
        let mut worker = BasicWorker::new(url.clone(), WorkerType::Regular)
            .with_circuit_breaker_config(circuit_breaker_config);

        // Add labels to metadata
        worker.metadata.labels = labels;

        Box::new(worker)
    }

818
819
820
821
822
823
824
825
826
827
828
829
    /// Create a DP-aware worker of specified type
    pub fn create_dp_aware(
        base_url: String,
        dp_rank: usize,
        dp_size: usize,
        worker_type: WorkerType,
    ) -> Box<dyn Worker> {
        Box::new(DPAwareWorker::new(base_url, dp_rank, dp_size, worker_type))
    }

    /// Get DP size from a worker
    async fn get_worker_dp_size(url: &str, api_key: &Option<String>) -> WorkerResult<usize> {
830
        let mut req_builder = WORKER_CLIENT.get(format!("{}/get_server_info", url));
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943

        if let Some(key) = api_key {
            req_builder = req_builder.bearer_auth(key);
        }

        let response = req_builder
            .send()
            .await
            .map_err(|e| WorkerError::NetworkError {
                url: url.to_string(),
                error: e.to_string(),
            })?;

        if !response.status().is_success() {
            return Err(WorkerError::NetworkError {
                url: url.to_string(),
                error: format!("Server returned: {}", response.status()),
            });
        }

        let info: serde_json::Value =
            response
                .json()
                .await
                .map_err(|e| WorkerError::NetworkError {
                    url: url.to_string(),
                    error: format!("Failed to parse JSON: {}", e),
                })?;

        let dp_size = info
            .get("dp_size")
            .and_then(|v| v.as_u64())
            .ok_or_else(|| WorkerError::InvalidConfiguration {
                message: "dp_size not found in server info".to_string(),
            })?;

        if dp_size > usize::MAX as u64 {
            return Err(WorkerError::InvalidConfiguration {
                message: format!("dp_size is too large: {}", dp_size),
            });
        }

        Ok(dp_size as usize)
    }

    /// Private helper to create DP-aware workers of any type
    async fn create_dp_aware_workers_of_type(
        url: &str,
        api_key: &Option<String>,
        worker_type: WorkerType,
    ) -> WorkerResult<Vec<Box<dyn Worker>>> {
        let dp_size = Self::get_worker_dp_size(url, api_key).await?;

        let workers = (0..dp_size)
            .map(|rank| Self::create_dp_aware(url.to_string(), rank, dp_size, worker_type.clone()))
            .collect();

        Ok(workers)
    }

    /// Create DP-aware regular workers from a single URL
    pub async fn create_dp_aware_regular_workers(
        url: &str,
        api_key: &Option<String>,
    ) -> WorkerResult<Vec<Box<dyn Worker>>> {
        Self::create_dp_aware_workers_of_type(url, api_key, WorkerType::Regular).await
    }

    /// Create DP-aware prefill workers from a single URL
    pub async fn create_dp_aware_prefill_workers(
        url: &str,
        bootstrap_port: Option<u16>,
        api_key: &Option<String>,
    ) -> WorkerResult<Vec<Box<dyn Worker>>> {
        Self::create_dp_aware_workers_of_type(url, api_key, WorkerType::Prefill { bootstrap_port })
            .await
    }

    /// Create DP-aware decode workers from a single URL
    pub async fn create_dp_aware_decode_workers(
        url: &str,
        api_key: &Option<String>,
    ) -> WorkerResult<Vec<Box<dyn Worker>>> {
        Self::create_dp_aware_workers_of_type(url, api_key, WorkerType::Decode).await
    }

    /// Create workers based on configuration (for regular router)
    pub async fn create_workers(
        urls: Vec<String>,
        dp_aware: bool,
        api_key: &Option<String>,
    ) -> WorkerResult<Vec<Box<dyn Worker>>> {
        if dp_aware {
            // Create futures for all worker creations
            let worker_futs = urls
                .iter()
                .map(|url| Self::create_dp_aware_regular_workers(url, api_key));

            // Execute all futures concurrently and flatten results
            let all_workers = futures::future::try_join_all(worker_futs)
                .await?
                .into_iter()
                .flatten()
                .collect();

            Ok(all_workers)
        } else {
            Ok(urls
                .into_iter()
                .map(|url| Self::create_regular(url))
                .collect())
        }
    }
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
}

/// Helper trait for collections of workers
pub trait WorkerCollection {
    fn healthy_workers(&self) -> Vec<&dyn Worker>;
    fn total_load(&self) -> usize;
    fn find_worker(&self, url: &str) -> Option<&dyn Worker>;
    fn find_worker_mut(&mut self, url: &str) -> Option<&mut Box<dyn Worker>>;
}

impl WorkerCollection for Vec<Box<dyn Worker>> {
    fn healthy_workers(&self) -> Vec<&dyn Worker> {
        self.iter()
            .filter(|w| w.is_healthy())
            .map(|w| w.as_ref())
            .collect()
    }

    fn total_load(&self) -> usize {
        self.iter().map(|w| w.load()).sum()
    }

    fn find_worker(&self, url: &str) -> Option<&dyn Worker> {
        self.iter().find(|w| w.url() == url).map(|w| w.as_ref())
    }

    fn find_worker_mut(&mut self, url: &str) -> Option<&mut Box<dyn Worker>> {
        self.iter_mut().find(|w| w.url() == url)
    }
}

/// Convert a list of worker URLs to worker trait objects
pub fn urls_to_workers(urls: Vec<String>) -> Vec<Box<dyn Worker>> {
    urls.into_iter()
        .map(WorkerFactory::create_regular)
        .collect()
}

/// Convert worker trait objects back to URLs
pub fn workers_to_urls(workers: &[Box<dyn Worker>]) -> Vec<String> {
    workers.iter().map(|w| w.url().to_string()).collect()
}

/// RAII guard for worker load management
pub struct WorkerLoadGuard<'a> {
    workers: Vec<&'a dyn Worker>,
}

impl<'a> WorkerLoadGuard<'a> {
    /// Create a new load guard for a single worker
    pub fn new(worker: &'a dyn Worker) -> Self {
        worker.increment_load();
        Self {
            workers: vec![worker],
        }
    }

    /// Create a new load guard for multiple workers
    pub fn new_multi(workers: Vec<&'a dyn Worker>) -> Self {
        // Increment load counters for all workers
        for worker in &workers {
            worker.increment_load();
        }
        Self { workers }
    }
}

impl<'a> Drop for WorkerLoadGuard<'a> {
    fn drop(&mut self) {
        // Decrement load counters for all workers
        for worker in &self.workers {
            worker.decrement_load();
        }
    }
}

/// Health checker handle with graceful shutdown
pub struct HealthChecker {
    handle: tokio::task::JoinHandle<()>,
    shutdown: Arc<AtomicBool>,
}

impl fmt::Debug for HealthChecker {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("HealthChecker")
            .field("shutdown", &self.shutdown.load(Ordering::Relaxed))
            .finish()
    }
}

impl HealthChecker {
1035
1036
1037
1038
1039
    /// Create a new HealthChecker
    pub fn new(handle: tokio::task::JoinHandle<()>, shutdown: Arc<AtomicBool>) -> Self {
        Self { handle, shutdown }
    }

1040
1041
1042
1043
1044
1045
1046
1047
1048
    /// Shutdown the health checker gracefully
    pub async fn shutdown(self) {
        self.shutdown.store(true, Ordering::Release);
        let _ = self.handle.await;
    }
}

/// Start an async background health checker for a collection of workers
pub fn start_health_checker(
1049
    workers: std::sync::Arc<std::sync::RwLock<Vec<std::sync::Arc<dyn Worker>>>>,
1050
1051
1052
1053
1054
1055
1056
1057
1058
    check_interval_secs: u64,
) -> HealthChecker {
    let shutdown = Arc::new(AtomicBool::new(false));
    let shutdown_clone = shutdown.clone();

    let handle = tokio::spawn(async move {
        let mut interval =
            tokio::time::interval(tokio::time::Duration::from_secs(check_interval_secs));

1059
1060
1061
1062
        // Counter for periodic load reset (every 10 health check cycles)
        let mut check_count = 0u64;
        const LOAD_RESET_INTERVAL: u64 = 10;

1063
1064
1065
1066
1067
        loop {
            interval.tick().await;

            // Check for shutdown signal
            if shutdown_clone.load(Ordering::Acquire) {
1068
                tracing::debug!("Health checker shutting down");
1069
1070
1071
                break;
            }

1072
1073
            check_count += 1;

1074
1075
1076
1077
1078
1079
1080
1081
1082
            // Check health of all workers
            let workers_to_check = match workers.read() {
                Ok(guard) => guard.iter().map(|w| w.clone_worker()).collect::<Vec<_>>(),
                Err(poisoned) => {
                    tracing::error!("Worker lock poisoned: {}", poisoned);
                    continue;
                }
            };

1083
1084
            // Periodically reset load counters to prevent drift
            // Only do this when we believe all workers should be idle
1085
            if check_count % LOAD_RESET_INTERVAL == 0 {
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
                let max_load = workers_to_check.iter().map(|w| w.load()).max().unwrap_or(0);
                // Only reset if load appears to be very low (likely drift)
                if max_load <= 2 {
                    tracing::debug!(
                        "Resetting load counters to prevent drift (max_load: {})",
                        max_load
                    );
                    for worker in &workers_to_check {
                        worker.reset_load();
                    }
                }
            }

1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
            // Perform health checks concurrently
            let health_checks = workers_to_check.iter().map(|worker| {
                let worker_url = worker.url().to_string();
                let was_healthy = worker.is_healthy();

                async move {
                    match worker.check_health_async().await {
                        Ok(_) => {
                            if !was_healthy {
                                tracing::info!("Worker {} is now healthy", worker_url);
                            }
                        }
                        Err(e) => {
                            if was_healthy {
                                tracing::warn!("Worker {} health check failed: {}", worker_url, e);
1114
1115
1116
                            } else {
                                // Worker was already unhealthy, log at debug level
                                tracing::debug!("Worker {} remains unhealthy: {}", worker_url, e);
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
                            }
                        }
                    }
                }
            });

            // Execute all health checks concurrently
            futures::future::join_all(health_checks).await;
        }
    });

    HealthChecker { handle, shutdown }
}
1130
1131
1132
1133
1134

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::RwLock;
1135
    use std::thread;
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
    use std::time::Duration;
    use tokio::time::timeout;

    // Test WorkerType
    #[test]
    fn test_worker_type_display() {
        assert_eq!(WorkerType::Regular.to_string(), "Regular");
        assert_eq!(
            WorkerType::Prefill {
                bootstrap_port: Some(8080)
            }
            .to_string(),
            "Prefill(bootstrap:8080)"
        );
        assert_eq!(
            WorkerType::Prefill {
                bootstrap_port: None
            }
            .to_string(),
            "Prefill"
        );
        assert_eq!(WorkerType::Decode.to_string(), "Decode");
    }

    #[test]
    fn test_worker_type_equality() {
        assert_eq!(WorkerType::Regular, WorkerType::Regular);
        assert_ne!(WorkerType::Regular, WorkerType::Decode);
        assert_eq!(
            WorkerType::Prefill {
                bootstrap_port: Some(8080)
            },
            WorkerType::Prefill {
                bootstrap_port: Some(8080)
            }
        );
        assert_ne!(
            WorkerType::Prefill {
                bootstrap_port: Some(8080)
            },
            WorkerType::Prefill {
                bootstrap_port: Some(8081)
            }
        );
    }

    #[test]
    fn test_worker_type_clone() {
        let original = WorkerType::Prefill {
            bootstrap_port: Some(8080),
        };
        let cloned = original.clone();
        assert_eq!(original, cloned);
    }

    // Test HealthConfig
    #[test]
    fn test_health_config_default() {
        let config = HealthConfig::default();
        assert_eq!(config.timeout_secs, 5);
        assert_eq!(config.check_interval_secs, 30);
        assert_eq!(config.endpoint, "/health");
1198
1199
        assert_eq!(config.failure_threshold, 3);
        assert_eq!(config.success_threshold, 2);
1200
1201
1202
1203
1204
1205
1206
1207
    }

    #[test]
    fn test_health_config_custom() {
        let config = HealthConfig {
            timeout_secs: 10,
            check_interval_secs: 60,
            endpoint: "/healthz".to_string(),
1208
1209
            failure_threshold: 5,
            success_threshold: 3,
1210
1211
1212
1213
        };
        assert_eq!(config.timeout_secs, 10);
        assert_eq!(config.check_interval_secs, 60);
        assert_eq!(config.endpoint, "/healthz");
1214
1215
        assert_eq!(config.failure_threshold, 5);
        assert_eq!(config.success_threshold, 3);
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
    }

    // Test BasicWorker
    #[test]
    fn test_basic_worker_creation() {
        let worker = BasicWorker::new("http://test:8080".to_string(), WorkerType::Regular);
        assert_eq!(worker.url(), "http://test:8080");
        assert_eq!(worker.worker_type(), WorkerType::Regular);
        assert!(worker.is_healthy());
        assert_eq!(worker.load(), 0);
        assert_eq!(worker.processed_requests(), 0);
    }

    #[test]
    fn test_worker_with_labels() {
        let mut labels = std::collections::HashMap::new();
        labels.insert("env".to_string(), "prod".to_string());
        labels.insert("zone".to_string(), "us-west".to_string());

        let worker = BasicWorker::new("http://test:8080".to_string(), WorkerType::Regular)
            .with_labels(labels.clone());

        assert_eq!(worker.metadata().labels, labels);
    }

    #[test]
    fn test_worker_with_health_config() {
        let custom_config = HealthConfig {
            timeout_secs: 15,
            check_interval_secs: 45,
            endpoint: "/custom-health".to_string(),
1247
1248
            failure_threshold: 4,
            success_threshold: 2,
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
        };

        let worker = BasicWorker::new("http://test:8080".to_string(), WorkerType::Regular)
            .with_health_config(custom_config.clone());

        assert_eq!(worker.metadata().health_config.timeout_secs, 15);
        assert_eq!(worker.metadata().health_config.check_interval_secs, 45);
        assert_eq!(worker.metadata().health_config.endpoint, "/custom-health");
    }

    // Test Worker trait implementation
    #[test]
    fn test_worker_url() {
        let worker = BasicWorker::new("http://worker1:8080".to_string(), WorkerType::Regular);
        assert_eq!(worker.url(), "http://worker1:8080");
    }

    #[test]
    fn test_worker_type_getter() {
        let regular = BasicWorker::new("http://test:8080".to_string(), WorkerType::Regular);
        assert_eq!(regular.worker_type(), WorkerType::Regular);

        let prefill = BasicWorker::new(
            "http://test:8080".to_string(),
            WorkerType::Prefill {
                bootstrap_port: Some(9090),
            },
        );
        assert_eq!(
            prefill.worker_type(),
            WorkerType::Prefill {
                bootstrap_port: Some(9090)
            }
        );

        let decode = BasicWorker::new("http://test:8080".to_string(), WorkerType::Decode);
        assert_eq!(decode.worker_type(), WorkerType::Decode);
    }

    #[test]
    fn test_health_status() {
        let worker = BasicWorker::new("http://test:8080".to_string(), WorkerType::Regular);

        // Initial state is healthy
        assert!(worker.is_healthy());

        // Set unhealthy
        worker.set_healthy(false);
        assert!(!worker.is_healthy());

        // Set healthy again
        worker.set_healthy(true);
        assert!(worker.is_healthy());
    }

    #[test]
    fn test_load_counter_operations() {
        let worker = BasicWorker::new("http://test:8080".to_string(), WorkerType::Regular);

        // Initial load is 0
        assert_eq!(worker.load(), 0);

        // Increment once
        worker.increment_load();
        assert_eq!(worker.load(), 1);

        // Increment twice more
        worker.increment_load();
        worker.increment_load();
        assert_eq!(worker.load(), 3);

        // Decrement once
        worker.decrement_load();
        assert_eq!(worker.load(), 2);

        // Decrement to 0
        worker.decrement_load();
        worker.decrement_load();
        assert_eq!(worker.load(), 0);

        // Decrement below 0 should stay at 0
        worker.decrement_load();
        assert_eq!(worker.load(), 0);
    }

    #[test]
    fn test_processed_counter() {
        let worker = BasicWorker::new("http://test:8080".to_string(), WorkerType::Regular);

        // Initial count is 0
        assert_eq!(worker.processed_requests(), 0);

        // Increment multiple times
        for i in 1..=100 {
            worker.increment_processed();
            assert_eq!(worker.processed_requests(), i);
        }
    }

    #[test]
    fn test_clone_worker() {
        let original = BasicWorker::new("http://test:8080".to_string(), WorkerType::Regular);
        original.increment_load();
        original.increment_processed();
        original.set_healthy(false);

        let cloned = original.clone_worker();

        // Verify cloned worker has same URL and type
        assert_eq!(cloned.url(), original.url());
        assert_eq!(cloned.worker_type(), original.worker_type());

        // Load counters should be independent (cloned shares the Arc)
        assert_eq!(cloned.load(), original.load());

        // Modify original and verify clone is affected (shared state)
        original.increment_load();
        assert_eq!(cloned.load(), original.load());
    }

    // Test concurrent operations
    #[tokio::test]
    async fn test_concurrent_load_increments() {
        let worker = Arc::new(BasicWorker::new(
            "http://test:8080".to_string(),
            WorkerType::Regular,
        ));

        let mut handles = vec![];

        // Spawn 100 tasks incrementing load
        for _ in 0..100 {
            let worker_clone = Arc::clone(&worker);
            let handle = tokio::spawn(async move {
                worker_clone.increment_load();
            });
            handles.push(handle);
        }

        // Wait for all tasks
        for handle in handles {
            handle.await.unwrap();
        }

        // Final count should be 100
        assert_eq!(worker.load(), 100);
    }

    #[tokio::test]
    async fn test_concurrent_load_decrements() {
        let worker = Arc::new(BasicWorker::new(
            "http://test:8080".to_string(),
            WorkerType::Regular,
        ));

        // Set initial load to 100
        for _ in 0..100 {
            worker.increment_load();
        }
        assert_eq!(worker.load(), 100);

        let mut handles = vec![];

        // Spawn 100 tasks decrementing load
        for _ in 0..100 {
            let worker_clone = Arc::clone(&worker);
            let handle = tokio::spawn(async move {
                worker_clone.decrement_load();
            });
            handles.push(handle);
        }

        // Wait for all tasks
        for handle in handles {
            handle.await.unwrap();
        }

        // Final count should be 0
        assert_eq!(worker.load(), 0);
    }

    #[tokio::test]
    async fn test_concurrent_health_updates() {
        let worker = Arc::new(BasicWorker::new(
            "http://test:8080".to_string(),
            WorkerType::Regular,
        ));

        let mut handles = vec![];

        // Spawn threads randomly setting health status
        for i in 0..100 {
            let worker_clone = Arc::clone(&worker);
            let handle = tokio::spawn(async move {
                worker_clone.set_healthy(i % 2 == 0);
                tokio::time::sleep(Duration::from_micros(10)).await;
            });
            handles.push(handle);
        }

        // Wait for all tasks
        for handle in handles {
            handle.await.unwrap();
        }
    }

    // Test WorkerFactory
    #[test]
    fn test_create_regular_worker() {
        let worker = WorkerFactory::create_regular("http://regular:8080".to_string());
        assert_eq!(worker.url(), "http://regular:8080");
        assert_eq!(worker.worker_type(), WorkerType::Regular);
    }

    #[test]
    fn test_create_prefill_worker() {
        // With bootstrap port
        let worker1 = WorkerFactory::create_prefill("http://prefill:8080".to_string(), Some(9090));
        assert_eq!(worker1.url(), "http://prefill:8080");
        assert_eq!(
            worker1.worker_type(),
            WorkerType::Prefill {
                bootstrap_port: Some(9090)
            }
        );

        // Without bootstrap port
        let worker2 = WorkerFactory::create_prefill("http://prefill:8080".to_string(), None);
        assert_eq!(
            worker2.worker_type(),
            WorkerType::Prefill {
                bootstrap_port: None
            }
        );
    }

    #[test]
    fn test_create_decode_worker() {
        let worker = WorkerFactory::create_decode("http://decode:8080".to_string());
        assert_eq!(worker.url(), "http://decode:8080");
        assert_eq!(worker.worker_type(), WorkerType::Decode);
    }

    #[test]
    fn test_create_from_urls() {
        let regular_urls = vec![
            "http://regular1:8080".to_string(),
            "http://regular2:8080".to_string(),
        ];
        let prefill_urls = vec![
            ("http://prefill1:8080".to_string(), Some(9090)),
            ("http://prefill2:8080".to_string(), None),
        ];
        let decode_urls = vec![
            "http://decode1:8080".to_string(),
            "http://decode2:8080".to_string(),
        ];

        let (regular, prefill, decode) =
            WorkerFactory::create_from_urls(regular_urls, prefill_urls, decode_urls);

        assert_eq!(regular.len(), 2);
        assert_eq!(prefill.len(), 2);
        assert_eq!(decode.len(), 2);

        assert_eq!(regular[0].url(), "http://regular1:8080");
        assert_eq!(prefill[0].url(), "http://prefill1:8080");
        assert_eq!(decode[0].url(), "http://decode1:8080");
    }

    // Test WorkerCollection trait
    #[test]
    fn test_healthy_workers_filter() {
        let workers: Vec<Box<dyn Worker>> = vec![
            WorkerFactory::create_regular("http://w1:8080".to_string()),
            WorkerFactory::create_regular("http://w2:8080".to_string()),
            WorkerFactory::create_regular("http://w3:8080".to_string()),
        ];

        // Set some workers unhealthy
        workers[0].set_healthy(false);
        workers[2].set_healthy(false);

        let healthy = workers.healthy_workers();
        assert_eq!(healthy.len(), 1);
        assert_eq!(healthy[0].url(), "http://w2:8080");
    }

    #[test]
    fn test_total_load_calculation() {
        let workers: Vec<Box<dyn Worker>> = vec![
            WorkerFactory::create_regular("http://w1:8080".to_string()),
            WorkerFactory::create_regular("http://w2:8080".to_string()),
            WorkerFactory::create_regular("http://w3:8080".to_string()),
        ];

        // Set different loads
        workers[0].increment_load();
        workers[0].increment_load(); // load = 2

        workers[1].increment_load();
        workers[1].increment_load();
        workers[1].increment_load(); // load = 3

        workers[2].increment_load(); // load = 1

        assert_eq!(workers.total_load(), 6);
    }

    #[test]
    fn test_find_worker() {
        let workers: Vec<Box<dyn Worker>> = vec![
            WorkerFactory::create_regular("http://w1:8080".to_string()),
            WorkerFactory::create_regular("http://w2:8080".to_string()),
            WorkerFactory::create_regular("http://w3:8080".to_string()),
        ];

        // Found case
        let found = workers.find_worker("http://w2:8080");
        assert!(found.is_some());
        assert_eq!(found.unwrap().url(), "http://w2:8080");

        // Not found case
        let not_found = workers.find_worker("http://w4:8080");
        assert!(not_found.is_none());
    }

    #[test]
    fn test_find_worker_mut() {
        let mut workers: Vec<Box<dyn Worker>> = vec![
            WorkerFactory::create_regular("http://w1:8080".to_string()),
            WorkerFactory::create_regular("http://w2:8080".to_string()),
        ];

        // Find and modify
        if let Some(worker) = workers.find_worker_mut("http://w1:8080") {
            worker.set_healthy(false);
        }

        // Verify modification
        assert!(!workers[0].is_healthy());
        assert!(workers[1].is_healthy());
    }

    // Test WorkerLoadGuard
    #[test]
    fn test_load_guard_single_worker() {
        let worker = BasicWorker::new("http://test:8080".to_string(), WorkerType::Regular);
        assert_eq!(worker.load(), 0);

        {
            let _guard = WorkerLoadGuard::new(&worker);
            assert_eq!(worker.load(), 1);
        }

        // Guard dropped, load decremented
        assert_eq!(worker.load(), 0);
    }

    #[test]
    fn test_load_guard_multiple_workers() {
        let workers: Vec<Box<dyn Worker>> = vec![
            WorkerFactory::create_regular("http://w1:8080".to_string()),
            WorkerFactory::create_regular("http://w2:8080".to_string()),
            WorkerFactory::create_regular("http://w3:8080".to_string()),
        ];

        let worker_refs: Vec<&dyn Worker> = workers.iter().map(|w| w.as_ref()).collect();

        {
            let _guard = WorkerLoadGuard::new_multi(worker_refs);
            // All loads incremented
            assert_eq!(workers[0].load(), 1);
            assert_eq!(workers[1].load(), 1);
            assert_eq!(workers[2].load(), 1);
        }

        // All loads decremented
        assert_eq!(workers[0].load(), 0);
        assert_eq!(workers[1].load(), 0);
        assert_eq!(workers[2].load(), 0);
    }

    #[test]
    fn test_load_guard_panic_safety() {
        let worker = Arc::new(BasicWorker::new(
            "http://test:8080".to_string(),
            WorkerType::Regular,
        ));
        assert_eq!(worker.load(), 0);

        // Clone for use inside catch_unwind
        let worker_clone = Arc::clone(&worker);

Chang Su's avatar
Chang Su committed
1643
1644
1645
1646
1647
        // Use AssertUnwindSafe wrapper for the test
        // This is safe because we're only testing the load counter behavior,
        // not the grpc_client which is None for HTTP workers
        use std::panic::AssertUnwindSafe;

1648
        // This will panic, but the guard should still clean up
Chang Su's avatar
Chang Su committed
1649
        let result = std::panic::catch_unwind(AssertUnwindSafe(|| {
1650
1651
1652
            let _guard = WorkerLoadGuard::new(worker_clone.as_ref());
            assert_eq!(worker_clone.load(), 1);
            panic!("Test panic");
Chang Su's avatar
Chang Su committed
1653
        }));
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700

        // Verify panic occurred
        assert!(result.is_err());

        // Load should be decremented even after panic
        assert_eq!(worker.load(), 0);
    }

    // Test helper functions
    #[test]
    fn test_urls_to_workers() {
        let urls = vec!["http://w1:8080".to_string(), "http://w2:8080".to_string()];

        let workers = urls_to_workers(urls);
        assert_eq!(workers.len(), 2);
        assert_eq!(workers[0].url(), "http://w1:8080");
        assert_eq!(workers[1].url(), "http://w2:8080");
        assert_eq!(workers[0].worker_type(), WorkerType::Regular);
    }

    #[test]
    fn test_workers_to_urls() {
        let workers: Vec<Box<dyn Worker>> = vec![
            WorkerFactory::create_regular("http://w1:8080".to_string()),
            WorkerFactory::create_regular("http://w2:8080".to_string()),
        ];

        let urls = workers_to_urls(&workers);
        assert_eq!(urls, vec!["http://w1:8080", "http://w2:8080"]);
    }

    // Test synchronous health check wrapper
    #[test]
    fn test_check_health_sync_wrapper() {
        // We can't easily test the actual HTTP call without mocking,
        // but we can verify the sync wrapper works
        let worker = BasicWorker::new("http://test:8080".to_string(), WorkerType::Regular);

        // This will fail because there's no server at this URL,
        // but it tests that the sync wrapper doesn't panic
        let result = worker.check_health();
        assert!(result.is_err());
    }

    // Test HealthChecker background task
    #[tokio::test]
    async fn test_health_checker_startup() {
1701
        let worker = Arc::new(BasicWorker::new(
1702
            "http://w1:8080".to_string(),
1703
1704
1705
            WorkerType::Regular,
        )) as Arc<dyn Worker>;
        let workers = Arc::new(RwLock::new(vec![worker]));
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717

        let checker = start_health_checker(workers.clone(), 60);

        // Verify it starts without panic
        tokio::time::sleep(Duration::from_millis(100)).await;

        // Shutdown
        checker.shutdown().await;
    }

    #[tokio::test]
    async fn test_health_checker_shutdown() {
1718
        let worker = Arc::new(BasicWorker::new(
1719
            "http://w1:8080".to_string(),
1720
1721
1722
            WorkerType::Regular,
        )) as Arc<dyn Worker>;
        let workers = Arc::new(RwLock::new(vec![worker]));
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750

        let checker = start_health_checker(workers.clone(), 60);

        // Shutdown should complete quickly
        let shutdown_result = timeout(Duration::from_secs(1), checker.shutdown()).await;
        assert!(shutdown_result.is_ok());
    }

    // Performance test for load counter
    #[test]
    fn test_load_counter_performance() {
        use std::time::Instant;

        let worker = BasicWorker::new("http://test:8080".to_string(), WorkerType::Regular);
        let iterations = 1_000_000;

        let start = Instant::now();
        for _ in 0..iterations {
            worker.increment_load();
        }
        let duration = start.elapsed();

        let ops_per_sec = iterations as f64 / duration.as_secs_f64();
        println!("Load counter operations per second: {:.0}", ops_per_sec);

        // Should be well over 1M ops/sec
        assert!(ops_per_sec > 1_000_000.0);
    }
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924

    // ===== Tests for DPAwareWorker =====

    #[test]
    fn test_dp_aware_worker_creation() {
        let dp_worker =
            DPAwareWorker::new("http://worker1:8080".to_string(), 2, 4, WorkerType::Regular);

        assert_eq!(dp_worker.url(), "http://worker1:8080@2");
        assert_eq!(dp_worker.base_url(), "http://worker1:8080");
        assert!(dp_worker.is_dp_aware());
        assert_eq!(dp_worker.dp_rank(), Some(2));
        assert_eq!(dp_worker.dp_size(), Some(4));
        assert_eq!(dp_worker.worker_type(), WorkerType::Regular);
    }

    #[test]
    fn test_dp_aware_worker_creation_prefill() {
        let dp_worker = DPAwareWorker::new(
            "http://worker1:8080".to_string(),
            1,
            2,
            WorkerType::Prefill {
                bootstrap_port: Some(9090),
            },
        );

        assert_eq!(dp_worker.url(), "http://worker1:8080@1");
        assert!(dp_worker.is_dp_aware());
        assert_eq!(
            dp_worker.worker_type(),
            WorkerType::Prefill {
                bootstrap_port: Some(9090)
            }
        );
    }

    #[test]
    fn test_dp_aware_worker_creation_decode() {
        let dp_worker =
            DPAwareWorker::new("http://worker1:8080".to_string(), 0, 4, WorkerType::Decode);

        assert_eq!(dp_worker.url(), "http://worker1:8080@0");
        assert!(dp_worker.is_dp_aware());
        assert_eq!(dp_worker.worker_type(), WorkerType::Decode);
    }

    #[tokio::test]
    async fn test_dp_aware_prepare_request() {
        let dp_worker =
            DPAwareWorker::new("http://worker1:8080".to_string(), 3, 8, WorkerType::Regular);

        let original_req = serde_json::json!({
            "prompt": "Hello",
            "max_tokens": 100
        });

        let prepared_req = dp_worker.prepare_request(original_req).await.unwrap();

        assert_eq!(prepared_req["prompt"], "Hello");
        assert_eq!(prepared_req["max_tokens"], 100);
        assert_eq!(prepared_req["data_parallel_rank"], 3);
    }

    #[tokio::test]
    async fn test_dp_aware_prepare_request_invalid() {
        let dp_worker =
            DPAwareWorker::new("http://worker1:8080".to_string(), 0, 4, WorkerType::Regular);

        // Non-object JSON should fail
        let invalid_req = serde_json::json!("not an object");
        let result = dp_worker.prepare_request(invalid_req).await;

        assert!(result.is_err());
        match result.unwrap_err() {
            WorkerError::InvalidConfiguration { message } => {
                assert!(message.contains("JSON object"));
            }
            _ => panic!("Expected InvalidConfiguration error"),
        }
    }

    #[test]
    fn test_dp_aware_endpoint_url() {
        let dp_worker =
            DPAwareWorker::new("http://worker1:8080".to_string(), 1, 4, WorkerType::Regular);

        assert_eq!(
            dp_worker.endpoint_url("/generate"),
            "http://worker1:8080/generate"
        );
        assert_eq!(
            dp_worker.endpoint_url("/health"),
            "http://worker1:8080/health"
        );
    }

    #[test]
    fn test_dp_aware_worker_delegated_methods() {
        let dp_worker =
            DPAwareWorker::new("http://worker1:8080".to_string(), 0, 2, WorkerType::Regular);

        // Test health status
        assert!(dp_worker.is_healthy());
        dp_worker.set_healthy(false);
        assert!(!dp_worker.is_healthy());

        // Test load tracking
        assert_eq!(dp_worker.load(), 0);
        dp_worker.increment_load();
        assert_eq!(dp_worker.load(), 1);
        dp_worker.decrement_load();
        assert_eq!(dp_worker.load(), 0);

        // Test processed tracking
        assert_eq!(dp_worker.processed_requests(), 0);
        dp_worker.increment_processed();
        assert_eq!(dp_worker.processed_requests(), 1);
    }

    // ===== Tests for WorkerFactory async methods =====

    #[tokio::test]
    async fn test_factory_create_dp_aware() {
        let worker = WorkerFactory::create_dp_aware(
            "http://worker1:8080".to_string(),
            1,
            4,
            WorkerType::Regular,
        );

        assert_eq!(worker.url(), "http://worker1:8080@1");
        assert!(worker.is_dp_aware());
        assert_eq!(worker.dp_rank(), Some(1));
        assert_eq!(worker.dp_size(), Some(4));
        assert_eq!(worker.worker_type(), WorkerType::Regular);
    }

    #[tokio::test]
    async fn test_factory_create_dp_aware_prefill() {
        let worker = WorkerFactory::create_dp_aware(
            "http://worker1:8080".to_string(),
            0,
            2,
            WorkerType::Prefill {
                bootstrap_port: Some(8090),
            },
        );

        assert_eq!(worker.url(), "http://worker1:8080@0");
        assert!(worker.is_dp_aware());
        assert_eq!(
            worker.worker_type(),
            WorkerType::Prefill {
                bootstrap_port: Some(8090)
            }
        );
    }

    #[tokio::test]
    async fn test_factory_create_workers_regular() {
        let urls = vec!["http://w1:8080".to_string(), "http://w2:8080".to_string()];

        let workers = WorkerFactory::create_workers(urls, false, &None)
            .await
            .unwrap();

        assert_eq!(workers.len(), 2);
        assert!(!workers[0].is_dp_aware());
        assert!(!workers[1].is_dp_aware());
        assert_eq!(workers[0].url(), "http://w1:8080");
        assert_eq!(workers[1].url(), "http://w2:8080");
    }

1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
    // ===== Circuit Breaker Integration Tests =====

    #[test]
    fn test_worker_circuit_breaker() {
        let worker = BasicWorker::new("http://test:8080".to_string(), WorkerType::Regular);

        // Initial state should be available
        assert!(worker.is_available());
        assert_eq!(
            worker.circuit_breaker().state(),
            crate::core::CircuitState::Closed
        );

        // Record some failures
        worker.record_outcome(false);
        worker.record_outcome(false);

        // Still available (default threshold is 5)
        assert!(worker.is_available());

        // Record more failures to open circuit
        worker.record_outcome(false);
        worker.record_outcome(false);
        worker.record_outcome(false);

        // Circuit should be open, worker not available
        assert!(!worker.is_available());
        assert!(worker.is_healthy()); // Still healthy
        assert!(!worker.circuit_breaker().can_execute()); // But circuit is open
    }

    #[test]
    fn test_worker_with_circuit_breaker_config() {
        let config = crate::core::CircuitBreakerConfig {
            failure_threshold: 2,
            success_threshold: 1,
            timeout_duration: Duration::from_millis(100),
            window_duration: Duration::from_secs(60),
        };

        let worker = BasicWorker::new("http://test:8080".to_string(), WorkerType::Regular)
            .with_circuit_breaker_config(config);

        // Should open after 2 failures
        worker.record_outcome(false);
        assert!(worker.is_available());
        worker.record_outcome(false);
        assert!(!worker.is_available());

        // Wait for timeout
        thread::sleep(Duration::from_millis(150));

        // Should be half-open
        assert!(worker.is_available());
        assert_eq!(
            worker.circuit_breaker().state(),
            crate::core::CircuitState::HalfOpen
        );

        // Success should close it
        worker.record_outcome(true);
        assert_eq!(
            worker.circuit_breaker().state(),
            crate::core::CircuitState::Closed
        );
    }

    #[test]
    fn test_dp_aware_worker_circuit_breaker() {
        let dp_worker =
            DPAwareWorker::new("http://worker:8080".to_string(), 0, 2, WorkerType::Regular);

        // Should have circuit breaker
        assert!(dp_worker.is_available());

        // Record failures
        for _ in 0..5 {
            dp_worker.record_outcome(false);
        }

        // Should not be available
        assert!(!dp_worker.is_available());
        assert_eq!(
            dp_worker.circuit_breaker().state(),
            crate::core::CircuitState::Open
        );
    }

2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
    // ===== Integration tests =====

    #[tokio::test]
    async fn test_mixed_worker_types() {
        // Create a mix of worker types
        let regular = WorkerFactory::create_regular("http://regular:8080".to_string());
        let prefill = WorkerFactory::create_prefill("http://prefill:8080".to_string(), Some(9090));
        let decode = WorkerFactory::create_decode("http://decode:8080".to_string());
        let dp_aware_regular =
            WorkerFactory::create_dp_aware("http://dp:8080".to_string(), 0, 2, WorkerType::Regular);
        let dp_aware_prefill = WorkerFactory::create_dp_aware(
            "http://dp-prefill:8080".to_string(),
            1,
            2,
            WorkerType::Prefill {
                bootstrap_port: None,
            },
        );
        let dp_aware_decode = WorkerFactory::create_dp_aware(
            "http://dp-decode:8080".to_string(),
            0,
            4,
            WorkerType::Decode,
        );

        let workers: Vec<Box<dyn Worker>> = vec![
            regular,
            prefill,
            decode,
            dp_aware_regular,
            dp_aware_prefill,
            dp_aware_decode,
        ];

        // Test that they all implement Worker trait properly
        for worker in &workers {
            assert!(worker.is_healthy());
            assert_eq!(worker.load(), 0);
            assert_eq!(worker.processed_requests(), 0);
        }

        // Test specific behaviors
        assert!(!workers[0].is_dp_aware()); // regular
        assert!(!workers[1].is_dp_aware()); // prefill
        assert!(!workers[2].is_dp_aware()); // decode
        assert!(workers[3].is_dp_aware()); // dp_aware_regular
        assert!(workers[4].is_dp_aware()); // dp_aware_prefill
        assert!(workers[5].is_dp_aware()); // dp_aware_decode

        // Test worker types
        assert_eq!(workers[0].worker_type(), WorkerType::Regular);
        assert_eq!(
            workers[1].worker_type(),
            WorkerType::Prefill {
                bootstrap_port: Some(9090)
            }
        );
        assert_eq!(workers[2].worker_type(), WorkerType::Decode);
        assert_eq!(workers[3].worker_type(), WorkerType::Regular);
        assert_eq!(
            workers[4].worker_type(),
            WorkerType::Prefill {
                bootstrap_port: None
            }
        );
        assert_eq!(workers[5].worker_type(), WorkerType::Decode);
    }
2080
}