Coverage Report

Created: 2025-04-19 16:54

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/build/source/nativelink-scheduler/src/cache_lookup_scheduler.rs
Line
Count
Source
1
// Copyright 2024 The NativeLink Authors. All rights reserved.
2
//
3
// Licensed under the Apache License, Version 2.0 (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
//    http://www.apache.org/licenses/LICENSE-2.0
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
use std::sync::Arc;
17
18
use async_trait::async_trait;
19
use nativelink_error::{Code, Error, ResultExt, make_err};
20
use nativelink_metric::{MetricsComponent, RootMetricsComponent};
21
use nativelink_proto::build::bazel::remote::execution::v2::{
22
    ActionResult as ProtoActionResult, GetActionResultRequest,
23
};
24
use nativelink_store::ac_utils::get_and_decode_digest;
25
use nativelink_store::grpc_store::GrpcStore;
26
use nativelink_util::action_messages::{
27
    ActionInfo, ActionStage, ActionState, ActionUniqueKey, ActionUniqueQualifier, OperationId,
28
};
29
use nativelink_util::background_spawn;
30
use nativelink_util::common::DigestInfo;
31
use nativelink_util::digest_hasher::DigestHasherFunc;
32
use nativelink_util::known_platform_property_provider::KnownPlatformPropertyProvider;
33
use nativelink_util::operation_state_manager::{
34
    ActionStateResult, ActionStateResultStream, ClientStateManager, OperationFilter,
35
};
36
use nativelink_util::origin_context::ActiveOriginContext;
37
use nativelink_util::origin_event::{ORIGIN_EVENT_COLLECTOR, OriginMetadata};
38
use nativelink_util::store_trait::Store;
39
use parking_lot::{Mutex, MutexGuard};
40
use scopeguard::guard;
41
use tokio::sync::oneshot;
42
use tonic::{Request, Response};
43
use tracing::{Level, event};
44
45
/// Actions that are having their cache checked or failed cache lookup and are
46
/// being forwarded upstream.  Missing the `skip_cache_check` actions which are
47
/// forwarded directly.
48
type CheckActions = HashMap<
49
    ActionUniqueKey,
50
    Vec<(
51
        OperationId,
52
        oneshot::Sender<Result<Box<dyn ActionStateResult>, Error>>,
53
    )>,
54
>;
55
56
#[derive(MetricsComponent)]
57
pub struct CacheLookupScheduler {
58
    /// A reference to the AC to find existing actions in.
59
    /// To prevent unintended issues, this store should probably be a `CompletenessCheckingStore`.
60
    #[metric(group = "ac_store")]
61
    ac_store: Store,
62
    /// The "real" scheduler to use to perform actions if they were not found
63
    /// in the action cache.
64
    #[metric(group = "action_scheduler")]
65
    action_scheduler: Arc<dyn ClientStateManager>,
66
    /// Actions that are currently performing a `CacheCheck`.
67
    inflight_cache_checks: Arc<Mutex<CheckActions>>,
68
}
69
70
impl std::fmt::Debug for CacheLookupScheduler {
71
0
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
72
0
        f.debug_struct("CacheLookupScheduler")
73
0
            .field("ac_store", &self.ac_store)
74
0
            .finish_non_exhaustive()
75
0
    }
