Coverage Report

Created: 2026-12-01 07:53

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/build/source/nativelink-scheduler/src/worker_registry.rs
Line
Count
Source
1
// Copyright 2024 Trace Machina, Inc. All rights reserved.
2
//
3
// Licensed under the Functional Source License, Version 1.1, Apache 2.0 Future License (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
6
//
7
//    See LICENSE file for details
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14
15
use core::sync::atomic::{AtomicBool, Ordering};
16
use core::time::Duration;
17
use std::collections::HashMap;
18
use std::sync::{Arc, OnceLock};
19
use std::time::SystemTime;
20
21
use async_lock::RwLock;
22
use async_trait::async_trait;
23
use jiff::Timestamp;
24
use nativelink_error::Error;
25
use nativelink_util::action_messages::WorkerId;
26
use nativelink_util::spawn;
27
use nativelink_util::task::JoinHandleDropGuard;
28
use parking_lot::Mutex;
29
use tracing::{debug, trace, warn};
30
31
/// Ceiling for an action whose worker no instance here recognises. Long on
32
/// purpose: heartbeats never reach the shared state, so a healthy hour-long
33
/// action and an abandoned one look identical from here, and acting early
34
/// costs live work.
35
pub const ORPHANED_ACTION_TIMEOUT: Duration = Duration::from_hours(1);
36
37
/// What this scheduler instance knows about a worker's liveness.
38
///
39
/// A worker only appears in the registry of the instance holding its
40
/// `connect_worker` stream, so `Unknown` means "not mine to judge", not
41
/// "dead".
42
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43
pub enum WorkerLiveness {
44
    /// Registered here and has heartbeat within the timeout.
45
    Alive,
46
    /// Registered here, but has not been heard from within the timeout.
47
    Stale,
48
    /// Not registered here at all. Either connected to a different scheduler
49
    /// instance, or already evicted (in which case its actions were requeued
50
    /// at eviction time and no longer reference it).
51
    Unknown,
52
}
53
54
/// How long a read of a peer's worker lease is reused: a sweep asks about
55
/// the same worker once for every operation it holds.
56
const LEASE_READ_FRESHNESS: Duration = Duration::from_secs(5);
57
58
/// Past this many remembered lease reads, those not repeated within the
59
/// orphan backstop are forgotten, and all of them if that is not enough.
60
const MAX_LEASE_READS: usize = 10_000;
61
62
/// A lease's key expires in the store. Its renewal time only catches a key
63
/// left with no expiry, by a replica that died between writing the two, so
64
/// it allows this many lease periods for clocks that disagree.
65
const LEASE_TIME_SLACK: u32 = 3;
66
67
/// Leases on workers, in a store every scheduler replica shares. A replica
68
/// renews the lease of each worker connected to it; another replica reads
69
/// it to tell whether a worker it does not hold is alive.
70
#[async_trait]
71
pub trait WorkerLeases: Send + Sync + core::fmt::Debug {
72
    /// Marks each of `worker_ids` held by `scheduler_id`, renewed at `now`,
73
    /// for `ttl`.
74
    async fn renew(
75
        &self,
76
        scheduler_id: &str,
77
        worker_ids: &[WorkerId],
78
        now: SystemTime,
79
        ttl: Duration,
80
    ) -> Result<(), Error>;
81
82
    /// When the lease on `worker_id` was last renewed, if a replica holds
83
    /// one.
84
    async fn renewed_at(&self, worker_id: &WorkerId) -> Result<Option<SystemTime>, Error>;
85
}
86
87
#[derive(Debug, Clone, Copy)]
88
struct LeaseRead {
89
    read_at: SystemTime,
90
    held: bool,
91
    /// The first of the reads in a row that found the lease missing.
92
    missing_since: Option<SystemTime>,
93
}
94
95
#[derive(Debug, Default)]
96
struct LeaseState {
97
    last_renewal: Option<SystemTime>,
98
    renewing: bool,
99
    /// Recent reads of peers' worker leases.
100
    reads: HashMap<WorkerId, LeaseRead>,
101
}
102
103
/// In-memory worker registry that tracks worker liveness.
104
///
105
/// Per-process: fed by the `connect_worker` streams this instance owns, not a
106
/// view of every worker in the deployment.
107
#[derive(Debug)]
108
pub struct WorkerRegistry {
109
    workers: RwLock<HashMap<WorkerId, SystemTime>>,
110
    /// Set when the scheduler's state is shared with other replicas.
111
    leases: OnceLock<Arc<dyn WorkerLeases>>,
112
    /// Every live peer replica renews leases, so a missing lease means a
113
    /// dead worker. False until the peers have been read, and while any of
114
    /// them is an older replica that does not renew leases.
115
    peers_renew_leases: AtomicBool,
116
    lease_state: Arc<Mutex<LeaseState>>,
117
    /// In-flight lease renewal task. Dropped with the registry so scheduler
118
    /// shutdown aborts it instead of leaving a store handle running in the
119
    /// background.
120
    renewal_task: Mutex<Option<JoinHandleDropGuard<()>>>,
121
}
122
123
impl Default for WorkerRegistry {
124
0
    fn default() -> Self {
125
0
        Self::new()
126
0
    }
127
}
128
129
impl WorkerRegistry {
130
    /// Creates a new worker registry.
131
642
    pub fn new() -> Self {
132
642
        Self {
133
642
            workers: RwLock::new(HashMap::new()),
134
642
            leases: OnceLock::new(),
135
642
            peers_renew_leases: AtomicBool::new(false),
136
642
            lease_state: Arc::new(Mutex::new(LeaseState::default())),
137
642
            renewal_task: Mutex::new(None),
138
642
        }
139
642
    }
140
141
    /// Updates the heartbeat timestamp for a worker. A heartbeat never moves
142
    /// back: a message that waited to be processed carries the time it
143
    /// started waiting, and the worker has been heard from since.
144
63.7k
    pub async fn update_worker_heartbeat(&self, worker_id: &WorkerId, now: SystemTime) {
145
63.7k
        let mut workers = self.workers.write().await;
146
63.7k
        let last_seen = workers.entry(worker_id.clone()).or_insert(now);
147
63.7k
        if *last_seen < now {
148
1.01k
            *last_seen = now;
149
62.7k
        }
150
63.7k
        trace!(?worker_id, now = %
Timestamp::try_from847
(
now847
).
unwrap847
(), "FLOW: Worker heartbeat updated in registry");
151
63.7k
    }
152
153
    /// Moves a registered worker's heartbeat forward to `now`, as its
154
    /// messages arrive. A message can arrive after the worker was removed,
155
    /// and before an earlier one has been processed, so this neither
156
    /// registers a worker nor moves a heartbeat back.
157
63.5k
    pub async fn worker_heard_from(&self, worker_id: &WorkerId, now: SystemTime) {
158
63.5k
        let mut workers = self.workers.write().await;
159
63.5k
        if let Some(
last_seen63.5k
) = workers.get_mut(worker_id)
160
63.5k
            && *last_seen < now
161
30.3k
        {
162
30.3k
            *last_seen = now;
163
33.2k
        }
164
63.5k
    }
165
166
2.37k
    pub async fn register_worker(&self, worker_id: &WorkerId, now: SystemTime) {
167
2.37k
        let mut workers = self.workers.write().await;
168
2.37k
        workers.insert(worker_id.clone(), now);
169
2.37k
        debug!(?worker_id, "FLOW: Worker registered in registry");
170
2.37k
    }
171
172
1.28k
    pub async fn remove_worker(&self, worker_id: &WorkerId) {
173
1.28k
        let mut workers = self.workers.write().await;
174
1.28k
        workers.remove(worker_id);
175
1.28k
        debug!(?worker_id, "FLOW: Worker removed from registry");
176
1.28k
    }
177
178
    /// Liveness as far as THIS instance can tell. Callers acting on "dead"
179
    /// must handle `Unknown` separately.
180
5.90k
    pub async fn check_liveness(
181
5.90k
        &self,
182
5.90k
        worker_id: &WorkerId,
183
5.90k
        timeout: Duration,
184
5.90k
        now: SystemTime,
185
5.90k
    ) -> WorkerLiveness {
186
5.90k
        let workers = self.workers.read().await;
187
188
5.90k
        let Some(
last_seen5.16k
) = workers.get(worker_id) else {
189
741
            trace!(?worker_id, "FLOW: Worker not registered on this instance");
190
741
            return WorkerLiveness::Unknown;
191
        };
192
193
        // An overflowing deadline can only be clock skew; treat as alive.
194
5.16k
        let liveness = match last_seen.checked_add(timeout) {
195
5.16k
            Some(
deadline4.67k
) if deadline > no
w4.67k
=>
WorkerLiveness::Alive4.67k
,
196
484
            Some(_) => WorkerLiveness::Stale,
197
0
            None => WorkerLiveness::Alive,
198
        };
199
5.16k
        trace!(
200
            ?worker_id,
201
41
            last_seen = %Timestamp::try_from(*last_seen).unwrap_or_default(),
202
            ?timeout,
203
            ?liveness,
204
            "FLOW: Worker liveness check"
205
        );
206
5.16k
        liveness
207
5.90k
    }
208
209
    /// Gives the registry the worker leases it shares with peer replicas.
210
132
    pub fn set_leases(&self, leases: Arc<dyn WorkerLeases>) {
211
132
        if self.leases.set(leases).is_err() {
212
0
            debug!("Worker leases were already set");
213
132
        }
214
132
    }
215
216
    /// Whether every live peer replica renews worker leases, as the peers'
217
    /// fleet records say.
218
1.37k
    pub fn set_peers_renew_leases(&self, all: bool) {
219
1.37k
        self.peers_renew_leases.store(all, Ordering::Release);
220
1.37k
    }
221
222
    /// Liveness of a worker connected here or to a peer replica. One
223
    /// connected here is judged on its heartbeat; another on the lease its
224
    /// replica renews every third of `timeout`. Held is `Alive`. Missing
225
    /// for a whole lease period is `Stale` once every live peer renews
226
    /// leases: a lease also lapses while the store refuses writes, and is
227
    /// renewed once they are taken again. `Unknown` otherwise, and without
228
    /// shared leases or when the lease cannot be read.
229
5.18k
    pub async fn fleet_liveness(
230
5.18k
        &self,
231
5.18k
        worker_id: &WorkerId,
232
5.18k
        timeout: Duration,
233
5.18k
        now: SystemTime,
234
5.18k
    ) -> WorkerLiveness {
235
5.18k
        let local = self.check_liveness(worker_id, timeout, now).await;
236
5.18k
        if local != WorkerLiveness::Unknown {
237
4.44k
            return local;
238
737
        }
239
737
        let Some(
leases731
) = self.leases.get() else {
240
6
            return WorkerLiveness::Unknown;
241
        };
242
731
        let previous = self.lease_state.lock().reads.get(worker_id).copied();
243
729
        let read = match 
previous517
{
244
301
            Some(read)
245
517
                if now
246
517
                    .duration_since(read.read_at)
247
517
                    .is_ok_and(|age| age < LEASE_READ_FRESHNESS
)301
=>
248
            {
249
301
                read
250
            }
251
430
            _ => match leases.renewed_at(worker_id).await {
252
428
                Ok(renewed_at) => {
253
428
                    let held = renewed_at.is_some_and(|renewed_at| 
{7
254
7
                        renewed_at
255
7
                            .checked_add(timeout.saturating_mul(LEASE_TIME_SLACK))
256
7
                            .is_none_or(|until| until > now)
257
7
                    });
258
428
                    let read = LeaseRead {
259
428
                        read_at: now,
260
428
                        held,
261
428
                        missing_since: if held {
262
5
                            None
263
                        } else {
264
423
                            previous.and_then(|read| read.missing_since).or(Some(now))
265
                        },
266
                    };
267
428
                    let mut state = self.lease_state.lock();
268
428
                    if state.reads.len() >= MAX_LEASE_READS {
269
0
                        state.reads.retain(|_, read| {
270
0
                            now.duration_since(read.read_at)
271
0
                                .is_ok_and(|age| age < ORPHANED_ACTION_TIMEOUT)
272
0
                        });
273
0
                        if state.reads.len() >= MAX_LEASE_READS {
274
0
                            state.reads.clear();
275
0
                        }
276
428
                    }
277
428
                    state.reads.insert(worker_id.clone(), read);
278
428
                    read
279
                }
280
2
                Err(err) => {
281
2
                    debug!(?worker_id, ?err, "Could not read a worker's lease");
282
2
                    return WorkerLiveness::Unknown;
283
                }
284
            },
285
        };
286
729
        if read.held {
287
104
            return WorkerLiveness::Alive;
288
625
        }
289
625
        let missing_for_a_period = read
290
625
            .missing_since
291
625
            .is_some_and(|since| now.duration_since(since).is_ok_and(|gap| gap >= timeout));
292
625
        if missing_for_a_period && 
self.peers_renew_leases411
.
load411
(
Ordering::Acquire411
) {
293
409
            WorkerLiveness::Stale
294
        } else {
295
216
            WorkerLiveness::Unknown
296
        }
297
5.18k
    }
298
299
    /// Renews, for `timeout`, the lease of every worker connected here and
300
    /// heard from within `timeout`. Called every second; renews every third
301
    /// of `timeout`, so a live worker's lease does not lapse. The writes run
302
    /// in the background, so a slow store does not hold up the caller, and
303
    /// one renewal finishes before the next starts.
304
11.2k
    pub async fn renew_leases(&self, scheduler_id: &str, timeout: Duration, now: SystemTime) {
305
11.2k
        let Some(
leases5.13k
) = self.leases.get().cloned() else {
306
6.12k
            return;
307
        };
308
        {
309
5.13k
            let mut state = self.lease_state.lock();
310
5.13k
            if state.renewing
311
5.09k
                || state.last_renewal.is_some_and(|last| 
{4.98k
312
4.98k
                    now.duration_since(last)
313
4.98k
                        .is_ok_and(|since| since < timeout / 3)
314
4.98k
                })
315
            {
316
3.85k
                return;
317
1.27k
            }
318
1.27k
            state.last_renewal = Some(now);
319
        }
320
1.27k
        let alive: Vec<WorkerId> = self
321
1.27k
            .workers
322
1.27k
            .read()
323
1.27k
            .await
324
1.27k
            .iter()
325
8.39k
            .
filter1.27k
(|(_, last_seen)| {
326
8.39k
                last_seen
327
8.39k
                    .checked_add(timeout)
328
8.39k
                    .is_none_or(|deadline| deadline > now)
329
8.39k
            })
330
7.68k
            .
map1.27k
(|(worker_id, _)| worker_id.clone())
331
1.27k
            .collect();
332
1.27k
        if alive.is_empty() {
333
120
            return;
334
1.15k
        }
335
1.15k
        self.lease_state.lock().renewing = true;
336
1.15k
        let lease_state = self.lease_state.clone();
337
1.15k
        let scheduler_id = scheduler_id.to_string();
338
1.15k
        let task = spawn!("worker_lease_renewal", async move 
{1.13k
339
1.13k
            let 
result1.12k
= leases.renew(&scheduler_id, &alive, now, timeout).await;
340
1.12k
            let mut state = lease_state.lock();
341
1.12k
            state.renewing = false;
342
1.12k
            if let Err(
err11
) = result {
343
11
                warn!(
344
                    ?err,
345
1
                    workers = alive.len(),
346
                    "Could not renew worker leases; peers cannot tell whether these workers are alive"
347
                );
348
                // Tried again on the next call rather than a third of the
349
                // timeout later.
350
11
                state.last_renewal = None;
351
1.11k
            }
352
1.12k
        });
353
1.15k
        *self.renewal_task.lock() = Some(task);
354
11.2k
    }
355
356
717
    pub async fn is_worker_alive(
357
717
        &self,
358
717
        worker_id: &WorkerId,
359
717
        timeout: Duration,
360
717
        now: SystemTime,
361
717
    ) -> bool {
362
717
        self.check_liveness(worker_id, timeout, now).await == WorkerLiveness::Alive
363
717
    }
364
365
0
    pub async fn get_worker_last_seen(&self, worker_id: &WorkerId) -> Option<SystemTime> {
366
0
        let workers = self.workers.read().await;
367
0
        workers.get(worker_id).copied()
368
0
    }
369
}
370
371
pub type SharedWorkerRegistry = Arc<WorkerRegistry>;
372
373
#[cfg(test)]
374
mod tests {
375
    use nativelink_macro::nativelink_test;
376
377
    use super::*;
378
379
    #[nativelink_test]
380
    async fn test_worker_heartbeat() {
381
        let registry = WorkerRegistry::new();
382
        let worker_id = WorkerId::from(String::from("test"));
383
        let now = SystemTime::now();
384
385
        // Worker not registered yet
386
        assert!(
387
            !registry
388
                .is_worker_alive(&worker_id, Duration::from_secs(5), now)
389
                .await
390
        );
391
392
        // Register worker
393
        registry.register_worker(&worker_id, now).await;
394
        assert!(
395
            registry
396
                .is_worker_alive(&worker_id, Duration::from_secs(5), now)
397
                .await
398
        );
399
400
        // Check with expired timeout
401
        let future = now.checked_add(Duration::from_secs(10)).unwrap();
402
        assert!(
403
            !registry
404
                .is_worker_alive(&worker_id, Duration::from_secs(5), future)
405
                .await
406
        );
407
408
        // Update heartbeat
409
        registry.update_worker_heartbeat(&worker_id, future).await;
410
        assert!(
411
            registry
412
                .is_worker_alive(&worker_id, Duration::from_secs(5), future)
413
                .await
414
        );
415
    }
416
417
    #[nativelink_test]
418
    async fn test_check_liveness_distinguishes_stale_from_unknown() {
419
        let registry = WorkerRegistry::new();
420
        let mine = WorkerId::from(String::from("mine"));
421
        let theirs = WorkerId::from(String::from("belongs-to-another-instance"));
422
        let now = SystemTime::now();
423
        let timeout = Duration::from_secs(5);
424
425
        // Never registered here. This is the case that must NOT read as dead:
426
        // with several schedulers on shared state it is a peer's worker.
427
        assert_eq!(
428
            registry.check_liveness(&theirs, timeout, now).await,
429
            WorkerLiveness::Unknown
430
        );
431
432
        registry.register_worker(&mine, now).await;
433
        assert_eq!(
434
            registry.check_liveness(&mine, timeout, now).await,
435
            WorkerLiveness::Alive
436
        );
437
438
        // Registered here but gone quiet: genuinely ours and genuinely dead.
439
        let later = now.checked_add(Duration::from_secs(10)).unwrap();
440
        assert_eq!(
441
            registry.check_liveness(&mine, timeout, later).await,
442
            WorkerLiveness::Stale
443
        );
444
445
        // Eviction takes it back to Unknown, not Stale.
446
        registry.remove_worker(&mine).await;
447
        assert_eq!(
448
            registry.check_liveness(&mine, timeout, later).await,
449
            WorkerLiveness::Unknown
450
        );
451
    }
452
453
    #[nativelink_test]
454
    async fn test_remove_worker() {
455
        let registry = WorkerRegistry::new();
456
        let worker_id = WorkerId::from(String::from("test-worker"));
457
        let now = SystemTime::now();
458
459
        registry.register_worker(&worker_id, now).await;
460
        assert!(
461
            registry
462
                .is_worker_alive(&worker_id, Duration::from_secs(5), now)
463
                .await
464
        );
465
466
        registry.remove_worker(&worker_id).await;
467
        assert!(
468
            !registry
469
                .is_worker_alive(&worker_id, Duration::from_secs(5), now)
470
                .await
471
        );
472
    }
473
}