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/store_awaited_action_db.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::mem::Discriminant;
16
use core::ops::Bound;
17
use core::sync::atomic::{AtomicU64, Ordering};
18
use core::time::Duration;
19
use std::borrow::Cow;
20
use std::sync::{Arc, Weak};
21
use std::time::{SystemTime, UNIX_EPOCH};
22
23
use bytes::Bytes;
24
use futures::{Stream, StreamExt, TryStreamExt};
25
use nativelink_error::{Code, Error, ResultExt, make_err};
26
use nativelink_metric::MetricsComponent;
27
use nativelink_util::action_messages::{
28
    ActionInfo, ActionStage, ActionUniqueQualifier, OperationId, WorkerId,
29
};
30
use nativelink_util::instant_wrapper::InstantWrapper;
31
use nativelink_util::metrics::{EXECUTION_METRICS, EXECUTION_STAGE, ExecutionStage};
32
use nativelink_util::platform_properties::PlatformProperties;
33
use nativelink_util::spawn;
34
use nativelink_util::store_trait::{
35
    FalseValue, SchedulerCurrentVersionProvider, SchedulerIndexProvider, SchedulerStore,
36
    SchedulerStoreDataProvider, SchedulerStoreDecodeTo, SchedulerStoreKeyProvider,
37
    SchedulerSubscription, SchedulerSubscriptionManager, StoreKey, TrueValue,
38
};
39
use nativelink_util::task::JoinHandleDropGuard;
40
use opentelemetry::KeyValue;
41
use serde::{Deserialize, Serialize};
42
use tokio::sync::{Notify, OnceCell};
43
use tracing::{error, warn};
44
45
use crate::awaited_action_db::{
46
    AwaitedAction, AwaitedActionDb, AwaitedActionSubscriber, CLIENT_KEEPALIVE_DURATION,
47
    PeerScheduler, SortedAwaitedAction, SortedAwaitedActionState,
48
};
49
use crate::worker_registry::{
50
    ORPHANED_ACTION_TIMEOUT, SharedWorkerRegistry, WorkerLeases, WorkerLiveness,
51
};
52
53
type ClientOperationId = OperationId;
54
55
/// Maximum number of retries to update client keep alive.
56
const MAX_RETRIES_FOR_CLIENT_KEEPALIVE: u32 = 8;
57
58
/// Use separate non-versioned Redis key for client keepalives.
59
const USE_SEPARATE_CLIENT_KEEPALIVE_KEY: bool = true;
60
61
/// How often the actions in each stage are recounted for
62
/// `execution.active.count`.
63
const ACTIVE_COUNT_REFRESH_INTERVAL: Duration = Duration::from_secs(15);
64
65
/// Every stage the store indexes, with the label it is reported under.
66
const COUNTED_STATES: [(SortedAwaitedActionState, ExecutionStage); 4] = [
67
    (
68
        SortedAwaitedActionState::CacheCheck,
69
        ExecutionStage::CacheCheck,
70
    ),
71
    (SortedAwaitedActionState::Queued, ExecutionStage::Queued),
72
    (
73
        SortedAwaitedActionState::Executing,
74
        ExecutionStage::Executing,
75
    ),
76
    (
77
        SortedAwaitedActionState::Completed,
78
        ExecutionStage::Completed,
79
    ),
80
];
81
82
enum OperationSubscriberState<Sub> {
83
    Unsubscribed,
84
    Subscribed(Sub),
85
}
86
87
pub struct OperationSubscriber<S: SchedulerStore, I: InstantWrapper, NowFn: Fn() -> I> {
88
    maybe_client_operation_id: Option<ClientOperationId>,
89
    subscription_key: OperationIdToAwaitedAction<'static>,
90
    weak_store: Weak<S>,
91
    state: OperationSubscriberState<
92
        <S::SubscriptionManager as SchedulerSubscriptionManager>::Subscription,
93
    >,
94
    last_known_keepalive_ts: AtomicU64,
95
    now_fn: NowFn,
96
    /// The record as a listing read it, when this subscriber came from one.
97
    /// A listing already loads every record it returns, so `borrow` serves
98
    /// this instead of reading the record again; only the client keepalive,
99
    /// kept under its own key, is read, once. The matching pass borrows each
100
    /// queued action two or three times per pass, so without this a pass
101
    /// cost several store round trips per queued action.
102
    listed: Option<AwaitedAction>,
103
    /// `listed` with the client keepalive merged in, filled on first borrow.
104
    listed_with_keepalive: OnceCell<AwaitedAction>,
105
    // If the SchedulerSubscriptionManager is not reliable, then this is populated
106
    // when the state is set to subscribed.  When set it causes the state to be polled
107
    // as well as listening for the publishing.
108
    maybe_last_stage: Option<Discriminant<ActionStage>>,
109
    retain_completed_for: Duration,
110
    /// How long a written client keepalive stays meaningful. Past it, an
111
    /// absent key and a stale one say the same thing, so the key may as
112
    /// well be gone.
113
    client_keepalive_ttl: Duration,
114
}
115
116
impl<S: SchedulerStore, I: InstantWrapper, NowFn: Fn() -> I + core::fmt::Debug> core::fmt::Debug
117
    for OperationSubscriber<S, I, NowFn>
118
where
119
    OperationSubscriberState<
120
        <S::SubscriptionManager as SchedulerSubscriptionManager>::Subscription,
121
    >: core::fmt::Debug,
122
{
123
0
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
124
0
        f.debug_struct("OperationSubscriber")
125
0
            .field("maybe_client_operation_id", &self.maybe_client_operation_id)
126
0
            .field("subscription_key", &self.subscription_key)
127
0
            .field("weak_store", &self.weak_store)
128
0
            .field("state", &self.state)
129
0
            .field("last_known_keepalive_ts", &self.last_known_keepalive_ts)
130
0
            .field("now_fn", &self.now_fn)
131
0
            .finish()
132
0
    }
133
}
134
impl<S, I, NowFn> OperationSubscriber<S, I, NowFn>
135
where
136
    S: SchedulerStore,
137
    I: InstantWrapper,
138
    NowFn: Fn() -> I,
