Cotton code
538 lines · 26.1 KB · RustRaw
//! What a device says of itself with every exchange (phone diagnostics, the//! architect's brief of 12 Oct 2026): its build, its schema, the last answer//! it had from its Mac, what it still has to send, how many databases it//! lists, the problem its open card shows and a copy in progress. The serving//! Mac writes it on the device's row (`cotton_devices.reported_state`), so a//! session reads a phone's state over MCP (`list_devices`) without the owner.//!//! A WHITELIST, cleaned on both sides. Only the fields below are ever kept —//! anything else a body carries is dropped on parse — and every sentence goes//! through [`clean_text`]: a credential, a `Bearer` header and a URL's query//! are cut out before the state is sent and again before it is written. The//! state never needs a value from a secret row or a link that carries one, so//! there is no field one could arrive in.use serde::{Deserialize, Serialize};use serde_json::Value;use std::collections::BTreeMap;use std::sync::LazyLock;/// The key the state rides under in an exchange body, beside `sections` or/// the single section's fields.pub const BODY_KEY: &str = "deviceState";/// The longest sentence kept; a longer one is cut with an ellipsis.const SENTENCE_MAX: usize = 300;/// A stored state older than this is written again even when nothing else/// changed, so `last_exchange_at` says the phone is still talking — and no/// more often, because every write is a synced change every device pulls.pub const RESTATE_AFTER_MS: i64 = 10 * 60 * 1000;/// One local database file, including files whose stamp cannot be read.#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct DatabaseFileState {    pub database_id: String,    pub filename: String,    pub schema_version: Option<u32>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub problem: Option<String>,    /// What the database holds on the device's disk ([`DiskHolding`]).    #[serde(default, skip_serializing_if = "Option::is_none")]    pub disk: Option<DiskHolding>,    /// The copy's own last check of itself ([`FileCheck`]), when it made one.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub check: Option<FileCheck>,    /// The sealed rows this copy holds parked ([`Parked`]): counted, or `"unknown"` while they cannot be counted    /// cheaply; absent only when the copy holds none.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub parked: Option<Parked>,    /// How long each slice of the parks' keys' fill held the copy's writer this launch ([`FillHolds`]); absent when    /// no slice ran.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub park_fill: Option<FillHolds>,    /// EVERY ROW THIS COPY HOLDS PARKED, by its code (PHONE MEASURES, 26 Nov 2026), kinds and counts only: a sealed    /// row's park by its seal code (`seal_key_missing`: no key; `seal_does_not_open`: a former database's key;    /// `waiting_parent`; `fold_refused`), and a change the sync set aside by its direction and code (`pull_author_unknown`,    /// `pull_newer_shape`: a newer schema, `push_bad_column`, …). Counted from the parks' keys, never their contents.    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]    pub parked_by_code: BTreeMap<String, u64>,    /// How the copy's first sync spent its time ([`FirstSyncTimes`]).    #[serde(default, skip_serializing_if = "Option::is_none")]    pub first_sync: Option<FirstSyncTimes>,}/// The holds of the writer by the fill of the parks' keys this launch (FIRST SYNC 9c, the coordinator's review of/// 9b: the aim is under 300 ms a hold, and it counts as measured only on a phone): how many slices, the longest, and/// the 99th of them, in milliseconds.#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct FillHolds {    pub slices: u64,    pub max_ms: u64,    pub p99_ms: u64,}/// WHAT A COPY'S FILE HOLDS, by kind, in bytes (PHONE MEASURES): read page by page (`dbstat`) beside its check of/// itself, in the background while the app is away, once a build and otherwise weekly ([`FileCheck`]).#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct CopySizes {    /// The person's rows: every table that is not the copy's own bookkeeping.    pub rows: u64,    /// The receipts of every write (`_writes`), without its indexes.    pub writes: u64,    /// Every index but a search index's and a park's.    pub indexes: u64,    /// The search indexes (`fts_*` and their tables).    pub search: u64,    /// The parks (`_seal_parked`, `_seal_park_keys`, `_parked`) and their indexes.    pub parked: u64,    /// The rest of the copy's bookkeeping (`_outbox`, `_seal`, …).    pub other: u64,    /// Pages the file holds free.    pub free: u64,    /// How long the measure took.    pub took_ms: u64,}/// HOW A COPY'S FIRST SYNC SPENT ITS TIME (PHONE MEASURES), in ms, from its first page to the pass that left it/// level: waiting on the server for each page (asked to answered, the network in it), opening sealed rows, merging/// them into the copy (making the changes, keeping their seal notes and the fold, a search index's triggers within/// it), and filling the search indexes after. `done_at_ms` once level; the search fill goes on counting after.#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct FirstSyncTimes {    pub started_at_ms: i64,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub done_at_ms: Option<i64>,    pub waiting_ms: u64,    pub opening_ms: u64,    pub merging_ms: u64,    pub indexing_ms: u64,    /// Whether the search fill is whole: `indexing_ms` stops counting then.    #[serde(default)]    pub indexed: bool,    pub pages: u64,    pub rows: u64,}/// A copy's parked sealed rows as it reports them (FIRST SYNC 8, the coordinator's review of FIRST SYNC 7): counted/// by why, or `"unknown"`, a value of its own, while the copy is still filling the parks' keys an older build left/// uncounted (counting them then reads every park whole). Never a zero for parks it holds and has not counted.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(untagged)]pub enum Parked {    /// Counted by why.    Counted(ParkedRows),    /// Not known yet: said as the string `"unknown"`.    Unknown(NotCounted),}/// The one value of [`Parked::Unknown`], said `"unknown"`.#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]pub enum NotCounted {    #[serde(rename = "unknown")]    Unknown,}/// THE SEALED ROWS A COPY HOLDS PARKED, by why (FIRST SYNC 6, the coordinator 26 Nov 2026). `waiting_parent` is no/// error: a row that opened and waits for the row it belongs to (a mail for its conversation), counted apart from/// `refused` (it opened and the copy refused its fold) so it never reads as one.#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct ParkedRows {    /// Waiting for the account's key (`seal_key_missing`).    pub waiting_key: u64,    /// Opened, and waiting for the row they belong to (`waiting_parent`).    pub waiting_parent: u64,    /// Opened, and refused by this copy's fold (`fold_refused`).    pub refused: u64,    /// Sealed with a former database's key, which this device's does not open (`seal_does_not_open`), counted    /// apart from `other` since PHONE MEASURES.    #[serde(default)]    pub former_database: u64,    /// Any other reason (a row that does not open with the key held: `seal_does_not_open`, and the like).    pub other: u64,}/// A COPY'S CHECK OF ITSELF (SCHEMA 155 REVIEW, 26 Nov 2026): `PRAGMA quick_check` over the whole file, on a/// read-only connection in the background, once for each build of the core and otherwise weekly. `verdict` is `ok`/// or SQLite's first words of what is wrong.#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct FileCheck {    /// The core build that checked it.    pub build: String,    /// When, in ms since the epoch.    pub at_ms: i64,    pub verdict: String,    pub took_ms: u64,    /// What the file holds by kind, measured with the check ([`CopySizes`]).    #[serde(default, skip_serializing_if = "Option::is_none")]    pub sizes: Option<CopySizes>,}/// WHAT ONE DATABASE HOLDS ON A DEVICE'S DISK, in bytes, measured by the/// device as it builds its state — so the serving Mac says what a phone is/// holding without guessing (row 8, 22 Oct 2026). The two files are measured/// on disk; the media store and the thumbnail cache are shared by every/// database on the device, so each database's part is what its own media/// ledger (`_media`) records there, and `None` when the ledger could not be/// read.////// Sizes move with every write, so they never make a state worth writing on/// their own ([`ReportedState::worth_writing`]): they ride along with a/// change and with the restate every [`RESTATE_AFTER_MS`].#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct DiskHolding {    /// The replica file itself.    pub replica_bytes: u64,    /// Its write-ahead log, not yet folded back in.    pub wal_bytes: u64,    /// Earlier copies kept beside it: the copy set aside for an update, a    /// download in progress, and a refused copy the person removed.    pub retained_copy_bytes: u64,    /// Originals held in the device's media store.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub media_bytes: Option<u64>,    /// Thumbnails held in the device's thumbnail cache.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub thumbnail_bytes: Option<u64>,}#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]pub struct ReportedState {    /// This Mac checked ownership and refs for every held repository in its    /// local database set. Missing means it has not supplied that evidence.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub repositories: Option<RepositoryReadiness>,    /// The app's build number (`CFBundleVersion`).    #[serde(default, skip_serializing_if = "Option::is_none")]    pub build: Option<String>,    #[serde(default, rename = "bundleId", skip_serializing_if = "Option::is_none")]    pub bundle_id: Option<String>,    #[serde(default, skip_serializing_if = "Vec::is_empty")]    pub databases: Vec<DatabaseFileState>,    /// The commit the app was built from, short.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub sha: Option<String>,    /// The schema this build folds.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub schema: Option<u32>,    /// When the device last heard from its Mac, ISO-8601 UTC.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub last_exchange_at: Option<String>,    /// "ok", "400 schemaVersion must be 132", "holder_asleep", "offline".    #[serde(default, skip_serializing_if = "Option::is_none")]    pub last_answer: Option<String>,    /// Changes not sent yet: the outbox and the writes held for the Mac's    /// time alike.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub unsent: Option<u64>,    /// Of `unsent`, the writes made before the device had the Mac's time this    /// launch, held until an answer gives it.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub held: Option<u64>,    /// UNSENT SEEN (coordinator, 26 Nov 2026): `unsent` counts the things waiting (each record once, as Account says    /// them); this is the raw count of writes beside it (the outbox's ops and the held writes).    #[serde(default, skip_serializing_if = "Option::is_none")]    pub unsent_ops: Option<u64>,    /// The things waiting, by the table they are of (its name here, `cotton_notes`): names and counts only.    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]    pub waiting_by_table: BTreeMap<String, u64>,    /// The writes waiting, by the code of the refusal that holds each (`seal_key_missing`, `version_moved`; `queued`    /// for one never refused, `other` for a refusal with no code): codes and counts only, never a reason.    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]    pub waiting_by_code: BTreeMap<String, u64>,    /// When the oldest write waiting was made, ISO-8601 UTC.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub oldest_waiting_at: Option<String>,    /// When the oldest write held for a `seal_*` refusal (this phone cannot seal it) was made.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub oldest_seal_waiting_at: Option<String>,    /// FIRST SYNC FAST (26 Nov 2026): the pass under way, said every few pages so a slow first sync and a stuck one    /// differ on the device row: of `pass_total` rows it brings, `pass_done` are here, and `parked` rows wait for the    /// key (counts only).    #[serde(default, skip_serializing_if = "Option::is_none")]    pub pass_done: Option<u64>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub pass_total: Option<u64>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub parked: Option<u64>,    /// "5 / 6": the databases the sheet shows / the databases the Mac answered.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub databases_listed: Option<String>,    /// The sentence the open card or the list showed, if any.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub open_problem: Option<String>,    /// A copy in progress: "copying · 400 MB to go".    #[serde(default, skip_serializing_if = "Option::is_none")]    pub copy: Option<String>,    /// How the app ran over the last day, as the phone's own MetricKit    /// payload measured it ([`DeviceUsage`]).    #[serde(default, skip_serializing_if = "Option::is_none")]    pub usage: Option<DeviceUsage>,    /// Comms' Sites pages kept alive (SITES 5): figures only, said by the phone.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub sites: Option<SitesMemory>,    /// Cotton Albums' first look on this phone (LOOK-ONLY, coordinator 27 Nov 2026): counts and timings only.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub albums: Option<AlbumsLook>,}/// HOW ALBUMS' FIRST LOOK IS GOING ON THE OWNER'S PHONE (LOOK-ONLY, coordinator 27 Nov 2026: "Those counts are what I/// need back from his phone"). A simulator cannot say what a real library with Optimise Storage gives, so the phone/// says it here and the device's row carries it. COUNTS AND TIMINGS ONLY: never a file name, a date, a place or a/// face. Said when the pass pauses or ends and every few thousand photos, because each change is a synced write.#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct AlbumsLook {    /// Photos and videos in the library, as the last complete read counted them.    pub photos: u64,    pub videos: u64,    /// Photos looked at (from a full-size picture or a small one).    pub looked: u64,    /// Of `looked`, made from a picture short of 256 px: owed a closer look.    pub small: u64,    /// No picture on the phone at all (only in iCloud): owed a look; this build never fetches one.    pub no_local_picture: u64,    /// Owed a closer look: `small` plus `no_local_picture`.    pub owed: u64,    pub failed: u64,    /// Seconds the pass has run, all runs together; and photos a minute over the last few hundred.    pub seconds: u64,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub per_minute: Option<u64>,    /// Faces found, faces with a vector, person groups shown (5 or more photos).    pub faces: u64,    pub vectors: u64,    pub shown_groups: u64,    /// The most memory Albums held at once (its footprint), in MB, and memory warnings iOS gave it.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub peak_footprint_mb: Option<u64>,    pub warnings: u64,}/// HOW COMMS' LIVE SITE PAGES FARE ON THE PHONE (SITES 4 keeps the 4 rows used last alive; coordinator, 25 Nov 2026:/// "add a counter the owner build logs, so I can read it from his phone"). A simulator cannot say what a page costs/// on a phone, so the phone says it here and the device's row carries it. Every figure moves rarely (counts since/// Comms started, a peak, a low), because each change is a synced write. iOS gives an app no figure for a web/// page's own process, so Comms' own footprint and its headroom stand for the pressure the pages put on it.#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct SitesMemory {    /// Pages alive now, and the most at once since Comms started.    pub alive: u32,    pub most_alive: u32,    /// How many Comms keeps alive at most.    pub limit: u32,    /// Pages Comms let go (past the limit, or on a memory warning) since it started.    pub let_go: u64,    /// Memory warnings iOS gave Comms since it started.    pub warnings: u64,    /// Web processes iOS ended under a page since Comms started (each page reloaded where it was).    pub web_ended: u64,    /// The most memory Comms itself held at once (its footprint), in MB, sampled as pages open and close.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub peak_footprint_mb: Option<u64>,    /// The least memory iOS said Comms could still take before it is ended, in MB.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub least_headroom_mb: Option<u64>,}/// HOW THE APP RAN, MEASURED BY THE PHONE ITSELF (fanperf, owner 15 Oct 2026:/// "the animations must never make the app heavy; prove it, keep it/// proven"). iOS hands the app one MetricKit payload a day; the app says its/// four figures here and the device's row carries them, so a regression shows/// in the owner's own data rather than in a lab. Numbers only — the/// definition's columns say them (`usage_columns`).#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]pub struct DeviceUsage {    /// When the payload's window ended, RFC 3339.    pub until: String,    /// Scroll hitch time over scrolling time, in microseconds per second    /// (MetricKit's `scrollHitchTimeRatio`, ms/s, × 1000).    #[serde(default, skip_serializing_if = "Option::is_none")]    pub hitch_us_per_s: Option<u64>,    /// Hangs over the window (every bucket of the hang-time histogram).    #[serde(default, skip_serializing_if = "Option::is_none")]    pub hangs: Option<u64>,    /// CPU time the app used over the window.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub cpu_ms: Option<u64>,    /// The most memory the app held at once over the window.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub peak_memory_bytes: Option<u64>,}impl DeviceUsage {    /// A window that ended at a readable time, a hitch ratio that is a ratio,    /// and at least one figure.    fn valid(&self) -> bool {        chrono::DateTime::parse_from_rfc3339(&self.until).is_ok()            && self.hitch_us_per_s.is_none_or(|hitch| hitch <= 1_000_000)            && (self.hitch_us_per_s.is_some() || self.hangs.is_some() || self.cpu_ms.is_some()                || self.peak_memory_bytes.is_some())    }}#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct RepositoryReadiness {    pub problems: Vec<RepositoryProblem>,}#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct RepositoryProblem {    pub database: String,    pub repository: String,    pub reason: String,}impl ReportedState {    /// The known fields of whatever arrived, cleaned; `None` when nothing    /// known did. Unknown keys are dropped by construction.    pub fn accept(value: &Value) -> Option<ReportedState> {        let state: ReportedState = serde_json::from_value(value.clone()).ok()?;        let state = state.cleaned();        (state != ReportedState::default()).then_some(state)    }    /// Every sentence through [`clean_text`].    pub fn cleaned(self) -> ReportedState {        let clean = |text: Option<String>| text.map(|text| clean_text(&text)).filter(|text| !text.is_empty());        ReportedState {            repositories: self.repositories.map(|readiness| RepositoryReadiness {                problems: readiness.problems.into_iter().map(|problem| RepositoryProblem {                    database: clean_text(&problem.database),                    repository: clean_text(&problem.repository),                    reason: clean_text(&problem.reason),                }).collect(),            }),            build: clean(self.build),            bundle_id: clean(self.bundle_id),            databases: {                let mut files: Vec<_> = self.databases.into_iter().map(|file| DatabaseFileState {                    database_id: clean_text(&file.database_id),                    filename: clean_text(&file.filename),                    schema_version: file.schema_version,                    problem: clean(file.problem),                    disk: file.disk,                    check: file.check.map(|check| FileCheck { build: clean_text(&check.build), verdict: clean_text(&check.verdict), ..check }),                    parked: file.parked,                    park_fill: file.park_fill,                    parked_by_code: named_counts(file.parked_by_code),                    first_sync: file.first_sync,                }).collect();                files.sort_by(|left, right| left.database_id.cmp(&right.database_id));                files            },            sha: clean(self.sha),            schema: self.schema,            last_exchange_at: clean(self.last_exchange_at),            last_answer: clean(self.last_answer),            unsent: self.unsent,            held: self.held,            unsent_ops: self.unsent_ops,            waiting_by_table: named_counts(self.waiting_by_table),            waiting_by_code: named_counts(self.waiting_by_code),            oldest_waiting_at: clean(self.oldest_waiting_at),            oldest_seal_waiting_at: clean(self.oldest_seal_waiting_at),            pass_done: self.pass_done,            pass_total: self.pass_total,            parked: self.parked,            databases_listed: clean(self.databases_listed),            open_problem: clean(self.open_problem),            copy: clean(self.copy),            usage: self.usage.filter(DeviceUsage::valid),            sites: self.sites,            albums: self.albums,        }    }    /// The state as it is stored and sent.    pub fn to_value(&self) -> Value {        serde_json::to_value(self).unwrap_or(Value::Null)    }    /// Should a Mac holding `stored` write `self`? When anything but the time    /// and the disk sizes changed, or the stored time is [`RESTATE_AFTER_MS`]    /// old. Every write is a synced change every device pulls, and a WAL's    /// size moves with every pass.    pub fn worth_writing(&self, stored: Option<&ReportedState>, now_ms: i64) -> bool {        let Some(stored) = stored else { return true };        let untimed = |state: &ReportedState| ReportedState {            last_exchange_at: None,            databases: state                .databases                .iter()                .map(|file| DatabaseFileState { disk: None, park_fill: None, ..file.clone() })                .collect(),            ..state.clone()        };        if untimed(self) != untimed(stored) {            return true;        }        let at = |state: &ReportedState| {            state.last_exchange_at.as_deref().and_then(|at| chrono::DateTime::parse_from_rfc3339(at).ok()).map(|at| at.timestamp_millis())        };        match (at(self), at(stored)) {            (Some(new), Some(old)) => new > old && now_ms - old >= RESTATE_AFTER_MS,            (new, old) => new != old,        }    }}static BEARER: LazyLock<regex::Regex> =    LazyLock::new(|| regex::Regex::new(r"(?i)\b(bearer)\s+[^\s,;]+").expect("the bearer pattern"));static URL_QUERY: LazyLock<regex::Regex> =    LazyLock::new(|| regex::Regex::new(r"(?i)\b(https?://[^\s?#]+)[?#][^\s]*").expect("the url pattern"));static NAMED: LazyLock<regex::Regex> = LazyLock::new(|| {    regex::Regex::new(r"(?i)\b(token|access_token|key|secret|password|passcode|code|signature|sig)=[^&\s]+")        .expect("the named-value pattern")});/// A sentence with every credential-shaped run cut out: the shared/// [`crate::transforms::redact::redact_secrets`] rules, then a `Bearer` value, a/// URL's query or fragment, and a `token=`/`key=`-style pair — then capped.pub fn clean_text(text: &str) -> String {    let text = redact_line(text);    let text = text.trim();    if text.chars().count() <= SENTENCE_MAX {        return text.to_string();    }    let mut cut: String = text.chars().take(SENTENCE_MAX - 1).collect();    cut.push('…');    cut}/// The same redaction as [`clean_text`] without its length cap: for a line/// that is kept whole, as a phone report keeps its log (`diagnostics.report`).#[must_use]pub fn redact_line(text: &str) -> String {    let text = crate::transforms::redact::redact_secrets(text);    let text = BEARER.replace_all(&text, "$1 ‹redacted›");    let text = URL_QUERY.replace_all(&text, "$1?‹redacted›");    NAMED.replace_all(&text, "$1=‹redacted›").into_owned()}#[cfg(test)]#[path = "reported_state_tests.rs"]mod tests;/// Counts keyed by a name a table or a code can be (lowercase letters, digits, `_`, up to 64), at most/// [`NAMED_COUNTS_KEPT`] of them: whatever else a map holds is no table name or code, and is not sent.fn named_counts(counts: BTreeMap<String, u64>) -> BTreeMap<String, u64> {    counts        .into_iter()        .filter(|(name, _)| !name.is_empty() && name.len() <= 64 && name.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_'))        .take(NAMED_COUNTS_KEPT)        .collect()}/// How many tables or codes a report names at most.pub const NAMED_COUNTS_KEPT: usize = 40;