~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
6129 lines · 223.2 KB Raw History
//! The space repo, as `spec/SPACES-REPO.md` says: each account's records in
//! each space it writes to, their commit and operation log, the
//! `com.atproto.space` record writes and the reads, with MACs on request;
//! and, as `spec/SPACES-EXPORT.md` says, a repo whole as a STAR archive
//! (`getRepo`), the blobs its records reference (`getBlob`, `listBlobs`),
//! and a repo imported whole (`importRepo`).
//!
//! An account's space repos are kept in its own log (`log`), beside its
//! repository: each commit of a space repo is one frame, holding one
//! `space` entry, and each import one `spaceRepoImport` entry. A write
//! takes the account's lock only to apply its commit and hand that frame to
//! the operating system; it answers once the frame is on disk, as a
//! repository write does.
//!
//! Of a space repo a store holds in memory its commit and what the next is
//! made from (`SpaceRepo`): its rev, the lanes of its LtHash, and the
//! counts of its records and operations. Its records, their bytes, its
//! operation log and its records' blob references are entries of the
//! account's table and of the log after it (`checkpoint::spaces`), read as
//! they are needed: a record by its path, a page of records or operations
//! by a scan from where it begins, the repo whole as it is sent.
//!
//! A space record's blob refs hold blobs as a public record's do (`blobs`):
//! each repo keeps which of its records reference each CID, and the
//! account's blobs count them across its space repos, as each commit,
//! import and drop lands, and again as the log is replayed.
//!
//! The records the space host publishes in its authority's repo (the
//! policy and the members, `space_authority`) are written through
//! `Publish`, as any write of that repo is: their commits go in the frame of
//! the change that made them, and a deleted space's repo is dropped with a
//! `spaceDrop` entry.
//!
//! For other parts of spaces: `Hooks::on_commit` hears of every commit once
//! it is durable, but an import's, and `with_space_repo` reads a repo at its
//! head.

use crate::blobs::{self, BlobRef, cids_in};
use crate::cache::Ctx;
use crate::checkpoint::spaces::{
    MemRecord, Meta, Old, Ops, SpaceMem, SpaceSnapshot, View, Void, after_prefix, space_key,
};
use crate::oauth::space_scope::SpaceOp;
use crate::repo::{typed, validation_status, with_status};
use crate::space_authority::{Publication, Publisher};
use crate::space_credentials::{presents_credential, verify_space_credential};
use crate::{
    Account, Call, Handler, Resp, Service, Shared, Shown, Store, XrpcError, err, internal, invalid,
    opt, read, required,
};
use axum::body::{Body, Bytes};
use axum::http::{StatusCode, header};
use axum::response::{IntoResponse, Response};
use pds_lexicon::Method;
use pds_repo::data::{V, cid_string, decode, from_json, parse_cid, to_json};
use pds_repo::{Record, Tids, make_record, put_record, put_value, valid_tid};
use pds_space::lthash::element;
use pds_space::mac::{self, ACCEPT_SIGNATURE};
use pds_space::{Commit, LtHash, MacHeaders, Profile, SharedSecret, SpaceRef, star};
use pds_store::Pos;
use pds_store::table::BlockCache;
use serde_json::{Map, Value as Json, json};
use std::collections::{BTreeMap, BTreeSet};
use std::io;
use std::ops::Bound::{self, Excluded, Included, Unbounded};
use std::pin::Pin;
use std::sync::{Arc, RwLock};

/// The type of a space repo's entries in its account's log: a commit, the
/// repo dropped with its space, and the repo imported whole.
pub(crate) const ENTRY: &str = "space";
pub(crate) const DROP: &str = "spaceDrop";
pub(crate) const IMPORT: &str = "spaceRepoImport";

/// The collections only the space host writes, from a space's configuration.
const PUBLISHED: [&str; 2] = ["com.atproto.space.policy", "com.atproto.memberspace.member"];

/// The longest record, as DRISL: the longest value a STAR archive of the repo may hold.
const MAX_RECORD: usize = 1_048_576;

/// The most writes one `applyWrites` takes; the longest bodies are `limits::body_limit`'s.
const MAX_WRITES: usize = crate::limits::MAX_WRITES;

pub(crate) fn handler(nsid: &str) -> Option<Handler> {
    Some(match nsid {
        "com.atproto.space.createRecord"
        | "com.atproto.space.putRecord"
        | "com.atproto.space.deleteRecord"
        | "com.atproto.space.applyWrites"
        | "com.atproto.space.clearRecords" => Handler::Call(write_call),
        "com.atproto.space.getRecord" => {
            Handler::Call(|s, c, m| Box::pin(read_call(s, c, m, get_record)))
        }
        "com.atproto.space.listRecords" => {
            Handler::Call(|s, c, m| Box::pin(read_call(s, c, m, list_records)))
        }
        "com.atproto.space.getLatestCommit" => {
            Handler::Call(|s, c, m| Box::pin(read_call(s, c, m, get_latest_commit)))
        }
        "com.atproto.space.listRepoOps" => {
            Handler::Call(|s, c, m| Box::pin(read_call(s, c, m, list_repo_ops)))
        }
        "com.atproto.space.getRepo" => {
            Handler::Call(|s, c, m| Box::pin(read_call(s, c, m, get_repo)))
        }
        "com.atproto.space.getBlob" => {
            Handler::Call(|s, c, m| Box::pin(read_call(s, c, m, get_blob)))
        }
        "com.atproto.space.listBlobs" => {
            Handler::Call(|s, c, m| Box::pin(read_call(s, c, m, list_blobs)))
        }
        "com.atproto.space.importRepo" => Handler::Call(|s, c, _| Box::pin(import_repo(s, c))),
        "com.atproto.space.listSpaces" => Handler::Query(list_spaces),
        _ => return None,
    })
}

// ---- Storage --------------------------------------------------------------

/// One operation of a space repo's log: at its commit's `rev`, and `index`
/// within that commit; the record's CID after it and before it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct Op {
    pub rev: String,
    pub index: usize,
    /// `{collection}/{rkey}`.
    pub path: String,
    pub cid: Option<Vec<u8>>,
    pub prev: Option<Vec<u8>>,
}

/// The operations of a commit at `rev`, from their list as its log entry
/// has it: each its path, and its CID after and before.
pub(crate) fn ops_of(rev: &str, list: &[Json]) -> Result<Vec<Op>, String> {
    let bad = |what: &str| format!("a space commit with a bad {what}");
    let cid = |j: &Json| match j {
        Json::Null => Ok(None),
        Json::String(c) => parse_cid(c).map(Some).ok_or_else(|| bad("cid")),
        _ => Err(bad("cid")),
    };
    list.iter()
        .enumerate()
        .map(|(index, o)| match o.as_array().map(Vec::as_slice) {
            Some([Json::String(p), c, prev]) if p.contains('/') => Ok(Op {
                rev: rev.into(),
                index,
                path: p.clone(),
                cid: cid(c)?,
                prev: cid(prev)?,
            }),
            _ => Err(bad("op")),
        })
        .collect()
}

/// What a change to a space repo did to the number of its records
/// referencing each blob, by CID (`Blobs::space_counted`).
pub(crate) type RefDelta = BTreeMap<String, i64>;

/// An account's repo in one space, as a store holds it in memory and its
/// table's `S` keeps it: its commit, and what the next is made from. Its
/// records, their bytes, its operation log and its records' blob
/// references are read from the table's sections and the log
/// (`checkpoint::spaces`).
pub(crate) struct SpaceRepo {
    /// The LtHash of the records' elements, and its digest.
    hash: LtHash,
    data: [u8; 32],
    rev: String,
    /// Its revs: each the TID of its time, or one after the last.
    tids: Tids,
    /// How many records it holds, and how many operations its log does:
    /// every one since the repo began or was last cleared or imported.
    records: u64,
    ops: u64,
}

impl SpaceRepo {
    fn new() -> SpaceRepo {
        let hash = LtHash::new();
        SpaceRepo {
            data: hash.digest(),
            hash,
            rev: String::new(),
            tids: Tids::new(),
            records: 0,
            ops: 0,
        }
    }

    /// Its commit, `repo` its author's DID and `space` the space's URI.
    pub fn commit(&self, repo: &str, space: &str) -> Commit {
        Commit {
            repo: repo.into(),
            space: space.into(),
            rev: self.rev.clone(),
            data: self.data,
        }
    }
}

/// An account's space repos, by their space's URI.
#[derive(Default)]
pub(crate) struct Spaces {
    repos: BTreeMap<String, SpaceRepo>,
}

/// The bytes a space repo is counted as in the cache: its hash's lanes,
/// its URI and the rest.
const REPO_COST: u64 = 2560;

/// One commit of a space repo: what it changed, as its log entry has it.
pub(crate) struct Change {
    space: String,
    rev: String,
    ops: Vec<Op>,
    /// The records it left at paths it wrote, and the paths it left empty.
    puts: Vec<(String, Record)>,
    dels: Vec<String>,
    /// Whether it cleared the operation log first (`clearRecords`).
    clear: bool,
    /// Of a `clearRecords` that names no record it deletes: the prefixes of
    /// the paths whose records stay, every other record deleted. None in a
    /// commit that names in `dels` each record it deletes.
    kept: Option<Vec<String>>,
}

fn cid_text(c: &Option<Vec<u8>>) -> Json {
    c.as_ref().map_or(Json::Null, |c| json!(cid_string(c)))
}

impl Change {
    /// Its log entry, but for its `data`.
    fn entry(&self) -> Json {
        let mut e = json!({
            "t": ENTRY, "space": self.space, "rev": self.rev, "clear": self.clear,
            "ops": self.ops.iter().map(|o| json!([o.path, cid_text(&o.cid), cid_text(&o.prev)])).collect::<Vec<_>>(),
            "puts": self.puts.iter().map(|(p, r)| json!([p, put_value(r)])).collect::<Vec<_>>(),
            "dels": self.dels,
        });
        if let Some(kept) = &self.kept {
            e["kept"] = json!(kept);
        }
        e
    }

    /// A log entry, and the `data` its commit had.
    fn parse(e: &Json) -> Result<(Change, [u8; 32]), String> {
        let bad = |what: &str| format!("a space commit with a bad {what}");
        let text = |k: &str| e[k].as_str().ok_or_else(|| bad(k));
        let space = text("space")?;
        if SpaceRef::parse(space).is_none() {
            return Err(bad("space"));
        }
        let rev = text("rev")?;
        if !valid_tid(rev) {
            return Err(bad("rev"));
        }
        let data: [u8; 32] = hex::decode(text("data")?)
            .ok()
            .and_then(|b| b.try_into().ok())
            .ok_or_else(|| bad("data"))?;
        let clear = e["clear"].as_bool().ok_or_else(|| bad("clear"))?;
        let list = |k: &str| e[k].as_array().ok_or_else(|| bad(k));
        let path = |j: &Json| {
            j.as_str()
                .filter(|p| p.contains('/'))
                .map(str::to_string)
                .ok_or_else(|| bad("path"))
        };
        let ops = ops_of(rev, list("ops")?)?;
        let puts: Vec<(String, Record)> = list("puts")?
            .iter()
            .map(|p| match p.as_array().map(Vec::as_slice) {
                Some([p, v]) => Ok((
                    path(p)?,
                    put_record(v).map_err(|why| format!("a space record: {why}"))?,
                )),
                _ => Err(bad("put")),
            })
            .collect::<Result<_, _>>()?;
        let dels: Vec<String> = list("dels")?.iter().map(path).collect::<Result<_, _>>()?;
        // A commit that keeps some records and deletes every other names none.
        let kept = match e.get("kept") {
            None => None,
            Some(k) => Some(
                k.as_array()
                    .filter(|_| clear && ops.is_empty() && puts.is_empty() && dels.is_empty())
                    .and_then(|k| {
                        k.iter()
                            .map(|p| p.as_str().filter(|p| !p.is_empty()).map(str::to_string))
                            .collect::<Option<Vec<String>>>()
                    })
                    .ok_or_else(|| bad("kept"))?,
            ),
        };
        Ok((
            Change {
                space: space.into(),
                rev: rev.into(),
                ops,
                puts,
                dels,
                clear,
                kept,
            },
            data,
        ))
    }
}

/// A repo imported whole (`importRepo`): its records, and the rev of the
/// commit it gets here, as its log entry has them.
pub(crate) struct Import {
    space: String,
    rev: String,
    /// In ascending order of path.
    records: Vec<(String, Record)>,
}

impl Import {
    /// Its log entry, with the `data` its records make.
    fn entry(&self, data: &[u8; 32]) -> Json {
        json!({
            "t": IMPORT, "space": self.space, "rev": self.rev, "data": hex::encode(data),
            "records": self.records.iter().map(|(p, r)| json!([p, put_value(r)])).collect::<Vec<_>>(),
        })
    }

    /// A log entry, and the `data` its records made.
    fn parse(e: &Json) -> Result<(Import, [u8; 32]), String> {
        let bad = |what: &str| format!("a space repo import with a bad {what}");
        let text = |k: &str| e[k].as_str().ok_or_else(|| bad(k));
        let space = text("space")?;
        if SpaceRef::parse(space).is_none() {
            return Err(bad("space"));
        }
        let rev = text("rev")?;
        if !valid_tid(rev) {
            return Err(bad("rev"));
        }
        let data: [u8; 32] = hex::decode(text("data")?)
            .ok()
            .and_then(|b| b.try_into().ok())
            .ok_or_else(|| bad("data"))?;
        let records: Vec<(String, Record)> = e["records"]
            .as_array()
            .ok_or_else(|| bad("records"))?
            .iter()
            .map(|p| match p.as_array().map(Vec::as_slice) {
                Some([Json::String(p), v]) if star::is_record_path(p) => Ok((
                    p.clone(),
                    put_record(v).map_err(|why| format!("a space record: {why}"))?,
                )),
                _ => Err(bad("record")),
            })
            .collect::<Result<_, _>>()?;
        if records.windows(2).any(|w| w[0].0 >= w[1].0) {
            return Err(bad("order of records"));
        }
        Ok((
            Import {
                space: space.into(),
                rev: rev.into(),
                records,
            },
            data,
        ))
    }
}

/// What a commit, an import or a drop does to a space repo, worked out
/// against what the repo holds, changing nothing: made once its frame is
/// written (`Spaces::land`).
pub(crate) struct Effect {
    space: String,
    /// The repo as it leaves it, or none, dropped: its hash, its rev, and
    /// how many records and operations it has.
    after: Option<(LtHash, String, u64, u64)>,
    /// Each record it wrote, as its `R` entry has it, or deleted, by path.
    records: Vec<(String, Option<Meta>)>,
    /// How many operations its commit has.
    ops: u32,
    /// Each blob reference it made, with the rev that wrote the referencing
    /// record, or took away: the blob's CID and the record's path.
    refs: Vec<(String, String, Option<String>)>,
    /// What it voids of the table's entries of the repo: the prefixes of
    /// the records' paths it keeps, none if it voids no record, and whether
    /// it voids the blob references (`Void`).
    void: Option<(Option<Vec<String>>, bool)>,
    /// What it does to the number of records referencing each blob.
    delta: RefDelta,
}

impl Effect {
    fn new(space: &str) -> Effect {
        Effect {
            space: space.into(),
            after: None,
            records: Vec::new(),
            ops: 0,
            refs: Vec::new(),
            void: None,
            delta: RefDelta::new(),
        }
    }

    /// The `data` of the commit it leaves.
    fn data(&self) -> [u8; 32] {
        match &self.after {
            Some((hash, ..)) => hash.digest(),
            None => LtHash::new().digest(),
        }
    }

    /// Every blob reference of the repo is gone: each counted in `delta`.
    fn unreferenced(&mut self, view: View<'_>) -> Result<(), String> {
        for r in view.refs(&self.space, b"") {
            *self.delta.entry(r?.0).or_default() -= 1;
        }
        Ok(())
    }
}

impl Spaces {
    /// The repo in a space, by its URI.
    pub fn get(&self, space: &str) -> Option<&SpaceRepo> {
        self.repos.get(space)
    }

    /// The bytes they are counted as in the cache.
    pub(crate) fn cost(&self) -> u64 {
        self.repos.len() as u64 * REPO_COST
    }

    /// What a commit does, beginning the repo if it is its first: its
    /// records, their LtHash, its rev and its operations, and the blobs its
    /// records reference. The record at each path it writes is read through
    /// `view`, for its CID and its blob references; of a commit that names
    /// no record it deletes, the records it keeps and every blob reference.
    fn commit(&self, c: &Change, view: View<'_>) -> Result<Effect, String> {
        let held = self.repos.get(&c.space);
        let (mut hash, mut records, mut ops) = match held {
            Some(r) => (r.hash.clone(), r.records, r.ops),
            None => (LtHash::new(), 0, 0),
        };
        let mut e = Effect::new(&c.space);
        e.ops = c.ops.len() as u32;
        let element_of = |path: &str, cid: &[u8]| element(path, &cid_string(cid));
        if let Some(kept) = &c.kept {
            (hash, records) = (LtHash::new(), 0);
            e.unreferenced(view)?;
            for prefix in kept {
                let (lo, hi) = (prefix.as_bytes(), after_prefix(prefix));
                for r in view.records(&c.space, Included(lo), Excluded(&hi), false) {
                    let (path, meta, _) = r?;
                    hash.add(&element_of(&path, &meta.cid));
                    records += 1;
                    for cid in meta.refs {
                        *e.delta.entry(cid.clone()).or_default() += 1;
                        e.refs.push((cid, path.clone(), Some(meta.rev.clone())));
                    }
                }
            }
            e.void = Some((Some(kept.clone()), true));
        } else if c.clear {
            e.void = Some((None, false));
        }
        for path in &c.dels {
            if let Some((old, _)) = view.record(&c.space, path)? {
                hash.remove(&element_of(path, &old.cid));
                records = records.saturating_sub(1);
                for cid in old.refs {
                    *e.delta.entry(cid.clone()).or_default() -= 1;
                    e.refs.push((cid, path.clone(), None));
                }
            }
            e.records.push((path.clone(), None));
        }
        for (path, rec) in &c.puts {
            let now = cids_in(&rec.value);
            hash.add(&element_of(path, &rec.cid));
            match view.record(&c.space, path)? {
                Some((old, _)) => {
                    hash.remove(&element_of(path, &old.cid));
                    for cid in old.refs {
                        *e.delta.entry(cid.clone()).or_default() -= 1;
                        if !now.contains(&cid) {
                            e.refs.push((cid, path.clone(), None));
                        }
                    }
                }
                None => records += 1,
            }
            for cid in &now {
                *e.delta.entry(cid.clone()).or_default() += 1;
                e.refs
                    .push((cid.clone(), path.clone(), Some(c.rev.clone())));
            }
            let meta = Meta {
                cid: rec.cid.clone(),
                rev: c.rev.clone(),
                refs: now,
            };
            e.records.push((path.clone(), Some(meta)));
        }
        if c.clear {
            ops = 0;
        }
        e.delta.retain(|_, d| *d != 0);
        e.after = Some((hash, c.rev.clone(), records, ops + c.ops.len() as u64));
        Ok(e)
    }

    /// What an import does: the repo replaced, or begun if there is none,
    /// with exactly its records, an empty operation log, and its rev. The
    /// blobs the records reference are counted, held by the account or not.
    fn import(&self, i: &Import, view: View<'_>) -> Result<Effect, String> {
        let mut e = Effect::new(&i.space);
        e.unreferenced(view)?;
        let mut hash = LtHash::new();
        for (path, rec) in &i.records {
            hash.add(&element(path, &cid_string(&rec.cid)));
            let refs = cids_in(&rec.value);
            for cid in &refs {
                *e.delta.entry(cid.clone()).or_default() += 1;
                e.refs
                    .push((cid.clone(), path.clone(), Some(i.rev.clone())));
            }
            let meta = Meta {
                cid: rec.cid.clone(),
                rev: i.rev.clone(),
                refs,
            };
            e.records.push((path.clone(), Some(meta)));
        }
        e.delta.retain(|_, d| *d != 0);
        e.void = Some((Some(vec![]), true));
        e.after = Some((hash, i.rev.clone(), i.records.len() as u64, 0));
        Ok(e)
    }

    /// What dropping a repo with its space does, if there is one: the blobs
    /// its records reference are no longer referenced by them.
    fn dropped(&self, uri: &str, view: View<'_>) -> Result<Option<Effect>, String> {
        if !self.repos.contains_key(uri) {
            return Ok(None);
        }
        let mut e = Effect::new(uri);
        e.unreferenced(view)?;
        e.void = Some((Some(vec![]), true));
        Ok(Some(e))
    }

    /// Make what `commit`, `import` or `dropped` worked out, its entry in
    /// the frame at `pos`: the repo as it leaves it; in the memtable, what
    /// it voids of the table, each record and blob reference it changed and
    /// where its operations are; and in the account's `blobs`, the
    /// references counted.
    fn land(&mut self, e: Effect, pos: Pos, mem: &mut SpaceMem, blobs: &mut blobs::Blobs) {
        let generation = pos.generation;
        if let Some((keep, refs)) = e.void {
            let void = Void {
                generation,
                keep,
                refs,
            };
            mem.void(&e.space, void);
        }
        for (path, meta) in e.records {
            let r = meta.map(|meta| MemRecord { meta, pos });
            mem.record(&e.space, &path, r, generation);
        }
        for (cid, path, rev) in e.refs {
            mem.reference(&e.space, &cid, &path, rev, generation);
        }
        match e.after {
            None => {
                self.repos.remove(&e.space);
            }
            Some((hash, rev, records, ops)) => {
                if e.ops > 0 {
                    mem.commit(&e.space, &rev, pos, e.ops);
                }
                let repo = self.repos.entry(e.space).or_insert_with(SpaceRepo::new);
                repo.data = hash.digest();
                repo.hash = hash;
                repo.tids.after(&rev);
                (repo.rev, repo.records, repo.ops) = (rev, records, ops);
            }
        }
        blobs.space_counted(e.delta);
    }

    /// Replay a space repo's entry of the account's log, in the frame at
    /// `pos`: a commit, an import, or the repo dropped with its space. A
    /// commit's or an import's rev must follow the repo's last, and its
    /// records must make the `data` it had: by the repo's LtHash and the
    /// CIDs of the records it replaces, read from `mem` and the table's
    /// entries, `old`. Record keys made after it are later than its rev, by
    /// `tids`.
    #[allow(clippy::too_many_arguments)]
    pub fn replay(
        &mut self,
        e: &Json,
        pos: Pos,
        mem: &mut SpaceMem,
        old: Old<'_>,
        cache: &BlockCache,
        tids: &mut Tids,
        blobs: &mut blobs::Blobs,
    ) -> Result<(), String> {
        let view = View { mem, old, cache };
        let follows = |space: &str, rev: &str, what: &str| {
            if self.repos.get(space).is_some_and(|r| r.rev.as_str() >= rev) {
                return Err(format!("space repo {space}: {what} {rev} out of order"));
            }
            Ok(())
        };
        let made = |effect: Effect, data: [u8; 32], rev: &str, what: &str| {
            if effect.data() != data {
                return Err(format!(
                    "space repo {}: the records do not make the data of {what} {rev}",
                    effect.space
                ));
            }
            Ok(effect)
        };
        let effect = match e["t"].as_str() {
            Some(ENTRY) => {
                let (c, data) = Change::parse(e)?;
                follows(&c.space, &c.rev, "commit")?;
                tids.after(&c.rev);
                made(self.commit(&c, view)?, data, &c.rev, "commit")?
            }
            Some(IMPORT) => {
                let (i, data) = Import::parse(e)?;
                follows(&i.space, &i.rev, "import")?;
                tids.after(&i.rev);
                made(self.import(&i, view)?, data, &i.rev, "import")?
            }
            _ => {
                let space = e["space"]
                    .as_str()
                    .filter(|s| SpaceRef::parse(s).is_some())
                    .ok_or("a space repo dropped with a bad space")?;
                self.dropped(space, view)?
                    .ok_or_else(|| format!("space repo {space} dropped, which there is not"))?
            }
        };
        self.land(effect, pos, mem, blobs);
        Ok(())
    }

    /// Each repo as a checkpoint keeps it, in ascending order of its space's URI.
    pub(crate) fn saved(&self) -> impl Iterator<Item = Saved<'_>> {
        self.repos.iter().map(|(space, r)| Saved {
            space,
            rev: &r.rev,
            data: &r.data,
            hash: r.hash.state().to_vec(),
            records: r.records,
            ops: r.ops,
        })
    }

    /// Restore a repo a checkpoint keeps: its hash's lanes must make its
    /// `data`. Revs made after it, its own and the account's `tids`, are later.
    pub(crate) fn restore(&mut self, r: Restore, tids: &mut Tids) -> Result<(), String> {
        let bad = |what: &str| format!("space repo {}: {what}", r.space);
        if SpaceRef::parse(&r.space).is_none() || !valid_tid(&r.rev) {
            return Err(bad("a bad space or rev"));
        }
        if self.repos.contains_key(&r.space) {
            return Err(bad("twice"));
        }
        let Some(hash) = LtHash::from_state(&r.hash).filter(|h| h.digest() == r.data) else {
            return Err(bad("a hash that does not make its data"));
        };
        let mut repo = SpaceRepo::new();
        repo.tids.after(&r.rev);
        tids.after(&r.rev);
        (repo.hash, repo.data, repo.records, repo.ops) = (hash, r.data, r.records, r.ops);
        repo.rev = r.rev;
        self.repos.insert(r.space, repo);
        Ok(())
    }
}

/// A space repo as a checkpoint keeps it (`spec/STORE.md`): its space's URI,
/// its commit's rev and data, the state of its LtHash, and how many records
/// and operations it has.
pub(crate) struct Saved<'a> {
    pub space: &'a str,
    pub rev: &'a str,
    pub data: &'a [u8; 32],
    pub hash: Vec<u8>,
    pub records: u64,
    pub ops: u64,
}

/// A space repo read from a checkpoint, as `Saved` has it.
pub(crate) struct Restore {
    pub space: String,
    pub rev: String,
    pub data: [u8; 32],
    pub hash: Vec<u8>,
    pub records: u64,
    pub ops: u64,
}

// ---- Reading a repo's records and operations --------------------------------