139
{
140
829k
    const fn new(
141
829k
        maybe_client_operation_id: Option<ClientOperationId>,
142
829k
        subscription_key: OperationIdToAwaitedAction<'static>,
143
829k
        weak_store: Weak<S>,
144
829k
        now_fn: NowFn,
145
829k
        retain_completed_for: Duration,
146
829k
        client_keepalive_ttl: Duration,
147
829k
    ) -> Self {
148
829k
        Self {
149
829k
            maybe_client_operation_id,
150
829k
            subscription_key,
151
829k
            weak_store,
152
829k
            last_known_keepalive_ts: AtomicU64::new(0),
153
829k
            state: OperationSubscriberState::Unsubscribed,
154
829k
            now_fn,
155
829k
            listed: None,
156
829k
            listed_with_keepalive: OnceCell::const_new(),
157
829k
            maybe_last_stage: None,
158
829k
            retain_completed_for,
159
829k
            client_keepalive_ttl,
160
829k
        }
161
829k
    }
162
163
    /// Serves `borrow` from the record a listing already read.
164
807k
    fn listed(mut self, awaited_action: AwaitedAction) -> Self {
165
807k
        self.listed = Some(awaited_action);
166
807k
        self
167
807k
    }
168
169
60.0k
    async fn inner_get_awaited_action(
170
60.0k
        store: &S,
171
60.0k
        key: OperationIdToAwaitedAction<'_>,
172
60.0k
        maybe_client_operation_id: Option<ClientOperationId>,
173
60.0k
        last_known_keepalive_ts: &AtomicU64,
174
60.0k
    ) -> Result<AwaitedAction, Error> {
175
60.0k
        let 
mut awaited_action59.2k
= store
176
60.0k
            .get_and_decode(key.borrow())
177
60.0k
            .await
178
59.8k
            .err_tip(|| 
format!609
("In OperationSubscriber::get_awaited_action {key:?}"))
?609
179
59.2k
            .ok_or_else(|| 
{7
180
7
                make_err!(
181
7
                    Code::NotFound,
182
                    "Could not find AwaitedAction for the given operation id {key:?}",
183
                )
184
7
            })?;
185
59.2k
        if let Some(
client_operation_id41.8k
) = maybe_client_operation_id {
186
41.8k
            awaited_action.set_client_operation_id(client_operation_id);
187
41.8k
        
}17.3k
188
59.2k
        Self::merge_client_keepalive(
189
59.2k
            store,
190
59.2k
            key.0.as_ref(),
191
59.2k
            &mut awaited_action,
192
59.2k
            last_known_keepalive_ts,
193
59.2k
        )
194
59.2k
        .await;
195
59.0k
        Ok(awaited_action)
196
59.6k
    }
197
198
    /// Folds the client keepalive kept under its own key into the action's
199
    /// timestamp and remembers it.
200
866k
    async fn merge_client_keepalive(
201
866k
        store: &S,
202
866k
        operation_id: &OperationId,
203
866k
        awaited_action: &mut AwaitedAction,
204
866k
        last_known_keepalive_ts: &AtomicU64,
205
866k
    ) {
206
        // Helper to convert SystemTime to unix timestamp
207
866k
        let to_unix_ts =
208
866k
            |t: SystemTime| -> u64 { t.duration_since(UNIX_EPOCH).map_or(0, |d| d.as_secs()) };
209
210
        // Check the separate keepalive key for the most recent timestamp.
211
866k
        let 
keepalive_ts866k
= if USE_SEPARATE_CLIENT_KEEPALIVE_KEY {
212
866k
            match store.get_and_decode(ClientKeepaliveKey(operation_id)).await {
213
95.0k
                Ok(Some(ts)) => {
214
95.0k
                    let awaited_ts = to_unix_ts(awaited_action.last_client_keepalive_timestamp());
215
95.0k
                    if ts > awaited_ts {
216
89.8k
                        let timestamp = UNIX_EPOCH + Duration::from_secs(ts);
217
89.8k
                        awaited_action.update_client_keep_alive(timestamp);
218
89.8k
                        ts
219
                    } else {
220
5.20k
                        awaited_ts
221
                    }
222
                }
223
771k
                Ok(None) | Err(_) => to_unix_ts(awaited_action.last_client_keepalive_timestamp()),
224
            }
225
        } else {
226
0
            to_unix_ts(awaited_action.last_client_keepalive_timestamp())
227
        };
228
229
866k
        last_known_keepalive_ts.store(keepalive_ts, Ordering::Release);
230
866k
    }
231
232
    #[expect(clippy::future_not_send)] // TODO(jhpratt) remove this
233
2.44M
    async fn get_awaited_action(&self) -> Result<AwaitedAction, Error> {
234
2.44M
        let store = self
235
2.44M
            .weak_store
236
2.44M
            .upgrade()
237
2.44M
            .err_tip(|| "Store gone in OperationSubscriber::get_awaited_action")
?0
;
238
2.44M
        if let Some(
listed2.41M
) = &self.listed {
239
2.41M
            let merged = self
240
2.41M
                .listed_with_keepalive
241
2.41M
                .get_or_init(|| async 
{807k
242
807k
                    let mut awaited_action = listed.clone();
243
807k
                    Self::merge_client_keepalive(
244
807k
                        store.as_ref(),
245
807k
                        self.subscription_key.0.as_ref(),
246
807k
                        &mut awaited_action,
247
807k
                        &self.last_known_keepalive_ts,
248
807k
                    )
249
807k
                    .await;
250
807k
                    awaited_action
251
1.61M
                })
252
2.41M
                .await;
253
2.41M
            return Ok(merged.clone());
254
27.4k
        }
255
27.4k
        Self::inner_get_awaited_action(
256
27.4k
            store.as_ref(),
257
27.4k
            self.subscription_key.borrow(),
258
27.4k
            self.maybe_client_operation_id.clone(),
259
27.4k
            &self.last_known_keepalive_ts,
260
27.4k
        )
261
27.4k
        .await
262
2.44M
    }
263
}
264
265
impl<S, I, NowFn> AwaitedActionSubscriber for OperationSubscriber<S, I, NowFn>
266
where
267
    S: SchedulerStore,
268
    I: InstantWrapper,
269
    NowFn: Fn() -> I + Send + Sync + 'static,
