allsource-core 0.30.0

High-performance event store core built in Rust
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
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
//! Read cost of `GET /api/v1/events/query`: per-request facts, walks and
//! aggregates. Design sections 6.3 and 10.4.
//!
//! The query handler attaches [`ReadCostFacts`] to its response. [`record`]
//! sits inside [`super::response_limit::bounded`], so it measures a body over
//! the 16 MiB bound before the bound replaces it. Nothing is persisted.

use crate::{
    application::dto::QueryEventsRequest,
    domain::{
        entities::egress::MAX_RESPONSE_BYTES,
        stream_class::{is_class, stream_class_for_tenant},
    },
    infrastructure::{observability::metrics::MetricsRegistry, security::middleware::Admin},
};
use axum::{
    Json,
    body::HttpBody,
    extract::{Extension, Query, Request, State},
    http::{HeaderMap, StatusCode},
    middleware::Next,
    response::{IntoResponse, Response},
};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
use std::{
    collections::{BTreeSet, HashMap, HashSet},
    sync::{
        Arc, LazyLock, Mutex, MutexGuard, PoisonError,
        atomic::{AtomicBool, Ordering},
    },
    time::{Duration, Instant},
};

const CALLER_HEADER: &str = "x-allsource-caller";
const READ_ID_HEADER: &str = "x-allsource-read-id";
const INVALID: &str = "invalid";
const OTHER: &str = "other";

const IN_FLIGHT_CAP: usize = 4_096;
const WALKS_PER_TENANT: usize = 256;
const WALK_IDLE: Duration = Duration::from_secs(30);
const SWEEP_EVERY: Duration = Duration::from_secs(10);
const CLASSES_PER_TENANT: usize = 128;
const CALLERS_PER_TENANT: usize = 256;
const TENANTS: usize = 128;
const LABEL_CAP: usize = 256;
const THRESHOLD_EVERY: Duration = Duration::from_mins(1);
const THRESHOLD_KEYS: usize = 4_096;
const THRESHOLD_PAGES: u64 = 20;
const THRESHOLD_MATCHED: usize = 50_000;

/// Which requests a read is: the shape decides what counts as a whole read.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Shape {
    Whole,
    Latest,
    CountProbe,
    Partial,
}

impl Shape {
    pub fn of(served_limit: usize, descending: bool, since_set: bool, entity_set: bool) -> Self {
        if served_limit == 0 {
            Self::CountProbe
        } else if descending && served_limit == 1 {
            Self::Latest
        } else if since_set || entity_set {
            Self::Partial
        } else {
            Self::Whole
        }
    }
}

/// What one query page answered, as the handler saw it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct QueryCounts {
    pub matched: usize,
    pub returned: usize,
    pub served_limit: usize,
    pub offset: usize,
    pub has_more: bool,
    pub since_set: bool,
    pub entity_set: bool,
    pub shape: Shape,
}

/// The read a page belongs to, before any header is considered.
#[derive(Debug, Clone)]
pub struct ReadFacts {
    pub tenant: String,
    pub stream_class: String,
    pub counts: QueryCounts,
}

/// What a query request asked for, fixed before the store answers.
#[derive(Debug, Clone)]
pub struct ReadScope {
    class: String,
    since_set: bool,
    entity_set: bool,
    served_limit: usize,
    offset: usize,
    descending: bool,
}

impl ReadScope {
    pub fn of(
        req: &QueryEventsRequest,
        tenant: Option<&str>,
        offset: usize,
        descending: bool,
        max_page: usize,
    ) -> Self {
        Self {
            class: stream_class_for_tenant(
                tenant,
                req.entity_id.as_deref(),
                req.event_type_prefix.as_deref(),
                req.event_type.as_deref(),
            ),
            since_set: req.since.is_some(),
            entity_set: req.entity_id.is_some(),
            served_limit: req.limit.unwrap_or(max_page).min(max_page),
            offset,
            descending,
        }
    }

    /// Facts for a page that matched `matched` events and returned `returned`.
    pub fn facts(
        self,
        tenant: String,
        matched: usize,
        returned: usize,
        has_more: bool,
    ) -> ReadFacts {
        let shape = Shape::of(
            self.served_limit,
            self.descending,
            self.since_set,
            self.entity_set,
        );
        ReadFacts {
            tenant,
            stream_class: self.class,
            counts: QueryCounts {
                matched,
                returned,
                served_limit: self.served_limit,
                offset: self.offset,
                has_more,
                since_set: self.since_set,
                entity_set: self.entity_set,
                shape,
            },
        }
    }
}