impl Store {
    /// Its space repos' sections as they are now.
    fn space_view(&self) -> View<'_> {
        self.disk.spaces(&self.ctx.blocks)
    }

    /// The record at `path` of its repo in the space `uri`, as its `R`
    /// entry has it, and where its frame is, if its bytes are in the log.
    fn space_meta(&self, uri: &str, path: &str) -> Option<(Meta, Option<Pos>)> {
        self.space_view()
            .record(uri, path)
            .unwrap_or_else(|e| self.disk.fail(e))
    }

    /// The value of the record at `path` of its repo in the space `uri`,
    /// which `meta` and `pos` are of, as JSON.
    fn space_json(&self, uri: &str, path: &str, meta: &Meta, pos: Option<Pos>) -> Json {
        let bytes = self
            .disk
            .space_bytes(&self.ctx.blocks, uri, path, meta, pos);
        match decode(&bytes) {
            Ok(v) => to_json(&v),
            Err(e) => self.disk.fail(format!("space record {uri} {path}: {e}")),
        }
    }

    /// The records of its repo in the space `uri` whose paths are within
    /// the bounds, in order of path or the last first, each read as it is
    /// reached: its path, its `R` entry, and where its frame is.
    fn space_records<'a>(
        &'a self,
        uri: &str,
        lo: Bound<&[u8]>,
        hi: Bound<&[u8]>,
        reverse: bool,
    ) -> impl Iterator<Item = (String, Meta, Option<Pos>)> + use<'a> {
        self.space_view()
            .records(uri, lo, hi, reverse)
            .map(|r| r.unwrap_or_else(|e| self.disk.fail(e)))
    }

    /// The operations of its repo in the space `uri` after the rev `since`
    /// and after the operation at `cursor`, its rev and index, in order, at
    /// most `limit`: a seek to the first, then those read.
    fn space_ops(
        &self,
        uri: &str,
        since: Option<&str>,
        cursor: Option<(&str, usize)>,
        limit: usize,
    ) -> Vec<Op> {
        let cache = &self.ctx.blocks;
        let after = |o: &Op| {
            since.is_none_or(|s| o.rev.as_str() > s)
                && cursor.is_none_or(|c| (o.rev.as_str(), o.index) > c)
        };
        // Past every operation of a rev: no index is five bytes of 0xff.
        let past = |rev: &str| [rev.as_bytes(), &[0xff; 5]].concat();
        let mut out: Vec<Op> = Vec::new();
        let mut from = match since {
            Some(s) if valid_tid(s) => past(s),
            Some(s) => s.as_bytes().to_vec(),
            None => Vec::new(),
        };
        if let Some((rev, index)) = cursor {
            let commit = space_key(uri, rev.as_bytes());
            let at = match self.disk.mem.spaces.commits.get(&commit) {
                // A commit of the log's: the rest of it, then those after it.
                Some((pos, _)) => {
                    let ops = self.disk.space_commit(cache, uri, rev, *pos);
                    out.extend(ops.into_iter().filter(|o| after(o)).take(limit));
                    past(rev)
                }
                None => match u32::try_from(index).ok().and_then(|i| i.checked_add(1)) {
                    Some(next) => [rev.as_bytes(), &next.to_be_bytes()].concat(),
                    None => past(rev),
                },
            };
            from = from.max(at);
        }
        for r in self.space_view().ops(uri, &from) {
            if out.len() >= limit {
                break;
            }
            match r.unwrap_or_else(|e| self.disk.fail(e)) {
                Ops::Row(o) if after(&o) => out.push(o),
                Ops::Row(_) => {}
                Ops::Commit(rev, pos) => {
                    let ops = self.disk.space_commit(cache, uri, &rev, pos);
                    let room = limit - out.len();
                    out.extend(ops.into_iter().filter(|o| after(o)).take(room));
                }
            }
        }
        out
    }

    /// The CIDs the records of its repo in the space `uri` reference, each
    /// once, in ascending order, after `cursor`, at most `limit`.
    fn space_blobs(&self, uri: &str, cursor: Option<&str>, limit: usize) -> Vec<String> {
        // Past every reference to a blob: no path follows a byte of 1.
        let past = |cid: &str| [cid.as_bytes(), &[1]].concat();
        let mut out: Vec<String> = Vec::new();
        let mut from = cursor.map_or_else(Vec::new, past);
        'seek: while out.len() < limit {
            let mut same = 0;
            for r in self.space_view().refs(uri, &from) {
                let (cid, _, _) = r.unwrap_or_else(|e| self.disk.fail(e));
                if out.last() == Some(&cid) {
                    // A blob many records reference: on from the next.
                    same += 1;
                    if same > 32 {
                        from = past(&cid);
                        continue 'seek;
                    }
                    continue;
                }
                if cursor.is_some_and(|c| cid.as_str() <= c) {
                    continue;
                }
                out.push(cid);
                same = 0;
                if out.len() == limit {
                    break;
                }
            }
            break;
        }
        out
    }

    /// The records of its repo in the space `uri`, each one's value as
    /// JSON, by path; none if it has no repo there.
    #[cfg(test)]
    pub(crate) fn space_values(&self, uri: &str) -> Option<BTreeMap<String, Json>> {
        self.spaces.get(uri)?;
        Some(
            self.space_records(uri, Unbounded, Unbounded, false)
                .map(|(path, meta, pos)| {
                    let value = self.space_json(uri, &path, &meta, pos);
                    (path, value)
                })
                .collect(),
        )
    }
}

// ---- For other parts ------------------------------------------------------

/// What hears of a space repo's commit: `on_commit(space, repo, rev, data)`,
/// the commit's fields.
pub(crate) type OnCommit = Box<dyn Fn(&Shared, &Commit) + Send + Sync>;

/// Who hears of each commit of a space repo on this server.
#[derive(Default)]
pub(crate) struct Hooks {
    on_commit: RwLock<Vec<OnCommit>>,
}

impl Hooks {
    /// Hear of every commit from now on: once each, after it is durable and
    /// before its write answers. It cannot refuse or undo the write.
    pub fn on_commit(&self, f: OnCommit) {
        crate::write(&self.on_commit).push(f);
    }

    pub(crate) fn committed(&self, svc: &Shared, c: &Commit) {
        for f in read(&self.on_commit).iter() {
            f(svc, c);
        }
    }
}

/// Read the account's repo in a space, at its head, None if it has none
/// there, with the store its records and operations are read through; the
/// answer goes out once what it read is on disk (`shown`).
pub(crate) fn with_space_repo<T>(
    a: &Account,
    shown: &mut Shown,
    space: &str,
    f: impl FnOnce(&Store, Option<&SpaceRepo>) -> T,
) -> T {
    let st = read(&a.store);
    shown.0.push((st.wal.clone(), st.wal.written()));
    f(&st, st.spaces.get(space))
}

/// A commit of `did`'s, staged: its log entry, with the `data` it leaves,
/// the commit, and what landing it does. Nothing changes until it is
/// landed, once its frame is written: a write the log could not take leaves
/// nothing of itself.
fn staged(st: &Store, did: &str, c: &Change) -> (Json, Commit, Effect) {
    let effect = st
        .spaces
        .commit(c, st.space_view())
        .unwrap_or_else(|e| st.disk.fail(e));
    let data = effect.data();
    let mut entry = c.entry();
    entry["data"] = json!(hex::encode(data));
    let commit = Commit {
        repo: did.into(),
        space: c.space.clone(),
        rev: c.rev.clone(),
        data,
    };
    (entry, commit, effect)
}

/// Append `entries` to the account's log as one frame, whose items are
/// read alone from then on (`Disk::indexed`): where the frame is.
pub(crate) fn append(st: &Store, entries: &[Json]) -> io::Result<Pos> {
    let frame = pds_store::frame(entries);
    let (_, pos) = st.wal.append_frame_at(&frame)?;
    st.disk
        .indexed(&st.ctx.blocks, pos, &frame[pds_store::HEADER..]);
    Ok(pos)
}

/// A change to an account's space repos, staged for the frame of the change
/// to its spaces that makes it, and made once that frame is written.
pub(crate) enum Staged {
    Land(Effect),
    Drop(String),
}

impl Staged {
    /// Make it, its entry in the frame at `pos`.
    pub fn apply(self, st: &mut Store, pos: Pos) {
        let effect = match self {
            Staged::Land(e) => Some(e),
            Staged::Drop(uri) => st
                .spaces
                .dropped(&uri, st.space_view())
                .unwrap_or_else(|e| st.disk.fail(e)),
        };
        if let Some(e) = effect {
            st.spaces
                .land(e, pos, &mut st.disk.mem.spaces, &mut st.blobs);
        }
    }
}

/// The space repo's write path for the records the space host publishes in
/// its authority's repo: each commit staged and landed as a write's is.
#[derive(Default)]
pub(crate) struct Publish;

impl Publisher for Publish {
    fn rkeys(&self, st: &Store, space: &SpaceRef, collection: &str) -> Vec<String> {
        let (uri, prefix) = (space.uri(), format!("{collection}/"));
        if st.spaces.get(&uri).is_none() {
            return vec![];
        }
        let (lo, hi) = (prefix.as_bytes(), after_prefix(&prefix));
        st.space_records(&uri, Included(lo), Excluded(&hi), false)
            .map(|(path, _, _)| path[prefix.len()..].to_string())
            .collect()
    }

    fn holds(&self, st: &Store, space: &SpaceRef, collection: &str, rkey: &str) -> bool {
        let uri = space.uri();
        st.spaces.get(&uri).is_some()
            && st
                .space_meta(&uri, &format!("{collection}/{rkey}"))
                .is_some()
    }

    fn commit(
        &self,
        st: &mut Store,
        space: &SpaceRef,
        ops: Vec<Publication>,
    ) -> (Json, Commit, Staged) {
        let writes = ops
            .into_iter()
            .map(|op| match op {
                Publication::Put {
                    collection,
                    rkey,
                    record,
                } => {
                    let record = make_record(
                        from_json(&record).expect("a published record is in the data model"),
                    );
                    Write::Put {
                        collection: collection.into(),
                        rkey,
                        record,
                    }
                }
                Publication::Delete { collection, rkey } => Write::Delete {
                    collection: collection.into(),
                    rkey,
                },
            })
            .collect();
        let (did, uri) = (space.authority.as_str(), space.uri());
        let Ok((_, c)) = stage(st, did, &uri, writes, None) else {
            unreachable!("the space host deletes only the records it holds")
        };
        let (entry, commit, effect) = staged(st, did, &c);
        (entry, commit, Staged::Land(effect))
    }

    fn drop_repo(&self, st: &mut Store, space: &SpaceRef) -> Option<(Json, Staged)> {
        let uri = space.uri();
        st.spaces.get(&uri)?;
        Some((json!({ "t": DROP, "space": uri }), Staged::Drop(uri)))
    }
}

// ---- Writes ---------------------------------------------------------------

/// One write, its input and record checked.
enum Write {
    Create {
        collection: String,
        rkey: Option<String>,
        record: Record,
    },
    /// `applyWrites`' update, of a record that must exist.
    Update {
        collection: String,
        rkey: String,
        record: Record,
    },
    /// `putRecord`'s: a create or a replacement.
    Put {
        collection: String,
        rkey: String,
        record: Record,
    },
    /// `applyWrites`' delete, of a record that must exist.
    Delete { collection: String, rkey: String },
}

impl Write {
    fn collection(&self) -> &str {
        match self {
            Write::Create { collection, .. }
            | Write::Update { collection, .. }
            | Write::Put { collection, .. }
            | Write::Delete { collection, .. } => collection,
        }
    }
}

/// What a write method asks.
enum Asked {
    CreateRecord(Write),
    PutRecord(Write),
    /// Of a record that may not exist, which makes no commit.
    DeleteRecord {
        collection: String,
        rkey: String,
    },
    ApplyWrites(Vec<Write>),
    ClearRecords,
}

fn write_call<'a>(
    svc: &'a Shared,
    call: &'a Call<'a>,
    m: &'static Method,
) -> Pin<Box<dyn Future<Output = Result<Resp, XrpcError>> + Send + 'a>> {
    Box::pin(write(svc, call, m))
}

/// A record as input: `validate: true` refused, in the data model, its
/// `$type` its collection, and no longer than a STAR value may be.
fn record_of(b: &Map<String, Json>, value: &Json, collection: &str) -> Result<Record, XrpcError> {
    validation_status(b)?;
    let v = from_json(value).or_else(invalid)?;
    let rec = make_record(typed(v, collection)?);
    if rec.bytes.len() > MAX_RECORD {
        return invalid(format!(
            "Record is {} bytes, more than {MAX_RECORD}",
            rec.bytes.len()
        ));
    }
    Ok(rec)
}

fn refuse_published(collection: &str) -> Result<(), XrpcError> {
    if PUBLISHED.contains(&collection) {
        return invalid(format!("{collection} is written only by the space host"));
    }
    Ok(())
}

/// What the method asks, from its input: the checks of its writes, its
/// records and its collections, in the order `spec/SPACES-REPO.md` gives.
fn asked(name: &str, b: &Map<String, Json>) -> Result<Asked, XrpcError> {
    let text = |w: &Map<String, Json>, k: &str| required(w, k).map(str::to_string);
    Ok(match name {
        "createRecord" | "putRecord" => {
            let collection = text(b, "collection")?;
            refuse_published(&collection)?;
            let record = record_of(b, &b["record"], &collection)?;
            if name == "createRecord" {
                Asked::CreateRecord(Write::Create {
                    rkey: opt(b, "rkey").map(String::from),
                    collection,
                    record,
                })
            } else {
                Asked::PutRecord(Write::Put {
                    rkey: text(b, "rkey")?,
                    collection,
                    record,
                })
            }
        }
        "deleteRecord" => {
            let collection = text(b, "collection")?;
            refuse_published(&collection)?;
            Asked::DeleteRecord {
                rkey: text(b, "rkey")?,
                collection,
            }
        }
        "applyWrites" => {
            let Some(Json::Array(given)) = b.get("writes") else {
                return invalid("Input/writes must be an array");
            };
            if given.len() > MAX_WRITES {
                return invalid(format!("Too many writes. Max: {MAX_WRITES}"));
            }
            let mut writes = Vec::with_capacity(given.len());
            for w in given {
                let Json::Object(w) = w else {
                    return invalid("invalid write");
                };
                let collection = text(w, "collection")?;
                writes.push(match opt(w, "$type") {
                    Some("com.atproto.space.applyWrites#create") => Write::Create {
                        rkey: opt(w, "rkey").map(String::from),
                        record: record_of(b, &w["value"], &collection)?,
                        collection,
                    },
                    Some("com.atproto.space.applyWrites#update") => Write::Update {
                        rkey: text(w, "rkey")?,
                        record: record_of(b, &w["value"], &collection)?,
                        collection,
                    },
                    Some("com.atproto.space.applyWrites#delete") => Write::Delete {
                        rkey: text(w, "rkey")?,
                        collection,
                    },
                    _ => return invalid("unknown write type"),
                });
            }
            for w in &writes {
                refuse_published(w.collection())?;
            }
            Asked::ApplyWrites(writes)
        }
        "clearRecords" => Asked::ClearRecords,
        _ => return internal(),
    })
}

/// A write checks, in this order, its token, the size of its body, its
/// input, its `repo`, its writes, records and collections, and then what
/// is stored: the space (one of the caller's own exists from its
/// `createSpace` here until its `deleteSpace`), the records it names, and
/// last its records' blob refs (`blobs`). A commit is in the account's log
/// before the account's lock is let go, and the write answers once it is on
/// disk and `on_commit` has heard of it; the files of the blobs it stopped
/// holding go then.
async fn write(svc: &Shared, call: &Call<'_>, m: &'static Method) -> Result<Resp, XrpcError> {
    let did = svc.auth(call.bearer).did()?;
    // The account's state, with its token's checks and before anything else
    // of the request: the public repository's writes' answers.
    crate::lifecycle::gate(svc, "com.atproto.repo.createRecord", &did)?;
    if call.body.len() > crate::limits::body_limit(call.nsid) {
        return crate::limits::too_large();
    }
    let b = crate::input(call, m)?;
    let Some(space) = SpaceRef::parse(required(&b, "space")?) else {
        return invalid("Input/space must be a valid space-ref");
    };
    if required(&b, "repo")? != did {
        return err(403, "Forbidden", "Cannot write to another account's repo");
    }
    record_scope(svc, call, &did, &space, &m.name, &b)?;
    let asked = asked(&m.name, &b)?;
    crate::limits::guard(svc, call, Some(&did), Some(&b))?;
    let status = validation_status(&b).unwrap_or(None);
    let Some(account) = svc.account(&did) else {
        return internal();
    };
    let uri = space.uri();
    let (out, shown, commit, doomed) = {
        let mut guard = crate::write(&account.store);
        let st = &mut *guard;
        st.blobs.time(svc.limits.clock.now(), svc.config.blob_ttl);
        writes_scope(st, call, &did, &space, &uri, &asked)?;
        let found = space.authority != did || st.authority.live(&uri).is_some();
        let (out, commit) = match apply(st, &did, &space, &uri, found, asked, status) {
            Ok((answer, Some(c))) => {
                let (entry, commit, effect) = staged(st, &did, &c);
                // The blobs its records reference are on disk before it is.
                st.blobs
                    .sync_before(&st.wal, c.puts.iter().flat_map(|(_, r)| cids_in(&r.value)));
                match crate::blobstore::mark_for(st).and_then(|()| append(st, &[entry])) {
                    Ok(pos) => {
                        st.spaces
                            .land(effect, pos, &mut st.disk.mem.spaces, &mut st.blobs);
                        (Ok(answer), Some(commit))
                    }
                    Err(e) => {
                        // Nothing of it reached the log: nothing of it stays.
                        crate::ops::failed_for(
                            crate::ops::Level::Error,
                            "a space write failed",
                            &did,
                            e,
                        );
                        (internal(), None)
                    }
                }
            }
            Ok((answer, None)) => (Ok(answer), None),
            Err(e) => (Err(e), None),
        };
        (
            out,
            Shown(vec![(st.wal.clone(), st.wal.written())]),
            commit,
            st.blobs.take_doomed(),
        )
    };
    // The commit is in the log: the rest must happen even if the caller goes away.
    let svc = svc.clone();
    let finish = crate::ops::spawn(async move {
        let synced = shown.durable().await;
        if let (Ok(()), Some(c)) = (&synced, commit) {
            svc.space_hooks.committed(&svc, &c);
        }
        blobs::forget(&svc, &account, doomed);
        synced
    });
    finish.await.unwrap_or_else(|_| internal())?;
    out.map(Resp::Json)
}

/// What `createRecord`, `putRecord` and `deleteRecord` need of an OAuth
/// scope, asked once the collection is checked and before the record
/// (`spec/OAUTH-SCOPES.md`, "What each method needs"): `create` or
/// `delete` of the collection; `putRecord`, `update` if the record is
/// there, else `create`.
fn record_scope(
    svc: &Service,
    call: &Call,
    did: &str,
    space: &SpaceRef,
    name: &str,
    b: &Map<String, Json>,
) -> Result<(), XrpcError> {
    if !matches!(call.bearer, crate::sessions::Bearer::OAuth(_))
        || !matches!(name, "createRecord" | "putRecord" | "deleteRecord")
    {
        return Ok(());
    }
    let collection = required(b, "collection")?;
    refuse_published(collection)?;
    let action = match name {
        "createRecord" => "create",
        "deleteRecord" => "delete",
        _ => {
            let there = opt(b, "rkey").is_some_and(|rkey| {
                svc.account(did).is_some_and(|a| {
                    read(&a.store)
                        .space_meta(&space.uri(), &format!("{collection}/{rkey}"))
                        .is_some()
                })
            });
            if there { "update" } else { "create" }
        }
    };
    crate::scopes::may_in(call.bearer, space, SpaceOp::Write { action, collection })
}

/// What `applyWrites` and `clearRecords` need of an OAuth scope, asked once
/// the input is checked and before the space is looked for
/// (`spec/OAUTH-SCOPES.md`, "What each method needs"): of each write, in
/// order, its action of its collection; of `clearRecords`, `delete` of each
/// collection the caller's repo there holds a record of, but those it
/// keeps, by name.
fn writes_scope(
    st: &Store,
    call: &Call,
    did: &str,
    space: &SpaceRef,
    uri: &str,
    asked: &Asked,
) -> Result<(), XrpcError> {
    if !matches!(call.bearer, crate::sessions::Bearer::OAuth(_)) {
        return Ok(());
    }
    let write = |action, collection| {
        crate::scopes::may_in(call.bearer, space, SpaceOp::Write { action, collection })
    };
    match asked {
        Asked::ApplyWrites(writes) => writes.iter().try_for_each(|w| {
            let action = match w {
                Write::Create { .. } | Write::Put { .. } => "create",
                Write::Update { .. } => "update",
                Write::Delete { .. } => "delete",
            };
            write(action, w.collection())
        }),
        Asked::ClearRecords => collections_held(st, uri)
            .iter()
            .filter(|c| space.authority != did || !PUBLISHED.contains(&c.as_str()))
            .try_for_each(|c| write("delete", c)),
        _ => Ok(()),
    }
}

/// The collections the repo in the space `uri` holds records of, by name,
/// each once: one record looked up for each.
fn collections_held(st: &Store, uri: &str) -> Vec<String> {
    let mut out: Vec<String> = Vec::new();
    let mut from: Vec<u8> = Vec::new();
    loop {
        let lo = if out.is_empty() {
            Unbounded
        } else {
            Included(from.as_slice())
        };
        let Some((path, _, _)) = st.space_records(uri, lo, Unbounded, false).next() else {
            return out;
        };
        let collection = path.split_once('/').map_or(path.as_str(), |(c, _)| c);
        from = after_prefix(&format!("{collection}/"));
        out.push(collection.to_string());
    }
}

/// The blob refs in the records the writes write.
fn refs_of(writes: &[Write]) -> Vec<BlobRef> {
    let mut refs = Vec::new();
    for w in writes {
        if let Write::Create { record, .. }
        | Write::Update { record, .. }
        | Write::Put { record, .. } = w
        {
            blobs::refs_in(&record.value, &mut refs);
        }
    }
    refs
}

/// Apply what a write asks to the account's repo in the space: its answer,
/// and the commit to make, if it makes one. `found` is whether the space
/// may be written, which only a write making a commit asks.
fn apply(
    st: &mut Store,
    did: &str,
    space: &SpaceRef,
    uri: &str,
    found: bool,
    asked: Asked,
    status: Option<&str>,
) -> Result<(Json, Option<Change>), XrpcError> {
    let space_found = || {
        if found {
            Ok(())
        } else {
            err(400, "SpaceNotFound", format!("Space not found: {uri}"))
        }
    };
    let held = st.spaces.get(uri);
    match asked {
        Asked::CreateRecord(w) | Asked::PutRecord(w) => {
            space_found()?;
            let writes = vec![w];
            let refs = refs_of(&writes);
            let (mut results, c) = stage(st, did, uri, writes, status)?;
            st.blobs.check(&refs)?;
            let mut answer = results.pop().unwrap_or_default();
            if let Some(a) = answer.as_object_mut() {
                a.remove("$type");
            }
            Ok((answer, Some(c)))
        }
        Asked::DeleteRecord { collection, rkey } => {
            if held.is_none()
                || st
                    .space_meta(uri, &format!("{collection}/{rkey}"))
                    .is_none()
            {
                return Ok((json!({}), None));
            }
            space_found()?;
            let (_, c) = stage(
                st,
                did,
                uri,
                vec![Write::Delete { collection, rkey }],
                status,
            )?;
            Ok((json!({}), Some(c)))
        }
        Asked::ApplyWrites(writes) if writes.is_empty() => Ok((json!({ "results": [] }), None)),
        Asked::ApplyWrites(writes) => {
            space_found()?;
            let refs = refs_of(&writes);
            let (results, c) = stage(st, did, uri, writes, status)?;
            st.blobs.check(&refs)?;
            Ok((json!({ "results": results }), Some(c)))
        }
        Asked::ClearRecords => {
            // In the authority's own repo, the published records are kept:
            // every other record goes, named by none.
            let kept: Vec<String> = if space.authority == did {
                PUBLISHED.iter().map(|c| format!("{c}/")).collect()
            } else {
                vec![]
            };
            let Some(repo) = held else {
                return Ok((json!({}), None));
            };
            let staying: usize = kept
                .iter()
                .map(|p| {
                    let (lo, hi) = (p.as_bytes(), after_prefix(p));
                    st.space_records(uri, Included(lo), Excluded(&hi), false)
                        .count()
                })
                .sum();
            if repo.records <= staying as u64 {
                return Ok((json!({}), None));
            }
            space_found()?;
            let rev = next_rev(&mut st.spaces, uri);
            Ok((
                json!({}),
                Some(Change {
                    space: uri.into(),
                    rev,
                    ops: vec![],
                    puts: vec![],
                    dels: vec![],
                    clear: true,
                    kept: Some(kept),
                }),
            ))
        }
    }
}

/// The rev of the repo's next commit: the TID of now, or one after its last.
fn next_rev(spaces: &mut Spaces, uri: &str) -> String {
    match spaces.repos.get_mut(uri) {
        Some(r) => r.tids.next_tid(),
        None => Tids::new().next_tid(),
    }
}

