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