/// A header that failed its pattern, kept by name and length only.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RejectedHeader {
    pub name: &'static str,
    pub length: usize,
}

/// Attached to a query response as an extension. Removed by [`record`].
#[derive(Debug, Clone)]
pub struct ReadCostFacts {
    pub read: ReadFacts,
    /// `Some("invalid")` when the header is present and fails its pattern.
    pub caller: Option<String>,
    /// `None` when absent or invalid: an invalid read id counts as absent.
    pub read_id: Option<String>,
    pub rejected: Vec<RejectedHeader>,
}

impl ReadCostFacts {
    pub fn from_headers(read: ReadFacts, headers: &HeaderMap) -> Self {
        let mut rejected = Vec::new();
        let caller = headers.get(CALLER_HEADER).map(|value| {
            let text = value.to_str().unwrap_or_default();
            if is_class(text) {
                text.to_owned()
            } else {
                rejected.push(RejectedHeader {
                    name: "caller",
                    length: value.as_bytes().len(),
                });
                INVALID.to_owned()
            }
        });
        // The gateway forwards a rejected value as `invalid` and has already
        // logged and counted it.
        let read_id = headers.get(READ_ID_HEADER).and_then(|value| {
            if value.as_bytes() == INVALID.as_bytes() {
                return None;
            }
            let text = value.to_str().ok().filter(|text| is_read_id(text));
            if text.is_none() {
                rejected.push(RejectedHeader {
                    name: "read_id",
                    length: value.as_bytes().len(),
                });
            }
            text.map(str::to_owned)
        });
        Self {
            read,
            caller,
            read_id,
            rejected,
        }
    }
}

fn is_read_id(text: &str) -> bool {
    text.len() == 16 && text.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
}

/// How a page ended, from its status and final body length.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Outcome {
    Complete,
    HasMore,
    NotModified,
    TooLarge,
}

impl Outcome {
    pub fn of(status: StatusCode, body_bytes: u64, has_more: bool) -> Self {
        if body_bytes > MAX_RESPONSE_BYTES {
            Self::TooLarge
        } else if status == StatusCode::NOT_MODIFIED {
            Self::NotModified
        } else if has_more {
            Self::HasMore
        } else {
            Self::Complete
        }
    }

    fn as_str(self) -> &'static str {
        match self {
            Self::Complete => "complete",
            Self::HasMore => "has_more",
            Self::NotModified => "not_modified",
            Self::TooLarge => "too_large",
        }
    }
}

/// Exact counts for one stream class within one tenant.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize)]
pub struct ClassRow {
    pub logical_reads: u64,
    pub pages: u64,
    pub whole_reads: u64,
    pub single_truncated: u64,
    pub walk_abandoned: u64,
    pub walk_evicted: u64,
    pub matched_sum: u64,
    pub matched_max: u64,
    pub max_pages_per_walk: u64,
}

/// Counts for one caller and stream class within one tenant. A row created by
/// replacing another inherits that row's counts and is `approximate`; so is a
/// row that counted a body whose length was not known exactly.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize)]
pub struct CallerRow {
    pub logical_reads: u64,
    pub pages: u64,
    pub whole_reads: u64,
    pub body_bytes: u64,
    pub single_truncated: u64,
    pub walk_abandoned: u64,
    pub approximate: bool,
    pub first_seen: Option<DateTime<Utc>>,
    pub last_seen: Option<DateTime<Utc>>,
}

#[derive(Debug)]
struct Walk {
    class: String,
    caller: Option<String>,
    pages: u64,
    last_seen: Instant,
}

#[derive(Debug, Default)]
struct Tenant {
    last_active: u64,
    /// Rows cover only pages since then: `Tables::since` while no tenant has
    /// been evicted, since a tenant first seen then had no earlier pages;
    /// otherwise the time it entered, as it may have been evicted before.
    tracked_since: Option<DateTime<Utc>>,
    classes: HashMap<String, ClassRow>,
    callers: HashMap<(Option<String>, String), CallerRow>,
}

