Skip to content

Commit 9e25615

Browse files
fix(mesh): read a single engine's queues; publish a failed tick's empty loads
- A worker without a DP rank reads atom:requests_running + requests_waiting: the engine charges dp_inflight only when it routes among its own DP ranks, so on a single-engine replica it stays 0. - A tick where every fetch fails publishes the empty map, so power_of_two drops the stale loads and falls back to its local request count. - LoadMonitor::new takes the backend instead of an opt-in with_backend. - Test: one instance's two DP ranks, a single engine and an unreachable worker through get_all_worker_loads. Co-authored-by: Cursor <cursoragent@cursor.com>
1 parent 0fb8107 commit 9e25615

5 files changed

Lines changed: 128 additions & 60 deletions

File tree

‎atom/mesh/src/app_context.rs‎

Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -435,21 +435,19 @@ impl AppContextBuilder {
435435
.client
436436
.as_ref()
437437
.expect("client must be set before load monitor");
438-
self.load_monitor = Some(Arc::new(
439-
LoadMonitor::new(
440-
self.worker_registry
441-
.as_ref()
442-
.expect("worker_registry must be set")
443-
.clone(),
444-
self.policy_registry
445-
.as_ref()
446-
.expect("policy_registry must be set")
447-
.clone(),
448-
client.clone(),
449-
config.load_sample_interval_secs(),
450-
)
451-
.with_backend(config.backend),
452-
));
438+
self.load_monitor = Some(Arc::new(LoadMonitor::new(
439+
self.worker_registry
440+
.as_ref()
441+
.expect("worker_registry must be set")
442+
.clone(),
443+
self.policy_registry
444+
.as_ref()
445+
.expect("policy_registry must be set")
446+
.clone(),
447+
client.clone(),
448+
config.backend,
449+
config.load_sample_interval_secs(),
450+
)));
453451
self
454452
}
455453

‎atom/mesh/src/core/worker_manager.rs‎

