/build/source/nativelink-store/src/completeness_checking_store.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::pin::Pin; |
16 | | use core::{iter, mem}; |
17 | | use std::sync::Arc; |
18 | | |
19 | | use async_trait::async_trait; |
20 | | use futures::stream::{FuturesUnordered, StreamExt}; |
21 | | use futures::{FutureExt, TryFutureExt, select, try_join}; |
22 | | use nativelink_error::{Code, Error, ResultExt, make_err}; |
23 | | use nativelink_metric::MetricsComponent; |
24 | | use nativelink_proto::build::bazel::remote::execution::v2::{ |
25 | | ActionResult as ProtoActionResult, OutputDirectory as ProtoOutputDirectory, Tree as ProtoTree, |
26 | | }; |
27 | | use nativelink_util::buf_channel::{DropCloserReadHalf, DropCloserWriteHalf}; |
28 | | use nativelink_util::common::DigestInfo; |
29 | | use nativelink_util::health_utils::{HealthStatusIndicator, default_health_status_indicator}; |
30 | | use nativelink_util::metrics_utils::CounterWithTime; |
31 | | use nativelink_util::store_trait::{ |
32 | | RemoveCallback, Store, StoreDriver, StoreKey, StoreLike, UploadSizeInfo, |
33 | | }; |
34 | | use parking_lot::Mutex; |
35 | | use tokio::sync::Notify; |
36 | | |
37 | | use crate::ac_utils::{get_and_decode_digest, get_size_and_decode_digest}; |
38 | | |
39 | | /// Given a proto action result, return all relevant digests and |
40 | | /// output directories that need to be checked. |
41 | 8 | fn get_digests_and_output_dirs( |
42 | 8 | action_result: ProtoActionResult, |
43 | 8 | ) -> Result<(Vec<StoreKey<'static>>, Vec<ProtoOutputDirectory>), Error> { |
44 | | // TODO(palfrey) When `try_collect()` is stable we can use it instead. |
45 | 8 | let mut digest_iter = action_result |
46 | 8 | .output_files |
47 | 8 | .into_iter() |
48 | 8 | .filter_map(|file| file.digest.map(DigestInfo::try_from)) |
49 | 8 | .chain(action_result.stdout_digest.map(DigestInfo::try_from)) |
50 | 8 | .chain(action_result.stderr_digest.map(DigestInfo::try_from)); |
51 | 8 | let mut digest_infos = Vec::with_capacity(digest_iter.size_hint().1.unwrap_or(0)); |
52 | 8 | digest_iter |
53 | 24 | .try_for_each8 (|maybe_digest| { |
54 | 24 | digest_infos.push(maybe_digest?0 .into()); |
55 | 24 | Result::<_, Error>::Ok(()) |
56 | 24 | }) |
57 | 8 | .err_tip(|| "Some digests could not be converted to DigestInfos")?0 ; |
58 | 8 | Ok((digest_infos, action_result.output_directories)) |
59 | 8 | } |
60 | | |
61 | | /// Given a list of output directories recursively get all digests |
62 | | /// that need to be checked and pass them into `handle_digest_infos_fn` |
63 | | /// as they are found. |
64 | | #[expect(clippy::future_not_send)] // TODO(jhpratt) remove this |
65 | 8 | async fn check_output_directories<'a>( |
66 | 8 | cas_store: &Store, |
67 | 8 | output_directories: Vec<ProtoOutputDirectory>, |
68 | 8 | handle_digest_infos_fn: &impl Fn(Vec<StoreKey<'a>>), |
69 | 8 | ) -> Result<(), Error> { |
70 | 8 | let mut futures = FuturesUnordered::new(); |
71 | | |
72 | 8 | let tree_digests = output_directories |
73 | 8 | .into_iter() |
74 | 8 | .filter_map(|output_dir| output_dir.tree_digest.map(DigestInfo::try_from)); |
75 | 8 | for maybe_tree_digest in tree_digests { |
76 | 8 | let tree_digest = maybe_tree_digest |
77 | 8 | .err_tip(|| "Could not decode tree digest CompletenessCheckingStore::has")?0 ; |
78 | 8 | futures.push(async move { |
79 | 8 | let tree = get_and_decode_digest::<ProtoTree>(cas_store, tree_digest.into()).await?0 ; |
80 | | // TODO(palfrey) When `try_collect()` is stable we can use it instead. |
81 | | // https://github.com/rust-lang/rust/issues/94047 |
82 | 16 | let mut digest_iter8 = tree.children8 .into_iter8 ().chain8 (tree.root8 ).flat_map8 (|dir| { |
83 | 16 | dir.files |
84 | 16 | .into_iter() |
85 | 16 | .filter_map(|f| f.digest.map(DigestInfo::try_from)) |
86 | 16 | }); |
87 | | |
88 | 8 | let mut digest_infos = Vec::with_capacity(digest_iter.size_hint().1.unwrap_or(0)); |
89 | 8 | digest_iter |
90 | 16 | .try_for_each8 (|maybe_digest| { |
91 | 16 | digest_infos.push(maybe_digest?0 .into()); |
92 | 16 | Result::<_, Error>::Ok(()) |
93 | 16 | }) |
94 | 8 | .err_tip(|| "Expected digest to exist and be convertible")?0 ; |
95 | 8 | handle_digest_infos_fn(digest_infos); |
96 | 8 | Ok(()) |
97 | 8 | }); |
98 | | } |
99 | | |
100 | 16 | while let Some(result8 ) = futures.next().await { |
101 | 8 | match result { |
102 | 8 | Ok(()) => {} |
103 | 0 | Err(e) => return Err(e), |
104 | | } |
105 | | } |
106 | 8 | Ok(()) |
107 | 8 | } |
108 | | |
109 | | #[derive(Debug, MetricsComponent)] |
110 | | pub struct CompletenessCheckingStore { |
111 | | cas_store: Store, |
112 | | ac_store: Store, |
113 | | |
114 | | #[metric(help = "Incomplete entries hit in CompletenessCheckingStore")] |
115 | | incomplete_entries_counter: CounterWithTime, |
116 | | #[metric(help = "Complete entries hit in CompletenessCheckingStore")] |
117 | | complete_entries_counter: CounterWithTime, |
118 | | } |
119 | | |
120 | | impl CompletenessCheckingStore { |
121 | 10 | pub fn new(ac_store: Store, cas_store: Store) -> Arc<Self> { |
122 | 10 | Arc::new(Self { |
123 | 10 | cas_store, |
124 | 10 | ac_store, |
125 | 10 | incomplete_entries_counter: CounterWithTime::default(), |
126 | 10 | complete_entries_counter: CounterWithTime::default(), |
127 | 10 | }) |
128 | 10 | } |
129 | | |
130 | | /// Check that all files and directories in action results |
131 | | /// exist in the CAS. Does this by decoding digests and |
132 | | /// checking their existence in two separate sets of futures that |
133 | | /// are polled concurrently. |
134 | 10 | async fn inner_has_with_results( |
135 | 10 | &self, |
136 | 10 | action_result_digests: &[StoreKey<'_>], |
137 | 10 | results: &mut [Option<u64>], |
138 | 10 | ) -> Result<(), Error> { |
139 | | // Holds shared state between the different futures. |
140 | | // This is how get around lifetime issues. |
141 | | struct State<'a> { |
142 | | results: &'a mut [Option<u64>], |
143 | | digests_to_check: Vec<StoreKey<'a>>, |
144 | | digests_to_check_idxs: Vec<usize>, |
145 | | notify: Arc<Notify>, |
146 | | done: bool, |
147 | | } |
148 | | // Note: In theory Mutex is not needed, but lifetimes are |
149 | | // very tricky to get right here. Since we are using parking_lot |
150 | | // and we are guaranteed to never have lock collisions, it should |
151 | | // be nearly as fast as a few atomic operations. |
152 | 10 | let state_mux = &Mutex::new(State { |
153 | 10 | results, |
154 | 10 | digests_to_check: Vec::new(), |
155 | 10 | digests_to_check_idxs: Vec::new(), |
156 | 10 | // Note: Any time `digests_to_check` or `digests_to_check_idxs` is |
157 | 10 | // modified we must notify the subscriber here. |
158 | 10 | notify: Arc::new(Notify::new()), |
159 | 10 | done: false, |
160 | 10 | }); |
161 | | |
162 | 10 | let mut futures = action_result_digests |
163 | 10 | .iter() |
164 | 10 | .enumerate() |
165 | 10 | .map(|(i, digest)| { |
166 | 10 | async move { |
167 | | // Note: We don't err_tip here because often have NotFound here which is ok. |
168 | 10 | let (action_result8 , size8 ) = get_size_and_decode_digest::<ProtoActionResult>( |
169 | 10 | &self.ac_store, |
170 | 10 | digest.borrow(), |
171 | 10 | ) |
172 | 10 | .await?2 ; |
173 | | |
174 | 8 | let (mut digest_infos, output_directories) = |
175 | 8 | get_digests_and_output_dirs(action_result)?0 ; |
176 | | |
177 | | { |
178 | 8 | let mut state = state_mux.lock(); |
179 | | |
180 | | // We immediately set the size of the digest here. Later we will unset it if |
181 | | // we find that the digest has missing outputs. |
182 | 8 | state.results[i] = Some(size); |
183 | 8 | let rep_len = digest_infos.len(); |
184 | 8 | if state.digests_to_check.is_empty() { |
185 | 8 | // Hot path: Most actions only have files and only one digest |
186 | 8 | // requested to be checked. So we can avoid the heap allocation |
187 | 8 | // by just swapping out our container's stack if our pending_digests |
188 | 8 | // is empty. |
189 | 8 | mem::swap(&mut state.digests_to_check, &mut digest_infos); |
190 | 8 | } else { |
191 | 0 | state.digests_to_check.extend(digest_infos); |
192 | 0 | } |
193 | 8 | state |
194 | 8 | .digests_to_check_idxs |
195 | 8 | .extend(iter::repeat_n(i, rep_len)); |
196 | 8 | state.notify.notify_one(); |
197 | | } |
198 | | |
199 | | // Hot path: It is very common for no output directories to be defined. |
200 | | // So we can avoid any needless work by early returning. |
201 | 8 | if output_directories.is_empty() { |
202 | 0 | return Ok(()); |
203 | 8 | } |
204 | | |
205 | 8 | check_output_directories( |
206 | 8 | &self.cas_store, |
207 | 8 | output_directories, |
208 | 8 | &move |digest_infos| { |
209 | 8 | let mut state = state_mux.lock(); |
210 | 8 | let rep_len = digest_infos.len(); |
211 | 8 | state.digests_to_check.extend(digest_infos); |
212 | 8 | state |
213 | 8 | .digests_to_check_idxs |
214 | 8 | .extend(iter::repeat_n(i, rep_len)); |
215 | 8 | state.notify.notify_one(); |
216 | 8 | }, |
217 | | ) |
218 | 8 | .await?0 ; |
219 | | |
220 | 8 | Result::<(), Error>::Ok(()) |
221 | 10 | } |
222 | | // Add a tip to the error to help with debugging and the index of the |
223 | | // digest that failed so we know which one to unset. |
224 | 10 | .map_err(move |mut e| {2 |
225 | 2 | if e.code != Code::NotFound { |
226 | 2 | e = e.append( |
227 | 2 | format!("Error checking existence of digest ({digest}) in CompletenessCheckingStore::has"), |
228 | 2 | ); |
229 | 2 | }0 |
230 | 2 | (e, i) |
231 | 2 | }) |
232 | 10 | }) |
233 | 10 | .collect::<FuturesUnordered<_>>(); |
234 | | |
235 | | // This future will wait for the notify to be notified and then |
236 | | // check the CAS store for the digest's existence. |
237 | | // For optimization reasons we only allow one outstanding call to |
238 | | // the underlying `has_with_results()` at a time. This is because |
239 | | // we want to give the ability for stores to batch requests together |
240 | | // whenever possible. |
241 | | // The most common case is only one notify will ever happen. |
242 | 10 | let check_existence_fut = async { |
243 | 10 | let mut has_results = vec![]; |
244 | 10 | let notify = state_mux.lock().notify.clone(); |
245 | | loop { |
246 | 26 | notify.notified().await; |
247 | 16 | let (digests, indexes) = { |
248 | 24 | let mut state = state_mux.lock(); |
249 | 24 | if state.done { |
250 | 9 | if state.digests_to_check.is_empty() { |
251 | 8 | break; |
252 | 1 | } |
253 | | // Edge case: It is possible for our `digest_to_check` to have had |
254 | | // data added, `notify_one` called, then immediately `done` set to |
255 | | // true. We protect ourselves by checking if we have digests if done |
256 | | // is set, and if we do, let ourselves know to run again, but continue |
257 | | // processing the data. |
258 | 1 | notify.notify_one(); |
259 | 15 | } |
260 | 16 | ( |
261 | 16 | mem::take(&mut state.digests_to_check), |
262 | 16 | mem::take(&mut state.digests_to_check_idxs), |
263 | 16 | ) |
264 | | }; |
265 | 16 | assert_eq!( |
266 | 16 | digests.len(), |
267 | 16 | indexes.len(), |
268 | | "Expected sizes to match in CompletenessCheckingStore::has" |
269 | | ); |
270 | | |
271 | | // Recycle our results vector to avoid needless allocations. |
272 | 16 | has_results.clear(); |
273 | 16 | has_results.resize(digests.len(), None); |
274 | 16 | self.cas_store |
275 | 16 | .has_with_results(&digests, &mut has_results[..]) |
276 | 16 | .await |
277 | 16 | .err_tip( |
278 | | || "Error calling has_with_results() inside CompletenessCheckingStore::has", |
279 | 0 | )?; |
280 | 16 | let missed_indexes = has_results |
281 | 16 | .iter() |
282 | 16 | .zip(indexes) |
283 | 40 | .filter_map16 (|(r, index)| r.map_or_else(|| Some(index6 ), |_| None)); |
284 | | { |
285 | 16 | let mut state = state_mux.lock(); |
286 | 16 | for index6 in missed_indexes { |
287 | 6 | state.results[index] = None; |
288 | 6 | } |
289 | | } |
290 | | } |
291 | 8 | Result::<(), Error>::Ok(()) |
292 | 8 | } |
293 | 10 | .fuse(); |
294 | 10 | tokio::pin!(check_existence_fut); |
295 | | |
296 | | loop { |
297 | | // Poll both futures at the same time. |
298 | 18 | select! { |
299 | 0 | r = check_existence_fut => { |
300 | 0 | return Err(make_err!( |
301 | 0 | Code::Internal, |
302 | 0 | "CompletenessCheckingStore's check_existence_fut ended unexpectedly {r:?}" |
303 | 0 | )); |
304 | | } |
305 | 18 | maybe_result = futures.next() => { |
306 | 10 | match maybe_result { |
307 | 8 | Some(Ok(())) => self.complete_entries_counter.inc(), |
308 | 2 | Some(Err((err, i))) => { |
309 | 2 | self.incomplete_entries_counter.inc(); |
310 | | // Only a genuine `NotFound` may be laundered into a "missing" |
311 | | // slot (which callers surface as `Code::NotFound`). That covers |
312 | | // a truly absent action-result record and a clean completeness |
313 | | // miss — the intended eviction-coherence behavior (an evicted |
314 | | // referent must still 404). ANY other code is a real backend |
315 | | // read/decode failure; collapsing it into `None` would make an |
316 | | // I/O fault indistinguishable from absence and get served as a |
317 | | // 404. Propagate it so the caller can tell "genuinely absent" |
318 | | // from "could not determine". |
319 | 2 | if err.code != Code::NotFound { |
320 | 2 | return Err(err); |
321 | 0 | } |
322 | 0 | state_mux.lock().results[i] = None; |
323 | | } |
324 | | None => { |
325 | | // We are done, so flag it done and ensure we notify the |
326 | | // subscriber future. |
327 | 8 | { |
328 | 8 | let mut state = state_mux.lock(); |
329 | 8 | state.done = true; |
330 | 8 | state.notify.notify_one(); |
331 | 8 | } |
332 | 8 | check_existence_fut |
333 | 8 | .await |
334 | 8 | .err_tip(|| "CompletenessCheckingStore's check_existence_fut ended unexpectedly on last await")?0 ; |
335 | 8 | return Ok(()); |
336 | | } |
337 | | } |
338 | | } |
339 | | } |
340 | | } |
341 | | // Unreachable. |
342 | 10 | } |
343 | | } |
344 | | |
345 | | #[async_trait] |
346 | | impl StoreDriver for CompletenessCheckingStore { |
347 | 0 | async fn post_init(self: Arc<Self>) -> Result<(), Error> { |
348 | | try_join!( |
349 | | self.cas_store.clone().into_inner().post_init(), |
350 | | self.ac_store.clone().into_inner().post_init() |
351 | | )?; |
352 | | Ok(()) |
353 | 0 | } |
354 | | |
355 | | async fn has_with_results( |
356 | | self: Pin<&Self>, |
357 | | keys: &[StoreKey<'_>], |
358 | | results: &mut [Option<u64>], |
359 | 7 | ) -> Result<(), Error> { |
360 | | self.inner_has_with_results(keys, results).await |
361 | 7 | } |
362 | | |
363 | | async fn update( |
364 | | self: Pin<&Self>, |
365 | | key: StoreKey<'_>, |
366 | | reader: DropCloserReadHalf, |
367 | | size_info: UploadSizeInfo, |
368 | 8 | ) -> Result<u64, Error> { |
369 | | self.ac_store.update(key, reader, size_info).await |
370 | 8 | } |
371 | | |
372 | | async fn get_part( |
373 | | self: Pin<&Self>, |
374 | | key: StoreKey<'_>, |
375 | | writer: &mut DropCloserWriteHalf, |
376 | | offset: u64, |
377 | | length: Option<u64>, |
378 | 3 | ) -> Result<(), Error> { |
379 | | let results = &mut [None]; |
380 | | self.inner_has_with_results(&[key.borrow()], results) |
381 | | .await |
382 | | .err_tip(|| "when calling CompletenessCheckingStore::get_part")?; |
383 | | if results[0].is_none() { |
384 | | return Err(make_err!( |
385 | | Code::NotFound, |
386 | | "Digest found, but not all parts were found in CompletenessCheckingStore::get_part" |
387 | | )); |
388 | | } |
389 | | self.ac_store.get_part(key, writer, offset, length).await |
390 | 3 | } |
391 | | |
392 | 0 | fn inner_store(&self, _digest: Option<StoreKey>) -> &dyn StoreDriver { |
393 | 0 | self |
394 | 0 | } |
395 | | |
396 | 0 | fn as_any(&self) -> &(dyn core::any::Any + Sync + Send + 'static) { |
397 | 0 | self |
398 | 0 | } |
399 | | |
400 | 0 | fn as_any_arc(self: Arc<Self>) -> Arc<dyn core::any::Any + Sync + Send + 'static> { |
401 | 0 | self |
402 | 0 | } |
403 | | |
404 | 0 | fn register_remove_callback(self: Arc<Self>, callback: RemoveCallback) -> Result<(), Error> { |
405 | 0 | self.ac_store.register_remove_callback(callback.clone())?; |
406 | 0 | self.cas_store.register_remove_callback(callback)?; |
407 | 0 | Ok(()) |
408 | 0 | } |
409 | | } |
410 | | |
411 | | default_health_status_indicator!(CompletenessCheckingStore); |