#[derive(Debug, Default)]
struct Tables {
    /// When recording last started: the process start, or the switch turning
    /// recording back on, which clears every table.
    since: DateTime<Utc>,
    tick: u64,
    /// A tenant has been pushed out of `tenants` since `since`.
    tenant_evicted: bool,
    tenants: HashMap<String, Tenant>,
    walks: HashMap<(String, String), Walk>,
    /// Every walk in `walks` by last seen, so the oldest is found without a scan.
    walks_by_age: BTreeSet<(Instant, String, String)>,
    /// Each tenant's walks by last seen, keyed by read id.
    walks_per_tenant: HashMap<String, BTreeSet<(Instant, String)>>,
    labels: HashSet<String>,
    label_overflow_logged: bool,
    last_sweep: Option<Instant>,
    threshold_logged: HashMap<(String, String, String), Instant>,
    header_logged: HashMap<&'static str, Instant>,
    /// Series bumps and log lines queued under the lock and emitted by
    /// [`ReadCost::unlock`] after it is released. Empty whenever unlocked.
    effects: Vec<Effect>,
}

#[derive(Debug)]
enum Effect {
    Page {
        label: String,
        outcome: &'static str,
    },
    Matched {
        label: String,
        matched: u64,
    },
    Whole {
        label: String,
    },
    Truncated {
        label: String,
        kind: &'static str,
    },
    LabelOverflow {
        log: bool,
    },
    HeaderInvalid {
        header: &'static str,
        length: usize,
        log: bool,
    },
    Threshold {
        fingerprint: String,
        caller: String,
        class: String,
        reason: &'static str,
        pages: u64,
        matched: usize,
    },
}

impl Tables {
    fn insert_walk(&mut self, key: (String, String), walk: Walk) {
        self.remove_walk(&key);
        let last_seen = walk.last_seen;
        self.walks_by_age
            .insert((last_seen, key.0.clone(), key.1.clone()));
        self.walks_per_tenant
            .entry(key.0.clone())
            .or_default()
            .insert((last_seen, key.1.clone()));
        self.walks.insert(key, walk);
    }

    fn remove_walk(&mut self, key: &(String, String)) -> Option<Walk> {
        let walk = self.walks.remove(key)?;
        self.walks_by_age
            .remove(&(walk.last_seen, key.0.clone(), key.1.clone()));
        if let Some(own) = self.walks_per_tenant.get_mut(&key.0) {
            own.remove(&(walk.last_seen, key.1.clone()));
            if own.is_empty() {
                self.walks_per_tenant.remove(&key.0);
            }
        }
        Some(walk)
    }

    fn clear_walks(&mut self) {
        self.walks.clear();
        self.walks_by_age.clear();
        self.walks_per_tenant.clear();
    }
}

/// Process-wide read-cost state, shared by the query handler's layer and the
/// admin switch.
pub struct ReadCost {
    enabled: AtomicBool,
    metrics: Arc<MetricsRegistry>,
    tables: Mutex<Tables>,
}

impl ReadCost {
    pub fn new(metrics: Arc<MetricsRegistry>, enabled: bool) -> Arc<Self> {
        Arc::new(Self {
            enabled: AtomicBool::new(enabled),
            metrics,
            tables: Mutex::new(Tables {
                since: Utc::now(),
                ..Tables::default()
            }),
        })
    }

    /// Enabled unless `ALLSOURCE_READ_COST=off` at boot.
    pub fn from_env(metrics: Arc<MetricsRegistry>) -> Arc<Self> {
        let disabled = std::env::var("ALLSOURCE_READ_COST")
            .is_ok_and(|value| value.eq_ignore_ascii_case("off"));
        Self::new(metrics, !disabled)
    }

    pub fn enabled(&self) -> bool {
        self.enabled.load(Ordering::Relaxed)
    }

    /// Turning recording off drops every live walk, since pages it skips can
    /// neither continue nor abandon one. Turning it back on clears every table
    /// and restarts `since`, so no row spans the gap.
    pub fn set_enabled(&self, enabled: bool) {
        let mut tables = self.lock();
        let was = self.enabled.swap(enabled, Ordering::Relaxed);
        if !enabled {
            tables.clear_walks();
        } else if !was {
            *tables = Tables {
                since: Utc::now(),
                // Prometheus series outlive the tables, and the label cap counts them.
                labels: std::mem::take(&mut tables.labels),
                label_overflow_logged: tables.label_overflow_logged,
                ..Tables::default()
            };
        }
    }

