trace-server: pack SpanEvent to 16 bytes, add a memory report

Peak RSS for a large trace is dominated by span / event structs. Cutting
those should be a meaningful RSS win.

Measurement:

- Store::memory_report(), behind MEMORY_REPORT=1, computes a breakdown
  of span chunks, events, arg heap spill, etc.
- TurboMalloc::memory_usage() is appended to the progress line. Whole-process
  RSS is too noisy to use here

SpanEvent cut in half:

- Drop a per-event OnceLock, which was half of the struct.
- Removing it left SpanEvent as a hand-packed, two word struct. And the
  CHILD_TAG bit allows ORD to ensure the previous sort order.
- invalidate_outdated_spans no longer walks event lists. That loop ran over
  every ancestor of every touched span after each read batch, so this is an
  ingestion speed win as well as a memory one.

Measured with STOP_AT=2000:

  size_of::<SpanEvent>()    32 -> 16
  size_of::<Span>()        344 -> 328
  events heap             1030 -> 515 MB
  allocator live          5044 -> 4424 MB    (-620 MB)
  peak RSS                5979 -> ~5200 MB   (-13%)
  ingest rate          236MB/s -> 262 MB/s

Tests:

Fixture tests so that we can guarantee behavior across changes, with
ignore'd tests so that we can manually run them without affecting CI.
There are 4 new tests that _do_ run on CI, including a cache coherence one.
parent d434afa8
...@@ -80,6 +80,32 @@ impl<T> ChunkedVec<T> { ...@@ -80,6 +80,32 @@ impl<T> ChunkedVec<T> {
// `push` and not freed by `truncate`. // `push` and not freed by `truncate`.
Some(unsafe { self.chunks[chunk_idx][off].assume_init_ref() }) Some(unsafe { self.chunks[chunk_idx][off].assume_init_ref() })
} }
/// Bytes held by the chunk allocations themselves (not counting anything
/// the elements point to). Every chunk is a full `CHUNK_SIZE` allocation
/// regardless of how many slots are in use, so the tail chunk's unused
/// slots are counted too — they are resident either way.
pub fn allocated_bytes(&self) -> usize {
self.chunks.len() * CHUNK_SIZE * std::mem::size_of::<T>()
}
pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut T> {
let len = self.len;
self.chunks
.iter_mut()
.enumerate()
.flat_map(move |(chunk_index, chunk)| {
let chunk_end = if chunk_index == len / CHUNK_SIZE {
len % CHUNK_SIZE
} else {
CHUNK_SIZE
};
// SAFETY: slots below `len` were initialized by `push`.
chunk[0..chunk_end]
.iter_mut()
.map(|slot| unsafe { slot.assume_init_mut() })
})
}
} }
impl<T> Default for ChunkedVec<T> { impl<T> Default for ChunkedVec<T> {
......
This diff is collapsed.
-- root/raw: page 1/1 of 6 --
id=1 name="turbo_tasks::function module_graph" cpu=9800 corrected=7098 rel=(0..13100) agg=false count=None
args=[("name", "module_graph"), ("extra", "1")]
memory_samples=[(1000, 1000000, 5)]
id=5 name="late late_span" cpu=2000 corrected=2000 rel=(10000..12000) agg=false count=None
args=[("name", "arrived_late")]
id=8 name="deep chain" cpu=1000 corrected=1006 rel=(20000..30000) agg=false count=None
memory_samples=[(0, 4000000, 40)]
id=93 name="json first_parent" cpu=0 corrected=1 rel=(40000..40000) agg=false count=None
id=94 name="json second_parent" cpu=800 corrected=800 rel=(40100..41000) agg=false count=None
id=96 name="json totalled" cpu=10000 corrected=10000 rel=(50000..60000) agg=false count=None
memory_samples=[(0, 2000000, 12)]
-- root/aggregated: page 1/1 of 6 --
id=a96 name="json totalled" cpu=10000 corrected=10000 rel=(50000..60000) agg=false count=Some(1)
memory_samples=[(0, 2000000, 12)]
id=a1 name="turbo_tasks::function module_graph" cpu=9800 corrected=7098 rel=(0..13100) agg=false count=Some(1)
args=[("name", "module_graph"), ("extra", "1")]
memory_samples=[(1000, 1000000, 5)]
id=a5 name="late late_span" cpu=2000 corrected=2000 rel=(10000..12000) agg=false count=Some(1)
args=[("name", "arrived_late")]
id=a8 name="deep chain" cpu=1000 corrected=1006 rel=(20000..30000) agg=false count=Some(1)
memory_samples=[(0, 4000000, 40)]
id=a94 name="json second_parent" cpu=800 corrected=800 rel=(40100..41000) agg=false count=Some(1)
id=a93 name="json first_parent" cpu=0 corrected=1 rel=(40000..40000) agg=false count=Some(1)
-- root/by-name: page 1/1 of 6 --
id=8 name="deep chain" cpu=1000 corrected=1006 rel=(20000..30000) agg=false count=None
memory_samples=[(0, 4000000, 40)]
id=93 name="json first_parent" cpu=0 corrected=1 rel=(40000..40000) agg=false count=None
id=5 name="late late_span" cpu=2000 corrected=2000 rel=(10000..12000) agg=false count=None
args=[("name", "arrived_late")]
id=1 name="turbo_tasks::function module_graph" cpu=9800 corrected=7098 rel=(0..13100) agg=false count=None
args=[("name", "module_graph"), ("extra", "1")]
memory_samples=[(1000, 1000000, 5)]
id=94 name="json second_parent" cpu=800 corrected=800 rel=(40100..41000) agg=false count=None
id=96 name="json totalled" cpu=10000 corrected=10000 rel=(50000..60000) agg=false count=None
memory_samples=[(0, 2000000, 12)]
-- search=link: page 1/5 of 84 --
id=12 name="deep link" cpu=1000 corrected=1006 rel=(20400..30000) agg=false count=None
id=18 name="deep link" cpu=1000 corrected=1006 rel=(21000..30000) agg=false count=None
id=24 name="deep link" cpu=1000 corrected=1006 rel=(21600..30000) agg=false count=None
id=25 name="deep link" cpu=1000 corrected=1006 rel=(21700..30000) agg=false count=None
id=30 name="deep link" cpu=1000 corrected=1006 rel=(22200..30000) agg=false count=None
id=31 name="deep link" cpu=1000 corrected=1006 rel=(22300..30000) agg=false count=None
id=37 name="deep link" cpu=1000 corrected=1006 rel=(22900..30000) agg=false count=None
id=43 name="deep link" cpu=1000 corrected=1006 rel=(23500..30000) agg=false count=None
id=44 name="deep link" cpu=1000 corrected=1006 rel=(23600..30000) agg=false count=None
id=49 name="deep link" cpu=1000 corrected=1006 rel=(24100..30000) agg=false count=None
id=50 name="deep link" cpu=1000 corrected=1006 rel=(24200..30000) agg=false count=None
id=56 name="deep link" cpu=1000 corrected=1006 rel=(24800..30000) agg=false count=None
id=62 name="deep link" cpu=1000 corrected=1006 rel=(25400..30000) agg=false count=None
id=68 name="deep link" cpu=1000 corrected=1006 rel=(26000..30000) agg=false count=None
id=69 name="deep link" cpu=1000 corrected=1006 rel=(26100..30000) agg=false count=None
id=74 name="deep link" cpu=1000 corrected=1006 rel=(26600..30000) agg=false count=None
id=75 name="deep link" cpu=1000 corrected=1006 rel=(26700..30000) agg=false count=None
id=81 name="deep link" cpu=1000 corrected=1006 rel=(27300..30000) agg=false count=None
id=87 name="deep link" cpu=0 corrected=1 rel=(27900..27900) agg=false count=None
id=88 name="deep link" cpu=0 corrected=1 rel=(28000..28000) agg=false count=None
-- child-of-1: page 1/1 of 4 --
id=1-2 name="turbo_tasks::resolve_call *resolve_module" cpu=2700 corrected=1516 rel=(100..4800) agg=false count=None
args=[("name", "resolve_module")]
memory_samples=[(900, 1000000, 5)]
id=1-3 name="parse parse_file index.js" cpu=6000 corrected=5066 rel=(200..9000) agg=false count=None
args=[("name", "index.js")]
memory_samples=[(800, 1000000, 5)]
id=1-4 name="io read_file" cpu=1000 corrected=416 rel=(300..3500) agg=false count=None
memory_samples=[(700, 1000000, 5)]
id=1-6 name="event instant tick" cpu=100 corrected=100 rel=(13000..13100) agg=false count=None
args=[("name", "tick")]
...@@ -33,8 +33,12 @@ impl<T> LazySortedVec<T> { ...@@ -33,8 +33,12 @@ impl<T> LazySortedVec<T> {
self.vec.get_mut().retain(|t| f(t)); self.vec.get_mut().retain(|t| f(t));
} }
pub fn iter_mut_unordered(&mut self) -> std::slice::IterMut<'_, T> { /// Storage accounting for the memory report: `(len, capacity, spilled)`.
self.vec.get_mut().iter_mut() /// Takes `&mut self` so it can read through the `UnsafeCell` without
/// going via the sorting `Deref` and without any unsafe.
pub fn storage_stats(&mut self) -> (usize, usize, bool) {
let vec = self.vec.get_mut();
(vec.len(), vec.capacity(), vec.spilled())
} }
} }
......
...@@ -18,7 +18,10 @@ use self::{ ...@@ -18,7 +18,10 @@ use self::{
mod bottom_up; mod bottom_up;
mod chunked_vec; mod chunked_vec;
#[cfg(test)]
mod golden;
mod lazy_sorted_vec; mod lazy_sorted_vec;
mod memory_report;
mod reader; mod reader;
mod self_time_tree; mod self_time_tree;
mod server; mod server;
......
...@@ -14,6 +14,7 @@ use self::{reader::TraceReader, server::serve, store_container::StoreContainer}; ...@@ -14,6 +14,7 @@ use self::{reader::TraceReader, server::serve, store_container::StoreContainer};
mod bottom_up; mod bottom_up;
mod chunked_vec; mod chunked_vec;
mod lazy_sorted_vec; mod lazy_sorted_vec;
mod memory_report;
mod reader; mod reader;
mod self_time_tree; mod self_time_tree;
mod server; mod server;
......
//! A computed — not sampled — breakdown of where the store's bytes go.
//!
//! Peak RSS is far too noisy to optimize against directly, and the allocator's
//! live-bytes counter tells you the total without saying which structure owns
//! it. This walks the store and adds up the parts, so a change in one of them
//! is attributable to the change that caused it.
//!
//! The numbers here are *live* bytes as the program understands them. The gap
//! between this total and peak RSS is allocator slack and fragmentation, which
//! is itself a useful signal: it is what moving small per-span allocations into
//! arenas is supposed to reclaim.
//!
//! Enable with `MEMORY_REPORT=1`. Walking every span costs a fraction of a
//! second at 13M spans, so it only runs at the end of the initial read.
use std::fmt;
const MB: usize = 1024 * 1024;
#[derive(Default)]
pub struct MemoryReport {
pub spans: usize,
/// `size_of::<Span>()` — the per-span constant the whole plan turns on.
pub span_size: usize,
/// What the `ChunkedVec` chunks actually cost, including the tail chunk's
/// unused slots.
pub span_chunk_bytes: usize,
pub events: usize,
pub event_size: usize,
/// Spans whose events outgrew the single inline `SmallVec` slot.
pub event_spilled_spans: usize,
/// Heap bytes held by those spilled event vectors, at real capacity.
pub event_heap_bytes: usize,
pub args: usize,
pub arg_spilled_spans: usize,
pub arg_heap_bytes: usize,
pub self_time_entries: usize,
pub self_time_bytes: usize,
pub memory_sample_bytes: usize,
/// How much of the lazily-computed half has actually been materialized.
/// Zero across all three during a headless ingest; that gap is what the
/// cold-side work targets.
pub totals_populated: usize,
pub names_populated: usize,
pub extra_populated: usize,
/// `TurboMalloc::memory_usage()` at the same instant, for comparison.
pub allocator_live_bytes: usize,
}
impl MemoryReport {
/// Everything above that is a real allocation (excludes the populated
/// counts, which are counts rather than bytes).
pub fn accounted_bytes(&self) -> usize {
self.span_chunk_bytes
+ self.event_heap_bytes
+ self.arg_heap_bytes
+ self.self_time_bytes
+ self.memory_sample_bytes
}
}
/// `1234 MB` with the value right-aligned so the column scans vertically.
struct Mb(usize);
impl fmt::Display for Mb {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:>7} MB", self.0 / MB)
}
}
impl fmt::Display for MemoryReport {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let spans = self.spans.max(1);
// Bytes per span is the figure that stays comparable across STOP_AT
// truncation points, so every row carries it.
let per_span = |bytes: usize| bytes as f64 / spans as f64;
writeln!(f, "memory report — {} spans", self.spans)?;
writeln!(
f,
" {:<22} {} {:>8.1} B/span size_of::<Span>() = {}",
"span chunks",
Mb(self.span_chunk_bytes),
per_span(self.span_chunk_bytes),
self.span_size,
)?;
writeln!(
f,
" {:<22} {} {:>8.1} B/span {} events, {} spans spilled, size_of::<SpanEvent>() = {}",
"events (heap)",
Mb(self.event_heap_bytes),
per_span(self.event_heap_bytes),
self.events,
self.event_spilled_spans,
self.event_size,
)?;
writeln!(
f,
" {:<22} {} {:>8.1} B/span {} args, {} spans spilled",
"args (heap)",
Mb(self.arg_heap_bytes),
per_span(self.arg_heap_bytes),
self.args,
self.arg_spilled_spans,
)?;
writeln!(
f,
" {:<22} {} {:>8.1} B/span {} entries",
"self time tree",
Mb(self.self_time_bytes),
per_span(self.self_time_bytes),
self.self_time_entries,
)?;
writeln!(
f,
" {:<22} {} {:>8.1} B/span",
"memory samples",
Mb(self.memory_sample_bytes),
per_span(self.memory_sample_bytes),
)?;
writeln!(
f,
" {:<22} {} {:>8.1} B/span",
"accounted",
Mb(self.accounted_bytes()),
per_span(self.accounted_bytes()),
)?;
writeln!(
f,
" {:<22} {} {:>8.1} B/span unaccounted (interner, reader buffers, id_mapping, \
allocator slack) = {}",
"allocator live",
Mb(self.allocator_live_bytes),
per_span(self.allocator_live_bytes),
Mb(self
.allocator_live_bytes
.saturating_sub(self.accounted_bytes())),
)?;
write!(
f,
" lazily computed: totals {}/{}, names {}/{}, extra {}/{}",
self.totals_populated,
self.spans,
self.names_populated,
self.spans,
self.extra_populated,
self.spans,
)
}
}
...@@ -15,6 +15,7 @@ use std::{ ...@@ -15,6 +15,7 @@ use std::{
use anyhow::Result; use anyhow::Result;
use flate2::bufread::GzDecoder; use flate2::bufread::GzDecoder;
use turbo_tasks_malloc::TurboMalloc;
use crate::{ use crate::{
reader::{heaptrack::HeaptrackFormat, nextjs::NextJsFormat, turbopack::TurbopackFormat}, reader::{heaptrack::HeaptrackFormat, nextjs::NextJsFormat, turbopack::TurbopackFormat},
...@@ -291,6 +292,12 @@ impl TraceReader { ...@@ -291,6 +292,12 @@ impl TraceReader {
if !stats.is_empty() { if !stats.is_empty() {
line += &format!(" - {stats}"); line += &format!(" - {stats}");
} }
// Live allocated bytes. Whole-process RSS is far too
// noisy to optimize against, so surface the allocator's
// own counter instead. It lags by up to ~100 KB per
// thread, which is irrelevant at these magnitudes.
let heap_mb = TurboMalloc::memory_usage() / (1024 * 1024);
line += &format!(" - {heap_mb} MB heap");
// `\r` returns to the start of the line and `\x1b[2K` erases // `\r` returns to the start of the line and `\x1b[2K` erases
// it, so a shorter update doesn't leave behind characters from // it, so a shorter update doesn't leave behind characters from
...@@ -303,6 +310,12 @@ impl TraceReader { ...@@ -303,6 +310,12 @@ impl TraceReader {
"Stopped reading file as requested by STOP_AT env var. \ "Stopped reading file as requested by STOP_AT env var. \
Waiting for new file..." Waiting for new file..."
); );
// STOP_AT exits here rather than through
// `wait_for_more_data`, so the report has to be
// emitted on this path too — it is the path
// every measurement run takes.
self.store.write().optimize();
self.print_memory_report();
self.wait_for_new_file(&mut file); self.wait_for_new_file(&mut file);
return true; return true;
} }
...@@ -331,6 +344,15 @@ impl TraceReader { ...@@ -331,6 +344,15 @@ impl TraceReader {
} }
} }
/// Print the store's byte breakdown when `MEMORY_REPORT=1`. Takes the
/// write lock and walks every span, so it is gated behind the env var
/// rather than being always-on.
fn print_memory_report(&self) {
if env::var("MEMORY_REPORT").is_ok() {
println!("{}", self.store.write().memory_report());
}
}
fn wait_for_more_data( fn wait_for_more_data(
&mut self, &mut self,
file: &mut TraceFile, file: &mut TraceFile,
...@@ -358,6 +380,7 @@ impl TraceReader { ...@@ -358,6 +380,7 @@ impl TraceReader {
} else if !stats.is_empty() { } else if !stats.is_empty() {
println!("{stats}"); println!("{stats}");
} }
self.print_memory_report();
} }
loop { loop {
// No more data to read, sleep for a while to wait for more data // No more data to read, sleep for a while to wait for more data
......
...@@ -47,6 +47,19 @@ impl<T> SelfTimeTree<T> { ...@@ -47,6 +47,19 @@ impl<T> SelfTimeTree<T> {
self.count self.count
} }
/// Bytes held by this node and every descendant: the `entries` buffers at
/// their real capacity, plus one `SelfTimeChildren` box per interior node.
/// Used by the memory report; walks the whole tree, so call it once.
pub fn allocated_bytes(&self) -> usize {
let mut bytes = self.entries.capacity() * std::mem::size_of::<SelfTimeEntry<T>>();
if let Some(children) = &self.children {
bytes += std::mem::size_of::<SelfTimeChildren<T>>();
bytes += children.left.allocated_bytes();
bytes += children.right.allocated_bytes();
}
bytes
}
pub fn insert(&mut self, start: Timestamp, end: Timestamp, item: T) { pub fn insert(&mut self, start: Timestamp, end: Timestamp, item: T) {
self.count += 1; self.count += 1;
self.entries.push(SelfTimeEntry { start, end, item }); self.entries.push(SelfTimeEntry { start, end, item });
......
...@@ -2,6 +2,7 @@ use std::{ ...@@ -2,6 +2,7 @@ use std::{
cmp::max, cmp::max,
collections::VecDeque, collections::VecDeque,
fmt::{Debug, Formatter}, fmt::{Debug, Formatter},
num::NonZeroU64,
vec, vec,
}; };
...@@ -14,8 +15,8 @@ use crate::{ ...@@ -14,8 +15,8 @@ use crate::{
FxIndexMap, FxIndexMap,
bottom_up::build_bottom_up_graph, bottom_up::build_bottom_up_graph,
span::{ span::{
Span, SpanEvent, SpanEventSelfTime, SpanExtra, SpanGraphEvent, SpanIndex, SpanName, Span, SpanEvent, SpanEventKind, SpanExtra, SpanGraphEvent, SpanIndex, SpanName, SpanNames,
SpanNames, SpanTimeData, SpanTotals, SpanTimeData, SpanTotals,
}, },
span_bottom_up_ref::SpanBottomUpRef, span_bottom_up_ref::SpanBottomUpRef,
span_graph_ref::{SpanGraphEventRef, SpanGraphRef, event_map_to_list}, span_graph_ref::{SpanGraphEventRef, SpanGraphRef, event_map_to_list},
...@@ -133,14 +134,15 @@ impl<'a> SpanRef<'a> { ...@@ -133,14 +134,15 @@ impl<'a> SpanRef<'a> {
self.span self.span
.events .events
.iter() .iter()
.map(|event: &'a SpanEvent| match event { .map(|event: &'a SpanEvent| match event.kind() {
SpanEvent::SelfTime(self_time) => SpanEventRef::SelfTime { SpanEventKind::SelfTime { duration } => SpanEventRef::SelfTime {
self_time: SpanEventSelfTimeRef { self_time: SpanEventSelfTimeRef {
store: self.store, store: self.store,
self_time, start: event.start(),
duration,
}, },
}, },
SpanEvent::Child { index, .. } => SpanEventRef::Child { SpanEventKind::Child { index } => SpanEventRef::Child {
span: SpanRef { span: SpanRef {
span: &self.store.spans[index.get()], span: &self.store.spans[index.get()],
store: self.store, store: self.store,
...@@ -152,25 +154,25 @@ impl<'a> SpanRef<'a> { ...@@ -152,25 +154,25 @@ impl<'a> SpanRef<'a> {
/// Children sorted by start time, excluding self time. /// Children sorted by start time, excluding self time.
pub fn children(&self) -> impl DoubleEndedIterator<Item = SpanRef<'a>> + 'a + use<'a> { pub fn children(&self) -> impl DoubleEndedIterator<Item = SpanRef<'a>> + 'a + use<'a> {
self.span.events.iter().filter_map(|event| match event { self.span.events.iter().filter_map(|event| {
SpanEvent::SelfTime { .. } => None, let index = event.child_index()?;
SpanEvent::Child { index, .. } => Some(SpanRef { Some(SpanRef {
span: &self.store.spans[index.get()], span: &self.store.spans[index.get()],
store: self.store, store: self.store,
index: index.get(), index: index.get(),
}), })
}) })
} }
/// Children sorted by start time, excluding self time, in parallel. /// Children sorted by start time, excluding self time, in parallel.
pub fn children_par(&self) -> impl ParallelIterator<Item = SpanRef<'a>> + 'a { pub fn children_par(&self) -> impl ParallelIterator<Item = SpanRef<'a>> + 'a {
self.span.events.par_iter().filter_map(|event| match event { self.span.events.par_iter().filter_map(|event| {
SpanEvent::SelfTime { .. } => None, let index = event.child_index()?;
SpanEvent::Child { index, .. } => Some(SpanRef { Some(SpanRef {
span: &self.store.spans[index.get()], span: &self.store.spans[index.get()],
store: self.store, store: self.store,
index: index.get(), index: index.get(),
}), })
}) })
} }
...@@ -240,12 +242,15 @@ impl<'a> SpanRef<'a> { ...@@ -240,12 +242,15 @@ impl<'a> SpanRef<'a> {
.events .events
.par_iter() .par_iter()
.filter_map(|event: &'a SpanEvent| { .filter_map(|event: &'a SpanEvent| {
if let SpanEvent::SelfTime(self_time) = event { let duration = event.self_time_duration()?;
return Some( Some(
SpanEventSelfTimeRef { store, self_time }.corrected_self_time(), SpanEventSelfTimeRef {
); store,
} start: event.start(),
None duration,
}
.corrected_self_time(),
)
}) })
.sum(); .sum();
if self.children().next().is_none() { if self.children().next().is_none() {
...@@ -501,30 +506,43 @@ impl Debug for SpanRef<'_> { ...@@ -501,30 +506,43 @@ impl Debug for SpanRef<'_> {
} }
} }
/// Carries the self-time values by copy rather than borrowing an event, because
/// [`SpanEvent`] is packed and has no separate self-time struct to point at.
pub struct SpanEventSelfTimeRef<'a> { pub struct SpanEventSelfTimeRef<'a> {
store: &'a Store, store: &'a Store,
self_time: &'a SpanEventSelfTime, start: Timestamp,
duration: NonZeroU64,
} }
impl<'a> SpanEventSelfTimeRef<'a> { impl<'a> SpanEventSelfTimeRef<'a> {
pub fn start(&self) -> Timestamp { pub fn start(&self) -> Timestamp {
self.self_time.start self.start
} }
pub fn end(&self) -> Timestamp { pub fn end(&self) -> Timestamp {
self.self_time.end() Timestamp::from_value(*self.start + self.duration.get())
} }
/// Recomputed on every call rather than cached on the event.
///
/// A per-event cache cost 16 bytes on every event in the trace — more total
/// memory than the span array itself at typical event-per-span ratios — to
/// avoid an interval-tree lookup. The lookup is cheap, and the caller that
/// matters ([`SpanRef::corrected_self_time`]) caches the sum across a span's
/// events, so each event is normally visited once per span-cache fill.
///
/// The one caller that does repeat is the viewer's per-event value in
/// `Duration` mode, and that is bounded by the events inside the current
/// view rect. If that ever shows up in a profile, memoize per request there
/// rather than putting the field back on the event.
pub fn corrected_self_time(&self) -> Timestamp { pub fn corrected_self_time(&self) -> Timestamp {
*self.self_time.corrected_self_time.get_or_init(|| { // `duration` is `NonZeroU64`, so zero-duration events are filtered
// `duration` is `NonZeroU64`, so zero-duration events are filtered // at construction time (see `SpanEvent::self_time`).
// at construction time (see `SpanEvent::self_time`). let end = self.end();
let end = self.self_time.end(); let duration = Timestamp::from_value(self.duration.get());
let duration = Timestamp::from_value(self.self_time.duration.get()); self.store.set_max_self_time_lookup(end);
self.store.set_max_self_time_lookup(end); self.store.self_time_tree.as_ref().map_or(duration, |tree| {
self.store.self_time_tree.as_ref().map_or(duration, |tree| { tree.lookup_range_corrected_time(self.start, end)
tree.lookup_range_corrected_time(self.self_time.start, end)
})
}) })
} }
} }
......
...@@ -7,9 +7,11 @@ use std::{ ...@@ -7,9 +7,11 @@ use std::{
use rustc_hash::FxHashSet; use rustc_hash::FxHashSet;
use turbo_rcstr::{RcStr, rcstr}; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks_malloc::TurboMalloc;
use crate::{ use crate::{
chunked_vec::ChunkedVec, chunked_vec::ChunkedVec,
memory_report::MemoryReport,
self_time_tree::SelfTimeTree, self_time_tree::SelfTimeTree,
span::{Span, SpanArgs, SpanEvent, SpanIndex, SpanTimeData}, span::{Span, SpanArgs, SpanEvent, SpanIndex, SpanTimeData},
span_ref::SpanRef, span_ref::SpanRef,
...@@ -90,6 +92,50 @@ impl Store { ...@@ -90,6 +92,50 @@ impl Store {
self.memory_samples.clear(); self.memory_samples.clear();
} }
/// Walk the store and add up where its bytes actually went. See
/// [`crate::memory_report`]. Takes `&mut self` so the per-span `SmallVec`
/// capacities can be read without going through `LazySortedVec`'s sorting
/// `Deref` (which would also mutate) and without unsafe.
pub fn memory_report(&mut self) -> MemoryReport {
let mut report = MemoryReport {
spans: self.spans.len(),
span_size: std::mem::size_of::<Span>(),
span_chunk_bytes: self.spans.allocated_bytes(),
event_size: std::mem::size_of::<SpanEvent>(),
self_time_entries: self.self_time_tree.as_ref().map_or(0, |t| t.len()),
self_time_bytes: self
.self_time_tree
.as_ref()
.map_or(0, |t| t.allocated_bytes()),
memory_sample_bytes: self.memory_samples.capacity()
* std::mem::size_of::<MemorySample>(),
allocator_live_bytes: TurboMalloc::memory_usage(),
..Default::default()
};
for span in self.spans.iter_mut() {
report.totals_populated += span.totals.get().is_some() as usize;
report.names_populated += span.names.get().is_some() as usize;
report.extra_populated += span.extra.get().is_some() as usize;
report.args += span.args.len();
if span.args.spilled() {
report.arg_spilled_spans += 1;
report.arg_heap_bytes +=
span.args.capacity() * std::mem::size_of::<(RcStr, RcStr)>();
}
let (len, capacity, spilled) = span.events.storage_stats();
report.events += len;
if spilled {
report.event_spilled_spans += 1;
report.event_heap_bytes += capacity * std::mem::size_of::<SpanEvent>();
}
}
report
}
pub fn optimize(&mut self) { pub fn optimize(&mut self) {
if let Some(tree) = self.self_time_tree.as_mut() { if let Some(tree) = self.self_time_tree.as_mut() {
tree.optimize(); tree.optimize();
...@@ -151,7 +197,7 @@ impl Store { ...@@ -151,7 +197,7 @@ impl Store {
depth = CUT_OFF_DEPTH - 1; depth = CUT_OFF_DEPTH - 1;
} }
if depth < CUT_OFF_DEPTH { if depth < CUT_OFF_DEPTH {
parent.events.push(SpanEvent::Child { start, index: id }); parent.events.push(SpanEvent::child(start, id));
} }
parent.start = min(parent.start, start); parent.start = min(parent.start, start);
let span = &mut self.spans[id.get()]; let span = &mut self.spans[id.get()];
...@@ -264,7 +310,7 @@ impl Store { ...@@ -264,7 +310,7 @@ impl Store {
self_time += start - current; self_time += start - current;
} }
} }
events.push(SpanEvent::Child { start, index }); events.push(SpanEvent::child(start, index));
current = max(current, end); current = max(current, end);
} }
current -= start_time; current -= start_time;
...@@ -303,16 +349,13 @@ impl Store { ...@@ -303,16 +349,13 @@ impl Store {
} else { } else {
&mut self.spans[0] &mut self.spans[0]
}; };
old_parent.events.retain_unordered( old_parent
|event: &SpanEvent| !matches!(event, SpanEvent::Child { index, .. } if *index == span_index), .events
); .retain_unordered(|event: &SpanEvent| event.child_index() != Some(span_index));
outdated_spans.insert(parent); outdated_spans.insert(parent);
let parent = &mut self.spans[parent.get()]; let parent = &mut self.spans[parent.get()];
parent.events.push(SpanEvent::Child { parent.events.push(SpanEvent::child(span_start, span_index));
start: span_start,
index: span_index,
});
} }
pub fn add_allocation( pub fn add_allocation(
...@@ -437,11 +480,10 @@ impl Store { ...@@ -437,11 +480,10 @@ impl Store {
span.time_data.total_time.take(); span.time_data.total_time.take();
span.time_data.corrected_self_time.take(); span.time_data.corrected_self_time.take();
span.time_data.corrected_total_time.take(); span.time_data.corrected_total_time.take();
for event in span.events.iter_mut_unordered() { // Events hold no cache of their own, so there is nothing to clear
if let SpanEvent::SelfTime(self_time) = event { // here. That matters for more than tidiness: this function runs on
self_time.corrected_self_time.take(); // every ancestor of every touched span after each read batch, and it
} // used to walk each of their event lists.
}
span.totals.take(); span.totals.take();
span.extra.take(); span.extra.take();
} }
...@@ -464,13 +506,13 @@ impl Store { ...@@ -464,13 +506,13 @@ impl Store {
} }
pub fn root_spans(&self) -> impl Iterator<Item = SpanRef<'_>> { pub fn root_spans(&self) -> impl Iterator<Item = SpanRef<'_>> {
self.spans[0].events.iter().filter_map(|event| match event { self.spans[0].events.iter().filter_map(|event| {
&SpanEvent::Child { index: id, .. } => Some(SpanRef { let id = event.child_index()?;
Some(SpanRef {
span: &self.spans[id.get()], span: &self.spans[id.get()],
store: self, store: self,
index: id.get(), index: id.get(),
}), })
_ => None,
}) })
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment