Coverage Report

Created: 2026-11-13 23:29

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/build/source/nativelink-config/src/schedulers.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 std::collections::HashMap;
16
17
#[cfg(feature = "dev-schema")]
18
use schemars::JsonSchema;
19
use serde::{Deserialize, Serialize};
20
21
use crate::serde_utils::{
22
    convert_data_size_with_shellexpand, convert_duration_with_shellexpand,
23
    convert_duration_with_shellexpand_and_negative, convert_numeric_with_shellexpand,
24
    convert_optional_numeric_with_shellexpand, convert_string_with_shellexpand,
25
};
26
use crate::stores::{GrpcEndpoint, Retry, StoreRefName};
27
28
#[derive(Deserialize, Serialize, Debug)]
29
#[serde(rename_all = "snake_case")]
30
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
31
pub enum SchedulerSpec {
32
    Simple(SimpleSpec),
33
    Grpc(GrpcSpec),
34
    CacheLookup(CacheLookupSpec),
35
    PropertyModifier(PropertyModifierSpec),
36
    HistoricalResource(HistoricalResourceSpec),
37
}
38
39
/// When the scheduler matches tasks to workers that are capable of running
40
/// the task, this value will be used to determine how the property is treated.
41
#[derive(Deserialize, Serialize, Debug, Clone, Copy, Hash, Eq, PartialEq)]
42
#[serde(rename_all = "snake_case")]
43
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
44
pub enum PropertyType {
45
    /// Requires the platform property to be a u64 and when the scheduler looks
46
    /// for appropriate worker nodes that are capable of executing the task,
47
    /// the task will not run on a node that has less than this value.
48
    Minimum,
49
50
    /// Requires the platform property to be a string and when the scheduler
51
    /// looks for appropriate worker nodes that are capable of executing the
52
    /// task, the task will not run on a node that does not have this property
53
    /// set to the value with exact string match.
54
    Exact,
55
56
    /// Does not restrict on this value and instead will be passed to the worker
57
    /// as an informational piece.
58
    /// TODO(palfrey) In the future this will be used by the scheduler and worker
59
    /// to cause the scheduler to prefer certain workers over others, but not
60
    /// restrict them based on these values.
61
    Priority,
62
63
    //// Allows jobs to be requested with said key, but without requiring workers
64
    //// to have that key
65
    Ignore,
66
}
67
68
/// When a worker is being searched for to run a job, this will be used
69
/// on how to choose which worker should run the job when multiple
70
/// workers are able to run the task.
71
#[derive(Copy, Clone, Deserialize, Serialize, Debug, Default)]
72
#[serde(rename_all = "snake_case")]
73
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
74
pub enum WorkerAllocationStrategy {
75
    /// Prefer workers that have been least recently used to run a job.
76
    #[default]
77
    LeastRecentlyUsed,
78
    /// Prefer workers that have been most recently used to run a job.
79
    MostRecentlyUsed,
80
    /// Prefer the worker running the fewest actions, least recently used
81
    /// among equals. A worker that just joined has nothing running, so it
82
    /// takes the next action instead of waiting for every older worker to
83
    /// be used once more, and a burst spreads across the fleet instead of
84
    /// filling one worker to its concurrency cap.
85
    LeastLoaded,
86
    /// Prefer the worker the action fits most tightly: among the workers
87
    /// that can take it, the one whose remaining `minimum` properties
88
    /// (memory, CPU) would be smallest afterwards, as a share of what it
89
    /// advertises. Big actions are kept for the workers with big room and
90
    /// small ones fill the gaps, so a fleet of mixed sizes wastes the
91
    /// least. A `priority` property on the action that a worker carries
92
    /// with the same value prefers that worker before the fit is judged,
93
    /// which is what such a property is for (a zone, a cache locality).
94
    /// Ties go to the fewest running actions, then least recently used.
95
    BestFit,
96
}
97
98
// Disabled by default: each log lists every queued and executing operation
99
// from the scheduler's store, on every replica, which on a shared Redis is
100
// a full index read per interval per replica.
101
18
const fn default_worker_match_logging_interval_s() -> i64 {
102
18
    -1
103
18
}
104
105
// defaults to every 5s
106
20
const fn default_fallback_match_interval_s() -> i64 {
107
20
    5
108
20
}
109
110
// defaults to every 30s
111
20
const fn default_executing_sweep_interval_s() -> i64 {
112
20
    30
113
20
}
114
115
#[derive(Deserialize, Serialize, Debug, Default)]
116
#[serde(deny_unknown_fields)]
117
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
118
pub struct SimpleSpec {
119
    /// A list of supported platform properties mapped to how these properties
120
    /// are used when the scheduler looks for worker nodes capable of running
121
    /// the task.
122
    ///
123
    /// For example, a value of:
124
    /// ```json
125
    /// { "cpu_count": "minimum", "cpu_arch": "exact" }
126
    /// ```
127
    /// With a job that contains:
128
    /// ```json
129
    /// { "cpu_count": "8", "cpu_arch": "arm" }
130
    /// ```
131
    /// Will result in the scheduler filtering out any workers that do not have
132
    /// `"cpu_arch" = "arm"` and filter out any workers that have less than 8 CPU
133
    /// cores available.
134
    ///
135
    /// The property names here must match the property keys provided by the
136
    /// worker nodes when they join the pool. In other words, the workers will
137
    /// publish their capabilities to the scheduler when they join the worker
138
    /// pool. If the worker fails to notify the scheduler of its (for example)
139
    /// `"cpu_arch"`, the scheduler will never send any jobs to it, if all jobs
140
    /// have the `"cpu_arch"` label. We have no special treatment of any platform
141
    /// property labels other and entirely driven by worker configs and this
142
    /// config.
143
    ///
144
    /// Properties that are not listed here are matched dynamically: workers
145
    /// that declare the key must match the value exactly, and workers that do
146
    /// not declare the key are not restricted by it. List a property here to
147
    /// enforce stricter matching.
148
    pub supported_platform_properties: Option<HashMap<String, PropertyType>>,
149
150
    /// The amount of time to retain completed actions for in case
151
    /// a `WaitExecution` is called after the action has completed.
152
    /// Default: 60 seconds
153
    #[serde(default, deserialize_with = "convert_duration_with_shellexpand")]
154
    pub retain_completed_for_s: u32,
155
156
    /// Mark operations as completed with error if no client has updated them
157
    /// within this duration.
158
    /// Default: 60 seconds
159
    #[serde(default, deserialize_with = "convert_duration_with_shellexpand")]
160
    pub client_action_timeout_s: u64,
161
162
    /// Periodically count the actions in each stage and report them as the
163
    /// `execution.active.count` metric.
164
    ///
165
    /// Only has an effect when scheduler state lives in a store, which today
166
    /// means Redis; the in-memory scheduler always maintains this count because
167
    /// it already holds the state in process. The count is a query against the
168
    /// scheduler store every 15 seconds from every scheduler replica, so it
169
    /// adds load to the same backend that serves action scheduling. Leave it
170
    /// off unless you want the metric.
171
    ///
172
    /// Every replica reports the same store-wide totals, so aggregate the
173
    /// series across replicas with `max`, not `sum`.
174
    /// Default: false
175
    #[serde(default)]
176
    pub enable_active_action_count_metric: bool,
177
178
    /// Remove workers from pool once the worker has not responded in this
179
    /// amount of time in seconds. Any message from the worker counts, not
180
    /// only keepalives. Eviction requeues everything the worker held, so
181
    /// keep this well above the longest pause a loaded worker can see.
182
    /// Default: 10 seconds (four default keepalive intervals)
183
    #[serde(default, deserialize_with = "convert_duration_with_shellexpand")]
184
    pub worker_timeout_s: u64,
185
186
    /// Maximum time (seconds) an action can stay in Executing state without
187
    /// any worker update before being timed out and re-queued.
188
    /// This applies regardless of worker keepalive status, catching cases
189
    /// where a worker is alive (sending keepalives) but stuck on a specific
190
    /// action. Set to 0 to disable (relies only on `worker_timeout_s`).
191
    ///
192
    /// Default: 0 (disabled)
193
    #[serde(default, deserialize_with = "convert_duration_with_shellexpand")]
194
    pub max_action_executing_timeout_s: u64,
195
196
    /// How often the scheduler sweeps executing actions for ones to retire:
197
    /// an action past `max_action_executing_timeout_s` (or its own
198
    /// `Action.timeout` plus `worker_timeout_s`) with no word from its
199
    /// worker, and an action whose worker is connected to this scheduler but
200
    /// no longer runs it, which means its result was lost on the way to the
201
    /// store. Without the sweep those checks run only inside a client's
202
    /// `Execute` or `WaitExecution` call, once per `worker_timeout_s`, and never
203
    /// once the client has gone.
204
    /// Defaults to 30s. Zero or any negative value disables it.
205
    #[serde(
206
        default = "default_executing_sweep_interval_s",
207
        deserialize_with = "convert_duration_with_shellexpand_and_negative"
208
    )]