    /// Caller and class rows for one tenant, ordered by `order` and cut to
    /// `limit`, with whether recording is on and the tenant is in the table.
    pub fn read_costs(&self, tenant: &str, order: RowOrder, limit: usize) -> ReadCostsResponse {
        let tables = self.lock();
        let enabled = self.enabled();
        let since = tables.since;
        let Some(state) = tables.tenants.get(tenant) else {
            return ReadCostsResponse {
                callers: Vec::new(),
                classes: Vec::new(),
                enabled,
                since,
                instance_id: instance_id(),
                tenant_tracked: false,
                tenant_since: None,
            };
        };
        let tenant_since = state.tracked_since;
        let mut callers: Vec<CallerCost> = state
            .callers
            .iter()
            .map(|((caller, class), counts)| CallerCost {
                caller: caller.clone().unwrap_or_else(|| UNATTRIBUTED.to_owned()),
                stream_class: class.clone(),
                counts: *counts,
            })
            .collect();
        let mut classes: Vec<ClassCost> = state
            .classes
            .iter()
            .map(|(class, counts)| ClassCost {
                stream_class: class.clone(),
                counts: *counts,
            })
            .collect();
        drop(tables);
        callers.sort_by(|a, b| {
            caller_key(order, &b.counts)
                .cmp(&caller_key(order, &a.counts))
                .then_with(|| (&a.caller, &a.stream_class).cmp(&(&b.caller, &b.stream_class)))
        });
        callers.truncate(limit);
        classes.sort_by(|a, b| {
            class_key(order, &b.counts)
                .cmp(&class_key(order, &a.counts))
                .then_with(|| a.stream_class.cmp(&b.stream_class))
        });
        classes.truncate(limit);
        ReadCostsResponse {
            callers,
            classes,
            enabled,
            since,
            instance_id: instance_id(),
            tenant_tracked: true,
            tenant_since,
        }
    }

