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/api_worker_scheduler.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::cmp::Reverse;
16
use core::hash::{Hash, Hasher};
17
use core::ops::{Deref, DerefMut};
18
use core::sync::atomic::{AtomicU64, Ordering};
19
use core::time::Duration;
20
use std::collections::hash_map::DefaultHasher;
21
use std::collections::{BTreeSet, HashMap, HashSet, VecDeque};
22
use std::sync::Arc;
23
use std::time::{Instant, SystemTime, UNIX_EPOCH};
24
25
use async_lock::Mutex;
26
use futures::{StreamExt, future};
27
use lru::LruCache;
28
use nativelink_config::schedulers::{
29
    MemoryEscalationSpec, ReservationHoldSpec, WorkerAllocationStrategy, WorkerOutcomeTripwireSpec,
30
};
31
use nativelink_error::{Code, Error, ResultExt, make_err, make_input_err};
32
use nativelink_metric::{
33
    MetricFieldData, MetricKind, MetricPublishKnownKindData, MetricsComponent,
34
    RootMetricsComponent, group,
35
};
36
use nativelink_proto::com::github::trace_machina::nativelink::events::{
37
    Event, OriginEvent, ResponseEvent, event, response_event,
38
};
39
use nativelink_proto::com::github::trace_machina::nativelink::remote_execution::{
40
    ActionAttemptEnded, ActionResourceUsage, AttemptEndReason, ResourceOutcome, WorkerLoad,
41
};
42
use nativelink_util::action_messages::{
43
    ActionStage, ActionUniqueQualifier, MISSING_INPUT_ERROR_TIP, OperationId,
44
    STORE_UNREACHABLE_ERROR_TIP, WorkerId,
45
};
46
use nativelink_util::metrics::{
47
    WorkerDisconnectReason, record_dispatch_requeue, record_execution_cpu_time,
48
    record_execution_peak_memory, record_held_workers, record_worker_connected,
49
    record_worker_disconnected, record_worker_hold, record_worker_keepalive,
50
    record_worker_keepalive_gap, record_worker_state, record_worker_tripwire,
51
};
52
use nativelink_util::operation_state_manager::{
53
    Decline, Escalation, LossEscalation, UpdateOperationType, WorkerStateManager,
54
};
55
use nativelink_util::origin_event::get_node_id;
56
use nativelink_util::platform_properties::{PlatformProperties, PlatformPropertyValue};
57
use nativelink_util::shutdown_guard::ShutdownGuard;
58
use tokio::sync::{Notify, mpsc};
59
use tonic::async_trait;
60
use tracing::{debug, error, info, trace, warn};
61
62
/// The memory reservation an action was dispatched with, 0 without one.
63
67
fn reservation_of(properties: &PlatformProperties, property: &str) -> u64 {
64
67
    match properties.properties.get(property) {
65
25
        Some(PlatformPropertyValue::Minimum(kb)) => *kb,
66
42
        _ => 0,
67
    }
68
67
}
69
70
/// Where a reservation goes next on the escalation ladder.
71
#[derive(Debug, Clone, PartialEq, Eq)]
72
enum NextReservation {
73
    /// No connected worker advertises the property: nothing to grow toward.
74
    NoCeiling,
75
    /// The action already reserves the largest worker whole.
76
    AlreadyWhole { ceiling_kb: u64 },
77
    /// Nothing to grow from: no reservation and no sample.
78
    NoBase,
79
    /// The next reservation, and on the last step the CPU to hold with it.
80
    Step {
81
        value: u64,
82
        cpu: Option<(String, u64)>,
83
        ceiling_kb: u64,
84
    },
85
}
86
87
/// The step after `base_kb`: the next ladder class above it, or `percent`
88
/// of it, capped at the fleet's ceiling; at the ceiling the largest worker
89
/// is reserved whole, its CPU too. A memory kill and a lost worker
90
/// (RFC-0018) climb the same ladder through this.
91
42
fn next_reservation(
92
42
    policy: &MemoryEscalationSpec,
93
42
    properties: &PlatformProperties,
94
42
    reserved_kb: u64,
95
42
    base_kb: u64,
96
42
    (fleet_memory_kb, fleet_cpu): (u64, Option<u64>),
97
42
) -> NextReservation {
98
    // `max_kb` caps the fleet's ceiling; it cannot raise it past what a
99
    // worker declares, or the escalation lands where nothing can run.
100
42
    let ceiling_kb = if policy.max_kb > 0 {
101
0
        fleet_memory_kb.min(policy.max_kb)
102
    } else {
103
42
        fleet_memory_kb
104
    };
105
42
    if ceiling_kb == 0 {
106
0
        return NextReservation::NoCeiling;
107
42
    }
108
42
    let cpu_held = reservation_of(properties, &policy.cpu_property);
109
42
    let whole_worker_cpu = fleet_cpu.filter(|cores| 
*cores0
> 0);
110
42
    if reserved_kb >= ceiling_kb && 
whole_worker_cpu5
.
is_none_or5
(|cores|
cpu_held0
>=
cores0
) {
111
5
        return NextReservation::AlreadyWhole { ceiling_kb };
112
37
    }
113
37
    if base_kb == 0 {
114
0
        return NextReservation::NoBase;
115
37
    }
116
37
    let next = if policy.ladder_kb.is_empty() {
117
28
        Some(
118
28
            base_kb
119
28
                .saturating_mul(policy.percent)
120
28
                .checked_div(100)
121
28
                .unwrap_or(base_kb)
122
28
                .max(base_kb.saturating_add(1)),
123
28
        )
124
    } else {
125
9
        policy
126
9
            .ladder_kb
127
9
            .iter()
128
9
            .copied()
129
32
            .
filter9
(|kb| *kb > base_kb)
130
9
            .min()
131
    };
132
37
    let value = next.map_or(ceiling_kb, |kb| 
kb36
.
min36
(
ceiling_kb36
));
133
37
    let cpu = if value >= ceiling_kb {
134
2
        whole_worker_cpu.map(|cores| (
policy.cpu_property0
.
clone0
(),
cores0
))
135
    } else {
136
35
        None
137
    };
138
37
    NextReservation::Step {
139
37
        value,
140
37
        cpu,
141
37
        ceiling_kb,
142
37
    }
143
42
}
144
145
/// Why an update ends the attempt it is about, and the error behind it;
146
/// `None` for an update that keeps or completes the attempt.
147
13.1k
fn attempt_end_reason(update: &UpdateOperationType) -> Option<(AttemptEndReason, String)> {
148
12.8k
    match update {
149
        UpdateOperationType::UpdateWithDisconnect(_) => {
150
2
            Some((AttemptEndReason::WorkerLost, String::new()))
151
        }
152
15
        UpdateOperationType::UpdateWithEscalation(escalation) => Some((
153
15
            AttemptEndReason::OutOfMemory,
154
15
            escalation.reason.message_string(),
155
15
        )),
156
        UpdateOperationType::UpdateWithDecline(_) => {
157
11
            Some((AttemptEndReason::Declined, String::new()))
158
        }
159
275
        UpdateOperationType::UpdateWithError(err) => {
160
275
            let reason = match err.code {
161
1
                Code::ResourceExhausted => AttemptEndReason::Backpressure,
162
                // A command past its timeout comes back as a result; an error
163
                // with this code is the input fetch past max_download_timeout.
164
1
                Code::DeadlineExceeded => AttemptEndReason::InputFetchTimeout,
165
273
                _ => AttemptEndReason::WorkerError,
166
            };
167
275
            Some((reason, err.message_string()))
168
        }
169
        // The worker turns an input missing from the CAS into a result with
170
        // FAILED_PRECONDITION, which the client answers by uploading it and
171
        // asking again; a command past its timeout into one with
172
        // DEADLINE_EXCEEDED.
173
12.8k
        UpdateOperationType::UpdateWithActionStage(ActionStage::Completed(result)) => {
174
12.8k
            match result.error.as_ref() {
175
32
                Some(
err28
) if err.code == Code::DeadlineExceede
d28
=> {
176
28
                    Some((AttemptEndReason::Timeout, err.message_string()))
177
                }
178
4
                Some(err) if err.code == Code::FailedPrecondition => {
179
4
                    let message = err.message_string();
180
4
                    message
181
4
                        .contains(MISSING_INPUT_ERROR_TIP)
182
4
                        .then_some((AttemptEndReason::MissingInput, message))
183
                }
184
12.8k
                _ => None,
185
            }
186
        }
187
        UpdateOperationType::UpdateWithActionStage(_)
188
        | UpdateOperationType::KeepAlive
189
0
        | UpdateOperationType::ExecutionComplete => None,
190
    }
191
13.1k
}
192
193
/// Publishes that an attempt ended, as a child of its start event, so the
194
/// telemetry can say why an action ran more than once. Called once the
195
/// state manager took the update, so a rejected one reports nothing.
196
/// `try_send`: this runs under the scheduler's lock, and a full queue must
197
/// not stall scheduling for a report; a dropped one is logged.
198
771
fn publish_attempt_ended(
199
771
    tx: Option<&mpsc::Sender<OriginEvent>>,
200
771
    action_info: &ActionInfoWithProps,
201
771
    worker_id: &WorkerId,
202
771
    operation_id: &OperationId,
203
771
    reason: AttemptEndReason,
204
771
    detail: String,
205
771
) {
206
771
    let Some(
tx4
) = tx else {
207
767
        return;
208
    };
209
4
    let event = Event {
210
4
        event: Some(event::Event::Response(ResponseEvent {
211
4
            event: Some(response_event::Event::ActionAttemptEnded(
212
4
                ActionAttemptEnded {
213
4
                    operation_id: operation_id.to_string(),
214
4
                    worker_id: worker_id.to_string(),
215
4
                    reason: reason.into(),
216
4
                    detail,
217
4
                },
218
4
            )),
219
4
        })),
220
4
    };
221
4
    let origin_event = OriginEvent {
222
4
        version: 0,
223
4
        event_id: Uuid::now_v6(&get_node_id(Some(&event)))
224
4
            .hyphenated()
225
4
            .to_string(),
226
4
        parent_event_id: action_info
227
4
            .scheduler_start_execute_event_id
228
4
            .clone()
229
4
            .unwrap_or_default(),
230
4
        bazel_request_metadata: action_info.origin_metadata.bazel_metadata.clone(),
231
4
        identity: action_info.origin_metadata.identity.clone(),
232
4
        event: Some(event),
233
4
    };
234
4
    if let Err(
err0
) = tx.try_send(origin_event) {
235
0
        warn!(%operation_id, ?reason, ?err, "Dropped an attempt-ended origin event");
236
4
    }
237
771
}
238
239
/// How many refused results `LostResults` keeps; past it the oldest goes, and
240
/// its requeue is not reported.
241
const MAX_LOST_RESULTS: usize = 4096;
242
243
/// A result the state manager refused: the worker that sent it, its
244
/// attempt's start, and the result.
245
#[derive(Debug)]
246
struct LostResult {
247
    worker_id: WorkerId,
248
    action_info: ActionInfoWithProps,
249
    stage: ActionStage,
250
}
251
252
/// Results the state manager refused, oldest first, so a store that refuses
253
/// everything cannot grow it without bound. The executing sweep writes each
254
/// once the store takes writes again; one pushed out by the bound is
255
/// requeued instead, as before results were kept.
256
///
257
/// A result belongs to one attempt, on the worker that sent it. It is only
258
/// handed back for that worker, and it is dropped when the operation is
259
/// dispatched again, so it never completes a later attempt.
260
#[derive(Debug, Default)]
261
struct LostResults {
262
    by_operation: HashMap<OperationId, LostResult>,
263
    order: VecDeque<OperationId>,
264
}
265
266
impl LostResults {
267
8
    fn insert(
268
8
        &mut self,
269
8
        operation_id: OperationId,
270
8
        worker_id: WorkerId,
271
8
        action_info: ActionInfoWithProps,
272
8
        stage: ActionStage,
273
8
    ) {
274
8
        let lost = LostResult {
275
8
            worker_id,
276
8
            action_info,
277
8
            stage,
278
8
        };
279
8
        if self
280
8
            .by_operation
281
8
            .insert(operation_id.clone(), lost)
282
8
            .is_none()
283
8
        {
284
8
            self.order.push_back(operation_id);
285
8
        
}0
286
8
        while self.order.len() > MAX_LOST_RESULTS {
287
0
            if let Some(oldest) = self.order.pop_front() {
288
0
                self.by_operation.remove(&oldest);
289
0
            }
290
        }
291
8
    }
292
293
    /// The result `worker_id` sent for `operation_id`, if one is held.
294
56
    fn stage(&self, worker_id: &WorkerId, operation_id: &OperationId) -> Option<&ActionStage> {
295
56
        self.by_operation
296
56
            .get(operation_id)
297
56
            .filter(|lost| 
lost.worker_id7
==
*worker_id7
)
298
56
            .map(|lost| &lost.stage)
299
56
    }
300
301
    /// Removes and returns the result `worker_id` sent for `operation_id`.
302
19
    fn take(
303
19
        &mut self,
304
19
        worker_id: &WorkerId,
305
19
        operation_id: &OperationId,
306
19
    ) -> Option<(ActionInfoWithProps, ActionStage)> {
307
19
        self.stage(worker_id, operation_id)
?18
;
308
1
        self.forget(operation_id)
309
1
            .map(|lost| (lost.action_info, lost.stage))
310
19
    }
311
312
    /// Removes whatever is held for `operation_id`, whoever sent it.
313
15.2k
    fn forget(&mut self, operation_id: &OperationId) -> Option<LostResult> {
314
15.2k
        let 
lost3
= self.by_operation.remove(operation_id)
?15.2k
;
315
3
        self.order.retain(|id| id != operation_id);
316
3
        Some(lost)
317
15.2k
    }
318
}
319
320
/// How many state-manager lookups `kill_revoked_operations` has in flight
321
/// at once while checking which running operations were revoked.
322
const MAX_CONCURRENT_REVOKED_CHECKS: usize = 32;
323
324
/// How many of the action's `priority` properties the worker carries with
325
/// the same value. A priority property never restricts placement; it says
326
/// where the action would rather be.
327
7
fn priority_matches(action: &PlatformProperties, worker: &Worker) -> usize {
328
7
    action
329
7
        .properties
330
7
        .iter()
331
11
        .
filter7
(|(name, value)| {
332
11
            
matches!7
(value, PlatformPropertyValue::Priority(_))
333
4
                && worker.platform_properties.properties.get(*name) == Some(*value)
334
11
        })
335
7
        .count()
336
7
}
337
338
/// How much of the worker's advertised capacity would be left after this
339
/// action, summed over the action's `minimum` properties, in thousandths.
340
/// Lower is a tighter fit. An action with no numbers fits every worker
341
/// equally, and a dimension the worker does not advertise is ignored.
342
7
fn fit_leftover_permille(action: &PlatformProperties, worker: &Worker) -> u64 {
343
7
    let mut leftover = 0u64;
344
11
    for (name, value) in 
&action.properties7
{
345
11
        let PlatformPropertyValue::Minimum(
needed7
) = value else {
346
4
            continue;
347
        };
348
        let (
349
7
            Some(PlatformPropertyValue::Minimum(available)),
350
7
            Some(PlatformPropertyValue::Minimum(total)),
351
        ) = (
352
7
            worker.platform_properties.properties.get(name),
353
7
            worker.total_platform_properties.properties.get(name),
354
        )
355
        else {
356
0
            continue;
357
        };
358
7
        if *total == 0 {
359
0
            continue;
360
7
        }
361
7
        let remaining = available.saturating_sub(*needed);
362
7
        leftover += remaining.saturating_mul(1000) / total;
363
    }
364
7
    leftover
365
7
}
366
367
/// How many property shapes `static_verdicts` holds before it is emptied.
368
const MAX_STATIC_VERDICTS: usize = 4096;
369
370
use uuid::Uuid;
371
372
/// Metrics for tracking scheduler performance.
373
#[derive(Debug, Default)]
374
pub struct SchedulerMetrics {
375
    /// Total number of worker additions.
376
    pub workers_added: AtomicU64,
377
    /// Total number of worker removals.
378
    pub workers_removed: AtomicU64,
379
    /// Total number of `find_worker_for_action` calls.
380
    pub find_worker_calls: AtomicU64,
381
    /// Total number of successful worker matches.
382
    pub find_worker_hits: AtomicU64,
383
    /// Total number of failed worker matches (no worker found).
384
    pub find_worker_misses: AtomicU64,
385
    /// Total time spent in `find_worker_for_action` (nanoseconds).
386
    pub find_worker_time_ns: AtomicU64,
387
    /// Total number of workers iterated during find operations.
388
    pub workers_iterated: AtomicU64,
389
    /// Total number of action dispatches.
390
    pub actions_dispatched: AtomicU64,
391
    /// Total number of keep-alive updates.
392
    pub keep_alive_updates: AtomicU64,
393
    /// Total number of worker timeouts.
394
    pub worker_timeouts: AtomicU64,
395
    /// Dispatches the worker declined, requeued untried.
396
    pub dispatches_declined: AtomicU64,
397
    /// Dispatches that found the worker's channel full, requeued untried.
398
    pub dispatch_channel_full: AtomicU64,
399
    /// Dispatches requeued because the worker never acknowledged them.
400
    pub dispatches_unacknowledged: AtomicU64,
401
}
402
403
use crate::awaited_action_db::PeerScheduler;
404
use crate::match_outcome::{
405
    MatchOutcome, PropertyShape, UnsatisfiableReason, explain_unsatisfiable,
406
};
407
use crate::platform_property_manager::PlatformPropertyManager;
408
use crate::resource_sketch::{Observation, ResourceSketch, SketchKey};
409
use crate::simple_scheduler_state_manager::OnWorker;
410
use crate::worker::{
411
    ActionInfoWithProps, PendingActionInfoData, TripwireState, Worker, WorkerIdChosenBy,
412
    WorkerTimestamp, WorkerUpdate,
413
};
414
use crate::worker_capability_index::WorkerCapabilityIndex;
415
use crate::worker_registry::SharedWorkerRegistry;
416
use crate::worker_scheduler::{WorkerScheduler, WorkerSummary};
417
418
#[derive(Debug)]
419
struct Workers(LruCache<WorkerId, Worker>);
420
421
impl Deref for Workers {
422
    type Target = LruCache<WorkerId, Worker>;
423
424
14.4M
    fn deref(&self) -> &Self::Target {
425
14.4M
        &self.0
426
14.4M
    }
427
}
428
429
impl DerefMut for Workers {
430
74.2k
    fn deref_mut(&mut self) -> &mut Self::Target {
431
74.2k
        &mut self.0
432
74.2k
    }
433
}
434
435
// Note: This could not be a derive macro because this derive-macro
436
// does not support LruCache and nameless field structs.
437
impl MetricsComponent for Workers {
438
0
    fn publish(
439
0
        &self,
440
0
        _kind: MetricKind,
441
0
        _field_metadata: MetricFieldData,
442
0
    ) -> Result<MetricPublishKnownKindData, nativelink_metric::Error> {
443
0
        let _enter = group!("workers").entered();
444
0
        for (worker_id, worker) in self.iter() {
445
0
            let _enter = group!(worker_id).entered();
446
0
            worker.publish(MetricKind::Component, MetricFieldData::default())?;
447
        }
448
0
        Ok(MetricPublishKnownKindData::Component)
449
0
    }
450
}
451
452
/// A worker kept for one queued action that found no room anywhere.
453
#[derive(Debug, Clone)]
454
struct Hold {
455
    /// The action the worker is kept for.
456
    action: ActionUniqueQualifier,
457
    /// When the hold is given up.
458
    until: SystemTime,
459
    /// The last matching pass that read the action, by `pass_generation`.
460
    /// A pass that read the whole queue without meeting it means the
461
    /// action is gone, and so is the reason to hold.
462
    seen_in: u64,
463
    /// Whether the action is on its way to a worker, which took it off the
464
    /// queue: the passes meanwhile do not meet it, and the hold waits for
465
    /// the worker to take it or send it back.
466
    dispatched: bool,
467
}
468
469
/// An action whose hold expired: it is not held for again until `until`.
470
#[derive(Debug, Clone)]
471
struct HoldCooldown {
472
    until: SystemTime,
473
    /// Expiries in a row on a worker that was idle, each doubling the
474
    /// cooldown, up to `MAX_IDLE_EXPIRY_DOUBLINGS`.
475
    idle_expiries: u32,
476
    /// The last matching pass that read the action; see `Hold::seen_in`.
477
    seen_in: u64,
478
}
479
480
/// The longest a hold lasts whatever `max_hold_s` says, so that the time
481
/// it ends at can always be computed.
482
const HOLD_CEILING_S: u64 = 7 * 24 * 60 * 60;
483
484
/// How many times in a row an expiry on an idle worker doubles the wait
485
/// before the action is held for again: sixteen times `max_hold_s` at most.
486
const MAX_IDLE_EXPIRY_DOUBLINGS: u32 = 4;
487
488
20
fn hold_duration(spec: ReservationHoldSpec) -> Duration {
489
20
    Duration::from_secs(spec.max_hold_s.min(HOLD_CEILING_S))
490
20
}
491
492
/// A queued action a matching pass asks a worker for: which action, so a
493
/// worker held for it recognises it, and since when it has waited, for
494
/// whether to hold a worker for it.
495
/// The platform property a worker advertises its node under (the chart's
496
/// `advertiseNodeName`). A retry keeps off every worker on the node a
497
/// failed attempt ran on, where the workers say which that is: a bad host
498
/// takes every worker on it down with it.
499
pub const NODE_NAME_PROPERTY: &str = "node_name";
500
501
/// The node a worker says it is on, if it says.
502
26.0k
fn node_name_of(worker: &Worker) -> Option<&str> {
503
26.0k
    match worker
504
26.0k
        .total_platform_properties
505
26.0k
        .properties
506
26.0k
        .get(NODE_NAME_PROPERTY)
?26.0k
507
    {
508
0
        PlatformPropertyValue::Exact(node)
509
9
        | PlatformPropertyValue::Priority(node)
510
0
        | PlatformPropertyValue::Ignore(node)
511
9
        | PlatformPropertyValue::Unknown(
node0
) => Some(node.as_str()),
512
0
        PlatformPropertyValue::Minimum(_) => None,
513
    }
514
26.0k
}
515
516
#[derive(Debug, Clone, Copy)]
517
pub struct QueuedAction<'a> {
518
    pub unique_qualifier: &'a ActionUniqueQualifier,
