Skip to content
Merged
Show file tree
Hide file tree
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 Mar 13, 2026
963456e
style: format tracing.md with prettier
andygrove Mar 18, 2026
ef0116b
fix: use stable API for getting thread ID in tracing
andygrove Apr 9, 2026
7e3846f
Merge remote-tracking branch 'apache/main' into improve-tracing
andygrove Apr 9, 2026
1700e36
feat: trace memory pool reserved bytes for comparing accounting vs ac…
andygrove Apr 9, 2026
53c1605
cargo fmt
andygrove Apr 9, 2026
e501b13
feat: improve tracing by adding task ID to memory_pool_reserved metri…
andygrove Apr 9, 2026
7f95a33
feat: use thread ID for tracing metrics and rename for consistency
andygrove Apr 9, 2026
25d51f7
use java thread id
andygrove Apr 9, 2026
7b50b6a
switch to ctx id not thread id
andygrove Apr 9, 2026
7018e0a
pad context ID to six digits in tracing metric names for lexicographi…
andygrove Apr 9, 2026
03655ac
fix: emit comet_memory_reserved=0 on releasePlan so tracing shows mem…
andygrove Apr 9, 2026
b516a9f
use Java thread ID for tracing memory metrics so multiple contexts on…
andygrove Apr 9, 2026
53b4755
sum memory reservations across all contexts on same thread for tracing
andygrove Apr 9, 2026
f864f84
drop per-context comet_memory and spark_memory tracing metrics in fav…
andygrove Apr 9, 2026
c5f34ce
simplify tracing: pre-compute metric name, unify poll counters, use p…
andygrove Apr 9, 2026
fdb3051
update tracing docs: fix inaccuracies, update screenshot
andygrove Apr 9, 2026
59b2023
prep for review
andygrove Apr 9, 2026
f376596
fix: pass tracing_enabled flag into native shuffle writer
andygrove Apr 10, 2026
24b7385
standardize tracing on Rust thread IDs instead of Java thread IDs
andygrove Apr 10, 2026
083761b
save
andygrove Apr 10, 2026
4cc71bf
remove redundant external_shuffle trace
andygrove Apr 10, 2026
6e6735c
add analyze_trace binary to compare jemalloc vs pool reservations
andygrove Apr 10, 2026
18bc84b
docs: document analyze_trace tool with sample output
andygrove Apr 10, 2026
08a3c88
chore: run prettier on tracing docs
andygrove Apr 10, 2026
e05c6f4
new screenshot
andygrove Apr 10, 2026
27cb7aa
revert
andygrove Apr 10, 2026
d0d69ed
bug fix:
andygrove Apr 10, 2026
619c47a
Merge branch 'improve-tracing' of github.com:andygrove/datafusion-com…
andygrove Apr 10, 2026
59245c1
perf: guard tracing allocations behind tracing_enabled check
andygrove Apr 10, 2026
7d642d3
refactor: simplify tracing label construction in executePlan
andygrove Apr 10, 2026
57e051d
perf: avoid String allocation on hot path when tracing disabled
andygrove Apr 10, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file modified docs/source/_static/images/tracing.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
75 changes: 63 additions & 12 deletions docs/source/contributor-guide/tracing.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,25 +40,76 @@ Example output:
{ "name": "decodeShuffleBlock", "cat": "PERF", "ph": "E", "pid": 1, "tid": 5, "ts": 10109228835 },
{ "name": "decodeShuffleBlock", "cat": "PERF", "ph": "B", "pid": 1, "tid": 5, "ts": 10109245928 },
{ "name": "decodeShuffleBlock", "cat": "PERF", "ph": "E", "pid": 1, "tid": 5, "ts": 10109248843 },
{ "name": "execute_plan", "cat": "PERF", "ph": "E", "pid": 1, "tid": 5, "ts": 10109350935 },
{ "name": "CometExecIterator_getNextBatch", "cat": "PERF", "ph": "E", "pid": 1, "tid": 5, "ts": 10109367116 },
{ "name": "CometExecIterator_getNextBatch", "cat": "PERF", "ph": "B", "pid": 1, "tid": 5, "ts": 10109479156 },
{ "name": "executePlan", "cat": "PERF", "ph": "E", "pid": 1, "tid": 5, "ts": 10109350935 },
{ "name": "getNextBatch[JVM] stage=2", "cat": "PERF", "ph": "E", "pid": 1, "tid": 5, "ts": 10109367116 },
{ "name": "getNextBatch[JVM] stage=2", "cat": "PERF", "ph": "B", "pid": 1, "tid": 5, "ts": 10109479156 },
```

Traces can be viewed with [Trace Viewer].
Traces can be viewed with [Perfetto UI].

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

[Trace Viewer]: https://github.com/catapult-project/catapult/blob/main/tracing/README.md
[Perfetto UI]: https://ui.perfetto.dev

Example trace visualization:

![tracing](../_static/images/tracing.png)

## Analyzing Memory Usage

The `analyze_trace` tool parses a trace log and compares jemalloc usage against the sum of per-thread
Comet memory pool reservations. This is useful for detecting untracked native memory growth where jemalloc
allocations exceed what the memory pools account for.

Build and run:

```shell
cd native
cargo run --bin analyze_trace -- /path/to/comet-event-trace.json
```

The tool reads counter events from the trace log. Because tracing logs metrics per thread, `jemalloc_allocated`
is a process-wide value (the same global allocation reported from whichever thread logs it), while
`thread_NNN_comet_memory_reserved` values are per-thread pool reservations that are summed to get the total
tracked memory.

Sample output:

```
=== Comet Trace Memory Analysis ===

