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 : storage_layer::LayerVisibilityHint, tasks::BackgroundLoopKind, timeline::EvictionError,
34 : LogicalSizeCalculationCause, Tenant,
35 : },
36 : };
37 :
38 : use utils::{completion, sync::gate::GateGuard};
39 :
40 : use super::Timeline;
41 :
42 : #[derive(Default)]
43 : pub struct EvictionTaskTimelineState {
44 : last_layer_access_imitation: Option<tokio::time::Instant>,
45 : }
46 :
47 : #[derive(Default)]
48 : pub struct EvictionTaskTenantState {
49 : last_layer_access_imitation: Option<Instant>,
50 : }
51 :
52 : impl Timeline {
53 0 : pub(super) fn launch_eviction_task(
54 0 : self: &Arc<Self>,
55 0 : parent: Arc<Tenant>,
56 0 : background_tasks_can_start: Option<&completion::Barrier>,
57 0 : ) {
58 0 : let self_clone = Arc::clone(self);
59 0 : let background_tasks_can_start = background_tasks_can_start.cloned();
60 0 : task_mgr::spawn(
61 0 : BACKGROUND_RUNTIME.handle(),
62 0 : TaskKind::Eviction,
63 0 : self.tenant_shard_id,
64 0 : Some(self.timeline_id),
65 0 : &format!(
66 0 : "layer eviction for {}/{}",
67 0 : self.tenant_shard_id, self.timeline_id
68 0 : ),
69 0 : async move {
70 0 : tokio::select! {
71 0 : _ = self_clone.cancel.cancelled() => { return Ok(()); }
72 0 : _ = completion::Barrier::maybe_wait(background_tasks_can_start) => {}
73 0 : };
74 0 :
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 :
218 0 : guard
219 0 : .likely_resident_layers()
220 0 : .filter(|layer| {
221 0 : let last_activity_ts = layer.latest_activity();
222 :
223 0 : let no_activity_for = match now.duration_since(last_activity_ts) {
224 0 : Ok(d) => d,
225 0 : Err(_e) => {
226 0 : // We reach here if `now` < `last_activity_ts`, which can legitimately
227 0 : // happen if there is an access between us getting `now`, and us getting
228 0 : // the access stats from the layer.
229 0 : //
230 0 : // The other reason why it can happen is system clock skew because
231 0 : // SystemTime::now() is not monotonic, so, even if there is no access
232 0 : // to the layer after we get `now` at the beginning of this function,
233 0 : // it could be that `now` < `last_activity_ts`.
234 0 : //
235 0 : // To distinguish the cases, we would need to record `Instant`s in the
236 0 : // access stats (i.e., monotonic timestamps), but then, the timestamps
237 0 : // values in the access stats would need to be `Instant`'s, and hence
238 0 : // they would be meaningless outside of the pageserver process.
239 0 : // At the time of writing, the trade-off is that access stats are more
240 0 : // valuable than detecting clock skew.
241 0 : return false;
242 : }
243 : };
244 :
245 0 : match layer.visibility() {
246 : LayerVisibilityHint::Visible => {
247 : // Usual case: a visible layer might be read any time, and we will keep it
248 : // resident until it hits our configured TTL threshold.
249 0 : no_activity_for > p.threshold
250 : }
251 : LayerVisibilityHint::Covered => {
252 : // Covered layers: this is probably a layer that was recently covered by
253 : // an image layer during compaction. We don't evict it immediately, but
254 : // it doesn't stay resident for the full `threshold`: we just keep it
255 : // for a shorter time in case
256 : // - it is used for Timestamp->LSN lookups
257 : // - a new branch is created in recent history which will read this layer
258 0 : no_activity_for > p.period
259 : }
260 : }
261 0 : })
262 0 : .cloned()
263 0 : .for_each(|layer| {
264 0 : js.spawn(async move {
265 0 : layer
266 0 : .evict_and_wait(std::time::Duration::from_secs(5))
267 0 : .await
268 0 : });
269 0 : stats.candidates += 1;
270 0 : });
271 0 : };
272 0 :
273 0 : let join_all = async move {
274 0 : while let Some(next) = js.join_next().await {
275 0 : match next {
276 0 : Ok(Ok(())) => stats.evicted += 1,
277 0 : Ok(Err(EvictionError::NotFound | EvictionError::Downloaded)) => {
278 0 : stats.not_evictable += 1;
279 0 : }
280 0 : Ok(Err(EvictionError::Timeout)) => {
281 0 : stats.timeouts += 1;
282 0 : }
283 0 : Err(je) if je.is_cancelled() => unreachable!("not used"),
284 0 : Err(je) if je.is_panic() => {
285 0 : /* already logged */
286 0 : stats.errors += 1;
287 0 : }
288 0 : Err(je) => tracing::error!("unknown JoinError: {je:?}"),
289 : }
290 : }
291 0 : stats
292 0 : };
293 :
294 0 : tokio::select! {
295 0 : stats = join_all => {
296 0 : if stats.candidates == stats.not_evictable {
297 0 : debug!(stats=?stats, "eviction iteration complete");
298 0 : } else if stats.errors > 0 || stats.not_evictable > 0 || stats.timeouts > 0 {
299 : // reminder: timeouts are not eviction cancellations
300 0 : warn!(stats=?stats, "eviction iteration complete");
301 : } else {
302 0 : info!(stats=?stats, "eviction iteration complete");
303 : }
304 : }
305 0 : _ = cancel.cancelled() => {
306 0 : // just drop the joinset to "abort"
307 0 : }
308 : }
309 :
310 0 : ControlFlow::Continue(())
311 0 : }
312 :
313 : /// Like `eviction_iteration_threshold`, but without any eviction. Eviction will be done by
314 : /// disk usage based eviction task.
315 0 : async fn imitiate_only(
316 0 : self: &Arc<Self>,
317 0 : tenant: &Tenant,
318 0 : p: &EvictionPolicyLayerAccessThreshold,
319 0 : cancel: &CancellationToken,
320 0 : gate: &GateGuard,
321 0 : ctx: &RequestContext,
322 0 : ) -> ControlFlow<()> {
323 0 : let permit = self.acquire_imitation_permit(cancel, ctx).await?;
324 :
325 0 : self.imitate_layer_accesses(tenant, p, cancel, gate, permit, ctx)
326 0 : .await
327 0 : }
328 :
329 0 : async fn acquire_imitation_permit(
330 0 : &self,
331 0 : cancel: &CancellationToken,
332 0 : ctx: &RequestContext,
333 0 : ) -> ControlFlow<(), tokio::sync::SemaphorePermit<'static>> {
334 0 : let acquire_permit = crate::tenant::tasks::concurrent_background_tasks_rate_limit_permit(
335 0 : BackgroundLoopKind::Eviction,
336 0 : ctx,
337 0 : );
338 0 :
339 0 : tokio::select! {
340 0 : permit = acquire_permit => ControlFlow::Continue(permit),
341 0 : _ = cancel.cancelled() => ControlFlow::Break(()),
342 0 : _ = self.cancel.cancelled() => ControlFlow::Break(()),
343 : }
344 0 : }
345 :
346 : /// If we evict layers but keep cached values derived from those layers, then
347 : /// we face a storm of on-demand downloads after pageserver restart.
348 : /// The reason is that the restart empties the caches, and so, the values
349 : /// need to be re-computed by accessing layers, which we evicted while the
350 : /// caches were filled.
351 : ///
352 : /// Solutions here would be one of the following:
353 : /// 1. Have a persistent cache.
354 : /// 2. Count every access to a cached value to the access stats of all layers
355 : /// that were accessed to compute the value in the first place.
356 : /// 3. Invalidate the caches at a period of < p.threshold/2, so that the values
357 : /// get re-computed from layers, thereby counting towards layer access stats.
358 : /// 4. Make the eviction task imitate the layer accesses that typically hit caches.
359 : ///
360 : /// We follow approach (4) here because in Neon prod deployment:
361 : /// - page cache is quite small => high churn => low hit rate
362 : /// => eviction gets correct access stats
363 : /// - value-level caches such as logical size & repatition have a high hit rate,
364 : /// especially for inactive tenants
365 : /// => eviction sees zero accesses for these
366 : /// => they cause the on-demand download storm on pageserver restart
367 : ///
368 : /// We should probably move to persistent caches in the future, or avoid
369 : /// having inactive tenants attached to pageserver in the first place.
370 0 : #[instrument(skip_all)]
371 : async fn imitate_layer_accesses(
372 : &self,
373 : tenant: &Tenant,
374 : p: &EvictionPolicyLayerAccessThreshold,
375 : cancel: &CancellationToken,
376 : gate: &GateGuard,
377 : permit: tokio::sync::SemaphorePermit<'static>,
378 : ctx: &RequestContext,
379 : ) -> ControlFlow<()> {
380 : if !self.tenant_shard_id.is_shard_zero() {
381 : // Shards !=0 do not maintain accurate relation sizes, and do not need to calculate logical size
382 : // for consumption metrics (consumption metrics are only sent from shard 0). We may therefore
383 : // skip imitating logical size accesses for eviction purposes.
384 : return ControlFlow::Continue(());
385 : }
386 :
387 : let mut state = self.eviction_task_timeline_state.lock().await;
388 :
389 : // Only do the imitate_layer accesses approximately as often as the threshold. A little
390 : // more frequently, to avoid this period racing with the threshold/period-th eviction iteration.
391 : let inter_imitate_period = p.threshold.checked_sub(p.period).unwrap_or(p.threshold);
392 :
393 : match state.last_layer_access_imitation {
394 : Some(ts) if ts.elapsed() < inter_imitate_period => { /* no need to run */ }
395 : _ => {
396 : self.imitate_timeline_cached_layer_accesses(gate, ctx).await;
397 : state.last_layer_access_imitation = Some(tokio::time::Instant::now())
398 : }
399 : }
400 : drop(state);
401 :
402 : if cancel.is_cancelled() {
403 : return ControlFlow::Break(());
404 : }
405 :
406 : // This task is timeline-scoped, but the synthetic size calculation is tenant-scoped.
407 : // Make one of the tenant's timelines draw the short straw and run the calculation.
408 : // The others wait until the calculation is done so that they take into account the
409 : // imitated accesses that the winner made.
410 : let (mut state, _permit) = {
411 : if let Ok(locked) = tenant.eviction_task_tenant_state.try_lock() {
412 : (locked, permit)
413 : } else {
414 : // we might need to wait for a long time here in case of pathological synthetic
415 : // size calculation performance
416 : drop(permit);
417 : let locked = tokio::select! {
418 : locked = tenant.eviction_task_tenant_state.lock() => locked,
419 : _ = self.cancel.cancelled() => {
420 : return ControlFlow::Break(())
421 : },
422 : _ = cancel.cancelled() => {
423 : return ControlFlow::Break(())
424 : }
425 : };
426 : // then reacquire -- this will be bad if there is a lot of traffic, but because we
427 : // released the permit, the overall latency will be much better.
428 : let permit = self.acquire_imitation_permit(cancel, ctx).await?;
429 : (locked, permit)
430 : }
431 : };
432 : match state.last_layer_access_imitation {
433 : Some(ts) if ts.elapsed() < inter_imitate_period => { /* no need to run */ }
434 : _ => {
435 : self.imitate_synthetic_size_calculation_worker(tenant, cancel, ctx)
436 : .await;
437 : state.last_layer_access_imitation = Some(tokio::time::Instant::now());
438 : }
439 : }
440 : drop(state);
441 :
442 : if cancel.is_cancelled() {
443 : return ControlFlow::Break(());
444 : }
445 :
446 : ControlFlow::Continue(())
447 : }
448 :
449 : /// Recompute the values which would cause on-demand downloads during restart.
450 0 : #[instrument(skip_all)]
451 : async fn imitate_timeline_cached_layer_accesses(
452 : &self,
453 : guard: &GateGuard,
454 : ctx: &RequestContext,
455 : ) {
456 : let lsn = self.get_last_record_lsn();
457 :
458 : // imitiate on-restart initial logical size
459 : let size = self
460 : .calculate_logical_size(
461 : lsn,
462 : LogicalSizeCalculationCause::EvictionTaskImitation,
463 : guard,
464 : ctx,
465 : )
466 : .instrument(info_span!("calculate_logical_size"))
467 : .await;
468 :
469 : match &size {
470 : Ok(_size) => {
471 : // good, don't log it to avoid confusion
472 : }
473 : Err(_) => {
474 : // we have known issues for which we already log this on consumption metrics,
475 : // gc, and compaction. leave logging out for now.
476 : //
477 : // https://github.com/neondatabase/neon/issues/2539
478 : }
479 : }
480 :
481 : // imitiate repartiting on first compactation
482 : if let Err(e) = self
483 : .collect_keyspace(lsn, ctx)
484 : .instrument(info_span!("collect_keyspace"))
485 : .await
486 : {
487 : // if this failed, we probably failed logical size because these use the same keys
488 : if size.is_err() {
489 : // ignore, see above comment
490 : } else {
491 : match e {
492 : CollectKeySpaceError::Cancelled => {
493 : // Shutting down, ignore
494 : }
495 : err => {
496 : warn!(
497 : "failed to collect keyspace but succeeded in calculating logical size: {err:#}"
498 : );
499 : }
500 : }
501 : }
502 : }
503 : }
504 :
505 : // Imitate the synthetic size calculation done by the consumption_metrics module.
506 0 : #[instrument(skip_all)]
507 : async fn imitate_synthetic_size_calculation_worker(
508 : &self,
509 : tenant: &Tenant,
510 : cancel: &CancellationToken,
511 : ctx: &RequestContext,
512 : ) {
513 : if self.conf.metric_collection_endpoint.is_none() {
514 : // We don't start the consumption metrics task if this is not set in the config.
515 : // So, no need to imitate the accesses in that case.
516 : return;
517 : }
518 :
519 : // The consumption metrics are collected on a per-tenant basis, by a single
520 : // global background loop.
521 : // It limits the number of synthetic size calculations using the global
522 : // `concurrent_tenant_size_logical_size_queries` semaphore to not overload
523 : // the pageserver. (size calculation is somewhat expensive in terms of CPU and IOs).
524 : //
525 : // If we used that same semaphore here, then we'd compete for the
526 : // same permits, which may impact timeliness of consumption metrics.
527 : // That is a no-go, as consumption metrics are much more important
528 : // than what we do here.
529 : //
530 : // So, we have a separate semaphore, initialized to the same
531 : // number of permits as the `concurrent_tenant_size_logical_size_queries`.
532 : // In the worst, we would have twice the amount of concurrenct size calculations.
533 : // But in practice, the `p.threshold` >> `consumption metric interval`, and
534 : // we spread out the eviction task using `random_init_delay`.
535 : // So, the chance of the worst case is quite low in practice.
536 : // It runs as a per-tenant task, but the eviction_task.rs is per-timeline.
537 : // So, we must coordinate with other with other eviction tasks of this tenant.
538 : let limit = self
539 : .conf
540 : .eviction_task_immitated_concurrent_logical_size_queries
541 : .inner();
542 :
543 : let mut throwaway_cache = HashMap::new();
544 : let gather = crate::tenant::size::gather_inputs(
545 : tenant,
546 : limit,
547 : None,
548 : &mut throwaway_cache,
549 : LogicalSizeCalculationCause::EvictionTaskImitation,
550 : cancel,
551 : ctx,
552 : )
553 : .instrument(info_span!("gather_inputs"));
554 :
555 : tokio::select! {
556 : _ = cancel.cancelled() => {}
557 : gather_result = gather => {
558 : match gather_result {
559 : Ok(_) => {},
560 : Err(e) => {
561 : // We don't care about the result, but, if it failed, we should log it,
562 : // since consumption metric might be hitting the cached value and
563 : // thus not encountering this error.
564 : warn!("failed to imitate synthetic size calculation accesses: {e:#}")
565 : }
566 : }
567 : }
568 : }
569 : }
570 : }
|