519
    pub insert_timestamp: SystemTime,
520
    /// Workers this action failed or timed out on: any other worker that
521
    /// can run it is preferred, and these only when none other has taken
522
    /// it within `AVOID_FALLBACK_AFTER` of its last requeue.
523
    pub avoid: &'a [WorkerId],
524
    /// The nodes of those workers, as the record remembers them: the
525
    /// worker itself may be connected to another replica.
526
    pub avoid_nodes: &'a [String],
527
    /// When the action was last queued, from its state.
528
    pub queued_since: SystemTime,
529
}
530
531
/// What a requeued action asks the matcher to keep off: the workers it
532
/// failed on, their nodes, and whether the wait for another taker is over.
533
#[derive(Debug, Clone, Copy)]
534
pub struct Avoidance<'a> {
535
    pub workers: &'a [WorkerId],
536
    pub nodes: &'a [String],
537
    /// The action has waited `AVOID_FALLBACK_AFTER` since its requeue with
538
    /// no other taker, so the avoided workers may have it.
539
    pub fallback_ok: bool,
540
}
541
542
impl Avoidance<'_> {
543
    const NONE: Avoidance<'static> = Avoidance {
544
        workers: &[],
545
        nodes: &[],
546
        fallback_ok: true,
547
    };
548
549
29.3k
    const fn is_empty(&self) -> bool {
550
29.3k
        self.workers.is_empty() && 
self.nodes28.8k
.
is_empty28.8k
()
551
29.3k
    }
552
}
553
554
/// The fewest workers the outcome tripwire may have drained at once on one
555
/// scheduler replica, whatever `max_drained_percent` of the replica's
556
/// workers comes to. Each replica brakes on the workers connected to it
557
/// (the census carries worker shapes, not counts), and a replica with a
558
/// handful of workers would otherwise round a node's pair down to one.
559
pub const TRIPWIRE_DRAIN_FLOOR: usize = 2;
560
561
/// How long a requeued action waits for a worker it did not fail on before
562
/// the ones it did fail on may take it. Each scheduler replica matches its
563
/// own workers only: a replica whose free workers are all avoided leaves
564
/// the action for a peer with others, and only after this long with no
565
/// taker (a lone worker, a fleet whose only room is the bad node) does any
566
/// worker do.
567
pub const AVOID_FALLBACK_AFTER: Duration = Duration::from_secs(30);
568
569
/// Which of `owners`, sorted, distinct and not empty, holds a worker for
570
/// `action`: the same one on every scheduler that sees the same owners,
571
/// by a hash of the action. Replicas run one binary, so the hash agrees.
572
#[must_use]
573
6
pub fn hold_owner<'a>(action: &ActionUniqueQualifier, owners: &[&'a str]) -> &'a str {
574
6
    let mut hasher = DefaultHasher::new();
575
6
    action.hash(&mut hasher);
576
6
    let count = u64::try_from(owners.len()).unwrap_or(u64::MAX);
577
6
    let index = usize::try_from(hasher.finish() % count).unwrap_or(0);
578
6
    owners[index]
579
6
}
580
581
/// Whether `platform_properties` would fit `worker` once any one of its
582
/// running actions finished: every `Minimum` it asks is within what the
583
/// worker has left plus the largest reservation of that property among
584
/// the actions running on it.
585
50
fn fits_after_one_finishes(platform_properties: &PlatformProperties, worker: &Worker) -> bool {
586
50
    platform_properties.properties.iter().all(|(name, value)| {
587
50
        let PlatformPropertyValue::Minimum(needed) = value else {
588
0
            return true;
589
        };
590
50
        let left = match worker.platform_properties.properties.get(name) {
591
50
            Some(PlatformPropertyValue::Minimum(left)) => *left,
592
0
            _ => 0,
593
        };
594
50
        let largest_running = worker
595
50
            .running_action_infos
596
50
            .values()
597
131
            .
filter_map50
(|pending| {
598
131
                match pending.action_info.platform_properties.properties.get(name) {
599
131
                    Some(PlatformPropertyValue::Minimum(reserved)) => Some(*reserved),
600
0
                    _ => None,
601
                }
602
131
            })
603
50
            .max()
604
50
            .unwrap_or(0);
605
50
        *needed <= left.saturating_add(largest_running)
606
50
    })
607
50
}
608
609
/// A collection of workers that are available to run tasks.
610
#[derive(MetricsComponent)]
611
struct ApiWorkerSchedulerImpl {
612
    /// A `LruCache` of workers available based on `allocation_strategy`.
613
    #[metric(group = "workers")]
614
    workers: Workers,
615
616
    /// The worker state manager.
617
    #[metric(group = "worker_state_manager")]
618
    worker_state_manager: Arc<dyn WorkerStateManager>,
619
    /// The allocation strategy for workers.
620
    allocation_strategy: WorkerAllocationStrategy,
621
    /// The `minimum` property compared against each worker's reported free
622
    /// memory before placement; unset means no veto.
623
    live_memory_veto: Option<String>,
624
    /// How a memory kill is turned into a retry with a larger reservation;
625
    /// unset means the kill fails the action.
626
    memory_escalation: Option<MemoryEscalationSpec>,
627
    /// How a queued action that keeps finding no room gets a worker held
628
    /// for it; unset means never.
629
    reservation_hold: Option<ReservationHoldSpec>,
630
    /// When a worker's own attempt outcomes drain it; unset means never.
631
    outcome_tripwire: Option<WorkerOutcomeTripwireSpec>,
632
    /// Where attempt-ended origin events go; unset publishes none.
633
    attempt_events: Option<mpsc::Sender<OriginEvent>>,
634
    /// Attempts whose result the state manager refused, by operation, for
635
    /// the executing sweep to report when it requeues them.
636
    lost_results: LostResults,
637
    /// Workers held for one queued action each, by worker, and the same
638
    /// holds by action. A held worker is offered nothing but its action.
639
    holds: HashMap<WorkerId, Hold>,
640
    holds_by_action: HashMap<ActionUniqueQualifier, WorkerId>,
641
    /// Actions whose hold expired, and until when they are not held for
642
    /// again, so one that never fits does not keep a worker idle in turns.
643
    hold_cooldowns: HashMap<ActionUniqueQualifier, HoldCooldown>,
644
    /// Counts matching passes, so a hold can record the last pass that
645
    /// met its action; see `Hold::seen_in`.
646
    pass_generation: u64,
647
    /// A channel to notify the matching engine that the worker pool has changed.
648
    worker_change_notify: Arc<Notify>,
649
    /// Bumped with every notification, under the same lock as placement, so
650
    /// a matching pass can tell that room opened while it was walking the
651
    /// queue and offer that room to the oldest waiting action first.
652
    capacity_generation: Arc<AtomicU64>,
653
    /// Worker registry for tracking worker liveness.
654
    worker_registry: SharedWorkerRegistry,
655
656
    /// Whether the worker scheduler is shutting down.
657
    shutting_down: bool,
658
659
    /// Index for fast worker capability lookup.
660
    /// Used to accelerate `find_worker_for_action` by filtering candidates
661
    /// based on properties before doing linear scan.
662
    capability_index: WorkerCapabilityIndex,
663
664
    /// Incremented when the set of distinct worker shapes changes, here or
665
    /// on a peer. A worker joining or leaving with a shape the fleet already
666
    /// has does not count: the unsatisfiable tracker keys its clock on this,
667
    /// and a pool that scales up and down with identical workers used to
668
    /// reset that clock every time, so an action no shape could ever run
669
    /// waited forever behind a fleet that never stopped moving.
670
    fleet_generation: u64,
671
    /// The distinct shapes behind `fleet_generation`, local and peer.
672
    fleet_shape_set: BTreeSet<PropertyShape>,
673
674
    /// What the workers connected to other schedulers on the same state
675
    /// registered with, one entry per distinct shape, sorted by shape so
676
    /// that an unchanged fleet compares equal. `None` until the peers have
677
    /// been read, and whenever reading them fails: an action is then never
678
    /// judged unsatisfiable, since a peer might have a worker for it.
679
    peer_fleet: Option<Vec<PlatformProperties>>,
680
681
    /// The peers as the census last read them, sorted by id, for deciding
682
    /// which scheduler holds a worker for an action; empty while the census
683
    /// is unknown.
684
    peer_schedulers: Vec<PeerScheduler>,
685
686
    /// The id this scheduler publishes to its peers under.
687
    scheduler_id: String,
688
689
    /// Whether this scheduler shares its state with peers. A non-shared db is
690
    /// the whole fleet, so peer-absence is authoritative at once; a shared one
691
    /// applies the census warm-up / staleness checks below before it trusts
692
    /// peer-absence to fail an action.
693
    shared: bool,
694
695
    /// One peer-record TTL, used for both the census warm-up and staleness
696
    /// bounds below.
697
    record_ttl: Duration,
698
699
    /// When the peer census last became known (a `None` -> `Some` exchange).
700
    /// Peer-absence is only trusted to fail an action once it has been known
701
    /// for `record_ttl`, so a peer publishing on its own cadence has had time
702
    /// to appear. Cleared whenever the census goes unknown.
703
    peer_fleet_known_since: Option<SystemTime>,
704
705
    /// When the peer census was last refreshed by a successful exchange. If the
706
    /// exchange task dies or stalls this stops advancing, and after `record_ttl`
707
    /// the census is treated as stale and peer-absence is no longer trusted
708
    /// (fail open). Cleared whenever the census goes unknown.
709
    peer_fleet_last_refresh: Option<SystemTime>,
710
711
    /// Woken when a worker joins or leaves this scheduler, so peers hear
712
    /// about it without waiting for the next periodic exchange.
713
    local_fleet_change_notify: Arc<Notify>,
714
715
    /// Whether an action with a given property shape could run on some
716
    /// connected worker when that worker is idle. `None` means it could. This
717
    /// depends only on what workers registered with, so it holds until the
718
    /// fleet changes, at which point the map is emptied.
719
    static_verdicts: HashMap<PropertyShape, Option<Arc<UnsatisfiableReason>>>,
720
}
721
722
/// Whether peer-absence can be trusted to fail an action, given the census
723
/// state and the current time. A free function so its edge cases (warm-up,
724
/// staleness, clock skew, db kind) can be unit-tested without a scheduler.
725
202
fn peer_census_trusted(
726
202
    shared: bool,
727
202
    peer_fleet_known: bool,
728
202
    peer_fleet_known_since: Option<SystemTime>,
729
202
    peer_fleet_last_refresh: Option<SystemTime>,
730
202
    record_ttl: Duration,
731
202
    now: SystemTime,
732
202
) -> bool {
733
    // Unknown (a shared db before its first exchange or after a failed one): a
734
    // peer we cannot see might run the action. Checked before the non-shared
735
    // short-circuit so a deliberately-unknown census is never trusted.
736
202
    if !peer_fleet_known {
737
2
        return false;
738
200
    }
739
    // A non-shared db is the whole fleet; peer-absence is authoritative at
740
    // once, with no warm-up or staleness delay.
741
200
    if !shared {
742
155
        return true;
743
45
    }
744
45
    let (Some(
known_since43
), Some(
last_refresh43
)) = (peer_fleet_known_since, peer_fleet_last_refresh)
745
    else {
746
2
        return false;
747
    };
748
    // Warm: the census must have been known for a full record TTL, so a peer
749
    // publishing on its own ~interval cadence has had time to appear. A clock
750
    // going backwards (Err) is treated as not-yet-warm: don't fail.
751
43
    let warm = now
752
43
        .duration_since(known_since)
753
43
        .is_ok_and(|elapsed| elapsed >= record_ttl);
754
    // Fresh: a successful exchange within the last record TTL. If the exchange
755
    // task died or stalled this goes stale and we stop trusting peer-absence
756
    // (fail open). A future-dated refresh (clock skew) counts as fresh.
757
43
    let fresh = now
758
43
        .duration_since(last_refresh)
759
43
        .map_or(true, |elapsed| 
elapsed42
<=
record_ttl42
);
760
43
    warm && 
fresh35
761
202
}
762
763
impl core::fmt::Debug for ApiWorkerSchedulerImpl {
764
0
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
765
0
        f.debug_struct("ApiWorkerSchedulerImpl")
766
0
            .field("workers", &self.workers)
767
0
            .field("allocation_strategy", &self.allocation_strategy)
768
0
            .field("worker_change_notify", &self.worker_change_notify)
769
0
            .field(
770
0
                "capability_index_size",
771
0
                &self.capability_index.worker_count(),
772
0
            )
773
0
            .field("worker_registry", &self.worker_registry)
774
0
            .finish_non_exhaustive()
775
0
    }
