Unverified Commit 28f497f7 authored by vercel-fleet-prod[bot]'s avatar vercel-fleet-prod[bot] Committed by GitHub

Source Timeline layout from self-time tree

Co-authored-by: 's avatarNiklas Mischkulnig <4586894+mischnic@users.noreply.github.com>
parent c9eadd80
......@@ -142,3 +142,77 @@ struct NextJsSpan<'a> {
// Emitted by Next.js trace
// trace_id: Cow<'a, str>,
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{server::ViewRect, viewer::Viewer};
#[test]
fn timeline_uses_parent_self_time_gaps_and_live_json_updates() {
let store = Arc::new(StoreContainer::new());
let mut format = NextJsFormat::new(store.clone());
// The parent arrives after its children, as in completed JSON spans.
let data = b"[{\"name\":\"child-a\",\"timestamp\":120,\"duration\":20,\"id\":2,\"parentId\":1,\"tags\":{}},{\"name\":\"child-b\",\"timestamp\":160,\"duration\":20,\"id\":3,\"parentId\":1,\"tags\":{}},{\"name\":\"parent\",\"timestamp\":100,\"duration\":100,\"id\":1,\"tags\":{}}]\n";
assert_eq!(format.read(data, &mut ()).unwrap(), data.len());
let rect = ViewRect {
x: 0,
y: 0,
width: 20000,
height: 100,
horizontal_pixels: 20000,
query: String::new(),
view_mode: "timeline".into(),
value_mode: "duration".into(),
value_filter: None,
count_filter: None,
};
let mut viewer = Viewer::new();
let update = viewer.compute_update(&store.read(), &rect);
assert_eq!(update.count, 1); // children replace parent CPU time, not overlap it
assert_eq!(update.max, 10000);
let lines = serde_json::to_value(&update.lines).unwrap();
let spans = lines[0]["spans"].as_array().unwrap();
let mut segments: Vec<_> = spans
.iter()
.map(|s| {
(
s["t"].as_str().unwrap(),
s["x"].as_u64().unwrap(),
s["w"].as_u64().unwrap(),
)
})
.collect();
segments.sort_unstable();
assert_eq!(
segments,
[
("child-a", 2000, 2000),
("child-b", 6000, 2000),
("parent", 0, 2000),
("parent", 4000, 2000),
("parent", 8000, 2000),
]
);
let parent_ids: Vec<_> = spans
.iter()
.filter(|s| s["t"] == "parent")
.map(|s| &s["id"])
.collect();
assert_eq!(parent_ids.len(), 3);
assert!(parent_ids.iter().all(|id| *id == parent_ids[0]));
let next =
b"[{\"name\":\"later\",\"timestamp\":220,\"duration\":10,\"id\":4,\"tags\":{}}]\n";
// An unfinished JSON record cannot alter the tree.
assert_eq!(format.read(&next[..next.len() - 1], &mut ()).unwrap(), 0);
assert_eq!(format.read(next, &mut ()).unwrap(), next.len());
viewer.invalidate_timeline();
let update = viewer.compute_update(&store.read(), &rect);
assert_eq!(update.max, 13000);
let lines = serde_json::to_value(&update.lines).unwrap();
assert_eq!(
lines[0]["spans"].as_array().unwrap().last().unwrap()["x"],
12000
);
}
}
......@@ -30,9 +30,7 @@ enum InternalRowType {
target: RcStr,
values: SpanArgs,
},
End {
ts: Timestamp,
},
End,
SelfTime {
start: Timestamp,
end: Timestamp,
......@@ -143,14 +141,12 @@ impl TurbopackFormat {
},
);
}
TraceRow::End { ts, id } => {
TraceRow::End { ts: _, id } => {
self.process_internal_row(
store,
InternalRow {
id: Some(id),
ty: InternalRowType::End {
ts: Timestamp::from_micros(ts),
},
ty: InternalRowType::End,
},
);
}
......@@ -310,7 +306,7 @@ impl TurbopackFormat {
let id = if let Some(id) = row.id {
if matches!(
row.ty,
InternalRowType::End { .. }
InternalRowType::End
| InternalRowType::Event { .. }
| InternalRowType::Record { .. }
| InternalRowType::SelfTime { .. }
......@@ -364,8 +360,7 @@ impl TurbopackFormat {
InternalRowType::Record { values } => {
store.add_args(id.unwrap(), values, &mut self.outdated_spans);
}
InternalRowType::End { ts } => {
store.set_span_end(id.unwrap(), ts);
InternalRowType::End => {
store.complete_span(id.unwrap());
}
InternalRowType::SelfTime { start, end } => {
......@@ -387,7 +382,6 @@ impl TurbopackFormat {
&mut self.outdated_spans,
);
store.add_self_time(id, start, ts, &mut self.outdated_spans);
store.set_span_end(id, ts);
store.complete_span(id);
}
InternalRowType::Allocation {
......@@ -566,22 +560,34 @@ mod tests {
}
#[test]
fn lifecycle_end_preserves_idle_tail_after_cpu_exit() {
fn timeline_uses_binary_activations_not_lifecycles_and_accepts_live_slices() {
use crate::{server::ViewRect, viewer::Viewer};
let enter = |ts, id, thread_id| TraceRow::Enter {
ts,
id,
thread_id,
allocations: None,
};
let exit = |ts, id, thread_id| TraceRow::Exit {
ts,
id,
thread_id,
allocations: None,
};
let rows = [
start(1, None, "async"),
TraceRow::Enter {
ts: 1,
id: 1,
thread_id: 1,
allocations: None,
},
TraceRow::Exit {
ts: 2,
id: 1,
thread_id: 1,
allocations: None,
},
TraceRow::End { ts: 5, id: 1 },
start(2, Some(1), "child"),
start(3, None, "blocking"),
start(4, None, "inactive"),
enter(10, 1, 1),
enter(12, 1, 2),
exit(18, 1, 2),
enter(20, 2, 1),
exit(30, 2, 1),
exit(40, 1, 1),
enter(50, 3, 4),
exit(60, 3, 4),
enter(70, 1, 3),
];
let data: Vec<_> = rows
.iter()
......@@ -590,13 +596,78 @@ mod tests {
let store = Arc::new(StoreContainer::new());
let mut format = TurbopackFormat::new(store.clone());
let mut reuse = TurbopackFormat::create_reused();
TraceFormat::read(&mut format, &data, &mut reuse).unwrap();
let store = store.read();
let span = store.root_spans().next().unwrap();
assert_eq!(*span.actual_start(), 0);
assert_eq!(*span.actual_end(), 500);
assert_eq!(*span.end(), 200); // existing flame extent is unchanged
assert_eq!(*span.total_time(), 100); // CPU time still excludes idle waiting
assert_eq!(format.read(&data, &mut reuse).unwrap(), data.len());
let rect = ViewRect {
x: 0,
y: 0,
width: 10000,
height: 100,
horizontal_pixels: 10000,
query: String::new(),
view_mode: "timeline".into(),
value_mode: "duration".into(),
value_filter: None,
count_filter: None,
};
let mut viewer = Viewer::new();
let initial = viewer.compute_update(&store.read(), &rect);
assert_eq!(initial.max, 4000); // only completed active slices, not the open span
assert_eq!(initial.count, 2); // same owning span executes on two threads
let tail: Vec<_> = [
exit(80, 1, 3),
TraceRow::End { ts: 1000, id: 1 },
TraceRow::End { ts: 2000, id: 4 },
]
.iter()
.flat_map(|row| postcard::to_stdvec(row).unwrap())
.collect();
// A partial encoded row must be left for the next read, not create a bar.
assert_eq!(format.read(&tail[..1], &mut reuse).unwrap(), 0);
assert_eq!(format.read(&tail, &mut reuse).unwrap(), tail.len());
viewer.invalidate_timeline();
let update = viewer.compute_update(&store.read(), &rect);
assert_eq!(update.max, 8000); // lifecycle end and waiting do not extend work
let lines = serde_json::to_value(&update.lines).unwrap();
let spans: Vec<_> = lines
.as_array()
.unwrap()
.iter()
.flat_map(|line| line["spans"].as_array().unwrap())
.collect();
let mut segments: Vec<_> = spans
.iter()
.map(|s| {
(
s["t"].as_str().unwrap(),
s["x"].as_u64().unwrap(),
s["w"].as_u64().unwrap(),
)
})
.collect();
segments.sort_unstable();
assert_eq!(
segments,
[
("async", 1000, 1000),
("async", 1200, 600),
("async", 3000, 1000),
("async", 7000, 1000),
("child", 2000, 1000),
]
);
let ids: Vec<_> = spans
.iter()
.filter(|s| s["t"] == "async")
.map(|s| &s["id"])
.collect();
assert_eq!(ids.len(), 4);
assert!(ids.iter().all(|id| *id == ids[0]));
for line in lines.as_array().unwrap() {
assert!(line["spans"].as_array().unwrap().windows(2).all(|pair| {
pair[0]["x"].as_u64().unwrap() + pair[0]["w"].as_u64().unwrap()
<= pair[1]["x"].as_u64().unwrap()
}));
}
}
#[test]
......
......@@ -288,14 +288,8 @@ fn handle_connection(
let store = state.store.read();
if let Some((span, is_graph)) = store.span(id) {
let root_start = store.root_span().start();
let (query_start, query_end) =
if state.view_rect.view_mode == "timeline" && !is_graph {
(span.actual_start(), span.actual_end())
} else {
(span.start(), span.end())
};
let span_start = query_start.saturating_sub(root_start);
let span_end = query_end.saturating_sub(root_start);
let span_start = span.start() - root_start;
let span_end = span.end() - root_start;
let duration = span.corrected_total_time();
let cpu = span.total_time();
let allocations = span.total_allocations();
......@@ -314,16 +308,16 @@ fn handle_connection(
}
path.reverse();
let memory_samples =
store.memory_samples_for_range(query_start, query_end);
let memory_pressure_samples =
store.memory_pressure_samples_for_range(query_start, query_end);
store.memory_samples_for_range(span.start(), span.end());
let memory_pressure_samples = store
.memory_pressure_samples_for_range(span.start(), span.end());
let active_worker_threads_samples = store
.active_worker_threads_samples_for_range(
query_start,
query_end,
span.start(),
span.end(),
);
let concurrency_samples =
store.concurrency_samples_for_range(query_start, query_end);
store.concurrency_samples_for_range(span.start(), span.end());
ServerToClientMessage::QueryResult {
id,
is_graph,
......
......@@ -23,10 +23,7 @@ pub struct Span {
// These values won't change after creation:
pub parent: Option<SpanIndex>,
pub depth: u32,
/// Expanded subtree start used by flame views.
pub start: Timestamp,
/// Original lifecycle start; children must not move it earlier.
pub recorded_start: Timestamp,
pub category: RcStr,
pub name: RcStr,
pub args: SpanArgs,
......@@ -76,8 +73,6 @@ pub struct SpanTimeData {
// This might change during writing:
pub self_end: Timestamp,
/// Explicit lifecycle end, independent of the last CPU exit or child extent.
pub recorded_end: Option<Timestamp>,
// These values are computed automatically:
pub self_time: Timestamp,
......
......@@ -54,17 +54,6 @@ impl<'a> SpanRef<'a> {
self.span.start
}
pub fn actual_start(&self) -> Timestamp {
self.span.recorded_start
}
pub fn actual_end(&self) -> Timestamp {
self.time_data().recorded_end.unwrap_or_else(|| {
// Without a completion record, show the elapsed extent observed so far.
max(self.actual_start(), self.end())
})
}
pub fn time_data(&self) -> &'a SpanTimeData {
&self.span.time_data
}
......
......@@ -47,7 +47,6 @@ fn new_root_span() -> Span {
parent: None,
depth: 0,
start: Timestamp::MAX,
recorded_start: Timestamp::MAX,
category: RcStr::default(),
name: rcstr!("(root)"),
args: SpanArgs::new(),
......@@ -123,7 +122,6 @@ impl Store {
parent,
depth: 0,
start,
recorded_start: start,
category,
name,
args,
......@@ -243,8 +241,6 @@ impl Store {
total_time: Timestamp,
outdated_spans: &mut FxHashSet<SpanIndex>,
) {
self.spans[span_index.get()].recorded_start = start_time;
self.spans[span_index.get()].time_data.recorded_end = Some(start_time + total_time);
if self.spans[span_index.get()].time_data.ignore_self_time {
let span = &mut self.spans[span_index.get()];
span.start = start_time;
......@@ -475,10 +471,6 @@ impl Store {
&self.memory_samples[lo..hi]
}
pub fn set_span_end(&mut self, span_index: SpanIndex, end: Timestamp) {
self.spans[span_index.get()].time_data.recorded_end = Some(end);
}
pub fn complete_span(&mut self, span_index: SpanIndex) {
let span = &mut self.spans[span_index.get()];
span.is_complete = true;
......
//! Chronological, flat interval lanes. Unlike flame layouts, neither search nor the
//! viewport changes lane assignment or turns elapsed time into a sum of work.
//! Chronological, flat lanes of active execution from the self-time tree. A span
//! may have several disjoint intervals; waiting and child execution leave gaps.
//! Neither search nor the viewport changes lane assignment or scales time.
use std::{cmp::Reverse, collections::BinaryHeap};
use rustc_hash::FxHashSet;
use super::{Update, ViewLineUpdate, ViewSpan};
use crate::{
server::ViewRect,
store::{SpanId, Store},
timestamp::Timestamp,
viewer::{Update, ViewLineUpdate, ViewSpan},
};
#[derive(Clone, Copy, Debug)]
......@@ -25,20 +27,23 @@ pub(super) struct Timeline {
impl Timeline {
pub(super) fn new(store: &Store) -> Self {
let origin = store.root_span().start();
let intervals = (1..store.spans.len())
.filter_map(|index| {
let id = SpanId::new(index << 1)?;
let (span, _) = store.span(id)?;
let start = *span.actual_start().saturating_sub(origin);
let end = *span.actual_end().saturating_sub(origin);
// A zero-duration event is a one-tick marker, not an invalid interval.
Some(Interval {
id,
start,
end: end.max(start.saturating_add(1)),
})
})
.collect();
let mut intervals = Vec::new();
if let Some(tree) = &store.self_time_tree {
tree.for_each_in_range(Timestamp::ZERO, Timestamp::MAX, &mut |start, end, index| {
if end <= start {
return;
}
// Each tree entry is one activation, not the owning span's extent.
// In particular, do not join separate activations across idle gaps.
if let Some(id) = SpanId::new(index.get() << 1) {
intervals.push(Interval {
id,
start: *start.saturating_sub(origin),
end: *end.saturating_sub(origin),
});
}
});
}
Self::from_intervals(intervals)
}
......@@ -117,7 +122,7 @@ impl Timeline {
previous.id = 0;
previous.width = interval.end - previous.start;
previous.count += 1;
previous.text = "Spans (zoom in)".to_string();
previous.text = "Self-time intervals (zoom in)".to_string();
previous.category.clear();
previous.secondary = 0;
previous.kind = if matched || previous.kind == 0 || previous.kind == 1 {
......@@ -137,7 +142,8 @@ impl Timeline {
kind: if matched { 0 } else { 10 },
start_in_parent: 0,
end_in_parent: 0,
secondary: *span.total_time(),
// Width is this activation's time; span totals belong in details.
secondary: 0,
});
last_bucket = tiny.then_some(bucket);
}
......@@ -187,9 +193,9 @@ mod tests {
let spans = vec![
interval(1, 0, 100),
interval(2, 10, 30),
interval(3, 10, 20),
interval(1, 10, 20), // the same span can execute concurrently
interval(4, 30, 50),
interval(5, 110, 120),
interval(1, 110, 120), // and resume after a waiting gap
interval(6, 110, 130),
];
let layout = Timeline::from_intervals(spans.clone());
......@@ -205,7 +211,11 @@ mod tests {
layout
.lanes
.iter()
.map(|lane| lane.iter().map(|span| span.id).collect::<Vec<_>>())
.map(|lane| {
lane.iter()
.map(|span| (span.id, span.start, span.end))
.collect::<Vec<_>>()
})
.collect::<Vec<_>>()
};
assert_eq!(ids(&layout), ids(&other));
......@@ -247,7 +257,7 @@ mod tests {
add(&mut store, 400, 0);
let layout = Timeline::new(&store);
let full = layout.compute_update(&store, &rect());
assert_eq!(full.max, 301);
assert_eq!(full.max, 250); // the zero-duration span contributes no work
assert_eq!(full.count, 2);
assert_eq!(full.lines[0].spans[0].start, 0);
assert_eq!(full.lines[1].spans[0].start, 50);
......@@ -270,7 +280,7 @@ mod tests {
}
#[test]
fn children_outliving_a_parent_do_not_extend_its_recorded_interval() {
fn children_outliving_a_parent_keep_their_own_self_time() {
let mut store = Store::new();
let mut outdated = FxHashSet::default();
let parent = store.add_span(
......@@ -337,6 +347,99 @@ mod tests {
assert_eq!(update.lines[1].spans[0].start, 50);
}
#[test]
fn tree_entries_not_span_extents_are_the_geometry_source() {
let mut store = Store::new();
let mut outdated = FxHashSet::default();
let owner = store.add_span(
None,
Timestamp::from_value(100),
rcstr!("test"),
rcstr!("resumed"),
SpanArgs::new(),
&mut outdated,
);
let tree = store.self_time_tree.as_mut().unwrap();
// Deliberately keep these out of the span's events/extent: the tree alone
// must determine the bars, including repeated and simultaneous owners.
for (start, end) in [(110, 120), (115, 118), (150, 160), (170, 170)] {
tree.insert(
Timestamp::from_value(start),
Timestamp::from_value(end),
owner,
);
}
let layout = Timeline::new(&store);
assert_eq!(layout.max, 60);
assert_eq!(layout.lanes.len(), 2);
assert_eq!(
layout.lanes[0]
.iter()
.map(|i| (i.start, i.end))
.collect::<Vec<_>>(),
[(10, 20), (50, 60)]
);
assert_eq!((layout.lanes[1][0].start, layout.lanes[1][0].end), (15, 18));
assert!(
layout
.lanes
.iter()
.flatten()
.all(|i| i.id.get() == owner.get() * 2)
);
let update = layout.compute_update(&store, &rect());
assert!(
update
.lines
.iter()
.flat_map(|line| &line.spans)
.all(|span| span.secondary == 0)
);
}
#[test]
fn missing_tree_and_lifecycle_only_spans_do_not_fabricate_work() {
let mut store = Store::new();
add(&mut store, 100, 500);
store.self_time_tree = None;
let layout = Timeline::new(&store);
assert_eq!(layout.max, 1);
assert!(layout.lanes.is_empty());
store.self_time_tree = Some(Default::default());
assert!(Timeline::new(&store).lanes.is_empty());
}
#[test]
fn appended_activation_invalidates_the_layout_without_bridging_the_gap() {
use crate::viewer::Viewer;
let mut store = Store::new();
add(&mut store, 100, 10);
let owner = crate::span::SpanIndex::new(1).unwrap();
let mut viewer = Viewer::new();
let initial = viewer.compute_update(&store, &rect());
assert_eq!(initial.max, 10);
let mut outdated = FxHashSet::default();
store.add_self_time(
owner,
Timestamp::from_value(200),
Timestamp::from_value(220),
&mut outdated,
);
viewer.invalidate_timeline();
let update = viewer.compute_update(&store, &rect());
assert_eq!(update.count, 1);
assert_eq!(update.max, 120);
assert_eq!(update.lines[0].spans.len(), 2);
assert_eq!(update.lines[0].spans[0].id, update.lines[0].spans[1].id);
assert_eq!(
(
update.lines[0].spans[1].start,
update.lines[0].spans[1].width
),
(100, 20)
);
}
#[test]
fn dense_spans_are_preserved_as_zoomable_placeholders() {
let mut store = Store::new();
......
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