270
{
271
28.7k
    async fn changed(&mut self) -> Result<AwaitedAction, Error> {
272
28.7k
        let store = self
273
28.7k
            .weak_store
274
28.7k
            .upgrade()
275
28.7k
            .err_tip(|| "Store gone in OperationSubscriber::get_awaited_action")
?0
;
276
28.7k
        let 
subscription28.1k
= match &mut self.state {
277
22.4k
            OperationSubscriberState::Subscribed(subscription) => subscription,
278
            OperationSubscriberState::Unsubscribed => {
279
6.32k
                let subscription = store
280
6.32k
                    .subscription_manager()
281
6.32k
                    .await
282
6.32k
                    .err_tip(|| "In OperationSubscriber::changed::subscription_manager")
?0
283
6.32k
                    .subscribe(self.subscription_key.borrow())
284
6.32k
                    .err_tip(|| "In OperationSubscriber::changed::subscribe")
?0
;
285
6.32k
                self.state = OperationSubscriberState::Subscribed(subscription);
286
                // When we've just subscribed, there may have been changes before now.
287
6.32k
                let 
action6.32k
= Self::inner_get_awaited_action(
288
6.32k
                    store.as_ref(),
289
6.32k
                    self.subscription_key.borrow(),
290
6.32k
                    self.maybe_client_operation_id.clone(),
291
6.32k
                    &self.last_known_keepalive_ts,
292
6.32k
                )
293
6.32k
                .await
294
6.32k
                .err_tip(|| "In OperationSubscriber::changed")
?0
;
295
6.32k
                if !<S as SchedulerStore>::SubscriptionManager::is_reliable() {
296
6.32k
                    self.maybe_last_stage = Some(core::mem::discriminant(&action.state().stage));
297
6.32k
                
}0
298
                // Existing changes are only interesting if the state is past queued.
299
6.32k
                if !
matches!589
(action.state().stage, ActionStage::Queued) {
300
589
                    return Ok(action);
301
5.73k
                }
302
5.73k
                let OperationSubscriberState::Subscribed(subscription) = &mut self.state else {
303
0
                    unreachable!("Subscription should be in Subscribed state");
304
                };
305
5.73k
                subscription
306
            }
307
        };
308
309
28.1k
        let changed_fut = subscription.changed();
310
28.1k
        tokio::pin!(changed_fut);
311
        loop {
312
            // This is set if the maybe_last_state doesn't match the state in the store.
313
1.56M
            let mut maybe_changed_action = None;
314
315
1.56M
            let last_known_keepalive_ts = self.last_known_keepalive_ts.load(Ordering::Acquire);
316
            // Only a subscriber that stands for a client may say a client is
317
            // still there. The matching engine subscribes to every queued
318
            // action it considers, and `get_range_of_actions` builds those
319
            // subscribers with no client operation id precisely because there
320
            // is no client behind them. Letting them write the keepalive
321
            // makes the scheduler hold open the actions it is supposed to be
322
            // retiring: the keepalive is refreshed, the client timeout in
323
            // `apply_filter_predicate` never comes due, and the action is
324
            // offered to the matcher again, which refreshes it again.
325
            //
326
            // The effect is that every queued action carries a keepalive
327
            // only seconds old however long its client has been gone, and
328
            // none of them are ever retired.
329
1.56M
            if self.maybe_client_operation_id.is_some()
330
1.56M
                && I::from_secs(last_known_keepalive_ts).elapsed() > CLIENT_KEEPALIVE_DURATION
331
            {
332
13.4k
                let now = (self.now_fn)().now();
333
13.4k
                let now_ts = now.duration_since(UNIX_EPOCH).map_or(0, |d| d.as_secs());
334
335
13.4k
                if USE_SEPARATE_CLIENT_KEEPALIVE_KEY {
336
13.4k
                    let operation_id = self.subscription_key.0.as_ref();
337
13.4k
                    let 
update_result8.19k
= store
338
13.4k
                        .update_data(
339
13.4k
                            UpdateClientKeepalive {
340
13.4k
                                operation_id,
341
13.4k
                                timestamp: now_ts,
342
13.4k
                            },
343
13.4k
                            // Written with no expiry these outlive every
344
13.4k
                            // action that produced them and accumulate
345
13.4k
                            // without bound. A keepalive older than the
346
13.4k
                            // client timeout cannot change any decision,
347
13.4k
                            // because the timeout has already come due and
348
13.4k
                            // the stored timestamp is consulted either way.
349
13.4k
                            Some(self.client_keepalive_ttl),
350
13.4k
                        )
351
13.4k
                        .await;
352
353
8.19k
                    if let Err(
e0
) = update_result {
354
0
                        warn!(
355
                            ?self.subscription_key,
356
                            ?e,
357
                            "Failed to update client keepalive (non-versioned)"
358
                        );
359
8.19k
                    }
360
361
                    // Update local timestamp
362
8.19k
                    self.last_known_keepalive_ts
363
8.19k
                        .store(now_ts, Ordering::Release);
364
365
                    // Check if state changed (for unreliable subscription managers)
366
8.19k
                    if self.maybe_last_stage.is_some() {
367
8.19k
                        let 
awaited_action7.80k
= Self::inner_get_awaited_action(
368
8.19k
                            store.as_ref(),
369
8.19k
                            self.subscription_key.borrow(),
370
8.19k
                            self.maybe_client_operation_id.clone(),
371
8.19k
                            &self.last_known_keepalive_ts,
372
8.19k
                        )
373
8.19k
                        .await
374
7.80k
                        .err_tip(|| "In OperationSubscriber::changed")
?5
;
375
376
7.80k
                        if self.maybe_last_stage.as_ref().is_some_and(|last_stage| {
377
7.80k
                            *last_stage != core::mem::discriminant(&awaited_action.state().stage)
378
7.80k
                        }) {
379
39
                            maybe_changed_action = Some(awaited_action);
380
7.76k
                        }
381
0
                    }
382
                } else {
383
0
                    for attempt in 1..=MAX_RETRIES_FOR_CLIENT_KEEPALIVE {
384
0
                        if attempt > 1 {
385
0
                            (self.now_fn)().sleep(Duration::from_millis(100)).await;
386
0
                            warn!(
387
                                ?self.subscription_key,
388
                                attempt,
389
                                "Client keepalive retry due to version conflict"
390
                            );
391
0
                        }
392
0
                        let mut awaited_action = Self::inner_get_awaited_action(
393
0
                            store.as_ref(),
394
0
                            self.subscription_key.borrow(),
395
0
                            self.maybe_client_operation_id.clone(),
396
0
                            &self.last_known_keepalive_ts,
397
0
                        )
398
0
                        .await
399
0
                        .err_tip(|| "In OperationSubscriber::changed")?;
400
0
                        awaited_action.update_client_keep_alive(now);
401
0
                        maybe_changed_action = self
402
0
                            .maybe_last_stage
403
0
                            .as_ref()
404
0
                            .is_some_and(|last_stage| {
405
0
                                *last_stage
406
0
                                    != core::mem::discriminant(&awaited_action.state().stage)
407
0
                            })
408
0
                            .then(|| awaited_action.clone());
409
0
                        let expiry = if awaited_action.is_complete() {
410
0
                            Some(self.retain_completed_for)
411
                        } else {
412
0
                            None
413
                        };
414
0
                        match inner_update_awaited_action(store.as_ref(), awaited_action, expiry)
415
0
                            .await
416
                        {
417
0
                            Ok(()) => break,
418
0
                            err if attempt == MAX_RETRIES_FOR_CLIENT_KEEPALIVE => {
419
0
                                err.err_tip_with_code(|_| {
420
0
                                    (Code::Aborted, "Could not update client keep alive")
421
0
                                })?;
422
                            }
423
0
                            _ => (),
424
                        }
425
                    }
426
                }
427
1.55M
            }
428
429
            // If the polling shows that it's changed state then publish now.
430
1.56M
            if let Some(
changed_action39
) = maybe_changed_action {
431
39
                self.maybe_last_stage =
432
39
                    Some(core::mem::discriminant(&changed_action.state().stage));
433
39
                return Ok(changed_action);
434
1.56M
            }
435
            // Determine the sleep time based on the last client keep alive.
436
1.56M
            let sleep_time = CLIENT_KEEPALIVE_DURATION
437
1.56M
                .checked_sub(
438
1.56M
                    I::from_secs(self.last_known_keepalive_ts.load(Ordering::Acquire)).elapsed(),
439
                )
440
1.56M
                .unwrap_or(Duration::from_millis(100));
441
1.56M
            tokio::select! {
442
1.56M
                
result18.1k
= &mut changed_fut => {
443
18.1k
                    result
?0
;
444
18.1k
                    break;
445
                }
446
1.56M
                () = (self.now_fn)().sleep(sleep_time) => {
447
1.54M
                    // If we haven't received any updates for a while, we should
448
1.54M
                    // let the database know that we are still listening to prevent
449
1.54M
                    // the action from being dropped.  Also poll for updates if the
450
1.54M
                    // subscription manager is unreliable.
451
1.54M
                }
452
            }
453
        }
454
455
18.1k
        let 
awaited_action18.1k
= Self::inner_get_awaited_action(
456
18.1k
            store.as_ref(),
457
18.1k
            self.subscription_key.borrow(),
458
18.1k
            self.maybe_client_operation_id.clone(),
459
18.1k
            &self.last_known_keepalive_ts,
460
18.1k
        )
461
18.1k
        .await
462
18.1k
        .err_tip(|| "In OperationSubscriber::changed")
?2
;
463
18.1k
        if self.maybe_last_stage.is_some() {
464
18.1k
            self.maybe_last_stage = Some(core::mem::discriminant(&awaited_action.state().stage));
465
18.1k
        
}1
466
18.1k
        Ok(awaited_action)
467
18.7k
    }
468
469
2.44M
    async fn borrow(&self) -> Result<AwaitedAction, Error> {
470
2.44M
        self.get_awaited_action()
471
2.44M
            .await
472
2.44M
            .err_tip(|| "In OperationSubscriber::borrow")
473
2.44M
    }
474
}
475
476
867k
fn awaited_action_decode(version: i64, data: &Bytes) -> Result<AwaitedAction, Error> {
477
867k
    let mut awaited_action: AwaitedAction = serde_json::from_slice(data).map_err(|e| 
{0
478
0
        Error::from_std_err(Code::InvalidArgument, &e).append("In AwaitedAction::decode")
479
0
    })?;
480
867k
    awaited_action.set_version(version);
481
867k
    Ok(awaited_action)
482
867k
}
483
484
const OPERATION_ID_TO_AWAITED_ACTION_KEY_PREFIX: &str = "aa_";
485
const CLIENT_ID_TO_OPERATION_ID_KEY_PREFIX: &str = "cid_";
486
/// TTL bounding the cid_* mapping's lifetime so it cannot outlive its
487
/// aa_* key and accumulate as a permanent orphan (24h safely exceeds
488
/// any real action lifetime).
489
const CLIENT_ID_MAPPING_TTL: Duration = Duration::from_hours(24);
490
/// Phase 2: Separate key prefix for client keepalives (non-versioned).
491
const CLIENT_KEEPALIVE_KEY_PREFIX: &str = "ck_";
492
/// One record per scheduler holding what its connected workers can run
493
/// (non-versioned, expires on its own).
494
const FLEET_CAPABILITIES_KEY_PREFIX: &str = "fc_";
495
const WORKER_LEASE_KEY_PREFIX: &str = "wl_";
496
/// Index over every fleet capabilities record. The value is the same for
497
/// all of them; the index exists so peers can be listed.
498
const FLEET_CAPABILITIES_INDEX_NAME: &str = "fleet";
499
500
#[derive(Debug)]
501
struct OperationIdToAwaitedAction<'a>(Cow<'a, OperationId>);
502
impl OperationIdToAwaitedAction<'_> {
503
126k
    fn borrow(&self) -> OperationIdToAwaitedAction<'_> {
504
126k
        OperationIdToAwaitedAction(Cow::Borrowed(self.0.as_ref()))
505
126k
    }
506
}
507
impl SchedulerStoreKeyProvider for OperationIdToAwaitedAction<'_> {
508
    type Versioned = TrueValue;
509
83.9k
    fn get_key(&self) -> StoreKey<'static> {
510
83.9k
        StoreKey::Str(Cow::Owned(format!(
511
83.9k
            "{OPERATION_ID_TO_AWAITED_ACTION_KEY_PREFIX}{}",
512
83.9k
            self.0
513
83.9k
        )))
514
83.9k
    }
515
}
516
impl SchedulerStoreDecodeTo for OperationIdToAwaitedAction<'_> {
517
    type DecodeOutput = AwaitedAction;
518
59.4k
    fn decode(version: i64, data: Bytes) -> Result<Self::DecodeOutput, Error> {
519
59.4k
        awaited_action_decode(version, &data)
520
59.4k
    }
521
}
522
523
struct ClientIdToOperationId<'a>(&'a OperationId);
524
impl SchedulerStoreKeyProvider for ClientIdToOperationId<'_> {
525
    type Versioned = FalseValue;
526
7.29k
    fn get_key(&self) -> StoreKey<'static> {
527
7.29k
        StoreKey::Str(Cow::Owned(format!(
528
7.29k
            "{CLIENT_ID_TO_OPERATION_ID_KEY_PREFIX}{}",
529
7.29k
            self.0
530
7.29k
        )))
531
7.29k
    }
532
}
533
impl SchedulerStoreDecodeTo for ClientIdToOperationId<'_> {
534
    type DecodeOutput = OperationId;
535
221
    fn decode(_version: i64, data: Bytes) -> Result<Self::DecodeOutput, Error> {
536
221
        serde_json::from_slice(&data).map_err(|e| 
{0
537
0
            Error::from_std_err(Code::InvalidArgument, &e).append(format!(
538
                "In ClientIdToOperationId::decode (data: {data:02x?})",
539
            ))
540
0
        })
541
221
    }
542
}
543
544
struct ClientKeepaliveKey<'a>(&'a OperationId);
545
impl SchedulerStoreKeyProvider for ClientKeepaliveKey<'_> {
546
    type Versioned = FalseValue;
547
879k
    fn get_key(&self) -> StoreKey<'static> {
548
879k
        StoreKey::Str(Cow::Owned(format!(
549
879k
            "{CLIENT_KEEPALIVE_KEY_PREFIX}{}",
550
879k
            self.0
551
879k
        )))
552
879k
    }
553
}
554
impl SchedulerStoreDecodeTo for ClientKeepaliveKey<'_> {
555
    type DecodeOutput = u64;
