Line data Source code
1 : use std::time::UNIX_EPOCH;
2 :
3 : use pageserver_api::key::{CONTROLFILE_KEY, Key};
4 : use tokio::task::JoinSet;
5 : use utils::completion::{self, Completion};
6 : use utils::id::TimelineId;
7 :
8 : use super::failpoints::{Failpoint, FailpointKind};
9 : use super::*;
10 : use crate::context::DownloadBehavior;
11 : use crate::tenant::harness::{TenantHarness, test_img};
12 : use crate::tenant::storage_layer::{IoConcurrency, LayerVisibilityHint};
13 :
14 : /// Used in tests to advance a future to wanted await point, and not futher.
15 : const ADVANCE: std::time::Duration = std::time::Duration::from_secs(3600);
16 :
17 : /// Used in tests to indicate forever long timeout; has to be longer than the amount of ADVANCE
18 : /// timeout uses to advance futures.
19 : const FOREVER: std::time::Duration = std::time::Duration::from_secs(ADVANCE.as_secs() * 24 * 7);
20 :
21 : /// Demonstrate the API and resident -> evicted -> resident -> deleted transitions.
22 : #[tokio::test]
23 4 : async fn smoke_test() {
24 4 : let handle = tokio::runtime::Handle::current();
25 4 :
26 4 : let h = TenantHarness::create("smoke_test").await.unwrap();
27 4 : let span = h.span();
28 4 : let download_span = span.in_scope(|| tracing::info_span!("downloading", timeline_id = 1));
29 4 : let (tenant, ctx) = h.load().await;
30 4 : let io_concurrency = IoConcurrency::spawn_for_test();
31 4 :
32 4 : let image_layers = vec![(
33 4 : Lsn(0x40),
34 4 : vec![(
35 4 : Key::from_hex("620000000033333333444444445500000000").unwrap(),
36 4 : test_img("foo"),
37 4 : )],
38 4 : )];
39 4 :
40 4 : // Create a test timeline with one real layer, and one synthetic test layer. The synthetic
41 4 : // one is only there so that we can GC the real one without leaving the timeline's metadata
42 4 : // empty, which is an illegal state (see [`IndexPart::validate`]).
43 4 : let timeline = tenant
44 4 : .create_test_timeline_with_layers(
45 4 : TimelineId::generate(),
46 4 : Lsn(0x10),
47 4 : 14,
48 4 : &ctx,
49 4 : Default::default(), // in-memory layers
50 4 : Default::default(),
51 4 : image_layers,
52 4 : Lsn(0x100),
53 4 : )
54 4 : .await
55 4 : .unwrap();
56 4 : let ctx = &ctx.with_scope_timeline(&timeline);
57 4 :
58 4 : // Grab one of the timeline's layers to exercise in the test, and the other layer that is just
59 4 : // there to avoid the timeline being illegally empty
60 4 : let (layer, dummy_layer) = {
61 4 : let mut layers = {
62 4 : let layers = timeline.layers.read().await;
63 4 : layers.likely_resident_layers().cloned().collect::<Vec<_>>()
64 4 : };
65 4 :
66 4 : assert_eq!(layers.len(), 2);
67 4 :
68 8 : layers.sort_by_key(|l| l.layer_desc().get_key_range().start);
69 4 : let synthetic_layer = layers.pop().unwrap();
70 4 : let real_layer = layers.pop().unwrap();
71 4 : tracing::info!(
72 4 : "real_layer={:?} ({}), synthetic_layer={:?} ({})",
73 0 : real_layer,
74 0 : real_layer.layer_desc().file_size,
75 0 : synthetic_layer,
76 0 : synthetic_layer.layer_desc().file_size
77 4 : );
78 4 : (real_layer, synthetic_layer)
79 4 : };
80 4 :
81 4 : // all layers created at pageserver are like `layer`, initialized with strong
82 4 : // Arc<DownloadedLayer>.
83 4 :
84 4 : let controlfile_keyspace = KeySpace {
85 4 : ranges: vec![CONTROLFILE_KEY..CONTROLFILE_KEY.next()],
86 4 : };
87 4 :
88 4 : let img_before = {
89 4 : let mut data = ValuesReconstructState::new(io_concurrency.clone());
90 4 : layer
91 4 : .get_values_reconstruct_data(
92 4 : controlfile_keyspace.clone(),
93 4 : Lsn(0x10)..Lsn(0x11),
94 4 : &mut data,
95 4 : ctx,
96 4 : )
97 4 : .await
98 4 : .unwrap();
99 4 :
100 4 : data.keys
101 4 : .remove(&CONTROLFILE_KEY)
102 4 : .expect("must be present")
103 4 : .collect_pending_ios()
104 4 : .await
105 4 : .expect("must not error")
106 4 : .img
107 4 : .take()
108 4 : .expect("tenant harness writes the control file")
109 4 : };
110 4 :
111 4 : // important part is evicting the layer, which can be done when there are no more ResidentLayer
112 4 : // instances -- there currently are none, only two `Layer` values, one in the layermap and on
113 4 : // in scope.
114 4 : layer.evict_and_wait(FOREVER).await.unwrap();
115 4 :
116 4 : // double-evict returns an error, which is valid if both eviction_task and disk usage based
117 4 : // eviction would both evict the same layer at the same time.
118 4 :
119 4 : let e = layer.evict_and_wait(FOREVER).await.unwrap_err();
120 4 : assert!(matches!(e, EvictionError::NotFound));
121 4 :
122 4 : let dl_ctx = RequestContextBuilder::from(ctx)
123 4 : .download_behavior(DownloadBehavior::Download)
124 4 : .attached_child();
125 4 :
126 4 : // on accesses when the layer is evicted, it will automatically be downloaded.
127 4 : let img_after = {
128 4 : let mut data = ValuesReconstructState::new(io_concurrency.clone());
129 4 : layer
130 4 : .get_values_reconstruct_data(
131 4 : controlfile_keyspace.clone(),
132 4 : Lsn(0x10)..Lsn(0x11),
133 4 : &mut data,
134 4 : &dl_ctx,
135 4 : )
136 4 : .instrument(download_span.clone())
137 4 : .await
138 4 : .unwrap();
139 4 : data.keys
140 4 : .remove(&CONTROLFILE_KEY)
141 4 : .expect("must be present")
142 4 : .collect_pending_ios()
143 4 : .await
144 4 : .expect("must not error")
145 4 : .img
146 4 : .take()
147 4 : .expect("tenant harness writes the control file")
148 4 : };
149 4 :
150 4 : assert_eq!(img_before, img_after);
151 4 :
152 4 : // evict_and_wait can timeout, but it doesn't cancel the evicting itself
153 4 : //
154 4 : // ZERO for timeout does not work reliably, so first take up all spawn_blocking slots to
155 4 : // artificially slow it down.
156 4 : let helper = SpawnBlockingPoolHelper::consume_all_spawn_blocking_threads(&handle).await;
157 4 :
158 4 : match layer
159 4 : .evict_and_wait(std::time::Duration::ZERO)
160 4 : .await
161 4 : .unwrap_err()
162 4 : {
163 4 : EvictionError::Timeout => {
164 4 : // expected, but note that the eviction is "still ongoing"
165 4 : helper.release().await;
166 4 : // exhaust spawn_blocking pool to ensure it is now complete
167 4 : SpawnBlockingPoolHelper::consume_and_release_all_of_spawn_blocking_threads(&handle)
168 4 : .await;
169 4 : }
170 4 : other => unreachable!("{other:?}"),
171 4 : }
172 4 :
173 4 : // only way to query if a layer is resident is to acquire a ResidentLayer instance.
174 4 : // Layer::keep_resident never downloads, but it might initialize if the layer file is found
175 4 : // downloaded locally.
176 4 : let none = layer.keep_resident().await;
177 4 : assert!(
178 4 : none.is_none(),
179 4 : "Expected none, because eviction removed the local file, found: {none:?}"
180 4 : );
181 4 :
182 4 : // plain downloading is rarely needed
183 4 : layer
184 4 : .download_and_keep_resident(&dl_ctx)
185 4 : .instrument(download_span)
186 4 : .await
187 4 : .unwrap();
188 4 :
189 4 : // last important part is deletion on drop: gc and compaction use it for compacted L0 layers
190 4 : // or fully garbage collected layers. deletion means deleting the local file, and scheduling a
191 4 : // deletion of the already unlinked from index_part.json remote file.
192 4 : //
193 4 : // marking a layer to be deleted on drop is irreversible; there is no technical reason against
194 4 : // reversiblity, but currently it is not needed so it is not provided.
195 4 : layer.delete_on_drop();
196 4 :
197 4 : let path = layer.local_path().to_owned();
198 4 :
199 4 : // wait_drop produces an unconnected to Layer future which will resolve when the
200 4 : // LayerInner::drop has completed.
201 4 : let mut wait_drop = std::pin::pin!(layer.wait_drop());
202 4 :
203 4 : // paused time doesn't really work well with timeouts and evict_and_wait, so delay pausing
204 4 : // until here
205 4 : tokio::time::pause();
206 4 : tokio::time::timeout(ADVANCE, &mut wait_drop)
207 4 : .await
208 4 : .expect_err("should had timed out because two strong references exist");
209 4 :
210 4 : tokio::fs::metadata(&path)
211 4 : .await
212 4 : .expect("the local layer file still exists");
213 4 :
214 4 : let rtc = &timeline.remote_client;
215 4 :
216 4 : // Simulate GC removing our test layer.
217 4 : {
218 4 : let mut g = timeline.layers.write().await;
219 4 :
220 4 : let layers = &[layer];
221 4 : g.open_mut().unwrap().finish_gc_timeline(layers);
222 4 :
223 4 : // this just updates the remote_physical_size for demonstration purposes
224 4 : rtc.schedule_gc_update(layers).unwrap();
225 4 : }
226 4 :
227 4 : // when strong references are dropped, the file is deleted and remote deletion is scheduled
228 4 : wait_drop.await;
229 4 :
230 4 : let e = tokio::fs::metadata(&path)
231 4 : .await
232 4 : .expect_err("the local file is deleted");
233 4 : assert_eq!(e.kind(), std::io::ErrorKind::NotFound);
234 4 :
235 4 : rtc.wait_completion().await.unwrap();
236 4 :
237 4 : assert_eq!(
238 4 : rtc.get_remote_physical_size(),
239 4 : dummy_layer.metadata().file_size
240 4 : );
241 4 : assert_eq!(0, LAYER_IMPL_METRICS.inits_cancelled.get())
242 4 : }
243 :
244 : /// This test demonstrates a previous hang when a eviction and deletion were requested at the same
245 : /// time. Now both of them complete per Arc drop semantics.
246 : #[tokio::test(start_paused = true)]
247 4 : async fn evict_and_wait_on_wanted_deleted() {
248 4 : // this is the runtime on which Layer spawns the blocking tasks on
249 4 : let handle = tokio::runtime::Handle::current();
250 4 :
251 4 : let h = TenantHarness::create("evict_and_wait_on_wanted_deleted")
252 4 : .await
253 4 : .unwrap();
254 4 : utils::logging::replace_panic_hook_with_tracing_panic_hook().forget();
255 4 : let (tenant, ctx) = h.load().await;
256 4 :
257 4 : let timeline = tenant
258 4 : .create_test_timeline(TimelineId::generate(), Lsn(0x10), 14, &ctx)
259 4 : .await
260 4 : .unwrap();
261 4 :
262 4 : let layer = {
263 4 : let mut layers = {
264 4 : let layers = timeline.layers.read().await;
265 4 : layers.likely_resident_layers().cloned().collect::<Vec<_>>()
266 4 : };
267 4 :
268 4 : assert_eq!(layers.len(), 1);
269 4 :
270 4 : layers.swap_remove(0)
271 4 : };
272 4 :
273 4 : // setup done
274 4 :
275 4 : let resident = layer.keep_resident().await.unwrap();
276 4 :
277 4 : {
278 4 : let mut evict_and_wait = std::pin::pin!(layer.evict_and_wait(FOREVER));
279 4 :
280 4 : // drive the future to await on the status channel
281 4 : tokio::time::timeout(ADVANCE, &mut evict_and_wait)
282 4 : .await
283 4 : .expect_err("should had been a timeout since we are holding the layer resident");
284 4 :
285 4 : layer.delete_on_drop();
286 4 :
287 4 : drop(resident);
288 4 :
289 4 : // make sure the eviction task gets to run
290 4 : SpawnBlockingPoolHelper::consume_and_release_all_of_spawn_blocking_threads(&handle).await;
291 4 :
292 4 : let resident = layer.keep_resident().await;
293 4 : assert!(
294 4 : resident.is_none(),
295 4 : "keep_resident should not have re-initialized: {resident:?}"
296 4 : );
297 4 :
298 4 : evict_and_wait
299 4 : .await
300 4 : .expect("evict_and_wait should had succeeded");
301 4 :
302 4 : // works as intended
303 4 : }
304 4 :
305 4 : // assert that once we remove the `layer` from the layer map and drop our reference,
306 4 : // the deletion of the layer in remote_storage happens.
307 4 : {
308 4 : let mut layers = timeline.layers.write().await;
309 4 : layers.open_mut().unwrap().finish_gc_timeline(&[layer]);
310 4 : }
311 4 :
312 4 : SpawnBlockingPoolHelper::consume_and_release_all_of_spawn_blocking_threads(&handle).await;
313 4 :
314 4 : assert_eq!(1, LAYER_IMPL_METRICS.started_deletes.get());
315 4 : assert_eq!(1, LAYER_IMPL_METRICS.completed_deletes.get());
316 4 : assert_eq!(1, LAYER_IMPL_METRICS.started_evictions.get());
317 4 : assert_eq!(1, LAYER_IMPL_METRICS.completed_evictions.get());
318 4 : assert_eq!(0, LAYER_IMPL_METRICS.inits_cancelled.get())
319 4 : }
320 :
321 : /// This test ensures we are able to read the layer while the layer eviction has been
322 : /// started but not completed.
323 : #[test]
324 4 : fn read_wins_pending_eviction() {
325 4 : let rt = tokio::runtime::Builder::new_current_thread()
326 4 : .max_blocking_threads(1)
327 4 : .enable_all()
328 4 : .start_paused(true)
329 4 : .build()
330 4 : .unwrap();
331 4 :
332 4 : rt.block_on(async move {
333 4 : // this is the runtime on which Layer spawns the blocking tasks on
334 4 : let handle = tokio::runtime::Handle::current();
335 4 : let h = TenantHarness::create("read_wins_pending_eviction")
336 4 : .await
337 4 : .unwrap();
338 4 : let (tenant, ctx) = h.load().await;
339 4 : let span = h.span();
340 4 : let download_span = span.in_scope(|| tracing::info_span!("downloading", timeline_id = 1));
341 :
342 4 : let timeline = tenant
343 4 : .create_test_timeline(TimelineId::generate(), Lsn(0x10), 14, &ctx)
344 4 : .await
345 4 : .unwrap();
346 4 : let ctx = ctx.with_scope_timeline(&timeline);
347 :
348 4 : let layer = {
349 4 : let mut layers = {
350 4 : let layers = timeline.layers.read().await;
351 4 : layers.likely_resident_layers().cloned().collect::<Vec<_>>()
352 4 : };
353 4 :
354 4 : assert_eq!(layers.len(), 1);
355 :
356 4 : layers.swap_remove(0)
357 : };
358 :
359 : // setup done
360 :
361 4 : let resident = layer.keep_resident().await.unwrap();
362 4 :
363 4 : let mut evict_and_wait = std::pin::pin!(layer.evict_and_wait(FOREVER));
364 4 :
365 4 : // drive the future to await on the status channel
366 4 : tokio::time::timeout(ADVANCE, &mut evict_and_wait)
367 4 : .await
368 4 : .expect_err("should had been a timeout since we are holding the layer resident");
369 4 : assert_eq!(1, LAYER_IMPL_METRICS.started_evictions.get());
370 :
371 4 : let (completion, barrier) = utils::completion::channel();
372 4 : let (arrival, arrived_at_barrier) = utils::completion::channel();
373 4 : layer.enable_failpoint(Failpoint::WaitBeforeStartingEvicting(
374 4 : Some(arrival),
375 4 : barrier,
376 4 : ));
377 4 :
378 4 : // now the eviction cannot proceed because the threads are consumed while completion exists
379 4 : drop(resident);
380 4 : arrived_at_barrier.wait().await;
381 4 : assert!(!layer.is_likely_resident());
382 :
383 : // because no actual eviction happened, we get to just reinitialize the DownloadedLayer
384 4 : layer
385 4 : .0
386 4 : .get_or_maybe_download(false, &ctx)
387 4 : .instrument(download_span)
388 4 : .await
389 4 : .expect("should had reinitialized without downloading");
390 4 :
391 4 : assert!(layer.is_likely_resident());
392 :
393 : // reinitialization notifies of new resident status, which should error out all evict_and_wait
394 4 : let e = tokio::time::timeout(ADVANCE, &mut evict_and_wait)
395 4 : .await
396 4 : .expect("no timeout, because get_or_maybe_download re-initialized")
397 4 : .expect_err("eviction should not have succeeded because re-initialized");
398 4 :
399 4 : // works as intended: evictions lose to "downloads"
400 4 : assert!(matches!(e, EvictionError::Downloaded), "{e:?}");
401 4 : assert_eq!(0, LAYER_IMPL_METRICS.completed_evictions.get());
402 :
403 : // this is not wrong: the eviction is technically still "on the way" as it's still queued
404 : // because of a failpoint
405 4 : assert_eq!(
406 4 : 0,
407 4 : LAYER_IMPL_METRICS
408 4 : .cancelled_evictions
409 4 : .values()
410 36 : .map(|ctr| ctr.get())
411 4 : .sum::<u64>()
412 4 : );
413 :
414 4 : drop(completion);
415 4 :
416 4 : tokio::time::sleep(ADVANCE).await;
417 4 : SpawnBlockingPoolHelper::consume_and_release_all_of_spawn_blocking_threads0(&handle, 1)
418 4 : .await;
419 :
420 4 : assert_eq!(0, LAYER_IMPL_METRICS.completed_evictions.get());
421 :
422 : // now we finally can observe the original eviction failing
423 : // it would had been possible to observe it earlier, but here it is guaranteed to have
424 : // happened.
425 4 : assert_eq!(
426 4 : 1,
427 4 : LAYER_IMPL_METRICS
428 4 : .cancelled_evictions
429 4 : .values()
430 36 : .map(|ctr| ctr.get())
431 4 : .sum::<u64>()
432 4 : );
433 :
434 4 : assert_eq!(
435 4 : 1,
436 4 : LAYER_IMPL_METRICS.cancelled_evictions[EvictionCancelled::AlreadyReinitialized].get()
437 4 : );
438 :
439 4 : assert_eq!(0, LAYER_IMPL_METRICS.inits_cancelled.get())
440 4 : });
441 4 : }
442 :
443 : /// Use failpoint to delay an eviction starting to get a VersionCheckFailed.
444 : #[test]
445 4 : fn multiple_pending_evictions_in_order() {
446 4 : let name = "multiple_pending_evictions_in_order";
447 4 : let in_order = true;
448 4 : multiple_pending_evictions_scenario(name, in_order);
449 4 : }
450 :
451 : /// Use failpoint to reorder later eviction before first to get a UnexpectedEvictedState.
452 : #[test]
453 4 : fn multiple_pending_evictions_out_of_order() {
454 4 : let name = "multiple_pending_evictions_out_of_order";
455 4 : let in_order = false;
456 4 : multiple_pending_evictions_scenario(name, in_order);
457 4 : }
458 :
459 8 : fn multiple_pending_evictions_scenario(name: &'static str, in_order: bool) {
460 8 : let rt = tokio::runtime::Builder::new_current_thread()
461 8 : .max_blocking_threads(1)
462 8 : .enable_all()
463 8 : .start_paused(true)
464 8 : .build()
465 8 : .unwrap();
466 8 :
467 8 : rt.block_on(async move {
468 8 : // this is the runtime on which Layer spawns the blocking tasks on
469 8 : let handle = tokio::runtime::Handle::current();
470 8 : let h = TenantHarness::create(name).await.unwrap();
471 8 : let (tenant, ctx) = h.load().await;
472 8 : let span = h.span();
473 8 : let download_span = span.in_scope(|| tracing::info_span!("downloading", timeline_id = 1));
474 :
475 8 : let timeline = tenant
476 8 : .create_test_timeline(TimelineId::generate(), Lsn(0x10), 14, &ctx)
477 8 : .await
478 8 : .unwrap();
479 8 : let ctx = ctx.with_scope_timeline(&timeline);
480 :
481 8 : let layer = {
482 8 : let mut layers = {
483 8 : let layers = timeline.layers.read().await;
484 8 : layers.likely_resident_layers().cloned().collect::<Vec<_>>()
485 8 : };
486 8 :
487 8 : assert_eq!(layers.len(), 1);
488 :
489 8 : layers.swap_remove(0)
490 : };
491 :
492 : // setup done
493 :
494 8 : let resident = layer.keep_resident().await.unwrap();
495 8 :
496 8 : let mut evict_and_wait = std::pin::pin!(layer.evict_and_wait(FOREVER));
497 8 :
498 8 : // drive the future to await on the status channel
499 8 : tokio::time::timeout(ADVANCE, &mut evict_and_wait)
500 8 : .await
501 8 : .expect_err("should had been a timeout since we are holding the layer resident");
502 8 : assert_eq!(1, LAYER_IMPL_METRICS.started_evictions.get());
503 :
504 8 : let (completion1, barrier) = utils::completion::channel();
505 8 : let mut completion1 = Some(completion1);
506 8 : let (arrival, arrived_at_barrier) = utils::completion::channel();
507 8 : layer.enable_failpoint(Failpoint::WaitBeforeStartingEvicting(
508 8 : Some(arrival),
509 8 : barrier,
510 8 : ));
511 8 :
512 8 : // now the eviction cannot proceed because we are simulating arbitrary long delay for the
513 8 : // eviction task start.
514 8 : drop(resident);
515 8 : assert!(!layer.is_likely_resident());
516 :
517 8 : arrived_at_barrier.wait().await;
518 :
519 : // because no actual eviction happened, we get to just reinitialize the DownloadedLayer
520 8 : layer
521 8 : .0
522 8 : .get_or_maybe_download(false, &ctx)
523 8 : .instrument(download_span)
524 8 : .await
525 8 : .expect("should had reinitialized without downloading");
526 8 :
527 8 : assert!(layer.is_likely_resident());
528 :
529 : // reinitialization notifies of new resident status, which should error out all evict_and_wait
530 8 : let e = tokio::time::timeout(ADVANCE, &mut evict_and_wait)
531 8 : .await
532 8 : .expect("no timeout, because get_or_maybe_download re-initialized")
533 8 : .expect_err("eviction should not have succeeded because re-initialized");
534 8 :
535 8 : // works as intended: evictions lose to "downloads"
536 8 : assert!(matches!(e, EvictionError::Downloaded), "{e:?}");
537 8 : assert_eq!(0, LAYER_IMPL_METRICS.completed_evictions.get());
538 :
539 : // this is not wrong: the eviction is technically still "on the way" as it's still queued
540 : // because of a failpoint
541 8 : assert_eq!(
542 8 : 0,
543 8 : LAYER_IMPL_METRICS
544 8 : .cancelled_evictions
545 8 : .values()
546 72 : .map(|ctr| ctr.get())
547 8 : .sum::<u64>()
548 8 : );
549 :
550 8 : assert_eq!(0, LAYER_IMPL_METRICS.completed_evictions.get());
551 :
552 : // configure another failpoint for the second eviction -- evictions are per initialization,
553 : // so now that we've reinitialized the inner, we get to run two of them at the same time.
554 8 : let (completion2, barrier) = utils::completion::channel();
555 8 : let (arrival, arrived_at_barrier) = utils::completion::channel();
556 8 : layer.enable_failpoint(Failpoint::WaitBeforeStartingEvicting(
557 8 : Some(arrival),
558 8 : barrier,
559 8 : ));
560 8 :
561 8 : let mut second_eviction = std::pin::pin!(layer.evict_and_wait(FOREVER));
562 8 :
563 8 : // advance to the wait on the queue
564 8 : tokio::time::timeout(ADVANCE, &mut second_eviction)
565 8 : .await
566 8 : .expect_err("timeout because failpoint is blocking");
567 8 :
568 8 : arrived_at_barrier.wait().await;
569 :
570 8 : assert_eq!(2, LAYER_IMPL_METRICS.started_evictions.get());
571 :
572 8 : let mut release_earlier_eviction = |expected_reason| {
573 8 : assert_eq!(
574 8 : 0,
575 8 : LAYER_IMPL_METRICS.cancelled_evictions[expected_reason].get(),
576 8 : );
577 :
578 8 : drop(completion1.take().unwrap());
579 8 :
580 8 : let handle = &handle;
581 :
582 8 : async move {
583 8 : tokio::time::sleep(ADVANCE).await;
584 8 : SpawnBlockingPoolHelper::consume_and_release_all_of_spawn_blocking_threads0(
585 8 : handle, 1,
586 8 : )
587 8 : .await;
588 :
589 8 : assert_eq!(
590 8 : 1,
591 8 : LAYER_IMPL_METRICS.cancelled_evictions[expected_reason].get(),
592 8 : );
593 8 : }
594 8 : };
595 :
596 8 : if in_order {
597 4 : release_earlier_eviction(EvictionCancelled::VersionCheckFailed).await;
598 4 : }
599 :
600 : // release the later eviction which is for the current version
601 8 : drop(completion2);
602 8 : tokio::time::sleep(ADVANCE).await;
603 8 : SpawnBlockingPoolHelper::consume_and_release_all_of_spawn_blocking_threads0(&handle, 1)
604 8 : .await;
605 :
606 8 : if !in_order {
607 4 : release_earlier_eviction(EvictionCancelled::UnexpectedEvictedState).await;
608 4 : }
609 :
610 8 : tokio::time::timeout(ADVANCE, &mut second_eviction)
611 8 : .await
612 8 : .expect("eviction goes through now that spawn_blocking is unclogged")
613 8 : .expect("eviction should succeed, because version matches");
614 8 :
615 8 : assert_eq!(1, LAYER_IMPL_METRICS.completed_evictions.get());
616 :
617 : // ensure the cancelled are unchanged
618 8 : assert_eq!(
619 8 : 1,
620 8 : LAYER_IMPL_METRICS
621 8 : .cancelled_evictions
622 8 : .values()
623 72 : .map(|ctr| ctr.get())
624 8 : .sum::<u64>()
625 8 : );
626 :
627 8 : assert_eq!(0, LAYER_IMPL_METRICS.inits_cancelled.get())
628 8 : });
629 8 : }
630 :
631 : /// The test ensures with a failpoint that a pending eviction is not cancelled by what is currently
632 : /// a `Layer::keep_resident` call.
633 : ///
634 : /// This matters because cancelling the eviction would leave us in a state where the file is on
635 : /// disk but the layer internal state says it has not been initialized. Futhermore, it allows us to
636 : /// have non-repairing `Layer::is_likely_resident`.
637 : #[tokio::test(start_paused = true)]
638 4 : async fn cancelled_get_or_maybe_download_does_not_cancel_eviction() {
639 4 : let handle = tokio::runtime::Handle::current();
640 4 : let h = TenantHarness::create("cancelled_get_or_maybe_download_does_not_cancel_eviction")
641 4 : .await
642 4 : .unwrap();
643 4 : let (tenant, ctx) = h.load().await;
644 4 :
645 4 : let timeline = tenant
646 4 : .create_test_timeline(TimelineId::generate(), Lsn(0x10), 14, &ctx)
647 4 : .await
648 4 : .unwrap();
649 4 : let ctx = ctx.with_scope_timeline(&timeline);
650 4 :
651 4 : // This test does downloads
652 4 : let ctx = RequestContextBuilder::from(&ctx)
653 4 : .download_behavior(DownloadBehavior::Download)
654 4 : .attached_child();
655 4 :
656 4 : let layer = {
657 4 : let mut layers = {
658 4 : let layers = timeline.layers.read().await;
659 4 : layers.likely_resident_layers().cloned().collect::<Vec<_>>()
660 4 : };
661 4 :
662 4 : assert_eq!(layers.len(), 1);
663 4 :
664 4 : layers.swap_remove(0)
665 4 : };
666 4 :
667 4 : // this failpoint will simulate the `get_or_maybe_download` becoming cancelled (by returning an
668 4 : // Err) at the right time as in "during" the `LayerInner::needs_download`.
669 4 : layer.enable_failpoint(Failpoint::AfterDeterminingLayerNeedsNoDownload);
670 4 :
671 4 : let (completion, barrier) = utils::completion::channel();
672 4 : let (arrival, arrived_at_barrier) = utils::completion::channel();
673 4 :
674 4 : layer.enable_failpoint(Failpoint::WaitBeforeStartingEvicting(
675 4 : Some(arrival),
676 4 : barrier,
677 4 : ));
678 4 :
679 4 : tokio::time::timeout(ADVANCE, layer.evict_and_wait(FOREVER))
680 4 : .await
681 4 : .expect_err("should had advanced to waiting on channel");
682 4 :
683 4 : arrived_at_barrier.wait().await;
684 4 :
685 4 : // simulate a cancelled read which is cancelled before it gets to re-initialize
686 4 : let e = layer
687 4 : .0
688 4 : .get_or_maybe_download(false, &ctx)
689 4 : .await
690 4 : .unwrap_err();
691 4 : assert!(
692 4 : matches!(
693 4 : e,
694 4 : DownloadError::Failpoint(FailpointKind::AfterDeterminingLayerNeedsNoDownload)
695 4 : ),
696 4 : "{e:?}"
697 4 : );
698 4 :
699 4 : assert!(
700 4 : layer.0.needs_download().await.unwrap().is_none(),
701 4 : "file is still on disk"
702 4 : );
703 4 :
704 4 : // release the eviction task
705 4 : drop(completion);
706 4 : tokio::time::sleep(ADVANCE).await;
707 4 : SpawnBlockingPoolHelper::consume_and_release_all_of_spawn_blocking_threads(&handle).await;
708 4 :
709 4 : // failpoint is still enabled, but it is not hit
710 4 : let e = layer
711 4 : .0
712 4 : .get_or_maybe_download(false, &ctx)
713 4 : .await
714 4 : .unwrap_err();
715 4 : assert!(matches!(e, DownloadError::DownloadRequired), "{e:?}");
716 4 :
717 4 : // failpoint is not counted as cancellation either
718 4 : assert_eq!(0, LAYER_IMPL_METRICS.inits_cancelled.get())
719 4 : }
720 :
721 : #[tokio::test(start_paused = true)]
722 4 : async fn evict_and_wait_does_not_wait_for_download() {
723 4 : // let handle = tokio::runtime::Handle::current();
724 4 : let h = TenantHarness::create("evict_and_wait_does_not_wait_for_download")
725 4 : .await
726 4 : .unwrap();
727 4 : let (tenant, ctx) = h.load().await;
728 4 : let span = h.span();
729 4 : let download_span = span.in_scope(|| tracing::info_span!("downloading", timeline_id = 1));
730 4 :
731 4 : let timeline = tenant
732 4 : .create_test_timeline(TimelineId::generate(), Lsn(0x10), 14, &ctx)
733 4 : .await
734 4 : .unwrap();
735 4 : let ctx = ctx.with_scope_timeline(&timeline);
736 4 :
737 4 : // This test does downloads
738 4 : let ctx = RequestContextBuilder::from(&ctx)
739 4 : .download_behavior(DownloadBehavior::Download)
740 4 : .attached_child();
741 4 :
742 4 : let layer = {
743 4 : let mut layers = {
744 4 : let layers = timeline.layers.read().await;
745 4 : layers.likely_resident_layers().cloned().collect::<Vec<_>>()
746 4 : };
747 4 :
748 4 : assert_eq!(layers.len(), 1);
749 4 :
750 4 : layers.swap_remove(0)
751 4 : };
752 4 :
753 4 : // kind of forced setup: start an eviction but do not allow it progress until we are
754 4 : // downloading
755 4 : let (eviction_can_continue, barrier) = utils::completion::channel();
756 4 : let (arrival, eviction_arrived) = utils::completion::channel();
757 4 : layer.enable_failpoint(Failpoint::WaitBeforeStartingEvicting(
758 4 : Some(arrival),
759 4 : barrier,
760 4 : ));
761 4 :
762 4 : let mut evict_and_wait = std::pin::pin!(layer.evict_and_wait(FOREVER));
763 4 :
764 4 : // use this once-awaited other_evict to synchronize with the eviction
765 4 : let other_evict = layer.evict_and_wait(FOREVER);
766 4 :
767 4 : tokio::time::timeout(ADVANCE, &mut evict_and_wait)
768 4 : .await
769 4 : .expect_err("should had advanced");
770 4 : eviction_arrived.wait().await;
771 4 : drop(eviction_can_continue);
772 4 : other_evict.await.unwrap();
773 4 :
774 4 : // now the layer is evicted, and the "evict_and_wait" is waiting on the receiver
775 4 : assert!(!layer.is_likely_resident());
776 4 :
777 4 : // following new evict_and_wait will fail until we've completed the download
778 4 : let e = layer.evict_and_wait(FOREVER).await.unwrap_err();
779 4 : assert!(matches!(e, EvictionError::NotFound), "{e:?}");
780 4 :
781 4 : let (download_can_continue, barrier) = utils::completion::channel();
782 4 : let (arrival, _download_arrived) = utils::completion::channel();
783 4 : layer.enable_failpoint(Failpoint::WaitBeforeDownloading(Some(arrival), barrier));
784 4 :
785 4 : let mut download = std::pin::pin!(
786 4 : layer
787 4 : .0
788 4 : .get_or_maybe_download(true, &ctx)
789 4 : .instrument(download_span)
790 4 : );
791 4 :
792 4 : assert!(
793 4 : !layer.is_likely_resident(),
794 4 : "during download layer is evicted"
795 4 : );
796 4 :
797 4 : tokio::time::timeout(ADVANCE, &mut download)
798 4 : .await
799 4 : .expect_err("should had timed out because of failpoint");
800 4 :
801 4 : // now we finally get to continue, and because the latest state is downloading, we deduce that
802 4 : // original eviction succeeded
803 4 : evict_and_wait.await.unwrap();
804 4 :
805 4 : // however a new evict_and_wait will fail
806 4 : let e = layer.evict_and_wait(FOREVER).await.unwrap_err();
807 4 : assert!(matches!(e, EvictionError::NotFound), "{e:?}");
808 4 :
809 4 : assert!(!layer.is_likely_resident());
810 4 :
811 4 : drop(download_can_continue);
812 4 : download.await.expect("download should had succeeded");
813 4 : assert!(layer.is_likely_resident());
814 4 :
815 4 : // only now can we evict
816 4 : layer.evict_and_wait(FOREVER).await.unwrap();
817 4 : }
818 :
819 : /// Asserts that there is no miscalculation when Layer is dropped while it is being kept resident,
820 : /// which is the last value.
821 : ///
822 : /// Also checks that the same does not happen on a non-evicted layer (regression test).
823 : #[tokio::test(start_paused = true)]
824 4 : async fn eviction_cancellation_on_drop() {
825 4 : use bytes::Bytes;
826 4 : use pageserver_api::value::Value;
827 4 :
828 4 : // this is the runtime on which Layer spawns the blocking tasks on
829 4 : let handle = tokio::runtime::Handle::current();
830 4 :
831 4 : let h = TenantHarness::create("eviction_cancellation_on_drop")
832 4 : .await
833 4 : .unwrap();
834 4 : utils::logging::replace_panic_hook_with_tracing_panic_hook().forget();
835 4 : let (tenant, ctx) = h.load().await;
836 4 :
837 4 : let timeline = tenant
838 4 : .create_test_timeline(TimelineId::generate(), Lsn(0x10), 14, &ctx)
839 4 : .await
840 4 : .unwrap();
841 4 :
842 4 : {
843 4 : // create_test_timeline wrote us one layer, write another
844 4 : let mut writer = timeline.writer().await;
845 4 : writer
846 4 : .put(
847 4 : pageserver_api::key::Key::from_i128(5),
848 4 : Lsn(0x20),
849 4 : &Value::Image(Bytes::from_static(b"this does not matter either")),
850 4 : &ctx,
851 4 : )
852 4 : .await
853 4 : .unwrap();
854 4 :
855 4 : writer.finish_write(Lsn(0x20));
856 4 : }
857 4 :
858 4 : timeline.freeze_and_flush().await.unwrap();
859 4 :
860 4 : // wait for the upload to complete so our Arc::strong_count assertion holds
861 4 : timeline.remote_client.wait_completion().await.unwrap();
862 4 :
863 4 : let (evicted_layer, not_evicted) = {
864 4 : let mut layers = {
865 4 : let mut guard = timeline.layers.write().await;
866 4 : let layers = guard.likely_resident_layers().cloned().collect::<Vec<_>>();
867 4 : // remove the layers from layermap
868 4 : guard.open_mut().unwrap().finish_gc_timeline(&layers);
869 4 :
870 4 : layers
871 4 : };
872 4 :
873 4 : assert_eq!(layers.len(), 2);
874 4 :
875 4 : (layers.pop().unwrap(), layers.pop().unwrap())
876 4 : };
877 4 :
878 4 : let victims = [(evicted_layer, true), (not_evicted, false)];
879 4 :
880 12 : for (victim, evict) in victims {
881 8 : let resident = victim.keep_resident().await.unwrap();
882 8 : drop(victim);
883 8 :
884 8 : assert_eq!(Arc::strong_count(&resident.owner.0), 1);
885 4 :
886 8 : if evict {
887 4 : let evict_and_wait = resident.owner.evict_and_wait(FOREVER);
888 4 :
889 4 : // drive the future to await on the status channel, and then drop it
890 4 : tokio::time::timeout(ADVANCE, evict_and_wait)
891 4 : .await
892 4 : .expect_err("should had been a timeout since we are holding the layer resident");
893 4 : }
894 4 :
895 4 : // 1 == we only evict one of the layers
896 8 : assert_eq!(1, LAYER_IMPL_METRICS.started_evictions.get());
897 4 :
898 8 : drop(resident);
899 8 :
900 8 : // run any spawned
901 8 : tokio::time::sleep(ADVANCE).await;
902 4 :
903 8 : SpawnBlockingPoolHelper::consume_and_release_all_of_spawn_blocking_threads(&handle).await;
904 4 :
905 8 : assert_eq!(
906 8 : 1,
907 8 : LAYER_IMPL_METRICS.cancelled_evictions[EvictionCancelled::LayerGone].get()
908 8 : );
909 4 : }
910 4 : }
911 :
912 : /// A test case to remind you the cost of these structures. You can bump the size limit
913 : /// below if it is really necessary to add more fields to the structures.
914 : #[test]
915 : #[cfg(target_arch = "x86_64")]
916 4 : fn layer_size() {
917 4 : assert_eq!(size_of::<LayerAccessStats>(), 8);
918 4 : assert_eq!(size_of::<PersistentLayerDesc>(), 104);
919 4 : assert_eq!(size_of::<LayerInner>(), 296);
920 : // it also has the utf8 path
921 4 : }
922 :
923 : struct SpawnBlockingPoolHelper {
924 : awaited_by_spawn_blocking_tasks: Completion,
925 : blocking_tasks: JoinSet<()>,
926 : }
927 :
928 : impl SpawnBlockingPoolHelper {
929 : /// All `crate::task_mgr::BACKGROUND_RUNTIME` spawn_blocking threads will be consumed until
930 : /// release is called.
931 : ///
932 : /// In the tests this can be used to ensure something cannot be started on the target runtimes
933 : /// spawn_blocking pool.
934 : ///
935 : /// This should be no issue nowdays, because nextest runs each test in it's own process.
936 4 : async fn consume_all_spawn_blocking_threads(handle: &tokio::runtime::Handle) -> Self {
937 4 : let default_max_blocking_threads = 512;
938 4 :
939 4 : Self::consume_all_spawn_blocking_threads0(handle, default_max_blocking_threads).await
940 4 : }
941 :
942 52 : async fn consume_all_spawn_blocking_threads0(
943 52 : handle: &tokio::runtime::Handle,
944 52 : threads: usize,
945 52 : ) -> Self {
946 52 : assert_ne!(threads, 0);
947 :
948 52 : let (completion, barrier) = completion::channel();
949 52 : let (started, starts_completed) = completion::channel();
950 52 :
951 52 : let mut blocking_tasks = JoinSet::new();
952 52 :
953 14360 : for _ in 0..threads {
954 14360 : let barrier = barrier.clone();
955 14360 : let started = started.clone();
956 14360 : blocking_tasks.spawn_blocking_on(
957 14360 : move || {
958 14360 : drop(started);
959 14360 : tokio::runtime::Handle::current().block_on(barrier.wait());
960 14360 : },
961 14360 : handle,
962 14360 : );
963 14360 : }
964 :
965 52 : drop(started);
966 52 :
967 52 : starts_completed.wait().await;
968 :
969 52 : drop(barrier);
970 52 :
971 52 : tracing::trace!("consumed all threads");
972 :
973 52 : SpawnBlockingPoolHelper {
974 52 : awaited_by_spawn_blocking_tasks: completion,
975 52 : blocking_tasks,
976 52 : }
977 52 : }
978 :
979 : /// Release all previously blocked spawn_blocking threads
980 52 : async fn release(self) {
981 52 : let SpawnBlockingPoolHelper {
982 52 : awaited_by_spawn_blocking_tasks,
983 52 : mut blocking_tasks,
984 52 : } = self;
985 52 :
986 52 : drop(awaited_by_spawn_blocking_tasks);
987 :
988 14412 : while let Some(res) = blocking_tasks.join_next().await {
989 14360 : res.expect("none of the tasks should had panicked");
990 14360 : }
991 :
992 52 : tracing::trace!("released all threads");
993 52 : }
994 :
995 : /// In the tests it is used as an easy way of making sure something scheduled on the target
996 : /// runtimes `spawn_blocking` has completed, because it must've been scheduled and completed
997 : /// before our tasks have a chance to schedule and complete.
998 24 : async fn consume_and_release_all_of_spawn_blocking_threads(handle: &tokio::runtime::Handle) {
999 24 : Self::consume_and_release_all_of_spawn_blocking_threads0(handle, 512).await
1000 24 : }
1001 :
1002 44 : async fn consume_and_release_all_of_spawn_blocking_threads0(
1003 44 : handle: &tokio::runtime::Handle,
1004 44 : threads: usize,
1005 44 : ) {
1006 44 : Self::consume_all_spawn_blocking_threads0(handle, threads)
1007 44 : .await
1008 44 : .release()
1009 44 : .await
1010 44 : }
1011 : }
1012 :
1013 : #[test]
1014 4 : fn spawn_blocking_pool_helper_actually_works() {
1015 4 : // create a custom runtime for which we know and control how many blocking threads it has
1016 4 : //
1017 4 : // because the amount is not configurable for our helper, expect the same amount as
1018 4 : // BACKGROUND_RUNTIME using the tokio defaults would have.
1019 4 : let rt = tokio::runtime::Builder::new_current_thread()
1020 4 : .max_blocking_threads(1)
1021 4 : .enable_all()
1022 4 : .build()
1023 4 : .unwrap();
1024 4 :
1025 4 : let handle = rt.handle();
1026 4 :
1027 4 : rt.block_on(async move {
1028 : // this will not return until all threads are spun up and actually executing the code
1029 : // waiting on `consumed` to be `SpawnBlockingPoolHelper::release`'d.
1030 4 : let consumed =
1031 4 : SpawnBlockingPoolHelper::consume_all_spawn_blocking_threads0(handle, 1).await;
1032 :
1033 4 : println!("consumed");
1034 4 :
1035 4 : let mut jh = std::pin::pin!(tokio::task::spawn_blocking(move || {
1036 4 : // this will not get to run before we release
1037 4 : }));
1038 4 :
1039 4 : println!("spawned");
1040 4 :
1041 4 : tokio::time::timeout(std::time::Duration::from_secs(1), &mut jh)
1042 4 : .await
1043 4 : .expect_err("the task should not have gotten to run yet");
1044 4 :
1045 4 : println!("tried to join");
1046 4 :
1047 4 : consumed.release().await;
1048 :
1049 4 : println!("released");
1050 4 :
1051 4 : tokio::time::timeout(std::time::Duration::from_secs(1), jh)
1052 4 : .await
1053 4 : .expect("no timeout")
1054 4 : .expect("no join error");
1055 4 :
1056 4 : println!("joined");
1057 4 : });
1058 4 : }
1059 :
1060 : /// Drop the low bits from a time, to emulate the precision loss in LayerAccessStats
1061 16 : fn lowres_time(hires: SystemTime) -> SystemTime {
1062 16 : let ts = hires.duration_since(UNIX_EPOCH).unwrap().as_secs();
1063 16 : UNIX_EPOCH + Duration::from_secs(ts)
1064 16 : }
1065 :
1066 : #[test]
1067 4 : fn access_stats() {
1068 4 : let access_stats = LayerAccessStats::default();
1069 4 : // Default is visible
1070 4 : assert_eq!(access_stats.visibility(), LayerVisibilityHint::Visible);
1071 :
1072 4 : access_stats.set_visibility(LayerVisibilityHint::Covered);
1073 4 : assert_eq!(access_stats.visibility(), LayerVisibilityHint::Covered);
1074 4 : access_stats.set_visibility(LayerVisibilityHint::Visible);
1075 4 : assert_eq!(access_stats.visibility(), LayerVisibilityHint::Visible);
1076 :
1077 4 : let rtime = UNIX_EPOCH + Duration::from_secs(2000000000);
1078 4 : access_stats.record_residence_event_at(rtime);
1079 4 : assert_eq!(access_stats.latest_activity(), lowres_time(rtime));
1080 :
1081 4 : let atime = UNIX_EPOCH + Duration::from_secs(2100000000);
1082 4 : access_stats.record_access_at(atime);
1083 4 : assert_eq!(access_stats.latest_activity(), lowres_time(atime));
1084 :
1085 : // Setting visibility doesn't clobber access time
1086 4 : access_stats.set_visibility(LayerVisibilityHint::Covered);
1087 4 : assert_eq!(access_stats.latest_activity(), lowres_time(atime));
1088 4 : access_stats.set_visibility(LayerVisibilityHint::Visible);
1089 4 : assert_eq!(access_stats.latest_activity(), lowres_time(atime));
1090 :
1091 : // Recording access implicitly makes layer visible, if it wasn't already
1092 4 : let atime = UNIX_EPOCH + Duration::from_secs(2200000000);
1093 4 : access_stats.set_visibility(LayerVisibilityHint::Covered);
1094 4 : assert_eq!(access_stats.visibility(), LayerVisibilityHint::Covered);
1095 4 : assert!(access_stats.record_access_at(atime));
1096 4 : access_stats.set_visibility(LayerVisibilityHint::Visible);
1097 4 : assert!(!access_stats.record_access_at(atime));
1098 4 : access_stats.set_visibility(LayerVisibilityHint::Visible);
1099 4 : }
1100 :
1101 : #[test]
1102 4 : fn access_stats_2038() {
1103 4 : // The access stats structure uses a timestamp representation that will run out
1104 4 : // of bits in 2038. One year before that, this unit test will start failing.
1105 4 :
1106 4 : let one_year_from_now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap()
1107 4 : + Duration::from_secs(3600 * 24 * 365);
1108 4 :
1109 4 : assert!(one_year_from_now.as_secs() < (2 << 31));
1110 4 : }
|