209
    pub executing_sweep_interval_s: i64,
210
211
    /// Evict a worker that has not reported back on an operation it was
212
    /// told to kill within this many seconds. A healthy worker
213
    /// acknowledges a kill in moments; one that cannot is wedged, and its
214
    /// keepalives would otherwise keep `worker_timeout_s` from ever firing
215
    /// while the dead operation holds its slot. Eviction requeues the
216
    /// worker's other operations.
217
    /// Default: 60 seconds
218
    #[serde(default, deserialize_with = "convert_duration_with_shellexpand")]
219
    pub unacknowledged_kill_timeout_s: u64,
220
221
    /// Requeue a dispatched action the worker has not acknowledged within
222
    /// this many seconds, untried and without counting an attempt, and
223
    /// pause the worker. The clock is the worker's own messages: a dispatch
224
    /// is dated by the worker's last message before it, and the check runs
225
    /// on each later message, so keep this above a few keepalive intervals.
226
    /// Workers from v1.7.3 acknowledge every dispatch;
227
    /// older workers never do, so leave this unset while any are
228
    /// connected or their every action would be requeued.
229
    /// Default: unset (off)
230
    #[serde(default, deserialize_with = "convert_duration_with_shellexpand")]
231
    pub dispatch_ack_timeout_s: u64,
232
233
    /// Fail a queued action once no connected worker has been able to run
234
    /// it for this many seconds, instead of leaving it queued forever. An
235
    /// action counts as impossible to run when no connected worker could
236
    /// take it even when idle: an `exact` value no worker has, a required
237
    /// key no worker declares, or a `minimum` larger than any worker's
238
    /// total. An action that is only waiting for a busy worker is never
239
    /// failed by this setting, and neither is any action while no workers
240
    /// are connected at all.
241
    ///
242
    /// The action fails with `FAILED_PRECONDITION` and a message naming the
243
    /// properties that could not be satisfied. Bazel does not retry this,
244
    /// and runs the action locally if `--remote_local_fallback` is set.
245
    ///
246
    /// The time is measured per distinct set of platform properties, and
247
    /// each action must also have been queued for this long itself before
248
    /// it is failed. Actions that queue together therefore fail within
249
    /// about one timeout of each other, while during a pool outage later
250
    /// actions fail as they age rather than in an immediate burst. An
251
    /// action's own wait is measured from its original submission, which
252
    /// is not reset when a second client attaches to the same action or
253
    /// when it is queued again after its worker is lost; in those cases
254
    /// the per-shape clock still guarantees no capable worker was seen for
255
    /// the full timeout before it is failed.
256
    ///
257
    /// Roll this out with the timeout at 0 on every scheduler first and
258
    /// watch the `scheduler.unsatisfiable.queued` metric for a while:
259
    /// anything that appears there during normal operation is an action
260
    /// this setting would have failed. Then set it above the longest time
261
    /// a worker pool needs to provision or restart, such as scaling up from
