Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
71 changes: 70 additions & 1 deletion crates/dbsp/src/circuit/dbsp_handle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1965,7 +1965,7 @@ pub(crate) mod tests {
if Runtime::worker_index() == 0 {
let runtime = Runtime::runtime().unwrap();
let panic_tx = panic_tx.clone();
runtime.tokio_merger_runtime().spawn(async move {
runtime.tokio_merger_runtime().unwrap().spawn(async move {
TOKIO_WORKER_INDEX
.scope(0, async move {
let _ = std::panic::catch_unwind(|| {
Expand Down Expand Up @@ -2004,6 +2004,75 @@ pub(crate) mod tests {
}
}

/// Regression test for the deadlock in `RuntimeHandle::join` (commit 1 of
/// PR #6331) where the `MutexGuard` from `tokio_merger_runtime.lock()` was
/// held across the `drop` of the runtime, and for the panic on
/// `.expect("tokio merger runtime has been shut down")` (commit 2 of the
/// same PR) that the early-return in `MergeJob::run` replaced.
///
/// Spawns a tokio merger task that hammers `Runtime::tokio_merger_runtime`
/// in a tight loop, then drops the `DBSPHandle` on a side thread and
/// asserts that:
/// - the drop completes within a timeout (regressing commit 1 would deadlock
/// the blocking pool against the held mutex), and
/// - the task exits cleanly via the `None` arm (regressing commit 2 would
/// panic on `.expect()` and the clean-exit signal would never arrive).
#[test]
fn test_drop_does_not_deadlock_with_active_merger_lookup() {
let (ready_tx, ready_rx) = std::sync::mpsc::channel();
let (task_done_tx, task_done_rx) = std::sync::mpsc::channel();
let (handle, _) = Runtime::init_circuit(1, move |circuit| {
let (_stream, _input_handle) = circuit.add_input_map::<u64, u64, i64, _>(|v, u| {
*v = ((*v as i64) + *u) as u64;
});
if Runtime::worker_index() == 0 {
let runtime = Runtime::runtime().unwrap();
let ready_tx = ready_tx.clone();
let task_done_tx = task_done_tx.clone();
runtime.tokio_merger_runtime().unwrap().spawn(async move {
TOKIO_WORKER_INDEX
.scope(0, async move {
let _ = ready_tx.send(());
// Hammer the accessor. Each batch of sync calls
// maximizes the chance of landing inside `lock()`
// when `RuntimeHandle::join` would (with the bug)
// hold the mutex across the runtime drop. Exits
// when the accessor returns `None` after `take()`.
'outer: loop {
for _ in 0..1000 {
if runtime.tokio_merger_runtime().is_none() {
break 'outer;
}
}
tokio::task::yield_now().await;
}
let _ = task_done_tx.send(());
})
.await;
});
}
Ok(())
})
.unwrap();

ready_rx
.recv_timeout(Duration::from_secs(5))
.expect("merger task did not start");

let (drop_done_tx, drop_done_rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
drop(handle);
let _ = drop_done_tx.send(());
});

drop_done_rx
.recv_timeout(Duration::from_secs(30))
.expect("DBSPHandle::drop deadlocked");
task_done_rx
.recv_timeout(Duration::from_secs(5))
.expect("merger task did not exit cleanly via the None arm");
}

// Kill the runtime.
#[test]
fn test_kill1() {
Expand Down
30 changes: 19 additions & 11 deletions crates/dbsp/src/circuit/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1316,16 +1316,19 @@ impl Runtime {
self.inner().panicked.store(true, Ordering::Release);
}

/// Tokio merger runtime associated with this DBSP runtime.
pub(crate) fn tokio_merger_runtime(&self) -> tokio::runtime::Handle {
/// Handle to the tokio merger runtime associated with this DBSP runtime.
///
/// Returns `None` if the runtime has already been torn down. Callers may
/// race `RuntimeHandle::join`, which takes the runtime out of its slot
/// before dropping it; an in-flight merger task that reaches this accessor
/// after the take observes `None` and should bail out of its work.
pub(crate) fn tokio_merger_runtime(&self) -> Option<tokio::runtime::Handle> {
self.inner()
.tokio_merger_runtime
.lock()
.unwrap()
.as_ref()
.expect("tokio merger runtime has been shut down")
.handle()
.clone()
.map(|rt| rt.handle().clone())
}

/// Takes and returns the TCP listener socket configured via
Expand Down Expand Up @@ -1523,17 +1526,22 @@ impl RuntimeHandle {
});

// Terminate the tokio merger runtime.
if let Some(tokio_merger_runtime) = self
//
// The `MutexGuard` returned by `lock()` must be dropped before the
// tokio runtime: dropping the runtime blocks until every blocking-pool
// task yields, and those tasks may call `tokio_merger_runtime()`, which
// re-locks this same mutex. Holding the guard across the runtime drop
// would deadlock. Binding `take()` to a `let` releases the guard at the
// `;`, leaving an owned `Option<TokioRuntime>` whose drop runs without
// the mutex held.
let tokio_merger_runtime = self
.runtime
.inner()
.tokio_merger_runtime
.lock()
.unwrap()
.take()
{
// Block until all running merger tasks have yielded. At this point, the tokio runtime will have shut down automatically.
drop(tokio_merger_runtime);
}
.take();
drop(tokio_merger_runtime);
Comment thread
gz marked this conversation as resolved.
Resolved
Comment thread
gz marked this conversation as resolved.
Resolved

// This must happen after we wait for the background threads, because
// they might try to initiate another merge before they exit, which
Expand Down
11 changes: 10 additions & 1 deletion crates/dbsp/src/trace/spine_async.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ use tokio::{
sync::{Notify, futures::OwnedNotified},
task::yield_now,
};
use tracing::trace;
mod index_set;
mod list_merger;
mod push_merger;
Expand Down Expand Up @@ -1115,7 +1116,15 @@ where

fn run(self: Arc<Self>, level: usize) {
let local_worker_offset = self.worker_index - self.runtime.layout().local_workers().start;
self.runtime.tokio_merger_runtime().spawn(async move {
// The merger runtime may have been torn down already if a concurrent
// `RuntimeHandle::join` reached the take of its slot first. In that case
// there is no work to do: workers exiting will set `request_exit` and
// any new spawn would just observe it and quit.
let Some(handle) = self.runtime.tokio_merger_runtime() else {
Comment thread
gz marked this conversation as resolved.
Resolved
trace!(level, "merger spawn skipped: runtime torn down");
return;
};
handle.spawn(async move {
let buffer_cache = self
.runtime
.get_buffer_cache(local_worker_offset, ThreadType::Background);
Expand Down
44 changes: 36 additions & 8 deletions js-packages/profiler-layout/src/lib/functions/processZipBundle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,40 @@ const circuitProfileRegex = /circuit_profile\.json$/
const dataflowGraphRegex = /dataflow_graph\.json$/
const pipelineConfigRegex = /pipeline_config\.json$/

// New bundle layout (since support-bundle metadata_version 1): each collection
// lives under a directory named after its timestamp, e.g.
// "2026-05-25T12-34-56.789Z/circuit_profile.json". Collisions get a "-N" suffix
// on the directory. The directory may be placed in a nested directory
// (e.g. "support/2026-05-25T12-34-56.789Z/circuit_profile.json"),
// so we match the timestamp segment anywhere in the path, not only at the start.
const collectionDirRegex =
/(?:^|\/)(\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(?:\.\d+)?Z(?:-\d+)?)\//

// Legacy layout: files were named "<ISO_TIMESTAMP>_<file>", optionally inside
// a sub-path, e.g. "2026-01-19T12:55:54.152834443+00:00_logs.txt".
const legacyTimestampPrefixRegex = /(?:^|\/)(\d{4}-\d{2}-\d{2}T[^/_]+)_/

/** Group key identifying one collection. Empty string means "not a collection file". */
function collectionKey(filename: string): string {
return (
filename.match(collectionDirRegex)?.[1] ??
filename.match(legacyTimestampPrefixRegex)?.[1] ??
''
)
}

/** Parse a collection key back into a Date for sorting and display. */
function collectionDate(key: string): Date {
// New keys use '-' between hours/minutes/seconds; JavaScript's Date parser
// wants ':', so rewrite the time portion. The trailing "-N" collision suffix
// (if any) is dropped — it carries no temporal information.
const m = key.match(/^(\d{4}-\d{2}-\d{2})T(\d{2})-(\d{2})-(\d{2})(\.\d+)?Z/)
if (m) {
return new Date(`${m[1]}T${m[2]}:${m[3]}:${m[4]}${m[5] ?? ''}Z`)
}
return new Date(key)
}

export interface ProcessedProfile {
profile: JsonProfiles
dataflow?: Dataflow
Expand All @@ -30,20 +64,14 @@ export function getSuitableProfiles(zipData: Uint8Array): [Date, ZipItem[]][] {
)
}

const profileTimestamps = groupBy(
profileFiles,
// group by file timestamp; all files in a bundle are named with names like TIMESTAMP_FILENAME
// where TIMESTAMP is an ISO 8601 timestamp
// Examples: "2026-01-19T12:55:54.152834443+00:00_logs.txt", "some/path/2026-01-19T12:55:54.152834443+00:00_logs.txt"
(file) => file.filename.match(/(?:^|\/)(\d{4}-\d{2}-\d{2}T[^/_]+)_/)?.[1] ?? ''
).filter(
const profileTimestamps = groupBy(profileFiles, (file) => collectionKey(file.filename)).filter(
(group) => group[0] && group[1].some((file) => circuitProfileRegex.test(file.filename))
// Pipeline config and dataflow graph are not required
)

return sortOn(
profileTimestamps.map(
([timestamp, files]) => [new Date(timestamp), files] as [Date, ZipItem[]]
([key, files]) => [collectionDate(key), files] as [Date, ZipItem[]]
),
(p) => p[0]
)
Expand Down
Loading