/// Make the writes, in order, each seeing those before it, as one commit:
/// each one's result as `applyWrites` answers it, and the commit. A create
/// of a record that exists, or an update or delete of one that does not,
/// refuses them all.
fn stage(
    st: &mut Store,
    did: &str,
    uri: &str,
    writes: Vec<Write>,
    status: Option<&str>,
) -> Result<(Vec<Json>, Change), XrpcError> {
    // Each path written, and the record it holds after the writes so far.
    let mut written: BTreeMap<String, Option<Record>> = BTreeMap::new();
    let mut ops = Vec::with_capacity(writes.len());
    let mut results = Vec::with_capacity(writes.len());
    for w in writes {
        let held = st.spaces.get(uri).is_some();
        let view = st.disk.spaces(&st.ctx.blocks);
        let now = |path: &str| match written.get(path) {
            Some(r) => r.as_ref().map(|r| r.cid.clone()),
            None if !held => None,
            None => view
                .record(uri, path)
                .unwrap_or_else(|e| st.disk.fail(e))
                .map(|(meta, _)| meta.cid),
        };
        let record_uri = |collection: &str, rkey: &str| format!("{uri}/{did}/{collection}/{rkey}");
        let missing = |path: &str| {
            err(
                400,
                "RecordNotFound",
                format!("Could not find record: {uri}/{did}/{path}"),
            )
        };
        let (path, record, prev, result) = match w {
            Write::Create {
                collection,
                rkey,
                record,
            } => {
                let rkey = rkey.unwrap_or_else(|| st.repo.tids.next_tid());
                let path = format!("{collection}/{rkey}");
                if now(&path).is_some() {
                    return err(
                        400,
                        "RecordAlreadyExists",
                        format!("Record already exists: {}", record_uri(&collection, &rkey)),
                    );
                }
                let r = json!({ "$type": "com.atproto.space.applyWrites#createResult", "uri": record_uri(&collection, &rkey), "cid": cid_string(&record.cid) });
                (path, Some(record), None, with_status(r, status))
            }
            Write::Update {
                collection,
                rkey,
                record,
            } => {
                let path = format!("{collection}/{rkey}");
                let Some(prev) = now(&path) else {
                    return missing(&path);
                };
                let r = json!({ "$type": "com.atproto.space.applyWrites#updateResult", "uri": record_uri(&collection, &rkey), "cid": cid_string(&record.cid) });
                (path, Some(record), Some(prev), with_status(r, status))
            }
            Write::Put {
                collection,
                rkey,
                record,
            } => {
                let path = format!("{collection}/{rkey}");
                let prev = now(&path);
                let r = json!({ "uri": record_uri(&collection, &rkey), "cid": cid_string(&record.cid) });
                (path, Some(record), prev, with_status(r, status))
            }
            Write::Delete { collection, rkey } => {
                let path = format!("{collection}/{rkey}");
                let Some(prev) = now(&path) else {
                    return missing(&path);
                };
                (
                    path,
                    None,
                    Some(prev),
                    json!({ "$type": "com.atproto.space.applyWrites#deleteResult" }),
                )
            }
        };
        ops.push(Op {
            rev: String::new(),
            index: ops.len(),
            cid: record.as_ref().map(|r| r.cid.clone()),
            prev,
            path: path.clone(),
        });
        results.push(result);
        written.insert(path, record);
    }
    let rev = next_rev(&mut st.spaces, uri);
    for o in &mut ops {
        o.rev.clone_from(&rev);
    }
    let (mut puts, mut dels) = (Vec::new(), Vec::new());
    for (path, r) in written {
        match r {
            Some(r) => puts.push((path, r)),
            None => dels.push(path),
        }
    }
    Ok((
        results,
        Change {
            space: uri.into(),
            rev,
            ops,
            puts,
            dels,
            clear: false,
            kept: None,
        },
    ))
}

// ---- Reads ----------------------------------------------------------------

/// A read of one account's repo in a space, once the caller may read it,
/// with the MAC its `Accept-Signature` asks for, if any.
type ReadFn = fn(
    &Service,
    &Account,
    Option<&mac::Request>,
    &mut Shown,
    &Map<String, Json>,
) -> Result<Resp, XrpcError>;

/// The profile of the MAC a read answers, if it answers one: a credential's
/// read of it must ask that MAC (`spec/SPACES-EXPORT.md`, "Who may read").
fn profile_of(name: &str) -> Option<Profile> {
    match name {
        "getRecord" => Some(Profile::Record),
        "getLatestCommit" | "listRepoOps" | "getRepo" => Some(Profile::Commit),
        _ => None,
    }
}

/// A read checks its input, then who calls: with a space credential
/// (`space_credentials`), its audience the repo's DID, any account's repo
/// here in the credential's space; with a token, the caller's own, whose
/// DID its `repo` must be. Then, of a read answering a MAC, its
/// `Accept-Signature`, which a credential's read must ask a MAC with. It
/// answers once what it read is on disk.
async fn read_call(
    s: &Shared,
    call: &Call<'_>,
    m: &'static Method,
    f: ReadFn,
) -> Result<Resp, XrpcError> {
    let p = m
        .parse_params(call.params.iter().map(|(k, v)| (k.as_str(), v.as_str())))
        .or_else(|e| invalid(e.0))?;
    let repo = required(&p, "repo")?;
    let not_found = || err(400, "RepoNotFound", format!("Could not find repo: {repo}"));
    let profile = profile_of(&m.name);
    let credential = presents_credential(call.headers);
    let a: Arc<Account> = if credential {
        let credential = verify_space_credential(s, call, repo).await?;
        if credential.space != required(&p, "space")? {
            return err(
                400,
                "InvalidCredential",
                "The credential is for another space",
            );
        }
        let a = s.account(repo).map_or_else(not_found, Ok)?;
        // `spec/SPACES-EXPORT.md`, "Takedown and deactivation".
        match crate::space_authority::status(&a) {
            crate::space_authority::Status::TakenDown => {
                return err(
                    400,
                    "RepoTakendown",
                    format!("Repo has been takendown: {repo}"),
                );
            }
            crate::space_authority::Status::Deactivated => {
                return err(
                    400,
                    "RepoDeactivated",
                    format!("Repo has been deactivated: {repo}"),
                );
            }
            crate::space_authority::Status::Active => {}
        }
        a
    } else {
        // A taken-down account's `allowTakendown` session reads its repo and blobs list.
        let did = match crate::sessions::takendown_ok_token(s, call.bearer) {
            Ok(t)
                if t.scope == crate::sessions::TAKENDOWN
                    && matches!(m.name.as_str(), "getRepo" | "listBlobs") =>
            {
                t.did
            }
            _ => s.auth(call.bearer).did()?,
        };
        if repo != did {
            return err(400, "RepoNotFound", format!("Could not find repo: {repo}"));
        }
        // `read_self` of the space, once the repo is the caller's own
        // (`spec/OAUTH-SCOPES.md`, "What each method needs").
        if let Some(sr) = SpaceRef::parse(required(&p, "space")?) {
            crate::scopes::may_in(call.bearer, &sr, SpaceOp::Read { whole: false })?;
        }
        s.account(&did).map_or_else(internal, Ok)?
    };
    let asked = match profile {
        None => None,
        Some(profile) => {
            let asked = asked_mac(call, profile)?;
            if credential && asked.is_none() {
                return err(
                    400,
                    "InvalidSpaceMac",
                    format!(
                        "A space credential's read must ask for a MAC of {} with Accept-Signature",
                        profile.as_str()
                    ),
                );
            }
            asked
        }
    };
    let mut shown = Shown::default();
    let out = f(s, &a, asked.as_ref(), &mut shown, &p);
    // A read changes nothing, so it pays once it has run.
    if !out.as_ref().is_err_and(crate::token_error) {
        crate::limits::charge(s, call, None, None)?;
    }
    shown.durable().await?;
    out
}

/// The MAC a request's `Accept-Signature` asks for of `profile`, read as
/// `spec/SPACES.md` ("MACs") reads it: None where it asks none; `400
/// InvalidSpaceMac` where it is refused. Its lines are one Dictionary, as
/// RFC 9651 joins them.
fn asked_mac(call: &Call, profile: Profile) -> Result<Option<mac::Request>, XrpcError> {
    fn bad<T>(why: impl std::fmt::Display) -> Result<T, XrpcError> {
        err(
            400,
            "InvalidSpaceMac",
            format!("Invalid Accept-Signature: {why}"),
        )
    }
    let lines = call
        .headers
        .get_all(ACCEPT_SIGNATURE)
        .iter()
        .map(|v| v.to_str())
        .collect::<Result<Vec<_>, _>>()
        .or_else(bad)?;
    let header = (!lines.is_empty()).then(|| lines.join(", "));
    mac::read_accept_signature(header.as_deref(), profile).or_else(bad)
}

/// The secret the account's KEM key and a key share make.
fn secret(a: &Account, asked: &mac::Request) -> Result<SharedSecret, XrpcError> {
    a.kem
        .as_ref()
        .map_or_else(internal, |k| Ok(k.shared_secret(&asked.key_share)))
}

/// The MAC of a commit, if one is asked.
fn commit_mac(
    a: &Account,
    asked: Option<&mac::Request>,
    c: &Commit,
) -> Result<Option<MacHeaders>, XrpcError> {
    asked
        .map(|r| Ok(MacHeaders::commit(r, &secret(a, r)?, c)))
        .transpose()
}

/// The headers of a `200` of a method taking `Accept-Signature`: `Vary`,
/// and with its MAC, the MAC's three headers and
/// `Access-Control-Expose-Headers` naming them.
fn mac_headers(mac: Option<MacHeaders>) -> Vec<(&'static str, String)> {
    let mut headers = vec![("vary", "Accept-Signature".to_string())];
    if let Some(m) = mac {
        let named: Vec<&str> = m.headers().iter().map(|(n, _)| *n).collect();
        headers.push(("access-control-expose-headers", named.join(", ")));
        headers.extend(m.headers().map(|(n, v)| (n, v.to_string())));
    }
    headers
}

/// A JSON answer of a method taking `Accept-Signature`, with its MAC if it has one.
fn with_mac(answer: Json, mac: Option<MacHeaders>) -> Resp {
    Resp::Headed(answer, mac_headers(mac))
}

/// A cursor `listRecords` or `listRepoOps` takes: every one they answer
/// has a `/`, and one without is `400 InvalidCursor`.
fn cursor_of(p: &Map<String, Json>) -> Result<Option<&str>, XrpcError> {
    match opt(p, "cursor") {
        Some(c) if !c.contains('/') => bad_cursor(),
        c => Ok(c),
    }
}

fn bad_cursor<T>() -> Result<T, XrpcError> {
    err(400, "InvalidCursor", "Malformed cursor")
}

fn limit(p: &Map<String, Json>, default: usize) -> usize {
    p.get("limit")
        .and_then(Json::as_u64)
        .map_or(default, |l| l as usize)
}

fn flag(p: &Map<String, Json>, name: &str) -> bool {
    p.get(name) == Some(&Json::Bool(true))
}

fn get_record(
    _: &Service,
    a: &Account,
    asked: Option<&mac::Request>,
    shown: &mut Shown,
    p: &Map<String, Json>,
) -> Result<Resp, XrpcError> {
    let (space, collection, rkey) = (
        required(p, "space")?,
        required(p, "collection")?,
        required(p, "rkey")?,
    );
    let path = format!("{collection}/{rkey}");
    let uri = format!("{space}/{}/{path}", a.did);
    let found = with_space_repo(a, shown, space, |st, r| {
        r?;
        let (meta, pos) = st.space_meta(space, &path)?;
        let value = st.space_json(space, &path, &meta, pos);
        Some((meta.cid, value))
    });
    let Some((cid, value)) = found else {
        return err(
            400,
            "RecordNotFound",
            format!("Could not locate record: {uri}"),
        );
    };
    let mac = asked
        .map(|r| {
            Ok::<_, XrpcError>(MacHeaders::record(
                r,
                &secret(a, r)?,
                &uri,
                &cid_string(&cid),
            ))
        })
        .transpose()?;
    Ok(with_mac(
        json!({ "uri": uri, "cid": cid_string(&cid), "value": value }),
        mac,
    ))
}

fn get_latest_commit(
    _: &Service,
    a: &Account,
    asked: Option<&mac::Request>,
    shown: &mut Shown,
    p: &Map<String, Json>,
) -> Result<Resp, XrpcError> {
    let space = required(p, "space")?;
    let head = with_space_repo(a, shown, space, |_, r| r.map(|r| r.commit(&a.did, space)));
    let Some(c) = head else {
        return err(
            400,
            "RepoNotFound",
            format!("Could not find repo for {} in {space}", a.did),
        );
    };
    let mac = commit_mac(a, asked, &c)?;
    Ok(with_mac(json!({ "commit": to_json(&c.to_value()) }), mac))
}

/// A page of the records, in descending order of the bytes of
/// `{collection}/{rkey}`, whatever `reverse` says, after the cursor, the
/// last path of the page before. The page is read from where it begins, no
/// more than it holds.
fn list_records(
    _: &Service,
    a: &Account,
    _: Option<&mac::Request>,
    shown: &mut Shown,
    p: &Map<String, Json>,
) -> Result<Resp, XrpcError> {
    let (space, limit, exclude, cursor) = (
        required(p, "space")?,
        limit(p, 50),
        flag(p, "excludeValues"),
        cursor_of(p)?,
    );
    // Every path of the collection is at least `{collection}/` and less than
    // `{collection}0`, as '0' follows '/'.
    let (lo, mut hi): (Bound<String>, Bound<String>) = match opt(p, "collection") {
        Some(c) => (Included(format!("{c}/")), Excluded(format!("{c}0"))),
        None => (Unbounded, Unbounded),
    };
    // A cursor is a record URI of this space and repo, as getRecord answers
    // one, the position of its `{collection}/{rkey}` whether or not that
    // record exists: a client builds one to start below a key of its choosing.
    let under = format!("{space}/{}/", a.did);
    let cursor = match cursor {
        Some(c) => Some(
            c.strip_prefix(under.as_str())
                .filter(|c| c.contains('/'))
                .map_or_else(bad_cursor, Ok)?,
        ),
        None => None,
    };
    if let Some(c) = cursor
        && !matches!(&hi, Excluded(h) if c > h.as_str())
    {
        hi = Excluded(c.to_string());
    }
    let empty = match (&lo, &hi) {
        (Included(l) | Excluded(l), Excluded(h)) => l >= h,
        _ => false,
    };
    fn bytes(b: &Bound<String>) -> Bound<&[u8]> {
        match b {
            Included(x) => Included(x.as_bytes()),
            Excluded(x) => Excluded(x.as_bytes()),
            Unbounded => Unbounded,
        }
    }
    let records: Vec<(String, Json)> = with_space_repo(a, shown, space, |st, r| {
        if r.is_none() || empty {
            return vec![];
        }
        st.space_records(space, bytes(&lo), bytes(&hi), true)
            .take(limit)
            .map(|(path, meta, pos)| {
                let (collection, rkey) = path.split_once('/').unwrap_or((&path, ""));
                let mut j =
                    json!({ "collection": collection, "rkey": rkey, "cid": cid_string(&meta.cid) });
                if !exclude {
                    j["value"] = st.space_json(space, &path, &meta, pos);
                }
                (path, j)
            })
            .collect()
    });
    let mut out = json!({ "records": records.iter().map(|(_, j)| j).collect::<Vec<_>>() });
    if records.len() == limit
        && let Some((path, _)) = records.last()
    {
        out["cursor"] = json!(format!("{under}{path}"));
    }
    Ok(Resp::Json(out))
}

/// An operation's position, as a cursor: `{rev}/{index}`.
fn op_cursor(o: &Op) -> String {
    format!("{}/{}", o.rev, o.index)
}

fn parse_op_cursor(c: &str) -> Option<(&str, usize)> {
    let (rev, index) = c.split_once('/')?;
    valid_tid(rev).then_some(())?;
    Some((rev, index.parse().ok()?))
}

/// The operation log, in order, after `since` and the cursor, with the
/// repo's commit on every page: a full page has a cursor too. The page is
/// read from where it begins, no more than it holds.
fn list_repo_ops(
    _: &Service,
    a: &Account,
    asked: Option<&mac::Request>,
    shown: &mut Shown,
    p: &Map<String, Json>,
) -> Result<Resp, XrpcError> {
    let (space, limit, exclude) = (
        required(p, "space")?,
        limit(p, 100),
        flag(p, "excludeValues"),
    );
    // A cursor with a `/` this server did not answer is refused too.
    let cursor = match cursor_of(p)? {
        None => None,
        Some(c) => Some(parse_op_cursor(c).map_or_else(bad_cursor, Ok)?),
    };
    let page = with_space_repo(a, shown, space, |st, r| {
        let r = r?;
        let ops = st.space_ops(space, opt(p, "since"), cursor, limit);
        let json: Vec<Json> = ops
            .iter()
            .map(|o| {
                let (collection, rkey) = o.path.split_once('/').unwrap_or((&o.path, ""));
                let mut j = json!({ "rev": o.rev, "collection": collection, "rkey": rkey, "cid": cid_text(&o.cid), "prev": cid_text(&o.prev) });
                // The value the operation left, if the record holds it still.
                let now = (!exclude && o.cid.is_some())
                    .then(|| st.space_meta(space, &o.path))
                    .flatten()
                    .filter(|(meta, _)| o.cid.as_ref() == Some(&meta.cid));
                if let Some((meta, pos)) = now {
                    j["value"] = st.space_json(space, &o.path, &meta, pos);
                }
                j
            })
            .collect();
        let cursor = (ops.len() == limit).then(|| ops.last().map(op_cursor).unwrap_or_default());
        Some((json, cursor, r.commit(&a.did, space)))
    });
    let Some((ops, cursor, c)) = page else {
        return err(
            400,
            "RepoNotFound",
            format!("Could not find repo for {} in {space}", a.did),
        );
    };
    let mac = commit_mac(a, asked, &c)?;
    let mut out = json!({ "ops": ops, "commit": to_json(&c.to_value()) });
    if let Some(cursor) = cursor {
        out["cursor"] = json!(cursor);
    }
    Ok(with_mac(out, mac))
}

/// The spaces the caller has a repo in, and those it created here and has
/// not deleted (`space_authority`), each once, by the bytes of their URIs:
/// each with its repo's commit, and of a space of its own, its `spaceRev`.
fn list_spaces(
    s: &Service,
    call: &Call,
    shown: &mut Shown,
    p: &Map<String, Json>,
) -> Result<Resp, XrpcError> {
    // A taken-down account's `allowTakendown` session lists its spaces (`spec/SPACES-EXPORT.md`).
    let did = match crate::sessions::takendown_ok_token(s, call.bearer) {
        Ok(t) if t.scope == crate::sessions::TAKENDOWN => t.did,
        _ => s.auth(call.bearer).did()?,
    };
    // `read_self` of the spaces it may list (`spec/OAUTH-SCOPES.md`, "What
    // each method needs").
    crate::scopes::may_space(
        call.bearer,
        opt(p, "spaceDid").unwrap_or("*"),
        opt(p, "spaceType").unwrap_or("*"),
        "*",
        SpaceOp::Read { whole: false },
    )?;
    let Some(a) = s.account(&did) else {
        return internal();
    };
    let (typ, authority, limit) = (opt(p, "spaceType"), opt(p, "spaceDid"), limit(p, 50));
    let from: Bound<String> = match opt(p, "cursor") {
        Some(c) if !c.contains('/') => return bad_cursor(),
        Some(c) => Excluded(c.to_string()),
        None => Unbounded,
    };
    let st = read(&a.store);
    shown.0.push((st.wal.clone(), st.wal.written()));
    let written = st
        .spaces
        .repos
        .range::<String, _>((from.clone(), Unbounded))
        .map(|(uri, _)| uri.as_str());
    let all: BTreeSet<&str> = written
        .chain(st.authority.live_spaces((from, Unbounded)))
        .collect();
    let spaces: Vec<Json> = all
        .into_iter()
        .filter(|uri| {
            SpaceRef::parse(uri).is_some_and(|r| {
                typ.is_none_or(|t| r.typ == t) && authority.is_none_or(|d| r.authority == d)
            })
        })
        .take(limit)
        .map(|uri| {
            let mut j = json!({ "space": uri });
            if let Some(r) = st.spaces.get(uri).filter(|r| !r.rev.is_empty()) {
                j["repoRev"] = json!(r.rev);
                j["data"] = to_json(&V::Bytes(r.data.to_vec()));
            }
            // The latest change to the writer set of a space of its own.
            let space_rev = st
                .authority
                .live(uri)
                .and_then(|s| s.writers.values().map(|w| &w.space_rev).max());
            if let Some(rev) = space_rev {
                j["spaceRev"] = json!(rev);
            }
            j
        })
        .collect();
    let mut out = json!({ "spaces": spaces });
    if spaces.len() == limit {
        out["cursor"] = spaces[limit - 1]["space"].clone();
    }
    Ok(Resp::Json(out))
}

// ---- The repo whole, its blobs, and imports (`spec/SPACES-EXPORT.md`) ----

/// A space repo as a STAR archive of the profile `atproto-space-repo`,
/// read from its store's files as it is sent: its commit, then each record,
/// in ascending order of the bytes of its path.
pub(crate) struct Archive {
    /// The archive up to its first record: the magic bytes and the commit.
    head: Vec<u8>,
    snapshot: SpaceSnapshot,
    ctx: Arc<Ctx>,
}

impl Archive {
    fn of(commit: &Commit, snapshot: SpaceSnapshot, ctx: Arc<Ctx>) -> Archive {
        // The archive of no records, less the byte that ends it.
        let mut head = star::write_sorted_repo(commit, std::iter::empty());
        head.pop();
        Archive {
            head,
            snapshot,
            ctx,
        }
    }

    /// Give `send` the archive in chunks of about `sync::CHUNK` bytes, as
    /// it is read; stop when it says to. Each record is a byte of `1`, then
    /// its path and its bytes, each after its length; a byte of `0` ends it.
    fn run(self, mut send: impl FnMut(Bytes) -> bool) -> io::Result<()> {
        use crate::sync::{CHUNK, varint};
        let Archive {
            head: mut buf,
            snapshot,
            ctx,
        } = self;
        let mut open = true;
        snapshot.run(&ctx.blocks, |path, bytes| {
            buf.push(1);
            varint(&mut buf, path.len());
            buf.extend_from_slice(path);
            varint(&mut buf, bytes.len());
            buf.extend_from_slice(bytes);
            if buf.len() >= CHUNK {
                open = send(Bytes::from(std::mem::take(&mut buf)));
            }
            open
        })?;
        if open {
            buf.push(0);
            send(Bytes::from(buf));
        }
        Ok(())
    }

    /// The archive whole, read now.
    #[cfg(test)]
    pub(crate) fn bytes(self) -> io::Result<Vec<u8>> {
        let mut out = Vec::new();
        self.run(|b| {
            out.extend_from_slice(&b);
            true
        })?;
        Ok(out)
    }

    /// The answer: the archive sent as it is read, a few chunks ahead of
    /// the reader at most.
    pub(crate) fn response(self) -> Response {
        let (tx, chunks) = tokio::sync::mpsc::channel(4);
        tokio::task::spawn_blocking(move || {
            let failed = tx.clone();
            if let Err(e) = self.run(|b| tx.blocking_send(Ok(b)).is_ok()) {
                crate::ops::failed("getRepo of a space failed", &e);
                let _ = failed.blocking_send(Err(e));
            }
        });
        (
            StatusCode::OK,
            [(header::CONTENT_TYPE, crate::STAR_TYPE)],
            Body::new(crate::sync::Chunks(chunks)),
        )
            .into_response()
    }
}

/// The repo whole: the STAR archive of its commit and its records, in
/// ascending order of the bytes of their paths, with the commit's MAC if one
/// is asked; read as it is sent (`Archive`).
fn get_repo(
    _: &Service,
    a: &Account,
    asked: Option<&mac::Request>,
    shown: &mut Shown,
    p: &Map<String, Json>,
) -> Result<Resp, XrpcError> {
    let space = required(p, "space")?;
    let whole = with_space_repo(a, shown, space, |st, r| {
        r.map(|r| {
            let c = r.commit(&a.did, space);
            (c, st.disk.space_snapshot(space), st.ctx.clone())
        })
    });
    let Some((c, snapshot, ctx)) = whole else {
        return err(
            400,
            "RepoNotFound",
            format!("Could not find repo for {} in {space}", a.did),
        );
    };
    let snapshot = match snapshot {
        Ok(s) => s,
        Err(e) => {
            crate::ops::failed_for(
                crate::ops::Level::Error,
                "getRepo of a space failed",
                &a.did,
                e,
            );
            return internal();
        }
    };
    let mac = commit_mac(a, asked, &c)?;
    Ok(Resp::Archive(
        Archive::of(&c, snapshot, ctx),
        mac_headers(mac),
    ))
}

/// A blob the repo's records reference, if the account holds its bytes.
fn get_blob(
    s: &Service,
    a: &Account,
    _: Option<&mac::Request>,
    shown: &mut Shown,
    p: &Map<String, Json>,
) -> Result<Resp, XrpcError> {
    let (space, cid) = (required(p, "space")?, required(p, "cid")?);
    let st = read(&a.store);
    shown.0.push((st.wal.clone(), st.wal.written()));
    let referenced = st.spaces.get(space).is_some()
        && st
            .space_view()
            .refers(space, cid)
            .unwrap_or_else(|e| st.disk.fail(e));
    if !referenced {
        return err(400, "BlobNotFound", format!("Blob not found: {cid}"));
    }
    st.blobs.serve_space(s, &a.did, cid)
}

/// The CIDs the repo's records reference, each once, in ascending order,
/// after the cursor; a `since` is ignored. A full page has a cursor, its
/// last CID.
fn list_blobs(
    _: &Service,
    a: &Account,
    _: Option<&mac::Request>,
    shown: &mut Shown,
    p: &Map<String, Json>,
) -> Result<Resp, XrpcError> {
    let (space, limit, cursor) = (required(p, "space")?, limit(p, 500), opt(p, "cursor"));
    let cids: Vec<String> = with_space_repo(a, shown, space, |st, r| match r {
        Some(_) => st.space_blobs(space, cursor, limit),
        None => vec![],
    });
    let mut out = json!({ "cids": cids });
    if cids.len() == limit {
        out["cursor"] = json!(cids.last());
    }
    Ok(Resp::Json(out))
}

