pigeonhole 1.3.2

Embedded, single-file, wide-column store: BigTable's data model with SQLite's deployment model.
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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
//! The engine's counters ([`Pigeonhole::engine_metrics`](crate::Pigeonhole::engine_metrics),
//! ICR 0044).

use crate::Durability;

/// What the writer has done since this instance opened: commits and their latency,
/// flushes, compactions, write stalls, the block cache, file growth, reader slots, the
/// engine's threads, transactions and cross-shard commits (ICR 0044, ICR 0087).
///
/// **Cumulative counters** (most fields) start at 0 when the database opens and only grow
/// while it is open. Nothing resets them; a reopen starts again from 0. To measure an
/// interval, take two readings and subtract. **Gauges** (marked so below) report the value
/// now. Durations are nanoseconds; sizes are bytes.
///
/// **Two lifetimes.** The engine's fields restart from 0 when an automatic recovery
/// (`Options::auto_recover`) swaps in a new engine. The three transaction counters
/// (`transactions`, `transaction_conflicts`, `transaction_retries`) are kept by the handle
/// and span recoveries. Subtract readings taken across a recovery only for those three.
///
/// Every field is a sum over the shards. Reading is cheap (about 300 relaxed atomic loads
/// per shard, no I/O), so a monitoring loop can call it every second; it never waits for a
/// shard.
///
/// ```
/// # use pigeonhole::{Durability, Family, Options, Pigeonhole};
/// # let dir = pigeonhole::doc_support::temp_dir();
/// # let db = Pigeonhole::open(dir.join("m.phdb"), Options::default())?;
/// # let t = db.table("t")?.family("f", Family::default()).create_if_missing()?;
/// let before = db.engine_metrics();
/// t.mutate(b"row").put("f", b"q", b"v").commit()?;
/// let after = db.engine_metrics();
/// let commits = after.commits(Durability::GroupSync).count - before.commits(Durability::GroupSync).count;
/// assert_eq!(commits, 1);
/// assert_eq!(after.write_stalls - before.write_stalls, 0);
/// # drop(t);
/// # db.close()?;
/// # Ok::<(), pigeonhole::Error>(())
/// ```
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct EngineMetrics {
    commits: [CommitStats; 4],
    commit_latency: [LatencyHistogram; 4],
    /// Memtable flushes completed (each writes one or more SSTs into the file).
    pub flushes: u64,
    /// Flushes that failed. They are retried after a growing backoff; the WAL keeps their
    /// data, so a failure loses nothing.
    pub flush_failures: u64,
    /// Compactions completed, background and requested (`compact()`).
    pub compactions: u64,
    /// Compactions that failed or could not start. Their slot backs off, then retries.
    pub compaction_failures: u64,
    /// Compactions an application-owned background worker
    /// ([`Pigeonhole::open_application_owned`](crate::Pigeonhole::open_application_owned),
    /// D284) held when its shard took them back, at the close or when the worker was
    /// dropped. They were dropped before their commit: not failures, and their slots compact
    /// again.
    pub compactions_reclaimed: u64,
    /// Flushes and compactions the shards took back from the background workers' queue
    /// because no worker looked at it for 10 ms: workers configured but not driven. 0 while
    /// the workers are driven; a count that keeps growing means a loop forgot its workers.
    pub background_fallback_take_backs: u64,
    /// Flushes a commit's wait for memtable room took back from a background worker that
    /// held them for 2 ms without running them. 0 while the workers are driven.
    pub background_room_take_backs: u64,
    /// Write stalls: times a shard paced or held its commits because L0 was too deep, or
    /// because its memtable arena had no room until a flush freed some. The sum of
    /// `room_stalls` and `pacing_stalls`.
    pub write_stalls: u64,
    /// Nanoseconds the shards spent in those stalls, summed over shards: the sum of
    /// `room_stall_nanos` and `pacing_stall_nanos`.
    pub write_stall_nanos: u64,
    /// Times a shard held its commits because its memtable arena had no room, until a
    /// flush freed some. Many of these point at arena pressure: too small an arena, or
    /// snapshots holding flushed memtables.
    pub room_stalls: u64,
    /// Nanoseconds the shards spent waiting for arena room, summed over shards.
    pub room_stall_nanos: u64,
    /// Times a shard paced its commits because L0 was too deep, until compaction caught
    /// up. Many of these point at compaction debt.
    pub pacing_stalls: u64,
    /// Nanoseconds the shards spent pacing commits, summed over shards.
    pub pacing_stall_nanos: u64,
    /// Block cache lookups that found the block. With the cache disabled
    /// (`Options::block_cache(0)`) nothing is counted.
    pub block_cache_hits: u64,
    /// Block cache lookups that did not, so the block was read from the file.
    pub block_cache_misses: u64,
    /// Gauge: the block cache's capacity in bytes (`Options::block_cache`).
    pub block_cache_capacity_bytes: u64,
    /// Gauge: bytes of SST top indexes and filters pinned in the block cache by the open
    /// SSTs. They count against the capacity and are never evicted: past about half of it,
    /// index partitions and data blocks no longer stay cached and a cold read costs two
    /// reads rather than one. Size the cache to at least twice this.
    pub block_cache_pinned_bytes: u64,
    /// Times `block_cache_pinned_bytes` rose past half the capacity: a warning that the
    /// cache is too small for the open SSTs' metadata. Counted at most once until the pinned
    /// bytes fall below 40% of the capacity again.
    pub block_cache_pinned_warnings: u64,
    /// Times the file grew because the page allocator ran out of free space.
    pub file_growths: u64,
    /// Nanoseconds those growths held the page allocator.
    pub file_growth_nanos: u64,
    /// Free blocks given back to the filesystem as holes
    /// ([`Options::punch_freed`](crate::Options::punch_freed), D333). 0 with it off.
    pub file_punches: u64,
    /// Nanoseconds those punches took.
    pub file_punch_nanos: u64,
    /// Bytes those punches gave back.
    pub file_punch_bytes: u64,
    /// Gauge: free bytes of the file that are holes now. The file's length less this is
    /// about what it occupies on disk; space reused since its punch no longer counts.
    pub file_punched_bytes: u64,
    /// Punch passes started (a background pass punches a bounded amount, paced).
    pub file_punch_passes: u64,
    /// Punches that failed. A filesystem that cannot punch fails once, and punching stops
    /// until the next open; one that keeps failing otherwise retries as free space grows,
    /// or at the first manifest commit (a flush, compaction or catalog change, say) 10 s
    /// after a failure. Many of these point at the filesystem, not the database.
    pub file_punch_refusals: u64,
    /// File reads made synchronously inside async reads: a separated value too large to
    /// cache, a block the cache could not keep, or a read that missed too often. 0 when
    /// async reads never block their executor thread.
    pub async_sync_reads: u64,
    /// Nanoseconds the engine-owned shard threads spent working (handling messages and
    /// background tasks; not spinning or parked), summed over shards. Its rise over an
    /// interval, divided by the interval, is how many shards' worth of work the database
    /// did. Application-owned shards count nothing.
    pub shard_busy_nanos: u64,
    /// Gauge: bytes of the memtable arenas that memtables take now, summed over shards
    /// (ICR 0116). It counts whole chunks, partly filled ones included, so it reads high by
    /// up to one chunk per live memtable. It also counts flushed memtables whose chunks
    /// aren't reusable yet, because a snapshot or an in-flight read still holds them: what
    /// matters for room, which they take as surely as live ones (perf287 on #1512). The
    /// arena updates it itself whenever chunks are taken or given back, never per commit.
    ///
    /// Against [`memtable_limit_bytes`](Self::memtable_limit_bytes), it shows how close the
    /// shards are to waiting for room, but only approximately. A commit can wait while this
    /// reads well under the limit: room other commits have reserved but not yet written,
    /// a cross-shard commit's share held until its decision, or a value too large for the
    /// free chunks' longest run. Those waits are [`room_stalls`](Self::room_stalls), the
    /// ground truth (cli692 on #1512).
    pub memtable_bytes: u64,
    /// Gauge: the memtable arenas' size, summed over shards (ICR 0116):
    /// `Options::memtable_budget`, which is per shard, rounded up to 2 MiB, times the shard
    /// count.
    pub memtable_limit_bytes: u64,
    /// Gauge: reader processes attached ([`Pigeonhole::open_reader`](crate::Pigeonhole::open_reader)
    /// handles holding a slot), out of [`reader_slots`](Self::reader_slots).
    pub reader_slots_active: u64,
    /// Gauge: the reader slot count ([`Options::reader_slots`](crate::Options::reader_slots)).
    pub reader_slots: u64,
    /// Reader slots freed because their process exited or was killed without closing.
    pub reader_slots_reclaimed: u64,
    /// Gauge: how many sequence numbers behind the visible one the oldest reader snapshot is
    /// (0 with none).
    pub reader_pin_seqno_lag: u64,
    /// Gauge: threads the engine started (shard and compaction threads). 0 in
    /// application-owned mode or once closed.
    pub threads_started: u64,
    /// Gauge: of those, threads pinned to a CPU of their own (`Options::pin_threads`).
    pub threads_pinned: u64,
    /// Gauge: of those, compaction threads confined to
    /// [`Options::compaction_cpu_set`](crate::Options::compaction_cpu_set) rather than pinned
    /// (ICR 0134). They run on those CPUs, shared, so they're neither pinned nor unpinned.
    pub threads_confined: u64,
    /// Gauge: why threads are unpinned although `pin_threads` asked for them, for people to
    /// read (the wording may change): the platform has no hard thread affinity (macOS), a
    /// CPU quota is narrower than the affinity set, too few free CPUs (with room for the
    /// shards only, just the compaction threads are unpinned), or the OS refused. `None`
    /// when every thread is pinned or pinning is off.
    pub unpinned_reason: Option<&'static str>,
    /// Transactions committed through this handle since open, write-free ones included
    /// (ICR 0061). Unlike the engine's counters, the three transaction counters span
    /// automatic recoveries (`Options::auto_recover`).
    pub transactions: u64,
    /// Transaction commits that failed with [`ErrorCode::Conflict`](crate::ErrorCode::Conflict).
    /// Over `transactions + transaction_conflicts`, the conflict rate.
    pub transaction_conflicts: u64,
    /// Attempts [`Pigeonhole::transact`](crate::Pigeonhole::transact) retried, for any
    /// reason its policy retries. A retry loop of the application's own (around
    /// [`RetryPolicy::next_pause`](crate::RetryPolicy::next_pause), say) is not counted.
    pub transaction_retries: u64,
    /// Cross-shard commits: their two-phase rounds and the commits that failed fast.
    pub cross_shard: CrossShardMetrics,
    /// Group syncs finished, a failed one included: each is one WAL sync covering the
    /// [`Durability::GroupSync`](crate::Durability::GroupSync) commits batched behind it,
    /// however many there were. A group of `Buffered` commits takes one too when its record
    /// lands in a WAL segment whose header still waits for the previous rollover's sync, so
    /// a few appear without `GroupSync` commits (at most one per rollover). Counted with the change feed on or off, so it isn't a feed
    /// cost on its own: set the `feed_*` syncs beside it. Its rise over an interval, against
    /// the `GroupSync` commits', is the commits each sync carried.
    pub group_syncs: u64,
    /// Nanoseconds the group syncs were in flight, summed over shards (ICR 0116): each
    /// sync adds its own duration, so its rise over an interval, divided by
    /// [`group_syncs`](Self::group_syncs)', is the mean group sync time, even with several
    /// syncs in flight at once. It covers group syncs only, the ones `group_syncs` counts
    /// (those of groups with a `GroupSync` commit, or held behind a rollover's sync): a
    /// `Sync` commit's own sync and flushes' and checkpoints' barrier syncs aren't in it. It's
    /// current as of the last time a group sync started or finished on its shard, so a
    /// sync still in flight counts from then (perf287 and cli692 on #1521).
    pub group_sync_nanos: u64,
    /// Syncs the change feed submitted on its own (D310): fed `Buffered` or `None` commits
    /// waited longer than the feed's sync interval for one and no commit's sync covered
    /// them. What a durable feed costs in syncs beyond the commits' own. 0 while the feed is
    /// off. For the feed's retained history, see
    /// [`DatabaseInfo::feed`](crate::DatabaseInfo::feed).
    pub feed_background_syncs: u64,
    /// Syncs of the change feed's sidecar file (`<db>-feed`, D310): at most one in flight,
    /// covering the sidecar entries of the flushes, checkpoints and catalog changes since the
    /// last one, never per commit. 0 while the feed is off. See
    /// [`DatabaseInfo::feed`](crate::DatabaseInfo::feed) for the feed's state.
    pub feed_sidecar_syncs: u64,
}