262
    /// zero, a rolling restart of the whole pool, or spot preemption, not
263
    /// above the typical queue wait. Only properties listed in
264
    /// `supported_platform_properties` are enforced strictly; a property
265
    /// that is not listed does not restrict workers that do not declare it.
266
    /// The memory backend knows only workers connected to this scheduler.
267
    /// A learned size class is not a promise that its pool is online: a pod
268
    /// being created or Pending does not stop this clock. For pools that
269
    /// scale from zero, leave this at 0 or allow the entire cold start through
270
    /// worker registration, including node creation and image downloads.
271
    /// Redis peer exchange below also describes connected workers, not
272
    /// provisioner pool templates. It does not solve this cold-start gap.
273
    ///
274
    /// When several schedulers share one Redis backend, each publishes what
275
    /// its workers can run whenever a worker joins or leaves and at least
276
    /// every 5 seconds, and reads what the others publish every 5 seconds.
277
    /// An action is only failed when no scheduler has a worker that could
278
    /// run it, and never while the other schedulers cannot be read. A
279
    /// worker that joins or leaves a peer is seen here within about 5
280
    /// seconds, and the workers of a peer that stops altogether stop
281
    /// counting within about 20, so keep this well above that. Schedulers
282
    /// publish whatever this is set to, so roll out a version that has this
283
    /// setting to every scheduler before setting it on any of them.
284
    /// (The 5 and 20 seconds follow from `FLEET_EXCHANGE_INTERVAL` and
285
    /// `FLEET_RECORD_TTL_INTERVALS` in the scheduler; if those change,
286
    /// remember to change this documentation.)
287
    ///
288
    /// Such actions are logged and counted in the
289
    /// `scheduler.unsatisfiable.queued` metric whatever this is set to.
290
    ///
291
    /// Default: 0 (never fail)
292
    #[serde(default, deserialize_with = "convert_duration_with_shellexpand")]
293
    pub unsatisfiable_action_timeout_s: u64,
294
295
    /// Seconds a queued action waits while no worker at all is connected to
296
    /// this scheduler, nor, on a shared backend, to any peer, before it
297
    /// fails with `FailedPrecondition`. `unsatisfiable_action_timeout_s`
298
    /// only runs against workers that are there, so a pool that scales from
299
    /// zero is never failed on sight; but a provisioner that will not create
300
    /// a pod for a shape it cannot serve leaves such an action waiting for
301
    /// a fleet that never comes, and this is the bound on that. Keep it
302
    /// above the longest time a pool needs to bring up its first worker.
303
    /// Default: 0 (never fail)
304
    #[serde(default, deserialize_with = "convert_duration_with_shellexpand")]
305
    pub no_worker_action_timeout_s: u64,
306
307
    /// If a job returns an internal error or times out this many times the
308
    /// scheduler completes it with `FailedPrecondition` carrying the last
309
    /// error, a code clients do not retry. This is to help prevent one rogue
310
    /// job from infinitely retrying and taking up a lot of resources when the
311
    /// task itself is the one causing the server to go into a bad state.
312
    /// A lost worker and a memory escalation are not the action's failures
313
    /// and have their own budgets: `max_worker_loss_retries` and
314
    /// `memory_escalation.max_steps`.
315
    /// Default: 3
316
    #[serde(default, deserialize_with = "convert_numeric_with_shellexpand")]
317
    pub max_job_retries: usize,
318
319
    /// How many times an action whose worker was lost (disconnected, timed
320
    /// out, evicted, or OOM-killed as a whole) is queued again before the
321
    /// scheduler completes it with `FailedPrecondition`. A lost worker is
322
    /// usually not the action's fault, so these do not spend
323
    /// `max_job_retries`; the cap only stops an action that takes a worker
324
    /// down every time it runs.
325
    /// Default: 10
326
    #[serde(default, deserialize_with = "convert_numeric_with_shellexpand")]
327
    pub max_worker_loss_retries: usize,
328
329
    /// The strategy used to assign workers jobs.
330
    #[serde(default)]
331
    pub allocation_strategy: WorkerAllocationStrategy,
332
333
    /// The name of a `minimum` platform property, usually `memory_kb`, that
334
    /// the scheduler compares against the free memory each worker reports
335
    /// with its keepalive: a worker reporting less than the action asks for
336
    /// is skipped for that action, whatever the admission ledger says. The
337
    /// ledger only subtracts what actions declare; this catches the ones
338
    /// that declared too little. Workers older than v1.7.3 report nothing
339
    /// and are never vetoed.
340
    /// Default: unset (off)
341
    #[serde(default)]
342
    pub live_memory_veto: Option<String>,
343
344
    /// When a worker reports an action killed for memory (`KILLED_MEMORY`,
345
    /// by its own reservation enforcement or by the kernel), requeue the
346
    /// action with a larger reservation instead of failing it. Escalations
347
    /// have their own budget (`max_steps`) and do not spend
348
    /// `max_job_retries`. The reservation grows to the largest memory any
349
    /// connected worker advertises (or `max_kb`); the last step reserves
350
    /// that worker whole, memory and CPU, so the action runs alone, and only
351
    /// a kill there fails the action: nothing in the fleet could run it.
352
    /// A worker that goes away on its own mid-action (a pod OOM-killed as
353
    /// a whole looks like that) escalates the action the same way: on that
354
    /// loss when the worker's last keepalive showed the action above its
355
    /// reservation, otherwise from `escalate_after_worker_losses`. Such
356
    /// losses still spend
357
    /// `max_worker_loss_retries`.
358
    /// Default: unset (a memory kill fails the action)
359
    #[serde(default)]
360
    pub memory_escalation: Option<MemoryEscalationSpec>,
361
362
    /// Hold a worker for a queued action that keeps finding no room. An
363
    /// action whose reservation only fits an idle worker starves under
364
    /// load: every pass tries it first and finds each worker partly busy,
365
    /// then fills the room that opens with newer, smaller actions, so no
