lean-ctx-cloud 3.12.8

The LeanCTX Cloud connector: enrollment, bus, knowledge sync, tasks and policy on top of LeanCTX | OSS.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
// SPDX-License-Identifier: Apache-2.0
//! Task reads shared by every process of this Instance (owner 09.11.: Cloud
//! takes large request volumes and does not block at the first limit).
//!
//! Cloud counts task reads per Instance (600 per 15 min). Thirteen Queens,
//! their workers, the relay catch-up and the sync each used to ask on their
//! own, every one a new process, so one busy hour used the budget up and
//! every caller got 429. Now:
//!
//! - A list or task younger than [`READ_TTL`] is answered from
//!   `<data>/cloud/task-reads.json` (0600) without a request.
//! - One fetch per list or task at a time (single flight): callers that
//!   arrive while it runs wait for it under a file lock and take its answer.
//! - A 429 holds every task read of this Instance until its `Retry-After`
//!   (or [`DEFAULT_HOLD`]); meanwhile, and when Cloud is not reachable, the
//!   last good answer is served marked [`Stale`] with its age. Without one
//!   the caller gets [`CloudError::RateLimited`] with the seconds left, never
//!   "not found".
//! - A change of this machine (claim, update, verify, propose…) or a task
//!   event from Cloud outdates the vault's entries (`outdate`).

use std::collections::BTreeMap;
use std::path::Path;
use std::time::Duration;

use lean_ctx_time::UtcDateTime;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};

use crate::CloudError;
use crate::state::{load_or_quarantine, lock_state, lock_state_within, write_private};

const READS_FILE: &str = "task-reads.json";
/// An answer younger than this is served without a request.
pub const READ_TTL: Duration = Duration::from_secs(15);
/// How long a 429 without `Retry-After` holds task reads.
pub const DEFAULT_HOLD: Duration = Duration::from_secs(60);
/// The longest hold one 429 sets (a wrong header never parks reads longer).
const MAX_HOLD: Duration = Duration::from_mins(15);
/// How long a caller waits for a fetch of the same entry already running.
const FLIGHT_WAIT: Duration = Duration::from_secs(7);
/// Entries older than this are dropped when the file is written.
const KEEP: Duration = Duration::from_hours(24);

/// Flight locks are spread over this many files (`task-fetch-<n>.lock`),
/// so they do not grow with every list query and task number read.
const FLIGHT_SLOTS: u64 = 64;

#[derive(Debug, Clone, Serialize, Deserialize)]
struct Stamped {
    /// When the fetch that brought the answer started: Cloud may have built
    /// it from any state since then.
    at: UtcDateTime,
    /// A change after `at` (this machine's write, a task event).
    #[serde(default)]
    outdated: bool,
    value: serde_json::Value,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
struct Reads {
    /// Cloud URL → until when it refuses task reads of this Instance (429).
    #[serde(default)]
    holds: BTreeMap<String, UtcDateTime>,
    /// Vault id → when a change last outdated its answers: an answer whose
    /// fetch started before that is not current, also one stored after the
    /// change by a fetch that was already running.
    #[serde(default)]
    outdated_at: BTreeMap<String, UtcDateTime>,
    /// Vault id → entry key (`list?state=open`, `task#376`) → answer.
    #[serde(default)]
    vaults: BTreeMap<String, BTreeMap<String, Stamped>>,
}

/// Why an answer is not current.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Stale {
    /// Seconds since Cloud sent it.
    pub age_s: u64,
    /// `rate_limited` (Cloud holds task reads) or `unavailable` (not reachable).
    pub reason: &'static str,
    /// Seconds until Cloud takes task reads again (`rate_limited`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub retry_after_s: Option<u64>,
}

/// An answer and, when it is not current, why.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Read<T> {
    pub value: T,
    pub stale: Option<Stale>,
}

impl<T> Read<T> {
    pub fn map<U>(self, f: impl FnOnce(T) -> U) -> Read<U> {
        Read {
            value: f(self.value),
            stale: self.stale,
        }
    }
}

