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