556
95.0k
    fn decode(_version: i64, data: Bytes) -> Result<Self::DecodeOutput, Error> {
557
95.0k
        let s = core::str::from_utf8(&data).map_err(|e| 
{0
558
0
            Error::from_std_err(Code::InvalidArgument, &e)
559
0
                .append("In ClientKeepaliveKey::decode utf8")
560
0
        })?;
561
95.0k
        s.parse::<u64>().map_err(|e| 
{0
562
0
            Error::from_std_err(Code::InvalidArgument, &e)
563
0
                .append("In ClientKeepaliveKey::decode parse")
564
0
        })
565
95.0k
    }
566
}
567
568
struct UpdateClientKeepalive<'a> {
569
    operation_id: &'a OperationId,
570
    timestamp: u64,
571
}
572
impl SchedulerStoreKeyProvider for UpdateClientKeepalive<'_> {
573
    type Versioned = FalseValue;
574
13.4k
    fn get_key(&self) -> StoreKey<'static> {
575
13.4k
        ClientKeepaliveKey(self.operation_id).get_key()
576
13.4k
    }
577
}
578
impl SchedulerStoreDataProvider for UpdateClientKeepalive<'_> {
579
12.2k
    fn try_into_bytes(self) -> Result<Bytes, Error> {
580
12.2k
        Ok(Bytes::from(self.timestamp.to_string()))
581
12.2k
    }
582
}
583
584
/// What one scheduler's workers can run, as published to its peers.
585
#[derive(Serialize, Deserialize)]
586
struct FleetCapabilities {
587
    scheduler_id: String,
588
    workers: Vec<PlatformProperties>,
589
    /// The scheduler renews its workers' leases. Absent from an older one.
590
    #[serde(default)]
591
    renews_worker_leases: bool,
592
}
593
594
/// The lease on a worker: the replica it is connected to, and when that
595
/// replica last renewed it. Gone a worker timeout after it stops.
596
#[derive(Serialize, Deserialize)]
597
struct WorkerLease {
598
    scheduler_id: String,
599
    renewed_at_s: u64,
600
}
601
602
struct WorkerLeaseKey<'a>(&'a WorkerId);
603
impl SchedulerStoreKeyProvider for WorkerLeaseKey<'_> {
604
    type Versioned = FalseValue;
605
8.04k
    fn get_key(&self) -> StoreKey<'static> {
606
8.04k
        StoreKey::Str(Cow::Owned(format!("{WORKER_LEASE_KEY_PREFIX}{}", self.0)))
607
8.04k
    }
608
}
609
impl SchedulerStoreDecodeTo for WorkerLeaseKey<'_> {
610
    type DecodeOutput = WorkerLease;
611
1
    fn decode(_version: i64, data: Bytes) -> Result<Self::DecodeOutput, Error> {
612
1
        serde_json::from_slice(&data).map_err(|e| 
{0
613
0
            Error::from_std_err(Code::InvalidArgument, &e).append("In WorkerLeaseKey::decode")
614
0
        })
615
1
    }
616
}
617
618
struct UpdateWorkerLease<'a> {
619
    worker_id: &'a WorkerId,
620
    scheduler_id: &'a str,
621
    renewed_at_s: u64,
622
}
623
impl SchedulerStoreKeyProvider for UpdateWorkerLease<'_> {
624
    type Versioned = FalseValue;
625
7.64k
    fn get_key(&self) -> StoreKey<'static> {
626
7.64k
        WorkerLeaseKey(self.worker_id).get_key()
627
7.64k
    }
628
}
629
impl SchedulerStoreDataProvider for UpdateWorkerLease<'_> {
630
7.64k
    fn try_into_bytes(self) -> Result<Bytes, Error> {
631
7.64k
        serde_json::to_string(&WorkerLease {
632
7.64k
            scheduler_id: self.scheduler_id.to_string(),
633
7.64k
            renewed_at_s: self.renewed_at_s,
634
7.64k
        })
635
7.64k
        .map(Bytes::from)
636
7.64k
        .map_err(|e| 
{0
637
0
            Error::from_std_err(Code::InvalidArgument, &e)
638
0
                .append("Could not convert WorkerLease to json")
639
0
        })
640
7.64k
    }
641
}
642
643
/// Worker leases kept in the scheduler store.
644
struct StoreWorkerLeases<S> {
645
    store: Arc<S>,
646
}
647
648
impl<S> core::fmt::Debug for StoreWorkerLeases<S> {
649
0
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
650
0
        f.debug_struct("StoreWorkerLeases").finish_non_exhaustive()
651
0
    }
652
}
653
654
/// How many lease writes a renewal has in flight at once.
655
const MAX_CONCURRENT_LEASE_WRITES: usize = 64;
656
657
#[async_trait::async_trait]
658
impl<S: SchedulerStore + 'static> WorkerLeases for StoreWorkerLeases<S> {
659
    async fn renew(
660
        &self,
661
        scheduler_id: &str,
662
        worker_ids: &[WorkerId],
663
        now: SystemTime,
664
        ttl: Duration,
665
1.13k
    ) -> Result<(), Error> {
666
        let renewed_at_s = now
667
            .duration_since(UNIX_EPOCH)
668
1.13k
            .map_or(0, |since| since.as_secs());
669
        let writes: Vec<_> = worker_ids
670
            .iter()
671
7.64k
            .map(|worker_id| {
672
7.64k
                self.store.update_data(
673
7.64k
                    UpdateWorkerLease {
674
7.64k
                        worker_id,
675
7.64k
                        scheduler_id,
676
7.64k
                        renewed_at_s,
677
7.64k
                    },
678
7.64k
                    Some(ttl),
679
7.64k
                )
680
7.64k
            })
681
            .collect();
682
        futures::stream::iter(writes)
683
            .buffer_unordered(MAX_CONCURRENT_LEASE_WRITES)
684
7.53k
            .try_for_each(|_| futures::future::ready(Ok(())))
685
            .await
686
            .err_tip(|| "In StoreWorkerLeases::renew")
687
1.13k
    }
688
689
411
    async fn renewed_at(&self, worker_id: &WorkerId) -> Result<Option<SystemTime>, Error> {
690
        self.store
691
            .get_and_decode(WorkerLeaseKey(worker_id))
692
            .await
693
411
            .map(|lease| lease.map(|lease| UNIX_EPOCH + 
Duration::from_secs1
(
lease.renewed_at_s1
)))
694
            .err_tip(|| "In StoreWorkerLeases::renewed_at")
695
411
    }
696
}
697
698
struct UpdateFleetCapabilities(FleetCapabilities);
699
impl SchedulerStoreKeyProvider for UpdateFleetCapabilities {
700
    type Versioned = FalseValue;
701
1.36k
    fn get_key(&self) -> StoreKey<'static> {
702
1.36k
        StoreKey::Str(Cow::Owned(format!(
703
1.36k
            "{FLEET_CAPABILITIES_KEY_PREFIX}{}",
704
1.36k
            self.0.scheduler_id
705
1.36k
        )))
706
1.36k
    }
707
}
708
impl SchedulerStoreDataProvider for UpdateFleetCapabilities {
709
1.36k
    fn try_into_bytes(self) -> Result<Bytes, Error> {
710
1.36k
        serde_json::to_string(&self.0)
711
1.36k
            .map(Bytes::from)
712
1.36k
            .map_err(|e| 
{0
713
0
                Error::from_std_err(Code::InvalidArgument, &e)
714
0
                    .append("Could not convert FleetCapabilities to json")
715
0
            })
716
1.36k
    }
717
1.36k
    fn get_indexes(&self) -> Result<Vec<(&'static str, Bytes)>, Error> {
718
1.36k
        Ok(vec![(
719
1.36k
            FLEET_CAPABILITIES_INDEX_NAME,
720
1.36k
            Bytes::from_static(b"1"),
721
1.36k
        )])
722
1.36k
    }
723
}
724
725
struct SearchFleetCapabilities;
726
impl SchedulerIndexProvider for SearchFleetCapabilities {
727
    const KEY_PREFIX: &'static str = FLEET_CAPABILITIES_KEY_PREFIX;
728
    const INDEX_NAME: &'static str = FLEET_CAPABILITIES_INDEX_NAME;
729
    type Versioned = FalseValue;
730
1.36k
    fn index_value(&self) -> Cow<'_, str> {
731
1.36k
        Cow::Borrowed("1")
732
1.36k
    }
733
}
734
impl SchedulerStoreDecodeTo for SearchFleetCapabilities {
735
    type DecodeOutput = FleetCapabilities;
736
1.34k
    fn decode(_version: i64, data: Bytes) -> Result<Self::DecodeOutput, Error> {
737
1.34k
        serde_json::from_slice(&data).map_err(|e| 
{0
738
0
            Error::from_std_err(Code::Internal, &e).append("In SearchFleetCapabilities::decode")
739
0
        })
740
1.34k
    }
741
}
742
743
// TODO(palfrey) We only need operation_id here, it would be nice if we had a way
744
// to tell the decoder we only care about specific fields.
745
struct SearchUniqueQualifierToAwaitedAction<'a>(&'a ActionUniqueQualifier);
746
impl SchedulerIndexProvider for SearchUniqueQualifierToAwaitedAction<'_> {
747
    const KEY_PREFIX: &'static str = OPERATION_ID_TO_AWAITED_ACTION_KEY_PREFIX;