    fn lock(&self) -> MutexGuard<'_, Tables> {
        self.tables.lock().unwrap_or_else(PoisonError::into_inner)
    }

    /// Releases the lock, then emits what the update queued.
    fn unlock(&self, mut tables: MutexGuard<'_, Tables>) {
        let effects = std::mem::take(&mut tables.effects);
        drop(tables);
        let metrics = self.metrics.read_cost();
        for effect in effects {
            match effect {
                Effect::Page { label, outcome } => metrics
                    .read_pages_total
                    .with_label_values(&[label.as_str(), outcome])
                    .inc(),
                Effect::Matched { label, matched } => metrics
                    .read_events_matched_total
                    .with_label_values(&[label.as_str()])
                    .inc_by(matched),
                Effect::Whole { label } => metrics
                    .read_whole_reads_total
                    .with_label_values(&[label.as_str()])
                    .inc(),
                Effect::Truncated { label, kind } => metrics
                    .read_truncated_total
                    .with_label_values(&[label.as_str(), kind])
                    .inc(),
                Effect::LabelOverflow { log } => {
                    metrics
                        .read_label_overflow_total
                        .with_label_values(&["stream_class"])
                        .inc();
                    if log {
                        tracing::warn!(event = "read_label_overflow", label = "stream_class");
                    }
                }
                Effect::HeaderInvalid {
                    header,
                    length,
                    log,
                } => {
                    metrics
                        .read_header_invalid_total
                        .with_label_values(&[header])
                        .inc();
                    if log {
                        tracing::warn!(event = "read_header_invalid", header, length);
                    }
                }
                Effect::Threshold {
                    fingerprint,
                    caller,
                    class,
                    reason,
                    pages,
                    matched,
                } => tracing::warn!(
                    event = "read_cost_threshold",
                    tenant_fingerprint = %fingerprint,
                    caller = %caller,
                    stream_class = %class,
                    reason,
                    pages,
                    matched,
                ),
            }
        }
    }

    /// Folds one page into the walks, aggregates, series and logs.
    pub fn observe(&self, now: Instant, facts: &ReadCostFacts, outcome: Outcome, body_bytes: u64) {
        self.observe_sized(now, facts, outcome, body_bytes, true);
    }

    /// [`Self::observe`] for a body whose length may be only a lower bound.
    fn observe_sized(
        &self,
        now: Instant,
        facts: &ReadCostFacts,
        outcome: Outcome,
        body_bytes: u64,
        bytes_exact: bool,
    ) {
        let wall = Utc::now();
        let mut tables = self.lock();
        if !self.enabled() {
            return;
        }
        self.sweep_if_due(&mut tables, now);
        log_rejected(&mut tables, now, &facts.rejected);

        let read = &facts.read;
        let counts = read.counts;
        let tenant = read.tenant.as_str();
        let class = read.stream_class.as_str();
        let caller = facts.caller.as_deref();
        let who = Who {
            tenant,
            caller,
            class,
        };
        let whole = counts.shape == Shape::Whole;
        let single = is_single_truncated(facts);

        let mut logical = true;
        let mut pages = 1;
        if let Some(read_id) = facts.read_id.as_deref() {
            let key = (tenant.to_owned(), read_id.to_owned());
            let idle = tables
                .walks
                .get(&key)
                .is_some_and(|walk| now.saturating_duration_since(walk.last_seen) > WALK_IDLE);
            if idle && let Some(walk) = tables.remove_walk(&key) {
                self.abandon(&mut tables, now, tenant, &walk);
            }
            if let Some(mut walk) = tables.remove_walk(&key) {
                logical = false;
                pages = walk.pages + 1;
                if counts.has_more {
                    walk.pages = pages;
                    walk.last_seen = now;
                    tables.insert_walk(key, walk);
                }
            } else if counts.has_more {
                self.make_room(&mut tables, tenant);
                tables.insert_walk(
                    key,
                    Walk {
                        class: class.to_owned(),
                        caller: caller.map(str::to_owned),
                        pages: 1,
                        last_seen: now,
                    },
                );
            }
        }

        let whole = whole && logical;
        let label = self.admit_label(&mut tables, class);
        let state = tenant_mut(&mut tables, tenant);
        let row = class_row(state, class);
        row.pages += 1;
        row.logical_reads += u64::from(logical);
        row.whole_reads += u64::from(whole);
        row.single_truncated += u64::from(single);
        row.matched_sum += wide(counts.matched);
        row.matched_max = row.matched_max.max(wide(counts.matched));
        row.max_pages_per_walk = row.max_pages_per_walk.max(pages);
        let row = caller_row(state, caller.map(str::to_owned), class);
        row.pages += 1;
        row.logical_reads += u64::from(logical);
        row.whole_reads += u64::from(whole);
        row.single_truncated += u64::from(single);
        row.body_bytes += body_bytes;
        row.approximate |= !bytes_exact;
        row.first_seen.get_or_insert(wall);
        row.last_seen = Some(wall);

        if whole {
            tables.effects.push(Effect::Whole {
                label: label.clone(),
            });
        }
        if single {
            truncated(&mut tables, &label, "single");
        }
        tables.effects.push(Effect::Matched {
            label: label.clone(),
            matched: wide(counts.matched),
        });
        tables.effects.push(Effect::Page {
            label,
            outcome: outcome.as_str(),
        });

        if pages > THRESHOLD_PAGES {
            threshold(&mut tables, now, who, "walk_pages", pages, counts.matched);
        }
        if counts.matched > THRESHOLD_MATCHED {
            threshold(
                &mut tables,
                now,
                who,
                "matched_pages",
                pages,
                counts.matched,
            );
        }
        if single && caller.is_some() {
            threshold(
                &mut tables,
                now,
                who,
                "single_truncated",
                pages,
                counts.matched,
            );
        }
        self.unlock(tables);
    }

    /// Ends every walk idle for more than `WALK_IDLE` as abandoned. Does
    /// nothing while recording is off.
    pub fn sweep(&self, now: Instant) {
        let mut tables = self.lock();
        if !self.enabled() {
            return;
        }
        self.sweep_locked(&mut tables, now);
        self.unlock(tables);
    }

    fn sweep_if_due(&self, tables: &mut Tables, now: Instant) {
        if tables
            .last_sweep
            .is_some_and(|last| now.saturating_duration_since(last) < SWEEP_EVERY)
        {
            return;
        }
        self.sweep_locked(tables, now);
    }

    fn sweep_locked(&self, tables: &mut Tables, now: Instant) {
        tables.last_sweep = Some(now);
        let idle: Vec<(String, String)> = tables
            .walks_by_age
            .iter()
            .take_while(|(last_seen, _, _)| now.saturating_duration_since(*last_seen) > WALK_IDLE)
            .map(|(_, tenant, read_id)| (tenant.clone(), read_id.clone()))
            .collect();
        for key in idle {
            if let Some(walk) = tables.remove_walk(&key) {
                self.abandon(tables, now, &key.0, &walk);
            }
        }
    }

    fn abandon(&self, tables: &mut Tables, now: Instant, tenant: &str, walk: &Walk) {
        let label = self.admit_label(tables, &walk.class);
        if let Some(state) = tables.tenants.get_mut(tenant) {
            class_row(state, &walk.class).walk_abandoned += 1;
            caller_row(state, walk.caller.clone(), &walk.class).walk_abandoned += 1;
        }
        truncated(tables, &label, "walk_abandoned");
        let who = Who {
            tenant,
            caller: walk.caller.as_deref(),
            class: &walk.class,
        };
        threshold(tables, now, who, "walk_abandoned", walk.pages, 0);
    }

    /// Evicts `tenant`'s least recently seen walk when it holds
    /// [`WALKS_PER_TENANT`], else the table's least recently seen walk when
    /// the table is full, so one tenant cannot push out another's walks. An
    /// evicted walk is `walk_evicted`, never `walk_abandoned`. Neither an
    /// eviction nor an abandon marks a tenant active.
    fn make_room(&self, tables: &mut Tables, tenant: &str) {
        let own = tables.walks_per_tenant.get(tenant);
        let oldest = if let Some(own) = own.filter(|own| own.len() >= WALKS_PER_TENANT) {
            own.first()
                .map(|(_, read_id)| (tenant.to_owned(), read_id.clone()))
        } else if tables.walks.len() >= IN_FLIGHT_CAP {
            tables
                .walks_by_age
                .first()
                .map(|(_, t, read_id)| (t.clone(), read_id.clone()))
        } else {
            None
        };
        let Some(key) = oldest else { return };
        if let Some(walk) = tables.remove_walk(&key) {
            let label = self.admit_label(tables, &walk.class);
            if let Some(state) = tables.tenants.get_mut(&key.0) {
                class_row(state, &walk.class).walk_evicted += 1;
            }
            truncated(tables, &label, "walk_evicted");
        }
    }

    /// The Prometheus label for `class`: the class itself while the process
    /// has room for it, else `other`.
    fn admit_label(&self, tables: &mut Tables, class: &str) -> String {
        if tables.labels.contains(class) {
            return class.to_owned();
        }
        if tables.labels.len() < LABEL_CAP {
            tables.labels.insert(class.to_owned());
            return class.to_owned();
        }
        let log = !tables.label_overflow_logged;
        tables.label_overflow_logged = true;
        tables.effects.push(Effect::LabelOverflow { log });
        OTHER.to_owned()
    }
}