impl EngineMetrics {
    /// Commits at `durability` and their latency.
    pub fn commits(&self, durability: Durability) -> CommitStats {
        self.commits[durability as usize]
    }

    /// The latency histogram of the commits at `durability` since open (ICR 0115): the
    /// buckets [`commits`](Self::commits)' percentiles come from. Unlike those, two readings
    /// subtracted ([`LatencyHistogram::since`]) give an interval's latency, so a regression
    /// shows up within that interval rather than being diluted by everything since open.
    ///
    /// ```
    /// # use pigeonhole::{Durability, Family, Options, Pigeonhole};
    /// # let dir = pigeonhole::doc_support::temp_dir();
    /// # let db = Pigeonhole::open(dir.join("h.phdb"), Options::default())?;
    /// # let t = db.table("t")?.family("f", Family::default()).create_if_missing()?;
    /// let before = db.engine_metrics().commit_latency(Durability::GroupSync);
    /// t.mutate(b"row").put("f", b"q", b"v").commit()?;
    /// let interval = db.engine_metrics().commit_latency(Durability::GroupSync).since(&before);
    /// assert_eq!(interval.total(), 1);
    /// let p99 = interval.quantile_upper_nanos(0.99).unwrap();
    /// assert!(p99 > 0);
    /// # drop(t);
    /// # db.close()?;
    /// # Ok::<(), pigeonhole::Error>(())
    /// ```
    pub fn commit_latency(&self, durability: Durability) -> LatencyHistogram {
        self.commit_latency[durability as usize]
    }
}