/// The value of a current answer; a stale one is the error it stands in
/// for (rate limited with the seconds left, or Cloud not reachable), for
/// callers that must not act on old task state.
pub fn current<T>(read: Read<T>) -> Result<T, CloudError> {
    match read.stale {
        None => Ok(read.value),
        Some(Stale {
            reason: "rate_limited",
            retry_after_s,
            ..
        }) => Err(CloudError::RateLimited {
            retry_after: retry_after_s,
        }),
        Some(stale) => Err(CloudError::Offline(format!(
            "LeanCTX Cloud not reachable; the last task answer is {}s old",
            stale.age_s
        ))),
    }
}

impl Stale {
    /// One line for people: `stale: Cloud's answer from 40s ago (rate
    /// limited, reads again in 320s)`.
    #[must_use]
    pub fn note(&self) -> String {
        let why = match (self.reason, self.retry_after_s) {
            ("rate_limited", Some(s)) => format!("rate limited, reads again in {s}s"),
            ("rate_limited", None) => "rate limited".to_string(),
            _ => "LeanCTX Cloud not reachable".to_string(),
        };
        format!(
            "stale: LeanCTX Cloud's answer from {}s ago ({why})",
            self.age_s
        )
    }
}

fn load(data_dir: &Path) -> Reads {
    load_or_quarantine(&data_dir.join(READS_FILE), |_: &Reads| true)
        .unwrap_or_else(|error| {
            tracing::warn!("cloud task reads: {error}");
            None
        })
        .unwrap_or_default()
}

/// Change the file under its lock; never around a request.
fn mutate(data_dir: &Path, change: impl FnOnce(&mut Reads)) {
    let saved = lock_state(data_dir, READS_FILE).and_then(|_lock| {
        let mut reads = load(data_dir);
        change(&mut reads);
        let keep = lean_ctx_time::Duration::from_std(KEEP)
            .unwrap_or_else(|_| lean_ctx_time::Duration::days(1));
        let oldest = UtcDateTime::now() - keep;
        for entries in reads.vaults.values_mut() {
            entries.retain(|_, e| e.at > oldest);
        }
        reads.vaults.retain(|_, entries| !entries.is_empty());
        let now = UtcDateTime::now();
        reads.outdated_at.retain(|_, at| *at > oldest);
        reads.holds.retain(|_, until| *until > now);
        let bytes = serde_json::to_vec(&reads).map_err(|e| CloudError::Local(e.to_string()))?;
        write_private(data_dir, READS_FILE, &bytes)
    });
    if let Err(error) = saved {
        tracing::debug!("cloud task reads not saved: {error}");
    }
}

/// Outdate every answer kept for `vault_id`, and every answer a fetch
/// running now stores later: the next read asks Cloud. Written even when
/// nothing is kept yet, since a first fetch may be running.
pub(crate) fn outdate(data_dir: &Path, vault_id: &str) {
    mutate(data_dir, |reads| {
        reads
            .outdated_at
            .insert(vault_id.to_string(), UtcDateTime::now());
        if let Some(entries) = reads.vaults.get_mut(vault_id) {
            for e in entries.values_mut() {
                e.outdated = true;
            }
        }
    });
}

/// Seconds until Cloud at `cloud` takes task reads again, `None` when it does.
fn held(reads: &Reads, cloud: &str, now: UtcDateTime) -> Option<u64> {
    let until = *reads.holds.get(cloud)?;
    (until > now).then(|| {
        u64::try_from((until - now).num_seconds())
            .unwrap_or(0)
            .max(1)
    })
}

fn age_s(entry: &Stamped, now: UtcDateTime) -> u64 {
    u64::try_from((now - entry.at).num_seconds()).unwrap_or(0)
}

/// Current: not outdated, its fetch started after the vault's last change
/// (`outdated_at`) and less than [`READ_TTL`] ago.
fn fresh(entry: &Stamped, outdated_at: Option<UtcDateTime>, now: UtcDateTime) -> bool {
    !entry.outdated
        && outdated_at.is_none_or(|changed| entry.at > changed)
        && lean_ctx_time::Duration::from_std(READ_TTL).is_ok_and(|ttl| entry.at + ttl > now)
        && entry.at <= now + lean_ctx_time::Duration::seconds(5)
}