366
    /// worker ever drains for it. With this set, once such an action has
367
    /// waited `hold_after_s` and fits no busy worker until more than one
368
    /// of that worker's actions finish (one finishing would make room for
369
    /// an action that is only waiting its turn), the scheduler picks a
370
    /// worker that would fit it idle and offers it nothing else until a
371
    /// worker takes the action, it leaves the queue, or `max_hold_s`
372
    /// passes. An action no connected worker would fit even idle gets no
373
    /// hold. Each scheduler replica holds only workers connected to it;
374
    /// replicas sharing a queue take turns per action, by a hash of the
375
    /// action over the replicas whose workers would fit it as the fleet
376
    /// census last read them, so one worker is held for it fleet-wide.
377
    /// While a replica cannot read the census it holds on its own.
378
    /// Default: unset (off)
379
    #[serde(default)]
380
    pub reservation_hold: Option<ReservationHoldSpec>,
381
382
    /// How many times an action whose command ran past its timeout on a
383
    /// worker is queued again for a different worker before the timeout
384
    /// is final. A worker whose host has gone slow runs everything it is
385
    /// given many times slower and times out actions that finish in
386
    /// seconds elsewhere, and nothing tells that from an action that is
387
    /// slow by itself until it has run elsewhere: the retry is that second
388
    /// opinion, and the matcher prefers any worker but the one that timed
389
    /// it out. An action that times out on the second worker fails with
390
    /// the timeout, as before. Each retry runs the action again, so this
391
    /// bounds the cost of an action that really is too slow. 0 keeps a
392
    /// timeout final on its first occurrence.
393
    /// The retry also keeps off every worker on the node the timeout
394
    /// happened on, where workers say which node they are on through the
395
    /// `node_name` platform property (the chart's `advertiseNodeName`,
396
    /// off by default). Without it the retry keeps off that worker only
397
    /// and may land on another worker of the same host.
398
    /// Default: 1
399
    #[serde(
400
        default,
401
        deserialize_with = "convert_optional_numeric_with_shellexpand"
402
    )]
403
    pub max_timeout_retries: Option<usize>,
404
405
    /// Drain a worker whose recent attempts keep failing. A worker that
406
    /// times out or errors most of what it is given while the rest of the
407
    /// fleet does not is a bad worker, whatever its host reports; this
408
    /// stops dispatch to it on the scheduler's own evidence, without a
409
    /// probe for the cause. See `WorkerOutcomeTripwireSpec`.
410
    /// Default: unset (off)
411
    #[serde(default)]
412
    pub worker_outcome_tripwire: Option<WorkerOutcomeTripwireSpec>,
413
414
    /// The storage backend to use for the scheduler.
415
    /// Default: memory
416
    pub experimental_backend: Option<ExperimentalSimpleSchedulerBackend>,
417
418
    /// Every N seconds, do logging of worker matching
419
    /// e.g. "worker busy", "can't find any worker", and the oldest queued
420
    /// and executing operations. Each pass lists every queued and executing
421
    /// operation from the store, on every scheduler replica: with a shared
422
    /// Redis that is a full index read per interval per replica, which is
423
    /// why it is off unless asked for. Turn it on for a look, not for good.
424
    /// Defaults to `-1` (disabled). Any positive value enables it.
425
    #[serde(
426
        default = "default_worker_match_logging_interval_s",
427
        deserialize_with = "convert_duration_with_shellexpand_and_negative"
428
    )]
429
    pub worker_match_logging_interval_s: i64,
430
431
    /// Every N seconds, run a worker matching pass even if no task or worker
432
    /// change notification arrived. This is a safety net for missed
433
    /// notifications and for scheduler backends with eventually consistent
434
    /// searches (for example Redis), where an operation that was re-queued
435
    /// may not be visible to the search triggered by its own notification.
436
    /// Without this, such an operation can stay queued until an unrelated
437
    /// event triggers another matching pass.
438
    /// Defaults to 5s. Zero or any negative value disables it.
439
    #[serde(
440
        default = "default_fallback_match_interval_s",
441
        deserialize_with = "convert_duration_with_shellexpand_and_negative"
442
    )]
443
    pub fallback_match_interval_s: i64,
