diff --git a/Cargo.lock b/Cargo.lock
index edf87d21b..0af80a080 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -259,6 +259,8 @@ dependencies = [
"plurality 0.2.4",
"scopeguard",
"seismograph",
+ "seismograph_protocol",
+ "seismograph_runtime",
"static_assertions",
"testing_aids",
"thread_aware",
diff --git a/crates/anyspawn/tests/arty.rs b/crates/anyspawn/tests/arty.rs
index b4a27d458..6210702cf 100644
--- a/crates/anyspawn/tests/arty.rs
+++ b/crates/anyspawn/tests/arty.rs
@@ -13,7 +13,7 @@ use std::time::Duration;
use anyspawn::{JoinHandle, Spawner};
use arty::runtime::hook::Panic;
-use arty::runtime::{Runtime, WorkersPolicy};
+use arty::runtime::{MonitorPolicy, Runtime, WorkersPolicy};
use futures::future::join_all;
use thread_aware::{Thread, ThreadAware};
@@ -31,7 +31,11 @@ impl ThreadAware for RelocationProbe {
}
fn runtime_and_spawner() -> (Runtime, Spawner) {
- let runtime = Runtime::builder().workers(WorkersPolicy::exactly(1)).build().unwrap();
+ let runtime = Runtime::builder()
+ .monitor(MonitorPolicy::disabled())
+ .workers(WorkersPolicy::exactly(1))
+ .build()
+ .unwrap();
let scheduler = runtime.scheduler().block_on(async |cx| cx.scheduler().clone()).unwrap();
let spawner = Spawner::new_arty(scheduler);
(runtime, spawner)
@@ -83,7 +87,11 @@ fn arty_relocation_round_trip_rebinds_to_destination_worker() {
if many_cpus::SystemHardware::current().processors().len() < 2 {
return;
}
- let runtime_a = Runtime::builder().workers(WorkersPolicy::exactly(2)).build().unwrap();
+ let runtime_a = Runtime::builder()
+ .monitor(MonitorPolicy::disabled())
+ .workers(WorkersPolicy::exactly(2))
+ .build()
+ .unwrap();
let (mut spawner, source, destination) = runtime_a
.scheduler()
.block_on(async |cx| {
@@ -97,7 +105,11 @@ fn arty_relocation_round_trip_rebinds_to_destination_worker() {
.unwrap();
let original = spawner.clone();
- let runtime_b = Runtime::builder().workers(WorkersPolicy::exactly(1)).build().unwrap();
+ let runtime_b = Runtime::builder()
+ .monitor(MonitorPolicy::disabled())
+ .workers(WorkersPolicy::exactly(1))
+ .build()
+ .unwrap();
let foreign = runtime_b.scheduler().block_on(async |cx| cx.thread().clone()).unwrap();
spawner.relocate(Some(&source), &foreign);
@@ -112,7 +124,11 @@ fn arty_relocation_round_trip_rebinds_to_destination_worker() {
#[test]
fn arty_spawn_anywhere_relocates_payload_before_factory() {
- let runtime = Runtime::builder().workers(WorkersPolicy::exactly(1)).build().unwrap();
+ let runtime = Runtime::builder()
+ .monitor(MonitorPolicy::disabled())
+ .workers(WorkersPolicy::exactly(1))
+ .build()
+ .unwrap();
let scheduler = runtime.scheduler().block_on(async |cx| cx.scheduler().clone()).unwrap();
let spawner = Spawner::new_arty(scheduler);
@@ -138,6 +154,7 @@ fn arty_spawn_blocking_returns_output() {
#[test]
fn arty_task_panics_return_join_errors() {
let runtime = Runtime::builder()
+ .monitor(MonitorPolicy::disabled())
.workers(WorkersPolicy::exactly(1))
.on(Panic::IGNORE)
.build()
@@ -209,7 +226,11 @@ fn arty_spawner_debug_names_the_runtime() {
#[test]
fn arty_builder_preserves_the_worker_association() {
- let runtime = Runtime::builder().workers(WorkersPolicy::exactly(1)).build().unwrap();
+ let runtime = Runtime::builder()
+ .monitor(MonitorPolicy::disabled())
+ .workers(WorkersPolicy::exactly(1))
+ .build()
+ .unwrap();
let (scheduler, expected) = runtime
.scheduler()
.block_on(async |cx| (cx.scheduler().clone(), thread::current().id()))
diff --git a/crates/anyspawn/tests/observed.rs b/crates/anyspawn/tests/observed.rs
index 01aa27f80..f03ea986f 100644
--- a/crates/anyspawn/tests/observed.rs
+++ b/crates/anyspawn/tests/observed.rs
@@ -200,6 +200,7 @@ fn pending_task_does_not_leak_context_on_the_same_thread() {
#[test]
fn arty_transfers_context_for_all_spawn_methods() {
let runtime = arty::runtime::Runtime::builder()
+ .monitor(arty::runtime::MonitorPolicy::disabled())
.workers(arty::runtime::WorkersPolicy::exactly(1))
.build()
.unwrap();
@@ -229,6 +230,7 @@ fn arty_relocates_data_before_the_observed_factory() {
}
let runtime = arty::runtime::Runtime::builder()
+ .monitor(arty::runtime::MonitorPolicy::disabled())
.workers(arty::runtime::WorkersPolicy::exactly(1))
.build()
.unwrap();
diff --git a/crates/arty/Cargo.toml b/crates/arty/Cargo.toml
index 1138bf021..31b121238 100644
--- a/crates/arty/Cargo.toml
+++ b/crates/arty/Cargo.toml
@@ -36,7 +36,13 @@ all-features = true
[features]
default = ["rt", "macros", "monitor"]
macros = ["rt", "dep:arty_macros"]
-monitor = ["dep:seismograph", "seismograph/monitor", "performables?/seismograph"]
+monitor = [
+ "dep:seismograph",
+ "dep:seismograph_runtime",
+ "arty_executor?/inspection",
+ "seismograph/monitor",
+ "performables?/seismograph",
+]
rt = [
"dep:arty_executor",
"dep:arty_io_host",
@@ -73,12 +79,13 @@ pin-project = { workspace = true, optional = true }
plurality = { workspace = true, features = ["std"], optional = true }
scopeguard = { workspace = true }
seismograph = { workspace = true, optional = true }
+seismograph_runtime = { workspace = true, optional = true }
thread_aware = { workspace = true, features = ["std", "derive"], optional = true }
thread_aware_core = { workspace = true, features = ["std"] }
tick = { workspace = true }
[dev-dependencies]
-arty_executor = { path = "../arty_executor" }
+arty_executor = { path = "../arty_executor", features = ["inspection"] }
arty_io_host = { path = "../arty_io_host" }
arty_macros = { path = "../arty_macros" }
bolero = { workspace = true, features = ["std"] }
@@ -98,6 +105,8 @@ performables = { path = "../performables", features = ["seismograph"] }
pin-project = { workspace = true }
plurality = { path = "../plurality", features = ["std"] }
seismograph = { path = "../seismograph", features = ["monitor"] }
+seismograph_protocol = { path = "../seismograph_protocol", features = ["test-util"] }
+seismograph_runtime = { path = "../seismograph_runtime", features = ["test-util"] }
static_assertions = { workspace = true }
testing_aids = { path = "../testing_aids" }
thread_aware = { path = "../thread_aware", features = ["std", "derive", "test-utils"] }
@@ -122,6 +131,16 @@ name = "arty_contention"
harness = false
required-features = ["rt"]
+[[bench]]
+name = "arty_inspection"
+harness = false
+required-features = ["rt"]
+
+[[bench]]
+name = "arty_spawn_allocations"
+harness = false
+required-features = ["rt"]
+
[[example]]
name = "arty_advanced"
required-features = ["rt"]
diff --git a/crates/arty/README.md b/crates/arty/README.md
index cdeefda51..2eb773982 100644
--- a/crates/arty/README.md
+++ b/crates/arty/README.md
@@ -65,11 +65,13 @@ The default feature set enables `rt`, `macros`, and `monitor`.
* `rt`: Enables the runtime, task, and I/O APIs.
* `macros`: Enables [`main`][__link13] and [`test`][__link14]. It also enables `rt`.
-* `monitor`: Enables the Seismograph monitor dependency. It forwards
- monitoring support for `performables` when `performables` is enabled. It does
- not start monitoring or emit new telemetry.
+* `monitor`: Connects runtime workers and tasks to Seismograph. An enabled
+ [`MonitorPolicy`][__link15] starts a local connection for
+ the Seismograph CLI. Task collection runs on request. Event recording stays
+ off until an application or the CLI enables it. This feature also forwards
+ monitoring support for `performables` when `performables` is enabled.
* `test-util`: Enables testing utilities, including
- [`ClockControl`][__link15].
+ [`ClockControl`][__link16].
Enable it in dev-dependencies, not production dependencies.
@@ -78,7 +80,7 @@ The default feature set enables `rt`, `macros`, and `monitor`.
This crate was developed as part of The Oxidizer Project. Browse this crate's source code.
- [__cargo_doc2readme_dependencies_info]: ggGmYW0CYXZlMC43LjNhdIQborR2_k_xJd4bTcf2krrNPIcbP72Pw1UdRjkbim_eMDe2BBthYvRhcoQbQL336xbftBwb3WEJKMJ3SngbyR3bGBAhBb0b0RYBQT1d6EhhZIKCZGFydHllMC42LjGCa2FydHlfbWFjcm9zZTAuNi4x
+ [__cargo_doc2readme_dependencies_info]: ggGmYW0CYXZlMC43LjNhdIQborR2_k_xJd4bTcf2krrNPIcbP72Pw1UdRjkbim_eMDe2BBthYvRhcoQbpjTzkOovhJgb4j8Xd8b5dycb1Kf_wRXWtfYbr0QtKZVggRRhZIKCZGFydHllMC42LjGCa2FydHlfbWFjcm9zZTAuNi4x
[__link0]: https://doc.rust-lang.org/stable/std/marker/trait.Send.html
[__link1]: https://docs.rs/arty/0.6.1/arty/?search=core::ThreadAware
[__link10]: https://docs.rs/arty/0.6.1/arty/core/index.html
@@ -86,7 +88,8 @@ This crate was developed as part of &'static str {
+ match self {
+ Self::Disabled => "disabled",
+ #[cfg(feature = "monitor")]
+ Self::Idle => "idle",
+ #[cfg(feature = "monitor")]
+ Self::Collecting => "collecting",
+ #[cfg(feature = "monitor")]
+ Self::Recording => "recording",
+ }
+ }
+}
+
+#[derive(Clone, Copy)]
+enum Workload {
+ LocalSpawn,
+ RepeatedPoll,
+ RemoteBatch,
+ BlockingBatch,
+}
+
+impl Workload {
+ const ALL: [Self; 4] = [Self::LocalSpawn, Self::RepeatedPoll, Self::RemoteBatch, Self::BlockingBatch];
+
+ fn name(self) -> &'static str {
+ match self {
+ Self::LocalSpawn => "local_spawn_w1",
+ Self::RepeatedPoll => "repeated_poll_w1",
+ Self::RemoteBatch => "remote_batch_w4",
+ Self::BlockingBatch => "blocking_batch_w4",
+ }
+ }
+}
+
+struct Case {
+ runtime: Runtime,
+ handles: Vec>,
+ collector: Option>,
+ stop: Arc,
+ captures: Arc,
+}
+
+impl Case {
+ fn new(mode: Mode, workload: Workload) -> Self {
+ #[cfg(feature = "monitor")]
+ seismograph::recorder(Configuration::default());
+ let workers = if matches!(workload, Workload::RemoteBatch | Workload::BlockingBatch) {
+ 4
+ } else {
+ 1
+ };
+ let policy = if matches!(mode, Mode::Disabled) {
+ MonitorPolicy::disabled()
+ } else {
+ MonitorPolicy::enabled()
+ };
+ let runtime = Runtime::builder()
+ .workers(WorkersPolicy::exactly(workers))
+ .blocking_pool(BlockingPoolPolicy::shared().max(4))
+ .monitor(policy)
+ .build()
+ .expect("benchmark runtime configuration is valid");
+ let stop = Arc::new(AtomicBool::new(false));
+ let captures = Arc::new(AtomicU64::new(0));
+ #[cfg(feature = "monitor")]
+ let collector = matches!(mode, Mode::Collecting).then(|| {
+ let stop = Arc::clone(&stop);
+ let captures = Arc::clone(&captures);
+ let (ready, started) = mpsc::sync_channel(1);
+ let collector = thread::spawn(move || {
+ black_box(seismograph::snapshot(SnapshotOptions::default()).expect("benchmark collection succeeds"));
+ captures.fetch_add(1, Ordering::Relaxed);
+ ready.send(()).expect("benchmark caller waits for collection");
+ while !stop.load(Ordering::Acquire) {
+ thread::park_timeout(Duration::from_millis(10));
+ black_box(seismograph::snapshot(SnapshotOptions::default()).expect("benchmark collection succeeds"));
+ captures.fetch_add(1, Ordering::Relaxed);
+ }
+ });
+ started
+ .recv_timeout(Duration::from_secs(5))
+ .expect("benchmark collector must complete its first snapshot before measurement");
+ collector
+ });
+ #[cfg(not(feature = "monitor"))]
+ let collector = None;
+ #[cfg(feature = "monitor")]
+ if matches!(mode, Mode::Recording) {
+ seismograph::recorder(Configuration {
+ runtime_tasks: Policy::all(false),
+ ..Configuration::default()
+ });
+ }
+ let mut case = Self {
+ runtime,
+ handles: Vec::with_capacity(usize::try_from(OPERATIONS).expect("64 operations fit in usize")),
+ collector,
+ stop,
+ captures,
+ };
+ black_box(case.run(workload, 4));
+ case
+ }
+
+ fn run(&mut self, workload: Workload, iterations: u64) -> Duration {
+ let start = Instant::now();
+ match workload {
+ Workload::LocalSpawn => {
+ let task = self
+ .runtime
+ .scheduler()
+ .spawn_anywhere(iterations * OPERATIONS, |cx, operations| async move {
+ for _ in 0..operations {
+ cx.scheduler()
+ .spawn(async |_| black_box(()))
+ .await
+ .expect("benchmark child succeeds");
+ }
+ });
+ futures::executor::block_on(task).expect("benchmark parent succeeds");
+ }
+ Workload::RepeatedPoll => {
+ let task = self
+ .runtime
+ .scheduler()
+ .spawn_anywhere(iterations * OPERATIONS, |_, operations| RepeatedPoll(operations));
+ futures::executor::block_on(task).expect("benchmark task succeeds");
+ }
+ Workload::RemoteBatch | Workload::BlockingBatch => {
+ for _ in 0..iterations {
+ self.handles.clear();
+ for _ in 0..OPERATIONS {
+ let task = if matches!(workload, Workload::RemoteBatch) {
+ self.runtime.scheduler().spawn_anywhere((), |_, ()| async { black_box(()) })
+ } else {
+ self.runtime.scheduler().spawn_blocking(|| black_box(()))
+ };
+ self.handles.push(task);
+ }
+ for task in &mut self.handles {
+ futures::executor::block_on(black_box(task)).expect("benchmark task succeeds");
+ }
+ }
+ }
+ }
+ start.elapsed()
+ }
+}
+
+impl Drop for Case {
+ fn drop(&mut self) {
+ self.stop.store(true, Ordering::Release);
+ if let Some(collector) = self.collector.take() {
+ collector.thread().unpark();
+ collector.join().expect("benchmark diagnostic caller succeeds");
+ eprintln!("Completed process snapshots: {}", self.captures.load(Ordering::Relaxed));
+ }
+ #[cfg(feature = "monitor")]
+ seismograph::recorder(Configuration::default());
+ }
+}
+
+struct RepeatedPoll(u64);
+
+impl Future for RepeatedPoll {
+ type Output = ();
+
+ fn poll(mut self: Pin<&mut Self>, cx: &mut PollContext<'_>) -> Poll<()> {
+ if self.0 == 0 {
+ Poll::Ready(())
+ } else {
+ self.0 = black_box(self.0 - 1);
+ cx.waker().wake_by_ref();
+ Poll::Pending
+ }
+ }
+}
+
+fn benchmarks(criterion: &mut Criterion) {
+ let mut group = criterion.benchmark_group("arty_inspection/tasks");
+ group.throughput(Throughput::Elements(OPERATIONS));
+ for workload in Workload::ALL {
+ for &mode in Mode::ALL {
+ let mut case = None;
+ group.bench_function(BenchmarkId::new(workload.name(), mode.name()), |bencher| {
+ let case = case.get_or_insert_with(|| Case::new(mode, workload));
+ bencher.iter_custom(|iterations| case.run(workload, iterations));
+ });
+ }
+ }
+ group.finish();
+}
+
+criterion_group! {
+ name = inspection;
+ config = Criterion::default()
+ .sample_size(50)
+ .warm_up_time(Duration::from_secs(1))
+ .measurement_time(Duration::from_secs(3));
+ targets = benchmarks
+}
+criterion_main!(inspection);
diff --git a/crates/arty/benches/arty_spawn_allocations.rs b/crates/arty/benches/arty_spawn_allocations.rs
new file mode 100644
index 000000000..ef38b0eb8
--- /dev/null
+++ b/crates/arty/benches/arty_spawn_allocations.rs
@@ -0,0 +1,182 @@
+// Copyright (c) Microsoft Corporation.
+// Licensed under the MIT License.
+
+//! Measures warmed task spawning with Metabench.
+//!
+//! Run with `--criterion --allocations`. Metabench runs allocation cases in
+//! separate processes. To exclude monitoring dependencies, use a separate
+//! package with Arty as a normal, runtime-only dependency.
+//! Arty's own dev-dependencies can enable monitoring through feature unification.
+//! Runtime setup and warm-up are excluded.
+//! Unrelated process threads can contribute allocations. The local case measures
+//! 4096 sequential children in one parent. The remote case measures 64 batches
+//! of 64 tasks on four workers, including dispatch and joins. The blocking case
+//! uses the same batches and one blocking worker. Reports show totals per
+//! 4096-task workload, not per task.
+//! The blocking backlog case queues 4096 tasks behind a gate. Its timer covers
+//! releasing the gate and joining all tasks, but excludes submission.
+//! Its allocation counts include the gate and its task.
+
+use std::borrow::BorrowMut;
+use std::hint::black_box;
+use std::sync::{Arc, Barrier};
+use std::time::{Duration, Instant};
+
+use arty::runtime::{BlockingPoolPolicy, MonitorPolicy, Runtime, WorkersPolicy};
+use arty::task::JoinHandle;
+use criterion::{BenchmarkId, Criterion, Throughput};
+use metabench::benchmark;
+
+#[derive(Clone, Copy, Debug)]
+enum Workload {
+ Local,
+ Remote,
+ Blocking,
+ BlockingBacklog,
+}
+
+impl Workload {
+ const fn name(self) -> &'static str {
+ match self {
+ Self::Local => "local",
+ Self::Remote => "remote",
+ Self::Blocking => "blocking",
+ Self::BlockingBacklog => "blocking_backlog",
+ }
+ }
+}
+
+#[derive(Debug)]
+struct Case {
+ runtime: Runtime,
+ handles: Vec>,
+ workload: Workload,
+}
+
+impl Case {
+ fn new(workload: Workload, enabled: bool) -> Self {
+ let runtime = Runtime::builder()
+ .workers(WorkersPolicy::exactly(if matches!(workload, Workload::Local) { 1 } else { 4 }))
+ .blocking_pool(BlockingPoolPolicy::shared().max(1))
+ .monitor(if enabled {
+ MonitorPolicy::enabled()
+ } else {
+ MonitorPolicy::disabled()
+ })
+ .build()
+ .expect("benchmark requires the configured worker count");
+ let mut case = Self {
+ runtime,
+ handles: Vec::with_capacity(if matches!(workload, Workload::BlockingBacklog) { 4096 } else { 64 }),
+ workload,
+ };
+ black_box(case.run());
+ case
+ }
+
+ fn run(&mut self) -> Duration {
+ if matches!(self.workload, Workload::BlockingBacklog) {
+ self.handles.clear();
+ let gate = Arc::new(Barrier::new(2));
+ let worker_gate = Arc::clone(&gate);
+ let first = self.runtime.scheduler().spawn_blocking(move || {
+ worker_gate.wait();
+ });
+ for _ in 0..4096 {
+ self.handles.push(self.runtime.scheduler().spawn_blocking(|| black_box(())));
+ }
+ let start = Instant::now();
+ gate.wait();
+ futures::executor::block_on(first).expect("benchmark gate succeeds");
+ for task in &mut self.handles {
+ futures::executor::block_on(task).expect("benchmark task succeeds");
+ }
+ return start.elapsed();
+ }
+ let start = Instant::now();
+ match self.workload {
+ Workload::Local => {
+ let parent = self.runtime.scheduler().spawn_anywhere((), |cx, ()| async move {
+ for _ in 0..4096 {
+ cx.scheduler()
+ .spawn(async |_| black_box(()))
+ .await
+ .expect("benchmark child succeeds");
+ }
+ });
+ futures::executor::block_on(parent).expect("benchmark parent succeeds");
+ }
+ Workload::Remote | Workload::Blocking | Workload::BlockingBacklog => {
+ for _ in 0..64 {
+ self.handles.clear();
+ for _ in 0..64 {
+ let task = match self.workload {
+ Workload::Blocking => self.runtime.scheduler().spawn_blocking(|| black_box(())),
+ Workload::Remote => self.runtime.scheduler().spawn_anywhere((), |_, ()| async { black_box(()) }),
+ Workload::Local | Workload::BlockingBacklog => unreachable!("local and backlog spawning use separate paths"),
+ };
+ self.handles.push(task);
+ }
+ for task in &mut self.handles {
+ futures::executor::block_on(task).expect("benchmark task succeeds");
+ }
+ }
+ }
+ }
+ start.elapsed()
+ }
+}
+
+fn configured_criterion() -> Criterion {
+ Criterion::default()
+ .sample_size(50)
+ .warm_up_time(Duration::from_millis(500))
+ .measurement_time(Duration::from_secs(2))
+}
+
+fn criterion_benchmarks(criterion: &mut Criterion) {
+ let mut group = criterion.benchmark_group(SPAWN.group_name());
+ group.throughput(Throughput::Elements(4096));
+ for workload in [Workload::Local, Workload::Remote, Workload::Blocking, Workload::BlockingBacklog] {
+ for enabled in [true, false] {
+ let mode = if enabled { "idle" } else { "disabled" };
+ group.bench_function(
+ BenchmarkId::new(SPAWN.benchmark_name(), format!("{}_{mode}", workload.name())),
+ |bencher| {
+ let mut case = Case::new(workload, enabled);
+ bencher.iter_custom(|iterations| {
+ let mut elapsed = Duration::ZERO;
+ for _ in 0..iterations {
+ elapsed += spawn_workload(&mut case).0;
+ }
+ elapsed
+ });
+ },
+ );
+ }
+ }
+ group.finish();
+}
+
+#[benchmark(SPAWN, "arty_spawn_allocations/tasks", "spawn")]
+#[bench::local_idle(Box::new(Case::new(Workload::Local, true)))]
+#[bench::local_disabled(Box::new(Case::new(Workload::Local, false)))]
+#[bench::remote_idle(Box::new(Case::new(Workload::Remote, true)))]
+#[bench::remote_disabled(Box::new(Case::new(Workload::Remote, false)))]
+#[bench::blocking_idle(Box::new(Case::new(Workload::Blocking, true)))]
+#[bench::blocking_disabled(Box::new(Case::new(Workload::Blocking, false)))]
+#[bench::blocking_backlog_idle(Box::new(Case::new(Workload::BlockingBacklog, true)))]
+#[bench::blocking_backlog_disabled(Box::new(Case::new(Workload::BlockingBacklog, false)))]
+fn spawn_workload>(mut input: S) -> (Duration, S) {
+ let elapsed = input.borrow_mut().run();
+ (elapsed, input)
+}
+
+metabench::main!(
+ criterion = {
+ factory = configured_criterion,
+ benchmarks = criterion_benchmarks,
+ unit = "ns",
+ },
+ benchmarks = [SPAWN],
+);
diff --git a/crates/arty/src/io/handle.rs b/crates/arty/src/io/handle.rs
index 680d77d9c..d8b608978 100644
--- a/crates/arty/src/io/handle.rs
+++ b/crates/arty/src/io/handle.rs
@@ -275,7 +275,10 @@ mod tests {
#[test]
fn blocking_marker_io_lookup_survives_scheduler_slot_teardown() {
- let runtime = crate::runtime::Runtime::new().unwrap();
+ let runtime = crate::runtime::Runtime::builder()
+ .monitor(crate::runtime::MonitorPolicy::disabled())
+ .build()
+ .unwrap();
let context = runtime.scheduler().block_on(async |cx| cx).unwrap();
let scheduler = context.scheduler().clone();
let io = context.io().clone();
diff --git a/crates/arty/src/lib.rs b/crates/arty/src/lib.rs
index 51398af2d..7b9df475c 100644
--- a/crates/arty/src/lib.rs
+++ b/crates/arty/src/lib.rs
@@ -70,13 +70,18 @@
//!
//! - `rt`: Enables the runtime, task, and I/O APIs.
//! - `macros`: Enables [`main`] and [`test`]. It also enables `rt`.
-//! - `monitor`: Enables the Seismograph monitor dependency. It forwards
-//! monitoring support for `performables` when `performables` is enabled. It does
-//! not start monitoring or emit new telemetry.
+//! - `monitor`: Connects runtime workers and tasks to Seismograph. An enabled
+//! [`MonitorPolicy`](crate::runtime::MonitorPolicy) starts a local connection for
+//! the Seismograph CLI. Task collection runs on request. Event recording stays
+//! off until an application or the CLI enables it. This feature also forwards
+//! monitoring support for `performables` when `performables` is enabled.
//! - `test-util`: Enables testing utilities, including
//! [`ClockControl`](crate::time::ClockControl).
//! Enable it in dev-dependencies, not production dependencies.
+#[cfg(all(test, feature = "macros", feature = "monitor", not(miri)))]
+extern crate self as arty;
+
use arty_io_core as _;
/// Runs an async entry point on an Arty runtime.
///
@@ -103,7 +108,8 @@ use arty_io_core as _;
/// causes runtime construction to fail.
/// - `workers = all` starts one async worker per available processor.
/// - `monitor = enabled` or `monitor = disabled` selects whether the runtime
-/// is prepared for monitoring. The default is `enabled`.
+/// starts a local Seismograph monitor when the `monitor` feature is present.
+/// The default is `enabled`.
/// - `panic = shutdown` or `panic = ignore` selects whether the runtime stops
/// after Arty catches a task panic. The default is `shutdown`.
///
@@ -147,15 +153,6 @@ use arty_io_core as _;
/// # #[cfg(not(all(feature = "macros", feature = "rt")))] fn main() {}
/// ```
///
-/// Disable monitoring for the runtime:
-///
-/// ```
-/// # #[cfg(all(feature = "macros", feature = "rt"))]
-/// #[arty::main(monitor = disabled)]
-/// async fn main(_cx: arty::task::Context) {}
-/// # #[cfg(not(all(feature = "macros", feature = "rt")))] fn main() {}
-/// ```
-///
/// Keep the runtime running after a task panic that Arty catches:
///
/// ```
@@ -259,7 +256,7 @@ pub use arty_macros::main;
///
/// Enable monitoring for a test that exercises monitoring behavior:
///
-/// ```test_harness
+/// ```no_run,test_harness
/// # #[cfg(all(feature = "macros", feature = "rt"))]
/// #[arty::test(monitor = enabled)]
/// async fn monitored(_cx: arty::task::Context) {}
diff --git a/crates/arty/src/runtime/bootstrap/startup.rs b/crates/arty/src/runtime/bootstrap/startup.rs
index 0ebef1d2b..2176dacc8 100644
--- a/crates/arty/src/runtime/bootstrap/startup.rs
+++ b/crates/arty/src/runtime/bootstrap/startup.rs
@@ -25,7 +25,7 @@ fn build_with_processors(
thread_builder: &ThreadBuilder,
available: &ProcessorSet,
) -> Result {
- let (workers, shutdown) = prepare_workers(
+ let prepared = prepare_workers(
processor_config,
clock,
thread_builder,
@@ -33,19 +33,41 @@ fn build_with_processors(
|name| std::env::var(name).ok(),
asynchronous::start,
)?;
+ let workers = prepared.workers;
let dispatcher = DispatcherCore::new(
NonEmpty::from_vec(workers.iter().map(|worker| worker.endpoint().clone()).collect())
.expect("the number is either hardcoded or validated in the builder, so can never be zero"),
- shutdown,
+ prepared.shutdown,
);
let dispatcher_client = DispatcherClient::new(dispatcher);
+ #[cfg(feature = "monitor")]
+ dispatcher_client.set_diagnostics(
+ prepared
+ .diagnostics
+ .as_ref()
+ .map(crate::runtime::monitoring::RuntimeDiagnostics::handle),
+ );
let mut join_handles = Vec::with_capacity(workers.len());
for worker in workers {
join_handles.push(worker.activate(dispatcher_client.clone()));
}
let worker_joiner = WorkerJoiner::new(join_handles);
- Ok(Runtime::with_dispatcher(dispatcher_client, worker_joiner))
+ let runtime = Runtime::with_dispatcher(dispatcher_client, worker_joiner);
+ #[cfg(feature = "monitor")]
+ let runtime = {
+ let mut runtime = runtime;
+ runtime.set_diagnostics(prepared.diagnostics);
+ runtime
+ };
+ Ok(runtime)
+}
+
+struct PreparedWorkers {
+ workers: Vec,
+ shutdown: Shutdown,
+ #[cfg(feature = "monitor")]
+ diagnostics: Option,
}
fn prepare_workers(
@@ -55,12 +77,13 @@ fn prepare_workers(
available: &ProcessorSet,
environment: impl FnOnce(&str) -> Option,
mut start: impl FnMut(asynchronous::StartOptions) -> W,
-) -> Result<(Vec, Shutdown), Error> {
+) -> Result, Error> {
let name = processor_config.name;
name.validate()?;
let processors = processor_config.workers_policy.select(available)?;
- let mut workers = Vec::with_capacity(processors.len());
+ let worker_count = processors.len();
+ let mut workers = Vec::with_capacity(worker_count);
// Respect the RUST_MIN_STACK environment variable if set and larger than the configured stack size.
let stack_size = select_stack_size(processor_config.stack_size, environment);
@@ -69,6 +92,13 @@ fn prepare_workers(
let shutdown = Shutdown::default();
let io_runtime = IoRuntime::new(observed::Sink::noop());
let blocking_pools = processor_config.blocking_pool_policy.into_pools(name.clone())?;
+ #[cfg(feature = "monitor")]
+ let (diagnostics, monitor_options) = {
+ let diagnostics = crate::runtime::monitoring::RuntimeDiagnostics::start(monitor_options.policy(), &name, worker_count)?;
+ let mut monitor_options = monitor_options;
+ monitor_options.set_runtime(diagnostics.as_ref().map(crate::runtime::monitoring::RuntimeDiagnostics::handle));
+ (diagnostics, monitor_options)
+ };
for (worker_index, processor) in processors.into_iter().enumerate() {
workers.push(start(asynchronous::StartOptions {
@@ -86,7 +116,12 @@ fn prepare_workers(
}));
}
- Ok((workers, shutdown))
+ Ok(PreparedWorkers {
+ workers,
+ shutdown,
+ #[cfg(feature = "monitor")]
+ diagnostics,
+ })
}
fn select_stack_size(configured: std::num::NonZeroUsize, environment: impl FnOnce(&str) -> Option) -> usize {
@@ -128,7 +163,7 @@ mod tests {
fn nov4_startup_passes_the_selected_stack_size_to_each_native_worker_request() {
let hardware = many_cpus::SystemHardware::fake(HardwareBuilder::from_counts(NonZero::new(2).unwrap(), NonZero::new(1).unwrap()));
for environment in [None, Some("32769")] {
- let (requests, shutdown) = prepare_workers(
+ let prepared = prepare_workers(
RuntimeConfig {
name: crate::runtime::config::RuntimeName::default(),
workers_policy: WorkersPolicy::at_most(2),
@@ -147,6 +182,8 @@ mod tests {
|request| request,
)
.unwrap();
+ let requests = prepared.workers;
+ let shutdown = prepared.shutdown;
assert_eq!(requests.len(), 2);
assert!(
requests
@@ -260,7 +297,7 @@ mod tests {
let hardware = fake_hardware(PROCESSORS);
let runtime = runtime_with_processors(
WorkersPolicy::exactly(WORKERS),
- MonitorPolicy::enabled().into(),
+ MonitorPolicy::disabled().into(),
&hardware.processors(),
);
let cx = runtime.scheduler().block_on(async |cx| cx).unwrap();
diff --git a/crates/arty/src/runtime/builder.rs b/crates/arty/src/runtime/builder.rs
index 132c8fe04..44d4b35cb 100644
--- a/crates/arty/src/runtime/builder.rs
+++ b/crates/arty/src/runtime/builder.rs
@@ -42,7 +42,7 @@ pub struct RuntimeBuilder {
}
impl RuntimeBuilder {
- /// Sets the runtime name used in worker thread names.
+ /// Sets the runtime name used in worker thread names and monitoring.
///
/// Async threads use `-async-`, with indices starting at zero.
/// Shared blocking pools use `-blocking-`.
@@ -89,7 +89,9 @@ impl RuntimeBuilder {
///
/// The default is [`MonitorPolicy::enabled`]. The `monitor` Cargo feature
/// enables the Seismograph dependencies that monitoring needs.
- /// This choice does not start a monitor or add task measurements.
+ /// Building an enabled runtime starts a local connection for the Seismograph CLI.
+ /// Task collection runs on request. This does not enable event recording or
+ /// change which tasks run. See the [monitoring guide](crate::runtime#monitoring).
///
/// # Examples
///
@@ -217,6 +219,7 @@ impl RuntimeBuilder {
///
/// Returns [`Error`] if the worker count or blocking-pool limit is zero,
/// or if the runtime name contains a null character (`\0`).
+ /// With monitoring enabled, also returns an error if the local monitor cannot start.
///
/// # Panics
///
diff --git a/crates/arty/src/runtime/config/monitor_options.rs b/crates/arty/src/runtime/config/monitor_options.rs
index 2922d37ac..2745207ed 100644
--- a/crates/arty/src/runtime/config/monitor_options.rs
+++ b/crates/arty/src/runtime/config/monitor_options.rs
@@ -7,6 +7,8 @@ use crate::runtime::config::MonitorPolicy;
#[derive(Clone, Debug)]
pub(crate) struct MonitorOptions {
policy: MonitorPolicy,
+ #[cfg(feature = "monitor")]
+ runtime: Option,
}
impl MonitorOptions {
@@ -19,6 +21,16 @@ impl MonitorOptions {
pub(crate) const fn policy(&self) -> &MonitorPolicy {
&self.policy
}
+
+ #[cfg(feature = "monitor")]
+ pub(crate) fn set_runtime(&mut self, runtime: Option) {
+ self.runtime = runtime;
+ }
+
+ #[cfg(feature = "monitor")]
+ pub(crate) fn runtime(&self) -> Option<&seismograph_runtime::RuntimeHandle> {
+ self.runtime.as_ref()
+ }
}
impl Default for MonitorOptions {
@@ -29,7 +41,11 @@ impl Default for MonitorOptions {
impl From for MonitorOptions {
fn from(policy: MonitorPolicy) -> Self {
- Self { policy }
+ Self {
+ policy,
+ #[cfg(feature = "monitor")]
+ runtime: None,
+ }
}
}
diff --git a/crates/arty/src/runtime/config/monitor_policy.rs b/crates/arty/src/runtime/config/monitor_policy.rs
index d336a348e..dad7fcbb7 100644
--- a/crates/arty/src/runtime/config/monitor_policy.rs
+++ b/crates/arty/src/runtime/config/monitor_policy.rs
@@ -8,11 +8,13 @@
/// The enabled policy is the default.
///
/// The `monitor` Cargo feature enables the Seismograph dependencies that
-/// monitoring needs. This choice does not start a monitor or add task measurements.
+/// monitoring needs. Building an enabled runtime starts a local monitor.
+/// Task collection and poll timing run only when requested. This policy does
+/// not enable event recording or install an allocator.
///
/// # Examples
///
-/// ```
+/// ```no_run
/// use arty::runtime::{MonitorPolicy, Runtime};
///
/// let runtime = Runtime::builder()
@@ -21,7 +23,6 @@
/// runtime.stop()?;
/// # Ok::<(), Box>(())
/// ```
-#[repr(transparent)]
#[derive(Debug, Clone)]
pub struct MonitorPolicy {
enabled: bool,
@@ -40,7 +41,6 @@ impl MonitorPolicy {
Self { enabled: false }
}
- #[cfg(test)]
pub(crate) const fn is_enabled(&self) -> bool {
self.enabled
}
diff --git a/crates/arty/src/runtime/config/runtime_name.rs b/crates/arty/src/runtime/config/runtime_name.rs
index e44b2919e..f5ba02dac 100644
--- a/crates/arty/src/runtime/config/runtime_name.rs
+++ b/crates/arty/src/runtime/config/runtime_name.rs
@@ -5,7 +5,7 @@ use std::sync::Arc;
use crate::runtime::error::Error;
-/// Creates thread names for one runtime.
+/// Names one runtime and its threads.
#[derive(Clone, Debug)]
pub(crate) struct RuntimeName(Arc);
@@ -14,6 +14,11 @@ impl RuntimeName {
Self(Arc::from(name.as_ref()))
}
+ #[cfg(feature = "monitor")]
+ pub(crate) fn as_str(&self) -> &str {
+ &self.0
+ }
+
pub(crate) fn async_worker(&self, index: usize) -> String {
format!("{}-async-{index}", self.0)
}
diff --git a/crates/arty/src/runtime/control.rs b/crates/arty/src/runtime/control.rs
index 6cd3281f6..d10c6d5c3 100644
--- a/crates/arty/src/runtime/control.rs
+++ b/crates/arty/src/runtime/control.rs
@@ -105,7 +105,7 @@ impl RuntimeControl {
/// ```
/// use arty::runtime::Runtime;
///
- /// let runtime = Runtime::new()?;
+ /// let runtime = Runtime::builder().build()?;
/// let control = runtime
/// .scheduler()
/// .block_on(async |cx| cx.control().clone())?;
diff --git a/crates/arty/src/runtime/dispatch/client.rs b/crates/arty/src/runtime/dispatch/client.rs
index 84f75d2ef..978e7d0bb 100644
--- a/crates/arty/src/runtime/dispatch/client.rs
+++ b/crates/arty/src/runtime/dispatch/client.rs
@@ -26,6 +26,16 @@ pub(crate) struct DispatcherClient {
}
impl DispatcherClient {
+ #[cfg(feature = "monitor")]
+ pub(crate) fn set_diagnostics(&self, runtime: Option) {
+ self.core.set_diagnostics(runtime);
+ }
+
+ #[cfg(feature = "monitor")]
+ pub(crate) fn register_task_provider(&self, thread: ThreadId, handle: &seismograph_runtime::worker::WorkerHandle) {
+ self.core.register_task_provider(thread, handle);
+ }
+
pub(crate) const fn new(core: Arc) -> Self {
Self { core }
}
@@ -68,13 +78,18 @@ impl DispatcherClient {
self.core.spawn_on_worker(worker_index, future_factory)
}
- pub(crate) fn spawn(&self, future_factory: FF) -> JoinHandle
+ pub(crate) fn spawn(
+ &self,
+ future_factory: FF,
+ monitoring: crate::runtime::monitoring::TaskMonitoring,
+ ) -> JoinHandle
where
FF: FnOnce(Context) -> F + Send + 'static,
F: Future