fn truncated(tables: &mut Tables, label: &str, kind: &'static str) {
    tables.effects.push(Effect::Truncated {
        label: label.to_owned(),
        kind,
    });
}

/// A walk page's tenant, caller and stream class, for log keys.
#[derive(Clone, Copy)]
struct Who<'a> {
    tenant: &'a str,
    caller: Option<&'a str>,
    class: &'a str,
}

/// Single truncated per design 4: no read id, no since, no entity, offset 0,
/// a served limit of two or more, and a full page with more behind it.
fn is_single_truncated(facts: &ReadCostFacts) -> bool {
    let counts = facts.read.counts;
    facts.read_id.is_none()
        && !counts.since_set
        && !counts.entity_set
        && counts.offset == 0
        && counts.served_limit >= 2
        && counts.returned == counts.served_limit
        && counts.has_more
}

fn tenant_mut<'a>(tables: &'a mut Tables, tenant: &str) -> &'a mut Tenant {
    tables.tick += 1;
    let tick = tables.tick;
    if !tables.tenants.contains_key(tenant)
        && tables.tenants.len() >= TENANTS
        && let Some(coldest) = tables
            .tenants
            .iter()
            .min_by_key(|(_, state)| state.last_active)
            .map(|(name, _)| name.clone())
    {
        tables.tenants.remove(&coldest);
        tables.tenant_evicted = true;
    }
    let first_seen = if tables.tenant_evicted {
        Utc::now()
    } else {
        tables.since
    };
    let state = tables.tenants.entry(tenant.to_owned()).or_default();
    state.last_active = tick;
    state.tracked_since.get_or_insert(first_seen);
    state
}