fn decode<T: DeserializeOwned>(entry: &Stamped) -> Option<T> {
    serde_json::from_value(entry.value.clone()).ok()
}

/// The kept answer for `key`, served stale for `reason`.
fn stale<T: DeserializeOwned>(
    entry: Option<&Stamped>,
    now: UtcDateTime,
    reason: &'static str,
    retry_after_s: Option<u64>,
) -> Option<Read<T>> {
    let entry = entry?;
    Some(Read {
        value: decode(entry)?,
        stale: Some(Stale {
            age_s: age_s(entry, now),
            reason,
            retry_after_s,
        }),
    })
}

/// The flight lock's name for one entry: one of [`FLIGHT_SLOTS`] fixed
/// names (`task-fetch-<n>`), so the lock files stay bounded. Two entries
/// that share a slot only take turns; each still checks its own answer.
fn flight(vault_id: &str, key: &str) -> String {
    let digest = blake3::hash(format!("{vault_id}\n{key}").as_bytes());
    let mut first = [0u8; 8];
    first.copy_from_slice(&digest.as_bytes()[..8]);
    format!("task-fetch-{}", u64::from_le_bytes(first) % FLIGHT_SLOTS)
}

/// The answer for `key` of `vault_id`: kept and fresh, else fetched once
/// for every caller of this Instance, else (429, Cloud not reachable) the
/// last good one marked stale. `cloud` (the Cloud URL) scopes a 429 hold to
/// the Cloud that sent it.
pub(crate) fn read_through<T: Serialize + DeserializeOwned>(
    data_dir: &Path,
    cloud: &str,
    vault_id: &str,
    key: &str,
    fetch: impl FnOnce() -> Result<T, CloudError>,
) -> Result<Read<T>, CloudError> {
    let lookup = |reads: &Reads| {
        reads
            .vaults
            .get(vault_id)
            .and_then(|entries| entries.get(key))
            .cloned()
    };
    let current = |reads: &Reads, now| -> Option<Read<T>> {
        let entry = lookup(reads)?;
        fresh(&entry, reads.outdated_at.get(vault_id).copied(), now)
            .then(|| decode(&entry))
            .flatten()
            .map(|value| Read { value, stale: None })
    };
    let held_answer = |reads: &Reads, now, left: u64| -> Result<Read<T>, CloudError> {
        stale(lookup(reads).as_ref(), now, "rate_limited", Some(left)).ok_or(
            CloudError::RateLimited {
                retry_after: Some(left),
            },
        )
    };

    let reads = load(data_dir);
    let now = UtcDateTime::now();
    if let Some(answer) = current(&reads, now) {
        return Ok(answer);
    }
    if let Some(left) = held(&reads, cloud, now) {
        return held_answer(&reads, now, left);
    }
    // One fetch per entry: a caller arriving while it runs waits for it
    // and takes its answer. A fetch that outlives the wait is not waited
    // for longer: the caller serves the kept answer or asks itself.
    let _flight = lock_state_within(data_dir, &flight(vault_id, key), FLIGHT_WAIT);
    let reads = load(data_dir);
    let now = UtcDateTime::now();
    if let Some(answer) = current(&reads, now) {
        return Ok(answer);
    }
    if let Some(left) = held(&reads, cloud, now) {
        return held_answer(&reads, now, left);
    }
    // Stamped with the start: a change while the request runs (another
    // process claims, `outdate`) leaves the stored answer not current.
    let started = UtcDateTime::now();
    match fetch() {
        Ok(value) => {
            if let Ok(json) = serde_json::to_value(&value) {
                mutate(data_dir, |reads| {
                    reads
                        .vaults
                        .entry(vault_id.to_string())
                        .or_default()
                        .insert(
                            key.to_string(),
                            Stamped {
                                at: started,
                                outdated: false,
                                value: json,
                            },
                        );
                });
            }
            Ok(Read { value, stale: None })
        }
        Err(CloudError::RateLimited { retry_after }) => {
            let hold = retry_after
                .map(Duration::from_secs)
                .unwrap_or(DEFAULT_HOLD)
                .clamp(Duration::from_secs(1), MAX_HOLD);
            let until = UtcDateTime::now()
                + lean_ctx_time::Duration::from_std(hold)
                    .unwrap_or_else(|_| lean_ctx_time::Duration::seconds(60));
            mutate(data_dir, |reads| {
                let hold = reads.holds.entry(cloud.to_string()).or_insert(until);
                *hold = (*hold).max(until);
            });
            let left = hold.as_secs().max(1);
            held_answer(&reads, UtcDateTime::now(), left)
        }
        Err(error) if error.is_transient() => stale(
            lookup(&reads).as_ref(),
            UtcDateTime::now(),
            "unavailable",
            None,
        )
        .ok_or(error),
        Err(error) => Err(error),
    }
}

