Line data Source code
1 : use std::cmp;
2 : use std::collections::hash_map::Entry;
3 : use std::collections::{HashMap, HashSet};
4 : use std::sync::Arc;
5 :
6 : use tenant_size_model::svg::SvgBranchKind;
7 : use tokio::sync::oneshot::error::RecvError;
8 : use tokio::sync::Semaphore;
9 : use tokio_util::sync::CancellationToken;
10 :
11 : use crate::context::RequestContext;
12 : use crate::pgdatadir_mapping::CalculateLogicalSizeError;
13 :
14 : use super::{GcError, LogicalSizeCalculationCause, Tenant};
15 : use crate::tenant::Timeline;
16 : use utils::id::TimelineId;
17 : use utils::lsn::Lsn;
18 :
19 : use tracing::*;
20 :
21 : use tenant_size_model::{Segment, StorageModel};
22 :
23 : /// Inputs to the actual tenant sizing model
24 : ///
25 : /// Implements [`serde::Serialize`] but is not meant to be part of the public API, instead meant to
26 : /// be a transferrable format between execution environments and developer.
27 : ///
28 : /// This tracks more information than the actual StorageModel that calculation
29 : /// needs. We will convert this into a StorageModel when it's time to perform
30 : /// the calculation.
31 : ///
32 12 : #[derive(Debug, serde::Serialize, serde::Deserialize)]
33 : pub struct ModelInputs {
34 : pub segments: Vec<SegmentMeta>,
35 : pub timeline_inputs: Vec<TimelineInputs>,
36 : }
37 :
38 : /// A [`Segment`], with some extra information for display purposes
39 112 : #[derive(Debug, serde::Serialize, serde::Deserialize)]
40 : pub struct SegmentMeta {
41 : pub segment: Segment,
42 : pub timeline_id: TimelineId,
43 : pub kind: LsnKind,
44 : }
45 :
46 0 : #[derive(thiserror::Error, Debug)]
47 : pub(crate) enum CalculateSyntheticSizeError {
48 : /// Something went wrong internally to the calculation of logical size at a particular branch point
49 : #[error("Failed to calculated logical size on timeline {timeline_id} at {lsn}: {error}")]
50 : LogicalSize {
51 : timeline_id: TimelineId,
52 : lsn: Lsn,
53 : error: CalculateLogicalSizeError,
54 : },
55 :
56 : /// Something went wrong internally when calculating GC parameters at start of size calculation
57 : #[error(transparent)]
58 : GcInfo(GcError),
59 :
60 : /// Totally unexpected errors, like panics joining a task
61 : #[error(transparent)]
62 : Fatal(anyhow::Error),
63 :
64 : /// Tenant shut down while calculating size
65 : #[error("Cancelled")]
66 : Cancelled,
67 : }
68 :
69 : impl From<GcError> for CalculateSyntheticSizeError {
70 0 : fn from(value: GcError) -> Self {
71 0 : match value {
72 : GcError::TenantCancelled | GcError::TimelineCancelled => {
73 0 : CalculateSyntheticSizeError::Cancelled
74 : }
75 0 : other => CalculateSyntheticSizeError::GcInfo(other),
76 : }
77 0 : }
78 : }
79 :
80 : impl SegmentMeta {
81 0 : fn size_needed(&self) -> bool {
82 0 : match self.kind {
83 : LsnKind::BranchStart => {
84 : // If we don't have a later GcCutoff point on this branch, and
85 : // no ancestor, calculate size for the branch start point.
86 0 : self.segment.needed && self.segment.parent.is_none()
87 : }
88 0 : LsnKind::BranchPoint => true,
89 0 : LsnKind::GcCutOff => true,
90 0 : LsnKind::BranchEnd => false,
91 0 : LsnKind::LeasePoint => true,
92 0 : LsnKind::LeaseStart => false,
93 0 : LsnKind::LeaseEnd => false,
94 : }
95 0 : }
96 : }
97 :
98 : #[derive(
99 56 : Debug, Clone, Copy, Eq, Ord, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize,
100 : )]
101 : pub enum LsnKind {
102 : /// A timeline starting here
103 : BranchStart,
104 : /// A child timeline branches off from here
105 : BranchPoint,
106 : /// GC cutoff point
107 : GcCutOff,
108 : /// Last record LSN
109 : BranchEnd,
110 : /// A LSN lease is granted here.
111 : LeasePoint,
112 : /// A lease starts from here.
113 : LeaseStart,
114 : /// Last record LSN for the lease (should have the same LSN as the previous [`LsnKind::LeaseStart`]).
115 : LeaseEnd,
116 : }
117 :
118 : impl From<LsnKind> for SvgBranchKind {
119 0 : fn from(kind: LsnKind) -> Self {
120 0 : match kind {
121 0 : LsnKind::LeasePoint | LsnKind::LeaseStart | LsnKind::LeaseEnd => SvgBranchKind::Lease,
122 0 : _ => SvgBranchKind::Timeline,
123 : }
124 0 : }
125 : }
126 :
127 : /// Collect all relevant LSNs to the inputs. These will only be helpful in the serialized form as
128 : /// part of [`ModelInputs`] from the HTTP api, explaining the inputs.
129 80 : #[derive(Debug, serde::Serialize, serde::Deserialize)]
130 : pub struct TimelineInputs {
131 : pub timeline_id: TimelineId,
132 :
133 : pub ancestor_id: Option<TimelineId>,
134 :
135 : ancestor_lsn: Lsn,
136 : last_record: Lsn,
137 : latest_gc_cutoff: Lsn,
138 : horizon_cutoff: Lsn,
139 : pitr_cutoff: Lsn,
140 :
141 : /// Cutoff point based on GC settings
142 : next_gc_cutoff: Lsn,
143 :
144 : /// Cutoff point calculated from the user-supplied 'max_retention_period'
145 : retention_param_cutoff: Option<Lsn>,
146 :
147 : /// Lease points on the timeline
148 : lease_points: Vec<Lsn>,
149 : }
150 :
151 : /// Gathers the inputs for the tenant sizing model.
152 : ///
153 : /// Tenant size does not consider the latest state, but only the state until next_gc_cutoff, which
154 : /// is updated on-demand, during the start of this calculation and separate from the
155 : /// [`TimelineInputs::latest_gc_cutoff`].
156 : ///
157 : /// For timelines in general:
158 : ///
159 : /// ```text
160 : /// 0-----|---------|----|------------| · · · · · |·> lsn
161 : /// initdb_lsn branchpoints* next_gc_cutoff latest
162 : /// ```
163 : ///
164 : /// Until gc_horizon_cutoff > `Timeline::last_record_lsn` for any of the tenant's timelines, the
165 : /// tenant size will be zero.
166 0 : pub(super) async fn gather_inputs(
167 0 : tenant: &Tenant,
168 0 : limit: &Arc<Semaphore>,
169 0 : max_retention_period: Option<u64>,
170 0 : logical_size_cache: &mut HashMap<(TimelineId, Lsn), u64>,
171 0 : cause: LogicalSizeCalculationCause,
172 0 : cancel: &CancellationToken,
173 0 : ctx: &RequestContext,
174 0 : ) -> Result<ModelInputs, CalculateSyntheticSizeError> {
175 0 : // refresh is needed to update gc related pitr_cutoff and horizon_cutoff
176 0 : tenant.refresh_gc_info(cancel, ctx).await?;
177 :
178 : // Collect information about all the timelines
179 0 : let mut timelines = tenant.list_timelines();
180 0 :
181 0 : if timelines.is_empty() {
182 : // perhaps the tenant has just been created, and as such doesn't have any data yet
183 0 : return Ok(ModelInputs {
184 0 : segments: vec![],
185 0 : timeline_inputs: Vec::new(),
186 0 : });
187 0 : }
188 0 :
189 0 : // Filter out timelines that are not active
190 0 : //
191 0 : // There may be a race when a timeline is dropped,
192 0 : // but it is unlikely to cause any issues. In the worst case,
193 0 : // the calculation will error out.
194 0 : timelines.retain(|t| t.is_active());
195 0 :
196 0 : // Build a map of branch points.
197 0 : let mut branchpoints: HashMap<TimelineId, HashSet<Lsn>> = HashMap::new();
198 0 : for timeline in timelines.iter() {
199 0 : if let Some(ancestor_id) = timeline.get_ancestor_timeline_id() {
200 0 : branchpoints
201 0 : .entry(ancestor_id)
202 0 : .or_default()
203 0 : .insert(timeline.get_ancestor_lsn());
204 0 : }
205 : }
206 :
207 : // These become the final result.
208 0 : let mut timeline_inputs = Vec::with_capacity(timelines.len());
209 0 : let mut segments: Vec<SegmentMeta> = Vec::new();
210 0 :
211 0 : //
212 0 : // Build Segments representing each timeline. As we do that, also remember
213 0 : // the branchpoints and branch startpoints in 'branchpoint_segments' and
214 0 : // 'branchstart_segments'
215 0 : //
216 0 :
217 0 : // BranchPoint segments of each timeline
218 0 : // (timeline, branchpoint LSN) -> segment_id
219 0 : let mut branchpoint_segments: HashMap<(TimelineId, Lsn), usize> = HashMap::new();
220 0 :
221 0 : // timeline, Branchpoint seg id, (ancestor, ancestor LSN)
222 0 : type BranchStartSegment = (TimelineId, usize, Option<(TimelineId, Lsn)>);
223 0 : let mut branchstart_segments: Vec<BranchStartSegment> = Vec::new();
224 :
225 0 : for timeline in timelines.iter() {
226 0 : let timeline_id = timeline.timeline_id;
227 0 : let last_record_lsn = timeline.get_last_record_lsn();
228 0 : let ancestor_lsn = timeline.get_ancestor_lsn();
229 0 :
230 0 : // there's a race between the update (holding tenant.gc_lock) and this read but it
231 0 : // might not be an issue, because it's not for Timeline::gc
232 0 : let gc_info = timeline.gc_info.read().unwrap();
233 0 :
234 0 : // similar to gc, but Timeline::get_latest_gc_cutoff_lsn() will not be updated before a
235 0 : // new gc run, which we have no control over. however differently from `Timeline::gc`
236 0 : // we don't consider the `Timeline::disk_consistent_lsn` at all, because we are not
237 0 : // actually removing files.
238 0 : //
239 0 : // We only consider [`GcInfo::pitr_cutoff`], and not [`GcInfo::horizon_cutoff`], because from
240 0 : // a user's perspective they have only requested retention up to the time bound (pitr_cutoff), rather
241 0 : // than a space bound (horizon cutoff). This means that if someone drops a database and waits for their
242 0 : // PITR interval, they will see synthetic size decrease, even if we are still storing data inside
243 0 : // horizon_cutoff.
244 0 : let pitr_cutoff = gc_info.cutoffs.pitr;
245 0 : let horizon_cutoff = gc_info.cutoffs.horizon;
246 0 : let mut next_gc_cutoff = pitr_cutoff;
247 :
248 : // If the caller provided a shorter retention period, use that instead of the GC cutoff.
249 0 : let retention_param_cutoff = if let Some(max_retention_period) = max_retention_period {
250 0 : let param_cutoff = Lsn(last_record_lsn.0.saturating_sub(max_retention_period));
251 0 : if next_gc_cutoff < param_cutoff {
252 0 : next_gc_cutoff = param_cutoff;
253 0 : }
254 0 : Some(param_cutoff)
255 : } else {
256 0 : None
257 : };
258 :
259 0 : let lease_points = gc_info
260 0 : .leases
261 0 : .keys()
262 0 : .filter(|&&lsn| lsn > ancestor_lsn)
263 0 : .copied()
264 0 : .collect::<Vec<_>>();
265 0 :
266 0 : // next_gc_cutoff in parent branch are not of interest (right now at least), nor do we
267 0 : // want to query any logical size before initdb_lsn.
268 0 : let branch_start_lsn = cmp::max(ancestor_lsn, timeline.initdb_lsn);
269 0 :
270 0 : // Build "interesting LSNs" on this timeline
271 0 : let mut lsns: Vec<(Lsn, LsnKind)> = gc_info
272 0 : .retain_lsns
273 0 : .iter()
274 0 : .filter(|&&lsn| lsn > ancestor_lsn)
275 0 : .copied()
276 0 : // this assumes there are no other retain_lsns than the branchpoints
277 0 : .map(|lsn| (lsn, LsnKind::BranchPoint))
278 0 : .collect::<Vec<_>>();
279 0 :
280 0 : lsns.extend(lease_points.iter().map(|&lsn| (lsn, LsnKind::LeasePoint)));
281 0 :
282 0 : drop(gc_info);
283 :
284 : // Add branch points we collected earlier, just in case there were any that were
285 : // not present in retain_lsns. We will remove any duplicates below later.
286 0 : if let Some(this_branchpoints) = branchpoints.get(&timeline_id) {
287 0 : lsns.extend(
288 0 : this_branchpoints
289 0 : .iter()
290 0 : .map(|lsn| (*lsn, LsnKind::BranchPoint)),
291 0 : )
292 0 : }
293 :
294 : // Add a point for the GC cutoff
295 0 : let branch_start_needed = next_gc_cutoff <= branch_start_lsn;
296 0 : if !branch_start_needed {
297 0 : lsns.push((next_gc_cutoff, LsnKind::GcCutOff));
298 0 : }
299 :
300 0 : lsns.sort_unstable();
301 0 : lsns.dedup();
302 0 :
303 0 : //
304 0 : // Create Segments for the interesting points.
305 0 : //
306 0 :
307 0 : // Timeline start point
308 0 : let ancestor = timeline
309 0 : .get_ancestor_timeline_id()
310 0 : .map(|ancestor_id| (ancestor_id, ancestor_lsn));
311 0 : branchstart_segments.push((timeline_id, segments.len(), ancestor));
312 0 : segments.push(SegmentMeta {
313 0 : segment: Segment {
314 0 : parent: None, // filled in later
315 0 : lsn: branch_start_lsn.0,
316 0 : size: None, // filled in later
317 0 : needed: branch_start_needed,
318 0 : },
319 0 : timeline_id: timeline.timeline_id,
320 0 : kind: LsnKind::BranchStart,
321 0 : });
322 0 :
323 0 : // GC cutoff point, and any branch points, i.e. points where
324 0 : // other timelines branch off from this timeline.
325 0 : let mut parent = segments.len() - 1;
326 0 : for (lsn, kind) in lsns {
327 0 : if kind == LsnKind::BranchPoint {
328 0 : branchpoint_segments.insert((timeline_id, lsn), segments.len());
329 0 : }
330 :
331 0 : segments.push(SegmentMeta {
332 0 : segment: Segment {
333 0 : parent: Some(parent),
334 0 : lsn: lsn.0,
335 0 : size: None,
336 0 : needed: lsn > next_gc_cutoff,
337 0 : },
338 0 : timeline_id: timeline.timeline_id,
339 0 : kind,
340 0 : });
341 0 :
342 0 : parent = segments.len() - 1;
343 0 :
344 0 : if kind == LsnKind::LeasePoint {
345 0 : // Needs `LeaseStart` and `LeaseEnd` as well to model lease as a read-only branch that never writes data
346 0 : // (i.e. it's lsn has not advanced from ancestor_lsn), and therefore the three segments have the same LSN
347 0 : // value. Without the other two segments, the calculation code would not count the leased LSN as a point
348 0 : // to be retained.
349 0 : // Did not use `BranchStart` or `BranchEnd` so we can differentiate branches and leases during debug.
350 0 : //
351 0 : // Alt Design: rewrite the entire calculation code to be independent of timeline id. Both leases and
352 0 : // branch points can be given a synthetic id so we can unite them.
353 0 : let mut lease_parent = parent;
354 0 :
355 0 : // Start of a lease.
356 0 : segments.push(SegmentMeta {
357 0 : segment: Segment {
358 0 : parent: Some(lease_parent),
359 0 : lsn: lsn.0,
360 0 : size: None, // Filled in later, if necessary
361 0 : needed: lsn > next_gc_cutoff, // only needed if the point is within rentention.
362 0 : },
363 0 : timeline_id: timeline.timeline_id,
364 0 : kind: LsnKind::LeaseStart,
365 0 : });
366 0 : lease_parent += 1;
367 0 :
368 0 : // End of the lease.
369 0 : segments.push(SegmentMeta {
370 0 : segment: Segment {
371 0 : parent: Some(lease_parent),
372 0 : lsn: lsn.0,
373 0 : size: None, // Filled in later, if necessary
374 0 : needed: true, // everything at the lease LSN must be readable => is needed
375 0 : },
376 0 : timeline_id: timeline.timeline_id,
377 0 : kind: LsnKind::LeaseEnd,
378 0 : });
379 0 : }
380 : }
381 :
382 : // Current end of the timeline
383 0 : segments.push(SegmentMeta {
384 0 : segment: Segment {
385 0 : parent: Some(parent),
386 0 : lsn: last_record_lsn.0,
387 0 : size: None, // Filled in later, if necessary
388 0 : needed: true,
389 0 : },
390 0 : timeline_id: timeline.timeline_id,
391 0 : kind: LsnKind::BranchEnd,
392 0 : });
393 0 :
394 0 : timeline_inputs.push(TimelineInputs {
395 0 : timeline_id: timeline.timeline_id,
396 0 : ancestor_id: timeline.get_ancestor_timeline_id(),
397 0 : ancestor_lsn,
398 0 : last_record: last_record_lsn,
399 0 : // this is not used above, because it might not have updated recently enough
400 0 : latest_gc_cutoff: *timeline.get_latest_gc_cutoff_lsn(),
401 0 : horizon_cutoff,
402 0 : pitr_cutoff,
403 0 : next_gc_cutoff,
404 0 : retention_param_cutoff,
405 0 : lease_points,
406 0 : });
407 : }
408 :
409 : // We now have all segments from the timelines in 'segments'. The timelines
410 : // haven't been linked to each other yet, though. Do that.
411 0 : for (_timeline_id, seg_id, ancestor) in branchstart_segments {
412 : // Look up the branch point
413 0 : if let Some(ancestor) = ancestor {
414 0 : let parent_id = *branchpoint_segments.get(&ancestor).unwrap();
415 0 : segments[seg_id].segment.parent = Some(parent_id);
416 0 : }
417 : }
418 :
419 : // We left the 'size' field empty in all of the Segments so far.
420 : // Now find logical sizes for all of the points that might need or benefit from them.
421 0 : fill_logical_sizes(
422 0 : &timelines,
423 0 : &mut segments,
424 0 : limit,
425 0 : logical_size_cache,
426 0 : cause,
427 0 : ctx,
428 0 : )
429 0 : .await?;
430 :
431 0 : if tenant.cancel.is_cancelled() {
432 : // If we're shutting down, return an error rather than a sparse result that might include some
433 : // timelines from before we started shutting down
434 0 : return Err(CalculateSyntheticSizeError::Cancelled);
435 0 : }
436 0 :
437 0 : Ok(ModelInputs {
438 0 : segments,
439 0 : timeline_inputs,
440 0 : })
441 0 : }
442 :
443 : /// Augment 'segments' with logical sizes
444 : ///
445 : /// This will leave segments' sizes as None if the Timeline associated with the segment is deleted concurrently
446 : /// (i.e. we cannot read its logical size at a particular LSN).
447 0 : async fn fill_logical_sizes(
448 0 : timelines: &[Arc<Timeline>],
449 0 : segments: &mut [SegmentMeta],
450 0 : limit: &Arc<Semaphore>,
451 0 : logical_size_cache: &mut HashMap<(TimelineId, Lsn), u64>,
452 0 : cause: LogicalSizeCalculationCause,
453 0 : ctx: &RequestContext,
454 0 : ) -> Result<(), CalculateSyntheticSizeError> {
455 0 : let timeline_hash: HashMap<TimelineId, Arc<Timeline>> = HashMap::from_iter(
456 0 : timelines
457 0 : .iter()
458 0 : .map(|timeline| (timeline.timeline_id, Arc::clone(timeline))),
459 0 : );
460 0 :
461 0 : // record the used/inserted cache keys here, to remove extras not to start leaking
462 0 : // after initial run the cache should be quite stable, but live timelines will eventually
463 0 : // require new lsns to be inspected.
464 0 : let mut sizes_needed = HashMap::<(TimelineId, Lsn), Option<u64>>::new();
465 0 :
466 0 : // with joinset, on drop, all of the tasks will just be de-scheduled, which we can use to
467 0 : // our advantage with `?` error handling.
468 0 : let mut joinset = tokio::task::JoinSet::new();
469 :
470 : // For each point that would benefit from having a logical size available,
471 : // spawn a Task to fetch it, unless we have it cached already.
472 0 : for seg in segments.iter() {
473 0 : if !seg.size_needed() {
474 0 : continue;
475 0 : }
476 0 :
477 0 : let timeline_id = seg.timeline_id;
478 0 : let lsn = Lsn(seg.segment.lsn);
479 :
480 0 : if let Entry::Vacant(e) = sizes_needed.entry((timeline_id, lsn)) {
481 0 : let cached_size = logical_size_cache.get(&(timeline_id, lsn)).cloned();
482 0 : if cached_size.is_none() {
483 0 : let timeline = Arc::clone(timeline_hash.get(&timeline_id).unwrap());
484 0 : let parallel_size_calcs = Arc::clone(limit);
485 0 : let ctx = ctx.attached_child();
486 0 : joinset.spawn(
487 0 : calculate_logical_size(parallel_size_calcs, timeline, lsn, cause, ctx)
488 0 : .in_current_span(),
489 0 : );
490 0 : }
491 0 : e.insert(cached_size);
492 0 : }
493 : }
494 :
495 : // Perform the size lookups
496 0 : let mut have_any_error = None;
497 0 : while let Some(res) = joinset.join_next().await {
498 : // each of these come with Result<anyhow::Result<_>, JoinError>
499 : // because of spawn + spawn_blocking
500 0 : match res {
501 0 : Err(join_error) if join_error.is_cancelled() => {
502 0 : unreachable!("we are not cancelling any of the futures, nor should be");
503 : }
504 0 : Err(join_error) => {
505 0 : // cannot really do anything, as this panic is likely a bug
506 0 : error!("task that calls spawn_ondemand_logical_size_calculation panicked: {join_error:#}");
507 :
508 0 : have_any_error = Some(CalculateSyntheticSizeError::Fatal(
509 0 : anyhow::anyhow!(join_error)
510 0 : .context("task that calls spawn_ondemand_logical_size_calculation"),
511 0 : ));
512 : }
513 0 : Ok(Err(recv_result_error)) => {
514 0 : // cannot really do anything, as this panic is likely a bug
515 0 : error!("failed to receive logical size query result: {recv_result_error:#}");
516 0 : have_any_error = Some(CalculateSyntheticSizeError::Fatal(
517 0 : anyhow::anyhow!(recv_result_error)
518 0 : .context("Receiving logical size query result"),
519 0 : ));
520 : }
521 0 : Ok(Ok(TimelineAtLsnSizeResult(timeline, lsn, Err(error)))) => {
522 0 : if matches!(error, CalculateLogicalSizeError::Cancelled) {
523 : // Skip this: it's okay if one timeline among many is shutting down while we
524 : // calculate inputs for the overall tenant.
525 0 : continue;
526 : } else {
527 0 : warn!(
528 0 : timeline_id=%timeline.timeline_id,
529 0 : "failed to calculate logical size at {lsn}: {error:#}"
530 : );
531 0 : have_any_error = Some(CalculateSyntheticSizeError::LogicalSize {
532 0 : timeline_id: timeline.timeline_id,
533 0 : lsn,
534 0 : error,
535 0 : });
536 : }
537 : }
538 0 : Ok(Ok(TimelineAtLsnSizeResult(timeline, lsn, Ok(size)))) => {
539 0 : debug!(timeline_id=%timeline.timeline_id, %lsn, size, "size calculated");
540 :
541 0 : logical_size_cache.insert((timeline.timeline_id, lsn), size);
542 0 : sizes_needed.insert((timeline.timeline_id, lsn), Some(size));
543 : }
544 : }
545 : }
546 :
547 : // prune any keys not needed anymore; we record every used key and added key.
548 0 : logical_size_cache.retain(|key, _| sizes_needed.contains_key(key));
549 :
550 0 : if let Some(error) = have_any_error {
551 : // we cannot complete this round, because we are missing data.
552 : // we have however cached all we were able to request calculation on.
553 0 : return Err(error);
554 0 : }
555 :
556 : // Insert the looked up sizes to the Segments
557 0 : for seg in segments.iter_mut() {
558 0 : if !seg.size_needed() {
559 0 : continue;
560 0 : }
561 0 :
562 0 : let timeline_id = seg.timeline_id;
563 0 : let lsn = Lsn(seg.segment.lsn);
564 :
565 0 : if let Some(Some(size)) = sizes_needed.get(&(timeline_id, lsn)) {
566 0 : seg.segment.size = Some(*size);
567 0 : }
568 : }
569 0 : Ok(())
570 0 : }
571 :
572 : impl ModelInputs {
573 4 : pub fn calculate_model(&self) -> tenant_size_model::StorageModel {
574 4 : // Convert SegmentMetas into plain Segments
575 4 : StorageModel {
576 4 : segments: self
577 4 : .segments
578 4 : .iter()
579 28 : .map(|seg| seg.segment.clone())
580 4 : .collect(),
581 4 : }
582 4 : }
583 :
584 : // calculate total project size
585 2 : pub fn calculate(&self) -> u64 {
586 2 : let storage = self.calculate_model();
587 2 : let sizes = storage.calculate();
588 2 : sizes.total_size
589 2 : }
590 : }
591 :
592 : /// Newtype around the tuple that carries the timeline at lsn logical size calculation.
593 : struct TimelineAtLsnSizeResult(
594 : Arc<crate::tenant::Timeline>,
595 : utils::lsn::Lsn,
596 : Result<u64, CalculateLogicalSizeError>,
597 : );
598 :
599 0 : #[instrument(skip_all, fields(timeline_id=%timeline.timeline_id, lsn=%lsn))]
600 : async fn calculate_logical_size(
601 : limit: Arc<tokio::sync::Semaphore>,
602 : timeline: Arc<crate::tenant::Timeline>,
603 : lsn: utils::lsn::Lsn,
604 : cause: LogicalSizeCalculationCause,
605 : ctx: RequestContext,
606 : ) -> Result<TimelineAtLsnSizeResult, RecvError> {
607 : let _permit = tokio::sync::Semaphore::acquire_owned(limit)
608 : .await
609 : .expect("global semaphore should not had been closed");
610 :
611 : let size_res = timeline
612 : .spawn_ondemand_logical_size_calculation(lsn, cause, ctx)
613 : .instrument(info_span!("spawn_ondemand_logical_size_calculation"))
614 : .await?;
615 : Ok(TimelineAtLsnSizeResult(timeline, lsn, size_res))
616 : }
617 :
618 : #[test]
619 2 : fn verify_size_for_multiple_branches() {
620 2 : // this is generated from integration test test_tenant_size_with_multiple_branches, but this way
621 2 : // it has the stable lsn's
622 2 : //
623 2 : // The timeline_inputs don't participate in the size calculation, and are here just to explain
624 2 : // the inputs.
625 2 : let doc = r#"
626 2 : {
627 2 : "segments": [
628 2 : {
629 2 : "segment": {
630 2 : "parent": 9,
631 2 : "lsn": 26033560,
632 2 : "size": null,
633 2 : "needed": false
634 2 : },
635 2 : "timeline_id": "20b129c9b50cff7213e6503a31b2a5ce",
636 2 : "kind": "BranchStart"
637 2 : },
638 2 : {
639 2 : "segment": {
640 2 : "parent": 0,
641 2 : "lsn": 35720400,
642 2 : "size": 25206784,
643 2 : "needed": false
644 2 : },
645 2 : "timeline_id": "20b129c9b50cff7213e6503a31b2a5ce",
646 2 : "kind": "GcCutOff"
647 2 : },
648 2 : {
649 2 : "segment": {
650 2 : "parent": 1,
651 2 : "lsn": 35851472,
652 2 : "size": null,
653 2 : "needed": true
654 2 : },
655 2 : "timeline_id": "20b129c9b50cff7213e6503a31b2a5ce",
656 2 : "kind": "BranchEnd"
657 2 : },
658 2 : {
659 2 : "segment": {
660 2 : "parent": 7,
661 2 : "lsn": 24566168,
662 2 : "size": null,
663 2 : "needed": false
664 2 : },
665 2 : "timeline_id": "454626700469f0a9914949b9d018e876",
666 2 : "kind": "BranchStart"
667 2 : },
668 2 : {
669 2 : "segment": {
670 2 : "parent": 3,
671 2 : "lsn": 25261936,
672 2 : "size": 26050560,
673 2 : "needed": false
674 2 : },
675 2 : "timeline_id": "454626700469f0a9914949b9d018e876",
676 2 : "kind": "GcCutOff"
677 2 : },
678 2 : {
679 2 : "segment": {
680 2 : "parent": 4,
681 2 : "lsn": 25393008,
682 2 : "size": null,
683 2 : "needed": true
684 2 : },
685 2 : "timeline_id": "454626700469f0a9914949b9d018e876",
686 2 : "kind": "BranchEnd"
687 2 : },
688 2 : {
689 2 : "segment": {
690 2 : "parent": null,
691 2 : "lsn": 23694408,
692 2 : "size": null,
693 2 : "needed": false
694 2 : },
695 2 : "timeline_id": "cb5e3cbe60a4afc00d01880e1a37047f",
696 2 : "kind": "BranchStart"
697 2 : },
698 2 : {
699 2 : "segment": {
700 2 : "parent": 6,
701 2 : "lsn": 24566168,
702 2 : "size": 25739264,
703 2 : "needed": false
704 2 : },
705 2 : "timeline_id": "cb5e3cbe60a4afc00d01880e1a37047f",
706 2 : "kind": "BranchPoint"
707 2 : },
708 2 : {
709 2 : "segment": {
710 2 : "parent": 7,
711 2 : "lsn": 25902488,
712 2 : "size": 26402816,
713 2 : "needed": false
714 2 : },
715 2 : "timeline_id": "cb5e3cbe60a4afc00d01880e1a37047f",
716 2 : "kind": "GcCutOff"
717 2 : },
718 2 : {
719 2 : "segment": {
720 2 : "parent": 8,
721 2 : "lsn": 26033560,
722 2 : "size": 26468352,
723 2 : "needed": true
724 2 : },
725 2 : "timeline_id": "cb5e3cbe60a4afc00d01880e1a37047f",
726 2 : "kind": "BranchPoint"
727 2 : },
728 2 : {
729 2 : "segment": {
730 2 : "parent": 9,
731 2 : "lsn": 26033560,
732 2 : "size": null,
733 2 : "needed": true
734 2 : },
735 2 : "timeline_id": "cb5e3cbe60a4afc00d01880e1a37047f",
736 2 : "kind": "BranchEnd"
737 2 : }
738 2 : ],
739 2 : "timeline_inputs": [
740 2 : {
741 2 : "timeline_id": "20b129c9b50cff7213e6503a31b2a5ce",
742 2 : "ancestor_lsn": "0/18D3D98",
743 2 : "last_record": "0/2230CD0",
744 2 : "latest_gc_cutoff": "0/1698C48",
745 2 : "horizon_cutoff": "0/2210CD0",
746 2 : "pitr_cutoff": "0/2210CD0",
747 2 : "next_gc_cutoff": "0/2210CD0",
748 2 : "retention_param_cutoff": null,
749 2 : "lease_points": []
750 2 : },
751 2 : {
752 2 : "timeline_id": "454626700469f0a9914949b9d018e876",
753 2 : "ancestor_lsn": "0/176D998",
754 2 : "last_record": "0/1837770",
755 2 : "latest_gc_cutoff": "0/1698C48",
756 2 : "horizon_cutoff": "0/1817770",
757 2 : "pitr_cutoff": "0/1817770",
758 2 : "next_gc_cutoff": "0/1817770",
759 2 : "retention_param_cutoff": null,
760 2 : "lease_points": []
761 2 : },
762 2 : {
763 2 : "timeline_id": "cb5e3cbe60a4afc00d01880e1a37047f",
764 2 : "ancestor_lsn": "0/0",
765 2 : "last_record": "0/18D3D98",
766 2 : "latest_gc_cutoff": "0/1698C48",
767 2 : "horizon_cutoff": "0/18B3D98",
768 2 : "pitr_cutoff": "0/18B3D98",
769 2 : "next_gc_cutoff": "0/18B3D98",
770 2 : "retention_param_cutoff": null,
771 2 : "lease_points": []
772 2 : }
773 2 : ]
774 2 : }
775 2 : "#;
776 2 : let inputs: ModelInputs = serde_json::from_str(doc).unwrap();
777 2 :
778 2 : assert_eq!(inputs.calculate(), 37_851_408);
779 2 : }
780 :
781 : #[test]
782 2 : fn verify_size_for_one_branch() {
783 2 : let doc = r#"
784 2 : {
785 2 : "segments": [
786 2 : {
787 2 : "segment": {
788 2 : "parent": null,
789 2 : "lsn": 0,
790 2 : "size": null,
791 2 : "needed": false
792 2 : },
793 2 : "timeline_id": "f15ae0cf21cce2ba27e4d80c6709a6cd",
794 2 : "kind": "BranchStart"
795 2 : },
796 2 : {
797 2 : "segment": {
798 2 : "parent": 0,
799 2 : "lsn": 305547335776,
800 2 : "size": 220054675456,
801 2 : "needed": false
802 2 : },
803 2 : "timeline_id": "f15ae0cf21cce2ba27e4d80c6709a6cd",
804 2 : "kind": "GcCutOff"
805 2 : },
806 2 : {
807 2 : "segment": {
808 2 : "parent": 1,
809 2 : "lsn": 305614444640,
810 2 : "size": null,
811 2 : "needed": true
812 2 : },
813 2 : "timeline_id": "f15ae0cf21cce2ba27e4d80c6709a6cd",
814 2 : "kind": "BranchEnd"
815 2 : }
816 2 : ],
817 2 : "timeline_inputs": [
818 2 : {
819 2 : "timeline_id": "f15ae0cf21cce2ba27e4d80c6709a6cd",
820 2 : "ancestor_lsn": "0/0",
821 2 : "last_record": "47/280A5860",
822 2 : "latest_gc_cutoff": "47/240A5860",
823 2 : "horizon_cutoff": "47/240A5860",
824 2 : "pitr_cutoff": "47/240A5860",
825 2 : "next_gc_cutoff": "47/240A5860",
826 2 : "retention_param_cutoff": "0/0",
827 2 : "lease_points": []
828 2 : }
829 2 : ]
830 2 : }"#;
831 2 :
832 2 : let model: ModelInputs = serde_json::from_str(doc).unwrap();
833 2 :
834 2 : let res = model.calculate_model().calculate();
835 2 :
836 2 : println!("calculated synthetic size: {}", res.total_size);
837 2 : println!("result: {:?}", serde_json::to_string(&res.segments));
838 2 :
839 2 : use utils::lsn::Lsn;
840 2 : let latest_gc_cutoff_lsn: Lsn = "47/240A5860".parse().unwrap();
841 2 : let last_lsn: Lsn = "47/280A5860".parse().unwrap();
842 2 : println!(
843 2 : "latest_gc_cutoff lsn 47/240A5860 is {}, last_lsn lsn 47/280A5860 is {}",
844 2 : u64::from(latest_gc_cutoff_lsn),
845 2 : u64::from(last_lsn)
846 2 : );
847 2 : assert_eq!(res.total_size, 220121784320);
848 2 : }
|