444
}
445
446
#[derive(Deserialize, Serialize, Debug)]
447
#[serde(rename_all = "snake_case")]
448
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
449
pub enum ExperimentalSimpleSchedulerBackend {
450
    /// Use an in-memory store for the scheduler.
451
    Memory,
452
    /// Use a redis store for the scheduler.
453
    Redis(ExperimentalRedisSchedulerBackend),
454
}
455
456
#[derive(Deserialize, Serialize, Debug, Default)]
457
#[serde(deny_unknown_fields)]
458
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
459
pub struct ExperimentalRedisSchedulerBackend {
460
    /// A reference to the redis store to use for the scheduler.
461
    /// Note: This MUST resolve to a `RedisSpec`.
462
    pub redis_store: StoreRefName,
463
}
464
465
/// A scheduler that forwards requests to an upstream scheduler. This
466
/// is useful to use when doing some kind of local action cache or CAS away from
467
/// the main cluster of workers. In general, it's more efficient to point the
468
/// build at the main scheduler directly though.
469
#[derive(Deserialize, Serialize, Debug)]
470
#[serde(deny_unknown_fields)]
471
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
472
pub struct GrpcSpec {
473
    /// The upstream scheduler to forward requests to.
474
    pub endpoint: GrpcEndpoint,
475
476
    /// Retry configuration to use when a network request fails.
477
    #[serde(default)]
478
    pub retry: Retry,
479
480
    /// Limit the number of simultaneous upstream requests to this many. A
481
    /// value of zero is treated as unlimited. If the limit is reached the
482
    /// request is queued.
483
    /// Default: unlimited
484
    #[serde(default, deserialize_with = "convert_numeric_with_shellexpand")]
485
    pub max_concurrent_requests: usize,
486
487
    /// The number of connections to make to each specified endpoint to balance
488
    /// the load over multiple TCP connections.
489
    /// Default: 1.
490
    #[serde(default, deserialize_with = "convert_numeric_with_shellexpand")]
491
    pub connections_per_endpoint: usize,
492
493
    /// Header names to copy from the incoming client request onto every
494
    /// request sent to the upstream scheduler. Use this to pass through
495
    /// dynamic credentials such as a JWT sent by the build client.
496
    ///
497
    /// Example: `["authorization", "x-custom-token"]`
498
    ///
499
    /// The OpenTelemetry trace context and baggage (the client's identity and
500
    /// build metadata) are always forwarded.
501
    #[serde(default)]
502
    pub forward_headers: Vec<String>,
503
}
504
505
#[derive(Deserialize, Serialize, Debug)]
506
#[serde(deny_unknown_fields)]
507
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
508
pub struct CacheLookupSpec {
509
    /// The reference to the action cache store used to return cached
510
    /// actions from rather than running them again.
511
    /// To prevent unintended issues, this store should probably be a `CompletenessCheckingSpec`.
512
    pub ac_store: StoreRefName,
513
514
    /// The nested scheduler to use if cache lookup fails.
515
    pub scheduler: Box<SchedulerSpec>,
516
}
517
518
#[derive(Deserialize, Serialize, Debug, Clone)]
519
#[serde(deny_unknown_fields)]
520
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
521
pub struct PlatformPropertyAddition {
522
    /// The name of the property to add.
523
    pub name: String,
524
    /// The value to assign to the property.
525
    pub value: String,
526
}
527
528
#[derive(Deserialize, Serialize, Debug, Clone)]
529
#[serde(deny_unknown_fields)]
530
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
531
pub struct PlatformPropertyReplacement {
532
    /// The name of the property to replace.
533
    pub name: String,
534
    /// The value to match against, if unset then any instance matches.
535
    #[serde(default)]
536
    pub value: Option<String>,
537
    /// The new name of the property.
538
    pub new_name: String,
539
    /// The value to assign to the property, if unset will remain the same.
540
    #[serde(default)]
541
    pub new_value: Option<String>,
542
}
543
544
#[derive(Deserialize, Serialize, Debug, Clone)]
545
#[serde(rename_all = "snake_case")]
546
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
547
pub enum PropertyModification {
548
    /// Add a property to the action properties.
549
    Add(PlatformPropertyAddition),
550
    /// Remove a named property from the action.
551
    Remove(String),
552
    /// If a property is found, then replace it with another one.
553
    Replace(PlatformPropertyReplacement),
554
}
555
556
#[derive(Deserialize, Serialize, Debug)]
557
#[serde(deny_unknown_fields)]
558
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
559
pub struct PropertyModifierSpec {
560
    /// A list of modifications to perform to incoming actions for the nested
561
    /// scheduler. These are performed in order and blindly, so removing a
562
    /// property that doesn't exist is fine and overwriting an existing property
563
    /// is also fine. If adding properties that do not exist in the nested
564
    /// scheduler is not supported and will likely cause unexpected behaviour.
565
    pub modifications: Vec<PropertyModification>,
566
567
    /// The nested scheduler to use after modifying the properties.
568
    pub scheduler: Box<SchedulerSpec>,
569
}
570
571
4
const fn default_historical_resource_refresh_interval_s() -> u64 {
572
4
    30
573
4
}
574
575
5
const fn default_historical_resource_headroom_percent() -> u64 {
576
5
    20
577
5
}
578
579
5
const fn default_historical_resource_window_days() -> u64 {
580
5
    7
581
5
}
582
583
2
const fn default_historical_resource_memory_budget_bytes() -> u64 {
584
2
    512 * 1024 * 1024
585
2
}
586
587
5
const fn default_historical_resource_snapshot_interval_s() -> u64 {
588
5
    60
589
5
}
590
591
5
fn default_historical_resource_cpu_property_name() -> String {
592
5
    "cpu_count".to_string()
593
5
}
594
595
5
fn default_historical_resource_memory_property_name() -> String {
596
5
    "memory_kb".to_string()
597
5
}
598
599
#[derive(Deserialize, Serialize, Debug, Clone)]
600
#[serde(deny_unknown_fields)]
601
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
602
pub struct MemoryEscalationSpec {
603
    /// The `minimum` platform property carrying the memory reservation.
604
    /// Default: `memory_kb`
605
    #[serde(default = "default_historical_resource_memory_property_name")]
606
    pub property: String,
607
608
    /// Each kill scales the reservation by this factor, in hundredths:
609
    /// 200 doubles it, 150 adds half.
610
    /// Default: 200
611
    #[serde(default = "default_memory_escalation_percent")]
612
    pub percent: u64,
613
614
    /// Never reserve more than this many KiB; 0 takes the largest memory
615
    /// any connected worker advertises.
616
    /// Default: 0
617
    #[serde(default)]
618
    pub max_kb: u64,
619
620
    /// The memory values of the fleet's size classes, ascending, in KiB.
621
    /// When set, a kill steps the reservation to the next class above it
622
    /// instead of scaling by `percent`; past the top class the last step
623
    /// reserves the largest worker whole. The chart fills this from the
624
    /// same classes the `historical_resource` scheduler uses.
625
    /// Default: empty (scale by `percent`)
626
    #[serde(default)]
627
    pub ladder_kb: Vec<u64>,
628
629
    /// The `minimum` platform property carrying the CPU reservation. The
630
    /// last escalation reserves the largest worker's whole memory and,
631
    /// through this property, its whole CPU, so nothing shares the worker
632
    /// with the action. Empty leaves CPU alone.
633
    /// Default: `cpu_count`
634
    #[serde(default = "default_memory_escalation_cpu_property")]
635
    pub cpu_property: String,
636
637
    /// The most escalations one action gets before the scheduler completes
638
    /// it with `FailedPrecondition`; 0 lets the ceiling alone bound them.
639
    /// Escalations on a lost worker spend the same budget, but spending it
640
    /// there does not end the action: it is queued again at its last
641
    /// reservation, and `max_worker_loss_retries` ends it if its workers
642
    /// keep going away.
643
    /// Default: 8
644
    #[serde(default = "default_memory_escalation_max_steps")]
645
    pub max_steps: u64,
646
647
    /// From the how-manyth worker lost under one action the requeue also
648
    /// raises its reservation, the way a memory kill does. A pod
649
    /// OOM-killed as a whole reaches the scheduler as a lost worker with no
650
    /// usage report, so without this the action is requeued at the size
651
    /// that took the pod down until the loss budget ends it. Only a worker
652
    /// that went away on its own counts (its stream ended, it timed out, or
653
    /// a command to it failed), not one that was removed, drained or shut
654
    /// down with the scheduler. 0 never escalates on a loss.
655
    /// Default: 2
656
    #[serde(default = "default_memory_escalation_after_worker_losses")]
657
    pub escalate_after_worker_losses: u64,
658
}
659
660
0
const fn default_memory_escalation_after_worker_losses() -> u64 {
661
0
    2
662
0
}
663
664
0
fn default_memory_escalation_cpu_property() -> String {
665
0
    "cpu_count".to_string()
666
0
}
667
668
0
const fn default_memory_escalation_max_steps() -> u64 {
669
0
    8
670
0
}
671
672
0
const fn default_memory_escalation_percent() -> u64 {
673
0
    200
674
0
}
675
676
#[derive(Deserialize, Serialize, Debug, Clone, Copy)]
677
#[serde(deny_unknown_fields)]
678
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
679
pub struct ReservationHoldSpec {
680
    /// Seconds a queued action has to have waited, finding no room on
681
    /// every pass, before a worker is held for it. Must be above zero.
682
    /// Default: 30
683
    #[serde(
684
        default = "default_reservation_hold_after_s",
685
        deserialize_with = "convert_duration_with_shellexpand"
686
    )]
