Unverified Commit db973dc7 authored by Niklas Mischkulnig's avatar Niklas Mischkulnig Committed by GitHub

Fix binary trace self-time on same-span re-entry (#100205)

## Summary

Fix lost binary-trace self-time when a span re-enters itself on the same
thread, as happens with instrumented futures. Previously, the inner Exit
restarted the outer frame's clock under the same `(span_id, thread_id)`
key and immediately removed it, dropping the outer frame's remaining
work.

Store the active slice start on each per-thread stack frame instead.
Enter closes the current top's slice; Exit closes the matching frame and
resumes the new top only when the exiting frame was on top. Non-LIFO
exits remove suspended frames without restarting another clock;
unmatched exits leave clocks unchanged. Allocation attribution,
queued-parent processing, and `DROP_SPANS` remain intact.

**Binary flame CPU/self-time, concurrency-corrected time, and
concurrency metrics will change because the previously missing slices
are now accounted for correctly.** This does not change the binary trace
format.

Add encoded `TraceRow` parser regressions for single/multiple same-span
nesting, child interleaving, cross-thread activity, non-LIFO/unmatched
exits, live input with a partial final row, allocations, queued parents,
and dropped spans. Five regression cases failed against the original
reader before the fix.

## Verification

- `cargo test -p turbopack-trace-server` — 84 library and 58 binary
tests passed.
- `cargo clippy -p turbopack-trace-server --all-targets -- -D warnings`
— passed.
- `cargo fmt --all -- --check` — passed.
- Generated a real binary trace from a small local app using published
`16.5.0-canary.10` with `NEXT_TURBOPACK_TRACING=turbo-tasks`: 2,282,825
rows, 652,508 Enter/Exit pairs, 11 threads, and 109,050 same-span
re-entries; all exits LIFO.
- Independently decoded the raw postcard rows with a standalone decoder
and reconstructed slices using per-thread span-ID stacks and transition
timestamps. Of 1,118,980 physical positive frame slices, five were
intentionally excluded by existing thread/blocking-span rules. The
remaining **1,118,975-slice multiset matched exactly** in both Store
events and `self_time_tree`, including ownership and start/end
timestamps. Independent self-time, stored self-time, and root flame CPU
total all equaled **11.537977 CPU seconds**. No trace payload or local
app files are included.
- Repository-wide `pnpm build-all` bootstrap could not start because
this checkout has no `node_modules` (`turbo: command not found`); the
Rust checks above ran successfully.

<!-- NEXT_JS_LLM -->


<!-- fleet 8e507624-bae8-4561-8469-867912a2654e -->
Co-authored-by: 's avatarvercel-fleet-prod[bot] <318278635+vercel-fleet-prod[bot]@users.noreply.github.com>
parent a73eee23
......@@ -65,8 +65,9 @@ pub struct TurbopackFormat {
remaining_ids_to_drop: usize,
queued_rows: FxHashMap<u64, Vec<InternalRow>>,
outdated_spans: FxHashSet<SpanIndex>,
thread_stacks: FxHashMap<u64, Vec<u64>>,
self_time_started: FxHashMap<(u64, u64), Timestamp>,
// Each entry is a separate enter, even when the same span re-enters itself.
// Only the top frame has an active self-time start; suspended frames have None.
thread_stacks: FxHashMap<u64, Vec<(u64, Option<Timestamp>)>>,
interner: RcStrInterning,
}
......@@ -84,7 +85,6 @@ impl TurbopackFormat {
queued_rows: FxHashMap::with_capacity_and_hasher(1_024, Default::default()),
outdated_spans: FxHashSet::with_capacity_and_hasher(8_192, Default::default()),
thread_stacks: FxHashMap::with_capacity_and_hasher(64, Default::default()),
self_time_started: FxHashMap::with_capacity_and_hasher(256, Default::default()),
interner: RcStrInterning::new(),
}
}
......@@ -162,27 +162,19 @@ impl TurbopackFormat {
}
let ts = Timestamp::from_micros(ts);
let stack = self.thread_stacks.entry(thread_id).or_default();
if let Some(&parent) = stack.last() {
if let Some(parent_start) = self.self_time_started.remove(&(parent, thread_id))
{
stack.push(id);
self.process_internal_row(
store,
InternalRow {
id: Some(parent),
ty: InternalRowType::SelfTime {
start: parent_start,
end: ts,
},
},
);
} else {
stack.push(id);
}
} else {
stack.push(id);
let parent_slice = stack
.last_mut()
.and_then(|(parent, start)| start.take().map(|start| (*parent, start)));
stack.push((id, Some(ts)));
if let Some((parent, start)) = parent_slice {
self.process_internal_row(
store,
InternalRow {
id: Some(parent),
ty: InternalRowType::SelfTime { start, end: ts },
},
);
}
self.self_time_started.insert((id, thread_id), ts);
}
TraceRow::Exit {
ts,
......@@ -196,22 +188,24 @@ impl TurbopackFormat {
}
let ts = Timestamp::from_micros(ts);
let stack = self.thread_stacks.entry(thread_id).or_default();
if let Some(pos) = stack.iter().rev().position(|&x| x == id) {
let stack_index = stack.len() - pos - 1;
stack.remove(stack_index);
if stack_index > 0 {
let parent = stack[stack_index - 1];
self.self_time_started.insert((parent, thread_id), ts);
if let Some(stack_index) = stack.iter().rposition(|&(frame_id, _)| frame_id == id) {
let (_, start) = stack.remove(stack_index);
// A non-LIFO exit removes a suspended frame. The current top
// keeps running, so no other frame should be resumed yet.
if stack_index == stack.len()
&& let Some((_, parent_start)) = stack.last_mut()
{
*parent_start = Some(ts);
}
if let Some(start) = start {
self.process_internal_row(
store,
InternalRow {
id: Some(id),
ty: InternalRowType::SelfTime { start, end: ts },
},
);
}
}
if let Some(start) = self.self_time_started.remove(&(id, thread_id)) {
self.process_internal_row(
store,
InternalRow {
id: Some(id),
ty: InternalRowType::SelfTime { start, end: ts },
},
);
}
}
TraceRow::Event { ts, parent, values } => {
......@@ -274,7 +268,7 @@ impl TurbopackFormat {
allocations: Allocations,
) {
let stack = self.thread_stacks.entry(thread_id).or_default();
if let Some(&id) = stack.last() {
if let Some(&(id, _)) = stack.last() {
if allocations.allocations > 0 {
self.process_internal_row(
store,
......@@ -507,7 +501,9 @@ mod tests {
use crate::{
reader::{TraceFormat, turbopack::TurbopackFormat},
span::SpanEvent,
store_container::StoreContainer,
timestamp::Timestamp,
};
fn start(id: u64, parent: Option<u64>, name: &'static str) -> TraceRow<'static> {
......@@ -559,6 +555,334 @@ mod tests {
.collect()
}
fn enter(ts: u64, id: u64, thread_id: u64) -> TraceRow<'static> {
TraceRow::Enter {
ts,
id,
thread_id,
allocations: None,
}
}
fn exit(ts: u64, id: u64, thread_id: u64) -> TraceRow<'static> {
TraceRow::Exit {
ts,
id,
thread_id,
allocations: None,
}
}
fn encode(rows: &[TraceRow<'_>]) -> Vec<u8> {
rows.iter()
.flat_map(|row| postcard::to_stdvec(row).unwrap())
.collect()
}
fn ingest(format: &mut TurbopackFormat, rows: &[TraceRow<'_>]) {
let data = encode(rows);
assert_eq!(
format
.read(&data, &mut TurbopackFormat::create_reused())
.unwrap(),
data.len()
);
}
/// Check both representations of the positive slices, their per-span self-time,
/// and the total CPU time used by the flame view. Timestamps are in microseconds.
fn assert_slices(format: &TurbopackFormat, expected: &[(u64, u64, u64)]) {
let store = format.store.read();
let mut expected: Vec<_> = expected
.iter()
.map(|&(id, start, end)| {
(
format.id_mapping[&id].get(),
Timestamp::from_micros(start),
Timestamp::from_micros(end),
)
})
.collect();
expected.sort_unstable();
let mut events = Vec::new();
for i in 0..store.spans.len() {
let span = &store.spans[i];
for event in span.events.iter() {
if let SpanEvent::SelfTime(slice) = event {
events.push((i, slice.start, slice.end()));
}
}
let self_time: Timestamp = expected
.iter()
.filter(|&&(id, _, _)| id == i)
.map(|&(_, start, end)| end - start)
.sum();
assert_eq!(span.time_data.self_time, self_time, "span {i}");
}
events.sort_unstable();
assert_eq!(events, expected, "stored self-time events");
let mut tree_slices = Vec::new();
store.self_time_tree.as_ref().unwrap().for_each_in_range(
Timestamp::ZERO,
Timestamp::MAX,
&mut |start, end, id| tree_slices.push((id.get(), start, end)),
);
tree_slices.sort_unstable();
assert_eq!(tree_slices, expected, "self-time tree");
let total: Timestamp = expected.iter().map(|&(_, start, end)| end - start).sum();
assert_eq!(store.root_span().total_time(), total, "flame CPU total");
}
#[test]
fn same_span_reentry_keeps_every_frame_slice() {
for depth in [2, 3] {
let store = Arc::new(StoreContainer::new());
let mut format = TurbopackFormat::new(store);
let mut rows = vec![start(1, None, "span")];
for i in 0..depth {
rows.push(enter(10 + i * 10, 1, 1));
}
for i in 0..depth {
rows.push(exit(10 + (depth + i) * 10, 1, 1));
}
ingest(&mut format, &rows);
let expected: Vec<_> = (0..depth * 2 - 1)
.map(|i| (1, 10 + i * 10, 20 + i * 10))
.collect();
assert_slices(&format, &expected);
}
}
#[test]
fn same_span_reentry_interleaved_with_child() {
let mut format = TurbopackFormat::new(Arc::new(StoreContainer::new()));
ingest(
&mut format,
&[
start(1, None, "parent"),
start(2, Some(1), "child"),
enter(10, 1, 1),
enter(20, 1, 1),
enter(30, 2, 1),
exit(40, 2, 1),
exit(50, 1, 1),
exit(60, 1, 1),
],
);
assert_slices(
&format,
&[
(1, 10, 20),
(1, 20, 30),
(2, 30, 40),
(1, 40, 50),
(1, 50, 60),
],
);
}
#[test]
fn same_span_on_two_threads_has_independent_frames() {
let mut format = TurbopackFormat::new(Arc::new(StoreContainer::new()));
ingest(
&mut format,
&[
start(1, None, "span"),
enter(10, 1, 1),
enter(15, 1, 2),
enter(20, 1, 1),
exit(30, 1, 1),
exit(35, 1, 2),
exit(40, 1, 1),
],
);
assert_slices(
&format,
&[(1, 10, 20), (1, 20, 30), (1, 30, 40), (1, 15, 35)],
);
let store = format.store.read();
assert_eq!(
store.root_span().corrected_total_time(),
Timestamp::from_micros(30)
);
}
#[test]
fn non_lifo_exit_does_not_resume_a_suspended_parent() {
let mut format = TurbopackFormat::new(Arc::new(StoreContainer::new()));
ingest(
&mut format,
&[
start(1, None, "outer"),
start(2, Some(1), "middle"),
start(3, Some(2), "inner"),
enter(10, 1, 1),
enter(20, 2, 1),
enter(30, 3, 1),
exit(40, 2, 1),
exit(50, 3, 1),
exit(60, 1, 1),
],
);
assert_slices(
&format,
&[(1, 10, 20), (2, 20, 30), (3, 30, 50), (1, 50, 60)],
);
}
#[test]
fn non_lifo_exit_removes_the_most_recent_matching_frame() {
let mut format = TurbopackFormat::new(Arc::new(StoreContainer::new()));
ingest(
&mut format,
&[
start(1, None, "outer"),
start(2, Some(1), "inner"),
enter(10, 1, 1),
enter(20, 1, 1),
enter(30, 2, 1),
exit(40, 1, 1),
exit(50, 2, 1),
exit(60, 1, 1),
],
);
assert_slices(
&format,
&[(1, 10, 20), (1, 20, 30), (2, 30, 50), (1, 50, 60)],
);
}
#[test]
fn non_lifo_exit_can_remove_the_bottom_frame() {
let mut format = TurbopackFormat::new(Arc::new(StoreContainer::new()));
ingest(
&mut format,
&[
start(1, None, "outer"),
start(2, Some(1), "inner"),
enter(10, 1, 1),
enter(20, 2, 1),
start(3, Some(2), "child"),
enter(30, 3, 1),
exit(40, 2, 1),
exit(45, 1, 1),
exit(50, 3, 1),
],
);
assert_slices(&format, &[(1, 10, 20), (2, 20, 30), (3, 30, 50)]);
}
#[test]
fn unmatched_exit_leaves_active_frames_unchanged() {
let mut format = TurbopackFormat::new(Arc::new(StoreContainer::new()));
ingest(
&mut format,
&[
start(1, None, "span"),
exit(5, 1, 1),
enter(10, 1, 1),
exit(20, 99, 1),
exit(25, 1, 2),
exit(30, 1, 1),
exit(40, 1, 1),
],
);
assert_slices(&format, &[(1, 10, 30)]);
}
#[test]
fn live_trace_with_partial_exit_preserves_the_resumed_frame() {
let mut format = TurbopackFormat::new(Arc::new(StoreContainer::new()));
let mut reuse = TurbopackFormat::create_reused();
let prefix = encode(&[
start(1, None, "span"),
enter(10, 1, 1),
enter(20, 1, 1),
exit(30, 1, 1),
]);
let final_row = encode(&[exit(40, 1, 1)]);
let mut data = prefix.clone();
data.extend_from_slice(&final_row[..final_row.len() - 1]);
let consumed = format.read(&data, &mut reuse).unwrap();
assert_eq!(consumed, prefix.len());
assert_slices(&format, &[(1, 10, 20), (1, 20, 30)]);
assert_eq!(format.read(&[], &mut reuse).unwrap(), 0);
data.push(*final_row.last().unwrap());
assert_eq!(
format.read(&data[consumed..], &mut reuse).unwrap(),
final_row.len()
);
assert_slices(&format, &[(1, 10, 20), (1, 20, 30), (1, 30, 40)]);
}
#[test]
fn reentry_self_time_waits_for_queued_parent() {
let mut format = TurbopackFormat::new(Arc::new(StoreContainer::new()));
ingest(
&mut format,
&[
start(2, Some(1), "child"),
enter(10, 2, 1),
enter(20, 2, 1),
exit(30, 2, 1),
exit(40, 2, 1),
],
);
assert!(!format.queued_rows.is_empty());
ingest(&mut format, &[start(1, None, "parent")]);
assert!(format.queued_rows.is_empty());
assert_slices(&format, &[(2, 10, 20), (2, 20, 30), (2, 30, 40)]);
}
#[test]
fn dropped_reentered_span_does_not_contribute_self_time() {
let mut format = TurbopackFormat::new(Arc::new(StoreContainer::new()));
// Exercise DROP_SPANS without changing the process-wide environment.
format.remaining_ids_to_drop = 1;
ingest(
&mut format,
&[
start(1, None, "parent"),
start(2, Some(1), "dropped"),
enter(10, 1, 1),
enter(20, 2, 1),
enter(30, 2, 1),
exit(40, 2, 1),
exit(50, 2, 1),
exit(60, 1, 1),
],
);
assert!(format.dropped_ids.contains(&2));
assert_slices(&format, &[(1, 10, 20), (1, 50, 60)]);
}
#[test]
fn attributes_allocations_during_same_span_reentry() {
let rows = [
start(1, None, "span"),
enter(10, 1, 1),
TraceRow::Enter {
ts: 20,
id: 1,
thread_id: 1,
allocations: allocations(100, 20),
},
TraceRow::Exit {
ts: 30,
id: 1,
thread_id: 1,
allocations: allocations(50, 30),
},
TraceRow::Exit {
ts: 40,
id: 1,
thread_id: 1,
allocations: allocations(70, 40),
},
];
assert_eq!(read(&rows, &["span"]), vec![(220, 22, 90)]);
}
#[test]
fn attributes_allocations_of_enter_and_exit_rows() {
let enter = |ts, id, allocations| TraceRow::Enter {
......
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