openraft 0.10.2

Advanced Raft consensus
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
use std::fmt;
use std::time::Duration;

use base2histogram::PercentileStats;
#[cfg(feature = "runtime-stats")]
use tabled::builder::Builder;
#[cfg(feature = "runtime-stats")]
use tabled::settings::Alignment;
#[cfg(feature = "runtime-stats")]
use tabled::settings::Style;
#[cfg(feature = "runtime-stats")]
use tabled::settings::object::Columns;

use crate::RaftTypeConfig;
use crate::core::NotificationName;
use crate::core::raft_msg::RaftMsgName;
use crate::core::runtime_stats::display_mode::DisplayMode;
use crate::core::runtime_stats::log_stage::LogStageHistograms;
use crate::core::runtime_stats::log_stage::LogStages;
use crate::engine::CommandName;
use crate::type_config::alias::InstantOf;

/// Display data for [`RuntimeStats`](super::RuntimeStats).
///
/// The percentiles are computed and the counters and log-stage records copied when it is created.
/// Each `Display::fmt()` call formats them into text, building the tables and charts of the
/// human-readable mode again. It reads no clock, so the same display gives the same text each time
/// it is formatted, also after the runtime that created it has exited.
///
/// Use [`DisplayMode`] to control the output format.
pub struct RuntimeStatsDisplay<C>
where C: RaftTypeConfig
{
    pub(crate) mode: DisplayMode,
    pub(crate) core_busy_duration: Duration,
    pub(crate) core_busy_histogram: PercentileStats,
    pub(crate) apply_batch: PercentileStats,
    pub(crate) append_batch: PercentileStats,
    pub(crate) replicate_batch: PercentileStats,
    pub(crate) raft_msg_per_run: PercentileStats,
    pub(crate) write_batch: PercentileStats,
    pub(crate) raft_msg_budget: PercentileStats,
    pub(crate) notification_budget: PercentileStats,
    pub(crate) raft_msg_usage_permille: PercentileStats,
    pub(crate) notification_usage_permille: PercentileStats,
    pub(crate) command_counts: Vec<u64>,
    pub(crate) raft_msg_counts: Vec<u64>,
    pub(crate) notification_counts: Vec<u64>,
    pub(crate) log_stage_percentiles: [(&'static str, PercentileStats); 6],
    pub(crate) log_stage_histograms: LogStageHistograms,
    pub(crate) log_stages: LogStages<InstantOf<C>>,
}

impl<C> RuntimeStatsDisplay<C>
where C: RaftTypeConfig
{
    /// Set the display mode.
    pub fn mode(mut self, mode: DisplayMode) -> Self {
        self.mode = mode;
        self
    }

    /// Use compact single-line format.
    pub fn compact(self) -> Self {
        self.mode(DisplayMode::Compact)
    }

    /// Use multiline format.
    pub fn multiline(self) -> Self {
        self.mode(DisplayMode::Multiline)
    }

    /// Use human-readable format.
    pub fn human_readable(self) -> Self {
        self.mode(DisplayMode::HumanReadable)
    }
}

impl<C> fmt::Display for RuntimeStatsDisplay<C>
where C: RaftTypeConfig
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.mode {
            DisplayMode::Compact => self.fmt_compact(f),
            DisplayMode::Multiline => self.fmt_multiline(f),
            DisplayMode::HumanReadable => self.fmt_human_readable(f),
        }
    }
}

