-
Notifications
You must be signed in to change notification settings - Fork 300
fix: improve tracing feature #3688
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
32 commits
Select commit
Hold shift + click to select a range
4482790
fix: improve Chrome trace event format correctness and metric naming
andygrove 963456e
style: format tracing.md with prettier
andygrove ef0116b
fix: use stable API for getting thread ID in tracing
andygrove 7e3846f
Merge remote-tracking branch 'apache/main' into improve-tracing
andygrove 1700e36
feat: trace memory pool reserved bytes for comparing accounting vs ac…
andygrove 53c1605
cargo fmt
andygrove e501b13
feat: improve tracing by adding task ID to memory_pool_reserved metri…
andygrove 7f95a33
feat: use thread ID for tracing metrics and rename for consistency
andygrove 25d51f7
use java thread id
andygrove 7b50b6a
switch to ctx id not thread id
andygrove 7018e0a
pad context ID to six digits in tracing metric names for lexicographi…
andygrove 03655ac
fix: emit comet_memory_reserved=0 on releasePlan so tracing shows mem…
andygrove b516a9f
use Java thread ID for tracing memory metrics so multiple contexts on…
andygrove 53b4755
sum memory reservations across all contexts on same thread for tracing
andygrove f864f84
drop per-context comet_memory and spark_memory tracing metrics in fav…
andygrove c5f34ce
simplify tracing: pre-compute metric name, unify poll counters, use p…
andygrove fdb3051
update tracing docs: fix inaccuracies, update screenshot
andygrove 59b2023
prep for review
andygrove f376596
fix: pass tracing_enabled flag into native shuffle writer
andygrove 24b7385
standardize tracing on Rust thread IDs instead of Java thread IDs
andygrove 083761b
save
andygrove 4cc71bf
remove redundant external_shuffle trace
andygrove 6e6735c
add analyze_trace binary to compare jemalloc vs pool reservations
andygrove 18bc84b
docs: document analyze_trace tool with sample output
andygrove 08a3c88
chore: run prettier on tracing docs
andygrove e05c6f4
new screenshot
andygrove 27cb7aa
revert
andygrove d0d69ed
bug fix:
andygrove 619c47a
Merge branch 'improve-tracing' of github.com:andygrove/datafusion-com…
andygrove 59245c1
perf: guard tracing allocations behind tracing_enabled check
andygrove 7d642d3
refactor: simplify tracing label construction in executePlan
andygrove 57e051d
perf: avoid String allocation on hot path when tracing disabled
andygrove File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,204 @@ | ||
| // Licensed to the Apache Software Foundation (ASF) under one | ||
| // or more contributor license agreements. See the NOTICE file | ||
| // distributed with this work for additional information | ||
| // regarding copyright ownership. The ASF licenses this file | ||
| // to you under the Apache License, Version 2.0 (the | ||
| // "License"); you may not use this file except in compliance | ||
| // with the License. You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, | ||
| // software distributed under the License is distributed on an | ||
| // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
| // KIND, either express or implied. See the License for the | ||
| // specific language governing permissions and limitations | ||
| // under the License. | ||
|
|
||
| //! Analyzes a Comet chrome trace event log (`comet-event-trace.json`) and | ||
| //! compares jemalloc usage against the sum of per-thread Comet memory pool | ||
| //! reservations. Reports any points where jemalloc exceeds the total pool size. | ||
| //! | ||
| //! Usage: | ||
| //! cargo run --bin analyze_trace -- <path-to-comet-event-trace.json> | ||
|
|
||
| use serde::Deserialize; | ||
| use std::collections::HashMap; | ||
| use std::io::{BufRead, BufReader}; | ||
| use std::{env, fs::File}; | ||
|
|
||
| /// A single Chrome trace event (only the fields we care about). | ||
| #[derive(Deserialize)] | ||
| struct TraceEvent { | ||
| name: String, | ||
| ph: String, | ||
| #[allow(dead_code)] | ||
| tid: u64, | ||
| ts: u64, | ||
| #[serde(default)] | ||
| args: HashMap<String, serde_json::Value>, | ||
| } | ||
|
|
||
| /// Snapshot of memory state at a given timestamp. | ||
| struct MemorySnapshot { | ||
| ts: u64, | ||
| jemalloc: u64, | ||
| pool_total: u64, | ||
| } | ||
|
|
||
| fn format_bytes(bytes: u64) -> String { | ||
| const MB: f64 = 1024.0 * 1024.0; | ||
| format!("{:.1} MB", bytes as f64 / MB) | ||
| } | ||
|
|
||
| fn main() { | ||
| let args: Vec<String> = env::args().collect(); | ||
| if args.len() != 2 { | ||
| eprintln!("Usage: analyze_trace <path-to-comet-event-trace.json>"); | ||
| std::process::exit(1); | ||
| } | ||
|
|
||
| let file = File::open(&args[1]).expect("Failed to open trace file"); | ||
| let reader = BufReader::new(file); | ||
|
|
||
| // Latest jemalloc value (global, not per-thread) | ||
| let mut latest_jemalloc: u64 = 0; | ||
| // Per-thread pool reservations: thread_NNN -> bytes | ||
| let mut pool_by_thread: HashMap<String, u64> = HashMap::new(); | ||
| // Points where jemalloc exceeded pool total | ||
| let mut violations: Vec<MemorySnapshot> = Vec::new(); | ||
| // Track peak values | ||
| let mut peak_jemalloc: u64 = 0; | ||
| let mut peak_pool_total: u64 = 0; | ||
| let mut peak_excess: u64 = 0; | ||
| let mut counter_events: u64 = 0; | ||
|
|
||
| // Each line is one JSON event, possibly with a trailing comma. | ||
| // The file starts with "[ " on the first event line or as a prefix. | ||
| for line in reader.lines() { | ||
| let line = line.expect("Failed to read line"); | ||
| let trimmed = line.trim(); | ||
|
|
||
| // Skip empty lines or bare array brackets | ||
| if trimmed.is_empty() || trimmed == "[" || trimmed == "]" { | ||
| continue; | ||
| } | ||
|
|
||
| // Strip leading "[ " (first event) and trailing comma | ||
| let json_str = trimmed | ||
| .trim_start_matches("[ ") | ||
| .trim_start_matches('[') | ||
| .trim_end_matches(','); | ||
|
|
||
| if json_str.is_empty() { | ||
| continue; | ||
| } | ||
|
|
||
| // Only parse counter events (they contain "\"ph\": \"C\"") | ||
| if !json_str.contains("\"ph\": \"C\"") { | ||
| continue; | ||
| } | ||
|
|
||
| let event: TraceEvent = match serde_json::from_str(json_str) { | ||
| Ok(e) => e, | ||
| Err(_) => continue, | ||
| }; | ||
|
|
||
| if event.ph != "C" { | ||
| continue; | ||
| } | ||
|
|
||
| counter_events += 1; | ||
|
|
||
| if event.name == "jemalloc_allocated" { | ||
| if let Some(val) = event.args.get("jemalloc_allocated") { | ||
| latest_jemalloc = val.as_u64().unwrap_or(0); | ||
| if latest_jemalloc > peak_jemalloc { | ||
| peak_jemalloc = latest_jemalloc; | ||
| } | ||
| } | ||
| } else if event.name.contains("comet_memory_reserved") { | ||
| // Name format: thread_NNN_comet_memory_reserved | ||
| let thread_key = event.name.clone(); | ||
| if let Some(val) = event.args.get(&event.name) { | ||
| let bytes = val.as_u64().unwrap_or(0); | ||
| pool_by_thread.insert(thread_key, bytes); | ||
| } | ||
| } else { | ||
| // Skip jvm_heap_used and other counters | ||
| continue; | ||
| } | ||
|
|
||
| // After each jemalloc or pool update, check the current state | ||
| let pool_total: u64 = pool_by_thread.values().sum(); | ||
| if pool_total > peak_pool_total { | ||
| peak_pool_total = pool_total; | ||
| } | ||
|
|
||
| if latest_jemalloc > 0 && pool_total > 0 && latest_jemalloc > pool_total { | ||
| let excess = latest_jemalloc - pool_total; | ||
| if excess > peak_excess { | ||
| peak_excess = excess; | ||
| } | ||
| // Record violation (sample - don't record every single one) | ||
| if violations.is_empty() | ||
| || event.ts.saturating_sub(violations.last().unwrap().ts) > 1_000_000 | ||
| || excess == peak_excess | ||
| { | ||
| violations.push(MemorySnapshot { | ||
| ts: event.ts, | ||
| jemalloc: latest_jemalloc, | ||
| pool_total, | ||
| }); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // Print summary | ||
| println!("=== Comet Trace Memory Analysis ===\n"); | ||
| println!("Counter events parsed: {counter_events}"); | ||
| println!("Threads with memory pools: {}", pool_by_thread.len()); | ||
| println!("Peak jemalloc allocated: {}", format_bytes(peak_jemalloc)); | ||
| println!( | ||
| "Peak pool total: {}", | ||
| format_bytes(peak_pool_total) | ||
| ); | ||
| println!( | ||
| "Peak excess (jemalloc - pool): {}", | ||
| format_bytes(peak_excess) | ||
| ); | ||
| println!(); | ||
|
|
||
| if violations.is_empty() { | ||
| println!("OK: jemalloc never exceeded the total pool reservation."); | ||
| } else { | ||
| println!( | ||
| "WARNING: jemalloc exceeded pool reservation at {} sampled points:\n", | ||
| violations.len() | ||
| ); | ||
| println!( | ||
| "{:>14} {:>14} {:>14} {:>14}", | ||
| "Time (us)", "jemalloc", "pool_total", "excess" | ||
| ); | ||
| println!("{}", "-".repeat(62)); | ||
| for snap in &violations { | ||
| let excess = snap.jemalloc - snap.pool_total; | ||
| println!( | ||
| "{:>14} {:>14} {:>14} {:>14}", | ||
| snap.ts, | ||
| format_bytes(snap.jemalloc), | ||
| format_bytes(snap.pool_total), | ||
| format_bytes(excess), | ||
| ); | ||
| } | ||
| } | ||
|
|
||
| // Show final per-thread pool state | ||
| println!("\n--- Final per-thread pool reservations ---\n"); | ||
| let mut threads: Vec<_> = pool_by_thread.iter().collect(); | ||
| threads.sort_by_key(|(k, _)| (*k).clone()); | ||
| for (thread, bytes) in &threads { | ||
| println!(" {thread}: {}", format_bytes(**bytes)); | ||
| } | ||
| println!("\n Total: {}", format_bytes(pool_by_thread.values().sum())); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -64,10 +64,9 @@ impl Recorder { | |
| } | ||
|
|
||
| pub fn log_memory_usage(&self, name: &str, usage_bytes: u64) { | ||
| let usage_mb = (usage_bytes as f64 / 1024.0 / 1024.0) as usize; | ||
| let json = format!( | ||
| "{{ \"name\": \"{name}\", \"cat\": \"PERF\", \"ph\": \"C\", \"pid\": 1, \"tid\": {}, \"ts\": {}, \"args\": {{ \"{name}\": {usage_mb} }} }},\n", | ||
| Self::get_thread_id(), | ||
| "{{ \"name\": \"{name}\", \"cat\": \"PERF\", \"ph\": \"C\", \"pid\": 1, \"tid\": {}, \"ts\": {}, \"args\": {{ \"{name}\": {usage_bytes} }} }},\n", | ||
| get_thread_id(), | ||
| self.now.elapsed().as_micros() | ||
| ); | ||
| let mut writer = self.writer.lock().unwrap(); | ||
|
|
@@ -80,23 +79,23 @@ impl Recorder { | |
| let json = format!( | ||
| "{{ \"name\": \"{}\", \"cat\": \"PERF\", \"ph\": \"{ph}\", \"pid\": 1, \"tid\": {}, \"ts\": {} }},\n", | ||
| name, | ||
| Self::get_thread_id(), | ||
| get_thread_id(), | ||
| self.now.elapsed().as_micros() | ||
| ); | ||
| let mut writer = self.writer.lock().unwrap(); | ||
| writer | ||
| .write_all(json.as_bytes()) | ||
| .expect("Error writing tracing"); | ||
| } | ||
| } | ||
|
|
||
| fn get_thread_id() -> u64 { | ||
| let thread_id = std::thread::current().id(); | ||
| format!("{thread_id:?}") | ||
| .trim_start_matches("ThreadId(") | ||
| .trim_end_matches(")") | ||
| .parse() | ||
| .expect("Error parsing thread id") | ||
| } | ||
| pub fn get_thread_id() -> u64 { | ||
| let thread_id = std::thread::current().id(); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Claude suggests
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Yup, they told me the same. Turns out it is an unstable feature. |
||
| format!("{thread_id:?}") | ||
| .trim_start_matches("ThreadId(") | ||
| .trim_end_matches(")") | ||
| .parse() | ||
| .expect("Error parsing thread id") | ||
| } | ||
|
|
||
| pub fn trace_begin(name: &str) { | ||
|
|
||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
👍