/// The commit latency histogram of one durability level
/// ([`EngineMetrics::commit_latency`], ICR 0115).
///
/// **What it measures:** each commit's time from its submission to its resolution on its
/// shard, the engine side of the commit. It leaves out the caller's wake-up, the wait for
/// the commit to become visible and the return, which is where a commit's tail latency
/// often is: measure end-to-end latency in the application.
///
/// **Buckets:** [`BUCKETS`](Self::BUCKETS) half-power-of-two buckets, cumulative since open
/// and summed over shards. Bucket `b` counts the commits from
/// [`bucket_lower_nanos(b)`](Self::bucket_lower_nanos) up to, not including,
/// [`bucket_upper_nanos(b)`](Self::bucket_upper_nanos). Adjacent bounds differ by a factor of
/// 1.5 or 1.33 (about 1.41 on average), so a quantile is known to within one bucket. The
/// last bucket, from about 3.2 seconds, has no upper bound.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LatencyHistogram {
    counts: [u64; LatencyHistogram::BUCKETS],
}

impl Default for LatencyHistogram {
    fn default() -> Self {
        Self {
            counts: [0; Self::BUCKETS],
        }
    }
}

impl LatencyHistogram {
    /// The number of buckets.
    pub const BUCKETS: usize = 64;

    /// The commits counted in each bucket, bucket 0 first: [`BUCKETS`](Self::BUCKETS) of
    /// them. A slice, so a later release can change the bucket count without breaking it.
    pub fn counts(&self) -> &[u64] {
        &self.counts
    }