748
    const INDEX_NAME: &'static str = "unique_qualifier";
749
    type Versioned = TrueValue;
750
8.49k
    fn index_value(&self) -> Cow<'_, str> {
751
8.49k
        Cow::Owned(format!("{}", self.0))
752
8.49k
    }
753
}
754
impl SchedulerStoreDecodeTo for SearchUniqueQualifierToAwaitedAction<'_> {
755
    type DecodeOutput = AwaitedAction;
756
16
    fn decode(version: i64, data: Bytes) -> Result<Self::DecodeOutput, Error> {
757
16
        awaited_action_decode(version, &data)
758
16
    }
759
}
760
761
struct SearchStateToAwaitedAction(&'static str);
762
impl SchedulerIndexProvider for SearchStateToAwaitedAction {
763
    const KEY_PREFIX: &'static str = OPERATION_ID_TO_AWAITED_ACTION_KEY_PREFIX;
764
    const INDEX_NAME: &'static str = "state";
765
    const MAYBE_SORT_KEY: Option<&'static str> = Some("sort_key");
766
    // The matcher walks the queue highest priority first, oldest first,
767
    // which is descending over the packed sort key (see
768
    // `AwaitedActionSortKey`). The memory backend does the same with
769
    // `.rev()` over its `BTreeSet`.
770
    const SORT_DESCENDING: bool = true;
771
    type Versioned = TrueValue;
772
14.6k
    fn index_value(&self) -> Cow<'_, str> {
773
14.6k
        Cow::Borrowed(self.0)
774
14.6k
    }
775
}
776
impl SchedulerStoreDecodeTo for SearchStateToAwaitedAction {
777
    type DecodeOutput = AwaitedAction;
778
807k
    fn decode(version: i64, data: Bytes) -> Result<Self::DecodeOutput, Error> {
779
807k
        awaited_action_decode(version, &data)
780
807k
    }
781
}
782
783
/// Counts the actions in a state. Uses the same index as
784
/// [`SearchStateToAwaitedAction`], but only ever as a `count_by_index_prefix`
785
/// argument, so the store returns a total and never reads the actions.
786
struct CountActionsInState(&'static str);
787
impl SchedulerIndexProvider for CountActionsInState {
788
    const KEY_PREFIX: &'static str = OPERATION_ID_TO_AWAITED_ACTION_KEY_PREFIX;
789
    const INDEX_NAME: &'static str = "state";
790
    const MAYBE_SORT_KEY: Option<&'static str> = Some("sort_key");
791
    type Versioned = TrueValue;
792
0
    fn index_value(&self) -> Cow<'_, str> {
793
0
        Cow::Borrowed(self.0)
794
0
    }
795
}
796
797
31.8k
const fn get_state_prefix(state: SortedAwaitedActionState) -> &'static str {
798
31.8k
    match state {
799
3
        SortedAwaitedActionState::CacheCheck => "cache_check",
800
21.8k
        SortedAwaitedActionState::Queued => "queued",
801
5.45k
        SortedAwaitedActionState::Executing => "executing",
802
4.44k
        SortedAwaitedActionState::Completed => "completed",
803
    }
804
31.8k
}
805
806
/// Reports how many actions the store holds in each stage as
807
/// `execution.active.count`.
808
///
809
/// The store is shared, so every scheduler replica reports the same totals:
810
/// aggregate across replicas with `max`, not `sum`. Recording the change since
811
/// the last pass, rather than adding and subtracting per transition, keeps the
812
/// count right across restarts and for transitions another replica made.
813
3
async fn report_active_counts<S: SchedulerStore>(
814
3
    store: &S,
815
3
    reported: &mut [Option<i64>; COUNTED_STATES.len()],
816
3
) {
817
12
    for ((state, stage), last) in 
COUNTED_STATES3
.
iter3
().
zip3
(
reported3
.
iter_mut3
()) {
818
12
        let count = store
819
12
            .count_by_index_prefix(CountActionsInState(get_state_prefix(*state)))
820
12
            .await
821
12
            .map(|count| i64::try_from(count).unwrap_or(i64::MAX));
822
12
        match count {
823
            // The first pass records even a zero, so every stage has a series
824
            // and an empty queue reads as 0 rather than no data.
825
12
            Ok(
count4
) if *last != Some(count
)4
=> {
826
4
                EXECUTION_METRICS.execution_active_count.add(
827
4
                    count - last.unwrap_or(0),
828
4
                    &[KeyValue::new(EXECUTION_STAGE, *stage)],
829
4
                );
830
4
                *last = Some(count);
831
4
            }
832
8
            Ok(_) => {}
833
0
            Err(err) => warn!(
834
                ?err,
835
                ?stage,
836
                "Failed to count actions for execution.active.count"
837
            ),
838
        }
839
    }
840
3
}
841
842
#[derive(Debug)]
843
pub struct UpdateOperationIdToAwaitedAction(AwaitedAction);
844
impl SchedulerCurrentVersionProvider for UpdateOperationIdToAwaitedAction {
845
17.1k
    fn current_version(&self) -> i64 {
846
17.1k
        self.0.version()
847
17.1k
    }
848
}
849
impl SchedulerStoreKeyProvider for UpdateOperationIdToAwaitedAction {
850
    type Versioned = TrueValue;
851
17.1k
    fn get_key(&self) -> StoreKey<'static> {
852
17.1k
        OperationIdToAwaitedAction(Cow::Borrowed(self.0.operation_id())).get_key()
853
17.1k
    }
854
}
855
impl SchedulerStoreDataProvider for UpdateOperationIdToAwaitedAction {
856
17.1k
    fn try_into_bytes(self) -> Result<Bytes, Error> {
857
17.1k
        serde_json::to_string(&self.0)
858
17.1k
            .map(Bytes::from)
859
17.1k
            .map_err(|e| 
{0
860
0
                Error::from_std_err(Code::InvalidArgument, &e)
861
0
                    .append("Could not convert AwaitedAction to json")
862
0
            })
863
17.1k
    }
864
17.1k
    fn get_indexes(&self) -> Result<Vec<(&'static str, Bytes)>, Error> {
865
17.1k
        let unique_qualifier = &self.0.action_info().unique_qualifier;
866
17.1k
        let maybe_unique_qualifier = match &unique_qualifier {
867
12.5k
            ActionUniqueQualifier::Cacheable(_) => Some(unique_qualifier),
868
4.57k
            ActionUniqueQualifier::Uncacheable(_) => None,
869
        };
870
17.1k
        let mut output = Vec::with_capacity(2 + maybe_unique_qualifier.map_or(0, |_| 1));
871
17.1k
        if maybe_unique_qualifier.is_some() {
872
12.5k
            output.push((
873
12.5k
                "unique_qualifier",
874
12.5k
                Bytes::from(unique_qualifier.to_string()),
875
12.5k
            ));
876
12.5k
        
}4.57k
877
        {
878
17.1k
            let state = SortedAwaitedActionState::try_from(&self.0.state().stage)
879
17.1k
                .err_tip(|| "In UpdateOperationIdToAwaitedAction::get_index")
?0
;
880
17.1k
            output.push(("state", Bytes::from(get_state_prefix(state))));
881
17.1k
            let sorted_awaited_action = SortedAwaitedAction::from(&self.0);
882
17.1k
            output.push((
883
17.1k
                "sort_key",
884
17.1k
                // We encode to fixed-width hex to ensure that the sort key is
885
17.1k
                // lexicographically sorted.
886
17.1k
                Bytes::from(sorted_awaited_action.sort_key.index_field()),
887
17.1k
            ));
888
        }
889
17.1k
        Ok(output)
890
17.1k
    }
891
}
892
893
struct UpdateClientIdToOperationId {
894
    client_operation_id: ClientOperationId,
895
    operation_id: OperationId,
896
}
897
impl SchedulerStoreKeyProvider for UpdateClientIdToOperationId {
898
    type Versioned = FalseValue;
899
7.07k
    fn get_key(&self) -> StoreKey<'static> {
900
7.07k
        ClientIdToOperationId(&self.client_operation_id).get_key()
901
7.07k
    }