776
}
777
778
impl ApiWorkerSchedulerImpl {
779
    /// Refreshes the lifetime of the worker with the given timestamp.
780
    ///
781
    /// Instead of sending N keepalive messages (one per operation),
782
    /// we now send a single worker heartbeat. The worker registry tracks worker liveness,
783
    /// and timeout detection checks the worker's `last_seen` instead of per-operation timestamps.
784
    ///
785
    /// Note: This only updates the local worker state. The worker registry is updated
786
    /// separately after releasing the inner lock to reduce contention.
787
63.7k
    fn refresh_lifetime(
788
63.7k
        &mut self,
789
63.7k
        worker_id: &WorkerId,
790
63.7k
        timestamp: WorkerTimestamp,
791
63.7k
        load: Option<WorkerLoad>,
792
63.7k
        keepalive: bool,
793
63.7k
    ) -> Result<(), Error> {
794
63.7k
        let 
worker63.7k
= self.workers.0.peek_mut(worker_id).ok_or_else(||
{1
795
1
            make_input_err!(
796
                "Worker not found in worker map in refresh_lifetime() {}",
797
                worker_id
798
            )
799
1
        })?;
800
        // The scheduler's wall clock can step backwards (NTP, VM time
801
        // sync). The worker is no less alive for it, so a stale-looking
802
        // timestamp keeps the newer one instead of failing: an error here
803
        // propagates up through `touch_liveness` and would discard the
804
        // message that proved liveness — including a finished
805
        // `ExecuteResult`, stranding the operation in `Executing`.
806
63.7k
        if worker.last_update_timestamp > timestamp {
807
2
            warn!(
808
                %worker_id,
809
                last_update_timestamp = worker.last_update_timestamp,
810
                timestamp,
811
                "Scheduler clock stepped backwards; keeping newer liveness timestamp",
812
            );
813
63.7k
        }
814
63.7k
        record_worker_keepalive_gap(timestamp.saturating_sub(worker.last_update_timestamp));
815
63.7k
        worker.last_update_timestamp = worker.last_update_timestamp.max(timestamp);
816
        // Any other message (an acknowledgement, a decline, an execute
817
        // result) proves the worker is alive and nothing more. A decline in
818
        // particular is not the worker saying it is ready to be asked
819
        // again, so the pause it took stands until a real keepalive.
820
63.7k
        if !keepalive {
821
38.0k
            return Ok(());
822
25.7k
        }
823
        // A keepalive without a load (an older worker) leaves the last
824
        // report in place. A report with
825
        // more room than the last one can make a vetoed action eligible
826
        // again; less room never does.
827
25.7k
        let more_room = load.is_some_and(|load| 
{25.7k
828
25.7k
            let more = worker
829
25.7k
                .last_load
830
25.7k
                .as_ref()
831
25.7k
                .is_none_or(|last| 
load.free_memory_kb23.9k
>
last.free_memory_kb23.9k
);
832
25.7k
            worker.last_load = Some(load);
833
25.7k
            more
834
25.7k
        });
835
        // A keepalive is the worker saying it is ready to be asked again,
836
        // so a pause from backpressure lasts one keepalive interval. A
837
        // pause taken for a decline for load is the exception: it waits
838
        // for a keepalive whose free memory, read above, covers what the
839
        // declined action wanted. A worker that reports no load is taken
840
        // at its word. So is a worker that admits when idle and holds
841
        // nothing here: it declined while something of its own was still
842
        // finishing, and once idle it admits whatever it is offered, so
843
        // waiting for free memory it may never report would strand it.
844
25.7k
        let idle_and_admitting = worker.admits_when_idle && 
worker.running_action_infos5
.
is_empty5
();
845
25.7k
        let load_fits = idle_and_admitting
846
25.7k
            || match (worker.pause_needs_kb, worker.last_load) {
847
6
                (Some(needs_kb), Some(load)) => load.free_memory_kb >= needs_kb,
848
25.7k
                _ => true,
849
            };
850
        // A keepalive reporting room for what the worker declined while
851
        // idle makes that size worth offering it again.
852
25.7k
        let idle_decline_lifted = match (worker.idle_declined_kb, load) {
853
2
            (Some(declined_kb), Some(load)) => load.free_memory_kb >= declined_kb,
854
25.7k
            _ => false,
855
        };
856
25.7k
        if idle_decline_lifted {
857
1
            worker.idle_declined_kb = None;
858
25.7k
        }
859
25.7k
        let resumed = worker.is_paused && 
load_fits13
;
860
25.7k
        if resumed {
861
10
            worker.is_paused = false;
862
10
            worker.pause_needs_kb = None;
863
10
            record_worker_state("paused", false);
864
25.7k
        }
865
        // Either is room the fleet did not have a moment ago, so the
866
        // capacity generation moves and the matcher is woken, together:
867
        // a pass in flight offers the room to its parked actions first,
868
        // and a pass not in flight starts. `capacity_changed` by hand,
869
        // since `worker` still borrows the map.
870
25.7k
        if resumed || 
more_room25.7k
||
idle_decline_lifted18.6k
{
871
7.10k
            self.capacity_generation.fetch_add(1, Ordering::Relaxed);
872
7.10k
            self.worker_change_notify.notify_one();
873
18.6k
        }
874
875
25.7k
        trace!(
876
            ?worker_id,
877
277
            running_operations = worker.running_action_infos.len(),
878
            "Worker keepalive received"
879
        );
880
25.7k
        record_worker_keepalive();
881
882
25.7k
        Ok(())
883
63.7k
    }
884
885
    /// Adds a worker to the pool.
886
    /// Note: This function will not do any task matching.
887
2.36k
    fn add_worker(&mut self, worker: Worker) -> Result<(), Error> {
888
2.36k
        let worker_id = worker.id.clone();
889
2.36k
        let platform_properties = worker.platform_properties.clone();
890
        // A replacement is one out and one in, so the gauge only moves for a
891
        // genuinely new worker.
892
2.36k
        let replaced = self.workers.put(worker_id.clone(), worker);
893
894
        // Add to capability index for fast matching
895
2.36k
        self.capability_index
896
2.36k
            .add_worker(&worker_id, &platform_properties);
897
2.36k
        self.fleet_changed();
898
2.36k
        self.local_fleet_change_notify.notify_one();
899
900
        // Worker is not cloneable, and we do not want to send the initial connection results until
901
        // we have added it to the map, or we might get some strange race conditions due to the way
902
        // the multi-threaded runtime works.
903
2.36k
        let worker = self.workers.peek_mut(&worker_id).unwrap();
904
2.36k
        let res = worker
905
2.36k
            .send_initial_connection_result(self.live_memory_veto.as_deref())
906
2.36k
            .err_tip(|| "Failed to send initial connection result to worker");
907
2.36k
        if let Err(
err0
) = &res {
908
0
            error!(
909
                ?worker_id,
910
                ?err,
911
                "Worker connection appears to have been closed while adding to pool"
912
            );
913
2.36k
        }
914
2.36k
        if let Some(
replaced6
) = &replaced {
915
6
            if replaced.is_draining {
916
0
                record_worker_state("draining", false);
917
6
            }
918
6
            if replaced.is_paused {
919
0
                record_worker_state("paused", false);
920
6
            }
921
2.35k
        } else {
922
2.35k
            record_worker_connected();
923
2.35k
        }
924
2.36k
        self.capacity_changed();
925
2.36k
        res
926
2.36k
    }
927
928
    /// Removes worker from pool.
929
    /// Note: The caller is responsible for any rescheduling of any tasks that might be
930
    /// running.
931
1.82k
    fn remove_worker(&mut self, worker_id: &WorkerId) -> Option<Worker> {
932
1.82k
        self.end_hold(worker_id, "released");
933
        // Remove from capability index
934
1.82k
        self.capability_index.remove_worker(worker_id);
935
        // Pop before recomputing the shapes, or the departing worker still
936
        // counts and a cached verdict that only it satisfied survives it.
937
1.82k
        let result = self.workers.pop(worker_id);
938
1.82k
        self.fleet_changed();
939
1.82k
        self.local_fleet_change_notify.notify_one();
940
941
1.82k
        self.capacity_changed();
942
1.82k
        result
943
1.82k
    }
944
945
4.32k
    fn fleet_changed(&mut self) {
946
4.32k
        let mut shapes: BTreeSet<PropertyShape> = self
947
4.32k
            .workers
948
4.32k
            .iter()
949
152k
            .
map4.32k
(|(_, w)| PropertyShape::from(&w.total_platform_properties))
950
4.32k
            .collect();
951
4.32k
        if let Some(
peer_fleet3.81k
) = &self.peer_fleet {
952
3.81k
            shapes.extend(peer_fleet.iter().map(PropertyShape::from));
953
3.81k
        
}509
954
4.32k
        if shapes == self.fleet_shape_set {
955
3.46k
            return;
956
866
        }
957
866
        self.fleet_shape_set = shapes;
958
866
        self.fleet_generation += 1;
959
866
        self.static_verdicts.clear();
960
4.32k
    }
961
962
    /// Something about the fleet's room to run actions changed: a worker
963
    /// joined, left, paused, resumed, drained or finished an action.
964
19.1k
    fn capacity_changed(&self) {
965
19.1k
        self.capacity_generation.fetch_add(1, Ordering::Relaxed);
966
19.1k
        self.worker_change_notify.notify_one();
967
19.1k
    }
968
969
    /// The distinct properties this scheduler's workers registered with.
970
1.36k
    fn fleet_shapes(&self) -> Vec<PlatformProperties> {
971
1.36k
        let mut seen = HashSet::new();
972
1.36k
        self.workers
973
1.36k
            .iter()
974
1.36k
            .map(|(_, w)| &w.total_platform_properties)
975
6.71k
            .
filter1.36k
(|totals| seen.insert(PropertyShape::from(*totals)))
976
1.36k
            .cloned()
977
1.36k
            .collect()
978
1.36k
    }
979
980
1.37k
    fn set_peer_fleet(&mut self, peers: Option<Vec<PeerScheduler>>, now: SystemTime) {
981
        // Peers list their workers in no particular order and may share
982
        // shapes, so sort and dedup before comparing, or an unchanged fleet
983
        // would look changed on every exchange and empty `static_verdicts`.
984
1.37k
        let peer_fleet = peers.as_ref().map(|peers| 
{1.36k
985
1.36k
            let mut keyed: Vec<_> = peers
986
1.36k
                .iter()
987
1.36k
                .flat_map(|peer| 
peer.workers28
.
iter28
())
988
1.36k
                .map(|totals| (
PropertyShape::from28
(
totals28
),
totals28
.
clone28
()))
989
1.36k
                .collect();
990
1.36k
            keyed.sort_unstable_by(|a, b| 
a.03
.
cmp3
(
&b.03
));
991
1.36k
            keyed.dedup_by(|a, b| 
a.03
==
b.03
);
992
1.36k
            keyed.into_iter().map(|(_, totals)| totals).collect()
993
1.36k
        });
994
        // Which scheduler holds a worker for which action goes by the
995
        // peers' ids as well as their shapes, so the peers are kept as read
996
        // even when the union of shapes did not move.
997
1.37k
        let mut peer_schedulers = peers.unwrap_or_default();
998
1.37k
        peer_schedulers.sort_unstable_by(|a, b| 
a.scheduler_id0
.
cmp0
(
&b.scheduler_id0
));
999
1.37k
        self.peer_schedulers = peer_schedulers;
1000
        // Freshness bookkeeping: update the warm-up /
1001
        // staleness clocks BEFORE the unchanged-shapes early return, so a
1002
        // successful exchange that happens to return the same shapes still
1003
        // refreshes the staleness clock (otherwise a steady fleet would look
1004
        // like a stalled exchange task).
1005
1.37k
        if peer_fleet.is_some() {
1006
1.36k
            self.peer_fleet_last_refresh = Some(now);
1007
            // Start the warm-up only on the unknown -> known transition.
1008
1.36k
            if self.peer_fleet.is_none() {
1009
121
                self.peer_fleet_known_since = Some(now);
1010
1.24k
            }
1011
5
        } else {
1012
5
            self.peer_fleet_known_since = None;
1013
5
            self.peer_fleet_last_refresh = None;
1014
5
        }
1015
1.37k
        if self.peer_fleet == peer_fleet {
1016
1.23k
            return;
1017
135
        }
1018
        // Unknown peers make every verdict "maybe satisfiable elsewhere",
1019
        // and that verdict is cached. Peers becoming known (or unknown
1020
        // again) changes what a verdict means even when the union of shapes
1021
        // does not move, so the cache goes, though the generation stays:
1022
        // clocks already running were right and keep their start.
1023
135
        if self.peer_fleet.is_some() != peer_fleet.is_some() {
1024
126
            self.static_verdicts.clear();
1025
126
        
}9
1026
135
        self.peer_fleet = peer_fleet;
1027
135
        self.fleet_changed();
1028
1.37k
    }
1029
1030
    /// Sets if the worker is draining or not.
1031
16
    fn set_drain_worker(&mut self, worker_id: &WorkerId, is_draining: bool) -> Result<(), Error> {
1032
16
        let worker = self
1033
16
            .workers
1034
16
            .get_mut(worker_id)
1035
16
            .err_tip(|| 
format!0
("Worker {worker_id} doesn't exist in the pool"))
?0
;
1036
16
        if worker.is_draining != is_draining {
1037
14
            record_worker_state("draining", is_draining);
1038
14
        
}2
1039
16
        worker.is_draining = is_draining;
1040
16
        if !is_draining {
1041
4
            // An operator lifting a tripped worker's drain gives it a clean
1042
4
            // slate; the tripwire judges it afresh.
1043
4
            worker.tripwire = TripwireState::Clear;
1044
4
            worker.recent_outcomes.clear();
1045
12
        }
1046
16
        if is_draining {
1047
12
            // A draining worker takes nothing, its holder included.
1048
12
            self.end_hold(worker_id, "released");
1049
12
        
}4
1050
16
        self.capacity_changed();
1051
16
        Ok(())
1052
16
    }
1053
1054
    /// Records how an attempt on `worker_id` ended, `true` for a failure,
1055
    /// and drains the worker when its recent attempts say so (the outcome
1056
    /// tripwire): its last `min_failures` attempts all failed, or at least
1057
    /// `min_failures` failures among the last `window` attempts that are at
1058
    /// least `failure_percent` of them. At most
1059
    /// `max_drained_percent` of the connected workers, and at least
1060
    /// `TRIPWIRE_DRAIN_FLOOR`, are drained this way at once; past that the
1061
    /// worker is left alone and the hold is logged once.
1062
13.1k
    fn note_worker_outcome(&mut self, worker_id: &WorkerId, failed: bool) {
1063
13.1k
        let Some(
spec32
) = self.outcome_tripwire else {
1064
13.0k
            return;
1065
        };
1066
32
        let connected = self.workers.len();
1067
32
        let drained = self
1068
32
            .workers
1069
32
            .iter()
1070
69
            .
filter32
(|(_, w)| w.tripwire == TripwireState::Tripped &&
w.is_draining14
)
1071
32
            .count();
1072
32
        let Some(worker) = self.workers.peek_mut(worker_id) else {
1073
0
            return;
1074
        };
1075
32
        if worker.is_draining {
1076
0
            return;
1077
32
        }
1078
32
        worker.recent_outcomes.push_back(failed);
1079
32
        while worker.recent_outcomes.len() > spec.window {
1080
0
            worker.recent_outcomes.pop_front();
1081
0
        }
1082
32
        let judged = worker.recent_outcomes.len();
1083
32
        let failures = worker.recent_outcomes.iter().filter(|f| **f).count();
1084
        // A run of failures trips on its own: a worker that was healthy and
1085
        // went bad carries a window of successes that would otherwise hide
1086
        // the turn until half of it had failed.
1087
32
        let in_a_row = worker
1088
32
            .recent_outcomes
1089
32
            .iter()
1090
32
            .rev()
1091
32
            .take_while(|failed| **failed)
1092
32
            .count();
1093
32
        let trips = in_a_row >= spec.min_failures
1094
21
            || (failures >= spec.min_failures && 
failures * 1001
>= spec.failure_percent * judged);
1095
32
        if !trips {
1096
20
            return;
1097
12
        }
1098
12
        let allowed = (connected * spec.max_drained_percent / 100).max(TRIPWIRE_DRAIN_FLOOR);
1099
12
        if drained >= allowed {
1100
6
            if worker.tripwire != TripwireState::Held {
1101
2
                worker.tripwire = TripwireState::Held;
1102
2
                warn!(
1103
                    %worker_id,
1104
                    failures,
1105
                    judged,
1106
                    drained,
1107
                    allowed,
1108
                    "Outcome tripwire held: as many workers are already drained as it may drain at once"
1109
                );
1110
2
                record_worker_tripwire("held");
1111
4
            }
1112
6
            return;
1113
6
        }
1114
6
        worker.tripwire = TripwireState::Tripped;
1115
6
        warn!(
1116
            %worker_id,
1117
            failures,
1118
            judged,
1119
            "Worker drained by the outcome tripwire: its recent attempts failed"
1120
        );
1121
6
        record_worker_tripwire("drained");
1122
6
        if let Err(
err0
) = self.set_drain_worker(worker_id, true) {
1123
0
            error!(%worker_id, ?err, "Failed to drain the worker the outcome tripwire judged");
1124
6
        }
1125
13.1k
    }
1126
1127
    /// Ends the hold on `worker_id`, if any, for `outcome`. The worker is
1128
    /// room the fleet did not have a moment ago, so the matcher is woken.
1129
    /// An action placed starts over with its cooldown.
1130
1.84k
    fn end_hold(&mut self, worker_id: &WorkerId, outcome: &'static str) {
1131
1.84k
        let Some(
hold10
) = self.holds.remove(worker_id) else {
1132
1.83k
            return;
1133
        };
1134
10
        self.holds_by_action.remove(&hold.action);
1135
10
        if outcome == "placed" {
1136
3
            self.hold_cooldowns.remove(&hold.action);
1137
7
        }
1138
10
        info!(?worker_id, action = ?hold.action, outcome, "Worker hold ended");
1139
10
        record_worker_hold(outcome);
1140
10
        record_held_workers(self.holds.len());
1141
10
        self.capacity_changed();
1142
1.84k
    }
1143
1144
    /// Ends the hold for `action`, if any, for `outcome`.
1145
14.3k
    fn end_hold_for_action(&mut self, action: &ActionUniqueQualifier, outcome: &'static str) {
1146
14.3k
        if let Some(
worker_id3
) = self.holds_by_action.get(action).cloned() {
1147
3
            self.end_hold(&worker_id, outcome);
1148
14.3k
        }
1149
14.3k
    }
1150
1151
    /// Records that the held action was sent to a worker (`true`), or came
1152
    /// back from one untried (`false`); see `Hold::dispatched`.
1153
15.1k
    fn note_hold_dispatched(&mut self, action: &ActionUniqueQualifier, dispatched: bool) {
1154
15.1k
        if let Some(
worker_id7
) = self.holds_by_action.get(action)
1155
7
            && let Some(hold) = self.holds.get_mut(worker_id)
1156
7
        {
1157
7
            hold.dispatched = dispatched;
1158
15.1k
        }
1159
15.1k
    }
1160
1161
    /// A queued action found no room. Once it has waited `hold_after_s`,
1162
    /// if it fits no busy worker until more than one of that worker's
1163
    /// actions finish, and it is this scheduler's turn to hold for it, a
1164
    /// worker is held for it here, under the lock the match ran under.
1165
4.64M
    fn consider_hold(
1166
4.64M
        &mut self,
1167
4.64M
        asking: Option<QueuedAction<'_>>,
1168
4.64M
        platform_properties: &PlatformProperties,
1169
4.64M
        now: SystemTime,
1170
4.64M
        full_worker_logging: bool,
1171
4.64M
    ) {
1172
4.64M
        let (Some(
spec148
), Some(
asking148
)) = (self.reservation_hold, asking) else {
1173
4.64M
            return;
1174
        };
1175
148
        let action = asking.unique_qualifier;
1176
148
        if self.holds_by_action.contains_key(action) {
1177
52
            return;
1178
96
        }
1179
96
        let waited = now
1180
96
            .duration_since(asking.insert_timestamp)
1181
96
            .unwrap_or_default();
1182
96
        if waited < Duration::from_secs(spec.hold_after_s) {
1183
34
            return;
1184
62
        }
1185
62
        if self
1186
62
            .hold_cooldowns
1187
62
            .get(action)
1188
62
            .is_some_and(|cooldown| 
now11
<
cooldown.until11
)
1189
        {
1190
6
            return;
1191
56
        }
1192
56
        let cap = if spec.max_held_workers == 0 {
1193
50
            (self.workers.len() / 10).max(1)
1194
        } else {
1195
6
            spec.max_held_workers
1196
        };
1197
56
        if self.holds.len() >= cap {
1198
11
            return;
1199
45
        }
1200
45
        if !self.only_an_idle_worker_fits(platform_properties) {
1201
25
            if full_worker_logging {
1202
13
                info!("No hold: one action finishing on some worker would make room for this one");
1203
12
            }
1204
25
            return;
1205
20
        }
1206
20
        if !self.owns_hold(action, platform_properties) {
1207
3
            if full_worker_logging {
1208
2
                info!("No hold here: a peer scheduler holds a worker for this action");
1209
1
            }
1210
3
            return;
1211
17
        }
1212
17
        self.hold_worker_for(action, platform_properties, now, spec);
1213
4.64M
    }
1214
1215
    /// Whether `platform_properties` fits no matching worker that has an
1216
    /// action running until more than one of its actions finish: on each
1217
    /// such worker some `Minimum` the action asks exceeds what the worker
1218
    /// has left plus the most any one of its running actions reserved. An
1219
    /// action one completion would make room for is only waiting its turn,
1220
    /// which the pass order gives it; a hold for it would idle slots for
1221
    /// nothing. False too when no matching worker is busy: the idle ones
1222
    /// refuse it for a reason a hold does not change.
1223
45
    fn only_an_idle_worker_fits(&self, platform_properties: &PlatformProperties) -> bool {
1224
45
        let mut any_busy = false;
1225
67
        for (_, worker) in 
self.workers.iter()45
{
1226
67
            if worker.is_draining
1227
54
                || worker.running_action_infos.is_empty()
1228
50
                || !platform_properties.is_satisfied_by(&worker.total_platform_properties, false)
1229
            {
1230
17
                continue;
1231
50
            }
1232
50
            any_busy = true;
1233
50
            if fits_after_one_finishes(platform_properties, worker) {
1234
13
                return false;
1235
37
            }
1236
        }
1237
32
        any_busy
1238
45
    }
1239
1240
    /// Whether `action`, which found no room, is this scheduler's to hold a
1241
    /// worker for. Every replica reads the same queue in the same order, so
1242
    /// left to themselves they would each drain a worker of their own for
1243
    /// the same action. The schedulers with a worker that would fit it idle
1244
    /// (this one, and the peers as the census last read them) take turns
1245
    /// by a hash of the action; while the census cannot be read, this one
1246
    /// holds.
1247
20
    fn owns_hold(
1248
20
        &self,
1249
20
        action: &ActionUniqueQualifier,
1250
20
        platform_properties: &PlatformProperties,
1251
20
    ) -> bool {
1252
20
        let fits_here = self.workers.iter().any(|(_, worker)| {
1253
20
            platform_properties.is_satisfied_by(&worker.total_platform_properties, false)
1254
20
        });
1255
20
        if !fits_here {
1256
0
            return false;
1257
20
        }
1258
20
        if self.peer_fleet.is_none() {
1259
0
            return true;
1260
20
        }
1261
20
        let mut owners: Vec<&str> = self
1262
20
            .peer_schedulers
1263
20
            .iter()
1264
20
            .filter(|peer| 
{5
1265
5
                peer.workers
1266
5
                    .iter()
1267
5
                    .any(|totals| platform_properties.is_satisfied_by(totals, false))
1268
5
            })
1269
20
            .map(|peer| 
peer.scheduler_id4
.
as_str4
())
1270
20
            .collect();
1271
20
        if owners.is_empty() {
1272
16
            return true;
1273
4
        }
1274
4
        owners.push(self.scheduler_id.as_str());
1275
4
        owners.sort_unstable();
1276
4
        owners.dedup();
1277
4
        hold_owner(action, &owners) == self.scheduler_id
1278
20
    }
1279
1280
    /// Holds a worker for `action`: of the workers neither draining nor
1281
    /// held that would fit it idle and have not declined that much while
1282
    /// idle, the one with the fewest actions running and then the most
1283
    /// memory free, as last reported or else as the ledger has it. Nothing
1284
    /// is held when no connected worker would fit the action even idle,
1285
    /// which is not a matter of waiting.
1286
17
    fn hold_worker_for(
1287
17
        &mut self,
1288
17
        action: &ActionUniqueQualifier,
1289
17
        platform_properties: &PlatformProperties,
1290
17
        now: SystemTime,
1291
17
        spec: ReservationHoldSpec,
1292
17
    ) {
1293
17
        let needed_kb = self.live_memory_veto_kb(platform_properties);
1294
17
        let memory_property = self.live_memory_veto.as_deref();
1295
32
        let 
memory_free17
= |worker: &Worker| {
1296
32
            worker
1297
32
                .last_load
1298
32
                .map(|load| load.free_memory_kb)
1299
32
                .or_else(|| 
{29
1300
29
                    match memory_property
1301
29
                        .and_then(|property| 
worker.platform_properties.properties6
.
get6
(
property6
))
1302
                    {
1303
6
                        Some(PlatformPropertyValue::Minimum(kb)) => Some(*kb),
1304
23
                        _ => None,
1305
                    }
1306
29
                })
1307
32
                .unwrap_or(0)
1308
32
        };
1309
17
        let holds = &self.holds;
1310
17
        let chosen = self
1311
17
            .workers
1312
17
            .iter()
1313
36
            .
filter17
(|(worker_id, worker)| !worker.is_draining &&
!35
holds35
.contains_key(*worker_id))
1314
35
            .
filter17
(|(_, worker)| {
1315
35
                platform_properties.is_satisfied_by(&worker.total_platform_properties, false)
1316
35
            })
1317
            // A worker that declined this much while idle is not offered
1318
            // it again until it reports that much free; a hold on it would
1319
            // wait for the worker, not for its actions.
1320
35
            .
filter17
(|(_, worker)| {
1321
3
                !matches!(
1322
35
                    (needed_kb, worker.idle_declined_kb),
1323
3
                    (Some(needed_kb), Some(declined_kb)) if needed_kb >= declined_kb
1324
                )
1325
35
            })
1326
32
            .
min_by_key17
(|(_, worker)| {
1327
32
                (
1328
32
                    worker.running_action_infos.len(),
1329
32
                    Reverse(memory_free(worker)),
1330
32
                )
1331
32
            })
1332
17
            .map(|(worker_id, _)| worker_id.clone());
1333
17
        let Some(worker_id) = chosen else {
1334
0
            return;
1335
        };
1336
17
        info!(
1337
            ?worker_id,
1338
            ?action,
1339
            max_hold_s = spec.max_hold_s,
1340
            "Holding a worker for a queued action that fits only an idle one"
1341
        );
1342
17
        self.holds.insert(
1343
17
            worker_id.clone(),
1344
17
            Hold {
1345
17
                action: action.clone(),
1346
17
                until: now.checked_add(hold_duration(spec)).unwrap_or(now),
1347
17
                seen_in: self.pass_generation,
1348
17
                dispatched: false,
1349
17
            },
1350
        );
1351
17
        self.holds_by_action.insert(action.clone(), worker_id);
1352
17
        record_worker_hold("held");
1353
17
        record_held_workers(self.holds.len());
1354
17
    }
1355
1356
    /// A matching pass begins; returns its generation, which the holds it
1357
    /// meets record and `end_pass_holds` compares against.
1358
43.4k
    const fn begin_pass_holds(&mut self) -> u64 {
1359
43.4k
        self.pass_generation += 1;
1360
43.4k
        self.pass_generation
1361
43.4k
    }
1362
1363
    /// Ends the holds past their time, whose action is then not held for
1364
    /// again for as long (twice as long for each such expiry in a row on a
1365
    /// worker that was idle, up to a bound: nothing kept the action off it
1366
    /// but the action itself), and the ones no pass since `pass` began has
1367
    /// met, whose action is gone. A hold whose action is in flight to a
1368
    /// worker is not met by passes either and waits for the worker to
1369
    /// answer. Judged by generation rather than a flag so that two passes
1370
    /// in flight at once (a test entry point beside the matcher's own loop)
1371
    /// cannot clear each other's marks. A cooldown no pass has met since is
1372
    /// dropped the same way.
1373
43.4k
    fn end_pass_holds(&mut self, pass: u64, now: SystemTime) {
1374
43.4k
        let ended: Vec<(WorkerId, &'static str)> = self
1375
43.4k
            .holds
1376
43.4k
            .iter()
1377
43.4k
            .filter_map(|(worker_id, hold)| 
{88
1378
88
                if hold.until <= now {
1379
3
                    Some((worker_id.clone(), "expired"))
1380
85
                } else if hold.seen_in < pass && 
!hold.dispatched14
{
1381
1
                    Some((worker_id.clone(), "released"))
1382
                } else {
1383
84
                    None
1384
                }
1385
88
            })
1386
43.4k
            .collect();
1387
43.4k
        for (
worker_id4
,
outcome4
) in ended {
1388
4
            if outcome == "expired"
1389
3
                && let Some(spec) = self.reservation_hold
1390
3
                && let Some(hold) = self.holds.get(&worker_id)
1391
            {
1392
3
                let idle = self
1393
3
                    .workers
1394
3
                    .peek(&worker_id)
1395
3
                    .is_some_and(|worker| worker.running_action_infos.is_empty());
1396
3
                let cooldown =
1397
3
                    self.hold_cooldowns
1398
3
                        .entry(hold.action.clone())
1399
3
                        .or_insert(HoldCooldown {
1400
3
                            until: now,
1401
3
                            idle_expiries: 0,
1402
3
                            seen_in: pass,
1403
3
                        });
1404
3
                if idle {
1405
1
                    cooldown.idle_expiries =
1406
1
                        (cooldown.idle_expiries + 1).min(MAX_IDLE_EXPIRY_DOUBLINGS);
1407
2
                }
1408
3
                cooldown.until = now
1409
3
                    .checked_add(hold_duration(spec) * (1 << cooldown.idle_expiries))
1410
3
                    .unwrap_or(now);
1411
1
            }
1412
4
            self.end_hold(&worker_id, outcome);
1413
        }
1414
43.4k
        self.hold_cooldowns
1415
43.4k
            .retain(|_, cooldown| 
cooldown.seen_in14
>=
pass14
);
1416
43.4k
    }
1417
1418
    /// Marks the hold and the cooldown for `action`, if any, as met by the
1419
    /// pass under way.
1420
4.86M
    fn note_held_action_seen(&mut self, action: &ActionUniqueQualifier) {
1421
4.86M
        if let Some(
worker_id57
) = self.holds_by_action.get(action)
1422
57
            && let Some(hold) = self.holds.get_mut(worker_id)
1423
57
        {
1424
57
            hold.seen_in = self.pass_generation;
1425
4.86M
        }
1426
4.86M
        if let Some(
cooldown11
) = self.hold_cooldowns.get_mut(action) {
1427
11
            cooldown.seen_in = self.pass_generation;
1428
4.86M
        }
1429
4.86M
    }
1430
1431
    /// Whether peer-absence can be trusted to fail an action right now — a
1432
    /// shared census must be known, warm and fresh; a non-shared db is trusted
1433
    /// as soon as it is known. See the free `peer_census_trusted`.
1434
192
    fn peer_census_trusted(&self, now: SystemTime) -> bool {
1435
192
        peer_census_trusted(
1436
192
            self.shared,
1437
192
            self.peer_fleet.is_some(),
1438
192
            self.peer_fleet_known_since,
1439
192
            self.peer_fleet_last_refresh,
1440
192
            self.record_ttl,
1441
192
            now,
1442
        )
1443
192
    }
1444
1445
    /// Works out whether any of the `candidates` the capability index picked
1446
    /// could run an action with these properties when idle, and if not, why.
1447
374
    fn static_verdict(
1448
374
        &self,
1449
374
        platform_properties: &PlatformProperties,
1450
374
        candidates: &HashSet<WorkerId>,
1451
374
        full_worker_logging: bool,
1452
374
    ) -> Option<Arc<UnsatisfiableReason>> {
1453
        // The index only checks that Minimum keys are present, so the values
1454
        // are checked here against what each candidate registered with.
1455
374
        let satisfiable = candidates.iter().any(|worker_id| 
{368
1456
368
            self.workers.peek(worker_id).is_some_and(|w| {
1457
368
                platform_properties
1458
368
                    .is_satisfied_by(&w.total_platform_properties, full_worker_logging)
1459
368
            })
1460
368
        });
1461
374
        if satisfiable {
1462
274
            return None;
1463
100
        }
1464
        // A peer's worker counts too: the action would run there once that
1465
        // worker has room, and this scheduler cannot see how busy it is.
1466
        // While the peers are unknown, any of them might have one.
1467
100
        let 
peer_fleet96
= self.peer_fleet.as_deref()
?4
;
1468
96
        if peer_fleet
1469
96
            .iter()
1470
96
            .any(|totals| 
platform_properties3
.
is_satisfied_by3
(
totals3
, false))
1471
        {
1472
3
            return None;
1473
93
        }
1474
93
        let fleet: Vec<_> = self
1475
93
            .workers
1476
93
            .iter()
1477
93
            .map(|(_, w)| &w.total_platform_properties)
1478
93
            .chain(peer_fleet.iter())
1479
93
            .collect();
1480
93
        Some(Arc::new(explain_unsatisfiable(platform_properties, &fleet)))
1481
374
    }
1482
1483
    /// `static_verdict`, cached per property shape until the fleet changes.
1484
4.64M
    fn cached_static_verdict(
1485
4.64M
        &mut self,
1486
4.64M
        platform_properties: &PlatformProperties,
1487
4.64M
        candidates: Option<&HashSet<WorkerId>>,
1488
4.64M
        full_worker_logging: bool,
1489
4.64M
    ) -> Option<Arc<UnsatisfiableReason>> {
1490
4.64M
        let shape = PropertyShape::from(platform_properties);
1491
        // A cached verdict skips the per-property logging, so recompute when
1492
        // that logging was asked for.
1493
4.64M
        if !full_worker_logging && let Some(
verdict4.64M
) =
self.static_verdicts4.64M
.get(&shape) {
1494
4.64M
            return verdict.clone();
1495
374
        }
1496
374
        let verdict = if let Some(
candidates230
) = candidates {
1497
230
            self.static_verdict(platform_properties, candidates, full_worker_logging)
1498
        } else {
1499
144
            let candidates = self
1500
144
                .capability_index
1501
144
                .find_matching_workers(platform_properties, full_worker_logging);
1502
144
            self.static_verdict(platform_properties, &candidates, full_worker_logging)
1503
        };
1504
374
        if self.static_verdicts.len() >= MAX_STATIC_VERDICTS {
1505
0
            self.static_verdicts.clear();
1506
374
        }
1507
374
        self.static_verdicts.insert(shape, verdict.clone());
1508
374
        verdict
1509
4.64M
    }
1510
1511
    /// The memory the action reserves under the `live_memory_veto` property,
1512
    /// if the veto is on and the action declares it.
1513
29.4k
    fn live_memory_veto_kb(&self, platform_properties: &PlatformProperties) -> Option<u64> {
1514
29.4k
        let 
property13.7k
= self.live_memory_veto.as_deref()
?15.7k
;
1515
13.7k
        match platform_properties.properties.get(property) {
1516
13.7k
            Some(PlatformPropertyValue::Minimum(kb)) => Some(*kb),
1517
0
            _ => None,
1518
        }
1519
29.4k
    }
1520
1521
    /// Finds an idle worker among `candidates` that can run the action now.
1522
29.3k
    fn find_available_worker(
1523
29.3k
        &self,
1524
29.3k
        platform_properties: &PlatformProperties,
1525
29.3k
        candidates: &HashSet<WorkerId>,
1526
29.3k
        full_worker_logging: bool,
1527
29.3k
        asking: Option<&ActionUniqueQualifier>,
1528
29.3k
        avoidance: Avoidance<'_>,
1529
29.3k
    ) -> Option<WorkerId> {
1530
        // The workers this action failed or timed out on, and the others on
1531
        // their nodes, are offered it last: only when no other worker has
1532
        // taken it for a while (`fallback_ok`). The nodes come from the
1533
        // record, which every replica reads, and from the workers this
1534
        // replica knows.
1535
29.3k
        if !avoidance.is_empty() {
1536
566
            let avoid = avoidance.workers;
1537
566
            let shunned: HashSet<&str> = avoidance
1538
566
                .nodes
1539
566
                .iter()
1540
566
                .map(String::as_str)
1541
566
                .chain(
1542
566
                    avoid
1543
566
                        .iter()
1544
566
                        .filter_map(|id| self.workers.peek(id))
1545
566
                        .filter_map(node_name_of),
1546
                )
1547
566
                .collect();
1548
566
            let others: HashSet<WorkerId> = candidates
1549
566
                .iter()
1550
1.68k
                .
filter566
(|id| !avoid.contains(id))
1551
1.12k
                .
filter566
(|id| {
1552
1.12k
                    shunned.is_empty()
1553
6
                        || self
1554
6
                            .workers
1555
6
                            .peek(id)
1556
6
                            .and_then(node_name_of)
1557
6
                            .is_none_or(|node| !shunned.contains(node))
1558
1.12k
                })
1559
566
                .cloned()
1560
566
                .collect();
1561
566
            if let Some(
worker_id254
) = self.pick_available_worker(
1562
566
                platform_properties,
1563
566
                &others,
1564
566
                full_worker_logging,
1565
566
                asking,
1566
566
            ) {
1567
254
                return Some(worker_id);
1568
312
            }
1569
312
            if !avoidance.fallback_ok {
1570
292
                if full_worker_logging {
1571
1
                    info!(
1572
                        ?avoid,
1573
                        "Only workers this action failed on, or their nodes, are free here; leaving it for a peer"
1574
                    );
1575
291
                }
1576
292
                return None;
1577
20
            }
1578
20
            if full_worker_logging {
1579
0
                info!(
1580
                    ?avoid,
1581
                    "Only workers this action failed on, or their nodes, are free; offering it to one of them"
1582
                );
1583
20
            }
1584
28.8k
        }
1585
28.8k
        self.pick_available_worker(platform_properties, candidates, full_worker_logging, asking)
1586
29.3k
    }
1587
1588
29.4k
    fn pick_available_worker(
1589
29.4k
        &self,
1590
29.4k
        platform_properties: &PlatformProperties,
1591
29.4k
        candidates: &HashSet<WorkerId>,
1592
29.4k
        full_worker_logging: bool,
1593
29.4k
        asking: Option<&ActionUniqueQualifier>,
1594
29.4k
    ) -> Option<WorkerId> {
1595
        // Check function for availability AND dynamic Minimum property verification.
1596
        // The index only does presence checks for Minimum properties since their
1597
        // values change dynamically as jobs are assigned to workers.
1598
29.4k
        let needed_kb = self.live_memory_veto_kb(platform_properties);
1599
128k
        let 
worker_matches29.4k
= |(worker_id, w): &(&WorkerId, &Worker)| -> bool {
1600
128k
            if !w.can_accept_work() {
1601
99.4k
                if full_worker_logging {
1602
19
                    info!(
1603
                        "Worker {worker_id} cannot accept work: is_paused={}, is_draining={}, inflight={}/{}",
1604
                        w.is_paused,
1605
                        w.is_draining,
1606
19
                        w.running_action_infos.len(),
1607
                        w.max_inflight_tasks
1608
                    );
1609
99.4k
                }
1610
99.4k
                return false;
1611
29.1k
            }
1612
1613
            // A held worker takes nothing but the action it is held for.
1614
29.1k
            if let Some(
hold73
) = self.holds.get(*worker_id)
1615
73
                && asking != Some(&hold.action)
1616
            {
1617
19
                if full_worker_logging {
1618
3
                    info!("Worker {worker_id} is held for another action");
1619
16
                }
1620
19
                return false;
1621
29.1k
            }
1622
1623
29.1k
            if let (Some(
needed_kb6
), Some(
declined_kb6
)) = (needed_kb, w.idle_declined_kb)
1624
6
                && needed_kb >= declined_kb
1625
            {
1626
5
                if full_worker_logging {
1627
0
                    info!(
1628
                        "Worker {worker_id} skipped for this action: it declined {declined_kb} KiB while idle, the action asks {needed_kb} KiB"
1629
                    );
1630
5
                }
1631
5
                return false;
1632
29.1k
            }
1633
1634
            // The ledger only knows what actions declared; the worker's own
1635
            // report of what it has left catches the ones that declared too
1636
            // little. A worker that reports nothing is never vetoed.
1637
            // An action that asks for the worker's whole advertised memory
1638
            // (the last escalation step) is not vetoed: a worker seldom
1639
            // reports that much free, since its own process memory and
1640
            // active page cache still count as used, so the veto could
1641
            // hold it back indefinitely, and the ledger already keeps it
1642
            // alone there. Nor is a worker that admits when idle and holds
1643
            // nothing: it accepts whatever it reads free, so the veto would
1644
            // only keep from it the actions it is idle for.
1645
13.6k
            if let (Some(property), Some(needed_kb), Some(load)) =
1646
29.1k
                (self.live_memory_veto.as_deref(), needed_kb, w.last_load)
1647
13.6k
                && !(w.admits_when_idle && 
w.running_action_infos1
.
is_empty1
())
1648
13.6k
                && needed_kb > load.free_memory_kb
1649
13.3k
                && matches!(
1650
13.3k
                    w.total_platform_properties.properties.get(property),
1651
13.3k
                    Some(PlatformPropertyValue::Minimum(advertised_kb)) if needed_kb < *advertised_kb
1652
                )
1653
            {
1654
13.3k
                if full_worker_logging {
1655
4
                    info!(
1656
                        "Worker {worker_id} vetoed for this action: it reports {} KiB free, the action asks {needed_kb} KiB ({property})",
1657
                        load.free_memory_kb
1658
                    );
1659
13.3k
                }
1660
13.3k
                return false;
1661
15.7k
            }
1662
1663
            // Verify Minimum properties at runtime (their values are dynamic)
1664
15.7k
            platform_properties.is_satisfied_by(&w.platform_properties, full_worker_logging)
1665
128k
        };
1666
1667
        // Now check constraints on filtered candidates.
1668
        // Iterate in LRU order based on allocation strategy.
1669
29.4k
        let workers_iter = self.workers.iter();
1670
1671
29.4k
        match self.allocation_strategy {
1672
            // Use rfind to get the least recently used that satisfies the properties.
1673
29.4k
            WorkerAllocationStrategy::LeastRecentlyUsed => workers_iter
1674
29.4k
                .rev()
1675
129k
                .
filter29.4k
(|(worker_id, _)| candidates.contains(worker_id))
1676
29.4k
                .find(&worker_matches)
1677
29.4k
                .map(|(_, w)| 
w.id15.4k
.
clone15.4k
()),
1678
1679
            // Use find to get the most recently used that satisfies the properties.
1680
0
            WorkerAllocationStrategy::MostRecentlyUsed => workers_iter
1681
0
                .filter(|(worker_id, _)| candidates.contains(worker_id))
1682
0
                .find(&worker_matches)
1683
0
                .map(|(_, w)| w.id.clone()),
1684
1685
            // Fewest running actions wins; the scan runs from the least
1686
            // recently used end so `min_by_key` keeps that one on a tie.
1687
3
            WorkerAllocationStrategy::LeastLoaded => workers_iter
1688
3
                .rev()
1689
4
                .
filter3
(|(worker_id, _)| candidates.contains(worker_id))
1690
3
                .filter(&worker_matches)
1691
4
                .
min_by_key3
(|(_, w)| w.running_action_infos.len())
1692
3
                .map(|(_, w)| w.id.clone()),
1693
1694
4
            WorkerAllocationStrategy::BestFit => workers_iter
1695
4
                .rev()
1696
8
                .
filter4
(|(worker_id, _)| candidates.contains(worker_id))
1697
4
                .filter(&worker_matches)
1698
7
                .
min_by_key4
(|(_, w)| {
1699
7
                    (
1700
7
                        // More matching priority properties first.
1701
7
                        usize::MAX - priority_matches(platform_properties, w),
1702
7
                        fit_leftover_permille(platform_properties, w),
1703
7
                        w.running_action_infos.len(),
1704
7
                    )
1705
7
                })
1706
4
                .map(|(_, w)| w.id.clone()),
1707
        }
1708
29.4k
    }
1709
1710
4.86M
    fn inner_find_worker_for_action(
1711
4.86M
        &mut self,
1712
4.86M
        platform_properties: &PlatformProperties,
1713
4.86M
        full_worker_logging: bool,
1714
4.86M
        now: SystemTime,
1715
4.86M
        asking: Option<QueuedAction<'_>>,
1716
4.86M
    ) -> MatchOutcome {
1717
4.86M
        let outcome = self.match_worker_for_action(
1718
4.86M
            platform_properties,
1719
4.86M
            full_worker_logging,
1720
4.86M
            now,
1721
4.86M
            asking.map(|action| action.unique_qualifier),
1722
4.86M
            asking.map_or(Avoidance::NONE, |action| Avoidance {
1723
4.86M
                workers: action.avoid,
1724
4.86M
                nodes: action.avoid_nodes,
1725
4.86M
                fallback_ok: now
1726
4.86M
                    .duration_since(action.queued_since)
1727
4.86M
                    .is_ok_and(|waited| waited >= AVOID_FALLBACK_AFTER),
1728
4.86M
            }),
1729
        );
1730
4.86M
        if 
matches!222k
(outcome, MatchOutcome::WaitingForCapacity) {
1731
4.64M
            self.consider_hold(asking, platform_properties, now, full_worker_logging);
1732
4.64M
        
}222k
1733
4.86M
        outcome
1734
4.86M
    }
1735
1736
    /// The match itself; `inner_find_worker_for_action` adds the hold.
1737
4.86M
    fn match_worker_for_action(
1738
4.86M
        &mut self,
1739
4.86M
        platform_properties: &PlatformProperties,
1740
4.86M
        full_worker_logging: bool,
1741
4.86M
        now: SystemTime,
1742
4.86M
        asking: Option<&ActionUniqueQualifier>,
1743
4.86M
        avoidance: Avoidance<'_>,
1744
4.86M
    ) -> MatchOutcome {
1745
4.86M
        if let Some(
action4.86M
) = asking {
1746
4.86M
            self.note_held_action_seen(action);
1747
4.86M
        
}3
1748
4.86M
        if self.workers.is_empty() {
1749
206k
            if full_worker_logging {
1750
3.97k
                info!("No workers available to match!");
1751
202k
            }
1752
206k
            return MatchOutcome::NoWorkersConnected;
1753
4.65M
        }
1754
1755
        // Do a fast check to see if any workers are available at all for work allocation
1756
201M
        let 
candidates4.64M
= if
self.workers.iter()4.65M
.
any4.65M
(|(_, w)| w.can_accept_work()) {
1757
            // Use capability index to get candidate workers that match STATIC properties
1758
            // (Exact, Unknown) and have the required property keys (Priority, Minimum).
1759
            // This reduces complexity from O(W × P) to O(P × log(W)) for exact properties.
1760
29.3k
            let candidates = self
1761
29.3k
                .capability_index
1762
29.3k
                .find_matching_workers(platform_properties, full_worker_logging);
1763
29.3k
            if let Some(
worker_id15.4k
) = self.find_available_worker(
1764
29.3k
                platform_properties,
1765
29.3k
                &candidates,
1766
29.3k
                full_worker_logging,
1767
29.3k
                asking,
1768
29.3k
                avoidance,
1769
29.3k
            ) {
1770
15.4k
                return MatchOutcome::Matched(worker_id);
1771
13.9k
            }
1772
13.9k
            Some(candidates)
1773
        } else {
1774
4.62M
            if full_worker_logging {
1775
17
                info!("All workers are fully allocated");
1776
4.62M
            }
1777
4.62M
            None
1778
        };
1779
1780
        // Nothing can take the action now. Only then is it worth working out
1781
        // whether anything ever could, so a match pays nothing for this.
1782
4.64M
        if let Some(
reason185
) = self.cached_static_verdict(
1783
4.64M
            platform_properties,
1784
4.64M
            candidates.as_ref(),
1785
4.64M
            full_worker_logging,
1786
4.64M
        ) {
1787
            // The intrinsic verdict (nobody could run it) is cached by shape;
1788
            // the census freshness check is applied live here, OUTSIDE the
1789
            // cache, so a verdict computed while the census was trusted can
1790
            // never outlive a staleness transition (nor a warm-up one). On a
1791
            // shared db, trust peer-absence to fail only once the census is
1792
            // warm and fresh; otherwise a peer we cannot fully account for
1793
            // might run it, so wait rather than fail.
1794
185
            if !self.peer_census_trusted(now) {
1795
8
                if full_worker_logging {
1796
2
                    info!("No idle worker matched; peer census not yet trusted, waiting");
1797
6
                }
1798
8
                return MatchOutcome::WaitingForCapacity;
1799
177
            }
1800
177
            if full_worker_logging {
1801
69
                info!(%reason, "No connected worker can ever run this action");
1802
108
            }
1803
177
            return MatchOutcome::Unsatisfiable(reason);
1804
4.64M
        }
1805
4.64M
        if full_worker_logging && 
candidates53
.
is_some53
() {
1806
38
            warn!("No workers matched!");
1807
4.64M
        }
1808
4.64M
        MatchOutcome::WaitingForCapacity
1809
4.86M
    }
1810
1811
    /// The largest memory reservation any connected worker could hold.
1812
    /// The largest memory any connected worker advertises under `property`,
1813
    /// and that worker's whole CPU under `cpu_property` (`None` when the
1814
    /// property is empty or the worker does not advertise it). Reserving
1815
    /// both is what runs an action alone there.
1816
50
    fn fleet_largest_worker(&self, property: &str, cpu_property: &str) -> (u64, Option<u64>) {
1817
100
        let 
minimum50
= |worker: &Worker, name: &str| match worker
1818
100
            .total_platform_properties
1819
100
            .properties
1820
100
            .get(name)
1821
        {
1822
50
            Some(PlatformPropertyValue::Minimum(value)) => Some(*value),
1823
50
            _ => None,
1824
100
        };
1825
        // A draining worker is leaving: escalating to it would strand the
1826
        // action at a size the remaining fleet cannot serve.
1827
50
        self.workers
1828
50
            .iter()
1829
53
            .
filter50
(|(_, worker)| !worker.is_draining)
1830
50
            .filter_map(|(_, worker)| {
1831
50
                minimum(worker, property).map(|memory_kb| {
1832
50
                    let cpu = if cpu_property.is_empty() {
1833
0
                        None
1834
                    } else {
1835
50
                        minimum(worker, cpu_property)
1836
                    };
1837
50
                    (memory_kb, cpu)
1838
50
                })
1839
50
            })
1840
50
            .max_by_key(|(memory_kb, _)| *memory_kb)
1841
50
            .unwrap_or((0, None))
1842
50
    }
1843
1844
    /// The reservation a lost worker's action would be requeued with, and
1845
    /// whether the worker's own report showed it over its reservation
1846
    /// (RFC-0018). The state manager decides whether to apply it. `None`
1847
    /// without a policy, for an operation the scheduler had asked the worker
1848
    /// to kill, and for one with nowhere left to grow.
1849
25
    fn loss_escalation(
1850
25
        &self,
1851
25
        worker_id: &WorkerId,
1852
25
        pending: &PendingActionInfoData,
1853
25
        fleet: (u64, Option<u64>),
1854
25
    ) -> Option<LossEscalation> {
1855
25
        let policy = self.memory_escalation.as_ref()
?0
;
1856
25
        if pending.kill_requested_at.is_some() {
1857
0
            return None;
1858
25
        }
1859
25
        let properties = &pending.action_info.platform_properties;
1860
25
        let reserved_kb = reservation_of(properties, &policy.property);
1861
25
        let peak_kb = pending.reported_peak_memory_kb;
1862
        // Any amount over its reservation counts, not only past the worker's
1863
        // kill headroom: headroom spares an action a kill, but an action
1864
        // using more than it asked for is under-sized whatever the margin,
1865
        // and a larger reservation is the cheaper mistake than another
1866
        // lost worker and its co-tenants.
1867
25
        let sampled_over = reserved_kb > 0 && peak_kb > reserved_kb;
1868
25
        let (
value22
,
cpu22
) = match next_reservation(
1869
25
            policy,
1870
25
            properties,
1871
25
            reserved_kb,
1872
25
            reserved_kb.max(peak_kb),
1873
25
            fleet,
1874
25
        ) {
1875
22
            NextReservation::Step { value, cpu, .. } => (value, cpu),
1876
3
            skipped => {
1877
                // Nothing to grow from (no reservation and no report),
1878
                // nowhere to grow (the whole largest worker), or no fleet
1879
                // to grow into: the loss requeues the action as it was.
1880
3
                debug!(
1881
                    ?worker_id,
1882
                    property = %policy.property,
1883
                    reserved_kb,
1884
                    peak_kb,
1885
                    ?skipped,
1886
                    "Lost worker's action has no larger reservation to take"
1887
                );
1888
3
                return None;
1889
            }
1890
        };
1891
22
        Some(LossEscalation {
1892
22
            escalation: Escalation {
1893
22
                property: policy.property.clone(),
1894
22
                value,
1895
22
                reason: make_err!(
1896
22
                    Code::Unavailable,
1897
22
                    "Worker {worker_id} was lost while running this action with {reserved_kb} KiB reserved (highest reported {peak_kb} KiB)"
1898
22
                ),
1899
22
                cpu,
1900
22
            },
1901
22
            sampled_over,
1902
22
        })
1903
25
    }
1904
1905
    /// Keeps the highest memory a keepalive reported for each operation the
1906
    /// worker holds; an operation it does not hold is ignored.
1907
21
    fn operation_memory_reported(&mut self, worker_id: &WorkerId, peaks: Vec<(OperationId, u64)>) {
1908
21
        let Some(worker) = self.workers.peek_mut(worker_id) else {
1909
0
            return;
1910
        };
1911
21
        for (operation_id, peak_kb) in peaks {
1912
21
            if let Some(pending) = worker.running_action_infos.get_mut(&operation_id) {
1913
21
                pending.reported_peak_memory_kb = pending.reported_peak_memory_kb.max(peak_kb);
1914
21
            
}0
1915
        }
1916
21
    }
1917
1918
    /// Turns a result that the worker's last usage report says was a memory
1919
    /// kill into a requeue with a larger reservation, when escalation is
1920
    /// configured and there is room to grow. Returns the update to apply
1921
    /// and whether it was escalated.
1922
25.4k
    fn maybe_escalate(
1923
25.4k
        &self,
1924
25.4k
        worker_id: &WorkerId,
1925
25.4k
        operation_id: &OperationId,
1926
25.4k
        update: UpdateOperationType,
1927
25.4k
    ) -> (UpdateOperationType, bool) {
1928
25.4k
        let Some(
policy19
) = &self.memory_escalation else {
1929
25.4k
            return (update, false);
1930
        };
1931
19
        let UpdateOperationType::UpdateWithActionStage(ActionStage::Completed(result)) = &update
1932
        else {
1933
0
            return (update, false);
1934
        };
1935
19
        let Some(pending) = self
1936
19
            .workers
1937
19
            .peek(worker_id)
1938
19
            .and_then(|worker| worker.running_action_infos.get(operation_id))
1939
        else {
1940
0
            return (update, false);
1941
        };
1942
19
        let Some(
usage17
) = pending.last_usage.as_ref() else {
1943
2
            return (update, false);
1944
        };
1945
17
        if usage.outcome != ResourceOutcome::KilledMemory as i32 {
1946
0
            return (update, false);
1947
17
        }
1948
        // What it ran under: the worker's echo, else what the scheduler sent.
1949
17
        let reserved_kb = usage
1950
17
            .reserved
1951
17
            .map(|r| r.memory_kb)
1952
17
            .filter(|kb| *kb > 0)
1953
17
            .unwrap_or_else(|| 
{0
1954
0
                reservation_of(&pending.action_info.platform_properties, &policy.property)
1955
0
            });
1956
        // Grow from what the action was seen to use, not only from what it
1957
        // asked for: a kill sampled well past its reservation would
1958
        // otherwise be given a size it was just observed to exceed.
1959
17
        let base_kb = reserved_kb.max(usage.peak_memory_kb);
1960
17
        let fleet = self.fleet_largest_worker(&policy.property, &policy.cpu_property);
1961
17
        let (
value15
,
cpu15
,
ceiling_kb15
) = match next_reservation(
1962
17
            policy,
1963
17
            &pending.action_info.platform_properties,
1964
17
            reserved_kb,
1965
17
            base_kb,
1966
17
            fleet,
1967
17
        ) {
1968
0
            NextReservation::NoCeiling => return (update, false),
1969
2
            NextReservation::AlreadyWhole { ceiling_kb } => {
1970
                // A kill at the whole of the largest worker is the end: no
1971
                // worker in the fleet can run the action, and the client
1972
                // hears exactly that.
1973
2
                warn!(
1974
                    ?worker_id,
1975
                    ?operation_id,
1976
                    reserved_kb,
1977
                    ceiling_kb,
1978
                    "Action killed for memory with the largest worker reserved whole; no worker in the fleet can run it"
1979
                );
1980
2
                let mut failed = result.clone();
1981
2
                let no_worker = make_err!(
1982
2
                    Code::FailedPrecondition,
1983
                    "Action was killed for memory at {reserved_kb} KiB with the largest worker in the fleet ({ceiling_kb} KiB) reserved for it alone; no worker can run it. It needs a bigger worker or less memory"
1984
                );
1985
2
                failed.error = Some(match result.error.clone() {
1986
2
                    Some(worker_error) => no_worker.merge(worker_error),
1987
0
                    None => no_worker,
1988
                });
1989
2
                return (
1990
2
                    UpdateOperationType::UpdateWithActionStage(ActionStage::Completed(failed)),
1991
2
                    false,
1992
2
                );
1993
            }
1994
            NextReservation::NoBase => {
1995
                // Nothing to grow from: no reservation and an unsampled kill.
1996
                // Scaling zero would hand out the smallest steps the ladder or
1997
                // the percent allow and burn the budget on them.
1998
0
                warn!(
1999
                    ?worker_id,
2000
                    ?operation_id,
2001
                    "Action killed for memory with no reservation and no sampled peak; not escalating"
2002
                );
2003
0
                return (update, false);
2004
            }
2005
            NextReservation::Step {
2006
15
                value,
2007
15
                cpu,
2008
15
                ceiling_kb,
2009
15
            } => (value, cpu, ceiling_kb),
2010
        };
2011
15
        let reason = result.error.clone().unwrap_or_else(|| 
{0
2012
0
            make_err!(
2013
0
                Code::FailedPrecondition,
2014
                "Action was killed for memory at {} KiB",
2015
                usage.peak_memory_kb
2016
            )
2017
0
        });
2018
15
        warn!(
2019
            ?worker_id,
2020
            ?operation_id,
2021
            reserved_kb,
2022
            peak_memory_kb = usage.peak_memory_kb,
2023
            escalated_kb = value,
2024
            ceiling_kb,
2025
            property = %policy.property,
2026
            "Action killed for memory; requeuing with a larger reservation"
2027
        );
2028
15
        (
2029
15
            UpdateOperationType::UpdateWithEscalation(Escalation {
2030
15
                property: policy.property.clone(),
2031
15
                value,
2032
15
                reason,
2033
15
                cpu,
2034
15
            }),
2035
15
            true,
2036
15
        )
2037
25.4k
    }
2038
2039
25.4k
    async fn update_action(
2040
25.4k
        &mut self,
2041
25.4k
        worker_id: &WorkerId,
2042
25.4k
        operation_id: &OperationId,
2043
25.4k
        update: UpdateOperationType,
2044
25.4k
    ) -> Result<(), Error> {
2045
        // Any word from the worker about an action it was sent, other than
2046
        // sending it back, is the worker taking it: a hold for it ends as
2047
        // placed. A decline or a disconnect requeues the action, and its
2048
        // hold waits for it in the queue again.
2049
25.4k
        let held_for = self
2050
25.4k
            .workers
2051
25.4k
            .peek(worker_id)
2052
25.4k
            .and_then(|worker| 
worker.running_action_infos25.4k
.
get25.4k
(
operation_id25.4k
))
2053
25.4k
            .map(|pending| 
pending.action_info.inner.unique_qualifier25.4k
.
clone25.4k
())
2054
25.4k
            .filter(|action| 
self.holds_by_action25.4k
.
contains_key25.4k
(
action25.4k
));
2055
25.4k
        if let Some(
action2
) = held_for {
2056
0
            if matches!(
2057
2
                update,
2058
                UpdateOperationType::UpdateWithDecline(_)
2059
                    | UpdateOperationType::UpdateWithDisconnect(_)
2060
2
            ) {
2061
2
                self.note_hold_dispatched(&action, false);
2062
2
            } else {
2063
0
                self.end_hold_for_action(&action, "placed");
2064
0
            }
2065
25.4k
        }
2066
2067
25.4k
        let 
worker25.4k
= self.workers.get_mut(worker_id).err_tip(||
{2
2068
2
            format!("Worker {worker_id} does not exist in SimpleScheduler::update_action")
2069
2
        })?;
2070
        // The node the worker says it is on, for the record to remember
2071
        // against a failure here.
2072
25.4k
        let worker_node = node_name_of(worker).map(str::to_owned);
2073
2074
        // Ensure the worker is supposed to be running the operation. A
2075
        // result for something this worker no longer holds is stale, not
2076
        // rogue: the operation was requeued after a timeout or a kill and
2077
        // the worker finished it anyway. Refuse it and keep the worker;
2078
        // evicting it here requeued every other action it held for one
2079
        // late message.
2080
25.4k
        if !worker.running_action_infos.contains_key(operation_id) {
2081
6
            warn!(
2082
                %operation_id,
2083
                ?worker_id,
2084
2
                running_actions = worker.running_action_infos.len(),
2085
                "Dropping update for an operation the worker is not running"
2086
            );
2087
            // The one `FailedPrecondition` this returns: the update is
2088
            // settled, already applied or for an operation that moved on.
2089
6
            return Err(make_err!(
2090
6
                Code::FailedPrecondition,
2091
6
                "Operation {operation_id} should not be running on worker {worker_id} in SimpleScheduler::update_action"
2092
6
            ));
2093
25.4k
        }
2094
2095
        // How the attempt ended, for the outcome tripwire: a failure the
2096
        // worker is answerable for (its command or input fetch timed out,
2097
        // or it errored), a success (a result, whatever the exit code), or
2098
        // nothing to judge (backpressure, a store down, a disconnect, a
2099
        // memory escalation, a decline, a kill the scheduler asked for).
2100
25.4k
        let outcome = if worker.is_kill_requested(operation_id) {
2101
1
            None
2102
        } else {
2103
12.8k
            match &update {
2104
12.8k
                UpdateOperationType::UpdateWithActionStage(ActionStage::Completed(result)) => Some(
2105
12.8k
                    result
2106
12.8k
                        .error
2107
12.8k
                        .as_ref()
2108
12.8k
                        .is_some_and(|err| 
err.code32
==
Code::DeadlineExceeded32
),
2109
                ),
2110
275
                UpdateOperationType::UpdateWithError(err)
2111
275
                    if err.code != Code::ResourceExhausted
2112
274
                        && !err.message_string().contains(STORE_UNREACHABLE_ERROR_TIP
)271
=>
2113
                {
2114
271
                    Some(true)
2115
                }
2116
12.3k
                _ => None,
2117
            }
2118
        };
2119
2120
25.4k
        let (
is_finished13.1k
,
due_to_backpressure13.1k
) = match &update {
2121
12.8k
            UpdateOperationType::UpdateWithActionStage(action_stage) => {
2122
12.8k
                (action_stage.is_finished(), false)
2123
            }
2124
0
            UpdateOperationType::KeepAlive => (false, false),
2125
276
            UpdateOperationType::UpdateWithError(err) => {
2126
276
                (true, err.code == Code::ResourceExhausted)
2127
            }
2128
            // A decline pauses like backpressure: the worker said it has no
2129
            // room, so it gets nothing more until it says otherwise.
2130
11
            UpdateOperationType::UpdateWithDecline(_) => (true, true),
2131
            UpdateOperationType::UpdateWithDisconnect(_)
2132
17
            | UpdateOperationType::UpdateWithEscalation(_) => (true, false),
2133
            UpdateOperationType::ExecutionComplete => {
2134
                // The process has exited but the action is still resident on
2135
                // the worker until its result arrives, so nothing is released
2136
                // here; `complete_action` returns the budget and the slot
2137
                // together.
2138
12.3k
                return Ok(());
2139
            }
2140
        };
2141
2142
13.1k
        let attempt_ended = if worker.is_kill_requested(operation_id) {
2143
1
            None
2144
        } else {
2145
13.1k
            attempt_end_reason(&update).zip(
2146
13.1k
                worker
2147
13.1k
                    .running_action_infos
2148
13.1k
                    .get(operation_id)
2149
13.1k
                    .map(|pending| pending.action_info.clone()),
2150
            )
2151
        };
2152
        // A result the store refuses leaves the record Executing, and the
2153
        // executing sweep requeues it once this worker no longer runs it; by
2154
        // then the worker has forgotten the attempt, so its start is kept here.
2155
        // The result itself is kept too, for the sweep to write.
2156
13.1k
        let lost_result = match 
&update12.8k
{
2157
12.8k
            UpdateOperationType::UpdateWithActionStage(stage @ ActionStage::Completed(_)) => worker
2158
12.8k
                .running_action_infos
2159
12.8k
                .get(operation_id)
2160
12.8k
                .map(|pending| (pending.action_info.clone(), stage.clone())),
2161
304
            _ => None,
2162
        };
2163
2164
        // Update the operation in the worker state manager.
2165
13.1k
        let 
update_operation_res13.1k
= if worker.is_kill_requested(operation_id) {
2166
1
            debug!(
2167
                %operation_id,
2168
                ?worker_id,
2169
                "Ignoring update for operation the worker was told to kill"
2170
            );
2171
1
            Ok(())
2172
        } else {
2173
13.1k
            let 
update_operation_res13.1k
= self
2174
13.1k
                .worker_state_manager
2175
13.1k
                .update_operation_on_node(operation_id, worker_id, worker_node.as_deref(), update)
2176
13.1k
                .await
2177
13.1k
                .err_tip(|| "in update_operation on SimpleScheduler::update_action");
2178
13.1k
            match &update_operation_res {
2179
                Ok(()) => {
2180
13.1k
                    if let Some(((
reason332
,
detail332
),
action_info332
)) = attempt_ended {
2181
332
                        publish_attempt_ended(
2182
332
                            self.attempt_events.as_ref(),
2183
332
                            &action_info,
2184
332
                            worker_id,
2185
332
                            operation_id,
2186
332
                            reason,
2187
332
                            detail,
2188
332
                        );
2189
12.7k
                    }
2190
                }
2191
8
                Err(err) => {
2192
8
                    error!(
2193
                        %operation_id,
2194
                        ?worker_id,
2195
                        ?err,
2196
                        "Failed to update_operation on update_action"
2197
                    );
2198
8
                    if let Some((action_info, stage)) = lost_result {
2199
8
                        self.lost_results.insert(
2200
8
                            operation_id.clone(),
2201
8
                            worker_id.clone(),
2202
8
                            action_info,
2203
8
                            stage,
2204
8
                        );
2205
8
                    
}0
2206
                }
2207
            }
2208
13.1k
            update_operation_res
2209
        };
2210
2211
13.1k
        if !is_finished {
2212
0
            return update_operation_res;
2213
13.1k
        }
2214
        // The worker is done with this action even if the state-manager update
2215
        // failed (e.g. the operation was already torn down after its clients
2216
        // timed out). The worker bookkeeping below must still run, or the
2217
        // worker's platform properties leak until it can never match again.
2218
        // A result the store refused (Redis at its memory ceiling, a
2219
        // failover) is kept in `lost_results`; the record stays Executing on
2220
        // a worker that no longer runs it, and the executing sweep writes it.
2221
2222
        // Clear this action from the current worker if finished.
2223
13.1k
        let complete_action_res = {
2224
            // Note: We need to run this before dealing with backpressure logic.
2225
13.1k
            let was_paused = worker.is_paused;
2226
13.1k
            let complete_action_res = worker.complete_action(operation_id);
2227
2228
            // Backpressure pauses the worker even when it holds nothing
2229
            // else: an idle worker that refuses work and is not paused is
2230
            // offered the same action again at once, and the pair spin
2231
            // until something changes. The next keepalive clears it.
2232
13.1k
            if due_to_backpressure || (
!worker.can_accept_work()13.1k
&&
worker0
.
has_actions0
()) {
2233
12
                worker.is_paused = true;
2234
13.1k
            }
2235
            // complete_action clears is_paused on its way through, so compare
2236
            // the state either side of it rather than testing the flag after.
2237
            // Testing afterwards counts a re-pause every time and never
2238
            // unwinds, which leaves the gauge climbing forever.
2239
13.1k
            if was_paused != worker.is_paused {
2240
12
                record_worker_state("paused", worker.is_paused);
2241
13.1k
            }
2242
13.1k
            complete_action_res
2243
        };
2244
2245
13.1k
        self.capacity_changed();
2246
2247
13.1k
        if let Some(
failed13.1k
) = outcome {
2248
13.1k
            self.note_worker_outcome(worker_id, failed);
2249
13.1k
        
}33
2250
2251
13.1k
        update_operation_res.merge(complete_action_res)
2252
25.4k
    }
2253
2254
    /// Notifies the specified worker to run the given action and handles errors by evicting
2255
    /// the worker if the notification fails.
2256
15.2k
    async fn worker_notify_run_action(
2257
15.2k
        &mut self,
2258
15.2k
        worker_id: WorkerId,
2259
15.2k
        operation_id: OperationId,
2260
15.2k
        action_info: ActionInfoWithProps,
2261
15.2k
        dispatched_at: WorkerTimestamp,
2262
15.2k
    ) -> Result<(), Error> {
2263
        // A dispatch starts a new attempt. A result still held for this
2264
        // operation is an earlier attempt's, and must not complete this one.
2265
15.2k
        self.lost_results.forget(&operation_id);
2266
15.2k
        if let Some(worker) = self.workers.get_mut(&worker_id) {
2267
15.2k
            let notify_worker_result = worker
2268
15.2k
                .notify_update(WorkerUpdate::RunAction(Box::new((
2269
15.2k
                    operation_id.clone(),
2270
15.2k
                    action_info.clone(),
2271
15.2k
                    dispatched_at,
2272
15.2k
                ))))
2273
15.2k
                .await;
2274
2275
15.2k
            if let Err(
notify_worker_result69
) = notify_worker_result {
2276
69
                if notify_worker_result.code == Code::ResourceExhausted {
2277
                    // The worker's queue is full: it has stopped reading, or
2278
                    // it is far behind. Nothing was charged; the action goes
2279
                    // back untried and the worker waits for its next
2280
                    // keepalive before it is offered anything else.
2281
1
                    warn!(
2282
                        ?worker_id,
2283
                        %operation_id,
2284
                        "Worker channel full, requeuing dispatch and pausing the worker"
2285
                    );
2286
1
                    record_dispatch_requeue("channel_full");
2287
1
                    if !worker.is_paused {
2288
1
                        worker.is_paused = true;
2289
1
                        record_worker_state("paused", true);
2290
1
                    
}0
2291
1
                    self.worker_change_notify.notify_one();
2292
1
                    return self
2293
1
                        .worker_state_manager
2294
1
                        .update_operation(
2295
1
                            &operation_id,
2296
1
                            &worker_id,
2297
1
                            UpdateOperationType::UpdateWithDecline(Decline {
2298
1
                                reason: "channel_full".to_string(),
2299
1
                            }),
2300
1
                        )
2301
1
                        .await
2302
1
                        .err_tip(|| "requeuing a dispatch the worker's channel refused");
2303
68
                }
2304
68
                warn!(
2305
                    ?worker_id,
2306
                    ?action_info,
2307
                    ?notify_worker_result,
2308
                    "Worker command failed, removing worker",
2309
                );
2310
2311
                // A slightly nasty way of figuring out that the worker disconnected
2312
                // from send_msg_to_worker without introducing complexity to the
2313
                // code path from here to there.
2314
68
                let is_disconnect = notify_worker_result.code == Code::Internal
2315
68
                    && notify_worker_result.messages.len() == 1
2316
0
                    && notify_worker_result.messages[0] == "Worker Disconnected";
2317
2318
68
                let err = make_err!(
2319
68
                    Code::Internal,
2320
                    "Worker command failed, removing worker {worker_id} -- {notify_worker_result:?}",
2321
                );
2322
2323
68
                let reason = if is_disconnect {
2324
0
                    WorkerDisconnectReason::Disconnected
2325
                } else {
2326
68
                    WorkerDisconnectReason::Error
2327
                };
2328
68
                let evicted = self
2329
68
                    .immediate_evict_worker(&worker_id, err.clone(), is_disconnect, reason)
2330
68
                    .await;
2331
                // The dispatch was never charged to the worker (the send
2332
                // comes first), so the eviction did not see this operation;
2333
                // send it back to the queue here, untried: nothing ran, so
2334
                // no attempt is counted against it.
2335
68
                let requeued = self
2336
68
                    .worker_state_manager
2337
68
                    .update_operation(
2338
68
                        &operation_id,
2339
68
                        &worker_id,
2340
68
                        UpdateOperationType::UpdateWithDecline(Decline {
2341
68
                            reason: "worker_disconnected".to_string(),
2342
68
                        }),
2343
68
                    )
2344
68
                    .await;
2345
68
                return Result::<(), _>::Err(err).merge(evicted).merge(requeued);
2346
15.1k
            }
2347
            // A worker held for the action keeps its hold until the worker
2348
            // the action went to takes it; a decline sends the action back
2349
            // to the queue, and the hold waits for it there again.
2350
15.1k
            self.note_hold_dispatched(&action_info.inner.unique_qualifier, true);
2351
15.1k
            Ok(())
2352
        } else {
2353
0
            warn!(
2354
                ?worker_id,
2355
                %operation_id,
2356
                ?action_info,
2357
                "Worker not found in worker map in worker_notify_run_action"
2358
            );
2359
            // Ensure the operation is put back to queued state. The worker
2360
            // is already gone, so there is no record to propose a larger
2361
            // reservation from: this loss counts toward the budget but never
2362
            // escalates, even if it is the one that crosses
2363
            // `escalate_after_worker_losses`; the next loss will.
2364
0
            self.worker_state_manager
2365
0
                .update_operation(
2366
0
                    &operation_id,
2367
0
                    &worker_id,
2368
0
                    UpdateOperationType::UpdateWithDisconnect(None),
2369
0
                )
2370
0
                .await
2371
        }
2372
15.2k
    }
2373
2374
    /// Tells the worker to kill an operation it is still running but the
2375
    /// state manager no longer has executing on it. A worker that cannot be
2376
    /// reached is evicted, the same as for a failed run request.
2377
    /// The worker acknowledged a dispatch. A late acknowledgement for an
2378
    /// operation no longer on the worker is nothing to act on.
2379
14.3k
    fn dispatch_accepted(&mut self, worker_id: &WorkerId, operation_id: &OperationId) {
2380
14.3k
        let Some(worker) = self.workers.get_mut(worker_id) else {
2381
0
            return;
2382
        };
2383
14.3k
        if worker.mark_accepted(operation_id) {
2384
14.3k
            let action = worker
2385
14.3k
                .running_action_infos
2386
14.3k
                .get(operation_id)
2387
14.3k
                .map(|pending| pending.action_info.inner.unique_qualifier.clone());
2388
14.3k
            if let Some(action) = action {
2389
14.3k
                self.end_hold_for_action(&action, "placed");
2390
14.3k
            
}0
2391
14.3k
            return;
2392
1
        }
2393
        // Messages from a worker arrive in order and the acknowledgement
2394
        // comes before the run, so an acknowledgement for an operation not
2395
        // on this worker means the sweep took the dispatch back already: the
2396
        // worker is about to run an action that now belongs elsewhere. Tell
2397
        // it to stop now, not at the next revoked-operation sweep.
2398
1
        info!(
2399
            ?worker_id,
2400
            %operation_id,
2401
            "Acknowledgement for a dispatch already taken back; telling the worker to stop it"
2402
        );
2403
1
        if let Err(
err0
) = worker.kill_unknown_operation(operation_id) {
2404
0
            warn!(?worker_id, %operation_id, ?err, "Could not tell the worker to stop the operation");
2405
1
        }
2406
14.3k
    }
2407
2408
    /// The worker declined a dispatch: the ledger is restored, the action
2409
    /// requeued untried, and the worker paused; for a decline for load the
2410
    /// pause holds until the worker reports that much free memory.
2411
    /// Returns whether there was a dispatch to take back. A decline for an
2412
    /// operation the worker no longer holds (it finished, or the sweep
2413
    /// already requeued it) is nothing to act on, like a late
2414
    /// acknowledgement, and must not pause the worker.
2415
12
    async fn dispatch_declined(
2416
12
        &mut self,
2417
12
        worker_id: &WorkerId,
2418
12
        operation_id: &OperationId,
2419
12
        reason: String,
2420
12
        needs_kb: Option<u64>,
2421
12
    ) -> Result<bool, Error> {
2422
12
        let holds_it = self
2423
12
            .workers
2424
12
            .peek(worker_id)
2425
12
            .is_some_and(|worker| worker.running_action_infos.contains_key(operation_id));
2426
12
        if !holds_it {
2427
1
            debug!(?worker_id, %operation_id, %reason, "Decline for an operation not on this worker");
2428
1
            return Ok(false);
2429
11
        }
2430
11
        info!(?worker_id, %operation_id, %reason, ?needs_kb, "Worker declined dispatch");
2431
11
        let declined_action = self
2432
11
            .workers
2433
11
            .peek(worker_id)
2434
11
            .and_then(|worker| worker.running_action_infos.get(operation_id))
2435
11
            .map(|pending| pending.action_info.inner.unique_qualifier.clone());
2436
11
        self.update_action(
2437
11
            worker_id,
2438
11
            operation_id,
2439
11
            UpdateOperationType::UpdateWithDecline(Decline { reason }),
2440
11
        )
2441
11
        .await
?0
;
2442
11
        if let Some(worker) = self.workers.get_mut(worker_id) {
2443
11
            if !worker.is_paused {
2444
0
                worker.is_paused = true;
2445
0
                record_worker_state("paused", true);
2446
11
            }
2447
            // A worker that admits when idle declined for load because it
2448
            // holds other work, whatever this scheduler last saw it hold: it
2449
            // waits for room like any busy worker, and if this scheduler sees
2450
            // it holding nothing, its pause lifts on the next keepalive.
2451
            // One that does not (an older worker, or one with no cgroup
2452
            // limit) and declines while holding nothing here may not have
2453
            // more room however long it waits, so a pause until a keepalive
2454
            // with enough free could hold it for good. Its pause lifts on
2455
            // the next keepalive instead, and it is not offered that much
2456
            // again until it reports that much free, or the action would
2457
            // bounce between it and the queue untried.
2458
11
            if !worker.admits_when_idle && 
worker.running_action_infos8
.
is_empty8
() {
2459
5
                worker.pause_needs_kb = None;
2460
5
                if let Some(
needs_kb3
) = needs_kb {
2461
                    worker.idle_declined_kb = Some(
2462
3
                        worker
2463
3
                            .idle_declined_kb
2464
3
                            .map_or(needs_kb, |declined_kb| 
declined_kb0
.
min0
(
needs_kb0
)),
2465
                    );
2466
2
                }
2467
6
            } else {
2468
6
                worker.pause_needs_kb = needs_kb;
2469
6
            }
2470
0
        }
2471
        // A hold on this worker for the declined action outlives the
2472
        // decline: the worker is paused until it reports room, and is
2473
        // offered the action again then. Unless it declined the action
2474
        // idle: it is then not offered that much again until a keepalive
2475
        // says it has it free, which waits on the worker rather than on
2476
        // its actions, so the hold ends and the next pass holds another.
2477
11
        if let (Some(
action8
), Some(
needs_kb8
)) = (declined_action, needs_kb)
2478
8
            && self
2479
8
                .holds
2480
8
                .get(worker_id)
2481
8
                .is_some_and(|hold| 
hold.action2
==
action2
)
2482
2
            && self.workers.peek(worker_id).is_some_and(|worker| {
2483
2
                worker
2484
2
                    .idle_declined_kb
2485
2
                    .is_some_and(|declined_kb| 
needs_kb1
>=
declined_kb1
)
2486
2
            })
2487
1
        {
2488
1
            self.end_hold(worker_id, "declined");
2489
10
        }
2490
11
        Ok(true)
2491
12
    }
2492
2493
    /// Dispatches this worker has not acknowledged within the timeout, as
2494
    /// of its latest keepalive.
2495
    /// A keepalive's report of what the worker is running. An acknowledged
2496
    /// operation this scheduler holds for the worker that the report has
2497
    /// left out twice in a row ran without its result reaching here: the
2498
    /// store refused the write, or the worker's report of it was lost. Its
2499
    /// slot is released and it goes back through the error path, so a result
2500
    /// the store keeps refusing spends `max_job_retries` and ends in a
2501
    /// failure the client sees rather than running forever. A requeue the
2502
    /// store refuses is logged, not raised: the keepalive that carried the
2503
    /// report must not fail over it, and the executing sweep tries again.
2504
25.5k
    async fn running_operations_reported(
2505
25.5k
        &mut self,
2506
25.5k
        worker_id: &WorkerId,
2507
25.5k
        reported: &HashSet<OperationId>,
2508
25.5k
    ) {
2509
25.5k
        let Some(worker) = self.workers.0.peek_mut(worker_id) else {
2510
0
            return;
2511
        };
2512
25.5k
        let lost = worker.unreported_operations(reported);
2513
25.5k
        for 
operation_id1
in lost {
2514
1
            warn!(
2515
                ?worker_id,
2516
                %operation_id,
2517
                "Worker no longer reports an operation it acknowledged and sent no result for; requeuing"
2518
            );
2519
1
            record_dispatch_requeue("unreported");
2520
1
            if let Err(
err0
) = self
2521
1
                .update_action(
2522
1
                    worker_id,
2523
1
                    &operation_id,
2524
1
                    UpdateOperationType::UpdateWithError(make_err!(
2525
1
                        Code::Unavailable,
2526
1
                        "The worker stopped running this operation without its result reaching the scheduler"
2527
1
                    )),
2528
                )
2529
1
                .await
2530
            {
2531
0
                warn!(?worker_id, %operation_id, ?err, "Could not requeue an operation the worker dropped");
2532
1
            }
2533
        }
2534
25.5k
    }
2535
2536
22
    fn unacknowledged_dispatches(
2537
22
        &self,
2538
22
        worker_id: &WorkerId,
2539
22
        timestamp: WorkerTimestamp,
2540
22
        timeout_s: u64,
2541
22
    ) -> Vec<OperationId> {
2542
22
        self.workers
2543
22
            .peek(worker_id)
2544
22
            .map(|worker| worker.unacknowledged(timestamp.saturating_sub(timeout_s)))
2545
22
            .unwrap_or_default()
2546
22
    }
2547
2548
11
    async fn worker_notify_kill_operation(
2549
11
        &mut self,
2550
11
        worker_id: &WorkerId,
2551
11
        operation_id: OperationId,
2552
11
    ) -> Result<(), Error> {
2553
11
        let Some(worker) = self.workers.get_mut(worker_id) else {
2554
            // Gone between the snapshot and now; its actions were requeued.
2555
0
            return Ok(());
2556
        };
2557
        // Already told, or finished in the meantime; nothing more to send.
2558
11
        if !worker.running_action_infos.contains_key(&operation_id)
2559
8
            || worker.is_kill_requested(&operation_id)
2560
        {
2561
3
            return Ok(());
2562
8
        }
2563
8
        info!(
2564
            ?worker_id,
2565
            %operation_id,
2566
            "Killing operation the state manager no longer has executing on this worker"
2567
        );
2568
8
        if let Err(
err2
) = worker
2569
8
            .notify_update(WorkerUpdate::KillOperation(operation_id.clone()))
2570
8
            .await
2571
        {
2572
            // A full channel is a worker that is behind, not one that is
2573
            // gone. It keeps its place; the request is forgotten so the
2574
            // next sweep sends the kill again.
2575
2
            if err.code == Code::ResourceExhausted {
2576
1
                worker.clear_kill_request(&operation_id);
2577
1
                warn!(
2578
                    ?worker_id,
2579
                    %operation_id,
2580
                    "Worker channel full, kill deferred to the next sweep"
2581
                );
2582
1
                return Ok(());
2583
1
            }
2584
1
            warn!(
2585
                ?worker_id,
2586
                %operation_id,
2587
                ?err,
2588
                "Worker command failed, removing worker"
2589
            );
2590
1
            let err = make_err!(
2591
1
                Code::Internal,
2592
                "Worker command failed, removing worker {worker_id} -- {err:?}",
2593
            );
2594
1
            return Result::<(), _>::Err(err.clone()).merge(
2595
1
                self.immediate_evict_worker(
2596
1
                    worker_id,
2597
1
                    err,
2598
1
                    true,
2599
1
                    WorkerDisconnectReason::Disconnected,
2600
1
                )
2601
1
                .await,
2602
            );
2603
6
        }
2604
6
        Ok(())
2605
11
    }
2606
2607
    /// Evicts the worker from the pool and puts items back into the queue if anything was being executed on it.
2608
1.82k
    async fn immediate_evict_worker(
2609
1.82k
        &mut self,
2610
1.82k
        worker_id: &WorkerId,
2611
1.82k
        err: Error,
2612
1.82k
        is_disconnect: bool,
2613
1.82k
        reason: WorkerDisconnectReason,
2614
1.82k
    ) -> Result<(), Error> {
2615
1.82k
        let mut result = Ok(());
2616
        // The fleet's ceiling with the lost worker still in it: the pool
2617
        // that lost it brings up its like, and an action escalated past
2618
        // what remains would otherwise be capped by one worker's absence.
2619
1.82k
        let fleet = self
2620
1.82k
            .memory_escalation
2621
1.82k
            .as_ref()
2622
1.82k
            .map(|policy| 
self33
.
fleet_largest_worker33
(
&policy.property33
,
&policy.cpu_property33
));
2623
1.82k
        if let Some(
mut worker1.36k
) = self.remove_worker(worker_id) {
2624
            // Log every eviction here rather than in each caller, so a worker
2625
            // can never leave the pool unexplained. Without this, a worker that
2626
            // vanished mid-build left nothing on the scheduler side to
2627
            // attribute it to, and the only visible symptom was the worker
2628
            // reconnecting with a fresh id.
2629
1.36k
            info!(
2630
                ?worker_id,
2631
                is_disconnect,
2632
197
                running_actions = worker.running_action_infos.len(),
2633
197
                reason = %err.message_string(),
2634
                "Evicting worker from pool"
2635
            );
2636
1.36k
            record_worker_disconnected(reason, worker.is_draining, worker.is_paused);
2637
            // We don't care if we fail to send message to worker, this is only a best attempt.
2638
1.36k
            drop(worker.notify_update(WorkerUpdate::Disconnect).await);
2639
            // Whatever took the worker away (its stream ended, it timed
2640
            // out, a command to it failed, an operator removed it), the
2641
            // action running on it did nothing wrong: it is a worker loss
2642
            // with its own budget, not an attempt the action spent.
2643
            // A worker that went away on its own may have been OOM-killed as a
2644
            // whole; one removed, drained, shut down or evicted for an
2645
            // unacknowledged kill was not, and escalates nothing.
2646
1.36k
            let memory_plausible = 
matches!23
(
2647
1.36k
                reason,
2648
                WorkerDisconnectReason::Disconnected
2649
                    | WorkerDisconnectReason::Timeout
2650
                    | WorkerDisconnectReason::Error
2651
1.33k
            ) && !worker.is_draining;
2652
1.36k
            for (
operation_id646
,
pending646
) in worker.running_action_infos.drain() {
2653
646
                let update = UpdateOperationType::UpdateWithDisconnect(
2654
646
                    fleet
2655
646
                        .filter(|_| memory_plausible)
2656
646
                        .and_then(|fleet| 
self25
.
loss_escalation25
(
worker_id25
,
&pending25
,
fleet25
)),
2657
                );
2658
                // The worker can still hold an operation the executing sweep
2659
                // already timed out or that finished; that attempt was
2660
                // reported where it ended.
2661
641
                if matches!(
2662
646
                    self.worker_state_manager
2663
646
                        .is_executing_on_worker(&operation_id, worker_id)
2664
646
                        .await,
2665
                    Ok(false)
2666
                ) {
2667
5
                    continue;
2668
641
                }
2669
641
                let 
update_res640
= self
2670
641
                    .worker_state_manager
2671
641
                    .update_operation(&operation_id, worker_id, update)
2672
641
                    .await;
2673
                // An operation the worker was told to kill was already
2674
                // given up on; its loss is not a lost attempt.
2675
640
                if update_res.is_ok() && 
pending.kill_requested_at438
.
is_none438
() {
2676
438
                    publish_attempt_ended(
2677
438
                        self.attempt_events.as_ref(),
2678
438
                        &pending.action_info,
2679
438
                        worker_id,
2680
438
                        &operation_id,
2681
438
                        AttemptEndReason::WorkerLost,
2682
438
                        err.message_string(),
2683
438
                    );
2684
438
                
}202
2685
640
                result = result.merge(update_res);
2686
            }
2687
466
        }
2688
        // Note: Calling this many time is very cheap, it'll only trigger `do_try_match` once.
2689
        // TODO(palfrey) This should be moved to inside the Workers struct.
2690
1.82k
        self.capacity_changed();
2691
1.82k
        result
2692
1.82k
    }
2693
}
2694
2695
#[derive(Debug, MetricsComponent)]
2696
pub struct ApiWorkerScheduler {
2697
    #[metric]
2698
    inner: Mutex<ApiWorkerSchedulerImpl>,
2699
    /// See `ApiWorkerSchedulerImpl::capacity_generation`; read here without
2700
    /// the lock.
2701
    capacity_generation: Arc<AtomicU64>,
2702
    /// See `ApiWorkerSchedulerImpl::scheduler_id`; read here without the lock.
2703
    scheduler_id: String,
2704
    #[metric(group = "platform_property_manager")]
2705
    platform_property_manager: Arc<PlatformPropertyManager>,
2706
2707
    #[metric(
2708
        help = "Timeout of how long to evict workers if no response in this given amount of time in seconds."
2709
    )]
