Skip to main content

agentmux_srv_core/backend/container/
pull.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//! Pulling a container agent's image: the progress the pane shows, and the
4//! limits that end a pull which has stopped (spec
5//! docs/specs/SPEC_CONTAINER_AGENTS_AT_PARITY_2026_10_27.md, P1 and P2).
6
7use bollard::image::CreateImageOptions;
8use futures_util::StreamExt as _;
9
10pub mod pinned;
11
12use super::{ContainerError, ContainerManager};
13use crate::backend::agent_image_digest::{pin_for_running_version, Pin, DEVELOPER_IMAGE_NAME, IMAGE_NAME};
14use crate::backend::container::image::{
15    classify_pull_error, floating_image_for, is_legacy_agent_image, is_versioned_agent_image, versioned_agent_image, versioned_developer_image, PullFailure,
16    DEFAULT_AGENT_IMAGE,
17};
18
19impl ContainerManager {
20    /// Pull `image`; a legacy image that the registry refuses or no longer has
21    /// is replaced by the public base image, and a version-pinned base image that
22    /// is missing or unreachable by `:latest`. Returns the image to run.
23    pub(super) async fn pull_with_fallback(&self, image: &str, observe: StartObserver<'_>) -> Result<String, ContainerError> {
24        // This AgentMux's own base image (or its developer variant) is run by the digest its signed release names,
25        // when it names one.
26        let listed_as = if image == versioned_agent_image() {
27            Some(IMAGE_NAME)
28        } else if image == versioned_developer_image() {
29            Some(DEVELOPER_IMAGE_NAME)
30        } else {
31            None
32        };
33        if let Some(listed_as) = listed_as {
34            match pin_for_running_version(listed_as).await {
35                Pin::Digest(reference) => {
36                    self.pull_pinned(image, &reference, observe).await?;
37                    return Ok(image.to_string());
38                }
39                Pin::Refused(detail) => return Err(ContainerError::ImagePull { image: image.to_string(), kind: PullFailure::Unverified, detail }),
40                Pin::Unpinned(_) => {}
41            }
42        }
43        match self.pull_image(image, observe).await {
44            Ok(()) => Ok(image.to_string()),
45            Err(ContainerError::ImagePull { kind, .. }) if kind.is_unavailable_image() && is_legacy_agent_image(image) => {
46                tracing::warn!(
47                    image = image,
48                    fallback = DEFAULT_AGENT_IMAGE,
49                    "legacy agent image can't be pulled; using the public base image"
50                );
51                self.pull_image(DEFAULT_AGENT_IMAGE, observe).await?;
52                Ok(DEFAULT_AGENT_IMAGE.to_string())
53            }
54            // A version tag that is not published (a build ahead of its release) or cannot be
55            // reached right now: the variant's floating tag (`:latest`, or `:developer`) is the best image available.
56            Err(ContainerError::ImagePull { kind, .. })
57                if (kind.is_unavailable_image() || kind == PullFailure::Network) && is_versioned_agent_image(image) =>
58            {
59                let fallback = floating_image_for(image);
60                tracing::info!(
61                    image = image,
62                    fallback = fallback,
63                    "the agent image for this version can't be pulled; using its floating tag, whose agentmux-mcp may be older than this srv"
64                );
65                self.pull_image(fallback, observe).await?;
66                Ok(fallback.to_string())
67            }
68            Err(e) => Err(e),
69        }
70    }
71
72    /// Pull `image` via the Docker socket (create_image API).
73    ///
74    /// Streams the pull response to completion before returning. If the image is
75    /// already present locally, Docker returns an empty stream immediately — this
76    /// function treats that as success (no pull needed).
77    ///
78    /// Errors only on genuine pull failures (network, auth, no such image).
79    async fn pull_image(&self, image: &str, observe: StartObserver<'_>) -> Result<(), ContainerError> {
80        // Skip the pull entirely when the image is already present locally.
81        // `create_image` always contacts the registry, so on an offline host the
82        // pull stream errors out even when the image is cached — aborting
83        // container creation even though `docker run` would start it from the
84        // local cache. An `inspect_image` short-circuit makes the cached-offline
85        // path work (and avoids a redundant registry round-trip when online).
86        if self.inner.docker.inspect_image(image).await.is_ok() {
87            tracing::info!(image = image, "image already present locally; skipping pull");
88            return Ok(());
89        }
90
91        tracing::info!(image = image, "pulling image (not cached locally)");
92        observe(StartEvent::Pulling { image, progress: None });
93        let mut stream = self.inner.docker.create_image(
94            Some(CreateImageOptions {
95                from_image: image,
96                ..Default::default()
97            }),
98            None,
99            None,
100        );
101        drain_pull(image, &mut stream, PullLimits::default(), observe).await?;
102        tracing::info!(image = image, "image pull complete (or already cached)");
103        Ok(())
104    }
105}
106
107/// How far an image download has got, from the byte counts the daemon reports
108/// for each layer it is downloading.
109#[derive(Debug, Clone, Copy, PartialEq, Eq)]
110pub struct PullProgress {
111    pub downloaded: u64,
112    pub total: u64,
113}
114
115impl PullProgress {
116    /// Whole percent, 0 to 100.
117    pub fn percent(&self) -> u8 {
118        if self.total == 0 {
119            return 0;
120        }
121        (self.downloaded.min(self.total) * 100 / self.total) as u8
122    }
123}
124
125/// A step of getting a container ready that takes long enough for a person to
126/// wonder what is happening.
127#[derive(Debug, Clone, Copy, PartialEq, Eq)]
128pub enum StartEvent<'a> {
129    /// The image is being downloaded; `progress` is `None` until the daemon
130    /// has reported any byte counts.
131    Pulling { image: &'a str, progress: Option<PullProgress> },
132    /// The image is here and the container is being created and started.
133    Starting,
134}
135
136/// Told about each [`StartEvent`]; called from the task that is starting the
137/// container, so it must not block.
138pub type StartObserver<'a> = &'a (dyn Fn(StartEvent<'_>) + Send + Sync);
139
140/// How long a pull may go quiet, and how long it may take in all.
141#[derive(Debug, Clone, Copy)]
142pub struct PullLimits {
143    pub stall: std::time::Duration,
144    pub total: std::time::Duration,
145}
146
147impl Default for PullLimits {
148    fn default() -> Self {
149        Self {
150            stall: std::time::Duration::from_secs(crate::backend::container::image::PULL_STALL_SECS),
151            total: std::time::Duration::from_secs(crate::backend::container::image::PULL_TOTAL_SECS),
152        }
153    }
154}
155
156/// Turns the daemon's per-layer byte counts into [`PullProgress`] updates,
157/// few enough to show: the first one, then one every two seconds when the
158/// percentage moved, or sooner when it jumped by ten points.
159#[derive(Default)]
160struct PullTracker {
161    layers: std::collections::HashMap<String, (u64, u64)>,
162    last: Option<(std::time::Instant, u8)>,
163}
164
165impl PullTracker {
166    fn observe(&mut self, info: &bollard::models::CreateImageInfo, now: std::time::Instant) -> Option<PullProgress> {
167        let id = info.id.as_deref()?;
168        let status = info.status.as_deref().unwrap_or_default();
169        // Only `Downloading` counts are download bytes: `Extracting` reports
170        // uncompressed sizes, which would make the percentage jump back.
171        if let Some(total) = info
172            .progress_detail
173            .as_ref()
174            .and_then(|d| d.total)
175            .filter(|t| *t > 0 && status.starts_with("Downloading"))
176        {
177            let current = info.progress_detail.as_ref().and_then(|d| d.current).unwrap_or(0).clamp(0, total);
178            self.layers.insert(id.to_string(), (current as u64, total as u64));
179        } else if status.starts_with("Download complete") || status.starts_with("Pull complete") {
180            if let Some(layer) = self.layers.get_mut(id) {
181                layer.0 = layer.1;
182            }
183        } else {
184            return None;
185        }
186        let progress = PullProgress {
187            downloaded: self.layers.values().map(|l| l.0).sum(),
188            total: self.layers.values().map(|l| l.1).sum(),
189        };
190        let percent = progress.percent();
191        let due = match self.last {
192            None => true,
193            Some((at, last)) => {
194                percent >= last.saturating_add(10) || (percent != last && now.duration_since(at) >= std::time::Duration::from_secs(2))
195            }
196        };
197        if !due {
198            return None;
199        }
200        self.last = Some((now, percent));
201        Some(progress)
202    }
203}
204
205/// Read a pull's stream to its end, reporting progress, and give up when it
206/// goes quiet for `limits.stall` or runs past `limits.total`. Dropping the
207/// stream cancels the download at the daemon, so nothing is left running.
208async fn drain_pull<S>(
209    image: &str,
210    stream: &mut S,
211    limits: PullLimits,
212    observe: StartObserver<'_>,
213) -> Result<(), ContainerError>
214where
215    S: futures_util::Stream<Item = Result<bollard::models::CreateImageInfo, bollard::errors::Error>> + Unpin,
216{
217    let started = std::time::Instant::now();
218    let mut tracker = PullTracker::default();
219    loop {
220        let left = limits.total.saturating_sub(started.elapsed());
221        let total_is_next = left <= limits.stall;
222        let wait = limits.stall.min(left);
223        let item = match tokio::time::timeout(wait, stream.next()).await {
224            Ok(item) => item,
225            Err(_) => {
226                let kind = if total_is_next { PullFailure::TooSlow } else { PullFailure::Stalled };
227                tracing::warn!(image = image, ?kind, elapsed_s = started.elapsed().as_secs(), "image pull given up");
228                return Err(ContainerError::ImagePull {
229                    image: image.to_string(),
230                    kind,
231                    detail: format!("no end after {} s", started.elapsed().as_secs()),
232                });
233            }
234        };
235        match item {
236            None => return Ok(()),
237            Some(Ok(info)) => {
238                if let Some(status) = &info.status {
239                    tracing::debug!(image = image, status = %status, "pull progress");
240                }
241                if let Some(progress) = tracker.observe(&info, std::time::Instant::now()) {
242                    observe(StartEvent::Pulling { image, progress: Some(progress) });
243                }
244            }
245            Some(Err(e)) => {
246                tracing::warn!(image = image, error = %e, "image pull error");
247                return Err(pull_error(image, &e));
248            }
249        }
250    }
251}
252
253/// Map a bollard pull error to [`ContainerError::ImagePull`].
254pub(super) fn pull_error(image: &str, e: &bollard::errors::Error) -> ContainerError {
255    let status = match e {
256        bollard::errors::Error::DockerResponseServerError { status_code, .. } => Some(*status_code),
257        _ => None,
258    };
259    let detail = e.to_string();
260    ContainerError::ImagePull {
261        image: image.to_string(),
262        kind: classify_pull_error(status, &detail),
263        detail,
264    }
265}
266
267#[cfg(test)]
268mod itest;
269
270#[cfg(test)]
271mod tests {
272    use super::*;
273    use bollard::models::{CreateImageInfo, ProgressDetail};
274    use futures_util::stream;
275    use std::sync::Mutex as StdMutex;
276    use std::time::Duration;
277
278    fn layer(id: &str, status: &str, current: i64, total: i64) -> CreateImageInfo {
279        CreateImageInfo {
280            id: Some(id.to_string()),
281            status: Some(status.to_string()),
282            progress_detail: Some(ProgressDetail { current: Some(current), total: Some(total) }),
283            ..Default::default()
284        }
285    }
286
287    type Seen = StdMutex<Vec<Option<u8>>>;
288
289    fn recorder(seen: &Seen) -> impl Fn(StartEvent<'_>) + Send + Sync + '_ {
290        move |event| {
291            if let StartEvent::Pulling { progress, .. } = event {
292                seen.lock().unwrap().push(progress.map(|p| p.percent()));
293            }
294        }
295    }
296
297    fn quick() -> PullLimits {
298        PullLimits { stall: Duration::from_millis(60), total: Duration::from_millis(400) }
299    }
300
301    #[tokio::test]
302    async fn a_pull_that_goes_quiet_is_given_up_with_the_stalled_kind() {
303        let seen = Seen::default();
304        let mut quiet = stream::pending::<Result<CreateImageInfo, bollard::errors::Error>>();
305        let started = std::time::Instant::now();
306        let err = drain_pull("ghcr.io/x/y:z", &mut quiet, quick(), &recorder(&seen)).await.unwrap_err();
307        assert!(matches!(&err, ContainerError::ImagePull { kind: PullFailure::Stalled, .. }), "{err:?}");
308        assert!(started.elapsed() < Duration::from_millis(350), "gave up at the stall limit, not the total");
309        assert!(err.user_message().contains("no data for"), "{}", err.user_message());
310    }
311
312    #[tokio::test]
313    async fn a_pull_that_keeps_trickling_is_given_up_at_the_total_limit() {
314        let seen = Seen::default();
315        // One layer item every 30 ms, so the stall limit (60 ms) never trips.
316        let mut trickle = Box::pin(stream::unfold(0i64, |n| async move {
317            tokio::time::sleep(Duration::from_millis(30)).await;
318            Some((Ok::<_, bollard::errors::Error>(layer("a", "Downloading", n, 1_000_000)), n + 1))
319        }));
320        let err = drain_pull("ghcr.io/x/y:z", &mut trickle, quick(), &recorder(&seen)).await.unwrap_err();
321        assert!(matches!(&err, ContainerError::ImagePull { kind: PullFailure::TooSlow, .. }), "{err:?}");
322    }
323
324    #[tokio::test]
325    async fn a_pull_that_finishes_reports_progress_and_succeeds() {
326        let seen = Seen::default();
327        let items: Vec<Result<CreateImageInfo, bollard::errors::Error>> = vec![
328            Ok(CreateImageInfo { status: Some("Pulling from x/y".into()), ..Default::default() }),
329            Ok(layer("a", "Downloading", 10, 100)),
330            Ok(layer("a", "Downloading", 100, 100)),
331        ];
332        let mut s = stream::iter(items);
333        drain_pull("ghcr.io/x/y:z", &mut s, quick(), &recorder(&seen)).await.expect("pull ends cleanly");
334        let seen = seen.lock().unwrap().clone();
335        assert_eq!(seen.first(), Some(&Some(10)), "the first count is shown at once: {seen:?}");
336        assert_eq!(seen.last(), Some(&Some(100)), "a jump of ten points or more is shown at once: {seen:?}");
337    }
338
339    #[test]
340    fn progress_is_summed_over_layers_and_shown_sparingly() {
341        let now = std::time::Instant::now();
342        let mut t = PullTracker::default();
343        // First count: shown (10 of 100 bytes = 10 %).
344        assert_eq!(t.observe(&layer("a", "Downloading", 10, 100), now).map(|p| p.percent()), Some(10));
345        assert_eq!(t.observe(&layer("b", "Downloading", 10, 100), now), None, "same percent window, under 2 s, under 10 points");
346        // A change of under 10 points, 2 s later: shown.
347        let later = now + Duration::from_secs(2);
348        assert_eq!(t.observe(&layer("b", "Downloading", 20, 100), later).map(|p| p.percent()), Some(15));
349        // A layer that says it is complete counts as fully downloaded, and a 10-point jump is shown at once.
350        let done = CreateImageInfo { id: Some("a".into()), status: Some("Download complete".into()), ..Default::default() };
351        assert_eq!(t.observe(&done, later).map(|p| p.percent()), Some(60));
352        // A layer extracting after its download is not download progress.
353        let extracting = layer("a", "Extracting", 5, 1000);
354        assert_eq!(t.observe(&extracting, later + Duration::from_secs(5)), None);
355        assert_eq!(t.observe(&layer("c", "Downloading", 0, 100), later + Duration::from_secs(5)).map(|p| p.percent()), Some(40));
356        // Items without a layer id or byte counts say nothing.
357        assert_eq!(t.observe(&CreateImageInfo { status: Some("Pulling fs layer".into()), ..Default::default() }, later), None);
358    }
359}