902
}
903
impl SchedulerStoreDataProvider for UpdateClientIdToOperationId {
904
7.07k
    fn try_into_bytes(self) -> Result<Bytes, Error> {
905
7.07k
        serde_json::to_string(&self.operation_id)
906
7.07k
            .map(Bytes::from)
907
7.07k
            .map_err(|e| 
{0
908
0
                Error::from_std_err(Code::InvalidArgument, &e)
909
0
                    .append("Could not convert OperationId to json")
910
0
            })
911
7.07k
    }
912
}
913
914
10.0k
pub async fn inner_update_awaited_action(
915
10.0k
    store: &impl SchedulerStore,
916
10.0k
    mut new_awaited_action: AwaitedAction,
917
10.0k
    expiry: Option<Duration>,
918
10.0k
) -> Result<(), Error> {
919
10.0k
    let operation_id = new_awaited_action.operation_id().clone();
920
10.0k
    if new_awaited_action.state().client_operation_id != operation_id {
921
212
        new_awaited_action.set_client_operation_id(operation_id.clone());
922
9.84k
    }
923
924
10.0k
    let _is_finished = new_awaited_action.state().stage.is_finished();
925
926
10.0k
    let 
maybe_version10.0k
= store
927
10.0k
        .update_data(UpdateOperationIdToAwaitedAction(new_awaited_action), expiry)
928
10.0k
        .await
929
10.0k
        .err_tip(|| "In RedisAwaitedActionDb::update_awaited_action")
?15
;
930
931
10.0k
    if maybe_version.is_none() {
932
6
        warn!(
933
            %operation_id,
934
            "Could not update AwaitedAction because the version did not match"
935
        );
936
6
        return Err(make_err!(
937
6
            Code::Aborted,
938
6
            "Could not update AwaitedAction because the version did not match for {operation_id}",
939
6
        ));
940
10.0k
    }
941
942
10.0k
    Ok(())
943
10.0k
}
944
945
#[derive(Debug, MetricsComponent)]
946
pub struct StoreAwaitedActionDb<S, F, I, NowFn>
947
where
948
    S: SchedulerStore,
949
    F: Fn() -> OperationId,
950
    I: InstantWrapper,
951
    NowFn: Fn() -> I,
952
{
953
    store: Arc<S>,
954
    now_fn: NowFn,
955
    operation_id_creator: F,
956
    _pull_task_change_subscriber_spawn: JoinHandleDropGuard<()>,
957
    _active_count_spawn: Option<JoinHandleDropGuard<()>>,
958
    retain_completed_for: Duration,
959
    client_keepalive_ttl: Duration,
960
    worker_registry: Option<SharedWorkerRegistry>,
961
}
962
963
impl<S, F, I, NowFn> StoreAwaitedActionDb<S, F, I, NowFn>
964
where
965
    S: SchedulerStore,
966
    F: Fn() -> OperationId,
967
    I: InstantWrapper,
968
    NowFn: Fn() -> I + Send + Sync + Clone + 'static,
969
{
970
203
    pub async fn new(
971
203
        store: Arc<S>,
972
203
        task_change_publisher: Arc<Notify>,
973
203
        now_fn: NowFn,
974
203
        operation_id_creator: F,
975
203
        retain_completed_for_s: u32,
976
203
        client_action_timeout_s: u64,
977
203
        enable_active_action_count_metric: bool,
978
203
    ) -> Result<Self, Error> {
979
203
        let mut subscription = store
980
203
            .subscription_manager()
981
203
            .await
982
203
            .err_tip(|| "In RedisAwaitedActionDb::new")
?0
983
203
            .subscribe(OperationIdToAwaitedAction(Cow::Owned(OperationId::String(
984
203
                String::new(),
985
203
            ))))
986
203
            .err_tip(|| "In RedisAwaitedActionDb::new")
?0
;
987
203
        let pull_task_change_subscriber = spawn!(
988
            "redis_awaited_action_db_pull_task_change_subscriber",
989
195
            async move {
990
                loop {
991
15.1k
                    let 
changed_res14.9k
= subscription
992
15.1k
                        .changed()
993
15.1k
                        .await
994
14.9k
                        .err_tip(|| "In RedisAwaitedActionDb::new");
995
14.9k
                    if let Err(
err0
) = changed_res {
996
0
                        error!(
997
                            "Error waiting for pull task change subscriber in RedisAwaitedActionDb::new  - {err:?}"
998
                        );
999
                        // Sleep for a second to avoid a busy loop, then trigger the notify
1000
                        // so if a reconnect happens we let local resources know that things
1001
                        // might have changed.
1002
0
                        tokio::time::sleep(Duration::from_secs(1)).await;
1003
14.9k
                    }
1004
14.9k
                    task_change_publisher.as_ref().notify_one();
1005
                }
1006
            }
1007
        );
1008
        // Off by default: counting queries the same store that serves action
1009
        // scheduling, once per interval per replica, so it is opt-in rather
1010
        // than a cost every deployment pays for a metric it may not read.
1011
203
        let active_count_spawn = enable_active_action_count_metric.then(|| 
{1
1012
1
            let weak_store = Arc::downgrade(&store);
1013
1
            spawn!("store_awaited_action_db_active_count", async move {
1014
1
                let mut reported = [None; COUNTED_STATES.len()];
1015
                loop {
1016
                    // Wait first, so constructing the db never queries the store.
1017
4
                    tokio::time::sleep(ACTIVE_COUNT_REFRESH_INTERVAL).await;
1018
3
                    let Some(store) = weak_store.upgrade() else {
1019
0
                        return;
1020
                    };
1021
3
                    report_active_counts(store.as_ref(), &mut reported).await;
1022
                }
1023
0
            })
1024
1
        });
1025
203
        Ok(Self {
1026
203
            store,
1027
203
            now_fn,
1028
203
            operation_id_creator,
1029
203
            _pull_task_change_subscriber_spawn: pull_task_change_subscriber,
1030
203
            _active_count_spawn: active_count_spawn,
1031
203
            retain_completed_for: Duration::from_secs(retain_completed_for_s.into()),
1032
203
            client_keepalive_ttl: Duration::from_secs(client_action_timeout_s),
1033
203
            worker_registry: None,
1034
203
        })
1035
203
    }
1036
1037
    /// Whether an executing action looks abandoned and should be recreated
1038
    /// rather than joined.
1039
    ///
1040
    /// `last_worker_updated_timestamp` lives in the shared store and
1041
    /// heartbeats never refresh it, so on its own it goes stale on any action
1042
    /// outliving `worker_timeout_s` and a healthy worker looks abandoned.
1043
    /// Consult the registry first and only fall back to the timestamp for
1044
    /// workers this instance owns.
1045
    #[expect(clippy::future_not_send)] // TODO(jhpratt) remove this
1046
16
    async fn executing_action_is_abandoned(
1047
16
        &self,
1048
16
        awaited_action: &AwaitedAction,
1049
16
        no_event_action_timeout: Duration,
1050
16
        now: SystemTime,
1051
16
    ) -> bool {
1052
16
        if awaited_action.state().stage != ActionStage::Executing {
1053
4
            return false;
1054
12
        }
1055
1056
12
        let liveness = match (&self.worker_registry, awaited_action.worker_id()) {
1057
11
            (Some(worker_registry), Some(worker_id)) => {
1058
11
                worker_registry
1059
11
                    .fleet_liveness(worker_id, no_event_action_timeout, now)
1060
11
                    .await
1061
            }
1062
            // No registry, or not assigned yet: timestamp only, as before.
1063
1
            _ => WorkerLiveness::Stale,
1064
        };
1065
1066
12
        let 
ceiling5
= match liveness {
1067
            // Ours and heartbeating. Never recreate: that forks a second
1068
            // execution of work already running.
1069
7
            WorkerLiveness::Alive => return false,
1070
            // Ours and gone quiet.
1071
3
            WorkerLiveness::Stale => no_event_action_timeout,
1072
            // A peer's worker, or an orphan nobody owns.
1073
2
            WorkerLiveness::Unknown => ORPHANED_ACTION_TIMEOUT,
1074
        };
1075
1076
5
        awaited_action
1077
5
            .last_worker_updated_timestamp()
1078
5
            .checked_add(ceiling)
1079
5
            .is_some_and(|deadline| deadline < now)
1080
16
    }
1081
1082
    // `pub` so integration tests in `tests/` can drive this directly;
1083
    // matches the precedent of `inner_update_awaited_action` below.
1084
    #[expect(clippy::future_not_send)] // TODO(jhpratt) remove this
1085
7.08k
    pub async fn try_subscribe(
1086
7.08k
        &self,
1087
7.08k
        client_operation_id: &ClientOperationId,
1088
7.08k
        unique_qualifier: &ActionUniqueQualifier,
1089
7.08k
        no_event_action_timeout: Duration,
1090
7.08k
        // TODO(palfrey) To simplify the scheduler 2024 refactor, we
1091
7.08k
        // removed the ability to upgrade priorities of actions.
1092
7.08k
        // we should add priority upgrades back in.
1093
7.08k
        _priority: i32,
1094
7.08k
    ) -> Result<Option<AwaitedAction>, Error> {
1095
        // Retry once on miss: closes the RediSearch index-visibility
1096
        // window where two concurrent `add_action` calls can both see
1097
        // empty and create duplicate scheduler operations.
1098
        const SUBSCRIBE_RACE_RETRY_DELAY: Duration = Duration::from_millis(20);
1099
7.08k
        match unique_qualifier {
1100
4.25k
            ActionUniqueQualifier::Cacheable(_) => {}
1101
2.82k
            ActionUniqueQualifier::Uncacheable(_) => return Ok(None),
1102
        }
1103
4.25k
        let mut maybe_awaited_action: Option<AwaitedAction> = None;
1104
8.50k
        for attempt in 
0..2_u324.25k
{
1105
8.50k
            if attempt > 0 {
1106
4.24k
                tokio::time::sleep(SUBSCRIBE_RACE_RETRY_DELAY).await;
1107
4.25k
            }
1108
8.50k
            let 
stream8.50k
= self
1109
8.50k
                .store
1110
8.50k
                .search_by_index_prefix(SearchUniqueQualifierToAwaitedAction(unique_qualifier))
1111
8.50k
                .await
1112
8.50k
                .err_tip(|| "In RedisAwaitedActionDb::try_subscribe")
?1
;
1113
8.50k
            tokio::pin!(stream);
1114
            // This index search is by prefix. In particular, an unscoped key
1115
            // is a prefix of its scoped variants and must not join those jobs.
1116
8.50k
            while let Some(
candidate16
) = stream
1117
8.50k
                .try_next()
1118
8.50k
                .await
1119
8.50k
                .err_tip(|| "In RedisAwaitedActionDb::try_subscribe")
?0
1120
            {
1121
16
                if &candidate.action_info().unique_qualifier == unique_qualifier {
1122
16
                    maybe_awaited_action = Some(candidate);
1123
16
                    break;
1124
0
                }
1125
            }
1126
8.50k
            if maybe_awaited_action.is_some() {
1127
16
                break;
1128
8.48k
            }
1129
        }
1130
4.25k
        match maybe_awaited_action {
1131
16
            Some(awaited_action) => {
1132
                // TODO(palfrey) We don't support joining completed jobs because we
1133
                // need to also check that all the data is still in the cache.
1134
                // If the existing job failed then we need to set back to queued or we get
1135
                // a version mismatch.  Equally we need to check the timeout as the job
1136
                // may be abandoned in the store.
1137
16
                let abandoned = self
1138
16
                    .executing_action_is_abandoned(
1139
16
                        &awaited_action,
1140
16
                        no_event_action_timeout,
1141
16
                        (self.now_fn)().now(),
1142
16
                    )
1143
16
                    .await;
1144
16
                let awaited_action = if awaited_action.state().stage.is_finished() || abandoned {
1145
4
                    tracing::debug!(
1146
                        "Recreating action {:?} for operation {client_operation_id}",
1147
4
                        awaited_action.action_info().digest()
1148
                    );
1149
                    // The version is reset because we have a new operation ID.
1150
4
                    AwaitedAction::new(
1151
4
                        (self.operation_id_creator)(),
1152
4
                        awaited_action.action_info().clone(),
1153
4
                        (self.now_fn)().now(),
1154
                    )
1155
                } else {
1156
12
                    tracing::debug!(
1157
                        "Subscribing to existing action {:?} for operation {client_operation_id}",
1158
9
                        awaited_action.action_info().digest()
1159
                    );
1160
12
                    awaited_action
1161
                };
1162
16
                Ok(Some(awaited_action))
1163
            }
1164
4.24k
            None => Ok(None),
1165
        }
1166
7.08k
    }
1167
1168
    #[expect(clippy::future_not_send)] // TODO(jhpratt) remove this
1169
221
    async fn inner_get_awaited_action_by_id(
1170
221
        &self,
1171
221
        client_operation_id: &ClientOperationId,
1172
221
    ) -> Result<Option<OperationSubscriber<S, I, NowFn>>, Error> {
1173
221
        let maybe_operation_id = self
1174
221
            .store
1175
221
            .get_and_decode(ClientIdToOperationId(client_operation_id))
1176
221
            .await
1177
221
            .err_tip(|| "In RedisAwaitedActionDb::get_awaited_action_by_id")
?0
;
1178
221
        let Some(operation_id) = maybe_operation_id else {
1179
0
            return Ok(None);
1180
        };
1181
1182
        // Validate that the internal operation actually exists.
1183
        // If it doesn't, this is an orphaned client operation mapping that should be cleaned up.
1184
        // This can happen when an operation is deleted (completed/timed out) but the
1185
        // client_id -> operation_id mapping persists in the store.
1186
221
        let maybe_awaited_action = match self
1187
221
            .store
1188
221
            .get_and_decode(OperationIdToAwaitedAction(Cow::Borrowed(&operation_id)))
1189
221
            .await
1190
        {
1191
221
            Ok(maybe_action) => maybe_action,
1192
0
            Err(err) if err.code == Code::NotFound => {
1193
0
                tracing::warn!(
1194
                    "Orphaned client operation mapping detected: client_id={} maps to operation_id={}, \
1195
                    but the operation does not exist in the store (NotFound). This typically happens when \
1196
                    an operation completes or times out but the client mapping persists.",
1197
                    client_operation_id,
1198
                    operation_id
1199
                );
1200
0
                None
1201
            }
1202
0
            Err(err) => {
1203
                // Some other error occurred
1204
0
                return Err(err).err_tip(
1205
                    || "In RedisAwaitedActionDb::get_awaited_action_by_id::validate_operation",
1206
                );
1207
            }
1208
        };
1209
1210
221
        if maybe_awaited_action.is_none() {
1211
8
            tracing::warn!(
1212
                "Found orphaned client operation mapping: client_id={} -> operation_id={}, \
1213
                but operation no longer exists. Returning None to prevent client from polling \
1214
                a non-existent operation.",
1215
                client_operation_id,
1216
                operation_id
1217
            );
1218
8
            return Ok(None);
1219
213
        }
1220
1221
213
        Ok(Some(OperationSubscriber::new(
1222
213
            Some(client_operation_id.clone()),
1223
213
            OperationIdToAwaitedAction(Cow::Owned(operation_id)),
1224
213
            Arc::downgrade(&self.store),
1225
213
            self.now_fn.clone(),
1226
213
            self.retain_completed_for,
1227
213
            self.client_keepalive_ttl,
1228
213
        )))
1229
221
    }
1230
}
1231
1232
impl<S, F, I, NowFn> AwaitedActionDb for StoreAwaitedActionDb<S, F, I, NowFn>
1233
where
1234
    S: SchedulerStore,
