1mod conversion;
16
17use conversion::*;
18
19use std::sync::atomic::AtomicU64;
20use std::sync::atomic::Ordering;
21use std::sync::Arc;
22use std::time::Duration;
23
24use chrono::DateTime;
25use chrono::Utc;
26use serde::Deserialize;
27use serde::Serialize;
28
29use crate::blocking::BlockingExecutorAggregate;
30use crate::blocking::BlockingExecutorSnapshot;
31use crate::blocking::BlockingKind;
32use crate::blocking::BlockingLane;
33use crate::metadata_io::MetadataIoSnapshot;
34use crate::scheduled::ScheduledTaskSnapshot;
35use crate::shutdown_report::ShutdownReport;
36use crate::task_group::TaskDetailScope;
37use crate::task_group::TaskGroup;
38use crate::task_group::TaskGroupEventCounts;
39use crate::task_group::TaskGroupId;
40use crate::task_group::TaskGroupLifecycleState;
41use crate::task_group::TaskKind;
42
43static NEXT_RUNTIME_DIAGNOSTICS_ID: AtomicU64 = AtomicU64::new(1);
44
45#[derive(Debug, Clone)]
47pub struct RuntimeDiagnostics {
48 runtime_id: Arc<str>,
49}
50
51#[derive(Debug, Clone, Serialize)]
53pub struct RuntimeDiagnosticsSnapshot {
54 pub runtime_id: String,
56 pub root_name: String,
58 pub group_id: TaskGroupId,
60 pub parent_group_id: Option<TaskGroupId>,
62 pub lifecycle_state: TaskGroupLifecycleState,
64 pub task_count: usize,
66 pub child_count: usize,
68 pub active_tasks: usize,
70 pub registry_slots: usize,
72 pub events: TaskGroupEventCounts,
74 pub blocking_lanes: Vec<BlockingExecutorSnapshot>,
76}
77
78#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
83#[serde(rename_all = "snake_case")]
84pub enum RuntimeComponent {
85 Broker,
87 NameServer,
89 Controller,
91 Proxy,
93 Mcp,
95 SreControlPlane,
97 SreConnector,
99 Other,
101}
102
103#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
105#[serde(rename_all = "snake_case")]
106pub enum RuntimeLifecycleStateV1 {
107 Open,
109 Closing,
111 Closed,
113 ShutdownCompleted,
115 Poisoned,
117}
118
119#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
121#[serde(rename_all = "snake_case")]
122pub enum RuntimeTaskKindV1 {
123 Service,
125 Worker,
127 ScheduledDriver,
129 ScheduledRun,
131 BlockingReaper,
133 Shutdown,
135 Other,
137}
138
139#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
141#[serde(rename_all = "snake_case")]
142pub enum RuntimeBlockingLaneV1 {
143 StorageIo,
145 MetadataIo,
147 CpuCrypto,
149 ConsumeListener,
151}
152
153#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
155#[serde(rename_all = "snake_case")]
156pub enum RuntimeBlockingKindV1 {
157 ShortIo,
159 CpuBound,
161 LongRunning,
163}
164
165#[derive(Debug, Clone, Copy)]
167pub struct RuntimeDiagnosticsViewOptions {
168 pub long_running_threshold: Duration,
170 pub max_task_kind_summaries: usize,
172 pub max_blocking_lane_summaries: usize,
174}
175
176impl Default for RuntimeDiagnosticsViewOptions {
177 fn default() -> Self {
178 Self {
179 long_running_threshold: Duration::from_secs(30),
180 max_task_kind_summaries: TaskKind::COUNT,
181 max_blocking_lane_summaries: BlockingLane::ALL.len(),
182 }
183 }
184}
185
186#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
193pub struct RuntimeDiagnosticsViewV1 {
194 pub schema_version: String,
196 pub observed_at: DateTime<Utc>,
198 pub component: RuntimeComponent,
200 pub lifecycle_state: RuntimeLifecycleStateV1,
202 pub task_group_count: usize,
204 pub task_count: usize,
206 pub task_kinds: Vec<RuntimeTaskKindSummaryV1>,
208 pub blocking_lanes: Vec<RuntimeBlockingLaneSummaryV1>,
210 pub truncated: bool,
212}
213
214impl RuntimeDiagnosticsViewV1 {
215 pub const SCHEMA_VERSION: &'static str = "rocketmq.runtime-diagnostics.v1";
217}
218
219#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
221pub struct RuntimeTaskKindSummaryV1 {
222 pub kind: RuntimeTaskKindV1,
224 pub active: usize,
226 pub long_running: usize,
228 pub max_elapsed_millis: u64,
230}
231
232#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
234pub struct RuntimeBlockingLaneSummaryV1 {
235 pub lane: RuntimeBlockingLaneV1,
237 #[serde(default, skip_serializing_if = "Option::is_none")]
239 pub max_concurrency: Option<usize>,
240 #[serde(default, skip_serializing_if = "Option::is_none")]
242 pub max_queue_depth: Option<usize>,
243 pub queued: usize,
245 pub running: usize,
247 pub timed_out_still_running: usize,
249 pub blocking_still_running: usize,
251 pub task_kinds: Vec<RuntimeBlockingKindSummaryV1>,
253}
254
255#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
257pub struct RuntimeBlockingKindSummaryV1 {
258 pub kind: RuntimeBlockingKindV1,
260 pub active: usize,
262 pub max_elapsed_millis: u64,
264}
265
266impl RuntimeDiagnostics {
267 pub(crate) fn new() -> Self {
268 let runtime_id = NEXT_RUNTIME_DIAGNOSTICS_ID.fetch_add(1, Ordering::Relaxed);
269 Self {
270 runtime_id: Arc::from(format!("rocketmq-runtime-{runtime_id}")),
271 }
272 }
273
274 pub fn runtime_id(&self) -> &str {
276 &self.runtime_id
277 }
278
279 pub fn snapshot(
281 &self,
282 root: &TaskGroup,
283 blocking_lanes: Vec<BlockingExecutorSnapshot>,
284 ) -> RuntimeDiagnosticsSnapshot {
285 RuntimeDiagnosticsSnapshot {
286 runtime_id: self.runtime_id.to_string(),
287 root_name: root.name().to_string(),
288 group_id: root.id(),
289 parent_group_id: root.parent_id(),
290 lifecycle_state: root.lifecycle_state(),
291 task_count: root.task_count(),
292 child_count: root.component_count(),
293 active_tasks: root.task_count(),
294 registry_slots: root.component_count(),
295 events: root.event_counts(),
296 blocking_lanes,
297 }
298 }
299
300 pub fn view_v1(
302 &self,
303 component: RuntimeComponent,
304 root: &TaskGroup,
305 blocking_lanes: Vec<BlockingExecutorSnapshot>,
306 ) -> RuntimeDiagnosticsViewV1 {
307 self.view_v1_with_options(
308 component,
309 root,
310 blocking_lanes,
311 RuntimeDiagnosticsViewOptions::default(),
312 )
313 }
314
315 pub fn view_v1_with_options(
317 &self,
318 component: RuntimeComponent,
319 root: &TaskGroup,
320 blocking_lanes: Vec<BlockingExecutorSnapshot>,
321 options: RuntimeDiagnosticsViewOptions,
322 ) -> RuntimeDiagnosticsViewV1 {
323 self.view_v1_with_aggregates(
324 component,
325 root,
326 blocking_lanes.into_iter().map(Into::into).collect(),
327 options,
328 )
329 }
330
331 pub(crate) fn view_v1_with_aggregates(
332 &self,
333 component: RuntimeComponent,
334 root: &TaskGroup,
335 blocking_lanes: Vec<BlockingExecutorAggregate>,
336 options: RuntimeDiagnosticsViewOptions,
337 ) -> RuntimeDiagnosticsViewV1 {
338 let task_diagnostics = root.diagnostics(options.long_running_threshold);
339 let task_kind_count = task_diagnostics.task_kinds.len();
340 let task_kinds = task_diagnostics
341 .task_kinds
342 .into_iter()
343 .take(options.max_task_kind_summaries)
344 .map(|summary| RuntimeTaskKindSummaryV1 {
345 kind: runtime_task_kind(summary.kind),
346 active: summary.active,
347 long_running: summary.long_running,
348 max_elapsed_millis: duration_millis(summary.max_elapsed),
349 })
350 .collect();
351
352 let blocking_lane_count = blocking_lanes.len();
353 let blocking_lanes = blocking_lanes
354 .into_iter()
355 .take(options.max_blocking_lane_summaries.min(BlockingLane::ALL.len()))
356 .map(sanitize_blocking_lane)
357 .collect();
358
359 RuntimeDiagnosticsViewV1 {
360 schema_version: RuntimeDiagnosticsViewV1::SCHEMA_VERSION.to_string(),
361 observed_at: Utc::now(),
362 component,
363 lifecycle_state: runtime_lifecycle_state(root.lifecycle_state()),
364 task_group_count: task_diagnostics.group_count,
365 task_count: task_diagnostics.task_count,
366 task_kinds,
367 blocking_lanes,
368 truncated: task_kind_count > options.max_task_kind_summaries
369 || blocking_lane_count > options.max_blocking_lane_summaries.min(3),
370 }
371 }
372}
373
374#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
379#[serde(rename_all = "snake_case")]
380pub enum RuntimeDiagnosticsScope {
381 Local,
383 Subtree,
385 ProcessShared,
387}
388
389#[derive(Debug, Clone, Copy)]
397pub struct RuntimeDiagnosticsViewOptionsV2 {
398 pub long_running_threshold: Duration,
400 pub max_task_kind_summaries: usize,
402 pub max_blocking_lane_summaries: usize,
404 pub max_schedule_tasks: usize,
406 pub max_metadata_resources: usize,
408 pub max_detail_entries: usize,
410 pub detail_scan_budget: usize,
413}
414
415impl Default for RuntimeDiagnosticsViewOptionsV2 {
416 fn default() -> Self {
417 Self {
418 long_running_threshold: Duration::from_secs(30),
419 max_task_kind_summaries: TaskKind::COUNT,
420 max_blocking_lane_summaries: BlockingLane::ALL.len(),
421 max_schedule_tasks: 16,
422 max_metadata_resources: 32,
423 max_detail_entries: 0,
424 detail_scan_budget: 0,
425 }
426 }
427}
428
429#[derive(Debug, Clone, Default)]
435pub struct RuntimeDiagnosticsInputs {
436 pub schedule: Vec<ScheduledTaskSnapshot>,
438 pub metadata: Option<MetadataIoSnapshot>,
440 pub shutdown: Option<ShutdownReport>,
442}
443
444#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
446pub struct RuntimeTaskSectionV2 {
447 pub scope: RuntimeDiagnosticsScope,
449 pub task_group_count: usize,
451 pub task_count: usize,
453 pub local_task_count: usize,
459 pub long_running: usize,
461 pub max_elapsed_millis: u64,
463 pub task_kinds: Vec<RuntimeTaskKindSummaryV1>,
465 pub truncated: bool,
467}
468
469#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
471pub struct RuntimeBlockingSectionV2 {
472 pub scope: RuntimeDiagnosticsScope,
474 pub queued: usize,
476 pub running: usize,
478 pub timed_out_still_running: usize,
480 pub blocking_still_running: usize,
482 pub lanes: Vec<RuntimeBlockingLaneSummaryV1>,
484 pub truncated: bool,
486}
487
488#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
490pub struct RuntimeScheduleSectionV2 {
491 pub scope: RuntimeDiagnosticsScope,
493 pub tasks_scanned: usize,
495 pub tasks_emitted: usize,
497 pub active_runs: u64,
499 pub runs: u64,
501 pub skips: u64,
503 pub overlaps: u64,
505 pub failures: u64,
507 pub max_elapsed_millis: u64,
509 pub truncated: bool,
511}
512
513#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
515pub struct RuntimeMetadataSectionV2 {
516 pub scope: RuntimeDiagnosticsScope,
518 pub accepting: bool,
520 pub retained_operations: usize,
522 pub retained_bytes: usize,
524 pub waiters: usize,
526 pub resources_scanned: usize,
528 pub resources_emitted: usize,
530 pub truncated: bool,
532}
533
534#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
536pub struct RuntimeShutdownSectionV2 {
537 pub scope: RuntimeDiagnosticsScope,
539 pub elapsed_millis: u64,
541 pub cancelled: usize,
543 pub failed: usize,
545 pub timed_out: usize,
547 pub leaked: usize,
549}
550
551#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
557pub struct RuntimeTaskDetailV2 {
558 pub kind: RuntimeTaskKindV1,
560 pub scope: RuntimeDiagnosticsScope,
562 pub elapsed_millis: u64,
564}
565
566#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
573pub struct RuntimeDiagnosticsViewV2 {
574 pub schema_version: String,
576 pub observed_at: DateTime<Utc>,
578 pub component: RuntimeComponent,
580 pub lifecycle_state: RuntimeLifecycleStateV1,
582 pub tasks: RuntimeTaskSectionV2,
584 pub blocking: RuntimeBlockingSectionV2,
586 #[serde(default, skip_serializing_if = "Option::is_none")]
588 pub schedule: Option<RuntimeScheduleSectionV2>,
589 #[serde(default, skip_serializing_if = "Option::is_none")]
591 pub metadata: Option<RuntimeMetadataSectionV2>,
592 #[serde(default, skip_serializing_if = "Option::is_none")]
594 pub shutdown: Option<RuntimeShutdownSectionV2>,
595 pub details: Vec<RuntimeTaskDetailV2>,
597 pub detail_scan_budget: usize,
599 pub details_scanned: usize,
601 pub truncated: bool,
603}
604
605#[derive(Debug, Clone, Serialize)]
610pub struct RuntimeTaskDetails {
611 pub details: Vec<RuntimeTaskDetailV2>,
613 pub tasks_scanned: usize,
615 pub group_entries_scanned: usize,
617 pub truncated: bool,
619}
620
621impl From<crate::task_group::TaskDetailScan> for RuntimeTaskDetails {
622 fn from(scan: crate::task_group::TaskDetailScan) -> Self {
623 Self {
624 details: scan
625 .details
626 .into_iter()
627 .map(|detail| RuntimeTaskDetailV2 {
628 kind: runtime_task_kind(detail.kind),
629 scope: runtime_detail_scope(detail.scope),
630 elapsed_millis: duration_millis(detail.elapsed),
631 })
632 .collect(),
633 tasks_scanned: scan.scanned,
634 group_entries_scanned: scan.group_entries_scanned,
635 truncated: scan.truncated,
636 }
637 }
638}
639
640impl RuntimeDiagnosticsViewV2 {
641 pub const SCHEMA_VERSION: &'static str = "rocketmq.runtime-diagnostics.v2";
643}
644
645impl RuntimeDiagnostics {
646 pub fn view_v2(
648 &self,
649 component: RuntimeComponent,
650 root: &TaskGroup,
651 blocking_lanes: Vec<BlockingExecutorSnapshot>,
652 inputs: RuntimeDiagnosticsInputs,
653 ) -> RuntimeDiagnosticsViewV2 {
654 self.view_v2_with_options(
655 component,
656 root,
657 blocking_lanes,
658 inputs,
659 RuntimeDiagnosticsViewOptionsV2::default(),
660 )
661 }
662
663 pub fn view_v2_with_options(
666 &self,
667 component: RuntimeComponent,
668 root: &TaskGroup,
669 blocking_lanes: Vec<BlockingExecutorSnapshot>,
670 inputs: RuntimeDiagnosticsInputs,
671 options: RuntimeDiagnosticsViewOptionsV2,
672 ) -> RuntimeDiagnosticsViewV2 {
673 self.view_v2_with_aggregates(
674 component,
675 root,
676 blocking_lanes.into_iter().map(Into::into).collect(),
677 inputs,
678 options,
679 )
680 }
681
682 pub(crate) fn view_v2_with_aggregates(
683 &self,
684 component: RuntimeComponent,
685 root: &TaskGroup,
686 blocking_lanes: Vec<BlockingExecutorAggregate>,
687 inputs: RuntimeDiagnosticsInputs,
688 options: RuntimeDiagnosticsViewOptionsV2,
689 ) -> RuntimeDiagnosticsViewV2 {
690 let (tasks, tasks_truncated) = task_section_v2(root, options);
691 let (blocking, blocking_truncated) = blocking_section_v2(blocking_lanes, options);
692 let schedule = (!inputs.schedule.is_empty()).then(|| schedule_section_v2(&inputs.schedule, options));
693 let metadata = inputs
694 .metadata
695 .as_ref()
696 .map(|snapshot| metadata_section_v2(snapshot, options));
697 let shutdown = inputs.shutdown.as_ref().map(shutdown_section_v2);
698 let details = if options.max_detail_entries == 0 && options.detail_scan_budget == 0 {
702 crate::task_group::TaskDetailScan::default()
703 } else {
704 root.bounded_task_details(options.detail_scan_budget, options.max_detail_entries)
705 };
706 let details_truncated = details.truncated;
707
708 let schedule_truncated = schedule.as_ref().is_some_and(|section| section.truncated);
709 let metadata_truncated = metadata.as_ref().is_some_and(|section| section.truncated);
710
711 RuntimeDiagnosticsViewV2 {
712 schema_version: RuntimeDiagnosticsViewV2::SCHEMA_VERSION.to_string(),
713 observed_at: Utc::now(),
714 component,
715 lifecycle_state: runtime_lifecycle_state(root.lifecycle_state()),
716 tasks,
717 blocking,
718 schedule,
719 metadata,
720 shutdown,
721 details: details
722 .details
723 .into_iter()
724 .map(|detail| RuntimeTaskDetailV2 {
725 kind: runtime_task_kind(detail.kind),
726 scope: runtime_detail_scope(detail.scope),
727 elapsed_millis: duration_millis(detail.elapsed),
728 })
729 .collect(),
730 detail_scan_budget: options.detail_scan_budget,
731 details_scanned: details.scanned,
732 truncated: tasks_truncated
733 || blocking_truncated
734 || schedule_truncated
735 || metadata_truncated
736 || details_truncated,
737 }
738 }
739}
740
741#[cfg(test)]
742mod tests {
743 use super::*;
744 use crate::RuntimeContext;
745
746 #[tokio::test]
747 async fn lane_identity_survives_partial_and_reordered_inputs_in_both_schemas() {
748 let context = RuntimeContext::from_current("lane-identity");
749 let diagnostics = RuntimeDiagnostics::new();
750 let snapshot = |lane: BlockingLane| BlockingExecutorSnapshot {
751 name: "private-lane".to_owned(),
752 lane,
753 max_concurrency: 8,
754 max_queue_depth: 32,
755 global_capacity: 8,
756 global_running: 0,
757 global_available: 8,
758 lane_reserved: 1,
759 lane_running: 0,
760 lane_borrowed: 0,
761 queued: lane.index() + 10,
762 running: 0,
763 timed_out_still_running: 0,
764 blocking_still_running: 0,
765 rejected: 0,
766 oldest_queue_wait: Duration::ZERO,
767 tasks: Vec::new(),
768 };
769 for lanes in [
770 vec![BlockingLane::MetadataIo],
771 vec![
772 BlockingLane::CpuCrypto,
773 BlockingLane::StorageIo,
774 BlockingLane::MetadataIo,
775 ],
776 vec![BlockingLane::MetadataIo, BlockingLane::CpuCrypto],
777 vec![BlockingLane::ConsumeListener, BlockingLane::StorageIo],
778 vec![],
779 ] {
780 let snapshots: Vec<_> = lanes.iter().copied().map(snapshot).collect();
781 let v1 = diagnostics.view_v1(RuntimeComponent::Broker, context.root_group(), snapshots.clone());
782 let v2 = diagnostics.view_v2(
783 RuntimeComponent::Broker,
784 context.root_group(),
785 snapshots,
786 RuntimeDiagnosticsInputs::default(),
787 );
788 assert_eq!(v1.blocking_lanes, v2.blocking.lanes);
789 assert_eq!(v1.blocking_lanes.len(), lanes.len());
790 for (summary, lane) in v1.blocking_lanes.iter().zip(lanes) {
791 let expected = match lane {
792 BlockingLane::StorageIo => "storage_io",
793 BlockingLane::MetadataIo => "metadata_io",
794 BlockingLane::CpuCrypto => "cpu_crypto",
795 BlockingLane::ConsumeListener => "consume_listener",
796 };
797 assert_eq!(serde_json::to_value(summary.lane).unwrap(), expected);
798 assert_eq!(summary.queued, lane.index() + 10);
799 }
800 }
801 }
802
803 #[tokio::test]
804 async fn every_task_kind_keeps_its_own_population_and_wire_label() {
805 let context = RuntimeContext::from_current("kind-population");
806 let root = context.root_group();
807 let labels = [
808 "service",
809 "worker",
810 "scheduled_driver",
811 "scheduled_run",
812 "blocking_reaper",
813 "shutdown",
814 "other",
815 ];
816 for (kind, count) in TaskKind::ALL.into_iter().zip(1..) {
817 for _ in 0..count {
818 let cancellation = root.cancellation_token();
819 root.spawn("pending", kind, async move { cancellation.cancelled().await })
820 .unwrap();
821 }
822 }
823 let view = RuntimeDiagnostics::new().view_v1(RuntimeComponent::Broker, root, Vec::new());
824 assert_eq!(view.task_kinds.len(), labels.len());
825 for ((summary, label), count) in view.task_kinds.iter().zip(labels).zip(1..) {
826 assert_eq!(serde_json::to_value(summary.kind).unwrap(), label);
827 assert_eq!(summary.active, count);
828 }
829 assert!(root.shutdown(Duration::from_secs(1)).await.is_healthy());
830 }
831
832 #[tokio::test]
833 async fn sanitized_view_does_not_expose_runtime_or_task_names() {
834 let context = RuntimeContext::from_current("sensitive-root-name");
835 let child = context.service_context("sensitive-child-name");
836 child
837 .spawn("sensitive-task-name", TaskKind::Worker, std::future::pending())
838 .expect("task should spawn");
839 let diagnostics = RuntimeDiagnostics::new();
840
841 let view = diagnostics.view_v1(RuntimeComponent::Mcp, context.root_group(), Vec::new());
842 let json = serde_json::to_string(&view).expect("view should serialize");
843
844 assert!(!json.contains("sensitive-root-name"));
845 assert!(!json.contains("sensitive-child-name"));
846 assert!(!json.contains("sensitive-task-name"));
847 assert!(!json.contains("rocketmq-runtime-"));
848 assert!(json.contains("\"lifecycle_state\":\"open\""));
849 assert!(json.contains("\"kind\":\"worker\""));
850 assert!(view.task_group_count >= 2);
851 assert_eq!(view.task_count, 1);
852 }
853
854 #[tokio::test]
855 async fn zero_bounds_produce_an_explicit_truncated_view() {
856 let context = RuntimeContext::from_current("runtime-view-bounds");
857 context
858 .root_group()
859 .spawn("worker", TaskKind::Worker, std::future::pending())
860 .expect("task should spawn");
861 let diagnostics = RuntimeDiagnostics::new();
862 let view = diagnostics.view_v1_with_options(
863 RuntimeComponent::Other,
864 context.root_group(),
865 Vec::new(),
866 RuntimeDiagnosticsViewOptions {
867 max_task_kind_summaries: 0,
868 max_blocking_lane_summaries: 0,
869 ..RuntimeDiagnosticsViewOptions::default()
870 },
871 );
872
873 assert!(view.truncated);
874 assert!(view.task_kinds.is_empty());
875 assert!(view.blocking_lanes.is_empty());
876 }
877
878 #[tokio::test]
879 async fn sanitized_view_exposes_only_bounded_blocking_capacity_and_counts() {
880 let context = RuntimeContext::from_current("runtime-blocking-capacity");
881 let diagnostics = RuntimeDiagnostics::new();
882 let view = diagnostics.view_v1(
883 RuntimeComponent::Broker,
884 context.root_group(),
885 vec![BlockingExecutorSnapshot {
886 name: "sensitive-lane-name".to_owned(),
887 lane: crate::BlockingLane::StorageIo,
888 max_concurrency: 8,
889 max_queue_depth: 32,
890 global_capacity: 8,
891 global_running: 2,
892 global_available: 6,
893 lane_reserved: 8,
894 lane_running: 2,
895 lane_borrowed: 0,
896 queued: 3,
897 running: 2,
898 timed_out_still_running: 1,
899 blocking_still_running: 0,
900 rejected: 0,
901 oldest_queue_wait: Duration::ZERO,
902 tasks: Vec::new(),
903 }],
904 );
905
906 assert_eq!(view.blocking_lanes.len(), 1);
907 assert_eq!(view.blocking_lanes[0].max_concurrency, Some(8));
908 assert_eq!(view.blocking_lanes[0].max_queue_depth, Some(32));
909 let encoded = serde_json::to_string(&view).expect("view should serialize");
910 assert!(!encoded.contains("sensitive-lane-name"));
911 let decoded: RuntimeDiagnosticsViewV1 =
912 serde_json::from_str(&encoded).expect("versioned view should deserialize");
913 assert_eq!(decoded, view);
914
915 let mut legacy = serde_json::to_value(&view).expect("view should encode");
916 let lane = legacy
917 .get_mut("blocking_lanes")
918 .and_then(serde_json::Value::as_array_mut)
919 .and_then(|lanes| lanes.first_mut())
920 .and_then(serde_json::Value::as_object_mut)
921 .expect("blocking lane");
922 lane.remove("max_concurrency");
923 lane.remove("max_queue_depth");
924 let legacy: RuntimeDiagnosticsViewV1 =
925 serde_json::from_value(legacy).expect("older v1 view should remain readable");
926 assert_eq!(legacy.blocking_lanes[0].max_concurrency, None);
927 assert_eq!(legacy.blocking_lanes[0].max_queue_depth, None);
928 }
929
930 fn scheduled_snapshot(name: &str, runs: u64, skips: u64, max_elapsed_ms: u64) -> ScheduledTaskSnapshot {
931 ScheduledTaskSnapshot {
932 name: name.to_string(),
933 mode: crate::scheduled::ScheduleMode::FixedDelay,
934 running: true,
935 active_runs: 1,
936 runs,
937 skips,
938 overlaps: 0,
939 failures: 0,
940 last_drift_ms: 0,
941 last_elapsed_ms: max_elapsed_ms,
942 max_elapsed_ms,
943 }
944 }
945
946 fn metadata_snapshot(waiter_count: usize) -> MetadataIoSnapshot {
947 MetadataIoSnapshot {
948 accepting: true,
949 pending_operations: 2,
950 pending_bytes: 4_096,
951 max_pending_operations: 1_024,
952 max_pending_bytes: 65_536,
953 resources: vec![crate::metadata_io::MetadataIoResourceSnapshot {
954 resource: "sensitive-resource-name".into(),
955 target: None,
956 durable_generation: None,
957 in_flight_generation: None,
958 queued_generation: None,
959 waiter_count,
960 }],
961 }
962 }
963
964 #[tokio::test]
965 async fn v2_sections_state_their_scope_and_absent_inputs_stay_absent() {
966 let context = RuntimeContext::from_current("runtime-v2-scope");
967 context
968 .root_group()
969 .spawn("local-worker", TaskKind::Worker, std::future::pending())
970 .expect("task should spawn");
971 context
972 .service_context("runtime-v2-child")
973 .spawn("child-worker", TaskKind::Worker, std::future::pending())
974 .expect("task should spawn");
975 let diagnostics = RuntimeDiagnostics::new();
976
977 let view = diagnostics.view_v2(
978 RuntimeComponent::Broker,
979 context.root_group(),
980 Vec::new(),
981 RuntimeDiagnosticsInputs::default(),
982 );
983
984 assert_eq!(view.schema_version, "rocketmq.runtime-diagnostics.v2");
985 assert_eq!(view.tasks.scope, RuntimeDiagnosticsScope::Subtree);
986 assert_eq!(view.tasks.task_count, 2);
987 assert_eq!(view.tasks.local_task_count, 1);
988 assert_eq!(view.blocking.scope, RuntimeDiagnosticsScope::ProcessShared);
989 assert!(view.schedule.is_none());
990 assert!(view.metadata.is_none());
991 assert!(view.shutdown.is_none());
992 assert!(view.details.is_empty());
993 assert!(!view.truncated);
995 }
996
997 #[tokio::test]
998 async fn v2_reports_component_owned_sections_with_their_scope() {
999 let context = RuntimeContext::from_current("runtime-v2-sections");
1000 let diagnostics = RuntimeDiagnostics::new();
1001
1002 let view = diagnostics.view_v2(
1003 RuntimeComponent::Broker,
1004 context.root_group(),
1005 Vec::new(),
1006 RuntimeDiagnosticsInputs {
1007 schedule: vec![scheduled_snapshot("sensitive-schedule", 4, 3, 250)],
1008 metadata: Some(metadata_snapshot(2)),
1009 shutdown: Some(ShutdownReport {
1010 cancelled: 1,
1011 failed: 1,
1012 timed_out: 1,
1013 leaked: 1,
1014 ..ShutdownReport::new("sensitive-group", Duration::from_millis(120))
1015 }),
1016 },
1017 );
1018
1019 let schedule = view.schedule.clone().expect("a supplied schedule section is present");
1020 assert_eq!(schedule.scope, RuntimeDiagnosticsScope::Local);
1021 assert_eq!(schedule.tasks_scanned, 1);
1022 assert_eq!(schedule.tasks_emitted, 1);
1023 assert_eq!(schedule.runs, 4);
1024 assert_eq!(schedule.skips, 3);
1025 assert_eq!(schedule.max_elapsed_millis, 250);
1026 assert!(!schedule.truncated);
1027
1028 let metadata = view.metadata.clone().expect("a supplied metadata section is present");
1029 assert_eq!(metadata.scope, RuntimeDiagnosticsScope::Local);
1030 assert_eq!(metadata.retained_operations, 2);
1031 assert_eq!(metadata.retained_bytes, 4_096);
1032 assert_eq!(metadata.waiters, 2);
1033 assert!(metadata.accepting);
1034
1035 let shutdown = view.shutdown.clone().expect("a supplied shutdown section is present");
1036 assert_eq!(shutdown.scope, RuntimeDiagnosticsScope::Local);
1037 assert_eq!(shutdown.elapsed_millis, 120);
1038 assert_eq!(shutdown.failed, 1);
1039 assert_eq!(shutdown.timed_out, 1);
1040 assert_eq!(shutdown.leaked, 1);
1041
1042 let json = serde_json::to_string(&view).expect("view should serialize");
1043 assert!(!json.contains("sensitive"));
1044 }
1045
1046 #[tokio::test]
1047 async fn v2_truncation_reports_what_was_scanned_and_emitted() {
1048 let context = RuntimeContext::from_current("runtime-v2-truncation");
1049 let diagnostics = RuntimeDiagnostics::new();
1050 let schedule = vec![
1051 scheduled_snapshot("first", 1, 0, 10),
1052 scheduled_snapshot("second", 1, 0, 20),
1053 scheduled_snapshot("third", 1, 0, 30),
1054 ];
1055
1056 let view = diagnostics.view_v2_with_options(
1057 RuntimeComponent::Other,
1058 context.root_group(),
1059 Vec::new(),
1060 RuntimeDiagnosticsInputs {
1061 schedule,
1062 ..RuntimeDiagnosticsInputs::default()
1063 },
1064 RuntimeDiagnosticsViewOptionsV2 {
1065 max_schedule_tasks: 1,
1066 ..RuntimeDiagnosticsViewOptionsV2::default()
1067 },
1068 );
1069
1070 let section = view.schedule.expect("a supplied schedule section is present");
1071 assert!(section.truncated);
1072 assert_eq!(section.tasks_scanned, 3);
1073 assert_eq!(section.tasks_emitted, 1);
1074 assert_eq!(section.runs, 1);
1075 assert!(view.truncated);
1076 }
1077
1078 #[tokio::test]
1079 async fn v2_detail_lists_stay_bounded_and_redacted() {
1080 let context = RuntimeContext::from_current("sensitive-runtime-name");
1081 let child = context.service_context("sensitive-child-name");
1082 for index in 0..4 {
1083 child
1084 .spawn(
1085 format!("sensitive-task-{index}"),
1086 TaskKind::Worker,
1087 std::future::pending(),
1088 )
1089 .expect("task should spawn");
1090 }
1091 let diagnostics = RuntimeDiagnostics::new();
1092
1093 let view = diagnostics.view_v2_with_options(
1094 RuntimeComponent::Mcp,
1095 context.root_group(),
1096 Vec::new(),
1097 RuntimeDiagnosticsInputs::default(),
1098 RuntimeDiagnosticsViewOptionsV2 {
1099 max_detail_entries: 2,
1100 detail_scan_budget: 4,
1101 ..RuntimeDiagnosticsViewOptionsV2::default()
1102 },
1103 );
1104
1105 assert_eq!(view.details.len(), 2);
1106 assert_eq!(view.details_scanned, 4);
1107 assert_eq!(view.detail_scan_budget, 4);
1108 assert!(view.truncated);
1109 assert!(
1110 view.details
1111 .iter()
1112 .all(|detail| detail.scope == RuntimeDiagnosticsScope::Subtree),
1113 "the tasks belong to a descendant group"
1114 );
1115
1116 let json = serde_json::to_string(&view).expect("view should serialize");
1117 assert!(!json.contains("sensitive"));
1118 assert!(!json.contains("rocketmq-runtime-"));
1119 let decoded: RuntimeDiagnosticsViewV2 = serde_json::from_str(&json).expect("versioned view should deserialize");
1120 assert_eq!(decoded, view);
1121 }
1122
1123 #[tokio::test]
1124 async fn v2_detail_scan_budget_bounds_the_scan_and_not_only_the_output() {
1125 let context = RuntimeContext::from_current("runtime-v2-scan-budget");
1126 for index in 0..4 {
1127 context
1128 .root_group()
1129 .spawn(format!("worker-{index}"), TaskKind::Worker, std::future::pending())
1130 .expect("task should spawn");
1131 }
1132 let diagnostics = RuntimeDiagnostics::new();
1133
1134 let view = diagnostics.view_v2_with_options(
1135 RuntimeComponent::Other,
1136 context.root_group(),
1137 Vec::new(),
1138 RuntimeDiagnosticsInputs::default(),
1139 RuntimeDiagnosticsViewOptionsV2 {
1140 max_detail_entries: 8,
1141 detail_scan_budget: 2,
1142 ..RuntimeDiagnosticsViewOptionsV2::default()
1143 },
1144 );
1145
1146 assert_eq!(view.details_scanned, 2);
1147 assert_eq!(view.details.len(), 2);
1148 assert!(view.truncated, "the scan stopped before every task was examined");
1149 assert!(view
1150 .details
1151 .iter()
1152 .all(|detail| detail.scope == RuntimeDiagnosticsScope::Local));
1153 }
1154
1155 #[tokio::test]
1156 async fn v2_detail_scan_budget_also_bounds_the_groups_it_visits() {
1157 let context = RuntimeContext::from_current("runtime-v2-group-budget");
1158 let groups = (0..8)
1160 .map(|index| context.service_context(crate::ScopeId::try_new(format!("empty-{index}")).unwrap()))
1161 .collect::<Vec<_>>();
1162 let diagnostics = RuntimeDiagnostics::new();
1163 let view_with_budget = |detail_scan_budget| {
1164 diagnostics.view_v2_with_options(
1165 RuntimeComponent::Other,
1166 context.root_group(),
1167 Vec::new(),
1168 RuntimeDiagnosticsInputs::default(),
1169 RuntimeDiagnosticsViewOptionsV2 {
1170 max_detail_entries: 8,
1171 detail_scan_budget,
1172 ..RuntimeDiagnosticsViewOptionsV2::default()
1173 },
1174 )
1175 };
1176
1177 let bounded = view_with_budget(3);
1178 assert_eq!(bounded.details_scanned, 0);
1179 assert!(bounded.details.is_empty());
1180 assert!(bounded.truncated, "the scan stopped before every group was visited");
1181 assert_eq!(
1182 bounded.tasks.task_group_count, 9,
1183 "the aggregate section still covers every group"
1184 );
1185
1186 let complete = view_with_budget(8);
1187 assert_eq!(complete.details_scanned, 0);
1188 assert!(!complete.truncated, "a budget covering every group completes the scan");
1189 drop(groups);
1190 }
1191
1192 #[tokio::test]
1193 async fn v2_view_is_a_snapshot_that_late_completions_cannot_rewrite() {
1194 let context = RuntimeContext::from_current("runtime-v2-frozen");
1195 let (release, wait) = tokio::sync::oneshot::channel::<()>();
1196 context
1197 .root_group()
1198 .spawn("finishes-later", TaskKind::Worker, async move {
1199 let _ = wait.await;
1200 })
1201 .expect("task should spawn");
1202 let diagnostics = RuntimeDiagnostics::new();
1203
1204 let view = diagnostics.view_v2(
1205 RuntimeComponent::Other,
1206 context.root_group(),
1207 Vec::new(),
1208 RuntimeDiagnosticsInputs::default(),
1209 );
1210 assert_eq!(view.tasks.task_count, 1);
1211
1212 release.send(()).expect("the task should still be waiting");
1213 for _ in 0..10_000 {
1214 if context.root_group().task_count() == 0 {
1215 break;
1216 }
1217 tokio::task::yield_now().await;
1218 }
1219
1220 assert_eq!(context.root_group().task_count(), 0, "the task really finished");
1221 assert_eq!(
1222 view.tasks.task_count, 1,
1223 "the earlier view keeps what it observed instead of following late completions"
1224 );
1225 }
1226}