    /// The commits counted in all the buckets.
    pub fn total(&self) -> u64 {
        self.counts.iter().sum()
    }

    /// The smallest latency, in nanoseconds, that bucket `b` counts. Panics if `b` is not
    /// below [`BUCKETS`](Self::BUCKETS).
    pub fn bucket_lower_nanos(b: usize) -> u64 {
        assert!(b < Self::BUCKETS, "bucket {b} of {}", Self::BUCKETS);
        if b <= 1 {
            // Bucket 0 counts 0 and 1 ns; bucket 1 is never used.
            0
        } else {
            pigeonhole_engine::Engine::commit_latency_floor(b)
        }
    }

    /// The latency, in nanoseconds, at which bucket `b` ends (the next bucket's lower
    /// bound), or `None` for the last bucket, which has no end. Panics if `b` is not below
    /// [`BUCKETS`](Self::BUCKETS).
    pub fn bucket_upper_nanos(b: usize) -> Option<u64> {
        assert!(b < Self::BUCKETS, "bucket {b} of {}", Self::BUCKETS);
        (b + 1 < Self::BUCKETS).then(|| Self::bucket_lower_nanos(b + 1).max(2))
    }

    /// The commits counted since `earlier`, a reading of the same histogram taken before
    /// this one: bucket by bucket, this reading's count less `earlier`'s. A bucket that
    /// went down, as the counts do when an automatic recovery
    /// (`Options::auto_recover`) starts a new engine, counts 0.
    pub fn since(&self, earlier: &LatencyHistogram) -> LatencyHistogram {
        LatencyHistogram {
            counts: std::array::from_fn(|b| self.counts[b].saturating_sub(earlier.counts[b])),
        }
    }

    /// The `q` quantile (`0.99` for p99), as the upper bound in nanoseconds of the bucket it
    /// falls in, so it errs high: at least a fraction `q` of the commits took less. The one
    /// exception is the last bucket, which has no upper bound: a quantile there reports that
    /// bucket's lower bound (about 3.2 seconds), and the commits it counts took at least
    /// that long. `None` when the histogram is empty or `q` is outside `0.0..=1.0` (NaN
    /// included).
    pub fn quantile_upper_nanos(&self, q: f64) -> Option<u64> {
        if !(0.0..=1.0).contains(&q) {
            return None;
        }
        let total = self.total();
        if total == 0 {
            return None;
        }
        let target = ((total as f64 * q).ceil() as u64).max(1);
        let mut seen = 0;
        for (b, &n) in self.counts.iter().enumerate() {
            seen += n;
            if seen >= target {
                return Some(
                    Self::bucket_upper_nanos(b).unwrap_or_else(|| Self::bucket_lower_nanos(b)),
                );
            }
        }
        None
    }
}