2710
    worker_timeout_s: u64,
2711
    #[metric(
2712
        help = "How long a sent kill may go unacknowledged before the worker is evicted, in seconds."
2713
    )]
2714
    unacknowledged_kill_timeout_s: u64,
2715
    #[metric(
2716
        help = "How long a dispatch may go unacknowledged before it is requeued untried, in seconds; 0 is off."
2717
    )]
2718
    dispatch_ack_timeout_s: u64,
2719
    /// Shared worker registry for checking worker liveness.
2720
    worker_registry: SharedWorkerRegistry,
2721
2722
    /// Performance metrics for observability.
2723
    metrics: Arc<SchedulerMetrics>,
2724
2725
    /// Channel for publishing origin events such as worker-observed action
2726
    /// resource usage. `None` when origin events are disabled.
2727
    maybe_origin_event_tx: Option<mpsc::Sender<OriginEvent>>,
2728
2729
    /// Where a `historical_resource` parent keeps what each kind of action
2730
    /// used; every sampled usage report goes in. `None` without one.
2731
    resource_sketch: Option<Arc<ResourceSketch>>,
2732
2733
    /// The memory property the escalation policy reads, so a kill at a
2734
    /// reservation the worker did not echo can still be filed at it.
2735
    memory_property: Option<String>,