1235
    F: Fn() -> OperationId + Send + Sync + Unpin + 'static,
1236
    I: InstantWrapper,
1237
    NowFn: Fn() -> I + Send + Sync + Unpin + Clone + 'static,
1238
{
1239
    type Subscriber = OperationSubscriber<S, I, NowFn>;
1240
1241
221
    async fn get_awaited_action_by_id(
1242
221
        &self,
1243
221
        client_operation_id: &ClientOperationId,
1244
221
    ) -> Result<Option<Self::Subscriber>, Error> {
1245
221
        self.inner_get_awaited_action_by_id(client_operation_id)
1246
221
            .await
1247
221
    }
1248
1249
14.2k
    fn get_by_operation_id(
1250
14.2k
        &self,
1251
14.2k
        operation_id: &OperationId,
1252
14.2k
    ) -> impl Future<Output = Result<Option<Self::Subscriber>, Error>> {
1253
14.2k
        std::future::ready(Ok(Some(OperationSubscriber::new(
1254
14.2k
            None,
1255
14.2k
            OperationIdToAwaitedAction(Cow::Owned(operation_id.clone())),
1256
14.2k
            Arc::downgrade(&self.store),
1257
14.2k
            self.now_fn.clone(),
1258
14.2k
            self.retain_completed_for,
1259
14.2k
            self.client_keepalive_ttl,
1260
14.2k
        ))))
1261
14.2k
    }
1262
1263
10.0k
    async fn update_awaited_action(&self, new_awaited_action: AwaitedAction) -> Result<(), Error> {
1264
10.0k
        let expiry = if new_awaited_action.is_complete() {
1265
4.44k
            Some(self.retain_completed_for)
1266
        } else {
1267
5.61k
            None
1268
        };
1269
10.0k
        inner_update_awaited_action(self.store.as_ref(), new_awaited_action, expiry).await
1270
10.0k
    }
1271
1272
7.07k
    async fn add_action(
1273
7.07k
        &self,
1274
7.07k
        client_operation_id: ClientOperationId,
1275
7.07k
        action_info: Arc<ActionInfo>,
1276
7.07k
        no_event_action_timeout: Duration,
1277
7.07k
    ) -> Result<Self::Subscriber, Error> {
1278
        loop {
1279
            // Check to see if the action is already known and subscribe if it is.
1280
7.07k
            let 
mut awaited_action7.07k
= self
1281
7.07k
                .try_subscribe(
1282
7.07k
                    &client_operation_id,
1283
7.07k
                    &action_info.unique_qualifier,
1284
7.07k
                    no_event_action_timeout,
1285
7.07k
                    action_info.priority,
1286
7.07k
                )
1287
7.07k
                .await
1288
7.07k
                .err_tip(|| "In RedisAwaitedActionDb::add_action")
?1
1289
7.07k
                .unwrap_or_else(|| 
{7.06k
1290
7.06k
                    tracing::debug!(
1291
                        "Creating new action {:?} for operation {client_operation_id}",
1292
2.87k
                        action_info.digest()
1293
                    );
1294
7.06k
                    AwaitedAction::new(
1295
7.06k
                        (self.operation_id_creator)(),
1296
7.06k
                        action_info.clone(),
1297
7.06k
                        (self.now_fn)().now(),
1298
                    )
1299
7.06k
                });
1300
1301
7.07k
            debug_assert!(
1302
0
                !awaited_action.state().stage.is_finished(),
1303
                "Expected a queued or executing action; completed actions must be recreated"
1304
            );
1305
1306
7.07k
            let operation_id = awaited_action.operation_id().clone();
1307
7.07k
            if awaited_action.state().client_operation_id != operation_id {
1308
0
                // Just in case the client_operation_id was set to something else
1309
0
                // we put it back to the underlying operation_id.
1310
0
                awaited_action.set_client_operation_id(operation_id.clone());
1311
7.07k
            }
1312
7.07k
            awaited_action.update_client_keep_alive((self.now_fn)().now());
1313
1314
7.07k
            let version = awaited_action.version();
1315
7.07k
            let expiry = if awaited_action.is_complete() {
1316
0
                Some(self.retain_completed_for)
1317
            } else {
1318
7.07k
                None
1319
            };
1320
7.07k
            if self
1321
7.07k
                .store
1322
7.07k
                .update_data(UpdateOperationIdToAwaitedAction(awaited_action), expiry)
1323
7.07k
                .await
1324
7.07k
                .err_tip(|| "In RedisAwaitedActionDb::add_action")
?3
1325
7.07k
                .is_none()
1326
            {
1327
                // The version was out of date, try again.
1328
0
                tracing::info!(
1329
                    "Version out of date for {:?} {operation_id} {version}, retrying.",
1330
0
                    action_info.digest()
1331
                );
1332
0
                continue;
1333
7.07k
            }
1334
1335
            // Bound the cid_* mapping's lifetime (see CLIENT_ID_MAPPING_TTL).
1336
7.07k
            self.store
1337
7.07k
                .update_data(
1338
7.07k
                    UpdateClientIdToOperationId {
1339
7.07k
                        client_operation_id: client_operation_id.clone(),
1340
7.07k
                        operation_id: operation_id.clone(),
1341
7.07k
                    },
1342
7.07k
                    Some(CLIENT_ID_MAPPING_TTL),
1343
7.07k
                )
1344
7.07k
                .await
1345
7.07k
                .err_tip(|| "In RedisAwaitedActionDb::add_action while adding client mapping")
?0
;
1346
1347
7.07k
            return Ok(OperationSubscriber::new(
1348
7.07k
                Some(client_operation_id),
1349
7.07k
                OperationIdToAwaitedAction(Cow::Owned(operation_id)),
1350
7.07k
                Arc::downgrade(&self.store),
1351
7.07k
                self.now_fn.clone(),
1352
7.07k
                self.retain_completed_for,
1353
7.07k
                self.client_keepalive_ttl,
1354
7.07k
            ));
1355
        }
1356
7.07k
    }
1357
1358
122
    fn set_worker_registry(&mut self, worker_registry: SharedWorkerRegistry) {
1359
122
        worker_registry.set_leases(Arc::new(StoreWorkerLeases {
1360
122
            store: self.store.clone(),
1361
122
        }));
1362
122
        self.worker_registry = Some(worker_registry);
1363
122
    }
1364
1365
1.36k
    async fn exchange_fleet_capabilities(
1366
1.36k
        &self,
1367
1.36k
        scheduler_id: &str,
1368
1.36k
        local: Vec<PlatformProperties>,
1369
1.36k
        ttl: Duration,
1370
1.36k
    ) -> Result<Vec<PeerScheduler>, Error> {
1371
1.36k
        self.store
1372
1.36k
            .update_data(
1373
1.36k
                UpdateFleetCapabilities(FleetCapabilities {
1374
1.36k
                    scheduler_id: scheduler_id.to_string(),
1375
1.36k
                    workers: local,
1376
1.36k
                    renews_worker_leases: true,
1377
1.36k
                }),
1378
1.36k
                Some(ttl),
1379
1.36k
            )
1380
1.36k
            .await
1381
1.36k
            .err_tip(|| "In StoreAwaitedActionDb::exchange_fleet_capabilities publish")
?3
;
1382
1383
1.36k
        let 
stream1.36k
= self
1384
1.36k
            .store
1385
1.36k
            .search_by_index_prefix(SearchFleetCapabilities)
1386
1.36k
            .await
1387
1.36k
            .err_tip(|| "In StoreAwaitedActionDb::exchange_fleet_capabilities search")
?0
;
1388
        // Records that have expired on peers that stopped publishing are
1389
        // gone from the search already, so everything found here is live.
1390
1.36k
        stream
1391
1.36k
            .try_filter(|record| 
futures::future::ready1.34k
(
record.scheduler_id != scheduler_id1.34k
))
1392
1.36k
            .try_fold(Vec::new(), |mut peers, record| async move 
{22
1393
22
                peers.push(PeerScheduler {
1394
22
                    scheduler_id: record.scheduler_id,
1395
22
                    workers: record.workers,
1396
22
                    renews_worker_leases: record.renews_worker_leases,
1397
22
                });
1398
22
                Ok(peers)
1399
44
            })
1400
1.36k
            .await
1401
1.36k
            .err_tip(|| "In StoreAwaitedActionDb::exchange_fleet_capabilities collect")
1402
1.36k
    }
1403
1404
117
    fn shares_state(&self) -> bool {
1405
117
        true
1406
117
    }
1407
1408
14.6k
    async fn get_range_of_actions(
1409
14.6k
        &self,
1410
14.6k
        state: SortedAwaitedActionState,
1411
14.6k
        start: Bound<SortedAwaitedAction>,
1412
14.6k
        end: Bound<SortedAwaitedAction>,
1413
14.6k
        desc: bool,
1414
14.6k
    ) -> Result<impl Stream<Item = Result<Self::Subscriber, Error>> + Send, Error> {
1415
14.6k
        if !
matches!0
(start, Bound::Unbounded) {
1416
0
            return Err(make_err!(
1417
0
                Code::Unimplemented,
1418
0
                "Start bound is not supported in RedisAwaitedActionDb::get_range_of_actions",
1419
0
            ));
1420
14.6k
        }
1421
14.6k
        if !
matches!0
(end, Bound::Unbounded) {
1422
0
            return Err(make_err!(
1423
0
                Code::Unimplemented,
1424
0
                "End bound is not supported in RedisAwaitedActionDb::get_range_of_actions",
1425
0
            ));
1426
14.6k
        }
1427
        // The index is read in one direction, fixed by
1428
        // `SearchStateToAwaitedAction::SORT_DESCENDING`, and every caller
1429
        // asks for that direction. Ascending has no caller, so it is not
1430
        // implemented rather than silently served backwards.
1431
14.6k
        if !desc {
1432
0
            return Err(make_err!(
1433
0
                Code::Unimplemented,
1434
0
                "Ascending order is not supported in RedisAwaitedActionDb::get_range_of_actions",
1435
0
            ));
1436
14.6k
        }
1437
14.6k
        Ok(self
1438
14.6k
            .store
1439
14.6k
            .search_by_index_prefix(SearchStateToAwaitedAction(get_state_prefix(state)))
1440
14.6k
            .await
1441
14.6k
            .err_tip(|| "In RedisAwaitedActionDb::get_range_of_actions")
?0
1442
807k
            .
map_ok14.6k
(move |awaited_action| {
1443
807k
                OperationSubscriber::new(
1444
807k
                    None,
1445
807k
                    OperationIdToAwaitedAction(Cow::Owned(awaited_action.operation_id().clone())),
1446
807k
                    Arc::downgrade(&self.store),
1447
807k
                    self.now_fn.clone(),
1448
807k
                    self.retain_completed_for,
1449
807k
                    self.client_keepalive_ttl,
1450
                )
1451
807k
                .listed(awaited_action)
1452
807k
            }))
1453
14.6k
    }
1454
1455
0
    async fn get_all_awaited_actions(
1456
0
        &self,
1457
0
    ) -> Result<impl Stream<Item = Result<Self::Subscriber, Error>>, Error> {
1458
0
        Ok(self
1459
0
            .store
1460
0
            .search_by_index_prefix(SearchStateToAwaitedAction(""))
1461
0
            .await
1462
0
            .err_tip(|| "In RedisAwaitedActionDb::get_range_of_actions")?
1463
0
            .map_ok(move |awaited_action| {
1464
0
                OperationSubscriber::new(
1465
0
                    None,
1466
0
                    OperationIdToAwaitedAction(Cow::Owned(awaited_action.operation_id().clone())),
1467
0
                    Arc::downgrade(&self.store),
1468
0
                    self.now_fn.clone(),
1469
0
                    self.retain_completed_for,
1470
0
                    self.client_keepalive_ttl,
1471
                )
1472
0
                .listed(awaited_action)
1473
0
            }))
1474
0
    }
1475
}