/// Commits at one durability level ([`EngineMetrics::commits`]).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct CommitStats {
    /// Commits completed at this level.
    pub count: u64,
    /// Median commit latency, in nanoseconds, from submission to the result, over every
    /// commit since open. Latencies are kept in half-power-of-two buckets, so this is the
    /// lower edge of the bucket the percentile falls in (within a factor of 1.5).
    pub p50_nanos: u64,
    /// The 99th percentile, as `p50_nanos`.
    pub p99_nanos: u64,
    /// The 99.9th percentile, as `p50_nanos`.
    pub p999_nanos: u64,
}

/// Cross-shard commits ([`EngineMetrics::cross_shard`], ICR 0043, ICR 0087). Cumulative
/// since open.
///
/// A commit whose rows are on several shards runs as two-phase rounds. A participant that
/// cannot take its share makes the round abort everywhere, and the commit runs again in a
/// new round (or fails with `Busy` at the write-stall timeout), so `rounds` over the
/// cross-shard commits in an interval is the rounds each commit took.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct CrossShardMetrics {
    /// Two-phase rounds decided.
    pub rounds: u64,
    /// Commits that failed with `Conflict` without another round: a round was refused
    /// because it overlapped another commit's undecided share, and that share committed a
    /// write to a row this commit read, after its snapshot, so a retry could only fail
    /// validation (D276, ICR 0066). Counted once per commit.
    pub failed_fast: u64,
}

impl EngineMetrics {
    pub(crate) fn from_engine(m: pigeonhole_engine::Metrics) -> Self {
        let x = m.cross_shard;
        Self {
            commits: std::array::from_fn(|d| CommitStats {
                count: m.commits[d],
                p50_nanos: m.commit_latency_nanos[d][0],
                p99_nanos: m.commit_latency_nanos[d][1],
                p999_nanos: m.commit_latency_nanos[d][2],
            }),
            commit_latency: std::array::from_fn(|d| LatencyHistogram {
                counts: m.commit_latency_buckets[d].0,
            }),
            flushes: m.flushes,
            flush_failures: m.flush_failures,
            compactions: m.compactions,
            compaction_failures: m.compaction_failures,
            compactions_reclaimed: m.compactions_reclaimed,
            background_fallback_take_backs: m.background_take_backs.0,
            background_room_take_backs: m.background_take_backs.1,
            write_stalls: m.stalls.0,
            write_stall_nanos: m.stalls.1,
            room_stalls: m.room_stalls.0,
            room_stall_nanos: m.room_stalls.1,
            pacing_stalls: m.pacing_stalls.0,
            pacing_stall_nanos: m.pacing_stalls.1,
            block_cache_hits: m.block_cache.0,
            block_cache_misses: m.block_cache.1,
            block_cache_capacity_bytes: m.block_cache_capacity,
            block_cache_pinned_bytes: m.block_cache_pinned,
            block_cache_pinned_warnings: m.block_cache_pinned_warnings,
            file_growths: m.file_growths.0,
            file_growth_nanos: m.file_growths.1,
            file_punches: m.file_punches.0,
            file_punch_nanos: m.file_punches.1,
            file_punch_bytes: m.file_punch_bytes,
            file_punched_bytes: m.file_punched_bytes,
            file_punch_passes: m.file_punch_passes.0,
            file_punch_refusals: m.file_punch_passes.1,
            async_sync_reads: m.async_sync_reads,
            shard_busy_nanos: m.shard_busy_nanos,
            memtable_bytes: m.memtable_bytes,
            memtable_limit_bytes: m.memtable_limit,
            group_sync_nanos: m.group_sync_nanos,
            reader_slots_active: m.reader_slots.0,
            reader_slots: m.reader_slots.1,
            reader_slots_reclaimed: m.reader_slots_reclaimed,
            reader_pin_seqno_lag: m.reader_pin_lag.1,
            // The engine fills `pinned_threads` as (pinned, started).
            threads_started: m.pinned_threads.1,
            threads_pinned: m.pinned_threads.0,
            threads_confined: m.confined_threads,
            unpinned_reason: m.unpinned,
            // Filled from the handle's own counters (`Pigeonhole::engine_metrics`).
            transactions: 0,
            transaction_conflicts: 0,
            transaction_retries: 0,
            cross_shard: CrossShardMetrics {
                rounds: x.rounds,
                failed_fast: x.failed_fast,
            },
            group_syncs: 0,
            feed_background_syncs: 0,
            feed_sidecar_syncs: 0,
        }
    }
}