687
    pub hold_after_s: u64,
688
689
    /// Seconds a hold lasts at most, capped at a week. A hold that long
690
    /// without the action fitting means the worker never reported room for
691
    /// it even drained; the hold is given up so the worker is not idle for
692
    /// good, and the action is not held for again until as long has
693
    /// passed, twice as long for each such expiry in a row on a worker
694
    /// that was idle (up to sixteen times), since then nothing kept the
695
    /// action off the worker but the action itself. Must be above zero.
696
    /// Default: 300
697
    #[serde(
698
        default = "default_reservation_max_hold_s",
699
        deserialize_with = "convert_duration_with_shellexpand"
700
    )]
701
    pub max_hold_s: u64,
702
703
    /// Most workers held at once on this scheduler replica. 0 is one tenth
704
    /// of the workers connected to it, and at least one.
705
    /// Default: 0
706
    #[serde(default, deserialize_with = "convert_numeric_with_shellexpand")]
707
    pub max_held_workers: usize,
708
}
709
710
impl Default for ReservationHoldSpec {
711
0
    fn default() -> Self {
712
0
        Self {
713
0
            hold_after_s: default_reservation_hold_after_s(),
714
0
            max_hold_s: default_reservation_max_hold_s(),
715
0
            max_held_workers: 0,
716
0
        }
717
0
    }
718
}
719
720
0
const fn default_reservation_hold_after_s() -> u64 {
721
0
    30
722
0
}
723
724
0
const fn default_reservation_max_hold_s() -> u64 {
725
0
    300
726
0
}
727
728
/// When the scheduler drains a worker on the outcomes of its own attempts.
729
/// A command timeout, an input fetch timeout and a worker error are
730
/// failures; a result, whatever its exit code, is a success. A worker whose
731
/// last `min_failures` attempts all failed, or whose last `window` attempts
732
/// hold at least `min_failures` failures that are at least `failure_percent`
733
/// of them, is drained: it finishes what it runs and is offered nothing
734
/// more until it reconnects or an operator lifts its drain. Where a worker
735
/// provisioner runs the fleet, the drain ends with the pod: the provisioner
736
/// deletes a drained worker once it is idle and replaces it, so the
737
/// provisioner has to read the drain as evidence about the node, or the
738
/// replacement lands on the same host and is drained again. The run of failures
739
/// catches a worker that was healthy and went bad without waiting for half
740
/// its window to fail; the ratio catches one that fails often but not in a
741
/// row, and leaves alone one that fails a few of many.
742
/// At most `max_drained_percent` of the workers connected to this
743
/// scheduler replica, and at least two (a node's pair), are drained this
744
/// way at once, so a fault every worker shares (a store down) drains a few
745
/// workers, not the fleet.
746
#[derive(Deserialize, Serialize, Debug, Clone, Copy)]
747
#[serde(deny_unknown_fields)]
748
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
749
pub struct WorkerOutcomeTripwireSpec {
750
    /// Recent attempts judged, per worker.
751
    /// Default: 20
752
    #[serde(
753
        default = "default_tripwire_window",
754
        deserialize_with = "convert_numeric_with_shellexpand"
755
    )]
756
    pub window: usize,
757
758
    /// Failures that drain the worker: this many in a row, or this many
759
    /// among the attempts judged at `failure_percent` or more of them. Must
760
    /// be above zero and at most `window`.
761
    /// Default: 3
762
    #[serde(
763
        default = "default_tripwire_min_failures",
764
        deserialize_with = "convert_numeric_with_shellexpand"
765
    )]
766
    pub min_failures: usize,
767
768
    /// Failures as a percentage of the attempts judged, also required, so
769
    /// a worker that fails a few of many is left alone. At most 100.
770
    /// Default: 50
771
    #[serde(
772
        default = "default_tripwire_failure_percent",
773
        deserialize_with = "convert_numeric_with_shellexpand"
774
    )]
775
    pub failure_percent: usize,
776
777
    /// Most workers drained this way at once, as a percentage of the
778
    /// workers connected to this scheduler replica; at least two. At most
779
    /// 100.
780
    /// Default: 20
