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