fn class_row<'a>(state: &'a mut Tenant, class: &str) -> &'a mut ClassRow {
    let key = if state.classes.contains_key(class) || state.classes.len() < CLASSES_PER_TENANT {
        class
    } else {
        OTHER
    };
    state.classes.entry(key.to_owned()).or_default()
}

fn caller_row<'a>(state: &'a mut Tenant, caller: Option<String>, class: &str) -> &'a mut CallerRow {
    let key = (caller, class.to_owned());
    if !state.callers.contains_key(&key) && state.callers.len() >= CALLERS_PER_TENANT {
        let coldest = state
            .callers
            .iter()
            .min_by_key(|(_, row)| row.body_bytes)
            .map(|(k, row)| (k.clone(), *row));
        if let Some((victim, row)) = coldest {
            state.callers.remove(&victim);
            state.callers.insert(
                key.clone(),
                CallerRow {
                    approximate: true,
                    ..row
                },
            );
        }
    }
    state.callers.entry(key).or_default()
}

fn threshold(
    tables: &mut Tables,
    now: Instant,
    who: Who<'_>,
    reason: &'static str,
    pages: u64,
    matched: usize,
) {
    let key = (
        fingerprint(who.tenant),
        who.caller.unwrap_or("none").to_owned(),
        who.class.to_owned(),
    );
    if tables
        .threshold_logged
        .get(&key)
        .is_some_and(|last| now.saturating_duration_since(*last) < THRESHOLD_EVERY)
    {
        return;
    }
    if !tables.threshold_logged.contains_key(&key)
        && tables.threshold_logged.len() >= THRESHOLD_KEYS
    {
        tables
            .threshold_logged
            .retain(|_, last| now.saturating_duration_since(*last) < THRESHOLD_EVERY);
        if tables.threshold_logged.len() >= THRESHOLD_KEYS {
            return;
        }
    }
    tables.threshold_logged.insert(key.clone(), now);
    let (fingerprint, caller, class) = key;
    tables.effects.push(Effect::Threshold {
        fingerprint,
        caller,
        class,
        reason,
        pages,
        matched,
    });
}

fn log_rejected(tables: &mut Tables, now: Instant, rejected: &[RejectedHeader]) {
    for header in rejected {
        let log = tables
            .header_logged
            .get(header.name)
            .is_none_or(|last| now.saturating_duration_since(*last) >= THRESHOLD_EVERY);
        if log {
            tables.header_logged.insert(header.name, now);
        }
        tables.effects.push(Effect::HeaderInvalid {
            header: header.name,
            length: header.length,
            log,
        });
    }
}

/// Six bytes of SHA-256 over the tenant: the only form a log line carries.
fn fingerprint(tenant: &str) -> String {
    hex::encode(&Sha256::digest(tenant.as_bytes())[..6])
}

fn wide(value: usize) -> u64 {
    u64::try_from(value).unwrap_or(u64::MAX)
}

/// Pages and the sweeper both read the tokio clock, so a paused test clock
/// drives both.
fn clock() -> Instant {
    tokio::time::Instant::now().into_std()
}

/// Sweeps every `SWEEP_EVERY` until the last `Arc<ReadCost>` drops.
pub fn spawn_sweeper(read_cost: &Arc<ReadCost>) -> tokio::task::JoinHandle<()> {
    let read_cost = Arc::downgrade(read_cost);
    tokio::spawn(async move {
        let mut ticks = tokio::time::interval(SWEEP_EVERY);
        ticks.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
        loop {
            ticks.tick().await;
            let Some(read_cost) = read_cost.upgrade() else {
                return;
            };
            read_cost.sweep(clock());
        }
    })
}

/// Layer inside [`super::response_limit::bounded`]: reads the facts a query
/// handler attached and records them. Responses without facts pass untouched.
pub async fn record(
    State(read_cost): State<Arc<ReadCost>>,
    request: Request,
    next: Next,
) -> Response {
    let mut response = next.run(request).await;
    let Some(facts) = response.extensions_mut().remove::<ReadCostFacts>() else {
        return response;
    };
    if read_cost.enabled() {
        let hint = response.body().size_hint();
        let body_bytes = hint.exact().unwrap_or_else(|| hint.lower());
        let outcome = Outcome::of(response.status(), body_bytes, facts.read.counts.has_more);
        read_cost.observe_sized(clock(), &facts, outcome, body_bytes, hint.exact().is_some());
    }
    response
}