/// Counters outside [`EngineMetrics`], by name (`Pigeonhole::internal_metrics`, ICR 0087): the engine's mechanisms that 1.x may
/// change or remove, for benchmarks and tests. Names, and whether a name is present at all,
/// may change in any release; a reader treats a missing name as absent.
#[cfg(feature = "__unstable-hooks")]
pub(crate) fn internal(
    m: &pigeonhole_engine::Metrics,
    pooled: Option<usize>,
    nowait: Option<pigeonhole_io::NowaitReads>,
) -> Vec<(&'static str, u64)> {
    let x = &m.cross_shard;
    let mut v = vec![
        ("wal_unpin_passes", m.unpin.0),
        ("wal_unpin_flushes", m.unpin.1),
        ("wal_inline_syncs", m.wal_inline_syncs),
        ("wal_rollover_blocks", m.wal_rollover_blocks),
        ("file_growths_ahead", m.file_growths_ahead.0),
        ("file_growth_ahead_nanos", m.file_growths_ahead.1),
        ("default_ts_lead_micros", m.default_ts_lead_micros.0),
        ("max_default_ts_lead_micros", m.default_ts_lead_micros.1),
        ("shard_parks", m.shard_idle.0),
        ("shard_wakes", m.shard_idle.1),
        ("shard_pool_busy_nanos", m.shard_pool_busy_nanos),
        ("shard_spin_time_nanos", m.shard_spin_time_nanos),
        ("caller_turns", m.caller_turns),
        ("caller_backstop_wakes", m.caller_backstop_wakes),
        ("shard_commit_inflight_nanos", m.shard_commit_inflight_nanos),
        ("commit_parks", m.commit_parks),
        (
            "block_cache_deferred_evictions",
            m.cache_deferred_evictions.0,
        ),
        ("row_cache_deferred_evictions", m.cache_deferred_evictions.1),
        ("reader_pin_view_lag", m.reader_pin_lag.0),
        ("visibility_waits", m.visibility_waits.0),
        ("visibility_waiters_ahead", m.visibility_waits.1),
        ("visibility_wake_passes", m.visibility_wakes.0),
        ("visibility_woken", m.visibility_wakes.1),
        ("visibility_contended", m.visibility_contended),
        ("cross_shard.refused_rounds", x.refused_rounds),
        ("cross_shard.refused_moved", x.refused_moved),
        ("cross_shard.refused_room", x.refused_room),
        (
            "cross_shard.refused_pending_overlap",
            x.refused_pending_overlap,
        ),
        ("cross_shard.share_waits", x.share_waits),
        ("cross_shard.share_wait_nanos", x.share_wait_nanos),
        ("cross_shard.chained", x.chained),
        ("cross_shard.wounds", x.wounds),
        ("cross_shard.max_attempts_blind", x.max_attempts_blind),
        ("cross_shard.max_attempts_reading", x.max_attempts_reading),
    ];
    if let Some(p) = pooled {
        v.push(("io_rings.pooled", p as u64));
    }
    if let Some(n) = nowait {
        v.extend([
            ("nowait.on", u64::from(n.on)),
            ("nowait.hits", n.hits),
            ("nowait.misses", n.misses),
            ("nowait.miss_nanos", n.miss_nanos),
            ("nowait.refused", n.refused),
            ("nowait.breaks", n.breaks),
        ]);
    }
    v
}

/// What the row cache did since open
/// ([`Pigeonhole::row_cache_stats`](crate::Pigeonhole::row_cache_stats)). Cumulative from 0
/// at open.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct RowCacheStats {
    /// Family rows and gets answered from the cache.
    pub hits: u64,
    /// Lookups that found nothing usable (absent, older epoch, expired).
    pub misses: u64,
    /// Family rows stored.
    pub fills: u64,
    /// Cached family rows a commit moved forward to its own write (D290's write-through),
    /// instead of leaving them to miss.
    pub write_throughs: u64,
}

impl RowCacheStats {
    pub(crate) fn from_engine(engine: &pigeonhole_engine::Engine) -> Self {
        let s = engine.row_cache_stats();
        Self {
            hits: s.hits,
            misses: s.misses,
            fills: s.fills,
            write_throughs: engine.row_cache_write_throughs(),
        }
    }
}