/// Seconds until Cloud at `cloud` takes this Instance's task reads again
/// (`None`: now).
pub fn hold_left(data_dir: &Path, cloud: &str) -> Option<u64> {
    held(&load(data_dir), cloud, UtcDateTime::now())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::{Arc, Barrier};

    const CLOUD: &str = "https://cloud.example";

    fn age(dir: &Path, vault: &str, key: &str, secs: i64) {
        mutate(dir, |reads| {
            let e = reads.vaults.get_mut(vault).unwrap().get_mut(key).unwrap();
            e.at -= lean_ctx_time::Duration::seconds(secs);
        });
    }

    #[test]
    fn a_fresh_answer_is_served_without_a_request() {
        let dir = tempfile::tempdir().unwrap();
        let asked = AtomicUsize::new(0);
        let fetch = || {
            asked.fetch_add(1, Ordering::SeqCst);
            Ok::<_, CloudError>(vec![1u64, 2])
        };
        let first = read_through(dir.path(), CLOUD, "vlt_a", "list", fetch).unwrap();
        let second = read_through(dir.path(), CLOUD, "vlt_a", "list", || {
            asked.fetch_add(1, Ordering::SeqCst);
            Ok::<_, CloudError>(vec![9u64])
        })
        .unwrap();
        assert_eq!(first.value, vec![1, 2]);
        assert_eq!(
            second,
            Read {
                value: vec![1, 2],
                stale: None
            }
        );
        assert_eq!(
            asked.load(Ordering::SeqCst),
            1,
            "the second read asked LeanCTX Cloud again"
        );
        // Aged past the TTL, or outdated by a change: asked again.
        age(dir.path(), "vlt_a", "list", 16);
        read_through(dir.path(), CLOUD, "vlt_a", "list", || {
            Ok::<_, CloudError>(vec![3u64])
        })
        .unwrap();
        outdate(dir.path(), "vlt_a");
        let after = read_through(dir.path(), CLOUD, "vlt_a", "list", || {
            Ok::<_, CloudError>(vec![4u64])
        })
        .unwrap();
        assert_eq!(after.value, vec![4]);
    }

    #[test]
    fn callers_at_the_same_time_share_one_request() {
        let dir = Arc::new(tempfile::tempdir().unwrap());
        let asked = Arc::new(AtomicUsize::new(0));
        let start = Arc::new(Barrier::new(8));
        let handles: Vec<_> = (0..8)
            .map(|_| {
                let (dir, asked, start) = (dir.clone(), asked.clone(), start.clone());
                std::thread::spawn(move || {
                    start.wait();
                    read_through(dir.path(), CLOUD, "vlt_a", "list?state=open", || {
                        asked.fetch_add(1, Ordering::SeqCst);
                        std::thread::sleep(Duration::from_millis(300));
                        Ok::<_, CloudError>(vec![7u64])
                    })
                    .unwrap()
                })
            })
            .collect();
        for handle in handles {
            assert_eq!(handle.join().unwrap().value, vec![7]);
        }
        assert_eq!(
            asked.load(Ordering::SeqCst),
            1,
            "eight callers, one request"
        );
    }

    #[test]
    fn a_429_serves_the_last_good_answer_stale_and_holds_reads() {
        let dir = tempfile::tempdir().unwrap();
        read_through(dir.path(), CLOUD, "vlt_a", "task#376", || {
            Ok::<_, CloudError>(376u64)
        })
        .unwrap();
        age(dir.path(), "vlt_a", "task#376", 40);
        let limited = read_through(dir.path(), CLOUD, "vlt_a", "task#376", || {
            Err::<u64, _>(CloudError::RateLimited {
                retry_after: Some(320),
            })
        })
        .unwrap();
        assert_eq!(limited.value, 376, "the last good answer, not an error");
        let why = limited.stale.expect("marked stale");
        assert_eq!(why.reason, "rate_limited");
        assert!(why.age_s >= 40);
        assert_eq!(why.retry_after_s, Some(320));
        // While the hold lasts nothing is asked, for any entry of the Instance.
        let asked = AtomicUsize::new(0);
        let held = read_through(dir.path(), CLOUD, "vlt_b", "list", || {
            asked.fetch_add(1, Ordering::SeqCst);
            Ok::<_, CloudError>(1u64)
        });
        assert_eq!(asked.load(Ordering::SeqCst), 0);
        match held {
            Err(CloudError::RateLimited {
                retry_after: Some(s),
            }) => assert!((1..=320).contains(&s)),
            other => panic!("expected rate limited, got {other:?}"),
        }
        assert!(hold_left(dir.path(), CLOUD).is_some());
    }

    #[test]
    fn a_429_without_a_kept_answer_is_rate_limited_not_not_found() {
        let dir = tempfile::tempdir().unwrap();
        let answer = read_through(dir.path(), CLOUD, "vlt_a", "task#9", || {
            Err::<u64, _>(CloudError::RateLimited { retry_after: None })
        });
        match answer {
            Err(CloudError::RateLimited {
                retry_after: Some(s),
            }) => {
                assert_eq!(s, DEFAULT_HOLD.as_secs());
            }
            other => panic!("expected rate limited, got {other:?}"),
        }
        let held = hold_left(dir.path(), CLOUD).expect("held");
        assert!(held <= DEFAULT_HOLD.as_secs());
    }

    #[test]
    fn cloud_not_reachable_serves_the_kept_answer_and_not_found_stays_an_error() {
        let dir = tempfile::tempdir().unwrap();
        read_through(dir.path(), CLOUD, "vlt_a", "list", || {
            Ok::<_, CloudError>(5u64)
        })
        .unwrap();
        age(dir.path(), "vlt_a", "list", 30);
        let offline = read_through(dir.path(), CLOUD, "vlt_a", "list", || {
            Err::<u64, _>(CloudError::Offline("down".into()))
        })
        .unwrap();
        assert_eq!(offline.value, 5);
        assert_eq!(offline.stale.unwrap().reason, "unavailable");
        let gone = read_through(dir.path(), CLOUD, "vlt_a", "task#1", || {
            Err::<u64, _>(CloudError::NotFound)
        });
        assert!(matches!(gone, Err(CloudError::NotFound)));
        assert_eq!(hold_left(dir.path(), CLOUD), None, "only a 429 holds reads");
    }

    /// Review 5!246 #6: the flight locks are a bounded set of plain file
    /// names, not one file per list query or task number.
    #[test]
    fn flight_lock_names_carry_no_path_characters_and_stay_bounded() {
        let name = flight("vlt_a/../b", "list?state=open&priority=high");
        assert!(
            name.chars()
                .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
        );
        let names: std::collections::BTreeSet<String> = (0..5_000)
            .map(|n| flight("vlt_a", &format!("task#{n}")))
            .collect();
        assert!(names.len() as u64 <= FLIGHT_SLOTS, "{}", names.len());
        assert_eq!(flight("vlt_a", "task#1"), flight("vlt_a", "task#1"));
        let dir = tempfile::tempdir().unwrap();
        for n in 0..300u64 {
            read_through(dir.path(), CLOUD, "vlt_a", &format!("task#{n}"), || {
                Ok::<_, CloudError>(n)
            })
            .unwrap();
        }
        let locks = std::fs::read_dir(dir.path())
            .unwrap()
            .filter_map(Result::ok)
            .filter(|e| e.file_name().to_string_lossy().starts_with("task-fetch-"))
            .count();
        assert!(locks as u64 <= FLIGHT_SLOTS, "{locks} lock files");
    }

    /// Review 5!246 #3: a change while a fetch runs (another process
    /// claims) leaves the answer that fetch stores not current: the next
    /// read asks Cloud instead of serving it for the TTL.
    #[test]
    fn an_outdate_during_a_fetch_is_not_lost() {
        let dir = tempfile::tempdir().unwrap();
        let during = read_through(dir.path(), CLOUD, "vlt_a", "task#5", || {
            // Another process writes and outdates the vault meanwhile.
            std::thread::sleep(Duration::from_millis(5));
            outdate(dir.path(), "vlt_a");
            Ok::<_, CloudError>("before the write".to_string())
        })
        .unwrap();
        assert_eq!(during.value, "before the write");
        let asked = AtomicUsize::new(0);
        let next = read_through(dir.path(), CLOUD, "vlt_a", "task#5", || {
            asked.fetch_add(1, Ordering::SeqCst);
            Ok::<_, CloudError>("after the write".to_string())
        })
        .unwrap();
        assert_eq!(
            asked.load(Ordering::SeqCst),
            1,
            "served the pre-write answer"
        );
        assert_eq!(next.value, "after the write");
        // A fetch that starts after the change is current again.
        let cached = read_through(dir.path(), CLOUD, "vlt_a", "task#5", || {
            Ok::<_, CloudError>("asked again".to_string())
        })
        .unwrap();
        assert_eq!(cached.value, "after the write");
    }

    /// Review 5!246 #4: `tasks::list`/`show` (and the relay catch-up) take
    /// only a current answer; a stale one is the error it stands in for,
    /// never task state from before a claim or close.
    #[test]
    fn a_stale_answer_is_not_current() {
        let dir = tempfile::tempdir().unwrap();
        read_through(dir.path(), CLOUD, "vlt_a", "list", || {
            Ok::<_, CloudError>(1u64)
        })
        .unwrap();
        outdate(dir.path(), "vlt_a");
        let held = read_through(dir.path(), CLOUD, "vlt_a", "list", || {
            Err::<u64, _>(CloudError::RateLimited {
                retry_after: Some(30),
            })
        })
        .unwrap();
        assert!(held.stale.is_some(), "the outdated answer is served stale");
        match current(held) {
            Err(CloudError::RateLimited {
                retry_after: Some(30),
            }) => {}
            other => panic!("expected rate limited, got {other:?}"),
        }
        let offline = Read {
            value: 1u64,
            stale: Some(Stale {
                age_s: 9,
                reason: "unavailable",
                retry_after_s: None,
            }),
        };
        assert!(matches!(current(offline), Err(CloudError::Offline(_))));
        assert_eq!(
            current(Read {
                value: 1u64,
                stale: None
            })
            .unwrap(),
            1
        );
    }

    /// Review 5!246 #7: a 429 of one Cloud does not hold reads of another.
    #[test]
    fn a_hold_is_scoped_to_the_cloud_that_sent_it() {
        let dir = tempfile::tempdir().unwrap();
        let _ = read_through(dir.path(), CLOUD, "vlt_a", "list", || {
            Err::<u64, _>(CloudError::RateLimited {
                retry_after: Some(300),
            })
        });
        assert!(hold_left(dir.path(), CLOUD).is_some());
        let other = "https://cloud.other.example";
        assert_eq!(hold_left(dir.path(), other), None);
        let answer = read_through(dir.path(), other, "vlt_b", "list", || {
            Ok::<_, CloudError>(2u64)
        })
        .unwrap();
        assert_eq!(answer.value, 2);
    }
}