Skip to main content

rocketmq_runtime/
diagnostics.rs

1// Copyright 2023 The RocketMQ Rust Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15mod 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/// Represents runtime diagnostics.
46#[derive(Debug, Clone)]
47pub struct RuntimeDiagnostics {
48    runtime_id: Arc<str>,
49}
50
51/// Represents runtime diagnostics snapshot.
52#[derive(Debug, Clone, Serialize)]
53pub struct RuntimeDiagnosticsSnapshot {
54    /// The runtime identifier.
55    pub runtime_id: String,
56    /// The root name value.
57    pub root_name: String,
58    /// The group identifier.
59    pub group_id: TaskGroupId,
60    /// The parent group identifier.
61    pub parent_group_id: Option<TaskGroupId>,
62    /// The lifecycle state value.
63    pub lifecycle_state: TaskGroupLifecycleState,
64    /// The number of task entries.
65    pub task_count: usize,
66    /// The number of child entries.
67    pub child_count: usize,
68    /// The number of active task entries.
69    pub active_tasks: usize,
70    /// The number of active child registry slots.
71    pub registry_slots: usize,
72    /// Failures absorbed anywhere in the root's tree.
73    pub events: TaskGroupEventCounts,
74    /// The blocking lanes value.
75    pub blocking_lanes: Vec<BlockingExecutorSnapshot>,
76}
77
78/// A stable component identifier used by the sanitized diagnostics view.
79///
80/// The enum deliberately avoids caller-provided labels so diagnostics cannot
81/// disclose deployment names or other high-cardinality runtime data.
82#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
83#[serde(rename_all = "snake_case")]
84pub enum RuntimeComponent {
85    /// A RocketMQ broker process.
86    Broker,
87    /// A RocketMQ NameServer process.
88    NameServer,
89    /// A RocketMQ controller process.
90    Controller,
91    /// A RocketMQ proxy process.
92    Proxy,
93    /// A RocketMQ MCP server process.
94    Mcp,
95    /// An AI SRE control-plane process.
96    SreControlPlane,
97    /// An AI SRE connector process.
98    SreConnector,
99    /// A component without a dedicated bounded identifier.
100    Other,
101}
102
103/// Describes the lifecycle state of the root task group.
104#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
105#[serde(rename_all = "snake_case")]
106pub enum RuntimeLifecycleStateV1 {
107    /// The task group accepts new tasks and child groups.
108    Open,
109    /// Shutdown has started and new work is rejected.
110    Closing,
111    /// The task group is closed and its owned work is draining.
112    Closed,
113    /// Shutdown completed and all bounded cleanup attempts have finished.
114    ShutdownCompleted,
115    /// The lifecycle state could not be mapped to a supported value.
116    Poisoned,
117}
118
119/// Identifies a bounded category of runtime-owned task.
120#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
121#[serde(rename_all = "snake_case")]
122pub enum RuntimeTaskKindV1 {
123    /// A long-lived service task.
124    Service,
125    /// A background worker task.
126    Worker,
127    /// A task that drives a scheduled workload.
128    ScheduledDriver,
129    /// One execution of a scheduled workload.
130    ScheduledRun,
131    /// A task that reaps completed blocking work.
132    BlockingReaper,
133    /// A task that coordinates shutdown.
134    Shutdown,
135    /// A task kind without a dedicated bounded identifier.
136    Other,
137}
138
139/// Identifies a bounded blocking-executor lane.
140#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
141#[serde(rename_all = "snake_case")]
142pub enum RuntimeBlockingLaneV1 {
143    /// Blocking storage input and output.
144    StorageIo,
145    /// Blocking metadata input and output.
146    MetadataIo,
147    /// CPU-intensive cryptographic work.
148    CpuCrypto,
149    /// User consume listeners.
150    ConsumeListener,
151}
152
153/// Identifies a bounded category of blocking work.
154#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
155#[serde(rename_all = "snake_case")]
156pub enum RuntimeBlockingKindV1 {
157    /// Short blocking input or output.
158    ShortIo,
159    /// CPU-bound work.
160    CpuBound,
161    /// Blocking work expected to run for an extended duration.
162    LongRunning,
163}
164
165/// Bounds applied while creating [`RuntimeDiagnosticsViewV1`].
166#[derive(Debug, Clone, Copy)]
167pub struct RuntimeDiagnosticsViewOptions {
168    /// Elapsed time after which an active task is classified as long-running.
169    pub long_running_threshold: Duration,
170    /// Maximum number of task-kind summaries included in the view.
171    pub max_task_kind_summaries: usize,
172    /// Maximum number of blocking-lane summaries included in the view.
173    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/// Versioned, bounded, and sanitized runtime diagnostics safe for authenticated
187/// operational APIs.
188///
189/// Unlike [`RuntimeDiagnosticsSnapshot`], this view never exposes runtime IDs,
190/// task IDs, task names, task-group names, executor names, arguments, or
191/// configuration objects.
192#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
193pub struct RuntimeDiagnosticsViewV1 {
194    /// Schema identifier for this serialized diagnostics view.
195    pub schema_version: String,
196    /// UTC timestamp at which the snapshot was observed.
197    pub observed_at: DateTime<Utc>,
198    /// Bounded component category that owns the runtime.
199    pub component: RuntimeComponent,
200    /// Current lifecycle state of the root task group.
201    pub lifecycle_state: RuntimeLifecycleStateV1,
202    /// Number of task groups represented by the snapshot.
203    pub task_group_count: usize,
204    /// Number of active tasks represented by the snapshot.
205    pub task_count: usize,
206    /// Bounded aggregate summaries grouped by task kind.
207    pub task_kinds: Vec<RuntimeTaskKindSummaryV1>,
208    /// Bounded aggregate summaries for blocking-executor lanes.
209    pub blocking_lanes: Vec<RuntimeBlockingLaneSummaryV1>,
210    /// Whether one or more summaries were omitted by configured bounds.
211    pub truncated: bool,
212}
213
214impl RuntimeDiagnosticsViewV1 {
215    /// Stable schema identifier emitted by [`RuntimeDiagnostics::view_v1`].
216    pub const SCHEMA_VERSION: &'static str = "rocketmq.runtime-diagnostics.v1";
217}
218
219/// Aggregated task counts and elapsed-time information for one task kind.
220#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
221pub struct RuntimeTaskKindSummaryV1 {
222    /// Bounded task category.
223    pub kind: RuntimeTaskKindV1,
224    /// Number of active tasks in the category.
225    pub active: usize,
226    /// Number of active tasks exceeding the long-running threshold.
227    pub long_running: usize,
228    /// Maximum elapsed time among active tasks, in milliseconds.
229    pub max_elapsed_millis: u64,
230}
231
232/// Aggregated state for one blocking-executor lane.
233#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
234pub struct RuntimeBlockingLaneSummaryV1 {
235    /// Bounded blocking-executor lane.
236    pub lane: RuntimeBlockingLaneV1,
237    /// Configured concurrency limit when the executor exposes it.
238    #[serde(default, skip_serializing_if = "Option::is_none")]
239    pub max_concurrency: Option<usize>,
240    /// Configured queue-depth limit when the executor exposes it.
241    #[serde(default, skip_serializing_if = "Option::is_none")]
242    pub max_queue_depth: Option<usize>,
243    /// Number of queued blocking tasks.
244    pub queued: usize,
245    /// Number of running blocking tasks.
246    pub running: usize,
247    /// Number of timed-out tasks whose blocking work is still running.
248    pub timed_out_still_running: usize,
249    /// Number of blocking tasks that remain active during observation.
250    pub blocking_still_running: usize,
251    /// Bounded aggregate summaries grouped by blocking-work kind.
252    pub task_kinds: Vec<RuntimeBlockingKindSummaryV1>,
253}
254
255/// Aggregated task counts and elapsed-time information for one blocking-work kind.
256#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
257pub struct RuntimeBlockingKindSummaryV1 {
258    /// Bounded blocking-work category.
259    pub kind: RuntimeBlockingKindV1,
260    /// Number of active blocking tasks in the category.
261    pub active: usize,
262    /// Maximum elapsed time among active tasks, in milliseconds.
263    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    /// Returns the runtime id.
275    pub fn runtime_id(&self) -> &str {
276        &self.runtime_id
277    }
278
279    /// Returns the snapshot.
280    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    /// Creates a bounded diagnostics view using the default sanitization limits.
301    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    /// Creates a bounded diagnostics view using explicit sanitization limits.
316    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/// Names the population a V2 diagnostics value covers.
375///
376/// The scope is part of the payload, so a reader never has to infer it from how
377/// the view was produced, and a partial value cannot be read as a total.
378#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
379#[serde(rename_all = "snake_case")]
380pub enum RuntimeDiagnosticsScope {
381    /// Only the calling group's own state.
382    Local,
383    /// The calling group and every descendant group.
384    Subtree,
385    /// State owned once per process and shared by every component.
386    ProcessShared,
387}
388
389/// Bounds applied while creating [`RuntimeDiagnosticsViewV2`].
390///
391/// The detail budgets default to zero, so a routine sample emits only bounded
392/// aggregates and a task list is always an explicit request. Task age and group
393/// summaries still scan the active population; detail bounds do not cap that
394/// aggregate scan. Concurrent submissions and completions can be observed at
395/// different instants across groups; the snapshot is not a global transaction.
396#[derive(Debug, Clone, Copy)]
397pub struct RuntimeDiagnosticsViewOptionsV2 {
398    /// Elapsed time after which an active task is classified as long-running.
399    pub long_running_threshold: Duration,
400    /// Maximum number of task-kind summaries included in the view.
401    pub max_task_kind_summaries: usize,
402    /// Maximum number of blocking-lane summaries included in the view.
403    pub max_blocking_lane_summaries: usize,
404    /// Maximum number of schedule summaries included in the view.
405    pub max_schedule_tasks: usize,
406    /// Maximum number of metadata resources summarized in the view.
407    pub max_metadata_resources: usize,
408    /// Maximum number of task details emitted when a detail list is requested.
409    pub max_detail_entries: usize,
410    /// Maximum number of tasks examined, and of descendant task groups
411    /// visited, when a detail list is requested.
412    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/// Component-owned inputs for the V2 view.
430///
431/// A section whose input is absent is reported as absent rather than as zero, so
432/// a caller that does not own scheduled work, a metadata actor, or a shutdown
433/// report cannot make the view claim those values are empty.
434#[derive(Debug, Clone, Default)]
435pub struct RuntimeDiagnosticsInputs {
436    /// Snapshots of the caller's scheduled tasks.
437    pub schedule: Vec<ScheduledTaskSnapshot>,
438    /// The snapshot of the caller's metadata actor.
439    pub metadata: Option<MetadataIoSnapshot>,
440    /// The most recent shutdown report for the caller's group.
441    pub shutdown: Option<ShutdownReport>,
442}
443
444/// Bounded task counts for one group population.
445#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
446pub struct RuntimeTaskSectionV2 {
447    /// The population these counts cover.
448    pub scope: RuntimeDiagnosticsScope,
449    /// Number of task groups represented.
450    pub task_group_count: usize,
451    /// Number of active tasks represented.
452    pub task_count: usize,
453    /// Number of active tasks in the calling group alone.
454    ///
455    /// The aggregate `task_count` is scoped to the subtree, so this value lets a
456    /// reader separate the calling group's own work from its descendants without
457    /// requesting a detail list.
458    pub local_task_count: usize,
459    /// Number of active tasks exceeding the long-running threshold.
460    pub long_running: usize,
461    /// Maximum elapsed time among active tasks, in milliseconds.
462    pub max_elapsed_millis: u64,
463    /// Bounded aggregate summaries grouped by task kind.
464    pub task_kinds: Vec<RuntimeTaskKindSummaryV1>,
465    /// Whether summaries were omitted by configured bounds.
466    pub truncated: bool,
467}
468
469/// Bounded blocking-executor state, including work that outlived its wait.
470#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
471pub struct RuntimeBlockingSectionV2 {
472    /// The population these counts cover.
473    pub scope: RuntimeDiagnosticsScope,
474    /// Number of queued blocking tasks.
475    pub queued: usize,
476    /// Number of running blocking tasks.
477    pub running: usize,
478    /// Number of waits that expired while the blocking closure keeps running.
479    pub timed_out_still_running: usize,
480    /// Number of blocking tasks that were still running during observation.
481    pub blocking_still_running: usize,
482    /// Bounded per-lane summaries.
483    pub lanes: Vec<RuntimeBlockingLaneSummaryV1>,
484    /// Whether summaries were omitted by configured bounds.
485    pub truncated: bool,
486}
487
488/// Bounded scheduled-work aggregates.
489#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
490pub struct RuntimeScheduleSectionV2 {
491    /// The population these counts cover.
492    pub scope: RuntimeDiagnosticsScope,
493    /// Number of scheduled tasks examined.
494    pub tasks_scanned: usize,
495    /// Number of scheduled tasks included in the aggregates.
496    pub tasks_emitted: usize,
497    /// Number of runs that are still active.
498    pub active_runs: u64,
499    /// Number of runs started.
500    pub runs: u64,
501    /// Number of skipped ticks.
502    pub skips: u64,
503    /// Number of overlapping runs that were coalesced or refused.
504    pub overlaps: u64,
505    /// Number of failed runs.
506    pub failures: u64,
507    /// Maximum run duration, in milliseconds.
508    pub max_elapsed_millis: u64,
509    /// Whether summaries were omitted by configured bounds.
510    pub truncated: bool,
511}
512
513/// Bounded retained-metadata state.
514#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
515pub struct RuntimeMetadataSectionV2 {
516    /// The population these counts cover.
517    pub scope: RuntimeDiagnosticsScope,
518    /// Whether the metadata actor still accepts work.
519    pub accepting: bool,
520    /// Number of retained operations.
521    pub retained_operations: usize,
522    /// Number of retained payload bytes.
523    pub retained_bytes: usize,
524    /// Number of durability waiters.
525    pub waiters: usize,
526    /// Number of metadata resources examined.
527    pub resources_scanned: usize,
528    /// Number of metadata resources included in the counts.
529    pub resources_emitted: usize,
530    /// Whether resources were omitted by configured bounds.
531    pub truncated: bool,
532}
533
534/// The most recent shutdown result for one group population.
535#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
536pub struct RuntimeShutdownSectionV2 {
537    /// The population this result covers.
538    pub scope: RuntimeDiagnosticsScope,
539    /// Shutdown duration in milliseconds.
540    pub elapsed_millis: u64,
541    /// Number of tasks that were cancelled.
542    pub cancelled: usize,
543    /// Number of tasks that finished with an explicit failure.
544    pub failed: usize,
545    /// Number of tasks that did not finish inside the deadline.
546    pub timed_out: usize,
547    /// Number of tasks that were still tracked after shutdown.
548    pub leaked: usize,
549}
550
551/// One bounded task detail.
552///
553/// Carries a bounded category, the population it was observed in, and its
554/// elapsed time. Task names, group names, and identifiers are deliberately
555/// excluded because they are caller-provided labels.
556#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
557pub struct RuntimeTaskDetailV2 {
558    /// Bounded task category.
559    pub kind: RuntimeTaskKindV1,
560    /// The population the task was observed in.
561    pub scope: RuntimeDiagnosticsScope,
562    /// Elapsed time since the task started, in milliseconds.
563    pub elapsed_millis: u64,
564}
565
566/// Versioned, bounded, and sanitized runtime diagnostics with explicit scopes.
567///
568/// Unlike [`RuntimeDiagnosticsViewV1`], every section states the population it
569/// covers, the payload separates a section that has no input from a section that
570/// is empty, and a bounded detail list reports how much of the tree it examined
571/// instead of presenting a partial list as the whole runtime.
572#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
573pub struct RuntimeDiagnosticsViewV2 {
574    /// Schema identifier for this serialized diagnostics view.
575    pub schema_version: String,
576    /// UTC timestamp at which the snapshot was observed.
577    pub observed_at: DateTime<Utc>,
578    /// Bounded component category that owns the runtime.
579    pub component: RuntimeComponent,
580    /// Current lifecycle state of the root task group.
581    pub lifecycle_state: RuntimeLifecycleStateV1,
582    /// Bounded task counts and their scope.
583    pub tasks: RuntimeTaskSectionV2,
584    /// Bounded blocking state and its scope.
585    pub blocking: RuntimeBlockingSectionV2,
586    /// Bounded scheduled-work aggregates, absent when the caller owns none.
587    #[serde(default, skip_serializing_if = "Option::is_none")]
588    pub schedule: Option<RuntimeScheduleSectionV2>,
589    /// Bounded retained-metadata state, absent when the caller owns no actor.
590    #[serde(default, skip_serializing_if = "Option::is_none")]
591    pub metadata: Option<RuntimeMetadataSectionV2>,
592    /// The most recent shutdown result, absent until shutdown was attempted.
593    #[serde(default, skip_serializing_if = "Option::is_none")]
594    pub shutdown: Option<RuntimeShutdownSectionV2>,
595    /// Bounded task details, empty unless a detail list was requested.
596    pub details: Vec<RuntimeTaskDetailV2>,
597    /// The scan budget applied while collecting details.
598    pub detail_scan_budget: usize,
599    /// Number of tasks examined while collecting details.
600    pub details_scanned: usize,
601    /// Whether any section, including the detail list, was cut short.
602    pub truncated: bool,
603}
604
605/// A bounded detail sample that does not scan aggregate subtree statistics.
606///
607/// This separate API leaves the V1/V2 serialized views and their construction
608/// surfaces unchanged. Labels omit caller-provided names and identifiers.
609#[derive(Debug, Clone, Serialize)]
610pub struct RuntimeTaskDetails {
611    /// Sanitized details that fit the output budget.
612    pub details: Vec<RuntimeTaskDetailV2>,
613    /// Number of task entries examined.
614    pub tasks_scanned: usize,
615    /// Number of descendant registrations examined, including expired entries.
616    pub group_entries_scanned: usize,
617    /// Whether a task, group, or output budget truncated the sample.
618    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    /// Stable schema identifier emitted by [`RuntimeDiagnostics::view_v2`].
642    pub const SCHEMA_VERSION: &'static str = "rocketmq.runtime-diagnostics.v2";
643}
644
645impl RuntimeDiagnostics {
646    /// Creates a bounded, explicitly scoped diagnostics view.
647    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    /// Creates a bounded, explicitly scoped diagnostics view using explicit
664    /// budget limits.
665    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        // A zero budget means no detail list was requested, so a routine sample
699        // neither pays for the scan nor reports truncation for a list nobody
700        // asked for.
701        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        // No detail list was requested, so a routine sample reports no truncation.
994        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        // Empty groups add no tasks, so only the group bound can stop the scan.
1159        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}