Counter events parsed: 193104
Threads with memory pools: 8
Peak jemalloc allocated: 3068.2 MB
Peak pool total: 2864.6 MB
Peak excess (jemalloc - pool): 364.6 MB

WARNING: jemalloc exceeded pool reservation at 138 sampled points:

Time (us) jemalloc pool_total excess
--------------------------------------------------------------
179578 210.8 MB 0.1 MB 210.7 MB
429663 420.5 MB 145.1 MB 275.5 MB
1304969 2122.5 MB 1797.2 MB 325.2 MB
21974838 407.0 MB 42.3 MB 364.6 MB
33543599 5.5 MB 0.1 MB 5.3 MB

--- Final per-thread pool reservations ---

thread_60_comet_memory_reserved: 0.0 MB
thread_95_comet_memory_reserved: 0.0 MB
thread_96_comet_memory_reserved: 0.0 MB
...

Total: 0.0 MB
```

Some excess is expected (jemalloc metadata, fragmentation, non-pool allocations like Arrow IPC buffers).
Large or growing excess may indicate memory that is not being tracked by the pool.

## Definition of Labels

| Label | Meaning |
| --------------------- | -------------------------------------------------------------- |
| jvm_heapUsed | JVM heap memory usage of live objects for the executor process |
| jemalloc_allocated | Native memory usage for the executor process |
| task_memory_comet_NNN | Off-heap memory allocated by Comet for query execution |
| task_memory_spark_NNN | On-heap & Off-heap memory allocated by Spark |
| comet_shuffle_NNN | Off-heap memory allocated by Comet for columnar shuffle |
| Label | Meaning |
| -------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| jvm_heap_used | JVM heap memory usage of live objects for the executor process |
| jemalloc_allocated | Native memory usage for the executor process (requires `jemalloc` feature) |
| thread_NNN_comet_memory_reserved | Memory reserved by Comet's DataFusion memory pool (summed across all contexts on the thread). NNN is the Rust thread ID. |
| thread_NNN_comet_jvm_shuffle | Off-heap memory allocated by Comet for columnar shuffle. NNN is the Rust thread ID. |
4 changes: 4 additions & 0 deletions native/common/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,7 @@ thiserror = { workspace = true }
[lib]
name = "datafusion_comet_common"
path = "src/lib.rs"

[[bin]]
name = "analyze_trace"
path = "src/bin/analyze_trace.rs"
204 changes: 204 additions & 0 deletions native/common/src/bin/analyze_trace.rs
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()));
}
23 changes: 11 additions & 12 deletions native/common/src/tracing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -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();
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Claude suggests std::thread::current().id().as_u64() is better.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The 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) {
Expand Down
Loading
Loading