Skip to main content

agentmux_srv_core/backend/transcript/
withhold.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The values srv holds secret (its instance key, an agent's token, a Vault value it handed to an agent's process) are
5//! never written into an agent's transcript, and never served to a paired device from one: a line that carries one is
6//! stored, and shown to a device, with the value replaced by [`MARK`]. A value is matched as it is and in its ordinary
7//! spellings (base64, URL-encoded, hex, as JSON holds it: `vault::scrub::forms`).
8//!
9//! The values are registered where srv learns them (a token is minted or loaded, the instance key is made, a Vault value
10//! is handed to a process). The registry holds only what can still be used:
11//! - [`register`] keeps a value for the life of the process;
12//! - [`hold`] keeps a value for an owner, until its expiry, until the owner is [`release`]d (its token revoked, its
13//!   container removed, its device unpaired) or until the owner holds another value in its place;
14//! - [`hold_until`] keeps a value that works until a given time, and keeps it until then even when a renewed one
15//!   follows it: the value that was replaced still works, so it stays hidden until it expires;
16//! - [`hold_kept`] keeps a value with no known expiry (a refresh token, an API key) and keeps the values an owner held
17//!   before it, up to [`KEPT_PER_OWNER`], oldest dropped first;
18//! - a batch of registrations ([`register_all`]) costs one rebuild of the matcher, made when a line next needs it.
19//!
20//! The registry is bounded and never fails open. A value up to [`MAX_POOLED_LEN`] goes into the one pattern, and the
21//! registry holds at most [`MAX_TOTAL_BYTES`] of those; a larger value (a certificate bundle, a key file) is held apart
22//! and matched by an exact search, up to [`MAX_VALUE_LEN`] each and [`MAX_LARGE_BYTES`] in all. Within a budget the
23//! oldest values an owner holds make room first; a value that does not fit is refused, counted and logged. A pattern
24//! that cannot be built is replaced by an exact search over the same values, and if even that is over its limit every
25//! line is read as the mark ([`MARK`]) in place of its text. Either state is logged once with the counts and reported
26//! to the hook ([`set_alert`]).
27
28use std::borrow::Cow;
29use std::sync::atomic::{AtomicU64, Ordering};
30use std::sync::{Arc, OnceLock, RwLock};
31
32use regex::{NoExpand, Regex, RegexBuilder};
33
34/// What a withheld value is replaced by.
35pub const MARK: &str = "[withheld]";
36
37/// Shorter values are not registered: matching them would mangle ordinary text.
38pub const MIN_LEN: usize = 8;
39
40/// How many values with no known expiry an owner keeps with [`hold_kept`].
41pub const KEPT_PER_OWNER: usize = 8;
42
43/// How many values an owner holds with [`hold_until`] at once: past it the one that expires first is dropped (the
44/// value just held never is), so what one owner is given cannot crowd out the values of the others.
45pub const UNTIL_PER_OWNER: usize = 16;
46
47/// The longest a value is trusted to keep working (ms from now): an expiry beyond it is not believed, and the value is
48/// held as one with no known expiry ([`hold_kept`]).
49pub const MAX_TRUSTED_LIFE_MS: i64 = 30 * 24 * 60 * 60 * 1000;
50
51/// The longest value the registry takes (bytes): a longer one is refused.
52pub const MAX_VALUE_LEN: usize = 4 * 1024 * 1024;
53
54/// The longest value that goes into the one pattern; a longer one is held apart and matched by an exact search.
55pub const MAX_POOLED_LEN: usize = 32 * 1024;
56
57/// The most the pattern's values hold (bytes of values, not of spellings): past it the oldest values an owner holds
58/// make room.
59pub const MAX_TOTAL_BYTES: usize = 2 * 1024 * 1024;
60
61/// The most the values over [`MAX_POOLED_LEN`] hold in all (bytes). Each is kept in every spelling, about 15 times its
62/// size, so this bounds what the exact search holds.
63pub const MAX_LARGE_BYTES: usize = 4 * 1024 * 1024;
64
65/// The most the values registered while a matcher is out of date hold (bytes, and how many): past it matching is closed
66/// until the next matcher is swapped in.
67const EXTRA_LIMIT: usize = 4 * 1024 * 1024;
68const EXTRA_COUNT: usize = 4096;
69
70/// The size limit of the one-pattern matcher, and of the exact search that replaces it (bytes of spellings).
71const REGEX_LIMIT: usize = 64 << 20;
72const EXACT_LIMIT: usize = 32 << 20;
73
74/// How many values were refused, and how many times the one-pattern matcher could not be built.
75static REFUSED: AtomicU64 = AtomicU64::new(0);
76/// How many values stopped being held to make room for newer ones.
77static EVICTED: AtomicU64 = AtomicU64::new(0);
78static FALLBACKS: AtomicU64 = AtomicU64::new(0);
79
80/// How the registry matches.
81#[derive(Clone)]
82enum Matcher {
83    /// One pattern over every value in every spelling.
84    Pattern(Arc<Regex>),
85    /// The same spellings, longest first, searched one at a time: slower, and with no size limit but [`EXACT_LIMIT`].
86    Exact(Arc<Vec<String>>),
87    /// Neither could be used: every line reads as [`MARK`].
88    Closed,
89}
90
91/// What the registry matches with: the pattern (or its fallbacks) for the pooled values, and the large values apart.
92#[derive(Clone)]
93struct Built {
94    small: Option<Matcher>,
95    /// The spellings of the values over [`MAX_POOLED_LEN`], the same as the pooled values have (`vault::scrub::forms`).
96    large: Arc<Vec<String>>,
97    /// The values registered since this matcher's values were taken, searched exactly until the next matcher is
98    /// swapped in.
99    extra: Arc<Interim>,
100}
101
102/// Values registered since the matcher in use was built. Their spellings are made by the first reader that needs them,
103/// with no lock held, and kept for the readers after it.
104#[derive(Default)]
105struct Interim {
106    values: Vec<Arc<str>>,
107    spelled: OnceLock<Vec<String>>,
108}
109
110impl Interim {
111    fn new(values: Vec<Arc<str>>) -> Self {
112        Self { values, spelled: OnceLock::new() }
113    }
114
115    fn push(&mut self, value: Arc<str>) {
116        self.values.push(value);
117        self.spelled = OnceLock::new();
118    }
119
120    /// Every spelling of every value, longest first.
121    fn spelled(&self) -> &[String] {
122        self.spelled.get_or_init(|| {
123            let mut needles: Vec<String> = self.values.iter().flat_map(|v| crate::backend::vault::scrub::forms(v)).filter(|f| f.len() >= MIN_LEN).collect();
124            needles.sort_by(|a, b| b.len().cmp(&a.len()).then_with(|| a.cmp(b)));
125            needles.dedup();
126            needles
127        })
128    }
129}
130
131/// The state of the registry, for a health read.
132#[derive(Debug, Clone, PartialEq, Eq)]
133pub struct Health {
134    /// `none` (nothing registered), `pattern`, `exact`, `closed`, or `large` (only values over [`MAX_POOLED_LEN`]).
135    pub mode: &'static str,
136    pub values: usize,
137    /// How many of the values are over [`MAX_POOLED_LEN`].
138    pub large: usize,
139    pub bytes: usize,
140    /// Values refused since the process started.
141    pub refused: u64,
142    /// Values that stopped being held, since the process started, to make room for newer ones.
143    pub evicted: u64,
144    /// Times the one-pattern matcher could not be built.
145    pub fallbacks: u64,
146}
147
148struct Entry {
149    /// Who holds the value; `None` for one kept for the life of the process.
150    owner: Option<String>,
151    value: String,
152    /// Unix ms from which the value no longer works and is dropped.
153    expires_at: Option<i64>,
154}
155
156impl Entry {
157    /// Whether this is a value `base` holds with [`hold_until`]: held under `{base}#{its expiry}` and nothing else, so an
158    /// owner whose own name starts with `{base}#` is not mistaken for it.
159    fn is_until_of(&self, base: &str) -> bool {
160        let Some(at) = self.expires_at else { return false };
161        let suffix = self.owner.as_deref().and_then(|o| o.strip_prefix(base)).and_then(|rest| rest.strip_prefix('#'));
162        suffix.is_some_and(|rest| rest.parse::<i64>().ok() == Some(at))
163    }
164}
165
166#[derive(Default)]
167struct Registry {
168    entries: Vec<Entry>,
169    matcher: Option<Built>,
170    /// Told to the alert hook once the lock is released.
171    alerts: Vec<String>,
172    /// The sizes the matcher is built under (`None`: the constants), so a test can force a failure.
173    limits: Option<(usize, usize)>,
174    /// The values changed since `matcher` was built.
175    stale: bool,
176    /// The earliest expiry among the entries.
177    next_expiry: Option<i64>,
178    /// How many times the matcher has been built.
179    rebuilds: usize,
180    /// A matcher is being built, off the lock, from the values as they were when it began.
181    building: bool,
182    /// The values registered since the matcher was last swapped in, in the order they came.
183    extra: Vec<Arc<str>>,
184    /// How many of `extra` the build in progress already covers.
185    extra_covered: usize,
186    /// The bytes of `extra`.
187    extra_bytes: usize,
188    /// More was registered since the matcher was swapped in than `extra` holds ([`EXTRA_LIMIT`]): the matcher in use
189    /// cannot be relied on until a build that began after it is swapped in, and every line reads as [`MARK`] meanwhile.
190    overflow: bool,
191    /// The same, for what was registered before the build in progress began (which that build covers).
192    overflow_pre: bool,
193}
194
195/// What a build needs, taken under the lock so the build itself runs without it.
196struct BuildJob {
197    values: Vec<String>,
198    limits: (usize, usize),
199}
200
201impl BuildJob {
202    fn run(&self) -> Option<Built> {
203        let values: Vec<&str> = self.values.iter().map(String::as_str).collect();
204        build(&values, self.limits.0, self.limits.1)
205    }
206}
207
208impl Registry {
209    fn bytes(&self) -> usize {
210        self.entries.iter().map(|e| e.value.len()).sum()
211    }
212
213    /// Counts a refusal and queues a line for the log and the alert hook: the first, then each power of two.
214    fn refuse(&mut self, why: &str, len: usize) {
215        let n = REFUSED.fetch_add(1, Ordering::Relaxed) + 1;
216        if n.is_power_of_two() {
217            let line = format!("transcript withhold: a value was refused ({why}, {len} bytes); {n} refused since start");
218            tracing::warn!(refused = n, len, why, "{line}");
219            self.alerts.push(line);
220        }
221    }
222
223    /// Counts `n` values that stopped being held to make room, and queues a line for the log and the alert hook when
224    /// the count first reaches or passes a power of two.
225    fn evicted(&mut self, n: u64) {
226        let total = EVICTED.fetch_add(n, Ordering::Relaxed) + n;
227        if (total - n + 1..=total).any(u64::is_power_of_two) {
228            let line = format!("transcript withhold: {n} older value(s) are no longer held to make room; {total} since start");
229            tracing::warn!(evicted = total, "{line}");
230            self.alerts.push(line);
231        }
232    }
233
234    /// Whether a value of `len` bytes can be taken at all.
235    fn takes(&mut self, len: usize) -> bool {
236        if len > MAX_VALUE_LEN {
237            self.refuse("over the longest value", len);
238            return false;
239        }
240        true
241    }
242
243    /// Makes the registry fit its budget after a value was pushed last, and says whether that value is kept. For its
244    /// kind (pooled, or over [`MAX_POOLED_LEN`]) the oldest values an owner holds go first. When what cannot make room
245    /// (the values kept for the process, and the new one) is already over the budget, nothing is evicted: the new
246    /// value is refused and every other value stays.
247    fn fit(&mut self) -> bool {
248        let Some(newest) = self.entries.last() else { return true };
249        let large = newest.value.len() > MAX_POOLED_LEN;
250        let budget = if large { MAX_LARGE_BYTES } else { MAX_TOTAL_BYTES };
251        let same_kind = |e: &Entry| (e.value.len() > MAX_POOLED_LEN) == large;
252        let last = self.entries.len() - 1;
253        let fixed: usize = self.entries.iter().enumerate().filter(|(i, e)| same_kind(e) && (e.owner.is_none() || *i == last)).map(|(_, e)| e.value.len()).sum();
254        if fixed > budget {
255            let len = self.entries.pop().map_or(0, |e| e.value.len());
256            self.refuse("the registry is full", len);
257            return false;
258        }
259        let mut evicted = 0;
260        while self.entries.iter().filter(|e| same_kind(e)).map(|e| e.value.len()).sum::<usize>() > budget {
261            let last = self.entries.len() - 1;
262            if let Some(oldest) = self.entries[..last].iter().position(|e| e.owner.is_some() && same_kind(e)) {
263                self.entries.remove(oldest);
264                evicted += 1;
265            } else {
266                break;
267            }
268        }
269        if evicted > 0 {
270            self.evicted(evicted);
271        }
272        true
273    }
274
275    fn reindex(&mut self) {
276        self.next_expiry = self.entries.iter().filter_map(|e| e.expires_at).min();
277    }
278
279    /// Keeps `value` for the process (`owner` `None`) or for `owner`, in place of what the owner held. A value
280    /// shorter than [`MIN_LEN`] is not kept, so an owner given one holds nothing.
281    fn add(&mut self, owner: Option<&str>, value: &str, expires_at: Option<i64>) {
282        let value = value.trim();
283        let keep = value.len() >= MIN_LEN;
284        if keep && !self.takes(value.len()) {
285            // A refused value changes nothing: what the owner held is still held.
286            return;
287        }
288        let mine = |e: &Entry| e.owner.as_deref() == owner;
289        if let Some(same) = self.entries.iter_mut().find(|e| mine(e) && e.value == value) {
290            if keep && owner.is_none() {
291                return;
292            }
293            if keep && owner.is_some() {
294                // The same value again: the matcher stays, only the expiry can move.
295                same.expires_at = expires_at;
296                self.entries.retain(|e| !(mine(e) && e.value != value));
297                self.reindex();
298                return;
299            }
300        }
301        let was_stale = self.stale;
302        let mut old = Vec::new();
303        if owner.is_some() {
304            let (theirs, rest) = std::mem::take(&mut self.entries).into_iter().partition(|e| mine(e));
305            self.entries = rest;
306            old = theirs;
307            self.stale |= !old.is_empty();
308        }
309        if keep {
310            self.entries.push(Entry { owner: owner.map(str::to_string), value: value.to_string(), expires_at });
311            if self.fit() {
312                self.stale = true;
313                self.note_added(value);
314            } else {
315                // Not kept for lack of room: what the owner held is still held.
316                self.entries.extend(old);
317                self.stale = was_stale;
318            }
319        }
320        self.reindex();
321    }
322
323    /// [`hold_until`] at `now`: a value held with an expiry that is believed is one of at most [`UNTIL_PER_OWNER`] for
324    /// `base`; one with an expiry beyond [`MAX_TRUSTED_LIFE_MS`] is one of those kept with no expiry.
325    fn add_until(&mut self, base: &str, value: &str, expires_at: i64, now: i64) {
326        if expires_at.saturating_sub(now) > MAX_TRUSTED_LIFE_MS {
327            self.add_kept(base, value);
328            return;
329        }
330        let owner = format!("{base}#{expires_at}");
331        self.add(Some(&owner), value, Some(expires_at));
332        let held = |e: &Entry| e.is_until_of(base);
333        let mut dropped = 0u64;
334        while self.entries.iter().filter(|e| held(e)).count() > UNTIL_PER_OWNER {
335            let soonest = self.entries.iter().enumerate().filter(|(_, e)| held(e) && e.owner.as_deref() != Some(owner.as_str())).min_by_key(|(_, e)| e.expires_at);
336            let Some((at, _)) = soonest else { break };
337            self.entries.remove(at);
338            dropped += 1;
339        }
340        if dropped > 0 {
341            self.stale = true;
342            self.reindex();
343            self.evicted(dropped);
344        }
345    }
346
347    /// Keeps `value` for `owner` along with what the owner kept before, up to [`KEPT_PER_OWNER`] (the oldest is dropped).
348    fn add_kept(&mut self, owner: &str, value: &str) {
349        let value = value.trim();
350        let mine = |e: &Entry| e.owner.as_deref() == Some(owner);
351        if value.len() < MIN_LEN || self.entries.iter().any(|e| mine(e) && e.value == value) || !self.takes(value.len()) {
352            return;
353        }
354        self.entries.push(Entry { owner: Some(owner.to_string()), value: value.to_string(), expires_at: None });
355        if !self.fit() {
356            return;
357        }
358        if self.entries.iter().filter(|e| mine(e)).count() > KEPT_PER_OWNER {
359            if let Some(oldest) = self.entries.iter().position(|e| mine(e)) {
360                self.entries.remove(oldest);
361            }
362        }
363        self.stale = true;
364        self.note_added(value);
365        self.reindex();
366    }
367
368    /// Drops what `owner` holds, and what it holds with [`hold_until`].
369    fn release_all(&mut self, owner: &str) {
370        let before = self.entries.len();
371        self.entries.retain(|e| e.owner.as_deref().map_or(true, |o| o != owner) && !e.is_until_of(owner));
372        if self.entries.len() != before {
373            self.stale = true;
374            self.reindex();
375        }
376    }
377
378    /// Drops what every owner whose name starts with `prefix` holds.
379    fn release_prefix(&mut self, prefix: &str) {
380        let before = self.entries.len();
381        self.entries.retain(|e| !e.owner.as_deref().is_some_and(|o| o.starts_with(prefix)));
382        if self.entries.len() != before {
383            self.stale = true;
384            self.reindex();
385        }
386    }
387
388    fn release(&mut self, owner: &str) {
389        let before = self.entries.len();
390        self.entries.retain(|e| e.owner.as_deref() != Some(owner));
391        if self.entries.len() != before {
392            self.stale = true;
393            self.reindex();
394        }
395    }
396
397    /// Drops what has run out by `now`.
398    fn expire(&mut self, now: i64) {
399        if self.next_expiry.is_some_and(|at| at <= now) {
400            self.entries.retain(|e| e.expires_at.map_or(true, |at| at > now));
401            self.stale = true;
402            self.reindex();
403        }
404    }
405
406    /// Whether the matcher is right for `now` as it stands.
407    fn current(&self, now: i64) -> bool {
408        !self.stale && !self.overflow && !self.overflow_pre && self.next_expiry.map_or(true, |at| at > now)
409    }
410
411    /// What a reader uses while a build runs: the matcher in use with the values registered since, or closed when more
412    /// was registered than those can hold, or when there is no matcher in use to add them to.
413    fn interim(&self) -> Option<Built> {
414        if self.overflow || self.overflow_pre || (self.matcher.is_none() && self.building) {
415            return Some(Built { small: Some(Matcher::Closed), large: Arc::default(), extra: Arc::default() });
416        }
417        self.matcher.clone()
418    }
419
420    /// The matcher for the values that have not run out at `now`, built only when they changed, and here and now.
421    fn matcher(&mut self, now: i64) -> Option<Built> {
422        if let Some(job) = self.begin_build(now) {
423            match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| job.run())) {
424                Ok(built) => self.finish_build(built),
425                Err(panic) => {
426                    self.lost_build();
427                    std::panic::resume_unwind(panic);
428                }
429            }
430        }
431        self.matcher.clone()
432    }
433
434    /// A build ended without finishing: one is due again, and what it would have covered is not covered.
435    fn lost_build(&mut self) {
436        self.building = false;
437        self.stale = true;
438        self.overflow |= self.overflow_pre;
439        self.overflow_pre = false;
440    }
441
442    /// Notes that the values changed and a matcher is wanted: the values to build it from, when no build is running.
443    fn begin_build(&mut self, now: i64) -> Option<BuildJob> {
444        self.expire(now);
445        if !self.stale || self.building {
446            return None;
447        }
448        self.stale = false;
449        self.building = true;
450        self.extra_covered = self.extra.len();
451        self.overflow_pre = std::mem::take(&mut self.overflow);
452        let limits = self.limits.unwrap_or((REGEX_LIMIT, EXACT_LIMIT));
453        Some(BuildJob { values: self.entries.iter().map(|e| e.value.clone()).collect(), limits })
454    }
455
456    /// Swaps in a finished matcher. What was registered while it was built stays covered by the exact search, and the
457    /// matcher is built again when a line next needs it.
458    fn finish_build(&mut self, built: Option<Built>) {
459        let was = mode_of(self.matcher.as_ref());
460        self.extra.drain(..self.extra_covered.min(self.extra.len()));
461        self.extra_bytes = self.extra.iter().map(|v| v.len()).sum();
462        self.extra_covered = 0;
463        self.overflow_pre = false;
464        self.matcher = built;
465        self.refresh_extra();
466        let now_mode = mode_of(self.matcher.as_ref());
467        if matches!(now_mode, "exact" | "closed") && now_mode != was {
468            let n = FALLBACKS.load(Ordering::Relaxed);
469            let line = format!(
470                "transcript withhold: matching is degraded to {now_mode} ({} values, {} bytes; {n} builds failed, {} refused since start)",
471                self.entries.len(),
472                self.bytes(),
473                REFUSED.load(Ordering::Relaxed)
474            );
475            tracing::warn!(mode = now_mode, values = self.entries.len(), "{line}");
476            self.alerts.push(line);
477        }
478        self.rebuilds += 1;
479        self.building = false;
480    }
481
482    /// [`finish_build`](Self::finish_build), and what the reader that built the matcher reads with: closed when more was
483    /// registered during the build than the interim values hold.
484    fn finish_and_read(&mut self, built: Option<Built>) -> Option<Built> {
485        self.finish_build(built);
486        self.interim()
487    }
488
489    /// Covers a value just registered in every spelling, in the matcher in use, until the next one is swapped in. With
490    /// no matcher yet, the first read builds one under the lock.
491    fn note_added(&mut self, value: &str) {
492        if self.matcher.is_none() || self.overflow {
493            return;
494        }
495        if self.extra_bytes + value.len() > EXTRA_LIMIT || self.extra.len() >= EXTRA_COUNT {
496            let line = format!("transcript withhold: more was registered than a matcher being rebuilt can cover ({} values, {} bytes); matching is closed until it is swapped in", self.extra.len(), self.extra_bytes);
497            tracing::warn!("{line}");
498            self.alerts.push(line);
499            self.overflow = true;
500            self.extra.clear();
501            self.extra_bytes = 0;
502            self.refresh_extra();
503            return;
504        }
505        let value: Arc<str> = Arc::from(value);
506        self.extra_bytes += value.len();
507        self.extra.push(Arc::clone(&value));
508        if let Some(built) = self.matcher.as_mut() {
509            match Arc::get_mut(&mut built.extra) {
510                Some(interim) => interim.push(value),
511                None => built.extra = Arc::new(Interim::new(self.extra.clone())),
512            }
513        }
514    }
515
516    /// Puts `extra` into the matcher in use. Pointers only: the spellings are made by a reader, off the lock.
517    fn refresh_extra(&mut self) {
518        if self.extra.is_empty() && self.matcher.as_ref().is_some_and(|b| b.small.is_none() && b.large.is_empty()) {
519            self.matcher = None;
520            return;
521        }
522        if self.extra.is_empty() {
523            if let Some(built) = self.matcher.as_mut() {
524                built.extra = Arc::default();
525            }
526            return;
527        }
528        let built = self.matcher.get_or_insert_with(|| Built { small: None, large: Arc::default(), extra: Arc::default() });
529        built.extra = Arc::new(Interim::new(self.extra.clone()));
530    }
531}
532
533fn mode_of(built: Option<&Built>) -> &'static str {
534    match built.map(|b| (&b.small, !b.large.is_empty())) {
535        None => "none",
536        Some((Some(Matcher::Pattern(_)), _)) => "pattern",
537        Some((Some(Matcher::Exact(_)), _)) => "exact",
538        Some((Some(Matcher::Closed), _)) => "closed",
539        Some((None, _)) => "large",
540    }
541}
542
543fn state() -> &'static RwLock<Registry> {
544    static STATE: OnceLock<RwLock<Registry>> = OnceLock::new();
545    STATE.get_or_init(Default::default)
546}
547
548type Alert = Box<dyn Fn(&str) + Send + Sync>;
549
550static ALERT: OnceLock<Alert> = OnceLock::new();
551
552/// Sets what is told when the registry refuses a value or degrades its matching: one line with the counts, never a
553/// value. Called outside the registry's lock, so it may read or write the registry. The first call wins.
554pub fn set_alert(alert: impl Fn(&str) + Send + Sync + 'static) {
555    let _ = ALERT.set(Box::new(alert));
556}
557
558/// Runs `f` on the registry under its write lock, then tells the alert hook what it queued.
559fn with_write<R>(f: impl FnOnce(&mut Registry) -> R) -> R {
560    with_write_in(state(), f)
561}
562
563fn with_write_in<R>(lock: &RwLock<Registry>, f: impl FnOnce(&mut Registry) -> R) -> R {
564    let (result, alerts) = {
565        let mut registry = lock.write().unwrap_or_else(|e| e.into_inner());
566        let result = f(&mut registry);
567        (result, std::mem::take(&mut registry.alerts))
568    };
569    if let Some(alert) = ALERT.get() {
570        alerts.iter().for_each(|line| alert(line));
571    }
572    result
573}
574
575/// The state of the registry now.
576pub fn health() -> Health {
577    let matcher = matcher();
578    let registry = state().read().unwrap_or_else(|e| e.into_inner());
579    Health {
580        mode: mode_of(matcher.as_ref()),
581        values: registry.entries.len(),
582        large: registry.entries.iter().filter(|e| e.value.len() > MAX_POOLED_LEN).count(),
583        bytes: registry.bytes(),
584        refused: REFUSED.load(Ordering::Relaxed),
585        evicted: EVICTED.load(Ordering::Relaxed),
586        fallbacks: FALLBACKS.load(Ordering::Relaxed),
587    }
588}
589
590/// Registers `value` to be withheld from now on, for the life of the process. A value shorter than [`MIN_LEN`] and one
591/// already registered change nothing.
592pub fn register(value: &str) {
593    with_write(|r| r.add(None, value, None));
594}
595
596/// [`register`] for each of `values`, under one lock: the matcher is built once for the lot, when a line next needs it.
597pub fn register_all<'a>(values: impl IntoIterator<Item = &'a str>) {
598    with_write(|registry| {
599        for value in values {
600            registry.add(None, value, None);
601        }
602    });
603}
604
605/// Withholds `value` for `owner`, in place of what the owner held before, until `expires_at` (unix ms; `None` for no
606/// expiry) or until the owner is [`release`]d. Holding the value the owner already holds changes nothing.
607pub fn hold(owner: &str, value: &str, expires_at: Option<i64>) {
608    with_write(|r| r.add(Some(owner), value, expires_at));
609}
610
611/// Withholds `value` for `owner` until `expires_at` (unix ms), when it stops working. A renewed value the owner holds
612/// next with [`hold_until`] does not take its place: the value that was replaced still works until its own expiry,
613/// so it stays withheld until then. Holding the same value and expiry again changes nothing.
614pub fn hold_until(owner: &str, value: &str, expires_at: i64) {
615    let now = agentmux_common::time::now_ms();
616    with_write(|r| r.add_until(owner, value, expires_at, now));
617}
618
619/// Withholds `value` for `owner` with no expiry, until the process ends or the owner is [`release`]d. The values the
620/// owner kept before it stay withheld too, up to [`KEPT_PER_OWNER`]: past that the oldest is dropped. Keeping the same
621/// value again changes nothing.
622pub fn hold_kept(owner: &str, value: &str) {
623    with_write(|r| r.add_kept(owner, value));
624}
625
626/// Stops withholding what `owner` holds: its value no longer works.
627pub fn release(owner: &str) {
628    with_write(|r| r.release(owner));
629}
630
631/// [`release_all`] for every owner whose name starts with `prefix`.
632pub fn release_prefix(prefix: &str) {
633    with_write(|r| r.release_prefix(prefix));
634}
635
636/// [`release`] for what `owner` holds and what it holds with [`hold_until`].
637pub fn release_all(owner: &str) {
638    with_write(|r| r.release_all(owner));
639}
640
641/// What matches `values`. The values up to [`MAX_POOLED_LEN`] go into one matcher for every value in every spelling,
642/// longest first so a spelling that contains another is replaced whole; when one pattern cannot be built under
643/// `regex_limit` the same spellings are searched one at a time, and when they are over `exact_limit` bytes the matcher
644/// is [`Matcher::Closed`]. The larger values are held apart and searched exactly. `None` when nothing is registered.
645fn build(values: &[&str], regex_limit: usize, exact_limit: usize) -> Option<Built> {
646    let (large, pooled): (Vec<&str>, Vec<&str>) = values.iter().partition(|v| v.len() > MAX_POOLED_LEN);
647    let mut large_needles: Vec<String> = large.iter().flat_map(|v| crate::backend::vault::scrub::forms(v)).filter(|f| f.len() >= MIN_LEN).collect();
648    large_needles.sort_by(|a, b| b.len().cmp(&a.len()));
649    large_needles.dedup();
650    let small = build_pooled(&pooled, regex_limit, exact_limit);
651    if small.is_none() && large_needles.is_empty() {
652        return None;
653    }
654    Some(Built { small, large: Arc::new(large_needles), extra: Arc::default() })
655}
656
657fn build_pooled(values: &[&str], regex_limit: usize, exact_limit: usize) -> Option<Matcher> {
658    let mut needles: Vec<String> = Vec::new();
659    for value in values {
660        for form in crate::backend::vault::scrub::forms(value) {
661            if form.len() >= MIN_LEN && !needles.contains(&form) {
662                needles.push(form);
663            }
664        }
665    }
666    if needles.is_empty() {
667        return None;
668    }
669    needles.sort_by(|a, b| b.len().cmp(&a.len()));
670    let pattern = needles.iter().map(|n| regex::escape(n)).collect::<Vec<_>>().join("|");
671    // A limit of 0 means no one-pattern matcher at all.
672    let built = if regex_limit == 0 { Err("no pattern allowed".to_string()) } else { RegexBuilder::new(&pattern).size_limit(regex_limit).build().map_err(|e| e.to_string()) };
673    match built {
674        Ok(matcher) => Some(Matcher::Pattern(Arc::new(matcher))),
675        Err(e) => {
676            FALLBACKS.fetch_add(1, Ordering::Relaxed);
677            tracing::warn!(error = %e, values = values.len(), "transcript withhold: the matcher could not be built as one pattern");
678            let bytes: usize = needles.iter().map(String::len).sum();
679            Some(if bytes > exact_limit { Matcher::Closed } else { Matcher::Exact(Arc::new(needles)) })
680        }
681    }
682}
683
684/// Puts the registry back to wanting a build if the one in progress ends without finishing.
685struct BuildGuard<'a>(&'a RwLock<Registry>, bool);
686
687impl Drop for BuildGuard<'_> {
688    fn drop(&mut self) {
689        if !self.1 {
690            with_write_in(self.0, Registry::lost_build);
691        }
692    }
693}
694
695/// The matcher to read with. When the values changed it is built from a copy of them with no lock held: readers meanwhile
696/// use the matcher they had, plus an exact search for what was registered since, so nothing registered is ever left
697/// out. Only the very first matcher is built under the lock, because until then there is nothing to read with.
698fn matcher() -> Option<Built> {
699    // Tests share the registry and assert that a released value is shown at once, so there a reader waits for the
700    // build in progress; a reader outside tests never does. The server's own tests are tests too, though this crate
701    // is built without `cfg(test)` for them: its `test-support` feature says so.
702    read_from(state(), cfg!(any(test, feature = "test-support")))
703}
704
705/// [`matcher`] on `lock`; with `wait`, a reader that finds a build running waits for it.
706fn read_from(lock: &RwLock<Registry>, wait: bool) -> Option<Built> {
707    let now = agentmux_common::time::now_ms();
708    {
709        let registry = lock.read().unwrap_or_else(|e| e.into_inner());
710        if registry.current(now) {
711            return registry.matcher.clone();
712        }
713    }
714    let job = with_write_in(lock, |r| {
715        if r.matcher.is_none() && !r.building {
716            return Err(r.matcher(now));
717        }
718        Ok(r.begin_build(now))
719    });
720    let job = match job {
721        Err(built) => return built,
722        Ok(Some(job)) => job,
723        Ok(None) if wait => {
724            while lock.read().unwrap_or_else(|e| e.into_inner()).building {
725                std::thread::sleep(std::time::Duration::from_millis(2));
726            }
727            return read_from(lock, true);
728        }
729        Ok(None) => return lock.read().unwrap_or_else(|e| e.into_inner()).interim(),
730    };
731    let mut guard = BuildGuard(lock, false);
732    let built = job.run();
733    let matcher = with_write_in(lock, |r| r.finish_and_read(built));
734    guard.1 = true;
735    matcher
736}
737
738/// Where each needle of `needles` is in `text`.
739fn needle_spans(needles: &[String], text: &str, spans: &mut Vec<(usize, usize)>) {
740    for needle in needles.iter().filter(|n| n.len() <= text.len()) {
741        spans.extend(text.match_indices(needle.as_str()).map(|(at, found)| (at, at + found.len())));
742    }
743}
744
745/// `text` with every value `built` knows replaced by [`MARK`]. Every group (the pooled values, the large ones, the ones
746/// registered since) is matched against the original text, and matches that overlap are one: a value inside another, or
747/// two that overlap, are withheld whole whichever was registered first. Never the text of a line when matching is closed.
748fn replaced<'a>(built: &Built, text: &'a str) -> Cow<'a, str> {
749    let mut spans: Vec<(usize, usize)> = Vec::new();
750    match &built.small {
751        Some(Matcher::Closed) => return Cow::Owned(MARK.to_string()),
752        Some(Matcher::Pattern(regex)) => spans.extend(regex.find_iter(text).map(|m| (m.start(), m.end()))),
753        Some(Matcher::Exact(needles)) => needle_spans(needles, text, &mut spans),
754        None => {}
755    }
756    needle_spans(&built.large, text, &mut spans);
757    needle_spans(built.extra.spelled(), text, &mut spans);
758    if spans.is_empty() {
759        return Cow::Borrowed(text);
760    }
761    spans.sort_unstable();
762    let mut out = String::with_capacity(text.len());
763    let (mut copied, mut start, mut end) = (0, spans[0].0, spans[0].1);
764    for &(from, to) in &spans[1..] {
765        if from < end {
766            end = end.max(to);
767            continue;
768        }
769        out.push_str(&text[copied..start]);
770        out.push_str(MARK);
771        (copied, start, end) = (end, from, to);
772    }
773    out.push_str(&text[copied..start]);
774    out.push_str(MARK);
775    out.push_str(&text[end..]);
776    Cow::Owned(out)
777}
778
779/// `text` with every registered value replaced by [`MARK`]; the text itself when it holds none. Never the text of a
780/// line when matching is closed: then every line is the mark.
781pub fn text(text: &str) -> Cow<'_, str> {
782    match matcher() {
783        Some(built) => replaced(&built, text),
784        None => Cow::Borrowed(text),
785    }
786}
787
788/// Whether `text` holds a registered value, in any of its spellings: the same matcher [`text`] replaces with. Always
789/// true when matching is closed.
790pub fn holds(text: &str) -> bool {
791    let Some(built) = matcher() else { return false };
792    let small = match &built.small {
793        Some(Matcher::Pattern(regex)) => regex.is_match(text),
794        Some(Matcher::Exact(needles)) => needles.iter().any(|n| text.contains(n.as_str())),
795        Some(Matcher::Closed) => true,
796        None => false,
797    };
798    small || built.large.iter().chain(built.extra.spelled()).any(|n| text.contains(n.as_str()))
799}
800
801/// [`text`] over transcript bytes (NDJSON lines); bytes that are not UTF-8 are left as they are, except when matching is
802/// closed: then every line is the mark.
803pub fn lines(data: &[u8]) -> Cow<'_, [u8]> {
804    if matcher().is_some_and(|b| matches!(b.small, Some(Matcher::Closed))) {
805        return Cow::Owned(MARK.as_bytes().to_vec());
806    }
807    let Ok(as_text) = std::str::from_utf8(data) else { return Cow::Borrowed(data) };
808    match text(as_text) {
809        Cow::Borrowed(_) => Cow::Borrowed(data),
810        Cow::Owned(replaced) => Cow::Owned(replaced.into_bytes()),
811    }
812}
813
814/// [`text`] over each line, in place.
815pub fn in_place(lines: &mut [String]) {
816    for line in lines {
817        if let Cow::Owned(replaced) = text(line) {
818            *line = replaced;
819        }
820    }
821}
822
823#[cfg(test)]
824mod tests {
825    use super::*;
826    use base64::Engine as _;
827
828    // The registry is process-wide and tests run in parallel: every test registers values of its own.
829
830    #[test]
831    fn a_registered_value_is_withheld_in_every_ordinary_spelling() {
832        let value = "canary-withhold-0001-aB3dE";
833        register(value);
834        let hex: String = value.bytes().map(|b| format!("{b:02x}")).collect();
835        for shown in [
836            value.to_string(),
837            base64::engine::general_purpose::STANDARD.encode(value),
838            base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(value),
839            hex,
840        ] {
841            let line = format!(r#"{{"type":"user","message":{{"content":[{{"type":"tool_result","content":"env: KEY={shown}"}}]}}}}"#);
842            let out = text(&line);
843            assert!(!out.contains(&shown), "{shown} reached the line: {out}");
844            assert!(out.contains(MARK), "{out}");
845            assert!(serde_json::from_str::<serde_json::Value>(&out).is_ok(), "the line stays JSON: {out}");
846        }
847    }
848
849    #[test]
850    fn a_value_with_json_special_characters_is_withheld_as_json_holds_it() {
851        let value = "canary\"withhold\\0002/ö-xY";
852        register(value);
853        let line = serde_json::json!({ "type": "user", "content": format!("echo {value}") }).to_string();
854        assert!(!line.contains(value), "the stored form is escaped, not the plain value");
855        let out = text(&line);
856        assert!(out.contains(MARK) && !out.contains("withhold"), "{out}");
857        assert!(serde_json::from_str::<serde_json::Value>(&out).is_ok(), "{out}");
858    }
859
860    #[test]
861    fn text_with_no_registered_value_is_returned_as_it_is() {
862        register("canary-withhold-0003-zQ9");
863        assert!(matches!(text("an ordinary line"), Cow::Borrowed(_)));
864        assert!(matches!(lines(b"{\"type\":\"result\"}\n"), Cow::Borrowed(_)));
865        assert!(matches!(lines(&[0xff, 0xfe, 0x00]), Cow::Borrowed(_)), "bytes that are not text are left alone");
866    }
867
868    #[test]
869    fn a_value_too_short_to_match_safely_is_not_registered() {
870        register("shorty");
871        assert_eq!(text("shorty and shorty"), "shorty and shorty");
872    }
873
874    #[test]
875    fn a_value_registered_later_is_withheld_from_then_on() {
876        let before = "canary-withhold-0004-late";
877        assert_eq!(text(&format!("key {before}")), format!("key {before}"));
878        register(before);
879        assert_eq!(text(&format!("key {before}")), format!("key {MARK}"));
880        register(before);
881        assert_eq!(text(&format!("{before}{before}")), format!("{MARK}{MARK}"), "a value registered twice is one value");
882    }
883
884    #[test]
885    fn lines_and_in_place_withhold_what_text_does() {
886        let value = "canary-withhold-0005-lines";
887        register(value);
888        let out = lines(format!("a {value}\nb {value}\n").as_bytes()).into_owned();
889        assert_eq!(String::from_utf8(out).unwrap(), format!("a {MARK}\nb {MARK}\n"));
890        let mut many = vec![format!("x {value}"), "clean".to_string()];
891        in_place(&mut many);
892        assert_eq!(many, vec![format!("x {MARK}"), "clean".to_string()]);
893    }
894
895    // The tests below use a registry of their own and a clock they set, so they say nothing about the process-wide one.
896
897    fn shows(registry: &mut Registry, now: i64, value: &str) -> bool {
898        let line = format!("KEY={value}");
899        registry.matcher(now).map_or(line.clone(), |m| replaced(&m, &line).into_owned()).contains(value)
900    }
901
902    fn big(n: usize) -> String {
903        format!("canary-big-{n:04}-{}", "x".repeat(MAX_VALUE_LEN))
904    }
905
906    #[test]
907    fn a_value_is_dropped_at_its_expiry_and_a_live_one_stays() {
908        let mut registry = Registry::default();
909        registry.add(Some("short"), "canary-expiry-0001-short", Some(1_000));
910        registry.add(Some("long"), "canary-expiry-0002-long", Some(9_000));
911        registry.add(None, "canary-expiry-0003-forever", None);
912        for value in ["canary-expiry-0001-short", "canary-expiry-0002-long", "canary-expiry-0003-forever"] {
913            assert!(!shows(&mut registry, 999, value), "{value} is withheld before any expiry");
914        }
915        assert!(shows(&mut registry, 1_000, "canary-expiry-0001-short"), "an expired value is dropped");
916        assert!(!shows(&mut registry, 1_000, "canary-expiry-0002-long"), "a live one stays");
917        assert!(!shows(&mut registry, 1_000, "canary-expiry-0003-forever"), "one with no expiry stays");
918        assert_eq!(registry.entries.len(), 2, "the expired value is not kept");
919        assert!(shows(&mut registry, 9_000, "canary-expiry-0002-long"));
920        assert!(!shows(&mut registry, 9_000, "canary-expiry-0003-forever"));
921    }
922
923    #[test]
924    fn a_released_owner_is_dropped_and_the_others_stay() {
925        let mut registry = Registry::default();
926        registry.add(Some("container:a"), "canary-release-0001-a", None);
927        registry.add(Some("container:b"), "canary-release-0002-b", None);
928        registry.release("container:a");
929        assert!(shows(&mut registry, 0, "canary-release-0001-a"), "a revoked value is no longer matched");
930        assert!(!shows(&mut registry, 0, "canary-release-0002-b"));
931        registry.release("container:a");
932        registry.release("no-such-owner");
933        assert_eq!(registry.entries.len(), 1, "releasing what is not held changes nothing");
934    }
935
936    #[test]
937    fn an_owner_given_a_new_value_holds_only_that_one() {
938        let mut registry = Registry::default();
939        registry.add(Some("signin:acct:refresh"), "canary-replace-0001-old", None);
940        registry.add(Some("signin:acct:refresh"), "canary-replace-0002-new", None);
941        assert!(shows(&mut registry, 0, "canary-replace-0001-old"), "the value that was replaced is dropped");
942        assert!(!shows(&mut registry, 0, "canary-replace-0002-new"));
943        registry.add(Some("signin:acct:refresh"), "short", None);
944        assert!(registry.entries.is_empty(), "a value too short to match holds nothing, and the old one is gone");
945    }
946
947    #[test]
948    fn a_value_held_again_with_a_later_expiry_is_kept_to_that_expiry() {
949        let mut registry = Registry::default();
950        registry.add(Some("github:a"), "canary-again-0001-token", Some(1_000));
951        registry.add(Some("github:a"), "canary-again-0001-token", Some(5_000));
952        assert_eq!(registry.entries.len(), 1);
953        assert!(!shows(&mut registry, 2_000, "canary-again-0001-token"));
954        assert!(shows(&mut registry, 5_000, "canary-again-0001-token"));
955    }
956
957    #[test]
958    fn a_renewed_value_does_not_end_the_withholding_of_the_one_it_replaced_before_that_one_expires() {
959        let mut registry = Registry::default();
960        // What hold_until does: one owner per expiry.
961        registry.add(Some("github:a#3600"), "canary-renew-0001-first", Some(3_600));
962        registry.add(Some("github:a#7200"), "canary-renew-0002-second", Some(7_200));
963        assert!(!shows(&mut registry, 3_599, "canary-renew-0001-first"), "the replaced one still works");
964        assert!(!shows(&mut registry, 3_599, "canary-renew-0002-second"));
965        assert!(shows(&mut registry, 3_600, "canary-renew-0001-first"), "dropped at its own expiry");
966        assert!(!shows(&mut registry, 3_600, "canary-renew-0002-second"));
967        assert_eq!(registry.entries.len(), 1, "the registry holds only what can still be used");
968        assert!(shows(&mut registry, 7_200, "canary-renew-0002-second"));
969        assert!(registry.entries.is_empty());
970    }
971
972    #[test]
973    fn kept_values_stay_until_the_cap_and_then_the_oldest_goes() {
974        let mut registry = Registry::default();
975        for n in 0..KEPT_PER_OWNER + 2 {
976            registry.add_kept("acct:a", &format!("canary-kept-{n:04}-value"));
977            registry.add_kept("acct:a", &format!("canary-kept-{n:04}-value"));
978        }
979        registry.add_kept("acct:b", "canary-kept-other-value");
980        assert_eq!(registry.entries.iter().filter(|e| e.owner.as_deref() == Some("acct:a")).count(), KEPT_PER_OWNER);
981        assert!(shows(&mut registry, 0, "canary-kept-0000-value"), "the oldest was dropped");
982        assert!(shows(&mut registry, 0, "canary-kept-0001-value"));
983        assert!(!shows(&mut registry, 0, "canary-kept-0002-value"));
984        assert!(!shows(&mut registry, 0, &format!("canary-kept-{:04}-value", KEPT_PER_OWNER + 1)));
985        assert!(!shows(&mut registry, 0, "canary-kept-other-value"), "another owner's values are its own");
986        assert!(!shows(&mut registry, u64::MAX as i64, "canary-kept-0002-value"), "no expiry");
987        registry.release("acct:a");
988        assert!(shows(&mut registry, 0, "canary-kept-0002-value"));
989    }
990
991    #[test]
992    fn release_prefix_drops_every_owner_under_the_prefix_and_no_other() {
993        let mut registry = Registry::default();
994        registry.add(Some("acct:a:access#100"), "canary-prefix-0001-first", Some(100));
995        registry.add_kept("acct:a:refresh", "canary-prefix-0002-second");
996        registry.add(Some("acct:b:refresh"), "canary-prefix-0003-other", None);
997        registry.release_prefix("acct:a:");
998        assert_eq!(registry.entries.len(), 1);
999        assert!(!shows(&mut registry, 0, "canary-prefix-0003-other"));
1000    }
1001
1002    #[test]
1003    fn one_oversized_registration_is_refused_and_leaves_every_other_value_withheld() {
1004        let mut registry = Registry::default();
1005        registry.add(Some("acct:ok"), "canary-oversize-0001-ok", None);
1006        registry.add(Some("acct:evil"), &big(1), None);
1007        registry.add_kept("acct:evil", &big(2));
1008        registry.add(None, &big(3), None);
1009        assert_eq!(registry.entries.len(), 1, "an oversized value is refused, whoever registers it and however");
1010        assert!(!shows(&mut registry, 0, "canary-oversize-0001-ok"));
1011        assert!(REFUSED.load(Ordering::Relaxed) >= 3, "each refusal is counted");
1012    }
1013
1014    #[test]
1015    fn a_value_over_the_pooled_length_is_withheld_by_an_exact_search_and_the_small_values_keep_the_pattern() {
1016        use base64::Engine as _;
1017        let mut registry = Registry::default();
1018        let large = format!("canary-large-0001-{}", "z".repeat(100 * 1024));
1019        registry.add(Some("acct:small"), "canary-large-small-0001", None);
1020        registry.add(Some("acct:large"), &large, None);
1021        let built = registry.matcher(0).unwrap();
1022        assert!(matches!(built.small, Some(Matcher::Pattern(_))), "the small values still go through the pattern");
1023        assert!(built.large.len() >= 2, "the large one is held apart, in its spellings");
1024        assert!(!shows(&mut registry, 0, &large), "a 100 KiB value is withheld");
1025        assert!(!shows(&mut registry, 0, "canary-large-small-0001"));
1026        let spelled = base64::engine::general_purpose::STANDARD.encode(&large);
1027        assert!(!replaced(&built, &format!("out: {spelled}")).contains("canary-large"), "also as base64");
1028        // Every spelling the pooled values have: percent-encoded, hex, URL-safe base64, as JSON holds it.
1029        for form in crate::backend::vault::scrub::forms(&large) {
1030            assert_eq!(replaced(&built, &format!("out: {form}")), "out: [withheld]", "a spelling of the large value shows");
1031        }
1032        assert!(replaced(&built, "an ordinary line").as_ref() == "an ordinary line");
1033    }
1034
1035    /// A matcher in use, the way a reader gets it.
1036    fn in_use(registry: &Registry) -> Built {
1037        registry.matcher.clone().expect("a matcher is in use")
1038    }
1039
1040    #[test]
1041    fn while_a_matcher_is_built_off_the_lock_readers_use_the_one_they_had_and_what_is_registered_is_withheld_at_once() {
1042        let mut registry = Registry::default();
1043        registry.add(Some("acct:old"), "canary-swap-0001-old", None);
1044        registry.matcher(0);
1045        let large = format!("canary-swap-0002-{}", "l".repeat(100 * 1024));
1046        registry.add(Some("acct:large"), &large, None);
1047
1048        // The build begins; the lock is free and a reader gets a matcher that already covers the large value.
1049        let job = registry.begin_build(0).expect("the values changed, so a build is due");
1050        assert!(registry.begin_build(0).is_none(), "one build at a time");
1051        assert!(registry.building);
1052        assert_eq!(replaced(&in_use(&registry), &format!("x {large}")), "x [withheld]");
1053        assert_eq!(replaced(&in_use(&registry), "KEY=canary-swap-0001-old"), "KEY=[withheld]", "the old one still");
1054
1055        // A value registered while it is being built is withheld at once, small or large.
1056        registry.add(Some("acct:during"), "canary-swap-0003-during", None);
1057        let large_during = format!("canary-swap-0004-{}", "m".repeat(50 * 1024));
1058        registry.add(Some("acct:during-large"), &large_during, None);
1059        assert_eq!(replaced(&in_use(&registry), "KEY=canary-swap-0003-during"), "KEY=[withheld]");
1060        assert_eq!(replaced(&in_use(&registry), &format!("x {large_during}")), "x [withheld]");
1061        assert!(holds_in(&in_use(&registry), "canary-swap-0003-during"));
1062
1063        // The matcher is swapped in; what came during the build is still covered, and a build is still due.
1064        let built = job.run();
1065        registry.finish_build(built);
1066        assert!(!registry.building);
1067        assert!(registry.stale, "the values changed during the build, so another is due");
1068        assert_eq!(replaced(&in_use(&registry), "KEY=canary-swap-0003-during"), "KEY=[withheld]");
1069        assert_eq!(replaced(&in_use(&registry), "KEY=canary-swap-0001-old"), "KEY=[withheld]");
1070
1071        let built = registry.matcher(0).unwrap();
1072        assert!(built.extra.values.is_empty(), "the next matcher holds everything");
1073        for line in ["canary-swap-0001-old", "canary-swap-0003-during", large.as_str(), large_during.as_str()] {
1074            assert_eq!(replaced(&built, line), MARK, "{} bytes", line.len());
1075        }
1076    }
1077
1078    #[test]
1079    fn a_reader_that_finds_a_build_running_uses_the_matcher_in_use_with_what_was_registered_since() {
1080        let lock = RwLock::new(Registry::default());
1081        with_write_in(&lock, |r| r.add(Some("acct:a"), "canary-prod-0001-old", None));
1082        assert!(read_from(&lock, false).is_some());
1083        with_write_in(&lock, |r| r.add(Some("acct:b"), "canary-prod-0002-new", None));
1084        let job = with_write_in(&lock, |r| r.begin_build(0)).expect("a build is due");
1085
1086        // The production path: no waiting, the old matcher and the new value.
1087        let read = read_from(&lock, false).expect("a matcher");
1088        assert_eq!(replaced(&read, "a canary-prod-0001-old b canary-prod-0002-new"), "a [withheld] b [withheld]");
1089
1090        with_write_in(&lock, |r| {
1091            let built = job.run();
1092            r.finish_build(built);
1093        });
1094        assert!(!lock.read().unwrap().building);
1095    }
1096
1097    #[test]
1098    fn what_is_registered_while_a_matcher_is_out_of_date_is_bounded_and_past_the_bound_every_line_is_the_mark() {
1099        let lock = RwLock::new(Registry::default());
1100        with_write_in(&lock, |r| r.add(Some("acct:first"), "canary-bound-0001-first", None));
1101        assert!(read_from(&lock, false).is_some());
1102        // Values registered with no reader to rebuild: the interim values stop at the bound.
1103        for n in 0..EXTRA_COUNT + 10 {
1104            with_write_in(&lock, |r| r.add(Some(&format!("acct:{n}")), &format!("canary-bound-{n:05}-v"), None));
1105        }
1106        {
1107            let registry = lock.read().unwrap();
1108            assert!(registry.extra_bytes <= EXTRA_LIMIT && registry.extra.len() <= EXTRA_COUNT);
1109            assert!(registry.overflow, "past the bound the matcher cannot be relied on");
1110        }
1111        let job = with_write_in(&lock, |r| r.begin_build(0)).expect("a build is due");
1112        let read = read_from(&lock, false).expect("a matcher");
1113        assert_eq!(replaced(&read, "an ordinary line"), MARK, "closed while the new matcher is built");
1114        assert!(holds_in(&read, "canary-bound-0001-first"));
1115        with_write_in(&lock, |r| {
1116            let built = job.run();
1117            r.finish_build(built);
1118        });
1119        let read = read_from(&lock, false).expect("a matcher");
1120        assert_eq!(replaced(&read, "an ordinary line"), "an ordinary line", "open again once it is swapped in");
1121        assert_eq!(replaced(&read, "KEY=canary-bound-0001-first"), "KEY=[withheld]");
1122    }
1123
1124    #[test]
1125    fn a_value_registered_since_that_lies_inside_an_older_one_or_around_it_leaves_neither_exposed() {
1126        let mut registry = Registry::default();
1127        let large = format!("canary-span-0002-{}", "k".repeat(40 * 1024));
1128        registry.add(Some("acct:old"), "canary-span-0001-secret-suffix", None);
1129        registry.add(Some("acct:old-large"), &large, None);
1130        registry.matcher(0);
1131        // A shorter value registered during the next build, inside an older one; and a longer one around a large one.
1132        registry.add(Some("acct:inner"), "canary-span-0001", None);
1133        let outer = format!("{large}-and-more-private-text");
1134        registry.add(Some("acct:outer"), &outer, None);
1135        let _job = registry.begin_build(0).unwrap();
1136        let built = registry.interim().unwrap();
1137        assert!(!built.extra.values.is_empty(), "the interim values are what covers them");
1138        assert_eq!(replaced(&built, "a canary-span-0001-secret-suffix b"), "a [withheld] b", "the suffix is not left");
1139        assert_eq!(replaced(&built, &format!("a {outer} b")), "a [withheld] b", "none of the longer value is left");
1140        assert_eq!(replaced(&built, "a canary-span-0001 b"), "a [withheld] b");
1141        assert_eq!(replaced(&built, "an ordinary line"), "an ordinary line");
1142    }
1143
1144    #[test]
1145    fn the_reader_that_built_the_matcher_reads_closed_when_registrations_overflowed_during_the_build() {
1146        let mut registry = Registry::default();
1147        registry.add(Some("acct:a"), "canary-over-0001-value", None);
1148        registry.matcher(0);
1149        registry.add(Some("acct:b"), "canary-over-0002-value", None);
1150        let job = registry.begin_build(0).unwrap();
1151        for n in 0..EXTRA_COUNT + 10 {
1152            registry.add(Some(&format!("acct:n{n}")), &format!("canary-over-{n:05}-v"), None);
1153        }
1154        assert!(registry.overflow);
1155        let read = registry.finish_and_read(job.run()).expect("never nothing");
1156        assert_eq!(replaced(&read, "an ordinary line"), MARK, "closed until a later build covers them");
1157    }
1158
1159    #[test]
1160    fn a_reader_that_finds_a_build_running_and_no_matcher_in_use_gets_the_mark() {
1161        let lock = RwLock::new(Registry::default());
1162        with_write_in(&lock, |r| {
1163            r.add(Some("acct:a"), "canary-none-0001-value", None);
1164            r.matcher = None;
1165            r.stale = true;
1166            r.building = true;
1167        });
1168        let read = read_from(&lock, false).expect("closed, never nothing");
1169        assert_eq!(replaced(&read, "an ordinary line"), MARK);
1170        assert!(holds_in(&read, "canary-none-0001-value"));
1171    }
1172
1173    #[test]
1174    fn a_lost_build_leaves_a_build_due_and_what_it_covered_uncovered() {
1175        let mut registry = Registry::default();
1176        registry.add(Some("acct:a"), "canary-lost-0001-value", None);
1177        registry.matcher(0);
1178        registry.overflow = true;
1179        registry.add(Some("acct:b"), "canary-lost-0002-value", None);
1180        let _lost = registry.begin_build(0).unwrap();
1181        assert!(registry.building && !registry.stale && registry.overflow_pre);
1182        registry.lost_build();
1183        assert!(!registry.building && registry.stale && registry.overflow && !registry.overflow_pre);
1184        let built = registry.matcher(0).unwrap();
1185        assert_eq!(replaced(&built, "canary-lost-0002-value"), MARK);
1186        assert!(!registry.overflow);
1187    }
1188
1189    #[test]
1190    fn a_registry_with_no_matcher_yet_builds_the_first_one_for_the_reader() {
1191        let mut registry = Registry::default();
1192        registry.add(Some("acct:first"), "canary-first-0001-value", None);
1193        assert!(registry.matcher.is_none());
1194        let built = registry.matcher(0).unwrap();
1195        assert_eq!(replaced(&built, "canary-first-0001-value"), MARK);
1196        assert!(!registry.building);
1197    }
1198
1199    #[test]
1200    fn a_reader_that_waits_for_a_build_in_progress_does_not_find_a_released_value_withheld() {
1201        let lock = RwLock::new(Registry::default());
1202        with_write_in(&lock, |r| {
1203            r.add(Some("acct:released"), "canary-wait-0001-released", None);
1204            r.add(Some("acct:kept"), "canary-wait-0002-kept", None);
1205        });
1206        let first = read_from(&lock, true).expect("a matcher");
1207        assert!(holds_in(&first, "canary-wait-0001-released"));
1208
1209        // Another reader's build has begun on the values as they are; then the owner is released.
1210        with_write_in(&lock, |r| r.add(Some("acct:other"), "canary-wait-0003-other", None));
1211        let job = with_write_in(&lock, |r| r.begin_build(0)).expect("a build is due");
1212        with_write_in(&lock, |r| r.release("acct:released"));
1213
1214        // The build is still open here, whatever the scheduler does: nothing finishes it until the worker below runs.
1215        let meanwhile = read_from(&lock, false).expect("a matcher");
1216        assert!(holds_in(&meanwhile, "canary-wait-0001-released"), "a reader that does not wait uses the matcher it had");
1217
1218        let lock = &lock;
1219        std::thread::scope(|s| {
1220            // The pause only makes it likely that the reader below finds the build running; the outcome is the same if
1221            // the build has finished by then.
1222            s.spawn(move || {
1223                std::thread::sleep(std::time::Duration::from_millis(80));
1224                let built = job.run();
1225                with_write_in(lock, |r| r.finish_and_read(built));
1226            });
1227            let waited = read_from(lock, true).expect("a matcher");
1228            assert!(!holds_in(&waited, "canary-wait-0001-released"), "a reader that waits finds it released");
1229            assert!(holds_in(&waited, "canary-wait-0002-kept") && holds_in(&waited, "canary-wait-0003-other"));
1230        });
1231    }
1232
1233    /// Whether `built` finds a value in `text`, as [`holds`] does.
1234    fn holds_in(built: &Built, text: &str) -> bool {
1235        replaced(built, text).as_ref() != text
1236    }
1237
1238    #[test]
1239    fn a_large_value_that_holds_a_pooled_value_is_withheld_whole() {
1240        let mut registry = Registry::default();
1241        let large = format!("canary-contained-0001{}", "p".repeat(40 * 1024));
1242        registry.add(Some("acct:small"), "canary-contained-0001", None);
1243        registry.add(Some("acct:large"), &large, None);
1244        let built = registry.matcher(0).unwrap();
1245        for line in [large.clone(), format!("KEY={large} and canary-contained-0001")] {
1246            let out = replaced(&built, &line);
1247            assert!(!out.contains('p'), "none of the large value is left: {} bytes", out.len());
1248            assert!(!out.contains("canary-contained"));
1249        }
1250        assert!(!shows(&mut registry, 0, &large));
1251    }
1252
1253    #[test]
1254    fn the_large_values_have_a_total_of_their_own_and_the_oldest_owned_make_room() {
1255        let mut registry = Registry::default();
1256        let each = "q".repeat(1024 * 1024);
1257        for n in 0..40 {
1258            registry.add(Some(&format!("acct:{n}")), &format!("canary-lgroom-{n:04}-{each}"), None);
1259        }
1260        let large: usize = registry.entries.iter().filter(|e| e.value.len() > MAX_POOLED_LEN).map(|e| e.value.len()).sum();
1261        assert!(large <= MAX_LARGE_BYTES);
1262        assert!(registry.entries.iter().any(|e| e.value.starts_with("canary-lgroom-0039")), "the newest is held");
1263        assert!(!registry.entries.iter().any(|e| e.value.starts_with("canary-lgroom-0000")), "the oldest made room");
1264    }
1265
1266    #[test]
1267    fn the_registry_holds_a_bounded_total_and_the_oldest_owned_values_make_room() {
1268        let mut registry = Registry::default();
1269        let each = "y".repeat(MAX_POOLED_LEN - 64);
1270        for n in 0..100 {
1271            registry.add(Some(&format!("acct:{n}")), &format!("canary-room-{n:04}-{each}"), None);
1272        }
1273        assert!(registry.bytes() <= MAX_TOTAL_BYTES);
1274        assert!(shows(&mut registry, 0, &format!("canary-room-0000-{each}")), "the oldest made room");
1275        assert!(!shows(&mut registry, 0, &format!("canary-room-0099-{each}")), "the newest is held");
1276
1277        // Values kept for the process cannot make room: the one that does not fit is refused, the others stay.
1278        let mut registry = Registry::default();
1279        for n in 0..100 {
1280            registry.add(None, &format!("canary-forever-{n:04}-{each}"), None);
1281        }
1282        assert!(registry.bytes() <= MAX_TOTAL_BYTES);
1283        assert!(!shows(&mut registry, 0, &format!("canary-forever-0000-{each}")));
1284    }
1285
1286    #[test]
1287    fn values_that_stop_being_held_to_make_room_are_counted() {
1288        let before = EVICTED.load(Ordering::Relaxed);
1289        let mut registry = Registry::default();
1290        let each = "y".repeat(MAX_POOLED_LEN - 64);
1291        for n in 0..100 {
1292            registry.add(Some(&format!("acct:{n}")), &format!("canary-count-{n:04}-{each}"), None);
1293        }
1294        assert!(EVICTED.load(Ordering::Relaxed) - before >= 30, "each value made to make room is counted");
1295        assert!(health().evicted >= 30);
1296    }
1297
1298    #[test]
1299    fn a_replacement_that_is_refused_leaves_what_its_owner_held_and_every_other_value_hidden() {
1300        // Too long to be taken at all.
1301        let mut registry = Registry::default();
1302        registry.add(Some("acct:a"), "canary-keep-0001-first", None);
1303        registry.add(Some("acct:b"), "canary-keep-0002-other", None);
1304        registry.add(Some("acct:a"), &big(1), None);
1305        registry.add(Some("acct:a"), &big(2), Some(1_000));
1306        assert!(!shows(&mut registry, 0, "canary-keep-0001-first"), "the owner's value is still held");
1307        assert!(!shows(&mut registry, 0, "canary-keep-0002-other"));
1308
1309        // No room, because values kept for the process fill the registry: nothing is evicted for a value that
1310        // cannot be kept.
1311        let mut registry = Registry::default();
1312        registry.add(Some("acct:a"), "canary-keep-0003-first", None);
1313        registry.add(Some("acct:b"), "canary-keep-0004-other", None);
1314        let fixed = "z".repeat(MAX_POOLED_LEN);
1315        for n in 0..63 {
1316            registry.add(None, &format!("{n:04}{}", &fixed[4..]), None);
1317        }
1318        registry.add(None, &"w".repeat(20_000), None);
1319        let before = registry.entries.len();
1320        registry.add(Some("acct:a"), &format!("canary-keep-0005-{}", "v".repeat(19_000)), None);
1321        assert_eq!(registry.entries.len(), before, "refused: nothing changed");
1322        assert!(!shows(&mut registry, 0, "canary-keep-0003-first"), "the owner's value is still held");
1323        assert!(!shows(&mut registry, 0, "canary-keep-0004-other"), "another owner's value is still held");
1324    }
1325
1326    #[test]
1327    fn a_matcher_that_cannot_be_built_as_one_pattern_is_replaced_by_an_exact_search() {
1328        let mut registry = Registry::default();
1329        registry.add(Some("acct:a"), "canary-exact-0001-first", None);
1330        registry.add(Some("acct:b"), "canary-exact-0002-second", None);
1331        registry.limits = Some((0, EXACT_LIMIT));
1332        let line = "KEY=canary-exact-0001-first and canary-exact-0002-second";
1333        assert!(matches!(registry.matcher(0).unwrap().small, Some(Matcher::Exact(_))), "the pattern is over its limit");
1334        assert!(!shows(&mut registry, 0, "canary-exact-0001-first") && !shows(&mut registry, 0, "canary-exact-0002-second"));
1335        assert!(registry.alerts.iter().any(|a| a.contains("degraded to exact")), "one signal, with the counts: {:?}", registry.alerts);
1336
1337        // The exact search withholds what the pattern does, in every spelling.
1338        let exact = registry.matcher(0).unwrap();
1339        registry.limits = None;
1340        registry.stale = true;
1341        let pattern = registry.matcher(0).unwrap();
1342        assert!(matches!(pattern.small, Some(Matcher::Pattern(_))));
1343        let spelled = base64::engine::general_purpose::STANDARD.encode("canary-exact-0001-first");
1344        let line = format!("{line} {spelled}");
1345        assert_eq!(replaced(&exact, &line), replaced(&pattern, &line));
1346        assert!(!replaced(&exact, &line).contains("canary-exact"));
1347    }
1348
1349    #[test]
1350    fn when_even_the_exact_search_is_over_its_limit_every_line_reads_as_the_mark() {
1351        let mut registry = Registry::default();
1352        registry.add(Some("acct:a"), "canary-closed-0001-value", None);
1353        registry.limits = Some((0, 1));
1354        assert!(matches!(registry.matcher(0).unwrap().small, Some(Matcher::Closed)));
1355        assert!(registry.alerts.iter().any(|a| a.contains("degraded to closed")), "{:?}", registry.alerts);
1356        let closed = Built { small: Some(Matcher::Closed), large: Arc::new(Vec::new()), extra: Arc::default() };
1357        assert_eq!(replaced(&closed, "an ordinary line"), MARK, "never the text");
1358        assert_eq!(replaced(&closed, "KEY=canary-closed-0001-value"), MARK);
1359    }
1360
1361    #[test]
1362    fn an_expiry_beyond_the_longest_a_value_is_trusted_to_work_holds_it_as_one_with_no_expiry() {
1363        let day = 24 * 60 * 60 * 1000;
1364        let now = 1_800_000_000_000;
1365        let mut registry = Registry::default();
1366        registry.add_until("acct:far", "canary-far-0001-value", now + 365 * day, now);
1367        registry.add_until("acct:far", "canary-far-0002-value", now + 3_600_000, now);
1368        assert!(registry.entries.iter().any(|e| e.expires_at.is_none() && e.owner.as_deref() == Some("acct:far")), "held as kept");
1369        assert!(registry.entries.iter().any(|e| e.expires_at.is_some()), "a believable expiry is kept as one");
1370        assert!(!shows(&mut registry, now + 400 * day, "canary-far-0001-value"), "it never runs out");
1371        assert!(shows(&mut registry, now + 2 * 3_600_000, "canary-far-0002-value"), "the other does, at its own time");
1372    }
1373
1374    #[test]
1375    fn an_owner_holds_at_most_a_set_number_of_values_with_an_expiry_and_the_one_just_held_stays() {
1376        let now = 1_800_000_000_000;
1377        let evicted = EVICTED.load(Ordering::Relaxed);
1378        let mut registry = Registry::default();
1379        for n in 0..40 {
1380            registry.add_until("acct:cap", &format!("canary-cap-{n:04}-value"), now + 3_600_000 + n * 1000, now);
1381        }
1382        let held = registry.entries.iter().filter(|e| e.owner.as_deref().is_some_and(|o| o.starts_with("acct:cap#"))).count();
1383        assert_eq!(held, UNTIL_PER_OWNER);
1384        assert!(!shows(&mut registry, now, "canary-cap-0039-value"), "the latest is held");
1385        assert!(shows(&mut registry, now, "canary-cap-0000-value"), "the one that expires first made room");
1386        assert!(EVICTED.load(Ordering::Relaxed) - evicted >= 24, "the ones dropped are counted");
1387        // A value that expires sooner than all the rest is not the one dropped.
1388        registry.add_until("acct:cap", "canary-cap-0100-value", now + 1_800_000, now);
1389        assert!(!shows(&mut registry, now, "canary-cap-0100-value"));
1390    }
1391
1392    #[test]
1393    fn a_flood_of_values_for_one_owner_leaves_every_other_owners_value_hidden() {
1394        let now = 1_800_000_000_000;
1395        let mut registry = Registry::default();
1396        registry.add(Some("acct:real"), "canary-flood-real-0001-value", None);
1397        registry.add_kept("acct:real-kept", "canary-flood-real-0002-value");
1398        registry.add_until("acct:real-until", "canary-flood-real-0003-value", now + 3_600_000, now);
1399        let filler = "f".repeat(4096);
1400        for n in 0..1000 {
1401            registry.add_until("acct:flood", &format!("canary-flood-{n:05}-{filler}"), now + 3_600_000 + n, now);
1402            registry.add_until("acct:flood-far", &format!("canary-flood-far-{n:05}-{filler}"), now + 400 * 24 * 3_600_000, now);
1403        }
1404        assert!(registry.bytes() <= MAX_TOTAL_BYTES);
1405        for value in ["canary-flood-real-0001-value", "canary-flood-real-0002-value", "canary-flood-real-0003-value"] {
1406            assert!(!shows(&mut registry, now, value), "{value} is still hidden");
1407        }
1408    }
1409
1410    #[test]
1411    fn an_owner_whose_name_starts_with_another_owners_base_is_not_counted_or_released_with_it() {
1412        let now = 1_800_000_000_000;
1413        let mut registry = Registry::default();
1414        registry.add_kept("s:key#extra", "canary-base-0001-kept");
1415        for n in 0..3 {
1416            registry.add_until("s:key#extra", &format!("canary-base-0002-{n}-until"), now + 3_600_000 + n, now);
1417        }
1418        // Another base that is a prefix of that owner's name, given more than the cap.
1419        for n in 0..40 {
1420            registry.add_until("s", &format!("canary-base-0003-{n:02}-until"), now + 3_600_000 + n, now);
1421        }
1422        let of = |registry: &Registry, base: &str| registry.entries.iter().filter(|e| e.is_until_of(base)).count();
1423        assert_eq!(of(&registry, "s"), UNTIL_PER_OWNER, "the cap is on what `s` holds");
1424        assert_eq!(of(&registry, "s:key#extra"), 3, "none of the other owner's values was dropped for it");
1425        assert!(!shows(&mut registry, now, "canary-base-0001-kept"), "its kept value is still hidden");
1426
1427        registry.release_all("s");
1428        assert_eq!(of(&registry, "s"), 0);
1429        assert_eq!(of(&registry, "s:key#extra"), 3, "released with its own owner only");
1430        assert!(!shows(&mut registry, now, "canary-base-0001-kept"));
1431        registry.release_all("s:key#extra");
1432        assert!(registry.entries.is_empty());
1433    }
1434
1435    #[test]
1436    fn release_all_drops_every_value_an_owner_holds_and_no_other_owners() {
1437        let mut registry = Registry::default();
1438        registry.add(Some("acct:a#100"), "canary-all-0001-first", Some(100));
1439        registry.add(Some("acct:a#200"), "canary-all-0002-second", Some(200));
1440        registry.add(Some("acct:a"), "canary-all-0003-plain", None);
1441        registry.add(Some("acct:ab#200"), "canary-all-0004-other", Some(200));
1442        registry.release_all("acct:a");
1443        assert_eq!(registry.entries.len(), 1, "another owner whose name starts the same stays");
1444        assert!(!shows(&mut registry, 0, "canary-all-0004-other"));
1445    }
1446
1447    #[test]
1448    fn a_batch_of_registrations_builds_the_matcher_once() {
1449        let mut registry = Registry::default();
1450        for i in 0..200 {
1451            registry.add(None, &format!("canary-batch-{i:04}-value"), None);
1452            registry.add(Some(&format!("owner-{i}")), &format!("canary-batch-held-{i:04}-value"), Some(100_000));
1453        }
1454        assert_eq!(registry.rebuilds, 0, "nothing is built until a line needs it");
1455        for _ in 0..5 {
1456            assert!(registry.matcher(0).is_some());
1457        }
1458        assert_eq!(registry.rebuilds, 1, "400 registrations and five lines cost one build");
1459        registry.add(None, "canary-batch-late-value", None);
1460        registry.matcher(0);
1461        assert_eq!(registry.rebuilds, 2, "a later change builds again, once");
1462        registry.matcher(0);
1463        assert_eq!(registry.rebuilds, 2, "and a registration that changes nothing builds nothing");
1464        registry.add(None, "canary-batch-late-value", None);
1465        registry.matcher(0);
1466        assert_eq!(registry.rebuilds, 2);
1467    }
1468
1469    #[test]
1470    fn the_process_wide_registry_drops_an_owner_that_is_released() {
1471        let value = "canary-global-release-0001";
1472        hold("withhold-test:global-release", value, None);
1473        assert_eq!(text(&format!("k {value}")), format!("k {MARK}"));
1474        release("withhold-test:global-release");
1475        assert_eq!(text(&format!("k {value}")), format!("k {value}"));
1476    }
1477
1478    #[test]
1479    fn the_process_wide_registry_drops_a_value_after_its_expiry() {
1480        let value = "canary-global-expiry-0001";
1481        let now = agentmux_common::time::now_ms();
1482        hold("withhold-test:global-expiry", value, Some(now + 600_000));
1483        assert_eq!(text(&format!("k {value}")), format!("k {MARK}"));
1484        hold("withhold-test:global-expiry", value, Some(now - 1));
1485        assert_eq!(text(&format!("k {value}")), format!("k {value}"), "a value held to a time already past is not withheld");
1486    }
1487}