/// One shard's share of the work, for benchmarks that check writes spread over shards
/// (ICR 0010, a hidden bench hook outside the semver promise). Counters are cumulative since
/// open; take two and subtract for a phase. The fields are the engine's
/// (`pigeonhole_engine::ShardStats`).
#[cfg(feature = "__unstable-hooks")]
#[doc(hidden)]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct ShardStats {
    /// Commits the shard applied, summed over durability levels.
    pub commits: u64,
    /// Tablets the shard owns in the current view, over every table.
    pub tablets: u64,
    /// Splits the shard completed.
    pub splits: u64,
    /// Merges the shard completed.
    pub merges: u64,
    /// Moves the shard completed.
    pub moves: u64,
    /// Nanoseconds the shard's engine-owned thread spent in work turns (D217).
    pub busy_nanos: u64,
    /// Nanoseconds of group-sync in-flight time (D248).
    pub sync_busy_nanos: u64,
    /// Nanoseconds the compaction pool spent on this shard's work (D256).
    pub pool_busy_nanos: u64,
    /// Nanoseconds the shard's thread spent spinning before parking (D198, D256).
    pub spin_time_nanos: u64,
    /// Nanoseconds the shard's client commits spent in flight (D257, D262).
    pub commit_inflight_nanos: u64,
    /// WAL rollovers that reused the oldest change-feed-retained segment because no free
    /// segment was ready (D310): history cut early rather than a writer waiting. Expected 0.
    pub feed_retained_taken: u64,
}

