Skip to main content

agentmux_srv_core/backend/container/mounts/
caches.rs

1//! Cache volumes: directories an image asks to keep across container recreation, named in its
2//! `ai.agentmux.cache-dirs` label (the developer image lists its cargo home and build output).
3//! An image update removes the container and keeps volumes, so a toolchain's registry and build
4//! output there survive it. Spec: docs/specs/SPEC_CONTAINER_AGENT_DEVELOPER_IMAGE_2026_10_29.md section 4.
5
6use std::collections::HashMap;
7
8use bollard::models::{Mount, MountTypeEnum, MountVolumeOptions};
9use bollard::volume::{ListVolumesOptions, RemoveVolumeOptions};
10
11use super::{ContainerManager, CONTAINER_CLAUDE_DIR, CONTAINER_WORKSPACE_DIR};
12use crate::backend::rpc_types::ContainerCacheVolume;
13
14/// The image label that lists directories (absolute paths, separated by `:`) to keep in per-agent volumes.
15pub const CACHE_DIRS_LABEL: &str = "ai.agentmux.cache-dirs";
16
17/// Label on every volume made for an agent's container: which container, so a sweep can find them.
18pub const VOLUME_AGENT_LABEL: &str = "ai.agentmux.agent";
19
20/// Label on a volume that holds a cache (as opposed to a CLI or Claude home), so one can be cleared on its own.
21pub const VOLUME_KIND_LABEL: &str = "ai.agentmux.kind";
22
23/// The most directories one image may ask to keep.
24const MAX_CACHE_DIRS: usize = 6;
25
26/// Whether `a` and `b` are the same directory, or one is inside the other.
27fn overlaps(a: &str, b: &str) -> bool {
28    let (a, b) = (a.trim_end_matches('/'), b.trim_end_matches('/'));
29    a == b || a.strip_prefix(b).is_some_and(|r| r.starts_with('/')) || b.strip_prefix(a).is_some_and(|r| r.starts_with('/'))
30}
31
32/// The directories a label asks for that can be kept: absolute, plain (no `.` or `..` parts), not inside or around
33/// the workspace or Claude home and not one of the mounts already `taken`, at most [`MAX_CACHE_DIRS`], in order,
34/// each once. A label comes from an image that may be the user's own, so what it asks for is checked, not trusted.
35pub(super) fn parse_cache_dirs(label: &str, taken: &[String]) -> Vec<String> {
36    let mut dirs: Vec<String> = Vec::new();
37    for raw in label.split(':') {
38        let dir = raw.trim().trim_end_matches('/');
39        let plain = dir.starts_with('/') && dir.len() > 1 && dir.split('/').skip(1).all(|p| !p.is_empty() && p != "." && p != "..");
40        if !plain {
41            continue;
42        }
43        let reserved = [CONTAINER_CLAUDE_DIR, CONTAINER_WORKSPACE_DIR];
44        if reserved.iter().any(|r| overlaps(dir, r)) || taken.iter().any(|t| overlaps(dir, t)) || dirs.iter().any(|d| overlaps(dir, d)) {
45            continue;
46        }
47        dirs.push(dir.to_string());
48        if dirs.len() == MAX_CACHE_DIRS {
49            break;
50        }
51    }
52    dirs
53}
54
55/// The volume that keeps `dir` for `container_name`: `agentmux-cache-<container>-<dir as words>-<hash>`. The words
56/// are for a person reading `docker volume ls`; the hash of the exact container and directory is what keeps two
57/// different ones (`/a/.cargo` and `/a/cargo`, `/Cache` and `/cache`, agent `a` with `/b/c` and agent `a-b` with `/c`)
58/// from sharing a volume, and a label that lists its directories in another order still finds each one's data.
59pub(super) fn cache_volume_name(container_name: &str, dir: &str) -> String {
60    use sha2::{Digest, Sha256};
61    let mut words = String::new();
62    for c in dir.chars() {
63        let c = c.to_ascii_lowercase();
64        if c.is_ascii_alphanumeric() {
65            words.push(c);
66        } else if !words.ends_with('-') {
67            words.push('-');
68        }
69    }
70    let hash: String = Sha256::digest(format!("{container_name}\0{dir}")).iter().take(6).map(|b| format!("{b:02x}")).collect();
71    format!("agentmux-cache-{container_name}-{}-{hash}", words.trim_matches('-'))
72}
73
74fn cache_mount(container_name: &str, dir: &str) -> Mount {
75    Mount {
76        target: Some(dir.to_string()),
77        source: Some(cache_volume_name(container_name, dir)),
78        typ: Some(MountTypeEnum::VOLUME),
79        read_only: Some(false),
80        volume_options: Some(MountVolumeOptions {
81            labels: Some(HashMap::from([
82                (VOLUME_AGENT_LABEL.to_string(), container_name.to_string()),
83                (VOLUME_KIND_LABEL.to_string(), "cache".to_string()),
84            ])),
85            ..Default::default()
86        }),
87        ..Default::default()
88    }
89}
90
91impl ContainerManager {
92    /// The cache volumes a container about to be made from `image` gets: one per directory its label lists
93    /// (see [`parse_cache_dirs`]), none for an image without the label or one that is not here to read.
94    /// `taken` are the mounts it already has.
95    pub(in crate::backend::container) async fn cache_mounts_for_new(&self, container_name: &str, image: &str, taken: &[Mount]) -> Vec<Mount> {
96        let labels = self.docker().inspect_image(image).await.ok().and_then(|i| i.config).and_then(|c| c.labels);
97        let Some(label) = labels.as_ref().and_then(|l| l.get(CACHE_DIRS_LABEL)) else { return Vec::new() };
98        let taken: Vec<String> = taken.iter().filter_map(|m| m.target.clone()).collect();
99        parse_cache_dirs(label, &taken).iter().map(|dir| cache_mount(container_name, dir)).collect()
100    }
101
102    /// The cache volumes of `container_name` and what each holds, largest first (Docker's own disk-usage report,
103    /// which does not scan the volumes; a volume whose driver can't say is counted as 0).
104    pub async fn cache_volumes(&self, container_name: &str) -> Result<Vec<ContainerCacheVolume>, String> {
105        let usage = self.docker().df().await.map_err(|e| format!("Docker would not report volume sizes: {e}"))?;
106        let mut out: Vec<ContainerCacheVolume> = usage
107            .volumes
108            .unwrap_or_default()
109            .into_iter()
110            .filter(|v| v.labels.get(VOLUME_AGENT_LABEL).map(String::as_str) == Some(container_name) && v.labels.get(VOLUME_KIND_LABEL).map(String::as_str) == Some("cache"))
111            .map(|v| ContainerCacheVolume { bytes: v.usage_data.map_or(0, |u| u.size.max(0) as u64), name: v.name })
112            .collect();
113        out.sort_by(|a, b| b.bytes.cmp(&a.bytes).then_with(|| a.name.cmp(&b.name)));
114        Ok(out)
115    }
116
117    /// Removes the container and its cache volumes (the CLI and Claude home volumes stay): the next message starts a
118    /// new container, which fills them again. Returns what was removed. The caller makes sure no turn is using the
119    /// container.
120    pub async fn clear_caches(&self, container_name: &str) -> Result<Vec<ContainerCacheVolume>, String> {
121        let volumes = self.cache_volumes(container_name).await?;
122        let _ = self.stop(container_name, 10).await;
123        let _ = self.remove(container_name, true).await;
124        let mut removed = Vec::new();
125        for v in volumes {
126            match self.docker().remove_volume(&v.name, Some(RemoveVolumeOptions { force: true })).await {
127                Ok(()) | Err(bollard::errors::Error::DockerResponseServerError { status_code: 404, .. }) => removed.push(v),
128                Err(e) => return Err(format!("couldn't remove the volume {}: {e}", v.name)),
129            }
130        }
131        Ok(removed)
132    }
133
134    /// Removes the container and every volume made for an agent, once the agent is deleted: its cache volumes
135    /// (by label), and the CLI and Claude home volumes older versions made without one. Best effort: what is
136    /// not there, or is still in use, is skipped and logged.
137    pub async fn remove_agent_storage(&self, container_name: &str) {
138        let _ = self.stop(container_name, 10).await;
139        let _ = self.remove(container_name, true).await;
140        let mut names = vec![format!("agentmux-cli-{container_name}"), format!("agentmux-claude-{container_name}")];
141        let filter = HashMap::from([("label".to_string(), vec![format!("{VOLUME_AGENT_LABEL}={container_name}")])]);
142        match self.docker().list_volumes(Some(ListVolumesOptions { filters: filter })).await {
143            Ok(list) => names.extend(list.volumes.unwrap_or_default().into_iter().map(|v| v.name)),
144            Err(e) => tracing::warn!(container = container_name, error = %e, "container storage: can't list the agent's volumes"),
145        }
146        for name in names {
147            match self.docker().remove_volume(&name, Some(RemoveVolumeOptions { force: true })).await {
148                Ok(()) => tracing::info!(container = container_name, volume = %name, "removed an agent's volume"),
149                Err(bollard::errors::Error::DockerResponseServerError { status_code: 404, .. }) => {}
150                Err(e) => tracing::warn!(container = container_name, volume = %name, error = %e, "container storage: couldn't remove a volume"),
151            }
152        }
153    }
154}
155
156#[cfg(test)]
157mod tests {
158    use super::*;
159
160    #[test]
161    fn a_label_lists_plain_absolute_directories_in_order() {
162        assert_eq!(parse_cache_dirs("/home/agent/.cargo:/home/agent/target", &[]), ["/home/agent/.cargo", "/home/agent/target"]);
163        assert_eq!(parse_cache_dirs(" /a/b/ : /c ", &[]), ["/a/b", "/c"], "spaces and a trailing slash are dropped");
164        assert!(parse_cache_dirs("", &[]).is_empty());
165    }
166
167    #[test]
168    fn what_an_image_may_not_ask_for_is_skipped() {
169        let taken = ["/home/agent/.agentmux/cli".to_string()];
170        let label = "relative/dir:/:/a/../etc:/a/./b:/workspace:/workspace/target:/home/agent/.claude/projects:/home/agent:/home/agent/.agentmux/cli:/ok";
171        assert_eq!(parse_cache_dirs(label, &taken), ["/ok"], "no relative or odd paths, nothing in or around the workspace, Claude home or a mount it has");
172    }
173
174    #[test]
175    fn a_directory_is_asked_for_once_and_not_inside_another_it_asked_for() {
176        assert_eq!(parse_cache_dirs("/x/cargo:/x/cargo:/x/cargo/registry:/x/other", &[]), ["/x/cargo", "/x/other"]);
177        assert_eq!(parse_cache_dirs("/a:/b:/c:/d:/e:/f:/g:/h", &[]), ["/a", "/b", "/c", "/d", "/e", "/f"], "at most six");
178    }
179
180    /// The developer image's LABEL replaces the base image's, so it has to list the base image's directories too.
181    #[test]
182    fn the_developer_image_keeps_every_directory_the_base_image_asks_for() {
183        let label_of = |dockerfile: &str| {
184            let at = dockerfile.find("ai.agentmux.cache-dirs=\"").expect("the Dockerfile has the label") + "ai.agentmux.cache-dirs=\"".len();
185            dockerfile[at..].split('"').next().unwrap().to_string()
186        };
187        let base = parse_cache_dirs(&label_of(include_str!("../../../../../../docker/Dockerfile.agent-agentmux")), &[]);
188        let developer = parse_cache_dirs(&label_of(include_str!("../../../../../../docker/Dockerfile.agent-developer")), &[]);
189        assert_eq!(base, ["/home/agent/.cache/ms-playwright", "/home/agent/.npm", "/home/agent/.cache/pip"]);
190        for dir in &base {
191            assert!(developer.contains(dir), "the developer image's label drops {dir}");
192        }
193        assert!(developer.contains(&"/home/agent/.cargo".to_string()) && developer.contains(&"/home/agent/target".to_string()));
194    }
195
196    #[test]
197    fn different_agents_and_directories_never_share_a_volume() {
198        let name = |c: &str, d: &str| cache_volume_name(c, d);
199        assert_ne!(name("agentmux-a", "/home/agent/.cargo"), name("agentmux-a", "/home/agent/cargo"), "a dot is not nothing");
200        assert_ne!(name("agentmux-a", "/Cache"), name("agentmux-a", "/cache"), "nor is a capital");
201        assert_ne!(name("agentmux-a", "/b/c"), name("agentmux-a-b", "/c"), "nor which side of the dash a word is on");
202        assert_ne!(name("agentmux-a", "/x"), name("agentmux-b", "/x"));
203    }
204
205    #[test]
206    fn a_volume_is_named_by_its_agent_and_directory() {
207        let cargo = cache_volume_name("agentmux-demo", "/home/agent/.cargo");
208        assert!(cargo.starts_with("agentmux-cache-agentmux-demo-home-agent-cargo-"), "readable: {cargo}");
209        assert_eq!(cargo, cache_volume_name("agentmux-demo", "/home/agent/.cargo"), "the same input, the same volume");
210        assert!(cache_volume_name("agentmux-demo", "/home/agent/target").starts_with("agentmux-cache-agentmux-demo-home-agent-target-"));
211        let m = cache_mount("agentmux-demo", "/home/agent/target");
212        assert_eq!(m.typ, Some(MountTypeEnum::VOLUME));
213        let labels = m.volume_options.unwrap().labels.unwrap();
214        assert_eq!(labels.get(VOLUME_AGENT_LABEL).map(String::as_str), Some("agentmux-demo"));
215        assert_eq!(labels.get(VOLUME_KIND_LABEL).map(String::as_str), Some("cache"));
216    }
217}
218
219/// Live check against a real Docker daemon:
220///   cargo test -p agentmux-srv-core --lib -- --ignored --nocapture itest_cache_dirs
221/// An image that names cache directories gets a labelled volume for each; the data survives the container being
222/// recreated (what an image update does); deleting the agent removes the container and the volumes.
223#[cfg(test)]
224mod itest {
225    use bollard::container::{Config, CreateContainerOptions};
226    use bollard::image::{CommitContainerOptions, RemoveImageOptions};
227    use futures_util::StreamExt as _;
228
229    use super::*;
230    use crate::backend::container::ContainerMountSpec;
231
232    async fn run(cm: &ContainerManager, name: &str, script: &str) -> String {
233        let session = cm.exec(name, &["sh".into(), "-c".into(), script.into()], None, &[], false).await.expect("exec");
234        drop(session.input);
235        let mut out = String::new();
236        let mut stream = session.output;
237        while let Some(Ok(chunk)) = stream.next().await {
238            out.push_str(&String::from_utf8_lossy(&chunk.into_bytes()));
239        }
240        out
241    }
242
243    /// An image that is `debian:13` with the cache-dirs label, made by committing a container (no docker CLI).
244    async fn labelled_image(cm: &ContainerManager, image: &str) {
245        let maker = "agentmux-itest-cache-maker";
246        let _ = cm.docker().remove_container(maker, Some(bollard::container::RemoveContainerOptions { force: true, ..Default::default() })).await;
247        cm.docker()
248            .create_container(Some(CreateContainerOptions { name: maker, platform: None }), Config { image: Some("debian:13".to_string()), ..Default::default() })
249            .await
250            .expect("create the container to commit (debian:13 must be pulled)");
251        let labels = HashMap::from([(CACHE_DIRS_LABEL.to_string(), "/home/agent/.cargo:/home/agent/target".to_string())]);
252        let (repo, tag) = image.split_once(':').unwrap();
253        cm.docker()
254            .commit_container(
255                CommitContainerOptions { container: maker.to_string(), repo: repo.to_string(), tag: tag.to_string(), ..Default::default() },
256                Config::<String> { labels: Some(labels), cmd: Some(vec!["sleep".into(), "infinity".into()]), ..Default::default() },
257            )
258            .await
259            .expect("commit");
260        let _ = cm.docker().remove_container(maker, Some(bollard::container::RemoveContainerOptions { force: true, ..Default::default() })).await;
261    }
262
263    #[tokio::test]
264    #[ignore]
265    async fn itest_cache_dirs_survive_a_recreate_and_go_with_the_agent() {
266        let cm = ContainerManager::connect().expect("connect to docker (set DOCKER_HOST)");
267        cm.check_available().await.expect("docker daemon must be reachable");
268        let image = "agentmux-cache-itest:1";
269        labelled_image(&cm, image).await;
270
271        let name = "agentmux-itest-cache";
272        cm.remove_agent_storage(name).await;
273        let spec = ContainerMountSpec::default();
274        cm.ensure_running_observed(name, image, &[], &[], &spec, &|_| {}).await.expect("ensure_running");
275        let first = run(&cm, name, "echo built > /home/agent/target/artifact && echo registry > /home/agent/.cargo/crate && echo ok").await;
276        // What an image update does: the container goes, the volumes stay.
277        cm.update_container(name).await.expect("remove the container");
278        cm.ensure_running_observed(name, image, &[], &[], &spec, &|_| {}).await.expect("ensure_running again");
279        let kept = run(&cm, name, "cat /home/agent/target/artifact /home/agent/.cargo/crate").await;
280
281        let filter = HashMap::from([("label".to_string(), vec![format!("{VOLUME_AGENT_LABEL}={name}")])]);
282        let labelled: Vec<String> = cm
283            .docker()
284            .list_volumes(Some(ListVolumesOptions { filters: filter.clone() }))
285            .await
286            .unwrap()
287            .volumes
288            .unwrap_or_default()
289            .into_iter()
290            .map(|v| v.name)
291            .collect();
292
293        // Their sizes as Docker reports them, and clearing them (the container goes with them).
294        let sized = cm.cache_volumes(name).await.expect("volume sizes");
295        let freed = cm.clear_caches(name).await.expect("clear");
296        let after_clear = cm.cache_volumes(name).await.expect("volume sizes after clearing");
297        let container_gone_after_clear = cm.docker().inspect_container(name, None).await.is_err();
298
299        cm.remove_agent_storage(name).await;
300        let left = cm.docker().list_volumes(Some(ListVolumesOptions { filters: filter })).await.unwrap().volumes.unwrap_or_default().len();
301        let container_gone = cm.docker().inspect_container(name, None).await.is_err();
302        let _ = cm.docker().remove_image(image, Some(RemoveImageOptions { force: true, ..Default::default() }), None).await;
303
304        assert!(first.contains("ok"), "the agent can write into both cache directories: {first}");
305        assert_eq!(kept.trim(), "built\nregistry", "the data is there after the container was recreated: {kept:?}");
306        let mut labelled = labelled;
307        labelled.sort();
308        let mut want = [cache_volume_name(name, "/home/agent/.cargo"), cache_volume_name(name, "/home/agent/target")];
309        want.sort();
310        assert_eq!(labelled, want, "one labelled volume per directory");
311        assert_eq!(sized.len(), 2, "both caches are reported: {sized:?}");
312        assert!(sized.iter().all(|v| v.bytes > 0), "each holds what was written (Docker's own count): {sized:?}");
313        assert_eq!(freed.len(), 2, "clearing removed both");
314        assert!(after_clear.is_empty() && container_gone_after_clear, "and left nothing behind, the container included: {after_clear:?}");
315        assert_eq!(left, 0, "the agent's volumes are removed with it");
316        assert!(container_gone, "and its container");
317    }
318}