Lines changed: 111 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -225,15 +225,18 @@ async fn fetch_base_loads(
225225
None => return HashMap::new(),
226226
};
227227
let by_rank = parse_dp_inflight(&body);
228+
// The engine charges dp_inflight only when it routes among its own DP ranks, so
229+
// it stays 0 on a single-engine replica: a worker without a rank reads the
230+
// scheduler queues instead.
231+
let queued = parse_queued_requests(&body);
228232
let mut loads = HashMap::new();
229233
for worker in group {
230-
if let Some(rank) = worker.dp_rank() {
231-
if let Some(load) = by_rank.get(&rank) {
232-
loads.insert(worker.url().to_string(), *load);
233-
}
234-
} else if group.len() == 1 && !by_rank.is_empty() {
235-
let sum = by_rank.values().sum();
236-
loads.insert(worker.url().to_string(), sum);
234+
let load = match worker.dp_rank() {
235+
Some(rank) => by_rank.get(&rank).copied(),
236+
None => queued,
237+
};
238+
if let Some(load) = load {
239+
loads.insert(worker.url().to_string(), load);
237240
}
238241
}
239242
return loads;
@@ -284,34 +287,37 @@ fn sum_num_tokens(json: &Value) -> Option<isize> {
284287

285288
/// `atom:dp_inflight_requests{rank="k"}` values. Lines without a rank label are skipped.
286289
pub(crate) fn parse_dp_inflight(body: &str) -> HashMap<usize, isize> {
287-
let mut loads = HashMap::new();
288-
for line in body.lines() {
289-
let line = line.trim();
290-
if line.is_empty() || line.starts_with('#') {
291-
continue;
292-
}
293-
let Some(rest) = line.strip_prefix("atom:dp_inflight_requests") else {
294-
continue;
295-
};
290+
samples(body, "atom:dp_inflight_requests")
291+
.filter_map(|(rest, value)| {
292+
let rank = label_value(rest, "rank")?.parse().ok()?;
293+
Some((rank, value as isize))
294+
})
295+
.collect()
296+
}
297+
298+
/// Requests the instance's scheduler holds across its DP ranks, running or waiting.
299+
pub(crate) fn parse_queued_requests(body: &str) -> Option<isize> {
300+
let gauge = |name| samples(body, name).next().map(|(_, value)| value);
301+
let running = gauge("atom:requests_running")?;
302+
let waiting = gauge("atom:requests_waiting").unwrap_or(0.0);
303+
Some((running + waiting) as isize)
304+
}
305+
306+
/// The label block and finite value of each `name` sample in a Prometheus text body.
307+
fn samples<'a>(body: &'a str, name: &'a str) -> impl Iterator<Item = (&'a str, f64)> + 'a {
308+
body.lines().filter_map(move |line| {
309+
let rest = line.trim().strip_prefix(name)?;
296310
// `atom:dp_inflight_requests_total` and similar names are different metrics.
297-
if rest.starts_with(|c: char| c.is_ascii_alphanumeric() || c == '_') {
298-
continue;
311+
if rest.starts_with(|c: char| c.is_ascii_alphanumeric() || c == '_' || c == ':') {
312+
return None;
299313
}
300-
let Some(rank) = label_value(rest, "rank").and_then(|rank| rank.parse().ok()) else {
301-
continue;
302-
};
303-
let Some(value) = line
304-
.split_whitespace()
305-
.next_back()
306-
.and_then(|token| token.parse::<f64>().ok())
307-
else {
308-
continue;
314+
let value = match rest.trim_start().strip_prefix('{') {
315+
Some(labelled) => labelled.split_once('}')?.1,
316+
None => rest,
309317
};
310-
if value.is_finite() {
311-
loads.insert(rank, value as isize);
312-
}
313-
}
314-
loads
318+
let value: f64 = value.split_whitespace().next()?.parse().ok()?;
319+
value.is_finite().then_some((rest, value))
320+
})
315321
}
316322

317323
fn label_value<'a>(metric_rest: &'a str, name: &str) -> Option<&'a str> {
@@ -353,6 +359,7 @@ impl LoadMonitor {
353359
worker_registry: Arc<WorkerRegistry>,
354360
policy_registry: Arc<PolicyRegistry>,
355361
client: reqwest::Client,
362+
backend: BackendType,
356363
interval_secs: u64,
357364
) -> Self {
358365
let (tx, rx) = watch::channel(HashMap::new());
@@ -361,19 +368,14 @@ impl LoadMonitor {
361368
worker_registry,
362369
policy_registry,
363370
client,
364-
backend: BackendType::Sglang,
371+
backend,
365372
interval: Duration::from_secs(interval_secs),
366373
tx,
367374
rx,
368375
monitor_handle: Arc::new(Mutex::new(None)),
369376
}
370377
}
371378

372-
pub fn with_backend(mut self, backend: BackendType) -> Self {
373-
self.backend = backend;
374-
self
375-
}
376-
377379
pub async fn start(&self) {
378380
let mut handle_guard = self.monitor_handle.lock().await;
379381
if handle_guard.is_some() {
@@ -445,19 +447,21 @@ impl LoadMonitor {
445447
WorkerManager::get_all_worker_loads(&worker_registry, &client, backend).await;
446448
let loads = cacheable_loads(&result.loads);
447449

448-
if !loads.is_empty() {
450+
// An empty map is published too: loads from an earlier tick are stale, and
451+
// power_of_two falls back to its local request count without them.
452+
if loads.is_empty() {
453+
warn!("No loads fetched from workers");
454+
} else {
449455
debug!(
450456
"Fetched loads from {} workers, updating {} PowerOfTwo policies",
451457
loads.len(),
452458
power_of_two_policies.len()
453459
);
454-
for policy in &power_of_two_policies {
455-
policy.update_loads(&loads);
456-
}
457-
let _ = tx.send(loads);
458-
} else {
459-
warn!("No loads fetched from workers");
460460
}
461+
for policy in &power_of_two_policies {
462+
policy.update_loads(&loads);
463+
}
464+
let _ = tx.send(loads);
461465
}
462466
}
463467

@@ -480,6 +484,7 @@ impl Drop for LoadMonitor {
480484
#[cfg(test)]
481485
mod tests {
482486
use super::*;
487+
use crate::core::{BasicWorkerBuilder, DPAwareWorkerBuilder};
483488
use crate::protocols::worker_spec::WorkerLoadInfo;
484489

485490
#[test]
@@ -498,6 +503,67 @@ atom:dp_inflight_requests 13
498503
assert_eq!(loads.len(), 2);
499504
}
500505

506+
#[test]
507+
fn parse_queued_requests_needs_the_running_gauge() {
508+
let body = "atom:requests_running 2.0\n\
509+
atom:requests_waiting_total 7\n\
510+
atom:requests_waiting 3.0\n";
511+
assert_eq!(parse_queued_requests(body), Some(5));
512+
assert_eq!(parse_queued_requests("atom:requests_waiting 3\n"), None);
513+
}
514+
515+
/// Serves `body` at `/metrics` and returns the server's base URL.
516+
async fn metrics_server(body: &'static str) -> String {
517+
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
518+
let url = format!("http://{}", listener.local_addr().unwrap());
519+
let app =
520+
axum::Router::new().route("/metrics", axum::routing::get(move || async move { body }));
521+
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
522+
url
523+
}
524+
525+
#[tokio::test]
526+
async fn atom_loads_read_each_rank_of_an_instance_and_the_queues_of_one_engine() {
527+
let dp = metrics_server(
528+
"atom:dp_inflight_requests{rank=\"0\"} 4\n\
529+
atom:dp_inflight_requests{rank=\"1\"} 9\n\
530+
atom:requests_running 11\n",
531+
)
532+
.await;
533+
// A single-engine replica never charges dp_inflight.
534+
let single = metrics_server(
535+
"atom:dp_inflight_requests{rank=\"0\"} 0\n\
536+
atom:requests_running 2.0\n\
537+
atom:requests_waiting 3.0\n",
538+
)
539+
.await;
540+
let workers: Vec<Arc<dyn Worker>> = vec![
541+
Arc::new(DPAwareWorkerBuilder::new(&dp, 0, 2).build()),
542+
Arc::new(DPAwareWorkerBuilder::new(&dp, 1, 2).build()),
543+
Arc::new(BasicWorkerBuilder::new(&single).build()),
544+
Arc::new(BasicWorkerBuilder::new("http://127.0.0.1:1").build()),
545+
];
546+
let registry = WorkerRegistry::new();
547+
for worker in &workers {
548+
registry.register(Arc::clone(worker));
549+
}
550+
551+
let result = WorkerManager::get_all_worker_loads(
552+
&registry,
553+
&reqwest::Client::new(),
554+
BackendType::Atom,
555+
)
556+
.await;
557+
let loads: HashMap<&str, isize> = result
558+
.loads
559+
.iter()
560+
.map(|info| (info.worker.as_str(), info.load))
561+
.collect();
562+
let load = |index: usize| loads[workers[index].url()];
563+
assert_eq!((load(0), load(1), load(2), load(3)), (4, 9, 5, -1));
564+
assert_eq!((result.successful, result.failed), (3, 1));
565+
}
566+
501567
#[test]
502568
fn cacheable_loads_drops_failures() {
503569
let loads = vec![

‎atom/mesh/tests/common/mod.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -298,6 +298,7 @@ pub async fn create_test_context(config: RouterConfig) -> (Arc<AppContext>, Prep
298298
worker_registry.clone(),
299299
policy_registry.clone(),
300300
client.clone(),
301+
config.backend,
301302
config.worker_startup_check_interval_secs,
302303
)));
303304

@@ -382,6 +383,7 @@ pub async fn create_test_context_with_parsers(
382383
worker_registry.clone(),
383384
policy_registry.clone(),
384385
client.clone(),
386+
config.backend,
385387
config.worker_startup_check_interval_secs,
386388
)));
387389

‎atom/mesh/tests/common/test_app.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ pub fn create_test_app(
5454
worker_registry.clone(),
5555
policy_registry.clone(),
5656
client.clone(),
57+
router_config.backend,
5758
router_config.worker_startup_check_interval_secs,
5859
)));
5960

‎atom/mesh/tests/routing/test_pd_routing.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -198,6 +198,7 @@ mod pd_routing_unit_tests {
198198
worker_registry.clone(),
199199
policy_registry.clone(),
200200
client.clone(),
201+
config.backend,
201202
config.worker_startup_check_interval_secs,
202203
)));
203204

0 commit comments

Comments
 (0)