Skip to main content

agentmux_srv_core/backend/slug_migration/
holders.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Who holds a slug on this host outside the shared definitions: every
5//! `objects.db` on disk (a row's slug, a former slug, a former display name's
6//! route) and every live registration. A new agent's slug is picked against
7//! these as well as the shared definitions, under the host-wide slug
8//! allocation lock, so a row only one channel or version knows (an agent from
9//! before the shared definitions, a template launch, a copy that was never
10//! published) can't be given to a second agent; and the definition mirror
11//! reads them before it publishes a slug. The same holders `plan::holder_of`
12//! checks, read in one pass.
13//!
14//! Each `objects.db` is read once and kept until its file (or its WAL)
15//! changes: most of them are older versions nobody runs, and a host can have
16//! hundreds.
17
18use std::collections::HashMap;
19use std::path::{Path, PathBuf};
20use std::sync::{Arc, Mutex, OnceLock};
21use std::time::SystemTime;
22
23use super::home::{fold, has_agent_slugs, open_ro, place, table_exists, Home, Install};
24
25/// What a row holds a name as.
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27enum Kind {
28    Slug,
29    FormerSlug,
30    /// A former display name, by its route: it still addresses its agent.
31    FormerName,
32}
33
34#[derive(Debug, Clone)]
35struct Held {
36    kind: Kind,
37    /// Folded as every key table folds.
38    name: String,
39    uid: String,
40}
41
42/// One `objects.db`'s file state: a change to the database or its WAL
43/// changes one of these.
44#[derive(Debug, Clone, PartialEq, Eq)]
45struct Stamp(Vec<(u64, Option<SystemTime>)>);
46
47fn stamp(db: &Path) -> Stamp {
48    let mut wal = db.as_os_str().to_owned();
49    wal.push("-wal");
50    Stamp(
51        [db.to_path_buf(), PathBuf::from(wal)]
52            .iter()
53            .map(|p| std::fs::metadata(p).map(|m| (m.len(), m.modified().ok())).unwrap_or((0, None)))
54            .collect(),
55    )
56}
57
58type Cache = Mutex<HashMap<PathBuf, (Stamp, Arc<Vec<Held>>)>>;
59
60fn cache() -> &'static Cache {
61    static CACHE: OnceLock<Cache> = OnceLock::new();
62    CACHE.get_or_init(Default::default)
63}
64
65/// One `objects.db`'s holders, read now. An `objects.db` older than
66/// `db_agents.slug` holds none; one that can't be read is an error.
67fn read_db(db: &Path) -> Result<Vec<Held>, String> {
68    let conn = open_ro(db)?;
69    let failed = |e: rusqlite::Error| format!("{} can't be read: {e}", db.display());
70    // The schema checks below read a failure as "no such table", so a file
71    // that isn't a database is caught here (as `plan::unreadable_stores` does).
72    conn.query_row("SELECT name FROM sqlite_master LIMIT 1", [], |_| Ok(()))
73        .or_else(|e| if matches!(e, rusqlite::Error::QueryReturnedNoRows) { Ok(()) } else { Err(e) })
74        .map_err(failed)?;
75    let mut out = Vec::new();
76    if has_agent_slugs(&conn) {
77        let mut stmt = conn.prepare("SELECT id, COALESCE(slug, '') FROM db_agents").map_err(failed)?;
78        let rows = stmt.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?))).map_err(failed)?;
79        for row in rows {
80            let (uid, slug) = row.map_err(failed)?;
81            if !slug.trim().is_empty() {
82                out.push(Held { kind: Kind::Slug, name: fold(&slug), uid });
83            }
84        }
85    }
86    if table_exists(&conn, "db_agent_former_slugs") {
87        let mut stmt = conn.prepare("SELECT agent_uid, slug FROM db_agent_former_slugs").map_err(failed)?;
88        let rows = stmt.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?))).map_err(failed)?;
89        for row in rows {
90            let (uid, slug) = row.map_err(failed)?;
91            out.push(Held { kind: Kind::FormerSlug, name: fold(&slug), uid });
92        }
93    }
94    if table_exists(&conn, "db_agent_former_names") {
95        let mut stmt = conn.prepare("SELECT agent_id, name FROM db_agent_former_names").map_err(failed)?;
96        let rows = stmt.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?))).map_err(failed)?;
97        for row in rows {
98            let (uid, name) = row.map_err(failed)?;
99            if let Some(route) = route_key(&name) {
100                out.push(Held { kind: Kind::FormerName, name: route, uid });
101            }
102        }
103    }
104    Ok(out)
105}
106
107/// The key a display name is addressed by, as `resolve_slug_collision` and
108/// `plan::holder_of` read a former one: its route name, folded; `None` for a
109/// name no message can address.
110fn route_key(name: &str) -> Option<String> {
111    let name = name.trim();
112    if name.is_empty() {
113        return None;
114    }
115    let route = agentmux_common::slug::agent_route_name(name);
116    agentmux_common::slug::is_agent_id(&route).then(|| route.to_lowercase())
117}
118
119/// Every holder on this host outside the shared definitions, as one read
120/// found them.
121pub struct HostSlugs {
122    home: Home,
123    installs: Vec<Install>,
124    /// Folded name → what holds it, and where.
125    by_name: HashMap<String, Vec<(Held, String)>>,
126}
127
128impl HostSlugs {
129    /// Read every `objects.db` under `home` (each from its cache while its
130    /// files are unchanged). A directory that can't be listed or a database
131    /// that can't be read is an error: a slug picked without it could be one
132    /// that store holds.
133    pub fn read(home: &Home) -> Result<HostSlugs, String> {
134        let installs = home.installs()?;
135        let mut by_name: HashMap<String, Vec<(Held, String)>> = HashMap::new();
136        for install in &installs {
137            for version in &install.versions {
138                let db = version.objects_db();
139                let now = stamp(&db);
140                let cached = cache().lock().unwrap_or_else(|e| e.into_inner()).get(&db).filter(|(s, _)| *s == now).map(|(_, h)| h.clone());
141                let held = match cached {
142                    Some(h) => h,
143                    None => {
144                        let h = Arc::new(read_db(&db)?);
145                        cache().lock().unwrap_or_else(|e| e.into_inner()).insert(db.clone(), (now, h.clone()));
146                        h
147                    }
148                };
149                let at = place(install, version);
150                for h in held.iter() {
151                    by_name.entry(h.name.clone()).or_default().push((h.clone(), at.clone()));
152                }
153            }
154        }
155        Ok(HostSlugs { home: home.clone(), installs, by_name })
156    }
157
158    /// Who other than `uid` holds `name` as a slug or a former slug in some
159    /// `objects.db`, described for a log line or an error.
160    pub fn slug_holder(&self, name: &str, uid: &str) -> Option<String> {
161        self.held(name, uid, &[Kind::Slug, Kind::FormerSlug])
162    }
163
164    /// [`Self::slug_holder`], or a former display name of another agent that
165    /// routes to `name`, or a live registration of another agent's pane under
166    /// it: everything a new slug must not be.
167    pub fn holder(&self, name: &str, uid: &str) -> Option<String> {
168        self.held(name, uid, &[Kind::Slug, Kind::FormerSlug, Kind::FormerName])
169            .or_else(|| self.registered(&fold(name), uid))
170    }
171
172    fn held(&self, name: &str, uid: &str, kinds: &[Kind]) -> Option<String> {
173        let (h, at) = self.by_name.get(&fold(name))?.iter().find(|(h, _)| h.uid != uid && kinds.contains(&h.kind))?;
174        Some(match h.kind {
175            Kind::Slug => format!("agent {} has it in {at}", h.uid),
176            Kind::FormerSlug => format!("agent {} was renamed from it in {at}", h.uid),
177            Kind::FormerName => format!("agent {} had a name that routes to it in {at}", h.uid),
178        })
179    }
180
181    /// A live registration under `name` of a pane that isn't `uid`'s, in any
182    /// version or in the cross-channel registry (`plan::holder_of`'s rule).
183    fn registered(&self, name: &str, uid: &str) -> Option<String> {
184        for install in &self.installs {
185            for version in &install.versions {
186                let Some(entry) = super::running::registration(&version.registrations(), name) else { continue };
187                let owner = open_ro(&version.objects_db()).ok().and_then(|c| super::running::block_agent(&c, &entry.block_id));
188                if owner.as_deref() != Some(uid) {
189                    return Some(format!("a running pane is registered as it in {}", place(install, version)));
190                }
191            }
192        }
193        super::running::shared_entries(&self.home, name)
194            .into_iter()
195            .find(|e| e.uid != uid)
196            .map(|e| format!("a running pane in channel {} is registered as it", e.channel))
197    }
198}
199
200#[cfg(test)]
201mod tests {
202    use super::*;
203    use crate::backend::storage::store::Store;
204
205    fn version(root: &Path, channel: &str, v: &str) -> PathBuf {
206        let data = root.join("channels").join(channel).join("versions").join(v).join("data");
207        std::fs::create_dir_all(data.join("db")).unwrap();
208        drop(Store::open(&data.join("db").join("objects.db")).unwrap());
209        data
210    }
211
212    fn exec(data: &Path, sql: &str) {
213        rusqlite::Connection::open(data.join("db").join("objects.db")).unwrap().execute_batch(sql).unwrap();
214    }
215
216    #[test]
217    fn every_objects_db_counts_and_the_agents_own_rows_do_not() {
218        let tmp = tempfile::tempdir().unwrap();
219        let home = Home::at(tmp.path());
220        let a = version(tmp.path(), "ch-a", "1.0.0");
221        let b = version(tmp.path(), "ch-b", "2.0.0");
222        exec(&a, "INSERT INTO db_agents (id, name, provider, slug) VALUES ('uid-a', 'Claude', 'claude', 'Claude-2')");
223        exec(&b, "INSERT INTO db_agents (id, name, provider, slug) VALUES ('uid-b', 'Bee', 'claude', 'bee');
224                  INSERT INTO db_agent_former_slugs (agent_uid, slug, retired_at) VALUES ('uid-b', 'old-b', 1);
225                  INSERT INTO db_agent_former_names (agent_id, name, recorded_at) VALUES ('uid-b', 'Was Bee', 1);");
226
227        let host = HostSlugs::read(&home).unwrap();
228        assert!(host.slug_holder("claude-2", "uid-new").unwrap().contains("uid-a"));
229        assert!(host.slug_holder("claude-2", "uid-a").is_none(), "its own row");
230        assert!(host.slug_holder("old-b", "uid-new").unwrap().contains("renamed"));
231        assert!(host.slug_holder("was-bee", "uid-new").is_none(), "a former display name isn't a slug");
232        assert!(host.holder("was-bee", "uid-new").unwrap().contains("uid-b"));
233        assert!(host.holder("free", "uid-new").is_none());
234
235        // A change to a database is seen on the next read, not the cached one.
236        exec(&b, "INSERT INTO db_agents (id, name, provider, slug) VALUES ('uid-c', 'Free', 'claude', 'free')");
237        assert!(HostSlugs::read(&home).unwrap().holder("free", "uid-new").is_some());
238    }
239
240    #[test]
241    fn an_unreadable_objects_db_is_an_error() {
242        let tmp = tempfile::tempdir().unwrap();
243        let data = version(tmp.path(), "ch-a", "1.0.0");
244        std::fs::write(data.join("db").join("objects.db"), b"not a database, not at all").unwrap();
245        let err = HostSlugs::read(&Home::at(tmp.path())).err().expect("unreadable");
246        assert!(err.contains("objects.db"), "{err}");
247    }
248}