2736
2737
    /// Woken when a worker joins or leaves this scheduler.
2738
    local_fleet_change_notify: Arc<Notify>,
2739
}
2740
2741
impl ApiWorkerScheduler {
2742
    /// Whether `worker_id`, connected to this scheduler, still holds
2743
    /// `operation_id`. `None` when the worker is not connected here.
2744
37
    pub async fn running_on_worker(
2745
37
        &self,
2746
37
        worker_id: &WorkerId,
2747
37
        operation_id: &OperationId,
2748
37
    ) -> Option<OnWorker> {
2749
37
        let inner = self.inner.lock().await;
2750
        // Held whether or not the worker is still connected: its result is
2751
        // the attempt's outcome either way. Only for the worker that sent
2752
        // it, though: once the record is another worker's, that is a new
2753
        // attempt and the result is not its outcome.
2754
37
        if let Some(
stage3
) = inner.lost_results.stage(worker_id, operation_id) {
2755
3
            return Some(OnWorker::ResultHeld(Box::new(stage.clone())));
2756
34
        }
2757
34
        inner.workers.peek(worker_id).map(|worker| 
{32
2758
32
            if worker.running_action_infos.contains_key(operation_id) {
2759
26
                OnWorker::Running
2760
            } else {
2761
6
                OnWorker::NotRunning
2762
            }
2763
32
        })
2764
37
    }
2765
2766
    /// Forgets a result the sweep held: written, it reports the attempt's
2767
    /// end as the worker's own update would have; stale, it is dropped.
2768
2
    pub async fn settle_held_result(
2769
2
        &self,
2770
2
        worker_id: &WorkerId,
2771
2
        operation_id: &OperationId,
2772
2
        written: bool,
2773
2
    ) {
2774
2
        let mut inner = self.inner.lock().await;
2775
2
        let Some((
action_info1
,
stage1
)) = inner.lost_results.take(worker_id, operation_id) else {
2776
1
            return;
2777
        };
2778
1
        let Some((
reason0
,
detail0
)) = written
2779
1
            .then(|| attempt_end_reason(&UpdateOperationType::UpdateWithActionStage(stage)))
2780
1
            .flatten()
2781
        else {
2782
1
            return;
2783
        };
2784
0
        publish_attempt_ended(
2785
0
            inner.attempt_events.as_ref(),
2786
0
            &action_info,
2787
0
            worker_id,
2788
0
            operation_id,
2789
0
            reason,
2790
0
            detail,
2791
        );
2792
2
    }
2793
2794
    /// Reports an attempt the executing sweep ended on `worker_id`: timed out
2795
    /// while the worker still held it, or requeued after the state manager
2796
    /// refused its result. Nothing is published when the attempt's start is
2797
    /// no longer known, as for a peer's worker.
2798
18
    pub async fn report_swept_attempt(
2799
18
        &self,
2800
18
        worker_id: &WorkerId,
2801
18
        operation_id: &OperationId,
2802
18
        reason: AttemptEndReason,
2803
18
        detail: String,
2804
18
    ) {
2805
18
        let mut inner = self.inner.lock().await;
2806
18
        let held = inner
2807
18
            .workers
2808
18
            .peek(worker_id)
2809
18
            .and_then(|worker| 
worker.running_action_infos1
.
get1
(
operation_id1
))
2810
18
            .map(|pending| 
pending.action_info1
.
clone1
());
2811
18
        let Some(
action_info1
) = held.or_else(||
{17
2812
17
            inner
2813
17
                .lost_results
2814
17
                .take(worker_id, operation_id)
2815
17
                .map(|(action_info, _)| action_info)
2816
17
        }) else {
2817
17
            return;
2818
        };
2819
1
        publish_attempt_ended(
2820
1
            inner.attempt_events.as_ref(),
2821
1
            &action_info,
2822
1
            worker_id,
2823
1
            operation_id,
2824
1
            reason,
2825
1
            detail,
2826
        );
2827
18
    }
2828
2829
    #[expect(clippy::too_many_arguments)]
2830
590
    pub fn new(
2831
590
        worker_state_manager: Arc<dyn WorkerStateManager>,
2832
590
        platform_property_manager: Arc<PlatformPropertyManager>,
2833
590
        allocation_strategy: WorkerAllocationStrategy,
2834
590
        live_memory_veto: Option<String>,
2835
590
        memory_escalation: Option<MemoryEscalationSpec>,
2836
590
        reservation_hold: Option<ReservationHoldSpec>,
2837
590
        outcome_tripwire: Option<WorkerOutcomeTripwireSpec>,
2838
590
        worker_change_notify: Arc<Notify>,
2839
590
        worker_timeout_s: u64,
2840
590
        unacknowledged_kill_timeout_s: u64,
2841
590
        dispatch_ack_timeout_s: u64,
2842
590
        worker_registry: SharedWorkerRegistry,
2843
590
        maybe_origin_event_tx: Option<mpsc::Sender<OriginEvent>>,
2844
590
        resource_sketch: Option<Arc<ResourceSketch>>,
2845
590
        has_peers: bool,
2846
590
        record_ttl: Duration,
2847
590
        scheduler_id: String,
2848
590
    ) -> Arc<Self> {
2849
590
        debug_assert!(
2850
0
            !record_ttl.is_zero(),
2851
            "record_ttl must be non-zero; a zero TTL degenerates the census warm-up/staleness checks"
2852
        );
2853
590
        debug_assert!(
2854
0
            reservation_hold.is_none_or(|hold| hold.hold_after_s > 0 && hold.max_hold_s > 0),
2855
            "reservation_hold.hold_after_s and max_hold_s must be above zero; the factory refuses them"
2856
        );
2857
590
        let local_fleet_change_notify = Arc::new(Notify::new());
2858
590
        let capacity_generation = Arc::new(AtomicU64::new(0));
2859
590
        let memory_property = memory_escalation
2860
590
            .as_ref()
2861
590
            .map(|policy| 
policy.property19
.
clone19
());
2862
590
        Arc::new(Self {
2863
590
            inner: Mutex::new(ApiWorkerSchedulerImpl {
2864
590
                workers: Workers(LruCache::unbounded()),
2865
590
                worker_state_manager,
2866
590
                allocation_strategy,
2867
590
                live_memory_veto,
2868
590
                memory_escalation,
2869
590
                reservation_hold,
2870
590
                outcome_tripwire,
2871
590
                attempt_events: maybe_origin_event_tx.clone(),
2872
590
                lost_results: LostResults::default(),
2873
590
                holds: HashMap::new(),
2874
590
                holds_by_action: HashMap::new(),
2875
590
                hold_cooldowns: HashMap::new(),
2876
590
                pass_generation: 0,
2877
590
                worker_change_notify,
2878
590
                capacity_generation: capacity_generation.clone(),
2879
590
                worker_registry: worker_registry.clone(),
2880
590
                shutting_down: false,
2881
590
                capability_index: WorkerCapabilityIndex::new(),
2882
590
                fleet_generation: 0,
2883
590
                fleet_shape_set: BTreeSet::new(),
2884
590
                // Without peers there is nothing to wait for.
2885
590
                peer_fleet: (!has_peers).then(Vec::new),
2886
590
                peer_schedulers: Vec::new(),
2887
590
                scheduler_id: scheduler_id.clone(),
2888
590
                shared: has_peers,
2889
590
                record_ttl,
2890
590
                peer_fleet_known_since: None,
2891
590
                peer_fleet_last_refresh: None,
2892
590
                local_fleet_change_notify: local_fleet_change_notify.clone(),
2893
590
                static_verdicts: HashMap::new(),
2894
590
            }),
2895
590
            platform_property_manager,
2896
590
            worker_timeout_s,
2897
590
            unacknowledged_kill_timeout_s,
2898
590
            dispatch_ack_timeout_s,
2899
590
            worker_registry,
2900
590
            metrics: Arc::new(SchedulerMetrics::default()),
2901
590
            maybe_origin_event_tx,
2902
590
            resource_sketch,
2903
590
            memory_property,
2904
590
            local_fleet_change_notify,
2905
590
            capacity_generation,
2906
590
            scheduler_id,
2907
590
        })
2908
590
    }
2909
2910
    /// The id this scheduler publishes to its peers under.
2911
    #[must_use]
2912
0
    pub fn scheduler_id(&self) -> &str {
2913
0
        &self.scheduler_id
2914
0
    }
2915
2916
    /// Whether no worker is connected here and, as far as a trusted census
2917
    /// says, to any peer either. False while the census cannot be trusted,
2918
    /// so a peer we cannot see is assumed to have workers.
2919
10
    pub async fn no_worker_anywhere(&self, now: SystemTime) -> bool {
2920
10
        let inner = self.inner.lock().await;
2921
10
        inner.workers.is_empty()
2922
7
            && inner.peer_census_trusted(now)
2923
7
            && inner.peer_fleet.as_ref().is_some_and(Vec::is_empty)
2924
10
    }
2925
2926
    /// The capacity generation as of now; see `find_worker_for_action_observed`.
2927
65.2k
    pub fn capacity_generation(&self) -> u64 {
2928
65.2k
        self.capacity_generation.load(Ordering::Relaxed)
2929
65.2k
    }
2930
2931
    /// Returns a reference to the worker registry.
2932
1.36k
    pub const fn worker_registry(&self) -> &SharedWorkerRegistry {
2933
1.36k
        &self.worker_registry
2934
1.36k
    }
2935
2936
    /// `dispatched_at` is the scheduler's clock at the send; the
2937
    /// acknowledgement timeout counts from it.
2938
15.2k
    pub async fn worker_notify_run_action(
2939
15.2k
        &self,
2940
15.2k
        worker_id: WorkerId,
2941
15.2k
        operation_id: OperationId,
2942
15.2k
        action_info: ActionInfoWithProps,
2943
15.2k
        dispatched_at: WorkerTimestamp,
2944
15.2k
    ) -> Result<(), Error> {
2945
15.2k
        self.metrics
2946
15.2k
            .actions_dispatched
2947
15.2k
            .fetch_add(1, Ordering::Relaxed);
2948
15.2k
        let mut inner = self.inner.lock().await;
2949
15.2k
        inner
2950
15.2k
            .worker_notify_run_action(worker_id, operation_id, action_info, dispatched_at)
2951
15.2k
            .await
2952
15.2k
    }
2953
2954
    /// A keepalive, or another message standing in for one. Only a
2955
    /// keepalive carries a load and lifts a pause; anything else refreshes
2956
    /// the timestamp and runs the acknowledgement sweep.
2957
63.7k
    async fn refresh_worker(
2958
63.7k
        &self,
2959
63.7k
        worker_id: &WorkerId,
2960
63.7k
        timestamp: WorkerTimestamp,
2961
63.7k
        load: Option<WorkerLoad>,
2962
63.7k
        keepalive: bool,
2963
63.7k
    ) -> Result<(), Error> {
2964
        {
2965
63.7k
            let mut inner = self.inner.lock().await;
2966
63.7k
            inner
2967
63.7k
                .refresh_lifetime(worker_id, timestamp, load, keepalive)
2968
63.7k
                .err_tip(|| "Error refreshing lifetime in worker_keep_alive_received()")
?1
;
2969
63.7k
            if self.dispatch_ack_timeout_s > 0 {
2970
22
                let stale = inner.unacknowledged_dispatches(
2971
22
                    worker_id,
2972
22
                    timestamp,
2973
22
                    self.dispatch_ack_timeout_s,
2974
22
                );
2975
22
                for 
operation_id2
in stale {
2976
2
                    warn!(
2977
                        ?worker_id,
2978
                        %operation_id,
2979
                        timeout_s = self.dispatch_ack_timeout_s,
2980
                        "Dispatch never acknowledged, requeuing untried"
2981
                    );
2982
2
                    match inner
2983
2
                        .dispatch_declined(
2984
2
                            worker_id,
2985
2
                            &operation_id,
2986
2
                            "unacknowledged".to_string(),
2987
2
                            None,
2988
2
                        )
2989
2
                        .await
2990
                    {
2991
2
                        Ok(true) => {
2992
2
                            self.metrics
2993
2
                                .dispatches_unacknowledged
2994
2
                                .fetch_add(1, Ordering::Relaxed);
2995
2
                            record_dispatch_requeue("unacknowledged");
2996
2
                        }
2997
0
                        Ok(false) => {}
2998
0
                        Err(err) => {
2999
0
                            warn!(?worker_id, %operation_id, ?err, "Could not requeue unacknowledged dispatch");
3000
                        }
3001
                    }
3002
                }
3003
63.7k
            }
3004
        }
3005
63.7k
        let now = UNIX_EPOCH + Duration::from_secs(timestamp);
3006
63.7k
        self.worker_registry
3007
63.7k
            .update_worker_heartbeat(worker_id, now)
3008
63.7k
            .await;
3009
63.7k
        Ok(())
3010
63.7k
    }
3011
3012
23
    pub async fn running_action_info(
3013
23
        &self,
3014
23
        worker_id: &WorkerId,
3015
23
        operation_id: &OperationId,
3016
23
    ) -> Option<ActionInfoWithProps> {
3017
23
        let inner = self.inner.lock().await;
3018
23
        inner
3019
23
            .workers
3020
23
            .peek(worker_id)
3021
23
            .and_then(|worker| worker.running_action_infos.get(operation_id))
3022
23
            .map(|pending_action_info| 
pending_action_info.action_info22
.
clone22
())
3023
23
    }
3024
3025
    /// Returns the scheduler metrics for observability.
3026
    #[must_use]
3027
0
    pub const fn get_metrics(&self) -> &Arc<SchedulerMetrics> {
3028
0
        &self.metrics
3029
0
    }
3030
3031
    /// A counter that changes every time a worker joins or leaves.
3032
43.4k
    pub async fn fleet_generation(&self) -> u64 {
3033
43.4k
        self.inner.lock().await.fleet_generation
3034
43.4k
    }
3035
3036
    /// The distinct properties this scheduler's workers registered with.
3037
1.36k
    pub async fn fleet_shapes(&self) -> Vec<PlatformProperties> {
3038
1.36k
        self.inner.lock().await.fleet_shapes()
3039
1.36k
    }
3040
3041
    /// Records what the workers connected to peer schedulers can run, or
3042
    /// `None` when that is not known.
3043
1.37k
    pub async fn set_peer_fleet(&self, peers: Option<Vec<PeerScheduler>>, now: SystemTime) {
3044
1.37k
        self.inner.lock().await.set_peer_fleet(peers, now);
3045
1.37k
    }
3046
3047
    /// The workers held for a queued action right now.
3048
38
    pub async fn held_workers_for_test(&self) -> Vec<WorkerId> {
3049
38
        self.inner.lock().await.holds.keys().cloned().collect()
3050
38
    }
3051
3052
    /// Woken when a worker joins or leaves this scheduler.
3053
    #[must_use]
3054
556
    pub const fn local_fleet_change_notify(&self) -> &Arc<Notify> {
3055
556
        &self.local_fleet_change_notify
3056
556
    }
3057
3058
    /// Attempts to find a worker that is capable of running this action.
3059
    // TODO(palfrey) This algorithm is not very efficient. Simple testing using a tree-like
3060
    // structure showed worse performance on a 10_000 worker * 7 properties * 1000 queued tasks
3061
    // simulation of worst cases in a single threaded environment.
3062
801
    pub async fn find_worker_for_action(
3063
801
        &self,
3064
801
        platform_properties: &PlatformProperties,
3065
801
        full_worker_logging: bool,
3066
801
        now: SystemTime,
3067
801
        asking: Option<QueuedAction<'_>>,
3068
801
    ) -> MatchOutcome {
3069
801
        self.find_worker_for_action_observed(platform_properties, full_worker_logging, now, asking)
3070
801
            .await
3071
            .0
3072
801
    }
3073
3074
    /// A matching pass is about to read the queue; returns the pass, for
3075
    /// `end_pass_holds`.
3076
43.4k
    pub async fn begin_pass_holds(&self) -> u64 {
3077
43.4k
        self.inner.lock().await.begin_pass_holds()
3078
43.4k
    }
3079
3080
    /// The pass read the whole queue: release the holds no pass since it
3081
    /// began has met, and the ones past their time.
3082
43.4k
    pub async fn end_pass_holds(&self, pass: u64, now: SystemTime) {
3083
43.4k
        self.inner.lock().await.end_pass_holds(pass, now);
3084
43.4k
    }
3085
3086
    /// `find_worker_for_action`, also returning the capacity generation read
3087
    /// under the same lock as the placement. A pass compares it with the one
3088
    /// it saw last: a change means a worker gained room since, and an older
3089
    /// action that found none earlier in the pass should be offered that room
3090
    /// before this one takes it.
3091
4.86M
    pub async fn find_worker_for_action_observed(
3092
4.86M
        &self,
3093
4.86M
        platform_properties: &PlatformProperties,
3094
4.86M
        full_worker_logging: bool,
3095
4.86M
        now: SystemTime,
3096
4.86M
        asking: Option<QueuedAction<'_>>,
3097
4.86M
    ) -> (MatchOutcome, u64) {
3098
4.86M
        let start = Instant::now();
3099
4.86M
        self.metrics
3100
4.86M
            .find_worker_calls
3101
4.86M
            .fetch_add(1, Ordering::Relaxed);
3102
3103
4.86M
        let 
mut inner4.86M
= self.inner.lock().await;
3104
4.86M
        let worker_count = inner.workers.len() as u64;
3105
4.86M
        let result = inner.inner_find_worker_for_action(
3106
4.86M
            platform_properties,
3107
4.86M
            full_worker_logging,
3108
4.86M
            now,
3109
4.86M
            asking,
3110
4.86M
        );
3111
4.86M
        let generation = inner.capacity_generation.load(Ordering::Relaxed);
3112
3113
        // Track workers iterated (worst case is all workers)
3114
4.86M
        self.metrics
3115
4.86M
            .workers_iterated
3116
4.86M
            .fetch_add(worker_count, Ordering::Relaxed);
3117
3118
4.86M
        if 
matches!4.84M
(result, MatchOutcome::Matched(_)) {
3119
15.4k
            self.metrics
3120
15.4k
                .find_worker_hits
3121
15.4k
                .fetch_add(1, Ordering::Relaxed);
3122
4.84M
        } else {
3123
4.84M
            self.metrics
3124
4.84M
                .find_worker_misses
3125
4.84M
                .fetch_add(1, Ordering::Relaxed);
3126
4.84M
        }
3127
3128
        #[allow(clippy::cast_possible_truncation)]
3129
4.86M
        self.metrics
3130
4.86M
            .find_worker_time_ns
3131
4.86M
            .fetch_add(start.elapsed().as_nanos() as u64, Ordering::Relaxed);
3132
4.86M
        (result, generation)
3133
4.86M
    }
3134
3135
    /// Checks to see if the worker exists in the worker pool. Should only be used in unit tests.
3136
    #[must_use]
3137
20
    
pub async fn contains_worker_for_test(&self, worker_id: &WorkerId) -> bool0
{
3138
20
        let inner = self.inner.lock().await;
3139
20
        inner.workers.contains(worker_id)
3140
20
    }
3141
3142
    /// A unit test function used to send the keep alive message to the worker from the server.
3143
1
    pub async fn send_keep_alive_to_worker_for_test(
3144
1
        &self,
3145
1
        worker_id: &WorkerId,
3146
1
    ) -> Result<(), Error> {
3147
1
        let mut inner = self.inner.lock().await;
3148
1
        let worker = inner.workers.get_mut(worker_id).ok_or_else(|| 
{0
3149
0
            make_input_err!("WorkerId '{}' does not exist in workers map", worker_id)
3150
0
        })?;
3151
1
        worker.keep_alive()
3152
1
    }
3153
}
3154
3155
#[async_trait]
3156
impl WorkerScheduler for ApiWorkerScheduler {
3157
35
    fn get_platform_property_manager(&self) -> &PlatformPropertyManager {
3158
35
        self.platform_property_manager.as_ref()
3159
35
    }
3160
3161
    async fn record_action_resource_usage(
3162
        &self,
3163
        worker_id: &WorkerId,
3164
        operation_id: &OperationId,
3165
        mut resource_usage: ActionResourceUsage,
3166
18
    ) -> Result<(), Error> {
3167
        // The worker API talks to this `ApiWorkerScheduler` (it is the
3168
        // `WorkerScheduler` returned by `SimpleScheduler::new`), so the
3169
        // resource-usage origin event must be published here. Previously the
3170
        // only override lived on `SimpleScheduler`, which this path never
3171
        // reaches, so the event was silently dropped by the trait's no-op
3172
        // default and `observed_worker_peak_memory_mib` was never recorded.
3173
        // Sampling is optional, so only record when the worker actually took a
3174
        // reading. A zero here means "not sampled", not "used no memory".
3175
        {
3176
            // The result follows this report; what it says decides whether
3177
            // that result is a kill to escalate.
3178
            let mut inner = self.inner.lock().await;
3179
            if let Some(pending) = inner
3180
                .workers
3181
                .get_mut(worker_id)
3182
18
                .and_then(|worker| worker.running_action_infos.get_mut(operation_id))
3183
            {
3184
                pending.last_usage = Some(resource_usage.clone());
3185
            }
3186
        }
3187
        let maybe_action_info = self.running_action_info(worker_id, operation_id).await;
3188
        let action_mnemonic = maybe_action_info
3189
            .as_ref()
3190
18
            .and_then(|action_info| action_info.origin_metadata.bazel_metadata.as_ref())
3191
1
            .map_or_else(String::new, |bazel_metadata| {
3192
1
                bazel_metadata.action_mnemonic.clone()
3193
1
            });
3194
3195
        let outcome =
3196
            ResourceOutcome::try_from(resource_usage.outcome).unwrap_or(ResourceOutcome::Unknown);
3197
        if !matches!(
3198
            outcome,
3199
            ResourceOutcome::Unknown | ResourceOutcome::Completed
3200
        ) {
3201
            warn!(
3202
                ?worker_id,
3203
                ?operation_id,
3204
                outcome = outcome.as_str_name(),
3205
                enforced = resource_usage.enforced,
3206
                action_mnemonic,
3207
                peak_memory_kb = resource_usage.peak_memory_kb,
3208
                wall_time_ms = resource_usage.wall_time_ms,
3209
                reserved = ?resource_usage.reserved,
3210
                "Action ended by a kill"
3211
            );
3212
        }
3213
3214
        if resource_usage.sampled {
3215
            if resource_usage.peak_memory_kb > 0 {
3216
                record_execution_peak_memory(
3217
                    resource_usage.peak_memory_kb,
3218
                    "",
3219
                    &action_mnemonic,
3220
                    outcome.as_str_name(),
3221
                );
3222
            }
3223
            if resource_usage.cpu_time_ms > 0 {
3224
                record_execution_cpu_time(
3225
                    resource_usage.cpu_time_ms,
3226
                    "",
3227
                    &action_mnemonic,
3228
                    outcome.as_str_name(),
3229
                );
3230
            }
3231
        }
3232
3233
        // What the scheduler learns from: outside the `inner` lock, the
3234
        // sketch has its own.
3235
        if let (Some(sketch), Some(action_info), true) = (
3236
            self.resource_sketch.as_ref(),
3237
            maybe_action_info.as_ref(),
3238
            resource_usage.sampled,
3239
        ) {
3240
            let metadata = action_info.origin_metadata.bazel_metadata.as_ref();
3241
            let key = SketchKey::for_attempt(
3242
0
                metadata.map(|m| m.target_id.as_str()),
3243
0
                metadata.map(|m| m.action_mnemonic.as_str()),
3244
                &action_info.inner.command_digest.to_string(),
3245
            );
3246
            let killed = outcome == ResourceOutcome::KilledMemory;
3247
            // What it ran under: the worker's echo, else what the scheduler
3248
            // sent, the same two sources the escalation reads.
3249
            let killed_at_kb = killed
3250
0
                .then(|| {
3251
0
                    resource_usage
3252
0
                        .reserved
3253
0
                        .map(|r| r.memory_kb)
3254
0
                        .filter(|kb| *kb > 0)
3255
0
                        .or_else(|| {
3256
0
                            let property = self.memory_property.as_deref()?;
3257
0
                            match action_info.platform_properties.properties.get(property) {
3258
0
                                Some(PlatformPropertyValue::Minimum(kb)) => Some(*kb),
3259
0
                                _ => None,
3260
                            }
3261
0
                        })
3262
0
                })
3263
                .flatten();
3264
            let observation = Observation {
3265
                peak_memory_kb: resource_usage.peak_memory_kb,
3266
0
                cpu_millicores: (resource_usage.wall_time_ms > 0).then(|| {
3267
0
                    resource_usage.cpu_time_ms.saturating_mul(1000) / resource_usage.wall_time_ms
3268
0
                }),
3269
                peak_disk_kb: resource_usage.peak_disk_kb,
3270
                peak_gpu_memory_kb: resource_usage.peak_gpu_memory_kb,
3271
                killed_at_kb,
3272
                killed: !matches!(
3273
                    outcome,
3274
                    ResourceOutcome::Unknown | ResourceOutcome::Completed
3275
                ),
3276
                now_s: SystemTime::now()
3277
                    .duration_since(UNIX_EPOCH)
3278
0
                    .map_or(0, |d| d.as_secs()),
3279
            };
3280
            sketch.observe(key, &observation);
3281
        }
3282
3283
        let Some(origin_event_tx) = self.maybe_origin_event_tx.as_ref() else {
3284
            return Ok(());
3285
        };
3286
        let Some(action_info) = maybe_action_info else {
3287
            return Ok(());
3288
        };
3289
3290
        if resource_usage.operation_id.is_empty() {
3291
            resource_usage.operation_id = operation_id.to_string();
3292
        }
3293
        if resource_usage.worker_id.is_empty() {
3294
            resource_usage.worker_id = worker_id.to_string();
3295
        }
3296
3297
        let event = Event {
3298
            event: Some(event::Event::Response(ResponseEvent {
3299
                event: Some(response_event::Event::ActionResourceUsage(resource_usage)),
3300
            })),
3301
        };
3302
        let origin_event = OriginEvent {
3303
            version: 0,
3304
            event_id: Uuid::now_v6(&get_node_id(Some(&event)))
3305
                .hyphenated()
3306
                .to_string(),
3307
            parent_event_id: action_info
3308
                .scheduler_start_execute_event_id
3309
                .clone()
3310
                .unwrap_or_default(),
3311
            bazel_request_metadata: action_info.origin_metadata.bazel_metadata.clone(),
3312
            identity: action_info.origin_metadata.identity,
3313
            event: Some(event),
3314
        };
3315
        // Awaited send (not try_send): apply backpressure when the publisher
3316
        // queue is full instead of silently dropping the resource-usage event,
3317
        // which is what drives action-level resource sizing in the UI.
3318
        if let Err(err) = origin_event_tx.send(origin_event).await {
3319
            warn!(?err, "Failed to publish action resource usage origin event");
3320
        }
3321
        Ok(())
3322
18
    }
3323
3324
2.36k
    async fn add_worker(&self, worker: Worker) -> Result<(), Error> {
3325
        let worker_id = worker.id.clone();
3326
        let worker_timestamp = worker.last_update_timestamp;
3327
        let mut inner = self.inner.lock().await;
3328
        if inner.shutting_down {
3329
            warn!("Rejected worker add during shutdown: {}", worker_id);
3330
            return Err(make_err!(
3331
                Code::Unavailable,
3332
                "Received request to add worker while shutting down"
3333
            ));
3334
        }
3335
        // A worker that names itself reconnects under the same id, possibly
3336
        // before this scheduler has seen its earlier stream end. That
3337
        // connection is gone either way: its actions requeue as its
3338
        // disconnect would have requeued them.
3339
        if inner
3340
            .workers
3341
            .peek(&worker_id)
3342
7
            .is_some_and(|existing| existing.connection != worker.connection)
3343
        {
3344
            info!(
3345
                ?worker_id,
3346
                "Worker reconnected; ending its earlier connection"
3347
            );
3348
            drop(
3349
                inner
3350
                    .immediate_evict_worker(
3351
                        &worker_id,
3352
                        make_err!(Code::Unavailable, "Worker reconnected"),
3353
                        true,
3354
                        WorkerDisconnectReason::Disconnected,
3355
                    )
3356
                    .await,
3357
            );
3358
        }
3359
        let result = inner
3360
            .add_worker(worker)
3361
            .err_tip(|| "Error while adding worker, removing from pool");
3362
        if let Err(err) = result {
3363
            return Result::<(), _>::Err(err.clone()).merge(
3364
                inner
3365
                    .immediate_evict_worker(&worker_id, err, false, WorkerDisconnectReason::Error)
3366
                    .await,
3367
            );
3368
        }
3369
3370
        let now = UNIX_EPOCH + Duration::from_secs(worker_timestamp);
3371
        self.worker_registry.register_worker(&worker_id, now).await;
3372
3373
        self.metrics.workers_added.fetch_add(1, Ordering::Relaxed);
3374
        Ok(())
3375
2.36k
    }
3376
3377
    async fn update_action(
3378
        &self,
3379
        worker_id: &WorkerId,
3380
        operation_id: &OperationId,
3381
        update: UpdateOperationType,
3382
25.4k
    ) -> Result<(), Error> {
3383
        let mut inner = self.inner.lock().await;
3384
        let (update, escalated) = inner.maybe_escalate(worker_id, operation_id, update);
3385
        if escalated {
3386
            record_dispatch_requeue("memory_escalation");
3387
        }
3388
        inner.update_action(worker_id, operation_id, update).await
3389
25.4k
    }
3390
3391
    async fn worker_dispatch_accepted(
3392
        &self,
3393
        worker_id: &WorkerId,
3394
        operation_id: &OperationId,
3395
14.3k
    ) -> Result<(), Error> {
3396
        let mut inner = self.inner.lock().await;
3397
        inner.dispatch_accepted(worker_id, operation_id);
3398
        Ok(())
3399
14.3k
    }
3400
3401
    async fn worker_dispatch_declined(
3402
        &self,
3403
        worker_id: &WorkerId,
3404
        operation_id: &OperationId,
3405
        reason: String,
3406
        needs_kb: Option<u64>,
3407
10
    ) -> Result<(), Error> {
3408
        let mut inner = self.inner.lock().await;
3409
        // Counted once the action is back in the queue, not per message.
3410
        if inner
3411
            .dispatch_declined(worker_id, operation_id, reason, needs_kb)
3412
            .await?
3413
        {
3414
            self.metrics
3415
                .dispatches_declined
3416
                .fetch_add(1, Ordering::Relaxed);
3417
            record_dispatch_requeue("declined");
3418
        }
3419
        Ok(())
3420
10
    }
3421
3422
    async fn worker_keep_alive_received(
3423
        &self,
3424
        worker_id: &WorkerId,
3425
        timestamp: WorkerTimestamp,
3426
        load: Option<WorkerLoad>,
3427
25.7k
    ) -> Result<(), Error> {
3428
        self.refresh_worker(worker_id, timestamp, load, true).await
3429
25.7k
    }
3430
3431
    async fn worker_running_operations_reported(
3432
        &self,
3433
        worker_id: &WorkerId,
3434
        operation_ids: Vec<OperationId>,
3435
25.5k
    ) -> Result<(), Error> {
3436
        let reported: HashSet<OperationId> = operation_ids.into_iter().collect();
3437
        let mut inner = self.inner.lock().await;
3438
        inner
3439
            .running_operations_reported(worker_id, &reported)
3440
            .await;
3441
        Ok(())
3442
25.5k
    }
3443
3444
    async fn worker_operation_memory_reported(
3445
        &self,
3446
        worker_id: &WorkerId,
3447
        peaks: Vec<(OperationId, u64)>,
3448
21
    ) -> Result<(), Error> {
3449
        if peaks.is_empty() {
3450
            return Ok(());
3451
        }
3452
        self.inner
3453
            .lock()
3454
            .await
3455
            .operation_memory_reported(worker_id, peaks);
3456
        Ok(())
3457
21
    }
3458
3459
    async fn worker_liveness_refreshed(
3460
        &self,
3461
        worker_id: &WorkerId,
3462
        timestamp: WorkerTimestamp,
3463
38.0k
    ) -> Result<(), Error> {
3464
        self.refresh_worker(worker_id, timestamp, None, false).await
3465
38.0k
    }
3466
3467
63.5k
    async fn worker_message_received(&self, worker_id: &WorkerId, timestamp: WorkerTimestamp) {
3468
        // The registry has a lock of its own, so this does not wait behind
3469
        // whatever the scheduler's lock is held for. The timeout sweep
3470
        // reads it before it evicts.
3471
        self.worker_registry
3472
            .worker_heard_from(worker_id, UNIX_EPOCH + Duration::from_secs(timestamp))
3473
            .await;
3474
63.5k
    }
3475
3476
21
    async fn remove_worker(&self, worker_id: &WorkerId) -> Result<(), Error> {
3477
        self.worker_registry.remove_worker(worker_id).await;
3478
3479
        let mut inner = self.inner.lock().await;
3480
        inner
3481
            .immediate_evict_worker(
3482
                worker_id,
3483
                make_err!(Code::Internal, "Received request to remove worker"),
3484
                false,
3485
                WorkerDisconnectReason::Removed,
3486
            )
3487
            .await
3488
21
    }
3489
3490
    async fn worker_result_settled(
3491
        &self,
3492
        worker_id: &WorkerId,
3493
        operation_id: &OperationId,
3494
12.5k
    ) -> Result<(), Error> {
3495
        let mut inner = self.inner.lock().await;
3496
        let Some(worker) = inner.workers.peek_mut(worker_id) else {
3497
            return Ok(());
3498
        };
3499
        if worker.id_chosen_by != WorkerIdChosenBy::Worker {
3500
            return Ok(());
3501
        }
3502
        // A worker that does not hear it sends the result again later, and
3503
        // is acknowledged then.
3504
        if let Err(err) = worker
3505
            .notify_update(WorkerUpdate::ResultAccepted(operation_id.clone()))
3506
            .await
3507
        {
3508
            debug!(?worker_id, %operation_id, ?err, "Could not acknowledge a result");
3509
        }
3510
        Ok(())
3511
12.5k
    }
3512
3513
    async fn worker_disconnected(
3514
        &self,
3515
        worker_id: &WorkerId,
3516
        connection: u64,
3517
1.26k
    ) -> Result<(), Error> {
3518
        let mut inner = self.inner.lock().await;
3519
        if inner
3520
            .workers
3521
            .peek(worker_id)
3522
796
            .is_some_and(|worker| worker.connection != connection)
3523
        {
3524
            debug!(
3525
                ?worker_id,
3526
                connection, "An earlier connection of a reconnected worker ended"
3527
            );
3528
            return Ok(());
3529
        }
3530
        self.worker_registry.remove_worker(worker_id).await;
3531
        inner
3532
            .immediate_evict_worker(
3533
                worker_id,
3534
                make_err!(Code::Unavailable, "Worker stream ended without going away"),
3535
                true,
3536
                WorkerDisconnectReason::Disconnected,
3537
            )
3538
            .await
3539
1.26k
    }
3540
3541
0
    async fn shutdown(&self, shutdown_guard: ShutdownGuard) {
3542
        let mut inner = self.inner.lock().await;
3543
        inner.shutting_down = true; // should reject further worker registration
3544
        while let Some(worker_id) = inner
3545
            .workers
3546
            .peek_lru()
3547
0
            .map(|(worker_id, _worker)| worker_id.clone())
3548
        {
3549
            if let Err(err) = inner
3550
                .immediate_evict_worker(
3551
                    &worker_id,
3552
                    make_err!(Code::Internal, "Scheduler shutdown"),
3553
                    true,
3554
                    WorkerDisconnectReason::Shutdown,
3555
                )
3556
                .await
3557
            {
3558
                error!(?err, "Error evicting worker on shutdown.");
3559
            }
3560
        }
3561
        drop(shutdown_guard);
3562
0
    }
3563
3564
11.2k
    async fn remove_timedout_workers(&self, now_timestamp: WorkerTimestamp) -> Result<(), Error> {
3565
        // Check worker liveness using both the local timestamp (from LRU)
3566
        // and the worker registry. A worker is alive if either source says it's alive.
3567
        let timeout = Duration::from_secs(self.worker_timeout_s);
3568
        let now = UNIX_EPOCH + Duration::from_secs(now_timestamp);
3569
        let timeout_threshold = now_timestamp.saturating_sub(self.worker_timeout_s);
3570
        // Runs every second; the leases are renewed every third of the
3571
        // worker timeout.
3572
        self.worker_registry
3573
            .renew_leases(&self.scheduler_id, timeout, now)
3574
            .await;
3575
3576
        let workers_to_check: Vec<(WorkerId, bool, bool)> = {
3577
            let inner = self.inner.lock().await;
3578
            inner
3579
                .workers
3580
                .iter()
3581
68.3k
                .map(|(worker_id, worker)| {
3582
68.3k
                    let local_alive = worker.last_update_timestamp > timeout_threshold;
3583
68.3k
                    let kill_overdue = worker.running_action_infos.values().any(|info| 
{50.7k
3584
50.7k
                        info.kill_requested_at.is_some_and(|at| 
{4
3585
4
                            now_timestamp.saturating_sub(at) > self.unacknowledged_kill_timeout_s
3586
4
                        })
3587
50.7k
                    });
3588
68.3k
                    (worker_id.clone(), local_alive, kill_overdue)
3589
68.3k
                })
3590
                .collect()
3591
        };
3592
3593
        let mut worker_ids_to_remove = Vec::new();
3594
        for (worker_id, local_alive, kill_overdue) in workers_to_check {
3595
            // A healthy worker acknowledges a kill in moments; one that
3596
            // cannot is wedged, and its keepalives keep the liveness checks
3597
            // below from ever firing while the dead operation holds its
3598
            // slot (the nativelink#2672 symptom). Evicting requeues its
3599
            // other operations.
3600
            if kill_overdue {
3601
                warn!(
3602
                    ?worker_id,
3603
                    unacknowledged_kill_timeout_s = self.unacknowledged_kill_timeout_s,
3604
                    "Worker did not acknowledge a kill in time, removing from pool"
3605
                );
3606
                worker_ids_to_remove.push((worker_id, true));
3607
                continue;
3608
            }
3609
3610
            if local_alive {
3611
                continue;
3612
            }
3613
3614
            let registry_alive = self
3615
                .worker_registry
3616
                .is_worker_alive(&worker_id, timeout, now)
3617
                .await;
3618
3619
            if !registry_alive {
3620
                trace!(
3621
                    ?worker_id,
3622
                    local_alive,
3623
                    registry_alive,
3624
                    timeout_threshold,
3625
                    "Worker timed out - neither local nor registry shows alive"
3626
                );
3627
                worker_ids_to_remove.push((worker_id, false));
3628
            }
3629
        }
3630
3631
        if worker_ids_to_remove.is_empty() {
3632
            return Ok(());
3633
        }
3634
3635
        let mut inner = self.inner.lock().await;
3636
        let mut result = Ok(());
3637
3638
        for (worker_id, kill_overdue) in &worker_ids_to_remove {
3639
            let err = if *kill_overdue {
3640
                make_err!(
3641
                    Code::Internal,
3642
                    "Worker {worker_id} did not acknowledge a kill within {}s, removing from pool",
3643
                    self.unacknowledged_kill_timeout_s
3644
                )
3645
            } else {
3646
                warn!(?worker_id, "Worker timed out, removing from pool");
3647
                make_err!(
3648
                    Code::Internal,
3649
                    "Worker {worker_id} timed out, removing from pool"
3650
                )
3651
            };
3652
            let reason = if *kill_overdue {
3653
                WorkerDisconnectReason::KillUnacknowledged
3654
            } else {
3655
                WorkerDisconnectReason::Timeout
3656
            };
3657
            result = result.merge(
3658
                inner
3659
                    .immediate_evict_worker(worker_id, err, false, reason)
3660
                    .await,
3661
            );
3662
        }
3663
3664
        result
3665
11.2k
    }
3666
3667
22
    async fn worker_snapshot(&self) -> Vec<WorkerSummary> {
3668
70
        fn as_strings(properties: &PlatformProperties) -> HashMap<String, String> {
3669
70
            properties
3670
70
                .properties
3671
70
                .iter()
3672
70
                .map(|(name, value)| 
{8
3673
8
                    let value = match value {
3674
8
                        PlatformPropertyValue::Minimum(v) => v.to_string(),
3675
0
                        PlatformPropertyValue::Exact(v)
3676
0
                        | PlatformPropertyValue::Priority(v)
3677
0
                        | PlatformPropertyValue::Ignore(v)
3678
0
                        | PlatformPropertyValue::Unknown(v) => v.clone(),
3679
                    };
3680
8
                    (name.clone(), value)
3681
8
                })
3682
70
                .collect()
3683
70
        }
3684
        let inner = self.inner.lock().await;
3685
        inner
3686
            .workers
3687
            .iter()
3688
            .map(|(_, worker)| WorkerSummary {
3689
35
                id: worker.id.to_string(),
3690
35
                running_actions: u32::try_from(worker.running_action_infos.len())
3691
35
                    .unwrap_or(u32::MAX),
3692
35
                max_inflight_tasks: worker.max_inflight_tasks,
3693
35
                is_paused: worker.is_paused,
3694
35
                is_draining: worker.is_draining,
3695
35
                last_update_timestamp: worker.last_update_timestamp,
3696
35
                platform_properties: as_strings(&worker.total_platform_properties),
3697
35
                available_platform_properties: as_strings(&worker.platform_properties),
3698
35
                free_memory_kb: worker.last_load.map(|load| load.free_memory_kb),
3699
35
            })
3700
            .collect()
3701
22
    }
3702
3703
10
    async fn set_drain_worker(&self, worker_id: &WorkerId, is_draining: bool) -> Result<(), Error> {
3704
        let mut inner = self.inner.lock().await;
3705
        inner.set_drain_worker(worker_id, is_draining)
3706
10
    }
3707
3708
2.34k
    async fn kill_revoked_operations(&self) -> Result<(), Error> {
3709
        let (worker_state_manager, running) = {
3710
            let inner = self.inner.lock().await;
3711
            let running: Vec<(WorkerId, OperationId)> = inner
3712
                .workers
3713
                .iter()
3714
13.3k
                .flat_map(|(worker_id, worker)| {
3715
13.3k
                    worker
3716
13.3k
                        .running_action_infos
3717
13.3k
                        .iter()
3718
                        // An operation already told to die is never swept
3719
                        // again; the kill itself is not re-sent. A worker
3720
                        // that received the kill but never reports back is
3721
                        // evicted by remove_timedout_workers once the kill
3722
                        // has gone unacknowledged longer than
3723
                        // `unacknowledged_kill_timeout_s`; a dead worker by
3724
                        // the ordinary keepalive timeout.
3725
13.3k
                        .filter(|(_, pending_action_info)| 
{10.5k
3726
10.5k
                            pending_action_info.kill_requested_at.is_none()
3727
10.5k
                        })
3728
13.3k
                        .map(|(operation_id, _)| (
worker_id10.5k
.
clone10.5k
(),
operation_id10.5k
.
clone10.5k
()))
3729
13.3k
                })
3730
                .collect();
3731
            (inner.worker_state_manager.clone(), running)
3732
        };
3733
3734
        // On store-backed deployments each check is a network round-trip,
3735
        // so run them lock-free with bounded concurrency.
3736
        let revoked: Vec<(WorkerId, OperationId)> = futures::stream::iter(running)
3737
10.5k
            .map(|(worker_id, operation_id)| {
3738
10.5k
                let worker_state_manager = worker_state_manager.clone();
3739
10.5k
                async move {
3740
10.5k
                    match worker_state_manager
3741
10.5k
                        .is_executing_on_worker(&operation_id, &worker_id)
3742
10.5k
                        .await
3743
                    {
3744
10.3k
                        Ok(true) => None,
3745
11
                        Ok(false) => Some((worker_id, operation_id)),
3746
                        // Only kill on positive evidence; try again next pass.
3747
203
                        Err(err) => {
3748
203
                            warn!(
3749
                                ?worker_id,
3750
                                %operation_id,
3751
                                ?err,
3752
                                "Could not check whether operation is still executing on worker"
3753
                            );
3754
203
                            None
3755
                        }
3756
                    }
3757
10.5k
                }
3758
10.5k
            })
3759
            .buffer_unordered(MAX_CONCURRENT_REVOKED_CHECKS)
3760
            .filter_map(future::ready)
3761
            .collect()
3762
            .await;
3763
3764
        if revoked.is_empty() {
3765
            return Ok(());
3766
        }
3767
3768
        // Re-check lock-free so the scheduler mutex is never held across
3769
        // store I/O; the checks above may be stale by the time we get here.
3770
        // The remaining TOCTOU window is fine: worker_notify_kill_operation
3771
        // re-guards with contains_key + is_kill_requested under the lock.
3772
        let mut confirmed = Vec::new();
3773
        for (worker_id, operation_id) in revoked {
3774
            // A result of Ok(true) or Err(_) means the operation was
3775
            // reassigned to this worker after the first check, or the state
3776
            // manager went quiet: nothing to kill on this pass.
3777
            let revoked = worker_state_manager
3778
                .is_executing_on_worker(&operation_id, &worker_id)
3779
                .await
3780
11
                .is_ok_and(|executing| !executing);
3781
            if revoked {
3782
                confirmed.push((worker_id, operation_id));
3783
            }
3784
        }
3785
3786
        if confirmed.is_empty() {
3787
            return Ok(());
3788
        }
3789
3790
        let mut inner = self.inner.lock().await;
3791
        let mut result = Ok(());
3792
        for (worker_id, operation_id) in confirmed {
3793
            result = result.merge(
3794
                inner
3795
                    .worker_notify_kill_operation(&worker_id, operation_id)
3796
                    .await,
3797
            );
3798
        }
3799
        result
3800
2.34k
    }
3801
}
3802
3803
impl RootMetricsComponent for ApiWorkerScheduler {}
3804
3805
#[cfg(test)]
3806
mod peer_census_trusted_tests {
3807
    use super::{Duration, SystemTime, UNIX_EPOCH, peer_census_trusted};
3808
3809
    const TTL: Duration = Duration::from_secs(15);
3810
23
    fn at(secs: u64) -> SystemTime {
3811
23
        UNIX_EPOCH + Duration::from_secs(1000 + secs)
3812
23
    }
3813
3814
    #[test]
3815
1
    fn unknown_census_is_never_trusted() {
3816
        // Even a non-shared db, if explicitly unknown, is not trusted.
3817
1
        assert!(!peer_census_trusted(false, false, None, None, TTL, at(0)));
3818
1
        assert!(!peer_census_trusted(
3819
1
            true,
3820
1
            false,
3821
1
            Some(at(0)),
3822
1
            Some(at(0)),
3823
1
            TTL,
3824
1
            at(100)
3825
1
        ));
3826
1
    }
3827
3828
    #[test]
3829
1
    fn non_shared_known_is_trusted_immediately() {
3830
        // The whole fleet is local; no warm-up or staleness applies.
3831
1
        assert!(peer_census_trusted(false, true, None, None, TTL, at(0)));
3832
1
    }
3833
3834
    #[test]
3835
1
    fn shared_known_needs_both_timestamps() {
3836
1
        assert!(!peer_census_trusted(true, true, None, None, TTL, at(100)));
3837
1
        assert!(!peer_census_trusted(
3838
1
            true,
3839
1
            true,
3840
1
            Some(at(0)),
3841
1
            None,
3842
1
            TTL,
3843
1
            at(100)
3844
1
        ));
3845
1
    }
3846
3847
    #[test]
3848
1
    fn shared_trusts_only_when_warm_and_fresh() {
3849
        // Known at 0, refreshed at 100, evaluated at 100: warm and fresh.
3850
1
        assert!(peer_census_trusted(
3851
            true,
3852
            true,
3853
1
            Some(at(0)),
3854
1
            Some(at(100)),
3855
            TTL,
3856
1
            at(100)
3857
        ));
3858
        // Exactly one TTL since known counts as warm.
3859
1
        assert!(peer_census_trusted(
3860
            true,
3861
            true,
3862
1
            Some(at(0)),
3863
1
            Some(at(15)),
3864
            TTL,
3865
1
            at(15)
3866
        ));
3867
1
    }
3868
3869
    #[test]
3870
1
    fn shared_not_warm_is_not_trusted() {
3871
        // Known only half a TTL ago: a peer may not have published yet.
3872
1
        assert!(!peer_census_trusted(
3873
1
            true,
3874
1
            true,
3875
1
            Some(at(0)),
3876
1
            Some(at(7)),
3877
1
            TTL,
3878
1
            at(7)
3879
1
        ));
3880
1
    }
3881
3882
    #[test]
3883
1
    fn shared_stale_refresh_is_not_trusted() {
3884
        // Warm, but the last successful exchange was more than a TTL ago (the
3885
        // exchange task died/stalled): fail open.
3886
1
        assert!(!peer_census_trusted(
3887
1
            true,
3888
1
            true,
3889
1
            Some(at(0)),
3890
1
            Some(at(50)),
3891
1
            TTL,
3892
1
            at(100)
3893
1
        ));
3894
1
    }
3895
3896
    #[test]
3897
1
    fn future_dated_refresh_counts_as_fresh() {
3898
        // Clock skew: a refresh timestamped ahead of `now` is treated as fresh
3899
        // (the safe direction). Still requires warm.
3900
1
        assert!(peer_census_trusted(
3901
            true,
3902
            true,
3903
1
            Some(at(0)),
3904
1
            Some(at(120)),
3905
            TTL,
3906
1
            at(100)
3907
        ));
3908
1
    }
3909
}