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