#[cfg(feature = "__unstable-hooks")]
impl ShardStats {
    pub(crate) fn from_engine(s: pigeonhole_engine::ShardStats) -> Self {
        Self {
            commits: s.commits,
            tablets: s.tablets,
            splits: s.splits,
            merges: s.merges,
            moves: s.moves,
            busy_nanos: s.busy_nanos,
            sync_busy_nanos: s.sync_busy_nanos,
            pool_busy_nanos: s.pool_busy_nanos,
            spin_time_nanos: s.spin_time_nanos,
            commit_inflight_nanos: s.commit_inflight_nanos,
            feed_retained_taken: s.feed_retained_taken,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn histogram(counts: &[(usize, u64)]) -> LatencyHistogram {
        let mut h = LatencyHistogram::default();
        for &(b, n) in counts {
            h.counts[b] = n;
        }
        h
    }

    #[test]
    fn latency_buckets_tile_the_line() {
        assert_eq!(LatencyHistogram::bucket_lower_nanos(0), 0);
        assert_eq!(LatencyHistogram::bucket_upper_nanos(0), Some(2));
        for b in 1..LatencyHistogram::BUCKETS - 1 {
            let upper = LatencyHistogram::bucket_upper_nanos(b).unwrap();
            assert_eq!(
                upper,
                LatencyHistogram::bucket_lower_nanos(b + 1).max(2),
                "bucket {b}"
            );
            assert!(
                upper >= LatencyHistogram::bucket_lower_nanos(b),
                "bucket {b}"
            );
        }
        assert_eq!(
            LatencyHistogram::bucket_upper_nanos(LatencyHistogram::BUCKETS - 1),
            None
        );
    }

    #[test]
    fn quantiles_report_the_upper_bound_of_their_bucket() {
        assert_eq!(LatencyHistogram::default().quantile_upper_nanos(0.5), None);
        // 98 commits in bucket 10 ([32, 48) ns), 2 in bucket 20 ([1024, 1536) ns).
        let h = histogram(&[(10, 98), (20, 2)]);
        assert_eq!(h.total(), 100);
        assert_eq!(h.quantile_upper_nanos(0.5), Some(48));
        assert_eq!(h.quantile_upper_nanos(0.98), Some(48));
        assert_eq!(h.quantile_upper_nanos(0.99), Some(1536));
        assert_eq!(h.quantile_upper_nanos(1.0), Some(1536));
        assert_eq!(h.quantile_upper_nanos(0.0), Some(48));
        assert_eq!(h.quantile_upper_nanos(1.5), None);
        assert_eq!(h.quantile_upper_nanos(f64::NAN), None);
        // The open-ended last bucket reports its lower bound.
        let last = LatencyHistogram::BUCKETS - 1;
        let tail = histogram(&[(last, 1)]);
        assert_eq!(
            tail.quantile_upper_nanos(0.99),
            Some(LatencyHistogram::bucket_lower_nanos(last))
        );
    }

    #[test]
    fn since_subtracts_bucket_by_bucket_and_never_goes_negative() {
        let before = histogram(&[(10, 5), (20, 7)]);
        let after = histogram(&[(10, 8), (20, 3), (30, 1)]);
        let d = after.since(&before);
        assert_eq!(d.counts()[10], 3);
        // A count that fell (a recovery's new engine) counts 0, not a wrap.
        assert_eq!(d.counts()[20], 0);
        assert_eq!(d.counts()[30], 1);
        assert_eq!(d.total(), 4);
    }

    #[test]
    fn every_engine_counter_lands_in_its_named_field() {
        let mut m = pigeonhole_engine::Metrics::default();
        m.commits = [1, 2, 3, 4];
        m.commit_latency_nanos[Durability::Sync as usize] = [10, 20, 30];
        m.commit_latency_buckets[Durability::Buffered as usize].0[7] = 9;
        m.stalls = (5, 6);
        m.memtable_bytes = 41;
        m.memtable_limit = 42;
        m.group_sync_nanos = 43;
        m.room_stalls = (31, 32);
        m.pacing_stalls = (33, 34);
        m.block_cache = (7, 8);
        m.unpin = (9, 10);
        m.file_growths = (11, 12);
        m.file_growths_ahead = (13, 14);
        m.file_punches = (51, 52);
        m.file_punch_bytes = 53;
        m.file_punched_bytes = 54;
        m.file_punch_passes = (55, 56);
        m.shard_idle = (15, 16);
        m.pinned_threads = (3, 17); // (pinned, started)
        m.visibility_waits = (18, 19);
        m.visibility_wakes = (20, 21);
        m.cross_shard.rounds = 22;
        m.cross_shard.refused_room = 23;
        m.cross_shard.refused_pending_overlap = 24;
        let e = EngineMetrics::from_engine(m.clone());
        assert_eq!(e.commits(Durability::None).count, 1);
        assert_eq!(e.commits(Durability::GroupSync).count, 3);
        let buffered = e.commit_latency(Durability::Buffered);
        assert_eq!((buffered.counts()[7], buffered.total()), (9, 9));
        assert_eq!(e.commit_latency(Durability::Sync).total(), 0);
        let sync = e.commits(Durability::Sync);
        assert_eq!(
            (sync.count, sync.p50_nanos, sync.p99_nanos, sync.p999_nanos),
            (4, 10, 20, 30)
        );
        assert_eq!((e.write_stalls, e.write_stall_nanos), (5, 6));
        assert_eq!((e.memtable_bytes, e.memtable_limit_bytes), (41, 42));
        assert_eq!(e.group_sync_nanos, 43);
        assert_eq!((e.room_stalls, e.room_stall_nanos), (31, 32));
        assert_eq!((e.pacing_stalls, e.pacing_stall_nanos), (33, 34));
        assert_eq!((e.block_cache_hits, e.block_cache_misses), (7, 8));
        assert_eq!((e.file_growths, e.file_growth_nanos), (11, 12));
        assert_eq!(
            [
                e.file_punches,
                e.file_punch_nanos,
                e.file_punch_bytes,
                e.file_punched_bytes,
                e.file_punch_passes,
                e.file_punch_refusals
            ],
            [51, 52, 53, 54, 55, 56]
        );
        assert_eq!((e.threads_started, e.threads_pinned), (17, 3));
        assert_eq!(e.cross_shard.rounds, 22);

        // The rest by name (ICR 0087).
        let v = internal(&m, Some(25), None);
        let get = |name: &str| v.iter().find(|(n, _)| *n == name).map(|&(_, x)| x);
        assert_eq!(
            (get("wal_unpin_passes"), get("wal_unpin_flushes")),
            (Some(9), Some(10))
        );
        assert_eq!(
            (get("file_growths_ahead"), get("file_growth_ahead_nanos")),
            (Some(13), Some(14))
        );
        assert_eq!(
            (get("shard_parks"), get("shard_wakes")),
            (Some(15), Some(16))
        );
        assert_eq!(
            (get("visibility_waits"), get("visibility_waiters_ahead")),
            (Some(18), Some(19))
        );
        assert_eq!(
            (get("visibility_wake_passes"), get("visibility_woken")),
            (Some(20), Some(21))
        );
        assert_eq!(get("cross_shard.refused_room"), Some(23));
        assert_eq!(get("cross_shard.refused_pending_overlap"), Some(24));
        assert_eq!(get("io_rings.pooled"), Some(25));
        assert_eq!(get("nowait.hits"), None, "no backend counters were given");
        let mut names: Vec<_> = v.iter().map(|(n, _)| *n).collect();
        names.sort_unstable();
        names.dedup();
        assert_eq!(names.len(), v.len(), "a name appears twice");
    }
}