781
    #[serde(
782
        default = "default_tripwire_max_drained_percent",
783
        deserialize_with = "convert_numeric_with_shellexpand"
784
    )]
785
    pub max_drained_percent: usize,
786
}
787
788
impl Default for WorkerOutcomeTripwireSpec {
789
0
    fn default() -> Self {
790
0
        Self {
791
0
            window: default_tripwire_window(),
792
0
            min_failures: default_tripwire_min_failures(),
793
0
            failure_percent: default_tripwire_failure_percent(),
794
0
            max_drained_percent: default_tripwire_max_drained_percent(),
795
0
        }
796
0
    }
797
}
798
799
1
const fn default_tripwire_window() -> usize {
800
1
    20
801
1
}
802
803
1
const fn default_tripwire_min_failures() -> usize {
804
1
    3
805
1
}
806
807
1
const fn default_tripwire_failure_percent() -> usize {
808
1
    50
809
1
}
810
811
1
const fn default_tripwire_max_drained_percent() -> usize {
812
1
    20
813
1
}
814
815
#[derive(Deserialize, Serialize, Debug, Default, Clone, Copy)]
816
#[serde(deny_unknown_fields)]
817
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
818
pub struct ColdStartSpec {
819
    /// Value for `cpu_property_name`, on the scale the workers advertise.
820
    /// 0 leaves the property alone.
821
    #[serde(default, deserialize_with = "convert_numeric_with_shellexpand")]
822
    pub cpu_count: u64,
823
824
    /// Value for `memory_property_name`, in KiB. 0 leaves the property alone.
825
    #[serde(default, deserialize_with = "convert_numeric_with_shellexpand")]
826
    pub memory_kb: u64,
827
828
    /// Value for `disk_property_name`, in KiB. 0 leaves the property alone.
829
    #[serde(default, deserialize_with = "convert_numeric_with_shellexpand")]
830
    pub disk_kb: u64,
831
}
832
833
5
fn default_disk_property_name_for_hints() -> String {
834
5
    "disk_kb".to_string()
835
5
}
836
837
/// A named point on the fleet's size ladder. List them ascending; each
838
/// should dominate the one before on every dimension it names. A zero
839
/// leaves that dimension alone.
840
#[derive(Deserialize, Serialize, Debug, Clone)]
841
#[serde(deny_unknown_fields)]
842
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
843
pub struct SizeClassSpec {
844
    /// Free text, referenced by hints and by the cold-start policy.
845
    pub name: String,
846
847
    /// Value for `cpu_property_name`, on the scale the workers advertise.
848
    #[serde(default, deserialize_with = "convert_numeric_with_shellexpand")]
849
    pub cpu_count: u64,
850
851
    /// Value for `memory_property_name`, in KiB.
852
    #[serde(default, deserialize_with = "convert_numeric_with_shellexpand")]
853
    pub memory_kb: u64,
854
855
    /// Value for `disk_property_name`, in KiB.
856
    #[serde(default, deserialize_with = "convert_numeric_with_shellexpand")]
857
    pub disk_kb: u64,
858
}
859
860
/// A class for actions whose timeout is at least `min_timeout_s`. Bazel's
861
/// test sizes arrive as timeouts (short 60 s, moderate 300 s, long 900 s,
862
/// eternal 3600 s), so this maps them to classes without a CAS fetch.
863
#[derive(Deserialize, Serialize, Debug, Clone)]
864
#[serde(deny_unknown_fields)]
865
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
866
pub struct TimeoutClassSpec {
867
    #[serde(deserialize_with = "convert_numeric_with_shellexpand")]
868
    pub min_timeout_s: u64,
869
    pub class: String,
870
}
871
872
#[derive(Deserialize, Serialize, Debug)]
873
#[serde(deny_unknown_fields)]
874
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
875
pub struct HistoricalResourceSpec {
876
    /// Opt in to learning reservations from worker measurements. Defaults to
877
    /// false: existing configurations keep using `hints_file` and its refresh
878
    /// interval. In learning mode the file is only a startup seed.
879
    #[serde(default)]
880
    pub learn_from_workers: bool,
881
882
    /// JSON hints file. With learning disabled, reload it at `refresh_interval_s`
883
    /// and preserve the last usable hints if a reload fails. In learning mode,
884
    /// seed the scheduler's sketch from it, read
885
    /// once at start when no snapshot is loaded. The scheduler learns what
886
    /// every kind of action uses from the usage its workers report, so a
887
    /// file is only worth having for a fresh fleet that inherits another's
888
    /// history: the admin API's `/scheduler/{instance}/hints` is this shape.
889
    /// A seeded hint stands until the first real sample of its key.
890
    ///
891
    /// Supported file shapes:
892
    /// ```json
893
    /// [
894
    ///   { "target_id": "//pkg:test", "action_mnemonic": "TestRunner", "cpu_count": 2, "memory_kb": 12582912 }
895
    /// ]
896
    /// ```
897
    /// or:
898
    /// ```json
899
    /// { "hints": [ ... ] }
900
    /// ```
901
    #[serde(default, deserialize_with = "convert_string_with_shellexpand")]
902
    pub hints_file: String,
903
904
    /// Reload interval for `hints_file` when `learn_from_workers` is false.
905
    /// Zero reads once. Refresh happens in the background, outside Execute.
906
    /// Ignored only when learning is explicitly enabled. Default: 30 seconds.
907
    #[serde(
908
        default = "default_historical_resource_refresh_interval_s",
909
        deserialize_with = "convert_duration_with_shellexpand"
910
    )]
911
    pub refresh_interval_s: u64,
912
913
    /// Headroom over the measured 95th percentile, as a share of it: 20
914
    /// reserves 20% more than was measured.
915
    /// Default: 20
916
    #[serde(
917
        default = "default_historical_resource_headroom_percent",
918
        deserialize_with = "convert_numeric_with_shellexpand"
919
    )]
920
    pub headroom_percent: u64,
921
922
    /// A key not measured for this many days is forgotten. Within the