#[derive(Debug, Deserialize)]
pub struct ReadCostSwitch {
    pub enabled: bool,
}

/// Sort order for `GET /api/v1/read-costs`.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum RowOrder {
    #[default]
    Bytes,
    Pages,
    Matched,
    Whole,
    Truncated,
}

#[derive(Debug, Deserialize)]
pub struct ReadCostsParams {
    pub tenant_id: Option<String>,
    pub limit: Option<usize>,
    pub order: Option<RowOrder>,
}

#[derive(Debug, Serialize)]
pub struct CallerCost {
    pub caller: String,
    pub stream_class: String,
    #[serde(flatten)]
    pub counts: CallerRow,
}

#[derive(Debug, Serialize)]
pub struct ClassCost {
    pub stream_class: String,
    #[serde(flatten)]
    pub counts: ClassRow,
}

/// Rows plus what they cover: empty rows mean "no reads" only when recording
/// is on and the tenant is tracked.
#[derive(Debug, Serialize)]
pub struct ReadCostsResponse {
    pub callers: Vec<CallerCost>,
    pub classes: Vec<ClassCost>,
    /// Recording is on now.
    pub enabled: bool,
    /// When the tables last started empty: process start or recording
    /// switched back on.
    pub since: DateTime<Utc>,
    /// Random per Core process. Rows cover only the pages this process
    /// served, so two machines, or one restarted, answer with different ids.
    pub instance_id: &'static str,
    /// The tenant has rows. `false` for a tenant with no reads since `since`
    /// and for one pushed out of the 128-tenant table; the two look alike.
    pub tenant_tracked: bool,
    /// When the tenant's rows started: `since`, unless a tenant had been
    /// pushed out of the table when this one entered, in which case this one
    /// may have been pushed out too and its rows start when it came back.
    pub tenant_since: Option<DateTime<Utc>>,
}

static INSTANCE_ID: LazyLock<String> = LazyLock::new(|| uuid::Uuid::new_v4().simple().to_string());

fn instance_id() -> &'static str {
    INSTANCE_ID.as_str()
}

const UNATTRIBUTED: &str = "unattributed";
const READ_COSTS_DEFAULT_LIMIT: usize = 50;
const READ_COSTS_MAX_LIMIT: usize = 256;

/// Caller rows carry no matched count, so `matched` orders them by pages.
fn caller_key(order: RowOrder, counts: &CallerRow) -> u64 {
    match order {
        RowOrder::Bytes => counts.body_bytes,
        RowOrder::Pages | RowOrder::Matched => counts.pages,
        RowOrder::Whole => counts.whole_reads,
        RowOrder::Truncated => counts.single_truncated,
    }
}

/// Class rows carry no byte count, so `bytes` orders them by pages.
fn class_key(order: RowOrder, counts: &ClassRow) -> u64 {
    match order {
        RowOrder::Bytes | RowOrder::Pages => counts.pages,
        RowOrder::Matched => counts.matched_sum,
        RowOrder::Whole => counts.whole_reads,
        RowOrder::Truncated => counts.single_truncated,
    }
}

/// `GET /api/v1/read-costs`: the tenant named by the gateway, never another.
pub async fn serve_read_costs(
    Extension(read_cost): Extension<Arc<ReadCost>>,
    Query(params): Query<ReadCostsParams>,
) -> Response {
    let Some(tenant) = params.tenant_id.filter(|tenant| !tenant.is_empty()) else {
        return (
            StatusCode::BAD_REQUEST,
            Json(json!({ "error": "tenant_id is required" })),
        )
            .into_response();
    };
    let limit = params
        .limit
        .unwrap_or(READ_COSTS_DEFAULT_LIMIT)
        .min(READ_COSTS_MAX_LIMIT);
    let rows = read_cost.read_costs(&tenant, params.order.unwrap_or_default(), limit);
    Json(rows).into_response()
}

/// `PUT /api/v1/admin/read-cost {"enabled": bool}`. Admin only.
pub async fn set_read_cost(
    _admin: Admin,
    Extension(read_cost): Extension<Arc<ReadCost>>,
    Json(switch): Json<ReadCostSwitch>,
) -> Json<Value> {
    read_cost.set_enabled(switch.enabled);
    Json(json!({ "enabled": switch.enabled }))
}

#[cfg(test)]
#[path = "read_cost_tests.rs"]
mod read_cost_tests;