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