/// `importRepo` checks, in this order, its token (a session of the
/// account's password), its `Content-Type`, the size of its body, then pays
/// its rate limits and checks the free space (`limits::guard`), and reads
/// the archive (`InvalidRepoFile`), its commit's `repo` (`RepoMismatch`),
/// the space, and last each record's encoding. The caller's repo in that
/// space then becomes the archive's, with a commit of its own, in one frame;
/// answered once that is on disk, with no `on_commit`. The files of the
/// blobs it stopped holding go then.
async fn import_repo(svc: &Shared, call: &Call<'_>) -> Result<Resp, XrpcError> {
    use crate::space_authority::{Kind, caller};
    let a = caller(svc, call, Kind::Import)?;
    let media = call
        .headers
        .get(axum::http::header::CONTENT_TYPE)
        .and_then(|v| v.to_str().ok())
        .map(|t| t.split(';').next().unwrap_or_default().trim());
    if !media.is_some_and(|t| t.eq_ignore_ascii_case(crate::STAR_TYPE)) {
        return invalid(format!(
            "Wrong request encoding (Content-Type): expected {}",
            crate::STAR_TYPE
        ));
    }
    if call.body.len() > crate::limits::archive_limit(svc) {
        return err(413, "PayloadTooLarge", "request entity too large");
    }
    crate::limits::guard(svc, call, Some(&a.did), None)?;
    fn bad<T>(why: String) -> Result<T, XrpcError> {
        err(400, "InvalidRepoFile", why)
    }
    let archive = star::read_any_repo(call.body)
        .or_else(|why| bad(format!("An archive that does not read: {why}")))?;
    let commit = archive.commit;
    if !pds_repo::data::valid_did(&commit.repo) {
        return bad("An archive whose repo is not a DID".into());
    }
    let Some(space) = SpaceRef::parse(&commit.space) else {
        return bad("An archive whose space is not a space-ref".into());
    };
    if !valid_tid(&commit.rev) {
        return bad("An archive whose rev is not a TID".into());
    }
    let mut values = Vec::with_capacity(archive.records.len());
    for (path, bytes) in &archive.records {
        match decode(bytes) {
            Ok(v @ V::Map(_)) => values.push(v),
            _ => return bad(format!("An archive whose record {path} is not a DRISL map")),
        }
    }
    if commit.repo != a.did {
        return err(
            400,
            "RepoMismatch",
            "The archive is of another account's repo",
        );
    }
    // `create` of each collection its records name, in the order first
    // named (`spec/OAUTH-SCOPES.md`, "What each method needs").
    let mut named: Vec<&str> = Vec::new();
    for (path, _) in &archive.records {
        let collection = path.split_once('/').map_or(path.as_str(), |(c, _)| c);
        if !named.contains(&collection) {
            crate::scopes::may_in(
                call.bearer,
                &space,
                SpaceOp::Write {
                    action: "create",
                    collection,
                },
            )?;
            named.push(collection);
        }
    }
    let uri = space.uri();
    if space.authority == a.did && read(&a.store).authority.live(&uri).is_none() {
        return err(400, "SpaceNotFound", format!("Space not found: {uri}"));
    }
    let mut records = Vec::with_capacity(archive.records.len());
    for ((path, bytes), value) in archive.records.into_iter().zip(values) {
        if star::canonical(&bytes).is_err() {
            return bad(format!(
                "An archive whose record {path} is not in its canonical encoding"
            ));
        }
        records.push((
            path,
            Record {
                cid: pds_repo::data::cid_of(0x71, &bytes),
                bytes,
                value,
            },
        ));
    }
    let (shown, doomed) = {
        let mut guard = crate::write(&a.store);
        let st = &mut *guard;
        if space.authority == a.did && st.authority.live(&uri).is_none() {
            return err(400, "SpaceNotFound", format!("Space not found: {uri}"));
        }
        let rev = next_rev(&mut st.spaces, &uri);
        let import = Import {
            space: uri,
            rev,
            records,
        };
        let effect = st
            .spaces
            .import(&import, st.space_view())
            .unwrap_or_else(|e| st.disk.fail(e));
        st.blobs.sync_before(
            &st.wal,
            import.records.iter().flat_map(|(_, r)| cids_in(&r.value)),
        );
        match crate::blobstore::mark_for(st)
            .and_then(|()| append(st, &[import.entry(&commit.data)]))
        {
            Ok(pos) => st
                .spaces
                .land(effect, pos, &mut st.disk.mem.spaces, &mut st.blobs),
            Err(e) => {
                // Nothing of it reached the log: nothing of it stays.
                crate::ops::failed_for(
                    crate::ops::Level::Error,
                    "logging a space repo import failed",
                    &a.did,
                    e,
                );
                return internal();
            }
        }
        (
            Shown(vec![(st.wal.clone(), st.wal.written())]),
            st.blobs.take_doomed(),
        )
    };
    // The import is in the log: the rest must happen even if the caller goes away.
    let svc = svc.clone();
    let finish = crate::ops::spawn(async move {
        let synced = shown.durable().await;
        blobs::forget(&svc, &a, doomed);
        synced
    });
    finish.await.unwrap_or_else(|_| internal())?;
    Ok(Resp::Nothing)
}

#[cfg(test)]
pub(crate) mod tests {
    use super::*;
    use crate::testing::*;
    use axum::http::{HeaderMap, HeaderName, HeaderValue, Method as Http};
    use base64::Engine;
    use base64::engine::general_purpose::STANDARD_NO_PAD;
    use pds_space::KemKey;
    use std::sync::Mutex;

    /// A space of an authority no account here has.
    pub const SPACE: &str = "at://did:plc:ewvi7nxzyoun6zhxrhs64oiz/space/com.example.forum/main";
    const OTHER: &str = "at://did:web:example.com/space/com.example.chat/room";

    /// A call as sent: its token, its parameters, its body and its headers;
    /// the status, the JSON (`{error}` for an error) and the headers answered.
    pub async fn send(
        s: &Shared,
        nsid: &str,
        token: Option<&str>,
        params: &[(&str, &str)],
        body: &str,
        headers: &[(&str, &str)],
    ) -> (u16, Json, Vec<(&'static str, String)>) {
        let m = pds_lexicon::method(nsid).unwrap();
        let method = if m.kind == pds_lexicon::Kind::Query {
            Http::GET
        } else {
            Http::POST
        };
        let mut h = HeaderMap::new();
        for (k, v) in headers {
            h.append(
                HeaderName::from_bytes(k.as_bytes()).unwrap(),
                HeaderValue::from_str(v).unwrap(),
            );
        }
        let params: Vec<(String, String)> = params
            .iter()
            .map(|(k, v)| (k.to_string(), v.to_string()))
            .collect();
        let bearer = token.map_or(
            crate::sessions::Bearer::None,
            crate::sessions::Bearer::Token,
        );
        match crate::answer(
            s,
            &Call {
                nsid,
                method: &method,
                params: &params,
                body: body.as_bytes(),
                bearer,
                headers: &h,
                client: "127.0.0.1".into(),
                charged: Default::default(),
                http: None,
            },
        )
        .await
        {
            Ok(Resp::Json(j)) => (200, j, vec![]),
            Ok(Resp::Headed(j, hs)) => (200, j, hs),
            Ok(_) => panic!("{nsid} answered no JSON"),
            Err(e) => (e.status, json!({ "error": e.name }), vec![]),
        }
    }

    /// A write, `com.atproto.space.<name>`, and its notification's send
    /// settled: nothing of it reaches the account's log once the write is
    /// answered, as after a restart the server before would be writing to
    /// a log the one after reads.
    pub async fn w(s: &Shared, name: &str, token: &str, body: Json) -> Result<Json, String> {
        let got = call(s, &format!("com.atproto.space.{name}"), Some(token), body).await;
        crate::space_notify::tests::idle(s).await;
        got
    }

    /// A read, `com.atproto.space.<name>`.
    pub async fn r(
        s: &Shared,
        name: &str,
        token: &str,
        params: &[(&str, &str)],
    ) -> Result<Json, String> {
        let (status, j, _) = send(
            s,
            &format!("com.atproto.space.{name}"),
            Some(token),
            params,
            "",
            &[],
        )
        .await;
        if status == 200 {
            Ok(j)
        } else {
            Err(j["error"].as_str().unwrap().to_string())
        }
    }

    /// The CID a record gets, as the harness computes it.
    fn cid_of(record: &Json) -> String {
        cid_string(&make_record(from_json(record).unwrap()).cid)
    }

    /// The `data` of these `(path, cid)` records, as `pds-space` sums them.
    fn data_of<'a>(records: impl IntoIterator<Item = (&'a str, &'a str)>) -> Json {
        let mut h = LtHash::new();
        for (path, cid) in records {
            h.add(&element(path, cid));
        }
        json!({ "$bytes": STANDARD_NO_PAD.encode(h.digest()) })
    }

    fn commit_rev(c: &Json) -> String {
        c["commit"]["rev"].as_str().unwrap().to_string()
    }

    async fn latest(s: &Shared, token: &str, did: &str, space: &str) -> Json {
        r(
            s,
            "getLatestCommit",
            token,
            &[("space", space), ("repo", did)],
        )
        .await
        .unwrap()
    }

    /// Every operation of the repo's log, page by page with the cursors answered.
    async fn all_ops(
        s: &Shared,
        token: &str,
        did: &str,
        space: &str,
        limit: &str,
    ) -> (Vec<Json>, Json) {
        let mut ops = Vec::new();
        let mut cursor: Option<String> = None;
        loop {
            let mut p = vec![("space", space), ("repo", did), ("limit", limit)];
            if let Some(c) = &cursor {
                p.push(("cursor", c));
            }
            let page = r(s, "listRepoOps", token, &p).await.unwrap();
            let n = page["ops"].as_array().unwrap().len();
            ops.extend(page["ops"].as_array().unwrap().iter().cloned());
            // Every page has the repo's commit; a full one a cursor too.
            assert!(page.get("commit").is_some(), "{page}");
            if n == limit.parse::<usize>().unwrap() {
                cursor = Some(page["cursor"].as_str().unwrap().to_string());
            } else {
                assert!(page.get("cursor").is_none(), "{page}");
                return (ops, page["commit"].clone());
            }
        }
    }

