Line data Source code
1 : //! The per-timeline layer eviction task, which evicts data which has not been accessed for more
2 : //! than a given threshold.
3 : //!
4 : //! Data includes all kinds of caches, namely:
5 : //! - (in-memory layers)
6 : //! - on-demand downloaded layer files on disk
7 : //! - (cached layer file pages)
8 : //! - derived data from layer file contents, namely:
9 : //! - initial logical size
10 : //! - partitioning
11 : //! - (other currently missing unknowns)
12 : //!
13 : //! Items with parentheses are not (yet) touched by this task.
14 : //!
15 : //! See write-up on restart on-demand download spike: <https://gist.github.com/problame/2265bf7b8dc398be834abfead36c76b5>
16 : use std::{
17 : collections::HashMap,
18 : ops::ControlFlow,
19 : sync::Arc,
20 : time::{Duration, SystemTime},
21 : };
22 :
23 : use pageserver_api::models::{EvictionPolicy, EvictionPolicyLayerAccessThreshold};
24 : use tokio::time::Instant;
25 : use tokio_util::sync::CancellationToken;
26 : use tracing::{debug, info, info_span, instrument, warn, Instrument};
27 :
28 : use crate::{
29 : context::{DownloadBehavior, RequestContext},
30 : pgdatadir_mapping::CollectKeySpaceError,
31 : task_mgr::{self, TaskKind, BACKGROUND_RUNTIME},
32 : tenant::{
33 : tasks::BackgroundLoopKind, timeline::EvictionError, LogicalSizeCalculationCause, Tenant,
34 : },
35 : };
36 :
37 : use utils::{completion, sync::gate::GateGuard};
38 :
39 : use super::Timeline;
40 :
41 : #[derive(Default)]
42 : pub struct EvictionTaskTimelineState {
43 : last_layer_access_imitation: Option<tokio::time::Instant>,
44 : }
45 :
46 : #[derive(Default)]
47 : pub struct EvictionTaskTenantState {
48 : last_layer_access_imitation: Option<Instant>,
49 : }
50 :
51 : impl Timeline {
52 0 : pub(super) fn launch_eviction_task(
53 0 : self: &Arc<Self>,
54 0 : parent: Arc<Tenant>,
55 0 : background_tasks_can_start: Option<&completion::Barrier>,
56 0 : ) {
57 0 : let self_clone = Arc::clone(self);
58 0 : let background_tasks_can_start = background_tasks_can_start.cloned();
59 0 : task_mgr::spawn(
60 0 : BACKGROUND_RUNTIME.handle(),
61 0 : TaskKind::Eviction,
62 0 : Some(self.tenant_shard_id),
63 0 : Some(self.timeline_id),
64 0 : &format!(
65 0 : "layer eviction for {}/{}",
66 0 : self.tenant_shard_id, self.timeline_id
67 0 : ),
68 0 : false,
69 0 : async move {
70 : tokio::select! {
71 : _ = self_clone.cancel.cancelled() => { return Ok(()); }
72 : _ = completion::Barrier::maybe_wait(background_tasks_can_start) => {}
73 : };
74 :
75 0 : self_clone.eviction_task(parent).await;
76 0 : Ok(())
77 0 : },
78 0 : );
79 0 : }
80 :
81 0 : #[instrument(skip_all, fields(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), timeline_id = %self.timeline_id))]
82 : async fn eviction_task(self: Arc<Self>, tenant: Arc<Tenant>) {
83 : use crate::tenant::tasks::random_init_delay;
84 :
85 : // acquire the gate guard only once within a useful span
86 : let Ok(guard) = self.gate.enter() else {
87 : return;
88 : };
89 :
90 : {
91 : let policy = self.get_eviction_policy();
92 : let period = match policy {
93 : EvictionPolicy::LayerAccessThreshold(lat) => lat.period,
94 : EvictionPolicy::OnlyImitiate(lat) => lat.period,
95 : EvictionPolicy::NoEviction => Duration::from_secs(10),
96 : };
97 : if random_init_delay(period, &self.cancel).await.is_err() {
98 : return;
99 : }
100 : }
101 :
102 : let ctx = RequestContext::new(TaskKind::Eviction, DownloadBehavior::Warn);
103 : loop {
104 : let policy = self.get_eviction_policy();
105 : let cf = self
106 : .eviction_iteration(&tenant, &policy, &self.cancel, &guard, &ctx)
107 : .await;
108 :
109 : match cf {
110 : ControlFlow::Break(()) => break,
111 : ControlFlow::Continue(sleep_until) => {
112 : if tokio::time::timeout_at(sleep_until, self.cancel.cancelled())
113 : .await
114 : .is_ok()
115 : {
116 : break;
117 : }
118 : }
119 : }
120 : }
121 : }
122 :
123 0 : #[instrument(skip_all, fields(policy_kind = policy.discriminant_str()))]
124 : async fn eviction_iteration(
125 : self: &Arc<Self>,
126 : tenant: &Tenant,
127 : policy: &EvictionPolicy,
128 : cancel: &CancellationToken,
129 : gate: &GateGuard,
130 : ctx: &RequestContext,
131 : ) -> ControlFlow<(), Instant> {
132 : debug!("eviction iteration: {policy:?}");
133 : let start = Instant::now();
134 : let (period, threshold) = match policy {
135 : EvictionPolicy::NoEviction => {
136 : // check again in 10 seconds; XXX config watch mechanism
137 : return ControlFlow::Continue(Instant::now() + Duration::from_secs(10));
138 : }
139 : EvictionPolicy::LayerAccessThreshold(p) => {
140 : match self
141 : .eviction_iteration_threshold(tenant, p, cancel, gate, ctx)
142 : .await
143 : {
144 : ControlFlow::Break(()) => return ControlFlow::Break(()),
145 : ControlFlow::Continue(()) => (),
146 : }
147 : (p.period, p.threshold)
148 : }
149 : EvictionPolicy::OnlyImitiate(p) => {
150 : if self
151 : .imitiate_only(tenant, p, cancel, gate, ctx)
152 : .await
153 : .is_break()
154 : {
155 : return ControlFlow::Break(());
156 : }
157 : (p.period, p.threshold)
158 : }
159 : };
160 :
161 : let elapsed = start.elapsed();
162 : crate::tenant::tasks::warn_when_period_overrun(
163 : elapsed,
164 : period,
165 : BackgroundLoopKind::Eviction,
166 : );
167 : // FIXME: if we were to mix policies on a pageserver, we would have no way to sense this. I
168 : // don't think that is a relevant fear however, and regardless the imitation should be the
169 : // most costly part.
170 : crate::metrics::EVICTION_ITERATION_DURATION
171 : .get_metric_with_label_values(&[
172 : &format!("{}", period.as_secs()),
173 : &format!("{}", threshold.as_secs()),
174 : ])
175 : .unwrap()
176 : .observe(elapsed.as_secs_f64());
177 :
178 : ControlFlow::Continue(start + period)
179 : }
180 :
181 0 : async fn eviction_iteration_threshold(
182 0 : self: &Arc<Self>,
183 0 : tenant: &Tenant,
184 0 : p: &EvictionPolicyLayerAccessThreshold,
185 0 : cancel: &CancellationToken,
186 0 : gate: &GateGuard,
187 0 : ctx: &RequestContext,
188 0 : ) -> ControlFlow<()> {
189 0 : let now = SystemTime::now();
190 :
191 0 : let permit = self.acquire_imitation_permit(cancel, ctx).await?;
192 :
193 0 : self.imitate_layer_accesses(tenant, p, cancel, gate, permit, ctx)
194 0 : .await?;
195 :
196 : #[derive(Debug, Default)]
197 : struct EvictionStats {
198 : candidates: usize,
199 : evicted: usize,
200 : errors: usize,
201 : not_evictable: usize,
202 : timeouts: usize,
203 : #[allow(dead_code)]
204 : skipped_for_shutdown: usize,
205 : }
206 :
207 0 : let mut stats = EvictionStats::default();
208 0 : // Gather layers for eviction.
209 0 : // NB: all the checks can be invalidated as soon as we release the layer map lock.
210 0 : // We don't want to hold the layer map lock during eviction.
211 0 :
212 0 : // So, we just need to deal with this.
213 0 :
214 0 : let mut js = tokio::task::JoinSet::new();
215 : {
216 0 : let guard = self.layers.read().await;
217 0 : let layers = guard.layer_map();
218 0 : for layer in layers.iter_historic_layers() {
219 0 : let layer = guard.get_from_desc(&layer);
220 0 :
221 0 : // guard against eviction while we inspect it; it might be that eviction_task and
222 0 : // disk_usage_eviction_task both select the same layers to be evicted, and
223 0 : // seemingly free up double the space. both succeeding is of no consequence.
224 0 :
225 0 : if !layer.is_likely_resident() {
226 0 : continue;
227 0 : }
228 0 :
229 0 : let last_activity_ts = layer.access_stats().latest_activity_or_now();
230 :
231 0 : let no_activity_for = match now.duration_since(last_activity_ts) {
232 0 : Ok(d) => d,
233 0 : Err(_e) => {
234 0 : // We reach here if `now` < `last_activity_ts`, which can legitimately
235 0 : // happen if there is an access between us getting `now`, and us getting
236 0 : // the access stats from the layer.
237 0 : //
238 0 : // The other reason why it can happen is system clock skew because
239 0 : // SystemTime::now() is not monotonic, so, even if there is no access
240 0 : // to the layer after we get `now` at the beginning of this function,
241 0 : // it could be that `now` < `last_activity_ts`.
242 0 : //
243 0 : // To distinguish the cases, we would need to record `Instant`s in the
244 0 : // access stats (i.e., monotonic timestamps), but then, the timestamps
245 0 : // values in the access stats would need to be `Instant`'s, and hence
246 0 : // they would be meaningless outside of the pageserver process.
247 0 : // At the time of writing, the trade-off is that access stats are more
248 0 : // valuable than detecting clock skew.
249 0 : continue;
250 : }
251 : };
252 :
253 0 : if no_activity_for > p.threshold {
254 0 : js.spawn(async move {
255 0 : layer
256 0 : .evict_and_wait(std::time::Duration::from_secs(5))
257 0 : .await
258 0 : });
259 0 : stats.candidates += 1;
260 0 : }
261 : }
262 : };
263 :
264 0 : let join_all = async move {
265 0 : while let Some(next) = js.join_next().await {
266 0 : match next {
267 0 : Ok(Ok(())) => stats.evicted += 1,
268 0 : Ok(Err(EvictionError::NotFound | EvictionError::Downloaded)) => {
269 0 : stats.not_evictable += 1;
270 0 : }
271 0 : Ok(Err(EvictionError::Timeout)) => {
272 0 : stats.timeouts += 1;
273 0 : }
274 0 : Err(je) if je.is_cancelled() => unreachable!("not used"),
275 0 : Err(je) if je.is_panic() => {
276 0 : /* already logged */
277 0 : stats.errors += 1;
278 0 : }
279 0 : Err(je) => tracing::error!("unknown JoinError: {je:?}"),
280 : }
281 : }
282 0 : stats
283 0 : };
284 :
285 : tokio::select! {
286 : stats = join_all => {
287 : if stats.candidates == stats.not_evictable {
288 : debug!(stats=?stats, "eviction iteration complete");
289 : } else if stats.errors > 0 || stats.not_evictable > 0 || stats.timeouts > 0 {
290 : // reminder: timeouts are not eviction cancellations
291 : warn!(stats=?stats, "eviction iteration complete");
292 : } else {
293 : info!(stats=?stats, "eviction iteration complete");
294 : }
295 : }
296 : _ = cancel.cancelled() => {
297 : // just drop the joinset to "abort"
298 : }
299 : }
300 :
301 0 : ControlFlow::Continue(())
302 0 : }
303 :
304 : /// Like `eviction_iteration_threshold`, but without any eviction. Eviction will be done by
305 : /// disk usage based eviction task.
306 0 : async fn imitiate_only(
307 0 : self: &Arc<Self>,
308 0 : tenant: &Tenant,
309 0 : p: &EvictionPolicyLayerAccessThreshold,
310 0 : cancel: &CancellationToken,
311 0 : gate: &GateGuard,
312 0 : ctx: &RequestContext,
313 0 : ) -> ControlFlow<()> {
314 0 : let permit = self.acquire_imitation_permit(cancel, ctx).await?;
315 :
316 0 : self.imitate_layer_accesses(tenant, p, cancel, gate, permit, ctx)
317 0 : .await
318 0 : }
319 :
320 0 : async fn acquire_imitation_permit(
321 0 : &self,
322 0 : cancel: &CancellationToken,
323 0 : ctx: &RequestContext,
324 0 : ) -> ControlFlow<(), tokio::sync::SemaphorePermit<'static>> {
325 0 : let acquire_permit = crate::tenant::tasks::concurrent_background_tasks_rate_limit_permit(
326 0 : BackgroundLoopKind::Eviction,
327 0 : ctx,
328 0 : );
329 :
330 : tokio::select! {
331 : permit = acquire_permit => ControlFlow::Continue(permit),
332 : _ = cancel.cancelled() => ControlFlow::Break(()),
333 : _ = self.cancel.cancelled() => ControlFlow::Break(()),
334 : }
335 0 : }
336 :
337 : /// If we evict layers but keep cached values derived from those layers, then
338 : /// we face a storm of on-demand downloads after pageserver restart.
339 : /// The reason is that the restart empties the caches, and so, the values
340 : /// need to be re-computed by accessing layers, which we evicted while the
341 : /// caches were filled.
342 : ///
343 : /// Solutions here would be one of the following:
344 : /// 1. Have a persistent cache.
345 : /// 2. Count every access to a cached value to the access stats of all layers
346 : /// that were accessed to compute the value in the first place.
347 : /// 3. Invalidate the caches at a period of < p.threshold/2, so that the values
348 : /// get re-computed from layers, thereby counting towards layer access stats.
349 : /// 4. Make the eviction task imitate the layer accesses that typically hit caches.
350 : ///
351 : /// We follow approach (4) here because in Neon prod deployment:
352 : /// - page cache is quite small => high churn => low hit rate
353 : /// => eviction gets correct access stats
354 : /// - value-level caches such as logical size & repatition have a high hit rate,
355 : /// especially for inactive tenants
356 : /// => eviction sees zero accesses for these
357 : /// => they cause the on-demand download storm on pageserver restart
358 : ///
359 : /// We should probably move to persistent caches in the future, or avoid
360 : /// having inactive tenants attached to pageserver in the first place.
361 0 : #[instrument(skip_all)]
362 : async fn imitate_layer_accesses(
363 : &self,
364 : tenant: &Tenant,
365 : p: &EvictionPolicyLayerAccessThreshold,
366 : cancel: &CancellationToken,
367 : gate: &GateGuard,
368 : permit: tokio::sync::SemaphorePermit<'static>,
369 : ctx: &RequestContext,
370 : ) -> ControlFlow<()> {
371 : if !self.tenant_shard_id.is_shard_zero() {
372 : // Shards !=0 do not maintain accurate relation sizes, and do not need to calculate logical size
373 : // for consumption metrics (consumption metrics are only sent from shard 0). We may therefore
374 : // skip imitating logical size accesses for eviction purposes.
375 : return ControlFlow::Continue(());
376 : }
377 :
378 : let mut state = self.eviction_task_timeline_state.lock().await;
379 :
380 : // Only do the imitate_layer accesses approximately as often as the threshold. A little
381 : // more frequently, to avoid this period racing with the threshold/period-th eviction iteration.
382 : let inter_imitate_period = p.threshold.checked_sub(p.period).unwrap_or(p.threshold);
383 :
384 : match state.last_layer_access_imitation {
385 : Some(ts) if ts.elapsed() < inter_imitate_period => { /* no need to run */ }
386 : _ => {
387 : self.imitate_timeline_cached_layer_accesses(gate, ctx).await;
388 : state.last_layer_access_imitation = Some(tokio::time::Instant::now())
389 : }
390 : }
391 : drop(state);
392 :
393 : if cancel.is_cancelled() {
394 : return ControlFlow::Break(());
395 : }
396 :
397 : // This task is timeline-scoped, but the synthetic size calculation is tenant-scoped.
398 : // Make one of the tenant's timelines draw the short straw and run the calculation.
399 : // The others wait until the calculation is done so that they take into account the
400 : // imitated accesses that the winner made.
401 : let (mut state, _permit) = {
402 : if let Ok(locked) = tenant.eviction_task_tenant_state.try_lock() {
403 : (locked, permit)
404 : } else {
405 : // we might need to wait for a long time here in case of pathological synthetic
406 : // size calculation performance
407 : drop(permit);
408 : let locked = tokio::select! {
409 : locked = tenant.eviction_task_tenant_state.lock() => locked,
410 : _ = self.cancel.cancelled() => {
411 : return ControlFlow::Break(())
412 : },
413 : _ = cancel.cancelled() => {
414 : return ControlFlow::Break(())
415 : }
416 : };
417 : // then reacquire -- this will be bad if there is a lot of traffic, but because we
418 : // released the permit, the overall latency will be much better.
419 : let permit = self.acquire_imitation_permit(cancel, ctx).await?;
420 : (locked, permit)
421 : }
422 : };
423 : match state.last_layer_access_imitation {
424 : Some(ts) if ts.elapsed() < inter_imitate_period => { /* no need to run */ }
425 : _ => {
426 : self.imitate_synthetic_size_calculation_worker(tenant, cancel, ctx)
427 : .await;
428 : state.last_layer_access_imitation = Some(tokio::time::Instant::now());
429 : }
430 : }
431 : drop(state);
432 :
433 : if cancel.is_cancelled() {
434 : return ControlFlow::Break(());
435 : }
436 :
437 : ControlFlow::Continue(())
438 : }
439 :
440 : /// Recompute the values which would cause on-demand downloads during restart.
441 0 : #[instrument(skip_all)]
442 : async fn imitate_timeline_cached_layer_accesses(
443 : &self,
444 : guard: &GateGuard,
445 : ctx: &RequestContext,
446 : ) {
447 : let lsn = self.get_last_record_lsn();
448 :
449 : // imitiate on-restart initial logical size
450 : let size = self
451 : .calculate_logical_size(
452 : lsn,
453 : LogicalSizeCalculationCause::EvictionTaskImitation,
454 : guard,
455 : ctx,
456 : )
457 : .instrument(info_span!("calculate_logical_size"))
458 : .await;
459 :
460 : match &size {
461 : Ok(_size) => {
462 : // good, don't log it to avoid confusion
463 : }
464 : Err(_) => {
465 : // we have known issues for which we already log this on consumption metrics,
466 : // gc, and compaction. leave logging out for now.
467 : //
468 : // https://github.com/neondatabase/neon/issues/2539
469 : }
470 : }
471 :
472 : // imitiate repartiting on first compactation
473 : if let Err(e) = self
474 : .collect_keyspace(lsn, ctx)
475 : .instrument(info_span!("collect_keyspace"))
476 : .await
477 : {
478 : // if this failed, we probably failed logical size because these use the same keys
479 : if size.is_err() {
480 : // ignore, see above comment
481 : } else {
482 : match e {
483 : CollectKeySpaceError::Cancelled => {
484 : // Shutting down, ignore
485 : }
486 : err => {
487 : warn!(
488 : "failed to collect keyspace but succeeded in calculating logical size: {err:#}"
489 : );
490 : }
491 : }
492 : }
493 : }
494 : }
495 :
496 : // Imitate the synthetic size calculation done by the consumption_metrics module.
497 0 : #[instrument(skip_all)]
498 : async fn imitate_synthetic_size_calculation_worker(
499 : &self,
500 : tenant: &Tenant,
501 : cancel: &CancellationToken,
502 : ctx: &RequestContext,
503 : ) {
504 : if self.conf.metric_collection_endpoint.is_none() {
505 : // We don't start the consumption metrics task if this is not set in the config.
506 : // So, no need to imitate the accesses in that case.
507 : return;
508 : }
509 :
510 : // The consumption metrics are collected on a per-tenant basis, by a single
511 : // global background loop.
512 : // It limits the number of synthetic size calculations using the global
513 : // `concurrent_tenant_size_logical_size_queries` semaphore to not overload
514 : // the pageserver. (size calculation is somewhat expensive in terms of CPU and IOs).
515 : //
516 : // If we used that same semaphore here, then we'd compete for the
517 : // same permits, which may impact timeliness of consumption metrics.
518 : // That is a no-go, as consumption metrics are much more important
519 : // than what we do here.
520 : //
521 : // So, we have a separate semaphore, initialized to the same
522 : // number of permits as the `concurrent_tenant_size_logical_size_queries`.
523 : // In the worst, we would have twice the amount of concurrenct size calculations.
524 : // But in practice, the `p.threshold` >> `consumption metric interval`, and
525 : // we spread out the eviction task using `random_init_delay`.
526 : // So, the chance of the worst case is quite low in practice.
527 : // It runs as a per-tenant task, but the eviction_task.rs is per-timeline.
528 : // So, we must coordinate with other with other eviction tasks of this tenant.
529 : let limit = self
530 : .conf
531 : .eviction_task_immitated_concurrent_logical_size_queries
532 : .inner();
533 :
534 : let mut throwaway_cache = HashMap::new();
535 : let gather = crate::tenant::size::gather_inputs(
536 : tenant,
537 : limit,
538 : None,
539 : &mut throwaway_cache,
540 : LogicalSizeCalculationCause::EvictionTaskImitation,
541 : cancel,
542 : ctx,
543 : )
544 : .instrument(info_span!("gather_inputs"));
545 :
546 : tokio::select! {
547 : _ = cancel.cancelled() => {}
548 : gather_result = gather => {
549 : match gather_result {
550 : Ok(_) => {},
551 : Err(e) => {
552 : // We don't care about the result, but, if it failed, we should log it,
553 : // since consumption metric might be hitting the cached value and
554 : // thus not encountering this error.
555 : warn!("failed to imitate synthetic size calculation accesses: {e:#}")
556 : }
557 : }
558 : }
559 : }
560 : }
561 : }
|