impl<C> RuntimeStatsDisplay<C>
where C: RaftTypeConfig
{
    fn fmt_compact(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "RuntimeStats {{ core_busy_duration: {:?}, core_busy_histogram(us): {}, apply_batch: {}, append_batch: {}, replicate_batch: {}, raft_msg_per_run: {}, write_batch: {}, raft_msg_budget: {}, notification_budget: {}, raft_msg_usage_permille: {}, notification_usage_permille: {}, commands: {{",
            self.core_busy_duration,
            self.core_busy_histogram,
            self.apply_batch,
            self.append_batch,
            self.replicate_batch,
            self.raft_msg_per_run,
            self.write_batch,
            self.raft_msg_budget,
            self.notification_budget,
            self.raft_msg_usage_permille,
            self.notification_usage_permille
        )?;

        let mut first = true;
        for (i, name) in CommandName::ALL.iter().enumerate() {
            let count = self.command_counts[i];
            if count > 0 {
                if !first {
                    write!(f, ", ")?;
                }
                write!(f, "{}: {}", name, count)?;
                first = false;
            }
        }

        write!(f, "}}, raft_msgs: {{")?;

        let mut first = true;
        for (i, name) in RaftMsgName::ALL.iter().enumerate() {
            let count = self.raft_msg_counts[i];
            if count > 0 {
                if !first {
                    write!(f, ", ")?;
                }
                write!(f, "{}: {}", name, count)?;
                first = false;
            }
        }

        write!(f, "}}, notifications: {{")?;

        let mut first = true;
        for (i, name) in NotificationName::ALL.iter().enumerate() {
            let count = self.notification_counts[i];
            if count > 0 {
                if !first {
                    write!(f, ", ")?;
                }
                write!(f, "{}: {}", name, count)?;
                first = false;
            }
        }

        write!(f, "}}, log_stages(us): {{")?;

        let mut first = true;
        for (name, stats) in &self.log_stage_percentiles {
            if stats.samples > 0 {
                if !first {
                    write!(f, ", ")?;
                }
                write!(f, "{}: {}", name, stats)?;
                first = false;
            }
        }

        write!(f, "}} }}")
    }

    fn fmt_multiline(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(f, "RuntimeStats:")?;
        writeln!(f, "  core_busy_duration: {:?}", self.core_busy_duration)?;
        writeln!(f, "  core_busy_histogram(us): {}", self.core_busy_histogram)?;
        writeln!(f, "  apply_batch: {}", self.apply_batch)?;
        writeln!(f, "  append_batch: {}", self.append_batch)?;
        writeln!(f, "  replicate_batch: {}", self.replicate_batch)?;
        writeln!(f, "  raft_msg_per_run: {}", self.raft_msg_per_run)?;
        writeln!(f, "  write_batch: {}", self.write_batch)?;
        writeln!(f, "  raft_msg_budget: {}", self.raft_msg_budget)?;
        writeln!(f, "  notification_budget: {}", self.notification_budget)?;
        writeln!(f, "  raft_msg_usage_permille: {}", self.raft_msg_usage_permille)?;
        writeln!(f, "  notification_usage_permille: {}", self.notification_usage_permille)?;

        writeln!(f, "  commands:")?;
        for (i, name) in CommandName::ALL.iter().enumerate() {
            let count = self.command_counts[i];
            if count > 0 {
                writeln!(f, "    {}: {}", name, count)?;
            }
        }

        writeln!(f, "  raft_msgs:")?;
        for (i, name) in RaftMsgName::ALL.iter().enumerate() {
            let count = self.raft_msg_counts[i];
            if count > 0 {
                writeln!(f, "    {}: {}", name, count)?;
            }
        }

        writeln!(f, "  notifications:")?;
        for (i, name) in NotificationName::ALL.iter().enumerate() {
            let count = self.notification_counts[i];
            if count > 0 {
                writeln!(f, "    {}: {}", name, count)?;
            }
        }

        writeln!(f, "  log_stages(us):")?;
        for (name, stats) in &self.log_stage_percentiles {
            if stats.samples > 0 {
                writeln!(
                    f,
                    "    {:>22}: n={} p50={} p90={} p99={} p99.9={}",
                    name, stats.samples, stats.p50, stats.p90, stats.p99, stats.p99_9,
                )?;
            }
        }

        // Wall-clock timestamps would need the current time of the runtime that recorded them,
        // which may have exited, so proposals are shown relative to the first one.
        let mut lines = self.log_stages.relative_display_lines().peekable();
        if lines.peek().is_some() {
            writeln!(f, "  log_stage_segments (T: proposal of the first segment):")?;
            for line in lines {
                writeln!(f, "    {}", line)?;
            }
        }

        Ok(())
    }

    #[cfg(feature = "runtime-stats")]
    fn fmt_human_readable(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(f, "Core busy duration: {:?}", self.core_busy_duration)?;
        writeln!(f)?;
        writeln!(f, "Core loop busy (us):")?;
        let mut builder = Builder::default();
        builder.push_record([
            "", "#Samples", "P0.1", "P1", "P5", "P10", "P50", "P90", "P99", "P99.9", "",
        ]);
        builder.push_record(Self::percentile_row(
            "Busy",
            &self.core_busy_histogram,
            "Wall time of one core-loop turn",
        ));
        let mut table = builder.build();
        table.with(Style::rounded());
        table.with(Alignment::right());
        table.modify(Columns::first(), Alignment::left());
        table.modify(Columns::last(), Alignment::left());
        writeln!(f, "{}", table)?;

        // Batch sizes table
        writeln!(f, "Batch Sizes:")?;
        let mut builder = Builder::default();
        builder.push_record([
            "", "#Samples", "P0.1", "P1", "P5", "P10", "P50", "P90", "P99", "P99.9", "",
        ]);
        builder.push_record(Self::percentile_row(
            "Apply",
            &self.apply_batch,
            "Entries per state machine apply",
        ));
        builder.push_record(Self::percentile_row(
            "Append",
            &self.append_batch,
            "Entries per storage append",
        ));
        builder.push_record(Self::percentile_row(
            "Replicate",
            &self.replicate_batch,
            "Entries per replication RPC",
        ));
        builder.push_record(Self::percentile_row(
            "RaftMsg/run",
            &self.raft_msg_per_run,
            "RaftMsgs per run_engine_commands()",
        ));
        builder.push_record(Self::percentile_row(
            "Write",
            &self.write_batch,
            "Client writes merged per batch",
        ));
        let mut table = builder.build();
        table.with(Style::rounded());
        table.with(Alignment::right());
        table.modify(Columns::first(), Alignment::left());
        table.modify(Columns::last(), Alignment::left());
        writeln!(f, "{}", table)?;

        // Budget & utilization table
        writeln!(f, "Budget & Utilization:")?;
        let mut builder = Builder::default();
        builder.push_record([
            "", "#Samples", "P0.1", "P1", "P5", "P10", "P50", "P90", "P99", "P99.9", "",
        ]);
        builder.push_record(Self::percentile_row(
            "RaftMsgBudget",
            &self.raft_msg_budget,
            "Max RaftMsgs allowed per loop",
        ));
        builder.push_record(Self::percentile_row(
            "NotifyBudget",
            &self.notification_budget,
            "Max Notifications allowed per loop",
        ));
        builder.push_record(Self::percentile_row(
            "RaftMsgUsage‰",
            &self.raft_msg_usage_permille,
            "RaftMsg budget utilization (‰)",
        ));
        builder.push_record(Self::percentile_row(
            "NotifyUsage‰",
            &self.notification_usage_permille,
            "Notification budget utilization (‰)",
        ));
        let mut table = builder.build();
        table.with(Style::rounded());
        table.with(Alignment::right());
        table.modify(Columns::first(), Alignment::left());
        table.modify(Columns::last(), Alignment::left());
        writeln!(f, "{}", table)?;

        // Commands table with right-aligned counts
        let mut builder = Builder::default();
        builder.push_record(["Command", "Count"]);
        for (i, name) in CommandName::ALL.iter().enumerate() {
            let count = self.command_counts[i];
            if count > 0 {
                builder.push_record([name.to_string(), Self::format_count(count)]);
            }
        }
        if builder.count_records() > 1 {
            writeln!(f, "Commands:")?;
            let mut table = builder.build();
            table.with(Style::rounded());
            table.modify(Columns::last(), Alignment::right());
            writeln!(f, "{}", table)?;
        }

        // Raft messages table with right-aligned counts
        let mut builder = Builder::default();
        builder.push_record(["Message", "Count"]);
        for (i, name) in RaftMsgName::ALL.iter().enumerate() {
            let count = self.raft_msg_counts[i];
            if count > 0 {
                builder.push_record([name.to_string(), Self::format_count(count)]);
            }
        }
        if builder.count_records() > 1 {
            writeln!(f, "Raft Messages:")?;
            let mut table = builder.build();
            table.with(Style::rounded());
            table.modify(Columns::last(), Alignment::right());
            writeln!(f, "{}", table)?;
        }

        // Notifications table with right-aligned counts
        let mut builder = Builder::default();
        builder.push_record(["Notification", "Count"]);
        for (i, name) in NotificationName::ALL.iter().enumerate() {
            let count = self.notification_counts[i];
            if count > 0 {
                builder.push_record([name.to_string(), Self::format_count(count)]);
            }
        }
        if builder.count_records() > 1 {
            writeln!(f, "Notifications:")?;
            let mut table = builder.build();
            table.with(Style::rounded());
            table.modify(Columns::last(), Alignment::right());
            writeln!(f, "{}", table)?;
        }

        // Log stage latencies table (microseconds)
        let mut builder = Builder::default();
        builder.push_record(["", "#Samples", "P0.1", "P1", "P5", "P10", "P50", "P90", "P99", "P99.9"]);
        for (name, stats) in &self.log_stage_percentiles {
            if stats.samples > 0 {
                builder.push_record([
                    name.to_string(),
                    Self::format_count(stats.samples),
                    stats.p0_1.to_string(),
                    stats.p1.to_string(),
                    stats.p5.to_string(),
                    stats.p10.to_string(),
                    stats.p50.to_string(),
                    stats.p90.to_string(),
                    stats.p99.to_string(),
                    stats.p99_9.to_string(),
                ]);
            }
        }
        if builder.count_records() > 1 {
            writeln!(f, "Log Stage Latencies (us):")?;
            let mut table = builder.build();
            table.with(Style::rounded());
            table.with(Alignment::right());
            table.modify(Columns::first(), Alignment::left());
            writeln!(f, "{}", table)?;

            let chart = self.log_stage_histograms.ascii_chart();
            writeln!(f, "Log Stage Latency Distribution (us):")?;
            write!(f, "{}", chart.detailed())?;
        }

        Ok(())
    }

    /// Create a row with percentile values for the batch sizes table.
    #[cfg(feature = "runtime-stats")]
    fn percentile_row(name: &str, stats: &PercentileStats, comment: &str) -> [String; 11] {
        [
            name.to_string(),
            Self::format_count(stats.samples),
            stats.p0_1.to_string(),
            stats.p1.to_string(),
            stats.p5.to_string(),
            stats.p10.to_string(),
            stats.p50.to_string(),
            stats.p90.to_string(),
            stats.p99.to_string(),
            stats.p99_9.to_string(),
            comment.to_string(),
        ]
    }

    /// Fallback when tabled is not available.
    #[cfg(not(feature = "runtime-stats"))]
    fn fmt_human_readable(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.fmt_multiline(f)
    }

    /// Format count with a thousand separators for readability.
    #[cfg(feature = "runtime-stats")]
    fn format_count(n: u64) -> String {
        let s = n.to_string();
        let mut result = String::new();
        for (i, c) in s.chars().rev().enumerate() {
            if i > 0 && i % 3 == 0 {
                result.push(',');
            }
            result.push(c);
        }
        result.chars().rev().collect()
    }
}

#[cfg(test)]
mod runtime_stats_display_test;