//! the collection NSID dictionary. //! //! holds both directions of the interning map fully in memory, loaded once at //! [`Db::open`]. the network has ~26k distinct collections (UFOs census, //! 2026-08-01), which costs roughly 2 MB, so nothing here is evicted and no //! composite-key operation ever touches disk to resolve a collection. //! //! # the budget guard //! //! NSIDs are minted by whoever writes a record, so dictionary size is driven by //! untrusted input and retained for the process lifetime. past //! [`Config::collection_dict_max_mb`] the dictionary stops growing and new //! collections are written as NSID text instead — [`CollectionKey::Text`], the //! same form every key had before interning. that is a fallback to the *old key //! layout*, not to a disk lookup: there is no cache miss path, so no read can be //! slowed down by a full dictionary. the collections shut out are the long tail //! that arrived last, while the collections carrying real traffic appear early //! and keep their one-byte ids. //! //! the budget counts NSID bytes plus per-entry overhead rather than entry count, //! so padding an NSID out to its 317-byte maximum buys no extra headroom. use std::collections::HashMap; use miette::{IntoDiagnostic, Result, WrapErr}; use parking_lot::RwLock; use smol_str::SmolStr; use super::collection_id::{self, CollectionId}; use super::keys::SEP; use super::schema::{self, Ks}; /// charged against the budget per entry on top of the NSID bytes, covering both /// maps' slots and hashing overhead. const ENTRY_OVERHEAD: usize = 64; /// how a collection is written into a composite key. /// /// both forms are load-bearing rather than transitional: the chunked migration /// produces a mixed keyspace while it runs, and the budget guard can leave text /// keys in place permanently. every read path therefore has to accept both, and /// [`collection_id::is_interned`] is what tells them apart — an NSID always /// starts with `[a-zA-Z]` and no allocatable id encodes to a leading ASCII /// letter. /// /// # embedded versus terminal /// /// a collection sits in two different positions and needs a different encoding /// in each, because the text form is only self-delimiting when a separator /// follows it: /// /// - **embedded**, as in `records` (`{did}|{col}{rkey}`): [`Self::Id`] writes the /// bare varint, which needs no separator because the encoding is prefix-free, /// while [`Self::Text`] writes the NSID followed by [`SEP`] — exactly what /// these keys held before interning. /// - **terminal**, as in `counts` (`r|{did}|{col}`): nothing follows, so both /// forms write bare bytes. adding a separator here would change the text /// layout and force a rewrite of keys that do not otherwise need one. /// /// each reader consumes precisely what its writer produced, so both forms /// coexist in one keyspace and a prefix built either way isolates exactly one /// collection. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum CollectionKey<'a> { Id(CollectionId), Text(&'a str), } impl<'a> CollectionKey<'a> { /// bytes this segment occupies when something follows it, its separator /// included. pub fn embedded_len(&self) -> usize { match self { Self::Id(id) => id.encoded_len(), Self::Text(nsid) => nsid.len() + 1, } } /// write this segment where more key follows it. pub fn write_embedded(&self, buf: &mut Vec) { match self { Self::Id(id) => id.write_to_vec(buf), Self::Text(nsid) => { buf.extend_from_slice(nsid.as_bytes()); buf.push(SEP); } } } /// write this segment as the last part of a key. pub fn write_terminal(&self, buf: &mut Vec) { match self { Self::Id(id) => id.write_to_vec(buf), Self::Text(nsid) => buf.extend_from_slice(nsid.as_bytes()), } } /// decode an embedded segment from the front of `bytes`, with its remainder. pub fn read_embedded(bytes: &[u8]) -> Result<(CollectionKey<'_>, &[u8])> { if collection_id::is_interned(bytes) { let (id, rest) = CollectionId::read_from(bytes)?; return Ok((CollectionKey::Id(id), rest)); } let end = bytes .iter() .position(|&byte| byte == SEP) .ok_or_else(|| miette::miette!("collection segment is missing its separator"))?; let nsid = std::str::from_utf8(&bytes[..end]) .into_diagnostic() .wrap_err("collection segment is not valid utf8")?; Ok((CollectionKey::Text(nsid), &bytes[end + 1..])) } /// decode a segment that is the whole remainder of a key. pub fn read_terminal(bytes: &[u8]) -> Result> { if collection_id::is_interned(bytes) { let (id, rest) = CollectionId::read_from(bytes)?; if !rest.is_empty() { miette::bail!("trailing bytes after a terminal collection id"); } return Ok(CollectionKey::Id(id)); } std::str::from_utf8(bytes) .map(CollectionKey::Text) .into_diagnostic() .wrap_err("collection segment is not valid utf8") } } /// the in-memory dictionary. both directions, never evicted. struct Inner { forward: HashMap, /// indexed by raw id. the ids skipped to keep encodings out of ASCII leave /// at most 52 holes, all below 128, so a `Vec` stays dense; a hole holds the /// empty string. reverse: Vec, /// the next id to hand out, `None` once the id space is exhausted. next: Option, used_bytes: usize, /// whether the budget has already been reported as reached. reported_full: bool, } impl Inner { fn record(&mut self, nsid: SmolStr, id: CollectionId) { let slot = id.get() as usize; if self.reverse.len() <= slot { self.reverse.resize(slot + 1, SmolStr::default()); } self.reverse[slot] = nsid.clone(); self.used_bytes += nsid.len() + ENTRY_OVERHEAD; self.forward.insert(nsid, id); } } pub struct Interner { ks: Ks, budget_bytes: usize, inner: RwLock, } impl Interner { /// load the whole dictionary from `ks`. pub fn open(ks: Ks, budget_bytes: usize) -> Result { let mut inner = Inner { forward: HashMap::new(), reverse: Vec::new(), next: Some(CollectionId::first()), used_bytes: 0, reported_full: false, }; let mut highest: Option = None; for guard in ks.iter() { let (key, value) = guard.into_inner().into_diagnostic()?; let raw = u32::from_be_bytes( key.as_ref() .try_into() .into_diagnostic() .wrap_err("collection dictionary key expected to be 4 bytes")?, ); let id = CollectionId::from_raw(raw)?; let nsid = std::str::from_utf8(&value) .into_diagnostic() .wrap_err("collection dictionary value is not valid utf8")?; inner.record(SmolStr::new(nsid), id); highest = Some(highest.map_or(id, |h: CollectionId| h.max(id))); } // resume after the highest id ever handed out, never reusing one: a // reused id would silently reassign every key already written under it inner.next = match highest { Some(id) => id.next(), None => Some(CollectionId::first()), }; if !inner.forward.is_empty() { tracing::debug!( "loaded {} interned collections ({} KiB)", inner.forward.len(), inner.used_bytes / 1024 ); } Ok(Self { ks, budget_bytes, inner: RwLock::new(inner), }) } /// how a composite key should spell `nsid`, interning it if there is room. /// /// returns [`CollectionKey::Text`] when the budget is exhausted or the id /// space is used up, which keeps writes working at the pre-interning key /// size rather than failing. pub fn key_for<'a>(&self, nsid: &'a str) -> Result> { if let Some(id) = self.inner.read().forward.get(nsid) { return Ok(CollectionKey::Id(*id)); } self.intern(nsid) } /// how an already-written key spells `nsid`, without interning it. /// /// read paths must use this rather than [`Self::key_for`]: querying a /// collection that was never written would otherwise mint an id for it, so a /// stream of `getRecord` misses could grow the dictionary. falling back to /// [`CollectionKey::Text`] is also the correct lookup for a collection the /// budget guard shut out, since that is how its keys were written. pub fn lookup<'a>(&self, nsid: &'a str) -> CollectionKey<'a> { self.inner .read() .forward .get(nsid) .map(|id| CollectionKey::Id(*id)) .unwrap_or(CollectionKey::Text(nsid)) } /// the NSID behind `id`. pub fn nsid(&self, id: CollectionId) -> Result { self.inner .read() .reverse .get(id.get() as usize) .filter(|nsid| !nsid.is_empty()) .cloned() .ok_or_else(|| miette::miette!("collection id {} is not in the dictionary", id.get())) } /// the NSID text for either form of a collection segment. pub fn text(&self, key: CollectionKey<'_>) -> Result { match key { CollectionKey::Id(id) => self.nsid(id), CollectionKey::Text(nsid) => Ok(SmolStr::new(nsid)), } } /// the underlying keyspace handle, for the registry's by-name tables. pub fn keyspace(&self) -> fjall::Keyspace { self.ks.keyspace() } /// number of interned collections. pub fn len(&self) -> usize { self.inner.read().forward.len() } /// bytes the dictionary is charged against its budget. pub fn used_bytes(&self) -> usize { self.inner.read().used_bytes } fn intern<'a>(&self, nsid: &'a str) -> Result> { let mut inner = self.inner.write(); // another writer may have interned it between the read and write locks if let Some(id) = inner.forward.get(nsid) { return Ok(CollectionKey::Id(*id)); } if inner.used_bytes + nsid.len() + ENTRY_OVERHEAD > self.budget_bytes { if !inner.reported_full { inner.reported_full = true; tracing::warn!( interned = inner.forward.len(), used_bytes = inner.used_bytes, budget_bytes = self.budget_bytes, "collection dictionary budget reached; further collections keep NSID text in keys" ); } return Ok(CollectionKey::Text(nsid)); } let Some(id) = inner.next else { return Ok(CollectionKey::Text(nsid)); }; // persist before memoizing, so a failed write leaves an unused id rather // than an in-memory id whose dictionary entry never became durable. an // id burned this way is never handed out again, which is the safe // direction: reuse would remap keys already written under it. self.ks .insert(id.get().to_be_bytes(), nsid.as_bytes()) .into_diagnostic() .wrap_err_with(|| format!("failed to persist collection id for {nsid}"))?; inner.next = id.next(); inner.record(SmolStr::new(nsid), id); tracing::debug!("interned collection {nsid} as id {}", id.get()); Ok(CollectionKey::Id(id)) } } #[cfg(test)] mod tests { use super::*; use crate::db::Db; fn open_db() -> Result<(tempfile::TempDir, Db)> { let tmp = tempfile::tempdir().into_diagnostic()?; let cfg = crate::config::Config { database_path: tmp.path().to_path_buf(), ..Default::default() }; let db = Db::open(&cfg)?; Ok((tmp, db)) } fn encode(key: CollectionKey<'_>) -> Vec { let mut buf = Vec::new(); key.write_embedded(&mut buf); buf } fn encode_terminal(key: CollectionKey<'_>) -> Vec { let mut buf = Vec::new(); key.write_terminal(&mut buf); buf } #[test] fn both_key_forms_roundtrip_embedded_with_their_remainder() -> Result<()> { let id = CollectionKey::Id(CollectionId::first()); let text = CollectionKey::Text("app.bsky.feed.like"); for form in [id, text] { let mut buf = encode(form); buf.extend_from_slice(b"\x01rkeybytes"); let (decoded, rest) = CollectionKey::read_embedded(&buf)?; assert_eq!(decoded, form); assert_eq!(rest, b"\x01rkeybytes"); assert_eq!(encode(form).len(), form.embedded_len()); } Ok(()) } #[test] fn both_key_forms_roundtrip_terminal() -> Result<()> { for form in [ CollectionKey::Id(CollectionId::first()), CollectionKey::Text("app.bsky.feed.like"), ] { let buf = encode_terminal(form); assert_eq!(CollectionKey::read_terminal(&buf)?, form); } Ok(()) } /// the terminal text form must stay byte-identical to the pre-interning /// layout, or existing count keys would need a rewrite they do not deserve. #[test] fn terminal_text_is_the_bare_nsid() { assert_eq!( encode_terminal(CollectionKey::Text("app.bsky.feed.like")), b"app.bsky.feed.like" ); } /// an interned id must never be mistaken for the text form or vice versa, /// which is what lets both live in one keyspace. #[test] fn the_two_forms_are_never_confused() -> Result<()> { let mut id = CollectionId::first(); for _ in 0..500 { let embedded = encode(CollectionKey::Id(id)); let (decoded, _) = CollectionKey::read_embedded(&embedded)?; assert_eq!(decoded, CollectionKey::Id(id), "id {}", id.get()); assert_eq!( CollectionKey::read_terminal(&encode_terminal(CollectionKey::Id(id)))?, CollectionKey::Id(id) ); id = id.next().expect("id space"); } // including an uppercase-leading NSID, which the live network has for nsid in [ "app.bsky.feed.like", "C.d.e.f", "a.b.c", "sh.tangled.actor.profile", ] { let embedded = encode(CollectionKey::Text(nsid)); let (decoded, _) = CollectionKey::read_embedded(&embedded)?; assert_eq!(decoded, CollectionKey::Text(nsid)); assert_eq!( CollectionKey::read_terminal(&encode_terminal(CollectionKey::Text(nsid)))?, CollectionKey::Text(nsid) ); } Ok(()) } #[test] fn read_embedded_rejects_text_without_a_separator() { assert!(CollectionKey::read_embedded(b"app.bsky.feed.like").is_err()); } #[test] fn read_terminal_rejects_trailing_bytes_after_an_id() { let mut buf = encode_terminal(CollectionKey::Id(CollectionId::first())); buf.extend_from_slice(b"extra"); assert!(CollectionKey::read_terminal(&buf).is_err()); } #[test] fn interning_is_stable_and_reversible() -> Result<()> { let (_tmp, db) = open_db()?; let interner = &db.indexer.collections; let like = interner.key_for("app.bsky.feed.like")?; let post = interner.key_for("app.bsky.feed.post")?; assert_ne!(like, post); // the same NSID always resolves to the same id assert_eq!(interner.key_for("app.bsky.feed.like")?, like); let CollectionKey::Id(like_id) = like else { panic!("expected an interned id"); }; assert_eq!(interner.nsid(like_id)?, "app.bsky.feed.like"); assert_eq!(interner.text(like)?, "app.bsky.feed.like"); assert_eq!(interner.len(), 2); Ok(()) } /// the hot collections must land in the one-byte range, which is the whole /// point of the varint. #[test] fn the_first_collections_seen_get_one_byte_ids() -> Result<()> { let (_tmp, db) = open_db()?; let interner = &db.indexer.collections; for nsid in [ "app.bsky.feed.like", "app.bsky.feed.post", "app.bsky.graph.follow", "app.bsky.feed.repost", "app.bsky.graph.block", ] { let key = interner.key_for(nsid)?; assert_eq!(key.embedded_len(), 1, "{nsid} did not fit in one byte"); } Ok(()) } #[test] fn the_dictionary_survives_a_reopen() -> Result<()> { let tmp = tempfile::tempdir().into_diagnostic()?; let cfg = crate::config::Config { database_path: tmp.path().to_path_buf(), ..Default::default() }; let (like, post, len) = { let db = Db::open(&cfg)?; let interner = &db.indexer.collections; ( interner.key_for("app.bsky.feed.like")?, interner.key_for("app.bsky.feed.post")?, interner.len(), ) }; let db = Db::open(&cfg)?; let interner = &db.indexer.collections; assert_eq!(interner.len(), len); assert_eq!(interner.key_for("app.bsky.feed.like")?, like); assert_eq!(interner.key_for("app.bsky.feed.post")?, post); // a collection interned after the reopen must not reuse an existing id let follow = interner.key_for("app.bsky.graph.follow")?; assert_ne!(follow, like); assert_ne!(follow, post); Ok(()) } #[test] fn a_reopen_never_reuses_an_id_after_a_gap() -> Result<()> { let tmp = tempfile::tempdir().into_diagnostic()?; let cfg = crate::config::Config { database_path: tmp.path().to_path_buf(), ..Default::default() }; let highest = { let db = Db::open(&cfg)?; let interner = &db.indexer.collections; let mut highest = CollectionId::first(); for i in 0..300 { let nsid = format!("test{i}.collection.name"); let CollectionKey::Id(id) = interner.key_for(&nsid)? else { panic!("expected an interned id"); }; highest = highest.max(id); } highest }; let db = Db::open(&cfg)?; let key = db.indexer.collections.key_for("fresh.collection.name")?; let CollectionKey::Id(id) = key else { panic!("expected an interned id"); }; assert!( id > highest, "reopened interner handed out {} which is not past {}", id.get(), highest.get() ); Ok(()) } #[test] fn the_budget_falls_back_to_text_instead_of_failing() -> Result<()> { let tmp = tempfile::tempdir().into_diagnostic()?; let cfg = crate::config::Config { database_path: tmp.path().to_path_buf(), // room for two entries at ~64 bytes of overhead each collection_dict_max_bytes: 2 * (ENTRY_OVERHEAD + 20), ..Default::default() }; let db = Db::open(&cfg)?; let interner = &db.indexer.collections; assert!(matches!( interner.key_for("app.bsky.feed.like")?, CollectionKey::Id(_) )); assert!(matches!( interner.key_for("app.bsky.feed.post")?, CollectionKey::Id(_) )); // past the budget, keys keep the pre-interning layout let overflow = interner.key_for("app.bsky.graph.follow")?; assert_eq!(overflow, CollectionKey::Text("app.bsky.graph.follow")); // and an already-interned collection still resolves to its id assert!(matches!( interner.key_for("app.bsky.feed.like")?, CollectionKey::Id(_) )); // the shut-out collection is not persisted, so a reopen agrees drop(db); let db = Db::open(&cfg)?; assert_eq!(db.indexer.collections.len(), 2); assert_eq!( db.indexer.collections.key_for("app.bsky.graph.follow")?, CollectionKey::Text("app.bsky.graph.follow") ); Ok(()) } #[test] fn the_budget_counts_nsid_bytes_so_padding_buys_nothing() -> Result<()> { let tmp = tempfile::tempdir().into_diagnostic()?; let cfg = crate::config::Config { database_path: tmp.path().to_path_buf(), collection_dict_max_bytes: 4 * ENTRY_OVERHEAD, ..Default::default() }; let db = Db::open(&cfg)?; let interner = &db.indexer.collections; // one padded NSID consumes the budget that several short ones would let padded = format!("a{}.b.c", "-".repeat(200)); assert!(matches!(interner.key_for(&padded)?, CollectionKey::Text(_))); assert_eq!(interner.len(), 0); assert!(matches!( interner.key_for("app.bsky.feed.like")?, CollectionKey::Id(_) )); Ok(()) } #[test] fn nsid_rejects_an_id_that_was_never_interned() -> Result<()> { let (_tmp, db) = open_db()?; let unknown = CollectionId::from_raw(9_999)?; assert!(db.indexer.collections.nsid(unknown).is_err()); Ok(()) } }