76
}
77
78
0
async fn get_action_from_store(
79
0
    ac_store: &Store,
80
0
    action_digest: DigestInfo,
81
0
    instance_name: String,
82
0
    digest_function: DigestHasherFunc,
83
0
) -> Result<ProtoActionResult, Error> {
84
    // If we are a GrpcStore we shortcut here, as this is a special store.
85
0
    if let Some(grpc_store) = ac_store.downcast_ref::<GrpcStore>(Some(action_digest.into())) {
  Branch (85:12): [True: 0, False: 0]
  Branch (85:12): [Folded - Ignored]
86
0
        let action_result_request = GetActionResultRequest {
87
0
            instance_name,
88
0
            action_digest: Some(action_digest.into()),
89
0
            inline_stdout: false,
90
0
            inline_stderr: false,
91
0
            inline_output_files: Vec::new(),
92
0
            digest_function: digest_function.proto_digest_func().into(),
93
0
        };
94
0
        grpc_store
95
0
            .get_action_result(Request::new(action_result_request))
96
0
            .await
97
0
            .map(Response::into_inner)
98
    } else {
99
0
        get_and_decode_digest::<ProtoActionResult>(ac_store, action_digest.into()).await
100
    }
101
0
}
102
103
/// Future for when `ActionStateResults` are known.
104
type ActionStateResultOneshot = oneshot::Receiver<Result<Box<dyn ActionStateResult>, Error>>;
105
106
0
fn subscribe_to_existing_action(
107
0
    inflight_cache_checks: &mut MutexGuard<CheckActions>,
108
0
    unique_qualifier: &ActionUniqueKey,
109
0
    client_operation_id: &OperationId,
110
0
) -> Option<ActionStateResultOneshot> {
111
0
    inflight_cache_checks
112
0
        .get_mut(unique_qualifier)
113
0
        .map(|oneshots| {
114
0
            let (tx, rx) = oneshot::channel();
115
0
            oneshots.push((client_operation_id.clone(), tx));
116
0
            rx
117
0
        })
118
0
}
119
120
struct CacheLookupActionStateResult {
121
    action_state: Arc<ActionState>,
122
    maybe_origin_metadata: Option<OriginMetadata>,
123
    change_called: bool,
124
}
125
126
#[async_trait]
127
impl ActionStateResult for CacheLookupActionStateResult {
128
0
    async fn as_state(&self) -> Result<(Arc<ActionState>, Option<OriginMetadata>), Error> {
129
0
        Ok((
130
0
            self.action_state.clone(),
131
0
            self.maybe_origin_metadata.clone(),
132
0
        ))
133
0
    }
134
135
0
    async fn changed(&mut self) -> Result<(Arc<ActionState>, Option<OriginMetadata>), Error> {
136
0
        if self.change_called {
  Branch (136:12): [True: 0, False: 0]
  Branch (136:12): [Folded - Ignored]
137
0
            return Err(make_err!(
138
0
                Code::Internal,
139
0
                "CacheLookupActionStateResult::changed called twice"
140
0
            ));
141
0
        }
142
0
        self.change_called = true;
143
0
        Ok((
144
0
            self.action_state.clone(),
145
0
            self.maybe_origin_metadata.clone(),
146
0
        ))
147
0
    }
148
149
0
    async fn as_action_info(&self) -> Result<(Arc<ActionInfo>, Option<OriginMetadata>), Error> {
150
        // TODO(allada) We should probably remove as_action_info()
151
        // or implement it properly.
152
0
        return Err(make_err!(
153
0
            Code::Unimplemented,
154
0
            "as_action_info not implemented for CacheLookupActionStateResult::as_action_info"
155
0
        ));
156
0
    }
157
}
158
159
impl CacheLookupScheduler {
160
2
    pub fn new(
161
2
        ac_store: Store,
162
2
        action_scheduler: Arc<dyn ClientStateManager>,
163
2
    ) -> Result<Self, Error> {
164
2
        Ok(Self {
165
2
            ac_store,
166
2
            action_scheduler,
167
2
            inflight_cache_checks: Arc::default(),
168
2
        })
169
2
    }
170
171
1
    async fn inner_add_action(
172
1
        &self,
173
1
        client_operation_id: OperationId,
174
1
        action_info: Arc<ActionInfo>,
175
1
    ) -> Result<Box<dyn ActionStateResult>, Error> {
176
1
        let 
unique_key0
= match &action_info.unique_qualifier {
177
0
            ActionUniqueQualifier::Cachable(unique_key) => unique_key.clone(),
178
            ActionUniqueQualifier::Uncachable(_) => {
179
                // Cache lookup skipped, forward to the upstream.
180
1
                return self
181
1
                    .action_scheduler
182
1
                    .add_action(client_operation_id, action_info)
183
1
                    .await;
184
            }
185
        };
186
187
0
        let cache_check_result = {
188
0
            // Check this isn't a duplicate request first.
189
0
            let mut inflight_cache_checks = self.inflight_cache_checks.lock();
190
0
            subscribe_to_existing_action(
191
0
                &mut inflight_cache_checks,
192
0
                &unique_key,
193
0
                &client_operation_id,
194
0
            )
195
0
            .ok_or_else(move || {
196
0
                let (action_listener_tx, action_listener_rx) = oneshot::channel();
197
0
                inflight_cache_checks.insert(
198
0
                    unique_key.clone(),
199
0
                    vec![(client_operation_id, action_listener_tx)],
200
0
                );
201
0
                // In the event we loose the reference to our `scope_guard`, it will remove
202
0
                // the action from the inflight_cache_checks map.
203
0
                let inflight_cache_checks = self.inflight_cache_checks.clone();
204
0
                (
205
0
                    action_listener_rx,
206
0
                    guard((), move |()| {
207
0
                        inflight_cache_checks.lock().remove(&unique_key);
208
0
                    }),
209
                )
210
0
            })
211
        };
212
0
        let (action_listener_rx, scope_guard) = match cache_check_result {
213
0
            Ok(action_listener_fut) => {
214
0
                let action_listener = action_listener_fut.await.map_err(|_| {
215
0
                    make_err!(
216
0
                        Code::Internal,
217
0
                        "ActionStateResult tx hung up in CacheLookupScheduler::add_action"
218
0
                    )
219
0
                })?;
220
0
                return action_listener;
221
            }
222
0
            Err(client_tx_and_scope_guard) => client_tx_and_scope_guard,
223
0
        };
224
0
225
0
        let ac_store = self.ac_store.clone();
226
0
        let action_scheduler = self.action_scheduler.clone();
227
0
        let inflight_cache_checks = self.inflight_cache_checks.clone();
228
0
        // We need this spawn because we are returning a stream and this spawn will populate the stream's data.
229
0
        background_spawn!("cache_lookup_scheduler_add_action", async move {
230
0
            // If our spawn ever dies, we will remove the action from the inflight_cache_checks map.
231
0
            let _scope_guard = scope_guard;
232
233
0
            let unique_key = match &action_info.unique_qualifier {
234
0
                ActionUniqueQualifier::Cachable(unique_key) => unique_key,
235
0
                ActionUniqueQualifier::Uncachable(unique_key) => {
236
0
                    event!(
237
0
                        Level::ERROR,
238
                        ?action_info,
239
0
                        "ActionInfo::unique_qualifier should be ActionUniqueQualifier::Cachable()"
240
                    );
241
0
                    unique_key
242
                }
243
            };
244
245
            // Perform cache check.
246
0
            let instance_name = action_info.unique_qualifier.instance_name().clone();
247
0
            let maybe_action_result = get_action_from_store(
248
0
                &ac_store,
249
0
                action_info.unique_qualifier.digest(),
250
0
                instance_name,
251
0
                action_info.unique_qualifier.digest_function(),
252
0
            )
253
0
            .await;
254
0
            match maybe_action_result {
255
0
                Ok(action_result) => {
256
0
                    let maybe_pending_txs = {
257
0
                        let mut inflight_cache_checks = inflight_cache_checks.lock();
258
0
                        // We are ready to resolve the in-flight actions. We remove the
259
0
                        // in-flight actions from the map.
260
0
                        inflight_cache_checks.remove(unique_key)
261
                    };
262
0
                    let Some(pending_txs) = maybe_pending_txs else {
  Branch (262:25): [True: 0, False: 0]
  Branch (262:25): [Folded - Ignored]
263
0
                        return; // Nobody is waiting for this action anymore.
264
                    };
265
0
                    let mut action_state = ActionState {
266
0
                        client_operation_id: OperationId::default(),
267
0
                        stage: ActionStage::CompletedFromCache(action_result),
268
0
                        action_digest: action_info.unique_qualifier.digest(),
269
0
                    };
270
0
271
0
                    let maybe_origin_metadata =
272
0
                        ActiveOriginContext::get_value(&ORIGIN_EVENT_COLLECTOR)
273
0
                            .ok()
274
0
                            .flatten()
275
0
                            .map(|v| v.metadata.clone());
276
0
                    for (client_operation_id, pending_tx) in pending_txs {
277
0
                        action_state.client_operation_id = client_operation_id;
278
0
                        // Ignore errors here, as the other end may have hung up.
279
0
                        drop(pending_tx.send(Ok(Box::new(CacheLookupActionStateResult {
280
0
                            action_state: Arc::new(action_state.clone()),
281
0
                            maybe_origin_metadata: maybe_origin_metadata.clone(),
282
0
                            change_called: false,
283
0
                        }))));
284
0
                    }
285
0
                    return;
286
                }
287
0
                Err(err) => {
288
0
                    // NotFound errors just mean we need to execute our action.
289
0
                    if err.code != Code::NotFound {
  Branch (289:24): [True: 0, False: 0]
  Branch (289:24): [Folded - Ignored]
290
0
                        let err = err.append("In CacheLookupScheduler::add_action");
291
0
                        let maybe_pending_txs = {
292
0
                            let mut inflight_cache_checks = inflight_cache_checks.lock();
293
0
                            // We are ready to resolve the in-flight actions. We remove the
294
0
                            // in-flight actions from the map.
295
0
                            inflight_cache_checks.remove(unique_key)
296
                        };
297
0
                        let Some(pending_txs) = maybe_pending_txs else {
  Branch (297:29): [True: 0, False: 0]
  Branch (297:29): [Folded - Ignored]
298
0
                            return; // Nobody is waiting for this action anymore.
299
                        };
300
0
                        for (_client_operation_id, pending_tx) in pending_txs {
301
0
                            // Ignore errors here, as the other end may have hung up.
302
0
                            drop(pending_tx.send(Err(err.clone())));
303
0
                        }
304
0
                        return;
305
0
                    }
306
0
                }
307
0
            }
308
0
309
0
            let maybe_pending_txs = {
310
0
                let mut inflight_cache_checks = inflight_cache_checks.lock();
311
0
                inflight_cache_checks.remove(unique_key)
312
            };
313
0
            let Some(pending_txs) = maybe_pending_txs else {
  Branch (313:17): [True: 0, False: 0]
  Branch (313:17): [Folded - Ignored]
314
0
                return; // Noone is waiting for this action anymore.
315
            };
316
317
0
            for (client_operation_id, pending_tx) in pending_txs {
318
                // Ignore errors here, as the other end may have hung up.
319
0
                drop(
320
0
                    pending_tx.send(
321
0
                        action_scheduler
322
0
                            .add_action(client_operation_id, action_info.clone())
323
0
                            .await,
324
                    ),
325
                );
326
            }
327
0
        });
328
0
        action_listener_rx
329
0
            .await
330
0
            .map_err(|_| {
331
0
                make_err!(
332
0
                    Code::Internal,
333
0
                    "ActionStateResult tx hung up in CacheLookupScheduler::add_action"
334
0
                )
335
0
            })?
336
0
            .err_tip(|| "In CacheLookupScheduler::add_action")
337
1
    }
338
339
1
    async fn inner_filter_operations(
340
1
        &self,
341
1
        filter: OperationFilter,
342
1
    ) -> Result<ActionStateResultStream, Error> {
343
1
        self.action_scheduler
344
1
            .filter_operations(filter)
345
1
            .await
346
1
            .err_tip(|| 
"In CacheLookupScheduler::filter_operations"0
)
347
1
    }
348
}
349
350
#[async_trait]
351
impl ClientStateManager for CacheLookupScheduler {
352
    async fn add_action(
353
        &self,
354
        client_operation_id: OperationId,
355
        action_info: Arc<ActionInfo>,
356
2
    ) -> Result<Box<dyn ActionStateResult>, Error> {
357
1
        self.inner_add_action(client_operation_id, action_info)
358
1
            .await
359
2
    }
360
361
    async fn filter_operations(
362
        &self,
363
        filter: OperationFilter,
364
2
    ) -> Result<ActionStateResultStream, Error> {
365
1
        self.inner_filter_operations(filter).await
366
2
    }
367
368
0
    fn as_known_platform_property_provider(&self) -> Option<&dyn KnownPlatformPropertyProvider> {
369
0
        self.action_scheduler.as_known_platform_property_provider()
370
0
    }
371
}
372
373
impl RootMetricsComponent for CacheLookupScheduler {}