923
    /// window, two half-window histograms retain each sample for between
924
    /// half and one full window. A memory kill stops lifting the
925
    /// key's reservation this many days after it.
926
    /// Default: 7
927
    #[serde(
928
        default = "default_historical_resource_window_days",
929
        deserialize_with = "convert_numeric_with_shellexpand"
930
    )]
931
    pub window_days: u64,
932
933
    /// Accounting budget for the learned sketch, including keys, map and
934
    /// probation storage and reserved snapshot working memory. One quarter
935
    /// funds resident entries; the remainder allows encoding/loading snapshots.
936
    /// Long keys reduce the number of retained entries. This is conservative
937
    /// allocation accounting, not a process RSS limit (allocator overhead and
938
    /// other scheduler data are separate). Default: 512 MiB, holding roughly
939
    /// 55,000 target keys plus mnemonic and command families with short keys.
940
    /// An explicitly configured budget is unchanged. Size the process memory
941
    /// limit above this budget plus the scheduler's other allocations.
942
    #[serde(
943
        default = "default_historical_resource_memory_budget_bytes",
944
        deserialize_with = "convert_data_size_with_shellexpand"
945
    )]
946
    pub memory_budget_bytes: u64,
947
948
    /// Store for this replica's learned sketch. This must name a store in this
949
    /// scheduler process's own top-level `stores`, not in another CAS process.
950
    /// A missing name or failed startup probe logs a warning and disables
951
    /// persistence until restart; scheduling and in-memory learning continue.
952
    /// Each replica prefers its own key (`historical_resource_sketch/<replica_id>`).
953
    /// When that key is missing, it restores the newest compatible snapshot
954
    /// under the prefix if the store supports listing. Only one history is
955
    /// restored, never merged. Use a separate store prefix for each logical
956
    /// scheduler. Fallback scans at most 128 keys; retire old keys with a TTL.
957
    /// Version 3 snapshots use wide histogram counters; older snapshots are
958
    /// skipped with a warning. Give the store eviction or a TTL for retired
959
    /// replica keys. It must support string keys; startup probes write/read.
960
    /// Ignored when `learn_from_workers` is false. Unset means memory only.
961
    #[serde(default)]
962
    pub snapshot_store: Option<String>,
963
964
    /// Stable snapshot identity, unique among concurrent writers sharing the
965
    /// snapshot store. Empty uses `HOSTNAME`, or a random ID if unset. A stable
966
    /// identity avoids snapshot discovery on restart; Deployment pods whose
967
    /// names change can use the newest-snapshot fallback. Maximum: 256 bytes.
968
    #[serde(default, deserialize_with = "convert_string_with_shellexpand")]
969
    pub replica_id: String,
970
971
    /// How often the snapshot is written. Zero turns the periodic write
972
    /// off. Writes happen on the periodic tick; shutdown does not flush.
973
    /// Default: 60 seconds
974
    #[serde(
975
        default = "default_historical_resource_snapshot_interval_s",
976
        deserialize_with = "convert_duration_with_shellexpand"
977
    )]
978
    pub snapshot_interval_s: u64,
979
980
    /// Platform property name used for CPU minimums. The nested scheduler
981
    /// must declare it as a `minimum` property (as it must the memory and
982
    /// disk names): an undeclared property is matched as an exact string,
983
    /// and an action carrying a number would then match no worker.
984
    /// Default: `cpu_count`
985
    #[serde(
986
        default = "default_historical_resource_cpu_property_name",
987
        deserialize_with = "convert_string_with_shellexpand"
988
    )]
989
    pub cpu_property_name: String,
990
991
    /// Platform property name used for memory minimums, expressed in KiB.
992
    /// Declared as `minimum` on the nested scheduler, like the CPU name.
993
    /// Default: `memory_kb`
994
    #[serde(
995
        default = "default_historical_resource_memory_property_name",
996
        deserialize_with = "convert_string_with_shellexpand"
997
    )]
998
    pub memory_property_name: String,
999
1000
    /// Platform property name used for disk minimums, expressed in KiB.
1001
    /// Declared as `minimum` on the nested scheduler, like the CPU name.
1002
    /// Default: `disk_kb`
1003
    #[serde(
1004
        default = "default_disk_property_name_for_hints",
1005
        deserialize_with = "convert_string_with_shellexpand"
1006
    )]
1007
    pub disk_property_name: String,
1008
1009
    /// The fleet's size ladder. A hint may name a `class` instead of
1010
    /// numbers, and the cold-start policy below picks one for actions no
1011
    /// hint matches. Empty means raw numbers only.
1012
    #[serde(default)]
1013
    pub classes: Vec<SizeClassSpec>,
1014
1015
    /// The class an untagged action gets when no hint and no rule below
1016
    /// matches. Takes precedence over `cold_start` when both are set.
1017
    #[serde(default)]
1018
    pub default_class: Option<String>,
1019
1020
    /// Class by Bazel `action_mnemonic` for untagged actions; a known heavy
1021
    /// mnemonic (`TestRunner`, `Link`) starts in the right class.
1022
    #[serde(default)]
1023
    pub class_by_mnemonic: HashMap<String, String>,
1024
1025
    /// Class by the action's timeout, the largest `min_timeout_s` at or
1026
    /// below the timeout wins. Checked before `default_class`, after the
1027
    /// mnemonic rule.
1028
    #[serde(default)]
1029
    pub class_by_timeout: Vec<TimeoutClassSpec>,
1030
1031
    /// Reservation given to an action that no hint matches and the client
1032
    /// left untagged. Only a property that is absent is filled; a value the
1033
    /// client sent is kept. Without this an untagged action costs the
1034
    /// scheduler's ledger nothing, so any number of them can land on one
1035
    /// worker.
1036
    #[serde(default)]
1037
    pub cold_start: Option<ColdStartSpec>,
1038
1039
    /// The nested scheduler to use after applying resource hints.
1040
    pub scheduler: Box<SchedulerSpec>,
1041
}