    #[tokio::test]
    async fn writes_and_reads() {
        let plc = plc().await;
        let dir = scratch("space-rw");
        let s = open(&dir, &plc);
        let (alice, t) = create(&s, "alice").await;
        let public_before = repo_of(&s, &alice, |r| r.rev.clone());
        let body = |extra: Json| {
            let mut b = json!({ "space": SPACE, "repo": alice });
            b.as_object_mut()
                .unwrap()
                .extend(extra.as_object().unwrap().clone());
            b
        };
        let typed = |n: i64| json!({ "$type": "a.b.c", "n": n });
        // createRecord, with a key and without.
        let a = w(
            &s,
            "createRecord",
            &t,
            body(json!({ "collection": "a.b.c", "rkey": "a", "record": { "n": 1 } })),
        )
        .await
        .unwrap();
        assert_eq!(
            a,
            json!({ "uri": format!("{SPACE}/{alice}/a.b.c/a"), "cid": cid_of(&typed(1)), "validationStatus": "unknown" })
        );
        let first = latest(&s, &t, &alice, SPACE).await;
        assert_eq!(first["commit"]["ver"], 1);
        assert_eq!(
            (
                first["commit"]["repo"].as_str(),
                first["commit"]["space"].as_str()
            ),
            (Some(alice.as_str()), Some(SPACE))
        );
        assert!(valid_tid(&commit_rev(&first)));
        assert_eq!(
            w(
                &s,
                "createRecord",
                &t,
                body(json!({ "collection": "a.b.c", "rkey": "a", "record": { "n": 2 } }))
            )
            .await,
            Err("RecordAlreadyExists".into())
        );
        let k1 = w(
            &s,
            "createRecord",
            &t,
            body(json!({ "collection": "a.b.c", "record": typed(2), "validate": false })),
        )
        .await
        .unwrap();
        assert!(k1.get("validationStatus").is_none());
        let k2 = w(
            &s,
            "createRecord",
            &t,
            body(json!({ "collection": "a.b.c", "record": typed(3) })),
        )
        .await
        .unwrap();
        let key = |j: &Json| {
            j["uri"]
                .as_str()
                .unwrap()
                .rsplit('/')
                .next()
                .unwrap()
                .to_string()
        };
        let (k1, k2) = (key(&k1), key(&k2));
        assert!(valid_tid(&k1) && valid_tid(&k2) && k2 > k1);
        // putRecord always commits, even of the record stored.
        let before = latest(&s, &t, &alice, SPACE).await;
        let put = w(
            &s,
            "putRecord",
            &t,
            body(json!({ "collection": "a.b.c", "rkey": "a", "record": typed(1) })),
        )
        .await
        .unwrap();
        assert_eq!(put["cid"], json!(cid_of(&typed(1))));
        let after = latest(&s, &t, &alice, SPACE).await;
        assert!(commit_rev(&after) > commit_rev(&before));
        assert_eq!(after["commit"]["data"], before["commit"]["data"]);
        // A record without `$type` gets its collection's.
        w(
            &s,
            "putRecord",
            &t,
            body(json!({ "collection": "x.y.z", "rkey": "p", "record": { "n": 4 } })),
        )
        .await
        .unwrap();
        // getRecord.
        let got = r(
            &s,
            "getRecord",
            &t,
            &[
                ("space", SPACE),
                ("repo", &alice),
                ("collection", "x.y.z"),
                ("rkey", "p"),
            ],
        )
        .await
        .unwrap();
        assert_eq!(
            got,
            json!({ "uri": format!("{SPACE}/{alice}/x.y.z/p"), "cid": cid_of(&json!({ "$type": "x.y.z", "n": 4 })), "value": { "$type": "x.y.z", "n": 4 } })
        );
        assert_eq!(
            r(
                &s,
                "getRecord",
                &t,
                &[
                    ("space", SPACE),
                    ("repo", &alice),
                    ("collection", "x.y.z"),
                    ("rkey", "q")
                ]
            )
            .await,
            Err("RecordNotFound".into())
        );
        assert_eq!(
            r(
                &s,
                "getRecord",
                &t,
                &[
                    ("space", OTHER),
                    ("repo", &alice),
                    ("collection", "x.y.z"),
                    ("rkey", "p")
                ]
            )
            .await,
            Err("RecordNotFound".into())
        );
        assert_eq!(
            r(
                &s,
                "getLatestCommit",
                &t,
                &[("space", OTHER), ("repo", &alice)]
            )
            .await,
            Err("RepoNotFound".into())
        );
        // deleteRecord: of a record not there, no commit.
        let before = latest(&s, &t, &alice, SPACE).await;
        assert_eq!(
            w(
                &s,
                "deleteRecord",
                &t,
                body(json!({ "collection": "x.y.z", "rkey": "q" }))
            )
            .await,
            Ok(json!({}))
        );
        assert_eq!(latest(&s, &t, &alice, SPACE).await, before);
        assert_eq!(
            w(
                &s,
                "deleteRecord",
                &t,
                body(json!({ "collection": "x.y.z", "rkey": "p" }))
            )
            .await,
            Ok(json!({}))
        );
        assert!(commit_rev(&latest(&s, &t, &alice, SPACE).await) > commit_rev(&before));
        // applyWrites: each write sees those before it; a refusal keeps nothing.
        let ws = |writes: Json| body(json!({ "writes": writes }));
        let create = |rkey: &str, n: i64| json!({ "$type": "com.atproto.space.applyWrites#create", "collection": "a.b.c", "rkey": rkey, "value": typed(n) });
        let update = |rkey: &str, n: i64| json!({ "$type": "com.atproto.space.applyWrites#update", "collection": "a.b.c", "rkey": rkey, "value": typed(n) });
        let delete = |rkey: &str| json!({ "$type": "com.atproto.space.applyWrites#delete", "collection": "a.b.c", "rkey": rkey });
        let got = w(
            &s,
            "applyWrites",
            &t,
            ws(json!([
                create("x", 5),
                update("x", 6),
                delete("a"),
                create("a", 7)
            ])),
        )
        .await
        .unwrap();
        let uri = |k: &str| format!("{SPACE}/{alice}/a.b.c/{k}");
        assert_eq!(
            got,
            json!({ "results": [
                { "$type": "com.atproto.space.applyWrites#createResult", "uri": uri("x"), "cid": cid_of(&typed(5)), "validationStatus": "unknown" },
                { "$type": "com.atproto.space.applyWrites#updateResult", "uri": uri("x"), "cid": cid_of(&typed(6)), "validationStatus": "unknown" },
                { "$type": "com.atproto.space.applyWrites#deleteResult" },
                { "$type": "com.atproto.space.applyWrites#createResult", "uri": uri("a"), "cid": cid_of(&typed(7)), "validationStatus": "unknown" },
            ] })
        );
        let before = latest(&s, &t, &alice, SPACE).await;
        assert_eq!(
            w(
                &s,
                "applyWrites",
                &t,
                ws(json!([create("y", 1), update("nope", 1)]))
            )
            .await,
            Err("RecordNotFound".into())
        );
        assert_eq!(
            w(
                &s,
                "applyWrites",
                &t,
                ws(json!([create("y", 1), delete("y"), delete("y")]))
            )
            .await,
            Err("RecordNotFound".into())
        );
        assert_eq!(
            w(
                &s,
                "applyWrites",
                &t,
                ws(json!([create("y", 1), create("x", 1)]))
            )
            .await,
            Err("RecordAlreadyExists".into())
        );
        assert_eq!(
            w(&s, "applyWrites", &t, ws(json!([]))).await,
            Ok(json!({ "results": [] }))
        );
        assert_eq!(latest(&s, &t, &alice, SPACE).await, before);
        assert_eq!(
            r(
                &s,
                "getRecord",
                &t,
                &[
                    ("space", SPACE),
                    ("repo", &alice),
                    ("collection", "a.b.c"),
                    ("rkey", "y")
                ]
            )
            .await,
            Err("RecordNotFound".into())
        );
        // A batch leaving the repo as it was still commits.
        w(
            &s,
            "applyWrites",
            &t,
            ws(json!([create("z", 1), delete("z")])),
        )
        .await
        .unwrap();
        let after = latest(&s, &t, &alice, SPACE).await;
        assert!(commit_rev(&after) > commit_rev(&before));
        assert_eq!(after["commit"]["data"], before["commit"]["data"]);
        // `data` is the LtHash of the records, as pds-space sums them.
        let held = [
            ("a.b.c/a", cid_of(&typed(7))),
            ("a.b.c/x", cid_of(&typed(6))),
            (&format!("a.b.c/{k1}"), cid_of(&typed(2))),
            (&format!("a.b.c/{k2}"), cid_of(&typed(3))),
        ];
        assert_eq!(
            after["commit"]["data"],
            data_of(held.iter().map(|(p, c)| (*p, c.as_str())))
        );
        // listRecords: descending by path, or ascending; paged when full.
        let list = |p: Vec<(&'static str, String)>| {
            let s = s.clone();
            let t = t.clone();
            let alice = alice.clone();
            async move {
                let mut all: Vec<(&str, String)> =
                    vec![("space", SPACE.into()), ("repo", alice.clone())];
                all.extend(p);
                let refs: Vec<(&str, &str)> = all.iter().map(|(k, v)| (*k, v.as_str())).collect();
                r(&s, "listRecords", &t, &refs).await.unwrap()
            }
        };
        let paths = |j: &Json| {
            j["records"]
                .as_array()
                .unwrap()
                .iter()
                .map(|r| {
                    format!(
                        "{}/{}",
                        r["collection"].as_str().unwrap(),
                        r["rkey"].as_str().unwrap()
                    )
                })
                .collect::<Vec<_>>()
        };
        let mut want: Vec<String> = held.iter().map(|(p, _)| p.to_string()).collect();
        want.sort();
        let all = list(vec![]).await;
        assert_eq!(paths(&all), want.iter().rev().cloned().collect::<Vec<_>>());
        assert!(all.get("cursor").is_none());
        assert_eq!(all["records"][0]["value"], typed(6));
        assert_eq!(all["records"][0]["cid"], json!(cid_of(&typed(6))));
        // `reverse` is ignored: the order is always descending.
        let desc: Vec<String> = want.iter().rev().cloned().collect();
        let flipped = list(vec![
            ("reverse", "true".into()),
            ("excludeValues", "true".into()),
        ])
        .await;
        assert_eq!(paths(&flipped), desc);
        assert!(flipped["records"][0].get("value").is_none());
        for reverse in ["false", "true"] {
            let mut seen = Vec::new();
            let mut cursor: Option<String> = None;
            loop {
                let mut p = vec![("limit", "2".to_string()), ("reverse", reverse.to_string())];
                if let Some(c) = &cursor {
                    p.push(("cursor", c.clone()));
                }
                let page = list(p).await;
                seen.extend(paths(&page));
                match page.get("cursor") {
                    Some(c) => {
                        assert!(c.as_str().unwrap().contains('/'));
                        cursor = Some(c.as_str().unwrap().into())
                    }
                    None => break,
                }
            }
            assert_eq!(seen, desc, "reverse {reverse}");
        }
        // A cursor with no `/` is InvalidCursor, even with no repo.
        for space in [SPACE, OTHER] {
            assert_eq!(
                r(
                    &s,
                    "listRecords",
                    &t,
                    &[("space", space), ("repo", &alice), ("cursor", "nonsense")]
                )
                .await,
                Err("InvalidCursor".into())
            );
        }
        // A collection's records only: `a.b.c.d/1` sorts before `a.b.c/10`.
        w(
            &s,
            "createRecord",
            &t,
            body(json!({ "collection": "a.b.c.d", "rkey": "1", "record": {} })),
        )
        .await
        .unwrap();
        assert_eq!(
            paths(&list(vec![("collection", "a.b.c.d".into())]).await),
            ["a.b.c.d/1"]
        );
        assert_eq!(
            paths(&list(vec![("collection", "a.b.c".into())]).await),
            desc
        );
        assert_eq!(
            paths(&list(vec![("reverse", "true".into()), ("limit", "1".into())]).await),
            [desc[0].clone()]
        );
        assert_eq!(
            paths(
                &list(vec![
                    ("collection", "a.b.c".into()),
                    ("cursor", format!("{SPACE}/{alice}/a.b.c.d/1"))
                ])
                .await
            ),
            Vec::<String>::new()
        );
        assert_eq!(
            paths(
                &list(vec![
                    ("collection", "a.b.c.d".into()),
                    ("cursor", format!("{SPACE}/{alice}/a.b.c/zzz"))
                ])
                .await
            ),
            ["a.b.c.d/1"]
        );
        // A cursor is a record URI of this space and repo: a bare path, or
        // another repo's URI, is refused.
        for cursor in [
            "a.b.c/zzz".to_string(),
            format!("{OTHER}/{alice}/a.b.c/zzz"),
        ] {
            assert_eq!(
                r(
                    &s,
                    "listRecords",
                    &t,
                    &[("space", SPACE), ("repo", &alice), ("cursor", &cursor)]
                )
                .await,
                Err("InvalidCursor".into()),
                "{cursor}"
            );
        }
        assert_eq!(
            r(&s, "listRecords", &t, &[("space", OTHER), ("repo", &alice)]).await,
            Ok(json!({ "records": [] }))
        );
        // listRepoOps, replayed from the empty LtHash, gives `data`; any page size does.
        let (ops, commit) = all_ops(&s, &t, &alice, SPACE, "100").await;
        assert_eq!(commit, latest(&s, &t, &alice, SPACE).await["commit"]);
        let mut h = LtHash::new();
        for o in &ops {
            let path = format!(
                "{}/{}",
                o["collection"].as_str().unwrap(),
                o["rkey"].as_str().unwrap()
            );
            if let Some(c) = o["cid"].as_str() {
                h.add(&element(&path, c));
            }
            if let Some(c) = o["prev"].as_str() {
                h.remove(&element(&path, c));
            }
        }
        assert_eq!(
            json!({ "$bytes": STANDARD_NO_PAD.encode(h.digest()) }),
            commit["data"]
        );
        for limit in ["1", "3", "4"] {
            assert_eq!(
                all_ops(&s, &t, &alice, SPACE, limit).await,
                (ops.clone(), commit.clone()),
                "limit {limit}"
            );
        }
        // The first op: alice's create of `a`, since replaced and deleted, so no value.
        assert_eq!(
            ops[0],
            json!({ "rev": commit_rev(&first), "collection": "a.b.c", "rkey": "a", "cid": cid_of(&typed(1)), "prev": null })
        );
        // The put of the record stored: `cid` and `prev` equal.
        assert_eq!(ops[3]["cid"], ops[3]["prev"]);
        // Ops of one commit share its rev; those whose record is held now have its value.
        let batch: Vec<&Json> = ops.iter().filter(|o| o["rev"] == ops[7]["rev"]).collect();
        assert_eq!(batch.len(), 4);
        assert!(batch[0].get("value").is_none() && batch[2]["cid"].is_null());
        assert_eq!(batch[1]["value"], typed(6));
        let since = r(
            &s,
            "listRepoOps",
            &t,
            &[
                ("space", SPACE),
                ("repo", &alice),
                ("since", ops[7]["rev"].as_str().unwrap()),
                ("excludeValues", "true"),
            ],
        )
        .await
        .unwrap();
        let later = ops
            .iter()
            .filter(|o| o["rev"].as_str() > ops[7]["rev"].as_str())
            .count();
        assert_eq!((since["ops"].as_array().unwrap().len(), later), (3, 3));
        assert!(
            since["ops"]
                .as_array()
                .unwrap()
                .iter()
                .all(|o| o.get("value").is_none())
        );
        // No repo is RepoNotFound; a cursor with no `/` InvalidCursor first,
        // and one with a `/` this server did not answer refused too.
        assert_eq!(
            r(&s, "listRepoOps", &t, &[("space", OTHER), ("repo", &alice)]).await,
            Err("RepoNotFound".into())
        );
        for (space, cursor) in [(SPACE, "nonsense"), (OTHER, "nonsense"), (SPACE, "x/1")] {
            assert_eq!(
                r(
                    &s,
                    "listRepoOps",
                    &t,
                    &[("space", space), ("repo", &alice), ("cursor", cursor)]
                )
                .await,
                Err("InvalidCursor".into()),
                "{space} {cursor}"
            );
        }
        // listSpaces: the spaces alice has a repo in, by URI.
        let other = json!({ "space": OTHER, "repo": alice, "collection": "a.b.c", "record": {} });
        w(&s, "createRecord", &t, other).await.unwrap();
        let spaces = |p: &[(&str, &str)]| {
            let p: Vec<(String, String)> = p
                .iter()
                .map(|(k, v)| (k.to_string(), v.to_string()))
                .collect();
            let (s, t) = (s.clone(), t.clone());
            async move {
                let refs: Vec<(&str, &str)> =
                    p.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect();
                r(&s, "listSpaces", &t, &refs).await.unwrap()
            }
        };
        let named = |j: Json| -> Vec<String> {
            j["spaces"]
                .as_array()
                .unwrap()
                .iter()
                .map(|x| x["space"].as_str().unwrap().to_string())
                .collect()
        };
        let all = spaces(&[]).await;
        assert_eq!(named(all.clone()), [SPACE, OTHER]);
        // Each with its repo's commit; a space of another authority no spaceRev.
        let head = latest(&s, &t, &alice, SPACE).await["commit"].clone();
        assert_eq!(
            all["spaces"][0],
            json!({ "space": SPACE, "repoRev": head["rev"], "data": head["data"] })
        );
        assert_eq!(
            named(spaces(&[("spaceType", "com.example.chat")]).await),
            [OTHER]
        );
        // `spaceDid` filters by authority; a `did` is ignored.
        assert_eq!(
            named(spaces(&[("spaceDid", "did:web:example.com")]).await),
            [OTHER]
        );
        assert_eq!(
            named(spaces(&[("spaceDid", "did:web:example.org")]).await),
            Vec::<String>::new()
        );
        assert_eq!(
            named(spaces(&[("did", "did:web:example.org")]).await),
            [SPACE, OTHER]
        );
        let page = spaces(&[("limit", "1")]).await;
        assert_eq!(
            (named(page.clone()), &page["cursor"]),
            (vec![SPACE.to_string()], &json!(SPACE))
        );
        let page = spaces(&[("limit", "1"), ("cursor", SPACE)]).await;
        assert_eq!(
            (named(page.clone()), &page["cursor"]),
            (vec![OTHER.to_string()], &json!(OTHER))
        );
        assert_eq!(
            spaces(&[("limit", "1"), ("cursor", OTHER)]).await,
            json!({ "spaces": [] })
        );
        assert_eq!(
            r(&s, "listSpaces", &t, &[("cursor", "nonsense")]).await,
            Err("InvalidCursor".into())
        );
        assert_eq!(
            r(&s, "listSpaces", &t, &[("spaceDid", "nonsense")]).await,
            Err("InvalidRequest".into())
        );
        // clearRecords: every record and the log go, in one commit.
        let before = latest(&s, &t, &alice, SPACE).await;
        assert_eq!(
            w(
                &s,
                "clearRecords",
                &t,
                json!({ "space": SPACE, "repo": alice })
            )
            .await,
            Ok(json!({}))
        );
        let cleared = latest(&s, &t, &alice, SPACE).await;
        assert!(commit_rev(&cleared) > commit_rev(&before));
        assert_eq!(
            cleared["commit"]["data"],
            json!({ "$bytes": STANDARD_NO_PAD.encode(LtHash::new().digest()) })
        );
        assert_eq!(
            STANDARD_NO_PAD.encode(LtHash::new().digest()),
            STANDARD_NO_PAD.encode(
                hex::decode("e5a00aa9991ac8a5ee3109844d84a55583bd20572ad3ffcd42792f3c36b183ad")
                    .unwrap()
            )
        );
        assert_eq!(
            all_ops(&s, &t, &alice, SPACE, "10").await,
            (vec![], cleared["commit"].clone())
        );
        assert_eq!(list(vec![]).await, json!({ "records": [] }));
        assert_eq!(
            w(
                &s,
                "clearRecords",
                &t,
                json!({ "space": SPACE, "repo": alice })
            )
            .await,
            Ok(json!({}))
        );
        assert_eq!(latest(&s, &t, &alice, SPACE).await, cleared);
        assert_eq!(w(&s, "clearRecords", &t, json!({ "space": "at://did:web:example.com/space/com.example.chat/none", "repo": alice })).await, Ok(json!({})));
        assert_eq!(spaces(&[]).await["spaces"].as_array().unwrap().len(), 2);
        // The public repository is as it was.
        assert_eq!(repo_of(&s, &alice, |r| r.rev.clone()), public_before);
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// A body of exactly `len` bytes: `body` with a property no lexicon names to pad it.
    fn padded(body: Json, len: usize) -> String {
        let mut b = body;
        b["pad"] = json!("");
        let n = len - b.to_string().len();
        b["pad"] = json!("x".repeat(n));
        let text = b.to_string();
        assert_eq!(text.len(), len);
        text
    }

    /// A `createRecord` whose record's DRISL is exactly `len` bytes, its
    /// whole numbers written as exponents, as JSON far shorter than the record.
    fn big_record(space: &str, repo: &str, len: usize) -> String {
        let record = |k: usize, m: usize| {
            format!(
                r#"{{"$type":"a.b.c","n":[{}],"s":"{}"}}"#,
                vec!["9e15"; k].join(","),
                "x".repeat(m)
            )
        };
        let size = |text: &str| {
            make_record(from_json(&serde_json::from_str::<Json>(text).unwrap()).unwrap())
                .bytes
                .len()
        };
        let k = (len - 200) / 9;
        let m = 100 + len - size(&record(k, 100));
        assert!((24..256).contains(&m));
        let rec = record(k, m);
        assert_eq!(size(&rec), len);
        format!(
            r#"{{"space":"{space}","repo":"{repo}","collection":"a.b.c","rkey":"big","record":{rec}}}"#
        )
    }

    #[tokio::test]
    async fn refusals_in_order() {
        let plc = plc().await;
        let dir = scratch("space-refusals");
        let s = open(&dir, &plc);
        let (alice, t) = create(&s, "alice").await;
        let (bob, _) = create(&s, "bob").await;
        let own = format!("at://{alice}/space/com.example.forum/main");
        let create_body = |space: &str, repo: &str, record: Json| json!({ "space": space, "repo": repo, "collection": "a.b.c", "rkey": "k", "record": record });
        let nsid = |n: &str| format!("com.atproto.space.{n}");
        let status = |got: (u16, Json, Vec<(&'static str, String)>)| {
            (got.0, got.1["error"].as_str().unwrap_or("").to_string())
        };
        let send_body = |name: &str, token: Option<&str>, body: String| {
            let (s, nsid) = (s.clone(), nsid(name));
            let token = token.map(str::to_string);
            async move { status(send(&s, &nsid, token.as_deref(), &[], &body, &[]).await) }
        };
        // The token, before anything else.
        let huge = "x".repeat(1_000_001);
        assert_eq!(
            send_body("createRecord", None, huge.clone()).await,
            (401, "AuthMissing".into())
        );
        assert_eq!(
            send_body("createRecord", Some("nonsense"), huge.clone()).await,
            (400, "InvalidToken".into())
        );
        let session = call(
            &s,
            "com.atproto.server.createSession",
            None,
            json!({ "identifier": "alice.test", "password": "alice-pw" }),
        )
        .await
        .unwrap();
        let refresh = session["refreshJwt"].as_str().unwrap();
        assert_eq!(
            send_body(
                "createRecord",
                Some(refresh),
                create_body(SPACE, &alice, json!({})).to_string()
            )
            .await,
            (400, "InvalidToken".into())
        );
        for read in [
            "getRecord",
            "listRecords",
            "getLatestCommit",
            "listRepoOps",
            "listSpaces",
        ] {
            let p = [
                ("space", SPACE),
                ("repo", alice.as_str()),
                ("collection", "a.b.c"),
                ("rkey", "k"),
            ];
            assert_eq!(
                status(send(&s, &nsid(read), None, &p, "", &[]).await),
                (401, "AuthMissing".into()),
                "{read}"
            );
            assert_eq!(
                status(send(&s, &nsid(read), Some(refresh), &p, "", &[]).await),
                (400, "InvalidToken".into()),
                "{read}"
            );
        }
        // An app password's token writes.
        let app = call(
            &s,
            "com.atproto.server.createAppPassword",
            Some(&t),
            json!({ "name": "app" }),
        )
        .await
        .unwrap();
        let app_session = call(
            &s,
            "com.atproto.server.createSession",
            None,
            json!({ "identifier": "alice.test", "password": app["password"] }),
        )
        .await
        .unwrap();
        w(
            &s,
            "createRecord",
            app_session["accessJwt"].as_str().unwrap(),
            create_body(SPACE, &alice, json!({ "n": 0 })),
        )
        .await
        .unwrap();
        // Then the body's size, at its edges, before its input.
        assert_eq!(
            send_body("createRecord", Some(&t), huge).await,
            (413, "PayloadTooLargeError".into())
        );
        assert_eq!(
            send_body("clearRecords", Some(&t), "x".repeat(153_601)).await,
            (413, "PayloadTooLargeError".into())
        );
        let put = |len: usize| {
            padded(
                json!({ "space": SPACE, "repo": alice, "collection": "a.b.c", "rkey": "pad", "record": {} }),
                len,
            )
        };
        assert_eq!(
            send_body("putRecord", Some(&t), put(1_000_000)).await,
            (200, String::new())
        );
        assert_eq!(
            send_body("putRecord", Some(&t), put(1_000_001)).await,
            (413, "PayloadTooLargeError".into())
        );
        assert_eq!(
            send_body(
                "applyWrites",
                Some(&t),
                padded(
                    json!({ "space": SPACE, "repo": alice, "writes": [] }),
                    1_000_001
                )
            )
            .await,
            (413, "PayloadTooLargeError".into())
        );
        let del = |len: usize| {
            padded(
                json!({ "space": SPACE, "repo": alice, "collection": "a.b.c", "rkey": "pad" }),
                len,
            )
        };
        assert_eq!(
            send_body("deleteRecord", Some(&t), del(153_600)).await,
            (200, String::new())
        );
        assert_eq!(
            send_body("deleteRecord", Some(&t), del(153_601)).await,
            (413, "PayloadTooLargeError".into())
        );
        assert_eq!(
            send_body(
                "clearRecords",
                Some(&t),
                padded(json!({ "space": OTHER, "repo": alice }), 153_600)
            )
            .await,
            (200, String::new())
        );
        // Then its input against the lexicon.
        for space in [
            "at://alice.test/space/com.example.forum/main",
            "at://did:plc:abc/space/com.example.forum",
            &format!("{SPACE}/{alice}/a.b.c/k"),
            "nonsense",
        ] {
            assert_eq!(
                w(
                    &s,
                    "createRecord",
                    &t,
                    create_body(space, &alice, json!({}))
                )
                .await,
                Err("InvalidRequest".into()),
                "{space}"
            );
        }
        assert_eq!(
            w(
                &s,
                "createRecord",
                &t,
                create_body(SPACE, "alice.test", json!({}))
            )
            .await,
            Err("InvalidRequest".into())
        );
        assert_eq!(
            w(&s, "createRecord", &t, create_body(SPACE, &alice, json!(5))).await,
            Err("InvalidRequest".into())
        );
        let repo_writes = json!({ "space": SPACE, "repo": alice, "writes": [{ "$type": "com.atproto.repo.applyWrites#create", "collection": "a.b.c", "value": {} }] });
        assert_eq!(
            w(&s, "applyWrites", &t, repo_writes).await,
            Err("InvalidRequest".into())
        );
        // Then `repo`: another's is forbidden, whatever its record or collection.
        for repo in [bob.as_str(), "did:plc:nobodyatall00000000000000"] {
            assert_eq!(
                w(
                    &s,
                    "createRecord",
                    &t,
                    create_body(SPACE, repo, json!({ "n": 1.5, "$type": "x.y.z" }))
                )
                .await,
                Err("Forbidden".into())
            );
            let body = json!({ "space": SPACE, "repo": repo, "collection": "com.atproto.space.policy", "rkey": "k" });
            assert_eq!(
                w(&s, "deleteRecord", &t, body).await,
                Err("Forbidden".into())
            );
            assert_eq!(
                w(
                    &s,
                    "clearRecords",
                    &t,
                    json!({ "space": SPACE, "repo": repo })
                )
                .await,
                Err("Forbidden".into())
            );
            let many: Vec<Json> = (0..201).map(|i| json!({ "$type": "com.atproto.space.applyWrites#delete", "collection": "a.b.c", "rkey": format!("k{i}") })).collect();
            assert_eq!(
                w(
                    &s,
                    "applyWrites",
                    &t,
                    json!({ "space": SPACE, "repo": repo, "writes": many })
                )
                .await,
                Err("Forbidden".into())
            );
        }
        for read in ["getRecord", "listRecords", "getLatestCommit", "listRepoOps"] {
            let p = [
                ("space", SPACE),
                ("repo", bob.as_str()),
                ("collection", "a.b.c"),
                ("rkey", "k"),
            ];
            assert_eq!(
                r(&s, read, &t, &p).await,
                Err("RepoNotFound".into()),
                "{read}"
            );
        }
        // Then how many writes: 200 are taken.
        let creates = |n: usize| {
            (0..n).map(|i| json!({ "$type": "com.atproto.space.applyWrites#create", "collection": "a.b.c", "rkey": format!("w{i}"), "value": {} })).collect::<Vec<_>>()
        };
        assert_eq!(
            w(
                &s,
                "applyWrites",
                &t,
                json!({ "space": SPACE, "repo": alice, "writes": creates(201) })
            )
            .await,
            Err("InvalidRequest".into())
        );
        assert_eq!(
            w(
                &s,
                "applyWrites",
                &t,
                json!({ "space": SPACE, "repo": alice, "writes": creates(200) })
            )
            .await
            .unwrap()["results"]
                .as_array()
                .unwrap()
                .len(),
            200
        );
        // Then each record and collection.
        for bad in [
            json!({ "$type": "x.y.z" }),
            json!({ "n": 1.5 }),
            json!({ "$type": 5 }),
            json!({ "b": { "$bytes": "!" } }),
        ] {
            assert_eq!(
                w(&s, "putRecord", &t, create_body(SPACE, &alice, bad.clone())).await,
                Err("InvalidRequest".into()),
                "{bad}"
            );
        }
        let mut validated = create_body(SPACE, &alice, json!({}));
        validated["validate"] = json!(true);
        assert_eq!(
            w(&s, "putRecord", &t, validated).await,
            Err("InvalidRequest".into())
        );
        // A whole number is an integer however it is written.
        let text = format!(
            r#"{{"space":"{SPACE}","repo":"{alice}","collection":"a.b.c","rkey":"e","record":{{"a":1e3,"b":1E3,"c":1000.0,"d":-0,"e":9e15}}}}"#
        );
        let (code, got, _) = send(&s, &nsid("putRecord"), Some(&t), &[], &text, &[]).await;
        assert_eq!(code, 200, "{got}");
        assert_eq!(
            got["cid"],
            json!(cid_of(
                &json!({ "$type": "a.b.c", "a": 1000, "b": 1000, "c": 1000, "d": 0, "e": 9_000_000_000_000_000_i64 })
            ))
        );
        // A record of 1 MiB of DRISL is taken; one byte more is not.
        assert_eq!(
            send_body("putRecord", Some(&t), big_record(SPACE, &alice, MAX_RECORD)).await,
            (200, String::new())
        );
        assert_eq!(
            send_body(
                "putRecord",
                Some(&t),
                big_record(SPACE, &alice, MAX_RECORD + 1)
            )
            .await,
            (400, "InvalidRequest".into())
        );
        // The published collections, in every repo and space, whatever the record.
        for collection in PUBLISHED {
            for space in [SPACE, own.as_str()] {
                let body = json!({ "space": space, "repo": alice, "collection": collection, "rkey": "k", "record": {} });
                assert_eq!(
                    w(&s, "createRecord", &t, body.clone()).await,
                    Err("InvalidRequest".into())
                );
                assert_eq!(
                    w(&s, "putRecord", &t, body).await,
                    Err("InvalidRequest".into())
                );
                assert_eq!(w(&s, "deleteRecord", &t, json!({ "space": space, "repo": alice, "collection": collection, "rkey": "k" })).await, Err("InvalidRequest".into()));
                let writes = json!([{ "$type": "com.atproto.space.applyWrites#delete", "collection": collection, "rkey": "k" }]);
                assert_eq!(
                    w(
                        &s,
                        "applyWrites",
                        &t,
                        json!({ "space": space, "repo": alice, "writes": writes })
                    )
                    .await,
                    Err("InvalidRequest".into())
                );
            }
        }
        // Then the space: the caller's own must exist, for a write that would commit.
        assert_eq!(
            w(&s, "createRecord", &t, create_body(&own, &alice, json!({}))).await,
            Err("SpaceNotFound".into())
        );
        assert_eq!(
            w(&s, "putRecord", &t, create_body(&own, &alice, json!({}))).await,
            Err("SpaceNotFound".into())
        );
        let missing = json!([{ "$type": "com.atproto.space.applyWrites#delete", "collection": "a.b.c", "rkey": "k" }]);
        assert_eq!(
            w(
                &s,
                "applyWrites",
                &t,
                json!({ "space": own, "repo": alice, "writes": missing })
            )
            .await,
            Err("SpaceNotFound".into())
        );
        assert_eq!(
            w(
                &s,
                "applyWrites",
                &t,
                json!({ "space": own, "repo": alice, "writes": [] })
            )
            .await,
            Ok(json!({ "results": [] }))
        );
        assert_eq!(
            w(
                &s,
                "deleteRecord",
                &t,
                json!({ "space": own, "repo": alice, "collection": "a.b.c", "rkey": "k" })
            )
            .await,
            Ok(json!({}))
        );
        assert_eq!(
            w(
                &s,
                "clearRecords",
                &t,
                json!({ "space": own, "repo": alice })
            )
            .await,
            Ok(json!({}))
        );
        // A write refused, or making no commit, leaves no repo.
        let spaces = r(&s, "listSpaces", &t, &[]).await.unwrap();
        let listed: Vec<&Json> = spaces["spaces"]
            .as_array()
            .unwrap()
            .iter()
            .map(|x| &x["space"])
            .collect();
        assert_eq!(listed, [&json!(SPACE)]);
        assert_eq!(
            r(
                &s,
                "getLatestCommit",
                &t,
                &[("space", &own), ("repo", &alice)]
            )
            .await,
            Err("RepoNotFound".into())
        );
        // Another account's space needs no check, whether it exists or not.
        let bobs = format!("at://{bob}/space/com.example.forum/main");
        w(
            &s,
            "createRecord",
            &t,
            create_body(&bobs, &alice, json!({})),
        )
        .await
        .unwrap();
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// A taken-down account's `allowTakendown` session lists its spaces, as
    /// it reads its repo whole (`spec/SPACES-EXPORT.md`); its other reads
    /// are refused.
    #[tokio::test]
    async fn an_allow_takendown_session_lists_its_spaces() {
        let plc = plc().await;
        let dir = scratch("space-takendown-list");
        let s = open(&dir, &plc);
        let (alice, t) = create(&s, "alice").await;
        w(&s, "createRecord", &t, json!({ "space": SPACE, "repo": alice, "collection": "a.b.c", "rkey": "k", "record": {} })).await.unwrap();
        crate::space_credentials::tests::take_down(&s, &alice, true).await;
        let session = call(
            &s,
            "com.atproto.server.createSession",
            None,
            json!({ "identifier": "alice.test", "password": "alice-pw", "allowTakendown": true }),
        )
        .await
        .unwrap();
        let down = session["accessJwt"].as_str().unwrap();
        let listed = r(&s, "listSpaces", down, &[]).await.unwrap();
        assert!(
            listed["spaces"]
                .as_array()
                .unwrap()
                .iter()
                .any(|x| x["space"] == SPACE),
            "{listed}"
        );
        assert_eq!(
            r(
                &s,
                "listRecords",
                down,
                &[("space", SPACE), ("repo", &alice), ("collection", "a.b.c")]
            )
            .await,
            Err("InvalidToken".into())
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// Each write of a deactivated or taken-down account, with a token made
    /// before: refused after its token, before anything else of the request.
    #[tokio::test]
    async fn an_account_not_active_writes_nothing() {
        use crate::space_credentials::tests::{deactivate, take_down};
        let plc = plc().await;
        let dir = scratch("space-state");
        let s = open(&dir, &plc);
        let (alice, t) = create(&s, "alice").await;
        let (bob, _) = create(&s, "bob").await;
        let session = call(
            &s,
            "com.atproto.server.createSession",
            None,
            json!({ "identifier": "alice.test", "password": "alice-pw" }),
        )
        .await
        .unwrap();
        let refresh = session["refreshJwt"].as_str().unwrap().to_string();
        let app = call(
            &s,
            "com.atproto.server.createAppPassword",
            Some(&t),
            json!({ "name": "app" }),
        )
        .await
        .unwrap();
        let app_session = call(
            &s,
            "com.atproto.server.createSession",
            None,
            json!({ "identifier": "alice.test", "password": app["password"] }),
        )
        .await
        .unwrap();
        let app_token = app_session["accessJwt"].as_str().unwrap().to_string();
        let rec = |repo: &str, record: Json| json!({ "space": SPACE, "repo": repo, "collection": "a.b.c", "rkey": "k", "record": record });
        let key = |repo: &str| json!({ "space": SPACE, "repo": repo, "collection": "a.b.c", "rkey": "k" });
        let bodies = |repo: &str| {
            [
                ("createRecord", rec(repo, json!({}))),
                ("putRecord", rec(repo, json!({}))),
                ("deleteRecord", key(repo)),
                (
                    "applyWrites",
                    json!({ "space": SPACE, "repo": repo, "writes": [] }),
                ),
                ("clearRecords", json!({ "space": SPACE, "repo": repo })),
            ]
        };
        let answer = |name: &str, token: Option<&str>, body: String| {
            let (s, nsid, token) = (
                s.clone(),
                format!("com.atproto.space.{name}"),
                token.map(str::to_string),
            );
            async move {
                let got = send(&s, &nsid, token.as_deref(), &[], &body, &[]).await;
                (got.0, got.1["error"].as_str().unwrap_or("").to_string())
            }
        };
        let refused = |status: u16, name: &'static str| {
            let (alice, bob, refresh) = (alice.clone(), bob.clone(), refresh.clone());
            let (t, app_token) = (t.clone(), app_token.clone());
            async move {
                let want = (status, name.to_string());
                for (write, body) in bodies(&alice) {
                    // The token first.
                    assert_eq!(
                        answer(write, None, body.to_string()).await,
                        (401, "AuthMissing".into()),
                        "{write}"
                    );
                    assert_eq!(
                        answer(write, Some(&refresh), body.to_string()).await,
                        (400, "InvalidToken".into()),
                        "{write}"
                    );
                    // Then the state, whatever the token's session, and before the rest.
                    for token in [&t, &app_token] {
                        assert_eq!(
                            answer(write, Some(token), body.to_string()).await,
                            want,
                            "{write}"
                        );
                    }
                    let limit = crate::limits::body_limit(&format!("com.atproto.space.{write}"));
                    assert_eq!(
                        answer(write, Some(&t), "x".repeat(limit + 1)).await,
                        want,
                        "{write} past the limit"
                    );
                    assert_eq!(
                        answer(write, Some(&t), "nonsense".into()).await,
                        want,
                        "{write} not JSON"
                    );
                    assert_eq!(
                        answer(write, Some(&t), json!({ "repo": alice }).to_string()).await,
                        want,
                        "{write} no space"
                    );
                }
                assert_eq!(
                    answer("createRecord", Some(&t), rec(&alice, json!(5)).to_string()).await,
                    want
                );
                for (write, body) in bodies(&bob) {
                    assert_eq!(
                        answer(write, Some(&t), body.to_string()).await,
                        want,
                        "{write} another's repo"
                    );
                }
            }
        };
        w(&s, "createRecord", &t, rec(&alice, json!({})))
            .await
            .unwrap();
        deactivate(&s, &t, true).await;
        refused(401, "AccountDeactivated").await;
        take_down(&s, &alice, true).await;
        refused(401, "AccountTakedown").await;
        take_down(&s, &alice, false).await;
        refused(401, "AccountDeactivated").await;
        deactivate(&s, &t, false).await;
        // Active again, with the same token, every write is taken.
        let mut writes = bodies(&alice);
        writes.rotate_left(2);
        for (write, body) in writes {
            w(&s, write, &t, body).await.unwrap();
        }
        let _ = std::fs::remove_dir_all(&dir);
    }

    fn header<'a>(hs: &'a [(&'static str, String)], name: &str) -> Option<&'a str> {
        hs.iter().find(|(n, _)| *n == name).map(|(_, v)| v.as_str())
    }

    /// The MAC headers of an answer, as a syncer reads them for `profile`.
    fn received<'a>(hs: &'a [(&'static str, String)], profile: Profile) -> mac::Received<'a> {
        mac::Received {
            covered: header(hs, profile.as_str()),
            signature_input: header(hs, "signature-input"),
            signature: header(hs, "signature"),
        }
    }

    /// A commit as answered in JSON.
    fn commit_of(c: &Json) -> Commit {
        let data = STANDARD_NO_PAD
            .decode(c["data"]["$bytes"].as_str().unwrap())
            .unwrap();
        Commit {
            repo: c["repo"].as_str().unwrap().into(),
            space: c["space"].as_str().unwrap().into(),
            rev: c["rev"].as_str().unwrap().into(),
            data: data.try_into().unwrap(),
        }
    }

    /// Whether an answer has none of the MAC headers, and `Vary` naming
    /// `Accept-Signature`.
    fn no_mac(hs: &[(&'static str, String)]) -> bool {
        hs == [("vary", "Accept-Signature".to_string())]
    }

    #[tokio::test]
    async fn macs_on_request() {
        let plc = plc().await;
        let dir = scratch("space-macs");
        let s = open(&dir, &plc);
        let (alice, t) = create(&s, "alice").await;
        let author = s.account(&alice).unwrap().kem.as_ref().unwrap().public();
        let syncer = KemKey::from_bytes(&[7u8; 32]).unwrap();
        let secret = syncer.encapsulate(&author);
        let share = syncer.public().did_key();
        let ask =
            |profile: &str| format!(r#"mac=("{profile}";sf);keyid="{share}";tag="{profile}""#);
        let (commit_ask, record_ask) = (ask("atproto-space-commit"), ask("atproto-space-record"));
        w(&s, "createRecord", &t, json!({ "space": SPACE, "repo": alice, "collection": "a.b.c", "rkey": "k", "record": { "n": 1 } })).await.unwrap();
        w(&s, "createRecord", &t, json!({ "space": SPACE, "repo": alice, "collection": "a.b.c", "rkey": "l", "record": { "n": 2 } })).await.unwrap();
        let nsid = |n: &str| format!("com.atproto.space.{n}");
        let repo_p = [("space", SPACE), ("repo", alice.as_str())];
        let record_p = [
            ("space", SPACE),
            ("repo", alice.as_str()),
            ("collection", "a.b.c"),
            ("rkey", "k"),
        ];
        let commit_ok = |hs: &[(&'static str, String)], c: &Json| {
            mac::check_commit(
                &received(hs, Profile::Commit),
                &share,
                &secret,
                &commit_of(c),
            )
        };
        // getRecord: the record's full URI and CID, and the headers exposed.
        let (code, got, hs) = send(
            &s,
            &nsid("getRecord"),
            Some(&t),
            &record_p,
            "",
            &[("Accept-Signature", &record_ask)],
        )
        .await;
        assert_eq!(code, 200);
        mac::check_record(
            &received(&hs, Profile::Record),
            &share,
            &secret,
            got["uri"].as_str().unwrap(),
            got["cid"].as_str().unwrap(),
        )
        .unwrap();
        assert_eq!(header(&hs, "vary"), Some("Accept-Signature"));
        assert_eq!(
            header(&hs, "access-control-expose-headers"),
            Some("atproto-space-record, signature-input, signature")
        );
        // getLatestCommit and every page of listRepoOps: the commit answered.
        let (_, got, hs) = send(
            &s,
            &nsid("getLatestCommit"),
            Some(&t),
            &repo_p,
            "",
            &[("accept-signature", &commit_ask)],
        )
        .await;
        commit_ok(&hs, &got["commit"]).unwrap();
        let paged = [("space", SPACE), ("repo", alice.as_str()), ("limit", "1")];
        for p in [&repo_p[..], &paged[..]] {
            let (_, ops, hs) = send(
                &s,
                &nsid("listRepoOps"),
                Some(&t),
                p,
                "",
                &[("accept-signature", &commit_ask)],
            )
            .await;
            assert_eq!(ops["commit"], got["commit"]);
            commit_ok(&hs, &got["commit"]).unwrap();
        }
        // Without the header, or one asking no MAC of the method's profile:
        // no MAC, and Vary all the same.
        for h in [None, Some(""), Some(record_ask.as_str())] {
            for (n, p) in [
                ("getLatestCommit", &repo_p[..]),
                ("listRepoOps", &repo_p[..]),
            ] {
                let headers: Vec<(&str, &str)> =
                    h.map(|h| ("accept-signature", h)).into_iter().collect();
                let (code, _, hs) = send(&s, &nsid(n), Some(&t), p, "", &headers).await;
                assert_eq!(code, 200);
                assert!(no_mac(&hs), "{n} {h:?} {hs:?}");
            }
        }
        let (_, _, hs) = send(
            &s,
            &nsid("getRecord"),
            Some(&t),
            &record_p,
            "",
            &[("accept-signature", &commit_ask)],
        )
        .await;
        assert!(no_mac(&hs));
        // A header refused is InvalidSpaceMac, even where nothing is found,
        // and before a cursor.
        let k1 = "did:key:zQ3shokFTS3brHcDQrn82RUDfCZESWL1ZdCEJwekUDPQiYBme";
        let c = "atproto-space-commit";
        let bad = [
            "not a dictionary (".to_string(),
            format!("{commit_ask}, sig={}", &commit_ask[4..]),
            format!(r#"mac=("{c}");keyid="{share}";tag="{c}""#),
            format!(r#"mac=("{c}";sf "signature");keyid="{share}";tag="{c}""#),
            format!(r#"mac=("{c}";sf);keyid="{share}";tag="{c}";alg="ecdsa-p256-sha256""#),
            format!(r#"mac=("{c}";sf);keyid="{share}";tag="{c}";created=1"#),
            format!(r#"mac=("{c}";sf);tag="{c}""#),
            format!(r#"mac=("{c}";sf);keyid="{k1}";tag="{c}""#),
        ];
        for h in &bad {
            for p in [
                &repo_p[..],
                &[("space", OTHER), ("repo", alice.as_str())][..],
                &[("space", SPACE), ("repo", alice.as_str()), ("cursor", "x")][..],
            ] {
                for n in ["getLatestCommit", "listRepoOps", "getRepo"] {
                    if n == "getRepo" && p.len() > 2 {
                        continue;
                    }
                    let got = send_raw(&s, &nsid(n), Some(&t), p, b"", &[("accept-signature", h)])
                        .await
                        .err();
                    assert_eq!(got, Some((400, "InvalidSpaceMac".into())), "{n} {h}");
                }
            }
        }
        // The repo is checked first.
        let bobs = [
            ("space", SPACE),
            ("repo", "did:plc:nobodyatall00000000000000"),
        ];
        assert_eq!(
            send(
                &s,
                &nsid("getLatestCommit"),
                Some(&t),
                &bobs,
                "",
                &[("accept-signature", "(")]
            )
            .await
            .1["error"],
            "RepoNotFound"
        );
        // Several lines are one Dictionary, as RFC 9651 joins them; another
        // label and an `alg` are taken.
        let sig = format!(r#"sig=("{c}";sf);keyid="{share}";tag="{c}";alg="hmac-sha256""#);
        let (_, got, hs) = send(
            &s,
            &nsid("getLatestCommit"),
            Some(&t),
            &repo_p,
            "",
            &[
                ("accept-signature", "other=(\"x\")"),
                ("accept-signature", &sig),
            ],
        )
        .await;
        commit_ok(&hs, &got["commit"]).unwrap();
        assert!(header(&hs, "signature-input").unwrap().starts_with("sig=("));
        // listRecords and listSpaces ignore the header.
        for (n, p) in [("listRecords", &repo_p[..]), ("listSpaces", &[][..])] {
            let (code, _, hs) =
                send(&s, &nsid(n), Some(&t), p, "", &[("accept-signature", "(")]).await;
            assert_eq!((code, hs), (200, vec![]), "{n}");
        }
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// `on_commit` hears of each commit once its own frame is durable. Other
    /// hooks (`space_notify`'s) may log frames of their own after it before
    /// this one hears, so what is durable is held to the commit's frame,
    /// found in the log afterwards, not to whatever was written last.
    #[tokio::test]
    async fn on_commit_hears_each_durable_commit() {
        let plc = plc().await;
        let dir = scratch("space-hook");
        let s = open(&dir, &plc);
        let (alice, t) = create(&s, "alice").await;
        // Each commit heard, with the last frame durable when it was heard.
        let heard: Arc<Mutex<Vec<(Commit, u64)>>> = Arc::default();
        let h = heard.clone();
        s.space_hooks.on_commit(Box::new(move |svc, c| {
            let a = svc.account(&c.repo).unwrap();
            let st = read(&a.store);
            let durable = (0..=st.wal.written())
                .rev()
                .find(|n| st.wal.is_durable(*n))
                .unwrap();
            h.lock().unwrap().push((c.clone(), durable));
        }));
        let body = |rkey: &str| json!({ "space": SPACE, "repo": alice, "collection": "a.b.c", "rkey": rkey, "record": {} });
        let mut want = Vec::new();
        let committed = |s: Shared, t: String, alice: String| async move {
            let c = latest(&s, &t, &alice, SPACE).await["commit"].clone();
            let data: [u8; 32] = STANDARD_NO_PAD
                .decode(c["data"]["$bytes"].as_str().unwrap())
                .unwrap()
                .try_into()
                .unwrap();
            Commit {
                repo: alice,
                space: SPACE.into(),
                rev: c["rev"].as_str().unwrap().into(),
                data,
            }
        };
        w(&s, "createRecord", &t, body("a")).await.unwrap();
        want.push(committed(s.clone(), t.clone(), alice.clone()).await);
        w(&s, "putRecord", &t, body("a")).await.unwrap();
        want.push(committed(s.clone(), t.clone(), alice.clone()).await);
        // None for a write that makes no commit, or is refused.
        w(
            &s,
            "deleteRecord",
            &t,
            json!({ "space": SPACE, "repo": alice, "collection": "a.b.c", "rkey": "none" }),
        )
        .await
        .unwrap();
        w(
            &s,
            "applyWrites",
            &t,
            json!({ "space": SPACE, "repo": alice, "writes": [] }),
        )
        .await
        .unwrap();
        assert!(w(&s, "createRecord", &t, body("a")).await.is_err());
        w(
            &s,
            "clearRecords",
            &t,
            json!({ "space": OTHER, "repo": alice }),
        )
        .await
        .unwrap();
        let writes = json!([{ "$type": "com.atproto.space.applyWrites#create", "collection": "a.b.c", "rkey": "b", "value": {} }]);
        w(
            &s,
            "applyWrites",
            &t,
            json!({ "space": SPACE, "repo": alice, "writes": writes }),
        )
        .await
        .unwrap();
        want.push(committed(s.clone(), t.clone(), alice.clone()).await);
        w(
            &s,
            "deleteRecord",
            &t,
            json!({ "space": SPACE, "repo": alice, "collection": "a.b.c", "rkey": "b" }),
        )
        .await
        .unwrap();
        want.push(committed(s.clone(), t.clone(), alice.clone()).await);
        w(
            &s,
            "clearRecords",
            &t,
            json!({ "space": SPACE, "repo": alice }),
        )
        .await
        .unwrap();
        want.push(committed(s.clone(), t.clone(), alice.clone()).await);
        let heard = heard.lock().unwrap().clone();
        assert_eq!(
            heard.iter().map(|(c, _)| c.clone()).collect::<Vec<_>>(),
            want
        );
        // Each commit's frame, by its number: the log's frames since it was
        // opened are numbered from 1, those before it not at all.
        let frames = {
            let a = s.account(&alice).unwrap();
            let st = read(&a.store);
            let frames =
                pds_store::scan(&std::fs::read(crate::log::repo_log(&dir, &alice)).unwrap())
                    .unwrap()
                    .0;
            let before = frames.len() as u64 - st.wal.written();
            frames
                .into_iter()
                .zip(1u64..)
                .map(move |(f, i)| (f, i.checked_sub(before)))
                .collect::<Vec<_>>()
        };
        for (c, durable) in &heard {
            let at = frames
                .iter()
                .find(|(f, _)| {
                    f.iter()
                        .any(|e| e["t"] == ENTRY && e["rev"] == c.rev.as_str())
                })
                .and_then(|(_, n)| *n);
            let at = at
                .unwrap_or_else(|| panic!("no frame since the log was opened of commit {}", c.rev));
            assert!(
                at <= *durable,
                "commit {} in frame {at}, heard with frames to {durable} durable",
                c.rev
            );
        }
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// A space repo's URI, rev, data, records, operation log and the blobs its
    /// records reference, as `snapshot` gives them.
    pub(crate) type Snapshot = (
        String,
        String,
        String,
        Vec<(String, Vec<u8>)>,
        Vec<String>,
        String,
    );

    /// Everything a store's space repos hold, to compare across a restart:
    /// each repo's commit, records, operation log and the blobs its records
    /// reference, read from the store's table and log. What it holds in
    /// memory of each is checked to be what those make: its counts, its
    /// hash, and across them all, the blobs' count of the records
    /// referencing each CID.
    pub(crate) fn snapshot(st: &Store) -> Vec<Snapshot> {
        let mut counted: BTreeMap<String, u32> = BTreeMap::new();
        let repos = st
            .spaces
            .repos
            .iter()
            .map(|(uri, r)| {
                let records: Vec<(String, Meta, Option<Pos>)> =
                    st.space_records(uri, Unbounded, Unbounded, false).collect();
                let ops = st.space_ops(uri, None, None, usize::MAX);
                let refs: Vec<(String, String, String)> =
                    st.space_view().refs(uri, b"").map(Result::unwrap).collect();
                assert_eq!((records.len() as u64, ops.len() as u64), (r.records, r.ops));
                let mut hash = LtHash::new();
                let mut of_records = Vec::new();
                for (path, meta, _) in &records {
                    hash.add(&element(path, &cid_string(&meta.cid)));
                    for cid in &meta.refs {
                        of_records.push((cid.clone(), path.clone(), meta.rev.clone()));
                    }
                }
                of_records.sort();
                assert_eq!(refs, of_records, "{uri}: the blob references");
                assert!(hash == r.hash && hash.digest() == r.data, "{uri}: the hash");
                for (cid, _, _) in &refs {
                    *counted.entry(cid.clone()).or_default() += 1;
                }
                let bytes = |(path, meta, pos): &(String, Meta, Option<Pos>)| {
                    let b = st.disk.space_bytes(&st.ctx.blocks, uri, path, meta, *pos);
                    assert_eq!(pds_repo::data::cid_of(0x71, &b), meta.cid);
                    (path.clone(), b.to_vec())
                };
                (
                    uri.clone(),
                    r.rev.clone(),
                    hex::encode(r.data),
                    records.iter().map(bytes).collect(),
                    ops.iter().map(|o| format!("{o:?}")).collect(),
                    format!(
                        "{:?}",
                        (refs, records.iter().map(|r| &r.1.rev).collect::<Vec<_>>())
                    ),
                )
            })
            .collect();
        let held: BTreeMap<String, u32> = st
            .blobs
            .space_ref_list()
            .into_iter()
            .map(|(cid, n)| (cid.to_string(), n))
            .collect();
        assert_eq!(
            held, counted,
            "the blobs' count of the space repos' references"
        );
        repos
    }

    #[tokio::test]
    async fn a_restart_keeps_every_space_repo() {
        let plc = plc().await;
        let dir = scratch("space-restart");
        let s = open(&dir, &plc);
        let (alice, t) = create(&s, "alice").await;
        let (bob, tb) = create(&s, "bob").await;
        for (did, token) in [(&alice, &t), (&bob, &tb)] {
            for space in [SPACE, OTHER] {
                let writes: Vec<Json> =
                    (0..5).map(|i| json!({ "$type": "com.atproto.space.applyWrites#create", "collection": "a.b.c", "value": record(i) })).collect();
                w(
                    &s,
                    "applyWrites",
                    token,
                    json!({ "space": space, "repo": did, "writes": writes }),
                )
                .await
                .unwrap();
                w(&s, "putRecord", token, json!({ "space": space, "repo": did, "collection": "x.y.z", "rkey": "p", "record": {} })).await.unwrap();
            }
        }
        w(
            &s,
            "clearRecords",
            &t,
            json!({ "space": OTHER, "repo": alice }),
        )
        .await
        .unwrap();
        public_repo_write(&s, &alice, &t).await;
        let state =
            |s: &Service| [&alice, &bob].map(|d| snapshot(&read(&s.account(d).unwrap().store)));
        let before = state(&s);
        let revs: Vec<String> = before.iter().flatten().map(|r| r.1.clone()).collect();
        crate::space_notify::tests::idle(&s).await;
        drop(s);
        let s = open(&dir, &plc);
        assert_eq!(state(&s), before);
        // Each repo's next commit is later than every one before.
        for (did, token) in [(&alice, &t), (&bob, &tb)] {
            for space in [SPACE, OTHER] {
                let got = w(
                    &s,
                    "createRecord",
                    token,
                    json!({ "space": space, "repo": did, "collection": "a.b.c", "record": {} }),
                )
                .await
                .unwrap();
                let rev = commit_rev(&latest(&s, token, did, space).await);
                assert!(revs.iter().all(|r| rev > *r), "{rev}");
                let rkey = got["uri"]
                    .as_str()
                    .unwrap()
                    .rsplit('/')
                    .next()
                    .unwrap()
                    .to_string();
                assert!(valid_tid(&rkey));
            }
        }
        let after = state(&s);
        crate::space_notify::tests::idle(&s).await;
        drop(s);
        assert_eq!(state(&open(&dir, &plc)), after);
        let _ = std::fs::remove_dir_all(&dir);
    }

    async fn public_repo_write(s: &Shared, did: &str, token: &str) {
        let body =
            json!({ "repo": did, "collection": "a.b.c", "rkey": "pub", "record": record(1) });
        call(s, "com.atproto.repo.putRecord", Some(token), body)
            .await
            .unwrap();
    }

    /// A call with a raw body: the answer, or its status and name.
    async fn send_raw(
        s: &Shared,
        nsid: &str,
        token: Option<&str>,
        params: &[(&str, &str)],
        body: &[u8],
        headers: &[(&str, &str)],
    ) -> Result<Resp, (u16, String)> {
        let m = pds_lexicon::method(nsid).unwrap();
        let method = if m.kind == pds_lexicon::Kind::Query {
            Http::GET
        } else {
            Http::POST
        };
        let mut h = HeaderMap::new();
        for (k, v) in headers {
            h.append(
                HeaderName::from_bytes(k.as_bytes()).unwrap(),
                HeaderValue::from_str(v).unwrap(),
            );
        }
        let params: Vec<(String, String)> = params
            .iter()
            .map(|(k, v)| (k.to_string(), v.to_string()))
            .collect();
        let bearer = token.map_or(
            crate::sessions::Bearer::None,
            crate::sessions::Bearer::Token,
        );
        crate::answer(
            s,
            &Call {
                nsid,
                method: &method,
                params: &params,
                body,
                bearer,
                headers: &h,
                client: "127.0.0.1".into(),
                charged: Default::default(),
                http: None,
            },
        )
        .await
        .map_err(|e| (e.status, e.name.to_string()))
    }

    const STAR: (&str, &str) = ("content-type", "application/vnd.dasl.star");

    async fn get_repo_of(
        s: &Shared,
        token: &str,
        did: &str,
        space: &str,
    ) -> Result<Vec<u8>, String> {
        match send_raw(
            s,
            "com.atproto.space.getRepo",
            Some(token),
            &[("space", space), ("repo", did)],
            b"",
            &[],
        )
        .await
        {
            Ok(Resp::Archive(a, hs)) => {
                assert_eq!(hs, vec![("vary", "Accept-Signature".to_string())]);
                Ok(a.bytes().unwrap())
            }
            Ok(_) => panic!("getRepo answered no archive"),
            Err((_, e)) => Err(e),
        }
    }

    async fn import_repo_of(s: &Shared, token: &str, body: &[u8]) -> Result<(), String> {
        match send_raw(
            s,
            "com.atproto.space.importRepo",
            Some(token),
            &[],
            body,
            &[STAR],
        )
        .await
        {
            Ok(Resp::Nothing) => Ok(()),
            Ok(_) => panic!("importRepo answered something"),
            Err((_, e)) => Err(e),
        }
    }

    /// A space blob as `getBlob` answers it: its type and bytes.
    async fn space_blob(
        s: &Shared,
        token: &str,
        did: &str,
        space: &str,
        cid: &str,
    ) -> Result<(String, Vec<u8>), String> {
        match send_raw(
            s,
            "com.atproto.space.getBlob",
            Some(token),
            &[("space", space), ("repo", did), ("cid", cid)],
            b"",
            &[],
        )
        .await
        {
            Ok(Resp::Blob(b)) => {
                let res = crate::blobs::response(b);
                let mime = res.headers()["content-type"].to_str().unwrap().to_string();
                let bytes = axum::body::to_bytes(res.into_body(), usize::MAX)
                    .await
                    .unwrap()
                    .to_vec();
                Ok((mime, bytes))
            }
            Ok(_) => panic!("getBlob answered no blob"),
            Err((_, e)) => Err(e),
        }
    }

    fn raw_cid(body: &[u8]) -> String {
        cid_string(&pds_repo::data::cid_of(0x55, body))
    }

    fn bref(cid: &str, mime: &str, size: i64) -> Json {
        json!({ "$type": "blob", "ref": { "$link": cid }, "mimeType": mime, "size": size })
    }

    async fn space_cids(
        s: &Shared,
        token: &str,
        did: &str,
        space: &str,
        extra: &[(&str, &str)],
    ) -> Json {
        let mut p = vec![("space", space), ("repo", did)];
        p.extend_from_slice(extra);
        r(s, "listBlobs", token, &p).await.unwrap()
    }

    fn encode_json(j: Json) -> Vec<u8> {
        pds_repo::data::encode(&from_json(&j).unwrap())
    }

    /// Space records' blob refs: checked last, holding blobs as public
    /// records do, served and listed only through the space, and released
    /// with the last record that references them.
    #[tokio::test]
    async fn space_blobs() {
        let plc = plc().await;
        let dir = scratch("space-blobs");
        let s = open(&dir, &plc);
        let (alice, t) = create(&s, "alice").await;
        let (_, tb) = create(&s, "bob").await;
        let up = |token: String, body: &'static [u8], mime: &'static str| {
            let s = s.clone();
            async move {
                crate::blobs::test_upload(&s, Some(&token), Some(mime), body.to_vec(), false)
                    .await
                    .unwrap()
            }
        };
        let (one, two, bobs) = (
            b"spec-pds blob one" as &[u8],
            b"spec-pds blob two" as &[u8],
            b"spec-pds blob bob" as &[u8],
        );
        up(t.clone(), one, "text/plain").await;
        up(t.clone(), two, "text/plain").await;
        up(tb.clone(), bobs, "text/plain").await;
        let (c1, c2, cb) = (raw_cid(one), raw_cid(two), raw_cid(bobs));
        let rec = |img: Json| json!({ "space": SPACE, "repo": alice, "collection": "a.b.c", "rkey": "x", "record": { "img": img } });
        // Refs checked last, against the blobs held before the write.
        let exists = json!({ "space": SPACE, "repo": alice, "collection": "a.b.c", "rkey": "x", "record": {} });
        w(&s, "createRecord", &t, exists).await.unwrap();
        assert_eq!(
            w(
                &s,
                "createRecord",
                &t,
                rec(bref(&raw_cid(b"never"), "text/plain", 5))
            )
            .await,
            Err("RecordAlreadyExists".into())
        );
        for (img, want) in [
            (bref(&raw_cid(b"never"), "text/plain", 5), "BlobNotFound"),
            (bref(&cb, "text/plain", bobs.len() as i64), "BlobNotFound"),
            (bref(&c1, "image/png", one.len() as i64), "InvalidMimeType"),
            (bref(&c1, "text/plain", 3), "InvalidSize"),
        ] {
            assert_eq!(
                w(&s, "putRecord", &t, rec(img)).await,
                Err(want.to_string())
            );
        }
        w(
            &s,
            "putRecord",
            &t,
            rec(bref(&c1, "text/plain", one.len() as i64)),
        )
        .await
        .unwrap();
        // Once referenced, a ref to it is not checked.
        w(&s, "putRecord", &t, json!({ "space": OTHER, "repo": alice, "collection": "a.b.c", "rkey": "y", "record": { "img": bref(&c1, "image/png", 1) } })).await.unwrap();
        // Served and listed through the space, not the public methods.
        assert_eq!(
            space_blob(&s, &t, &alice, SPACE, &c1).await,
            Ok(("text/plain".into(), one.to_vec()))
        );
        assert_eq!(
            space_blob(&s, &t, &alice, SPACE, &c2).await,
            Err("BlobNotFound".into())
        );
        assert_eq!(
            space_cids(&s, &t, &alice, SPACE, &[]).await,
            json!({ "cids": [c1] })
        );
        assert_eq!(
            space_cids(
                &s,
                &t,
                &alice,
                "at://did:web:example.com/space/a.b.c/none",
                &[]
            )
            .await,
            json!({ "cids": [] })
        );
        let public = [
            ("did".to_string(), alice.clone()),
            ("cid".to_string(), c1.clone()),
        ];
        assert_eq!(
            call_with(&s, "com.atproto.sync.getBlob", None, &public, Json::Null).await,
            Err("InvalidRequest".into())
        );
        let listed = call_with(
            &s,
            "com.atproto.sync.listBlobs",
            None,
            &public[..1],
            Json::Null,
        )
        .await
        .unwrap();
        assert_eq!(listed["cids"], json!([]));
        // listBlobs: pages, a cursor only on a full page; a `since` ignored.
        let writes = json!([
            { "$type": "com.atproto.space.applyWrites#create", "collection": "a.b.c", "rkey": "z", "value": { "list": [bref(&c2, "text/plain", two.len() as i64), bref(&c1, "text/plain", 1)] } },
        ]);
        let rev_before = commit_rev(&latest(&s, &t, &alice, SPACE).await);
        w(
            &s,
            "applyWrites",
            &t,
            json!({ "space": SPACE, "repo": alice, "writes": writes }),
        )
        .await
        .unwrap();
        let mut all = vec![c1.clone(), c2.clone()];
        all.sort();
        assert_eq!(
            space_cids(&s, &t, &alice, SPACE, &[]).await,
            json!({ "cids": all })
        );
        assert_eq!(
            space_cids(&s, &t, &alice, SPACE, &[("limit", "1")]).await,
            json!({ "cids": [all[0]], "cursor": all[0] })
        );
        assert_eq!(
            space_cids(
                &s,
                &t,
                &alice,
                SPACE,
                &[("limit", "1"), ("cursor", &all[0])]
            )
            .await,
            json!({ "cids": [all[1]], "cursor": all[1] })
        );
        assert_eq!(
            space_cids(&s, &t, &alice, SPACE, &[("cursor", &all[1])]).await,
            json!({ "cids": [] })
        );
        let rev_now = commit_rev(&latest(&s, &t, &alice, SPACE).await);
        for since in [rev_before.as_str(), rev_now.as_str(), "nonsense"] {
            assert_eq!(
                space_cids(&s, &t, &alice, SPACE, &[("since", since)]).await,
                json!({ "cids": all })
            );
        }
        // A record in a public repo keeps a blob held when the space's go.
        let public_rec = json!({ "repo": alice, "collection": "a.b.c", "rkey": "pub", "record": { "img": bref(&c2, "text/plain", two.len() as i64) } });
        call(&s, "com.atproto.repo.putRecord", Some(&t), public_rec)
            .await
            .unwrap();
        assert_eq!(
            call_with(
                &s,
                "com.atproto.sync.listBlobs",
                None,
                &public[..1],
                Json::Null
            )
            .await
            .unwrap()["cids"],
            json!([c2])
        );
        let state = |s: &Service| {
            let a = s.account(&alice).unwrap();
            let st = read(&a.store);
            (snapshot(&st), st.blobs.snapshot())
        };
        let before = state(&s);
        crate::space_notify::tests::idle(&s).await;
        drop(s);
        let s = open(&dir, &plc);
        assert_eq!(state(&s), before);
        // Deleting the last records that reference a blob stops it being held.
        w(
            &s,
            "clearRecords",
            &t,
            json!({ "space": SPACE, "repo": alice }),
        )
        .await
        .unwrap();
        w(
            &s,
            "deleteRecord",
            &t,
            json!({ "space": OTHER, "repo": alice, "collection": "a.b.c", "rkey": "y" }),
        )
        .await
        .unwrap();
        assert_eq!(
            w(
                &s,
                "putRecord",
                &t,
                rec(bref(&c1, "text/plain", one.len() as i64))
            )
            .await,
            Err("BlobNotFound".into())
        );
        let blob_files = || {
            std::fs::read_dir(crate::blobs::blob_dir(&dir, &alice))
                .unwrap()
                .map(|e| e.unwrap().file_name().into_string().unwrap())
                .collect::<Vec<_>>()
        };
        assert_eq!(blob_files(), vec![c2.clone()]);
        w(&s, "putRecord", &t, rec(bref(&c2, "image/png", 0)))
            .await
            .unwrap();
        let before = state(&s);
        crate::space_notify::tests::idle(&s).await;
        drop(s);
        assert_eq!(state(&open(&dir, &plc)), before);
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// getRepo's archive is spec.mjs's of the commit and records, with the
    /// commit's MAC; importRepo takes it back, refusing each fault in order.
    #[tokio::test]
    async fn whole_repos_and_imports() {
        let plc = plc().await;
        let dir = scratch("space-import");
        let s = open(&dir, &plc);
        let (alice, t) = create(&s, "alice").await;
        let (bob, _) = create(&s, "bob").await;
        for (k, n) in [("b", 2), ("a", 1)] {
            w(&s, "putRecord", &t, json!({ "space": SPACE, "repo": alice, "collection": "a.b.c", "rkey": k, "record": record(n) })).await.unwrap();
        }
        assert_eq!(
            get_repo_of(&s, &t, &alice, OTHER).await,
            Err("RepoNotFound".into())
        );
        let archive = get_repo_of(&s, &t, &alice, SPACE).await.unwrap();
        let c = latest(&s, &t, &alice, SPACE).await["commit"].clone();
        let commit = Commit {
            repo: alice.clone(),
            space: SPACE.into(),
            rev: c["rev"].as_str().unwrap().into(),
            data: STANDARD_NO_PAD
                .decode(c["data"]["$bytes"].as_str().unwrap())
                .unwrap()
                .try_into()
                .unwrap(),
        };
        let bytes = |n: i64| make_record(from_json(&record(n)).unwrap()).bytes;
        assert_eq!(
            archive,
            star::write_repo(
                &commit,
                &[("a.b.c/a".into(), bytes(1)), ("a.b.c/b".into(), bytes(2))]
            )
        );
        // With a MAC, which the archive verifies with.
        let author = s.account(&alice).unwrap().kem.as_ref().unwrap().public();
        let syncer = KemKey::from_bytes(&[7u8; 32]).unwrap();
        let secret = syncer.encapsulate(&author);
        let share = syncer.public().did_key();
        let ask = format!(
            r#"mac=("atproto-space-commit";sf);keyid="{share}";tag="atproto-space-commit""#
        );
        let Ok(Resp::Archive(b, hs)) = send_raw(
            &s,
            "com.atproto.space.getRepo",
            Some(&t),
            &[("space", SPACE), ("repo", &alice)],
            b"",
            &[("accept-signature", &ask)],
        )
        .await
        else {
            panic!()
        };
        let b = b.bytes().unwrap();
        assert_eq!(
            star::read_repo(
                &b,
                SPACE,
                &alice,
                &share,
                &secret,
                &received(&hs, Profile::Commit)
            )
            .unwrap()
            .commit,
            commit
        );
        assert_eq!(
            header(&hs, "access-control-expose-headers"),
            Some("atproto-space-commit, signature-input, signature")
        );
        // Imported back: the same records, a later rev, an empty log.
        import_repo_of(&s, &t, &archive).await.unwrap();
        let after = latest(&s, &t, &alice, SPACE).await["commit"].clone();
        assert!(after["rev"].as_str() > c["rev"].as_str());
        assert_eq!(after["data"], c["data"]);
        assert_eq!(
            r(&s, "listRepoOps", &t, &[("space", SPACE), ("repo", &alice)])
                .await
                .unwrap()["ops"],
            json!([])
        );
        // An archive with refs to a blob not held: listed, not served until uploaded.
        let held = b"spec-pds import blob";
        let cid = raw_cid(held);
        let value = encode_json(
            json!({ "$type": "a.b.c", "img": bref(&cid, "text/plain", held.len() as i64) }),
        );
        let mut h = LtHash::new();
        h.add(&element(
            "a.b.c/x",
            &cid_string(&pds_repo::data::cid_of(0x71, &value)),
        ));
        let other = Commit {
            repo: alice.clone(),
            space: OTHER.into(),
            rev: "3mzzzzzzzzzz2".into(),
            data: h.digest(),
        };
        import_repo_of(
            &s,
            &t,
            &star::write_repo(&other, &[("a.b.c/x".into(), value.clone())]),
        )
        .await
        .unwrap();
        assert_eq!(
            space_cids(&s, &t, &alice, OTHER, &[]).await,
            json!({ "cids": [cid] })
        );
        assert_eq!(
            space_blob(&s, &t, &alice, OTHER, &cid).await,
            Err("InvalidRequest".into())
        );
        crate::blobs::test_upload(&s, Some(&t), Some("image/x-test"), held.to_vec(), false)
            .await
            .unwrap();
        assert_eq!(
            space_blob(&s, &t, &alice, OTHER, &cid).await,
            Ok(("image/x-test".into(), held.to_vec()))
        );
        assert!(
            r(&s, "listSpaces", &t, &[]).await.unwrap()["spaces"]
                .as_array()
                .unwrap()
                .iter()
                .any(|x| x["space"] == OTHER)
        );
        // Each fault, in order.
        const REV: &str = "3mzzzzzzzzzz2";
        let empty = |space: &str, repo: &str, rev: &str| {
            star::write_repo(
                &Commit {
                    repo: repo.into(),
                    space: space.into(),
                    rev: rev.into(),
                    data: LtHash::new().digest(),
                },
                &[],
            )
        };
        let good = empty(SPACE, &alice, REV);
        assert_eq!(
            send_raw(
                &s,
                "com.atproto.space.importRepo",
                None,
                &[],
                &good,
                &[STAR]
            )
            .await
            .err(),
            Some((401, "AuthMissing".into()))
        );
        let app = {
            let p = call(
                &s,
                "com.atproto.server.createAppPassword",
                Some(&t),
                json!({ "name": "x" }),
            )
            .await
            .unwrap();
            call(
                &s,
                "com.atproto.server.createSession",
                None,
                json!({ "identifier": "alice.test", "password": p["password"] }),
            )
            .await
            .unwrap()["accessJwt"]
                .as_str()
                .unwrap()
                .to_string()
        };
        assert_eq!(
            import_repo_of(&s, &app, &good).await,
            Err("InvalidToken".into())
        );
        for ct in [
            vec![],
            vec![("content-type", "application/json")],
            vec![("content-type", "application/octet-stream")],
        ] {
            assert_eq!(
                send_raw(
                    &s,
                    "com.atproto.space.importRepo",
                    Some(&t),
                    &[],
                    &good,
                    &ct
                )
                .await
                .err(),
                Some((400, "InvalidRequest".into()))
            );
        }
        // The media type up to its first `;`, whatever follows.
        send_raw(
            &s,
            "com.atproto.space.importRepo",
            Some(&t),
            &[],
            &empty("at://did:web:example.net/space/a.b.c/ct", &alice, REV),
            &[("content-type", "Application/Vnd.Dasl.Star; x=1")],
        )
        .await
        .unwrap();
        let mut big = good.clone();
        big.resize(5 * 1024 * 1024 + 1, 0);
        assert_eq!(
            send_raw(
                &s,
                "com.atproto.space.importRepo",
                Some(&t),
                &[],
                &big,
                &[STAR]
            )
            .await
            .err(),
            Some((413, "PayloadTooLarge".into()))
        );
        big.pop();
        assert_eq!(
            import_repo_of(&s, &t, &big).await,
            Err("InvalidRepoFile".into())
        );
        let with_value = |space: &str, repo: &str, v: Vec<u8>| {
            let mut h = LtHash::new();
            h.add(&element(
                "a.b.c/x",
                &cid_string(&pds_repo::data::cid_of(0x71, &v)),
            ));
            star::write_repo(
                &Commit {
                    repo: repo.into(),
                    space: space.into(),
                    rev: REV.into(),
                    data: h.digest(),
                },
                &[("a.b.c/x".into(), v)],
            )
        };
        let not_canonical = vec![0xa2, 0x61, 0x62, 0x02, 0x61, 0x61, 0x01];
        let own = format!("at://{alice}/space/a.b.c/mine");
        for (bad, want) in [
            (vec![], "InvalidRepoFile"),
            (b"hello".to_vec(), "InvalidRepoFile"),
            ([good.clone(), vec![0]].concat(), "InvalidRepoFile"),
            (empty(SPACE, &alice, "x"), "InvalidRepoFile"),
            (empty(SPACE, "alice.test", REV), "InvalidRepoFile"),
            (
                with_value(SPACE, &alice, encode_json(json!([1]))),
                "InvalidRepoFile",
            ),
            // The archive before the repo, the repo before the space, the
            // space before each record's encoding.
            (
                with_value(SPACE, &bob, encode_json(json!([1]))),
                "InvalidRepoFile",
            ),
            (empty(SPACE, &bob, REV), "RepoMismatch"),
            (
                with_value(&own, &bob, not_canonical.clone()),
                "RepoMismatch",
            ),
            (
                with_value(&own, &alice, not_canonical.clone()),
                "SpaceNotFound",
            ),
            (empty(&own, &alice, REV), "SpaceNotFound"),
            (with_value(SPACE, &alice, not_canonical), "InvalidRepoFile"),
        ] {
            assert_eq!(import_repo_of(&s, &t, &bad).await, Err(want.into()));
        }
        // A restart keeps every import.
        let state = |s: &Service| {
            let a = s.account(&alice).unwrap();
            let st = read(&a.store);
            (snapshot(&st), st.blobs.snapshot())
        };
        let before = state(&s);
        crate::space_notify::tests::idle(&s).await;
        drop(s);
        let s = open(&dir, &plc);
        assert_eq!(state(&s), before);
        let now = latest(&s, &t, &alice, SPACE).await["commit"].clone();
        let commit = Commit {
            rev: now["rev"].as_str().unwrap().into(),
            ..commit
        };
        assert_eq!(
            get_repo_of(&s, &t, &alice, SPACE).await.unwrap(),
            star::write_repo(
                &commit,
                &[("a.b.c/a".into(), bytes(1)), ("a.b.c/b".into(), bytes(2))]
            )
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// An archive's records are kept as their bytes where JSON would write
    /// one as another value: a blob ref whose `ref` is a map of the one key
    /// `$link`, a CID string, which JSON writes as a link; a map of
    /// `$bytes`; a `$link` that is no CID. `getRepo` answers each byte for
    /// byte, read from the log, from the table it is compacted into, and
    /// through a restart, and the blob such a `ref` names is the repo's.
    #[tokio::test]
    async fn imports_keep_each_record_as_its_bytes() {
        let plc = plc().await;
        let dir = scratch("space-import-bytes");
        let s = open(&dir, &plc);
        let (alice, t) = create(&s, "alice").await;
        let cid = raw_cid(b"spec-pds import blob");
        let text = |t: &str| V::Str(t.into());
        let map =
            |kv: &[(&str, V)]| V::Map(kv.iter().map(|(k, v)| (k.to_string(), v.clone())).collect());
        let rec = |field: &str, v: V| map(&[("$type", text("a.b.c")), (field, v)]);
        let icon = map(&[
            ("$type", text("blob")),
            ("ref", map(&[("$link", text(&cid))])),
            ("mimeType", text("text/plain")),
            ("size", V::Int(20)),
        ]);
        let records: Vec<(String, Vec<u8>)> = [
            ("a.b.c/bytes", rec("b", map(&[("$bytes", text("AQID"))]))),
            ("a.b.c/icon", rec("icon", icon)),
            ("a.b.c/odd", rec("l", map(&[("$link", text("not a cid"))]))),
        ]
        .into_iter()
        .map(|(p, v)| (p.to_string(), pds_repo::data::encode(&v)))
        .collect();
        let mut h = LtHash::new();
        for (p, v) in &records {
            h.add(&element(p, &cid_string(&pds_repo::data::cid_of(0x71, v))));
        }
        let commit = Commit {
            repo: alice.clone(),
            space: OTHER.into(),
            rev: "3mzzzzzzzzzz2".into(),
            data: h.digest(),
        };
        import_repo_of(&s, &t, &star::write_repo(&commit, &records))
            .await
            .unwrap();
        let held = |s: &Shared| {
            let (s, t, alice) = (s.clone(), t.clone(), alice.clone());
            async move {
                let archive = get_repo_of(&s, &t, &alice, OTHER).await.unwrap();
                star::read_any_repo(&archive).unwrap().records
            }
        };
        let cids = json!({ "cids": [cid] });
        assert_eq!(held(&s).await, records, "from the log");
        assert_eq!(space_cids(&s, &t, &alice, OTHER, &[]).await, cids);
        compact(&s, &alice);
        assert_eq!(held(&s).await, records, "from the table");
        crate::space_notify::tests::idle(&s).await;
        drop(s);
        let s = open(&dir, &plc);
        assert_eq!(held(&s).await, records, "through a restart");
        assert_eq!(space_cids(&s, &t, &alice, OTHER, &[]).await, cids);
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn a_commit_that_does_not_add_up_is_refused() {
        let cache = BlockCache::new(1 << 20);
        let pos = Pos {
            generation: 0,
            offset: 0,
            len: 0,
        };
        // A store's space repos with no table, replaying entries one by one.
        #[derive(Default)]
        struct Replayed(Spaces, SpaceMem, blobs::Blobs);
        let mut tids = Tids::new();
        let mut replay = |r: &mut Replayed, e: &Json| {
            r.0.replay(e, pos, &mut r.1, Old::None, &cache, &mut tids, &mut r.2)
        };
        let rec = make_record(from_json(&json!({ "$type": "a.b.c" })).unwrap());
        let mut h = LtHash::new();
        h.add(&element("a.b.c/k", &cid_string(&rec.cid)));
        let entry = |data: [u8; 32], rev: &str| {
            let c = Change {
                space: SPACE.into(),
                rev: rev.into(),
                ops: vec![],
                puts: vec![("a.b.c/k".into(), make_record(rec.value.clone()))],
                dels: vec![],
                clear: false,
                kept: None,
            };
            let mut e = c.entry();
            e["data"] = json!(hex::encode(data));
            e
        };
        let mut r = Replayed::default();
        assert!(
            replay(&mut r, &entry(LtHash::new().digest(), "3l3s4fxs7ft22"))
                .unwrap_err()
                .contains("do not make")
        );
        let mut r = Replayed::default();
        replay(&mut r, &entry(h.digest(), "3l3s4fxs7ft22")).unwrap();
        assert!(
            replay(&mut r, &entry(h.digest(), "3l3s4fxs7ft22"))
                .unwrap_err()
                .contains("out of order")
        );
        // The same record put again leaves the same data, read from the memtable.
        replay(&mut r, &entry(h.digest(), "3l3s4fxs7ft23")).unwrap();
        assert_eq!(r.0.get(SPACE).unwrap().records, 1);
        for bad in [
            json!({ "t": "space" }),
            json!({ "t": "space", "space": "nope", "rev": "3l3s4fxs7ft23", "data": "00", "clear": false, "ops": [], "puts": [], "dels": [] }),
            // A commit that keeps records names none.
            json!({ "t": "space", "space": SPACE, "rev": "3l3s4fxs7ft26", "data": hex::encode(h.digest()), "clear": false, "kept": [], "ops": [], "puts": [], "dels": [] }),
            json!({ "t": "space", "space": SPACE, "rev": "3l3s4fxs7ft26", "data": hex::encode(h.digest()), "clear": true, "kept": [], "ops": [], "puts": [], "dels": ["a.b.c/k"] }),
        ] {
            assert!(replay(&mut Replayed::default(), &bad).is_err(), "{bad}");
        }
        // A commit that keeps none deletes every record, and one that keeps
        // a prefix the records under it: each must make its data.
        let clear = |kept: &[&str], data: [u8; 32], rev: &str| json!({ "t": "space", "space": SPACE, "rev": rev, "data": hex::encode(data), "clear": true, "kept": kept, "ops": [], "puts": [], "dels": [] });
        assert!(
            replay(&mut r, &clear(&[], h.digest(), "3l3s4fxs7ft27"))
                .unwrap_err()
                .contains("do not make")
        );
        replay(&mut r, &clear(&["a.b.c/"], h.digest(), "3l3s4fxs7ft27")).unwrap();
        assert_eq!(r.0.get(SPACE).unwrap().records, 1);
        replay(
            &mut r,
            &clear(&["x.y.z/"], LtHash::new().digest(), "3l3s4fxs7ft2a"),
        )
        .unwrap();
        assert_eq!(r.0.get(SPACE).unwrap().records, 0);
        assert!(r.1.records.is_empty());
        // An import whose records do not make its data, or out of order.
        let import = |data: [u8; 32], rev: &str| {
            Import {
                space: SPACE.into(),
                rev: rev.into(),
                records: vec![("a.b.c/k".into(), make_record(rec.value.clone()))],
            }
            .entry(&data)
        };
        let mut r = Replayed::default();
        assert!(
            replay(&mut r, &import(LtHash::new().digest(), "3l3s4fxs7ft24"))
                .unwrap_err()
                .contains("do not make")
        );
        let mut r = Replayed::default();
        replay(&mut r, &import(h.digest(), "3l3s4fxs7ft24")).unwrap();
        assert!(
            replay(&mut r, &import(h.digest(), "3l3s4fxs7ft24"))
                .unwrap_err()
                .contains("out of order")
        );
        let unordered = json!({ "t": IMPORT, "space": SPACE, "rev": "3l3s4fxs7ft25", "data": hex::encode(h.digest()), "records": [["a.b.c/l", {}], ["a.b.c/k", {}]] });
        assert!(
            replay(&mut Replayed::default(), &unordered)
                .unwrap_err()
                .contains("order")
        );
        // A repo dropped that there is not.
        let dropped = json!({ "t": DROP, "space": SPACE });
        assert!(replay(&mut Replayed::default(), &dropped).is_err());
        replay(&mut r, &dropped).unwrap();
        assert!(r.0.get(SPACE).is_none() && r.1.records.is_empty());
        // Later TIDs follow every rev replayed.
        assert!(tids.next_tid().as_str() > "3l3s4fxs7ft22");
    }

    /// What a read of `did`'s repo in `space` answers, or its error's name.
    async fn ask(
        s: &Shared,
        name: &str,
        token: &str,
        did: &str,
        space: &str,
        extra: &[(&str, &str)],
    ) -> Json {
        let mut p = vec![("space", space), ("repo", did)];
        p.extend_from_slice(extra);
        match r(s, name, token, &p).await {
            Ok(j) => j,
            Err(e) => json!({ "error": e }),
        }
    }

    /// Every item of a list, `limit` at a time, by the cursors answered.
    #[allow(clippy::too_many_arguments)]
    async fn paged(
        s: &Shared,
        name: &str,
        token: &str,
        did: &str,
        space: &str,
        extra: &[(&str, &str)],
        field: &str,
        limit: usize,
    ) -> Vec<Json> {
        let (mut out, mut cursor): (Vec<Json>, Option<String>) = (Vec::new(), None);
        let limit_text = limit.to_string();
        loop {
            let mut p = extra.to_vec();
            p.push(("limit", &limit_text));
            if let Some(c) = &cursor {
                p.push(("cursor", c));
            }
            let page = ask(s, name, token, did, space, &p).await;
            // A refusal, as `listRepoOps` of no repo, is the one item.
            if page.get("error").is_some() {
                assert!(out.is_empty(), "{page}");
                return vec![page];
            }
            let items = page[field].as_array().unwrap_or_else(|| panic!("{page}"));
            assert!(items.len() <= limit);
            out.extend(items.iter().cloned());
            match page["cursor"].as_str() {
                Some(c) => {
                    assert_eq!(items.len(), limit, "{page}");
                    cursor = Some(c.to_string());
                }
                None => return out,
            }
        }
    }

    /// What every read of `did`'s repo in `space` answers: the latest
    /// commit; the records whole, by collection, and page by page, with
    /// their values and without; each record, and one there is not; the
    /// operations whole, page by page, and after each rev; the blobs whole
    /// and one at a time; each blob, and one not referenced; and the repo
    /// whole. The pages are checked to make the whole, and the repo to be
    /// its records' archive.
    async fn answers(s: &Shared, token: &str, did: &str, space: &str) -> Vec<Json> {
        let commit = ask(s, "getLatestCommit", token, did, space, &[]).await;
        let whole = [("limit", "1000")];
        let all = ask(s, "listRecords", token, did, space, &whole).await;
        let records = all["records"].as_array().unwrap().clone();
        let mut out = vec![commit.clone(), all];
        for exclude in ["false", "true"] {
            let extra = [("excludeValues", exclude)];
            let pages = paged(s, "listRecords", token, did, space, &extra, "records", 3).await;
            out.push(json!(pages));
            if exclude == "true" {
                assert!(pages.iter().all(|r| r.get("value").is_none()));
                let cids = |l: &[Json]| l.iter().map(|r| r["cid"].clone()).collect::<Vec<_>>();
                assert_eq!(cids(&pages), cids(&records));
            } else {
                assert_eq!(pages, records);
            }
        }
        let collections: BTreeSet<&str> = records
            .iter()
            .map(|r| r["collection"].as_str().unwrap())
            .chain(["none.at.all"])
            .collect();
        for c in collections {
            let extra = [("collection", c)];
            let of = paged(s, "listRecords", token, did, space, &extra, "records", 2).await;
            out.push(json!(of));
            let want: Vec<Json> = records
                .iter()
                .filter(|r| r["collection"] == c)
                .cloned()
                .collect();
            assert_eq!(of, want, "{c}");
        }
        let key = |r: &Json| {
            (
                r["collection"].as_str().unwrap().to_string(),
                r["rkey"].as_str().unwrap().to_string(),
            )
        };
        for rec in &records {
            let (c, k) = key(rec);
            let got = ask(
                s,
                "getRecord",
                token,
                did,
                space,
                &[("collection", &c), ("rkey", &k)],
            )
            .await;
            assert_eq!((&got["cid"], &got["value"]), (&rec["cid"], &rec["value"]));
            out.push(got);
        }
        let none = [("collection", "a.b.c"), ("rkey", "never-written")];
        out.push(ask(s, "getRecord", token, did, space, &none).await);
        // The operations.
        let ops = paged(s, "listRepoOps", token, did, space, &[], "ops", 1000).await;
        out.push(json!(ops));
        for extra in [vec![], vec![("excludeValues", "true")]] {
            let pages = paged(s, "listRepoOps", token, did, space, &extra, "ops", 3).await;
            if extra.is_empty() {
                assert_eq!(pages, ops);
            }
            out.push(json!(pages));
        }
        let mut revs: BTreeSet<String> = ops
            .iter()
            .chain(std::iter::once(&commit["commit"]))
            .filter_map(|o| o["rev"].as_str().map(str::to_string))
            .collect();
        revs.insert("2222222222222".into());
        for rev in &revs {
            let after = paged(
                s,
                "listRepoOps",
                token,
                did,
                space,
                &[("since", rev)],
                "ops",
                2,
            )
            .await;
            let want: Vec<Json> = ops
                .iter()
                .filter(|o| o["rev"].as_str().is_none_or(|r| r > rev.as_str()))
                .cloned()
                .collect();
            assert_eq!(after, want, "since {rev}");
            out.push(json!(after));
        }
        // The blobs.
        let cids = paged(s, "listBlobs", token, did, space, &[], "cids", 1000).await;
        assert_eq!(
            paged(s, "listBlobs", token, did, space, &[], "cids", 1).await,
            cids
        );
        out.push(json!(cids));
        assert_eq!(
            paged(
                s,
                "listBlobs",
                token,
                did,
                space,
                &[("since", "2222222222222")],
                "cids",
                1
            )
            .await,
            cids
        );
        for cid in cids
            .iter()
            .map(|c| c.as_str().unwrap())
            .chain([raw_cid(b"no blob").as_str()])
        {
            out.push(match space_blob(s, token, did, space, cid).await {
                Ok((mime, bytes)) => json!([mime, hex::encode(bytes)]),
                Err(e) => json!({ "error": e }),
            });
        }
        // The repo whole.
        match get_repo_of(s, token, did, space).await {
            Err(e) => out.push(json!({ "error": e })),
            Ok(archive) => {
                let c = &commit["commit"];
                let commit = Commit {
                    repo: did.into(),
                    space: space.into(),
                    rev: c["rev"].as_str().unwrap().into(),
                    data: STANDARD_NO_PAD
                        .decode(c["data"]["$bytes"].as_str().unwrap())
                        .unwrap()
                        .try_into()
                        .unwrap(),
                };
                let held: Vec<(String, Vec<u8>)> = records
                    .iter()
                    .map(|r| {
                        let (c, k) = key(r);
                        (format!("{c}/{k}"), encode_json(r["value"].clone()))
                    })
                    .collect();
                assert_eq!(archive, star::write_repo(&commit, &held));
                out.push(json!(hex::encode(archive)));
            }
        }
        out
    }

    /// Let go of `did`'s store, once what its log has is on disk and
    /// nothing of it is in flight.
    async fn let_go(s: &Shared, did: &str) {
        let wal = store_of(s, did, |st| st.wal.clone());
        wal.wait(wal.written()).unwrap();
        drop(wal);
        for _ in 0..500 {
            if s.account(did).unwrap().store.evict() {
                return;
            }
            tokio::time::sleep(std::time::Duration::from_millis(10)).await;
        }
        panic!("the store of {did} is never let go");
    }

    /// Compact the log of `did`'s store now: what it held of the log is in
    /// its table after.
    fn compact(s: &Shared, did: &str) {
        let wal = store_of(s, did, |st| st.wal.clone());
        wal.wait_compacted();
        wal.compact().unwrap();
        wal.wait(wal.written()).unwrap();
        drop(wal);
        store_of(s, did, |st| {
            let m = &st.disk.mem.spaces;
            assert!(st.disk.table.is_some());
            assert!(m.records.is_empty() && m.commits.is_empty() && m.refs.is_empty());
            assert!(m.voids.is_empty());
        });
    }

    /// Every space read answers the same from the log alone, from the table
    /// alone, and from a table with a log after it that writes over it,
    /// deletes from it and clears it: across compactions, the store let go
    /// and loaded again, and the server started again. A space whose URI
    /// another's begins with keeps its own.
    #[tokio::test]
    async fn reads_are_the_same_from_the_log_and_the_table() {
        let plc = plc().await;
        let dir = scratch("space-sections");
        let opened = || open_with(&dir, &plc, |c| c.load_all = false);
        let mut s = opened();
        let (did, t) = create(&s, "alice").await;
        let near = format!("{SPACE}2");
        let (one, two) = (
            b"spec-pds sections one" as &[u8],
            b"spec-pds sections two" as &[u8],
        );
        for b in [one, two] {
            crate::blobs::test_upload(&s, Some(&t), Some("text/plain"), b.to_vec(), false)
                .await
                .unwrap();
        }
        let img = |b: &[u8]| bref(&raw_cid(b), "text/plain", b.len() as i64);
        let put = |space: &str, collection: &str, rkey: &str, record: Json| json!({ "space": space, "repo": did, "collection": collection, "rkey": rkey, "record": record });
        let all = |s: &Shared| {
            let (s, t, did, near) = (s.clone(), t.clone(), did.clone(), near.clone());
            async move {
                let got = [
                    answers(&s, &t, &did, SPACE).await,
                    answers(&s, &t, &did, &near).await,
                    answers(&s, &t, &did, OTHER).await,
                ];
                // What is held in memory is what the table and the log make.
                store_of(&s, &did, |st| drop(snapshot(st)));
                got
            }
        };
        // The same, the store let go and loaded, and the server started again.
        macro_rules! everywhere {
            ($want:expr, $why:expr) => {
                assert!(all(&s).await == $want, "{}", $why);
                let_go(&s, &did).await;
                assert!(all(&s).await == $want, "{}, loaded again", $why);
                crate::space_notify::tests::idle(&s).await;
                drop(s);
                s = opened();
                assert!(all(&s).await == $want, "{}, started again", $why);
            };
        }
        // In the log alone.
        let creates: Vec<Json> = (1..=7)
            .map(|i| json!({ "$type": "com.atproto.space.applyWrites#create", "collection": "a.b.c", "rkey": format!("k{i}"), "value": record(i) }))
            .collect();
        w(
            &s,
            "applyWrites",
            &t,
            json!({ "space": SPACE, "repo": did, "writes": creates }),
        )
        .await
        .unwrap();
        w(
            &s,
            "putRecord",
            &t,
            put(SPACE, "x.y.z", "p", json!({ "img": img(one) })),
        )
        .await
        .unwrap();
        w(
            &s,
            "putRecord",
            &t,
            put(
                SPACE,
                "a.b.c",
                "img",
                json!({ "imgs": [img(one), img(two)] }),
            ),
        )
        .await
        .unwrap();
        w(&s, "putRecord", &t, put(SPACE, "a.b.c", "k2", record(20)))
            .await
            .unwrap();
        w(
            &s,
            "deleteRecord",
            &t,
            json!({ "space": SPACE, "repo": did, "collection": "a.b.c", "rkey": "k3" }),
        )
        .await
        .unwrap();
        w(&s, "putRecord", &t, put(&near, "a.b.c", "k1", record(100)))
            .await
            .unwrap();
        w(
            &s,
            "putRecord",
            &t,
            put(&near, "x.y.z", "q", json!({ "img": img(two) })),
        )
        .await
        .unwrap();
        store_of(&s, &did, |st| {
            assert!(st.disk.table.is_none() && st.disk.mem.spaces.records.len() == 11);
        });
        let logged = all(&s).await;
        assert_eq!(logged[0][1]["records"].as_array().unwrap().len(), 8);
        assert_eq!(logged[1][1]["records"].as_array().unwrap().len(), 2);
        everywhere!(logged, "in the log alone");
        // In the table alone.
        compact(&s, &did);
        everywhere!(logged, "in the table alone");
        // A log that writes over the table's, deletes from it and adds to it.
        w(&s, "putRecord", &t, put(SPACE, "a.b.c", "k1", record(11)))
            .await
            .unwrap();
        w(
            &s,
            "deleteRecord",
            &t,
            json!({ "space": SPACE, "repo": did, "collection": "a.b.c", "rkey": "k4" }),
        )
        .await
        .unwrap();
        w(&s, "putRecord", &t, put(SPACE, "a.b.c", "k0", record(0)))
            .await
            .unwrap();
        w(
            &s,
            "putRecord",
            &t,
            put(SPACE, "x.y.z", "p", json!({ "none": true })),
        )
        .await
        .unwrap();
        let writes = json!([
            { "$type": "com.atproto.space.applyWrites#create", "collection": "a.b.c", "rkey": "k8", "value": record(8) },
            { "$type": "com.atproto.space.applyWrites#update", "collection": "a.b.c", "rkey": "k5", "value": record(50) },
            { "$type": "com.atproto.space.applyWrites#delete", "collection": "a.b.c", "rkey": "k6" },
            { "$type": "com.atproto.space.applyWrites#create", "collection": "m.n.o", "rkey": "z", "value": { "img": img(two) } },
        ]);
        w(
            &s,
            "applyWrites",
            &t,
            json!({ "space": SPACE, "repo": did, "writes": writes }),
        )
        .await
        .unwrap();
        w(&s, "putRecord", &t, put(&near, "a.b.c", "k1", record(101)))
            .await
            .unwrap();
        w(&s, "putRecord", &t, put(OTHER, "a.b.c", "first", record(1)))
            .await
            .unwrap();
        let both = all(&s).await;
        assert!(both != logged);
        // The repo whole, taken now and read once it has been written to,
        // compacted and cleared, is the repo as it was when taken.
        let whole = get_repo_of(&s, &t, &did, SPACE).await.unwrap();
        let params = [("space", SPACE), ("repo", did.as_str())];
        let Ok(Resp::Archive(taken, _)) =
            send_raw(&s, "com.atproto.space.getRepo", Some(&t), &params, b"", &[]).await
        else {
            panic!("getRepo answered no archive")
        };
        let paths = |answers: &[Json]| -> Vec<String> {
            answers[1]["records"]
                .as_array()
                .unwrap()
                .iter()
                .map(|r| {
                    format!(
                        "{}/{}",
                        r["collection"].as_str().unwrap(),
                        r["rkey"].as_str().unwrap()
                    )
                })
                .collect()
        };
        // Listed in descending order.
        assert_eq!(
            paths(&both[0]),
            [
                "x.y.z/p",
                "m.n.o/z",
                "a.b.c/k8",
                "a.b.c/k7",
                "a.b.c/k5",
                "a.b.c/k2",
                "a.b.c/k1",
                "a.b.c/k0",
                "a.b.c/img"
            ]
        );
        everywhere!(both, "in the table and the log");
        compact(&s, &did);
        everywhere!(both, "in the next table");
        // A log that clears what the table holds, and writes after.
        w(
            &s,
            "clearRecords",
            &t,
            json!({ "space": SPACE, "repo": did }),
        )
        .await
        .unwrap();
        let cleared = all(&s).await;
        assert!(paths(&cleared[0]).is_empty() && cleared[1] == both[1] && cleared[2] == both[2]);
        everywhere!(cleared, "cleared in the log");
        w(&s, "putRecord", &t, put(SPACE, "a.b.c", "k9", record(9)))
            .await
            .unwrap();
        w(
            &s,
            "putRecord",
            &t,
            put(SPACE, "a.b.c", "k1", json!({ "img": img(two) })),
        )
        .await
        .unwrap();
        let after = all(&s).await;
        assert_eq!(paths(&after[0]), ["a.b.c/k9", "a.b.c/k1"]);
        everywhere!(after, "written after it was cleared");
        compact(&s, &did);
        everywhere!(after, "in the table after it was cleared");
        assert!(taken.bytes().unwrap() == whole);
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// A space repo of thousands of records costs a store no more to hold
    /// than a small one, but for its table's index: its records are in the
    /// table. A load of it reads none of them, and a read after reads those
    /// it answers.
    #[tokio::test]
    async fn a_large_space_repo_is_read_as_it_is_needed() {
        use crate::checkpoint::spaces::tests::READS;
        let plc = plc().await;
        let dir = scratch("space-large");
        // Compacted only when the test says.
        let s = open_with(&dir, &plc, |c| (c.load_all, c.log_floor) = (false, 1 << 30));
        let (did, t) = create(&s, "alice").await;
        let value = |i: usize| json!({ "$type": "a.b.c", "n": i, "pad": "x".repeat(1000) });
        let fill = |from: usize, to: usize| {
            let (s, t, did) = (s.clone(), t.clone(), did.clone());
            async move {
                for at in (from..to).step_by(200) {
                    let writes: Vec<Json> = (at..(at + 200).min(to))
                        .map(|i| json!({ "$type": "com.atproto.space.applyWrites#create", "collection": "a.b.c", "rkey": format!("k{i:05}"), "value": value(i) }))
                        .collect();
                    w(
                        &s,
                        "applyWrites",
                        &t,
                        json!({ "space": SPACE, "repo": did, "writes": writes }),
                    )
                    .await
                    .unwrap();
                }
            }
        };
        // What a store holds, its table's index apart, once loaded afresh.
        let held = |s: &Shared| {
            let (s, did) = (s.clone(), did.clone());
            async move {
                let_go(&s, &did).await;
                READS.set(0);
                store_of(&s, &did, |st| {
                    let table = st.disk.table.as_ref().unwrap().cost();
                    (
                        st.cost() - table,
                        st.spaces.cost(),
                        st.disk.mem.cost(),
                        table,
                    )
                })
            }
        };
        fill(0, 200).await;
        compact(&s, &did);
        let small = held(&s).await;
        assert_eq!(READS.get(), 0, "a load read the table's records");
        fill(200, 4000).await;
        // Uncompacted, the store holds where each record is in the log.
        let logged = store_of(&s, &did, |st| st.cost());
        assert!(logged > small.0 + 3800 * 200, "{logged}");
        compact(&s, &did);
        let large = held(&s).await;
        assert_eq!(READS.get(), 0, "a load read the table's records");
        assert_eq!((large.0, large.1, large.2), (small.0, small.1, small.2));
        // The records are four megabytes: the table's index is a fraction of them.
        assert!(large.3 < 200 * 1024, "{}", large.3);
        // Each read reads what it answers, and little more.
        let reads = |n: u64| {
            let got = READS.replace(0);
            assert!(got <= n, "{got} entries read, more than {n}");
        };
        let got = ask(
            &s,
            "getRecord",
            &t,
            &did,
            SPACE,
            &[("collection", "a.b.c"), ("rkey", "k02000")],
        )
        .await;
        assert_eq!(got["value"]["n"], 2000);
        reads(1);
        let from = format!("{SPACE}/{did}/a.b.c/k01000");
        let extra = [("limit", "10"), ("cursor", from.as_str())];
        let page = ask(&s, "listRecords", &t, &did, SPACE, &extra).await;
        assert_eq!(page["records"][0]["rkey"], "k00999");
        assert_eq!(page["records"].as_array().unwrap().len(), 10);
        reads(12);
        let ops = ask(&s, "listRepoOps", &t, &did, SPACE, &[("limit", "5")]).await;
        let cursor = ops["cursor"].as_str().unwrap().to_string();
        reads(6 + 5);
        let since = ops["ops"][0]["rev"].as_str().unwrap().to_string();
        let extra = [("limit", "5"), ("since", &since), ("excludeValues", "true")];
        let page = ask(&s, "listRepoOps", &t, &did, SPACE, &extra).await;
        assert_eq!(page["ops"][0]["rkey"], "k00200");
        reads(6);
        let extra = [
            ("limit", "5"),
            ("cursor", &cursor),
            ("excludeValues", "true"),
        ];
        let page = ask(&s, "listRepoOps", &t, &did, SPACE, &extra).await;
        assert_eq!(page["ops"][0]["rkey"], "k00005");
        reads(6);
        ask(&s, "getLatestCommit", &t, &did, SPACE, &[]).await;
        reads(0);
        ask(&s, "listBlobs", &t, &did, SPACE, &[]).await;
        reads(1);
        // A write reads the record it replaces, and a load after it the same.
        w(&s, "putRecord", &t, json!({ "space": SPACE, "repo": did, "collection": "a.b.c", "rkey": "k00007", "record": value(7) })).await.unwrap();
        reads(2);
        w(&s, "putRecord", &t, json!({ "space": SPACE, "repo": did, "collection": "a.b.c", "rkey": "new", "record": value(1) })).await.unwrap();
        reads(2);
        let_go(&s, &did).await;
        READS.set(0);
        store_of(&s, &did, |st| {
            assert_eq!(st.spaces.get(SPACE).unwrap().records, 4001)
        });
        reads(2);
        // The repo whole is every record, read as it is sent.
        let archive = get_repo_of(&s, &t, &did, SPACE).await.unwrap();
        assert!(archive.len() > 4000 * 1000);
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// `clearRecords`, an import and a repo dropped with its space each
    /// void what was before them: the same is read whether what was before
    /// is in the log, or in a table made between any two of them, and
    /// whether the store was let go and loaded again after each; and after
    /// the server starts again. Blobs are held by what records reference
    /// them through it all, across the space repos.
    #[tokio::test]
    async fn clears_imports_and_drops_void_what_was_before() {
        use crate::space_authority::MEMBER;
        let plc = plc().await;
        let dir = scratch("space-voids");
        let opened = || open_with(&dir, &plc, |c| c.load_all = false);
        let s = opened();
        let (one, two) = (
            b"spec-pds voids one" as &[u8],
            b"spec-pds voids two" as &[u8],
        );
        let img = |b: &[u8]| bref(&raw_cid(b), "text/plain", b.len() as i64);
        let (c1, c2) = (raw_cid(one), raw_cid(two));
        const STEPS: usize = 11;
        // What the account holds, less what differs from one account to another.
        let shape = |s: &Shared, did: &str, t: &str, mine: &str| {
            let (s, did, t, mine) = (s.clone(), did.to_string(), t.to_string(), mine.to_string());
            let (c1, c2) = (c1.clone(), c2.clone());
            async move {
                let mut out = Vec::new();
                for space in [mine.as_str(), SPACE] {
                    let commit = ask(&s, "getLatestCommit", &t, &did, space, &[]).await;
                    let records =
                        paged(&s, "listRecords", &t, &did, space, &[], "records", 4).await;
                    let ops = paged(&s, "listRepoOps", &t, &did, space, &[], "ops", 3).await;
                    let revs: Vec<&str> = ops.iter().filter_map(|o| o["rev"].as_str()).collect();
                    assert!(revs.is_sorted());
                    let ops: Vec<Json> = ops
                        .iter()
                        .map(|o| {
                            json!([o["collection"], o["rkey"], o["cid"], o["prev"], o["value"]])
                        })
                        .collect();
                    let cids = paged(&s, "listBlobs", &t, &did, space, &[], "cids", 1).await;
                    let mut served = Vec::new();
                    for cid in [&c1, &c2] {
                        served.push(space_blob(&s, &t, &did, space, cid).await.map(|b| b.0));
                    }
                    let archive = get_repo_of(&s, &t, &did, space).await.map(|a| a.len());
                    out.push(json!([
                        commit["commit"]["data"],
                        commit["error"],
                        records,
                        ops,
                        cids,
                        format!("{served:?} {archive:?}")
                    ]));
                }
                let (held, refs) = store_of(&s, &did, |st| {
                    drop(snapshot(st));
                    let held: Vec<String> = st.blobs.held_list().map(|h| h.0.to_string()).collect();
                    let refs: Vec<(String, u32)> = st
                        .blobs
                        .space_ref_list()
                        .into_iter()
                        .map(|(c, n)| (c.to_string(), n))
                        .collect();
                    (held, refs)
                });
                out.push(json!([held, refs]));
                Json::String(json!(out).to_string().replace(&did, "DID"))
            }
        };
        // One account's run: after each step, its log compacted if
        // `compacted` says so, and its store let go if `freed`.
        let run = |n: usize, compacted: Vec<bool>, freed: bool| {
            let (s, shape) = (s.clone(), &shape);
            async move {
                let name = format!("acct{n}");
                let (did, t) = create(&s, &name).await;
                for b in [one, two] {
                    crate::blobs::test_upload(&s, Some(&t), Some("text/plain"), b.to_vec(), false)
                        .await
                        .unwrap();
                }
                let policy =
                    json!({ "$type": MEMBER, "publishPolicy": true, "publishMembers": true });
                let made = call(
                    &s,
                    "com.atproto.space.createSpace",
                    Some(&t),
                    json!({ "spaceType": "com.example.forum", "skey": "mine", "policy": policy }),
                )
                .await
                .unwrap();
                let mine = made["space"].as_str().unwrap().to_string();
                let members: Vec<Json> = [
                    "did:plc:aaaaaaaaaaaaaaaaaaaaaaaa",
                    "did:plc:bbbbbbbbbbbbbbbbbbbbbbbb",
                ]
                .iter()
                .map(|m| json!({ "did": m, "read": true, "write": false }))
                .collect();
                call(
                    &s,
                    "com.atproto.memberspace.putMembers",
                    Some(&t),
                    json!({ "space": mine, "members": members }),
                )
                .await
                .unwrap();
                let put = |space: &str, rkey: &str, record: Json| json!({ "space": space, "repo": did, "collection": "a.b.c", "rkey": rkey, "record": record });
                let import = |space: &str, records: Vec<(&str, Json)>| {
                    let records: Vec<(String, Vec<u8>)> = records
                        .into_iter()
                        .map(|(p, v)| (p.to_string(), encode_json(v)))
                        .collect();
                    let mut h = LtHash::new();
                    for (p, bytes) in &records {
                        h.add(&element(
                            p,
                            &cid_string(&pds_repo::data::cid_of(0x71, bytes)),
                        ));
                    }
                    let commit = Commit {
                        repo: did.clone(),
                        space: space.into(),
                        rev: "3mzzzzzzzzzz2".into(),
                        data: h.digest(),
                    };
                    star::write_repo(&commit, &records)
                };
                let mut shapes = Vec::new();
                for (step, compacted) in compacted.into_iter().enumerate() {
                    match step {
                        0 => {
                            w(
                                &s,
                                "putRecord",
                                &t,
                                put(&mine, "1", json!({ "img": img(one) })),
                            )
                            .await
                            .unwrap();
                            w(&s, "putRecord", &t, put(&mine, "2", record(2)))
                                .await
                                .unwrap();
                            w(&s, "putRecord", &t, put(&mine, "3", record(3)))
                                .await
                                .unwrap();
                            w(
                                &s,
                                "putRecord",
                                &t,
                                put(SPACE, "1", json!({ "img": img(one) })),
                            )
                            .await
                            .unwrap();
                            w(
                                &s,
                                "putRecord",
                                &t,
                                put(SPACE, "2", json!({ "img": img(two) })),
                            )
                            .await
                            .unwrap();
                        }
                        // Its own repo cleared: the published records stay.
                        1 => drop(
                            w(
                                &s,
                                "clearRecords",
                                &t,
                                json!({ "space": mine, "repo": did }),
                            )
                            .await
                            .unwrap(),
                        ),
                        2 => {
                            w(
                                &s,
                                "putRecord",
                                &t,
                                put(&mine, "4", json!({ "img": img(two) })),
                            )
                            .await
                            .unwrap();
                            w(&s, "putRecord", &t, put(&mine, "2", record(22)))
                                .await
                                .unwrap();
                        }
                        // The other cleared: nothing of it stays, nor the blob only it held.
                        3 => drop(
                            w(
                                &s,
                                "clearRecords",
                                &t,
                                json!({ "space": SPACE, "repo": did }),
                            )
                            .await
                            .unwrap(),
                        ),
                        4 => {
                            let archive = import(
                                SPACE,
                                vec![
                                    ("a.b.c/9", json!({ "$type": "a.b.c", "img": img(two) })),
                                    ("a.b.c/1", record(1)),
                                ],
                            );
                            import_repo_of(&s, &t, &archive).await.unwrap();
                        }
                        5 => {
                            w(&s, "putRecord", &t, put(SPACE, "10", record(10)))
                                .await
                                .unwrap();
                            w(&s, "putRecord", &t, put(&mine, "5", record(5)))
                                .await
                                .unwrap();
                        }
                        // Its own imported: the published records go with the rest.
                        6 => {
                            let archive = import(&mine, vec![("a.b.c/7", record(7))]);
                            import_repo_of(&s, &t, &archive).await.unwrap();
                        }
                        7 => drop(
                            w(
                                &s,
                                "putRecord",
                                &t,
                                put(&mine, "8", json!({ "img": img(two) })),
                            )
                            .await
                            .unwrap(),
                        ),
                        // Its space deleted: its repo there is dropped.
                        8 => {
                            call(
                                &s,
                                "com.atproto.space.deleteSpace",
                                Some(&t),
                                json!({ "space": mine }),
                            )
                            .await
                            .unwrap();
                        }
                        9 => drop(
                            w(&s, "putRecord", &t, put(SPACE, "11", record(11)))
                                .await
                                .unwrap(),
                        ),
                        // Its space made again: its repo there begins anew.
                        _ => {
                            let again = json!({ "spaceType": "com.example.forum", "skey": "mine", "policy": policy });
                            call(&s, "com.atproto.space.createSpace", Some(&t), again)
                                .await
                                .unwrap();
                            let put = put(&mine, "12", json!({ "img": img(two) }));
                            w(&s, "putRecord", &t, put).await.unwrap();
                        }
                    }
                    crate::space_notify::tests::idle(&s).await;
                    if compacted {
                        compact(&s, &did);
                    }
                    if freed {
                        let_go(&s, &did).await;
                    }
                    shapes.push(shape(&s, &did, &t, &mine).await);
                }
                (did, t, mine, shapes)
            }
        };
        let plain = run(0, vec![false; STEPS], false).await;
        // What each step leaves, as the methods say.
        let at = |step: usize| -> Json {
            serde_json::from_str(plain.3[step].as_str().unwrap()).unwrap()
        };
        let paths = |shape: &Json, space: usize| -> Vec<String> {
            shape[space][2]
                .as_array()
                .unwrap()
                .iter()
                .map(|r| {
                    format!(
                        "{}/{}",
                        r["collection"].as_str().unwrap(),
                        r["rkey"].as_str().unwrap()
                    )
                })
                // Listed in descending order: ascending here.
                .rev()
                .collect()
        };
        let published = [
            "com.atproto.memberspace.member/did:plc:aaaaaaaaaaaaaaaaaaaaaaaa",
            "com.atproto.memberspace.member/did:plc:bbbbbbbbbbbbbbbbbbbbbbbb",
            "com.atproto.space.policy/self",
        ];
        let with = |own: &[&str]| -> Vec<String> {
            let mut all: Vec<String> = own
                .iter()
                .chain(&published)
                .map(|p| p.to_string())
                .collect();
            all.sort();
            all
        };
        assert_eq!(paths(&at(0), 0), with(&["a.b.c/1", "a.b.c/2", "a.b.c/3"]));
        assert_eq!(paths(&at(1), 0), with(&[]));
        assert_eq!(at(1)[0][3], json!([]), "a cleared repo's operations");
        assert_eq!(paths(&at(2), 0), with(&["a.b.c/2", "a.b.c/4"]));
        assert_eq!(paths(&at(2), 1), ["a.b.c/1", "a.b.c/2"]);
        assert!(paths(&at(3), 1).is_empty());
        // The blob only the cleared repo's records referenced is held no more.
        let mut held = [c1.clone(), c2.clone()];
        held.sort();
        assert_eq!(at(2)[2][0], json!(held));
        assert_eq!(at(3)[2], json!([[c2], [[c2, 1]]]));
        assert_eq!(paths(&at(4), 1), ["a.b.c/1", "a.b.c/9"]);
        assert_eq!(at(4)[1][3], json!([]), "an imported repo's operations");
        assert_eq!(at(4)[2], json!([[c2], [[c2, 2]]]));
        assert_eq!(paths(&at(6), 0), ["a.b.c/7"]);
        assert_eq!(at(6)[2], json!([[c2], [[c2, 1]]]));
        assert_eq!(paths(&at(7), 0), ["a.b.c/7", "a.b.c/8"]);
        assert_eq!(at(8)[0][1], json!("RepoNotFound"));
        assert_eq!(
            paths(&at(9), 1),
            ["a.b.c/1", "a.b.c/10", "a.b.c/11", "a.b.c/9"]
        );
        assert_eq!(at(9)[2], json!([[c2], [[c2, 1]]]));
        assert_eq!(
            paths(&at(10), 0),
            ["a.b.c/12", "com.atproto.space.policy/self"]
        );
        assert_eq!(at(10)[0][3].as_array().unwrap().len(), 2);
        assert_eq!(at(10)[2], json!([[c2], [[c2, 2]]]));
        // The same with a table made after any one step, after every step,
        // and after a few of them, the store held or let go.
        let mut masks: Vec<Vec<bool>> = (0..STEPS)
            .map(|i| (0..STEPS).map(|j| i == j).collect())
            .collect();
        masks.push(vec![true; STEPS]);
        masks.extend((0..3).map(|k| (0..STEPS).map(|j| (j + k) % 3 != 0).collect::<Vec<bool>>()));
        let mut runs = vec![plain];
        for (i, mask) in masks.into_iter().enumerate() {
            for freed in [false, true] {
                let n = 1 + i * 2 + usize::from(freed);
                let got = run(n, mask.clone(), freed).await;
                for step in 0..STEPS {
                    assert!(
                        got.3[step] == runs[0].3[step],
                        "step {step}, compacted after {mask:?}, let go: {freed}"
                    );
                }
                runs.push(got);
            }
        }
        runs.push(run(99, vec![false; STEPS], true).await);
        assert_eq!(runs.last().unwrap().3, runs[0].3);
        // Started again, each account holds what it held.
        crate::space_notify::tests::idle(&s).await;
        drop(s);
        let s = opened();
        for (did, t, mine, shapes) in &runs {
            assert_eq!(&shape(&s, did, t, mine).await, shapes.last().unwrap());
        }
        let _ = std::fs::remove_dir_all(&dir);
    }
}