From 1ef4505a690db1618966c4874d8bc0baff7c4ee3 Mon Sep 17 00:00:00 2001 From: Josh Knapp Date: Mon, 2 Nov 2026 15:19:43 -0800 Subject: [PATCH] Gateway upgrade: pull only at launch, never tear down a working gateway Third-review follow-ups: - The pinned image is pulled in the background at app launch only, not inside every ensure, so Start and settings saves never stall on a download. - With no pinned image present, ensure keeps the gateway on the image it already runs (recreated with new config if that changed) instead of removing it; status reports it as outdated. - The container is created from the resolved image id, so a concurrent build/pull retag can't make it disagree with its fingerprint. - "Outdated" means the container runs neither pinned image, so a later local build of the same pin doesn't flag a registry-image gateway. - After starting on the pin, superseded triple-c-gateway:* tags (the old floating `latest`, earlier pins) are removed so they don't linger. - Reuse container::remove_container (404-tolerant); fix misplaced docs. - Settings: Start needs an image again (no silent pull); the outdated label says whether to Pull/Build or to Stop and Start. Co-Authored-By: Claude Opus 5.5 --- app/src-tauri/src/docker/gateway.rs | 256 +++++++++++------- app/src-tauri/src/lib.rs | 7 + .../settings/GatewaySettings.test.tsx | 15 +- .../components/settings/GatewaySettings.tsx | 31 +-- 4 files changed, 191 insertions(+), 118 deletions(-) diff --git a/app/src-tauri/src/docker/gateway.rs b/app/src-tauri/src/docker/gateway.rs index 6ec3708..cfeb9d2 100644 --- a/app/src-tauri/src/docker/gateway.rs +++ b/app/src-tauri/src/docker/gateway.rs @@ -21,7 +21,7 @@ //! `docker inspect`. use bollard::container::{ - Config, CreateContainerOptions, ListContainersOptions, RemoveContainerOptions, + Config, CreateContainerOptions, ListContainersOptions, StartContainerOptions, StopContainerOptions, UploadToContainerOptions, }; use bollard::image::BuildImageOptions; @@ -96,31 +96,109 @@ fn choose_gateway_image(local_id: Option, registry_id: Option) - }) } -/// `Ok(None)` when neither pinned image is present; other Docker errors are -/// returned so "Docker is unreachable" is not mistaken for "image missing". -async fn resolve_gateway_image() -> Result, String> { +/// Ids of the locally present images that carry the current pin. +#[derive(Debug, Clone, Default, PartialEq)] +struct PinnedImages { + local: Option, + registry: Option, +} + +impl PinnedImages { + fn chosen(&self) -> Option { + choose_gateway_image(self.local.clone(), self.registry.clone()) + } + + /// Either pinned image counts as current: a container on the registry + /// image is not "outdated" just because a local build of the same pin + /// appeared later. + fn contains(&self, image_id: &str) -> bool { + self.local.as_deref() == Some(image_id) || self.registry.as_deref() == Some(image_id) + } +} + +/// Other Docker errors are returned so "Docker is unreachable" is not mistaken +/// for "image missing". +async fn pinned_images() -> Result { let local_ref = local_image_ref(); let (local, registry) = tokio::join!( super::migration::image_id(&local_ref), super::migration::image_id(GATEWAY_REGISTRY_IMAGE) ); - Ok(choose_gateway_image(local?, registry?)) + Ok(PinnedImages { + local: local?, + registry: registry?, + }) } -/// Whether an existing gateway container is running something other than the -/// pinned image. Unknown (the image check failed) is reported as not outdated -/// rather than guessed. +/// Whether an existing gateway container runs something other than a pinned +/// image. Unknown (the image check failed) is reported as not outdated rather +/// than guessed. fn container_image_outdated( container_image_id: Option<&str>, - chosen: Result, ()>, + pinned: Result<&PinnedImages, ()>, ) -> bool { - match (container_image_id, chosen) { - (None, _) | (_, Err(())) => false, - (Some(_), Ok(None)) => true, - (Some(running), Ok(Some(chosen))) => running != chosen.id, + match (container_image_id, pinned) { + (Some(running), Ok(pinned)) => !pinned.contains(running), + _ => false, } } +/// Pull the pinned upstream image if neither pinned image is present. Called +/// in the background at app launch (not on Start or a settings save, which +/// must not stall for a multi-hundred-MB download), so the first start after +/// an app update moves the gateway onto the new pin without a manual step. +/// Returns whether a pull happened. +pub async fn pull_pinned_image_if_missing() -> Result { + if pinned_images().await?.chosen().is_some() { + return Ok(false); + } + log::info!( + "No gateway image for LiteLLM {} — pulling {}", + pinned_litellm_version(), + GATEWAY_REGISTRY_IMAGE + ); + super::image::pull_image(GATEWAY_REGISTRY_IMAGE, |_| {}).await?; + Ok(true) +} + +/// Drop `triple-c-gateway:*` tags other than the current pin — the old +/// floating `latest`, and builds for earlier pins — so a superseded LiteLLM +/// build doesn't sit on disk forever as a tagged orphan. Best effort. +async fn remove_superseded_local_builds() { + let Ok(docker) = get_docker() else { return }; + let filters: HashMap> = HashMap::from([( + "reference".to_string(), + vec![GATEWAY_LOCAL_REPO.to_string()], + )]); + let images = match docker + .list_images(Some(bollard::image::ListImagesOptions { + filters, + ..Default::default() + })) + .await + { + Ok(images) => images, + Err(e) => { + log::debug!("Could not list old gateway builds: {}", e); + return; + } + }; + let current = local_image_ref(); + for tag in images.iter().flat_map(|i| i.repo_tags.iter()) { + if is_superseded_local_build(tag, ¤t) { + if let Err(e) = super::container::remove_image_by_name(tag).await { + log::warn!("Could not remove old gateway build {}: {}", tag, e); + } + } + } +} + +fn is_superseded_local_build(tag: &str, current: &str) -> bool { + tag.strip_prefix(GATEWAY_LOCAL_REPO) + .is_some_and(|rest| rest.starts_with(':')) + && tag != current +} + const GATEWAY_DOCKERFILE: &str = include_str!("../../../../gateway-container/Dockerfile"); const GATEWAY_DEFAULT_CONFIG: &str = include_str!("../../../../gateway-container/config.yaml"); @@ -281,10 +359,10 @@ fn sha256_hex(input: &str) -> String { } pub async fn get_gateway_status(settings: &GatewaySettings) -> Result { - let chosen = resolve_gateway_image().await.map_err(|e| { + let pinned = pinned_images().await.map_err(|e| { log::warn!("Gateway image check failed: {}", e); }); - let image_exists = matches!(chosen, Ok(Some(_))); + let image_exists = matches!(&pinned, Ok(p) if p.chosen().is_some()); let container = find_gateway_container().await?; let (container_exists, running) = match &container { @@ -293,7 +371,7 @@ pub async fn get_gateway_status(settings: &GatewaySettings) -> Result>) -> bool { names.is_some_and(|names| names.iter().any(|n| n == &expected)) } -/// `(id, state, config fingerprint label)` for the gateway container, if any. -/// `(id, state, config fingerprint label, image id)` for the gateway container. +/// `(id, state, config fingerprint label, image id)` for the gateway container, +/// if any. async fn find_gateway_container() -> Result)>, String> { let docker = get_docker()?; @@ -554,7 +632,9 @@ async fn create_gateway_container( ); let config = Config { - image: Some(image.reference.clone()), + // The resolved id, not the tag: a build or pull retagging the image + // mid-create can't make the container disagree with its fingerprint. + image: Some(image.id.clone()), // The upstream entrypoint (`docker/prod_entrypoint.sh`) execs // `litellm "$@"`. Passed explicitly so the pulled upstream image and // our locally built one behave identically. @@ -585,6 +665,12 @@ async fn create_gateway_container( Ok(response.id) } +/// Force-removes (no graceful stop: LiteLLM holds no state worth flushing), +/// tolerating a container that is already gone. +async fn remove_gateway_container(id: &str) -> Result<(), String> { + super::container::remove_container(id).await +} + /// Serialises every mutation of the single fixed-name gateway container. /// /// `ensure_gateway_running` is check-then-act over one container name, so two @@ -595,59 +681,18 @@ async fn create_gateway_container( /// refuse, because the second caller then observes the first's container, finds /// a matching fingerprint, and returns its status — which is exactly what it /// asked for. -async fn remove_gateway_container(docker: &Docker, id: &str, state: &str) -> Result<(), String> { - if state == "running" { - docker - .stop_container(id, None::) - .await - .map_err(|e| format!("Failed to stop gateway container: {}", e))?; - } - docker - .remove_container( - id, - Some(RemoveContainerOptions { - force: true, - ..Default::default() - }), - ) - .await - .map_err(|e| format!("Failed to remove gateway container: {}", e)) -} - fn gateway_lock() -> &'static Mutex<()> { static LOCK: OnceLock> = OnceLock::new(); LOCK.get_or_init(|| Mutex::new(())) } pub async fn ensure_gateway_running(settings: &GatewaySettings) -> Result { - // Typically the first start after an app update moved the pin: fetch the - // pinned image so the user isn't left on the old LiteLLM. Done *before* - // taking the lock — a multi-hundred-MB download must not hold up Stop or - // shutdown, which take the same lock. Skipped when the start would fail on - // configuration anyway. - let mut pull_error = None; - if !settings.valid_models().is_empty() - && secure::has_gateway_api_key() - && resolve_gateway_image().await?.is_none() - { - log::info!( - "No gateway image for LiteLLM {} — pulling {}", - pinned_litellm_version(), - GATEWAY_REGISTRY_IMAGE - ); - if let Err(e) = super::image::pull_image(GATEWAY_REGISTRY_IMAGE, |_| {}).await { - log::warn!("Gateway image pull failed: {}", e); - pull_error = Some(e); - } - } - let _guard = gateway_lock().lock().await; - ensure_gateway_running_locked(settings, pull_error).await + ensure_gateway_running_locked(settings).await } async fn ensure_gateway_running_locked( settings: &GatewaySettings, - pull_error: Option, ) -> Result { let docker = get_docker()?; @@ -669,28 +714,34 @@ async fn ensure_gateway_running_locked( // Rotation id, not a hash of either secret — see `storage::secure`. let secret_version = secure::get_gateway_secret_version()?.unwrap_or_default(); - let Some(image) = resolve_gateway_image().await? else { - let mut message = format!( - "The gateway needs LiteLLM {} and {}. Pull or build the image in Settings.", - pinned_litellm_version(), - match &pull_error { - Some(e) => format!("pulling it failed: {}", e), - None => "that image is not available locally".to_string(), + let existing = find_gateway_container().await?; + let pinned = pinned_images().await?; + let on_pin = pinned.chosen().is_some(); + let image = match pinned.chosen() { + Some(image) => image, + // No pinned image yet (the launch-time pull failed or is still + // running). Never tear down a working gateway over that: keep it on + // the image it already runs — recreated with the new config if that + // changed — and let status report it as outdated. + None => match existing.as_ref().and_then(|c| c.3.clone()) { + Some(id) => { + log::warn!( + "Gateway image for LiteLLM {} not present; keeping the gateway on its current image {}", + pinned_litellm_version(), + id + ); + ChosenImage { + reference: id.clone(), + id, + } } - ); - // Neither pinned image exists, so any existing container runs an old - // LiteLLM — and, after a settings change or key rotation, an old - // config and old keys. Never leave it serving. - if let Some((id, state, _, _)) = find_gateway_container().await? { - match remove_gateway_container(&docker, &id, &state).await { - Ok(()) => message.push_str(" The out-of-date gateway container was removed."), - Err(e) => message.push_str(&format!( - " Removing the out-of-date gateway container also failed: {}", - e - )), + None => { + return Err(format!( + "Gateway image for LiteLLM {} not found. Please pull or build the image first.", + pinned_litellm_version() + )) } - } - return Err(message); + }, }; // The image id is part of the fingerprint: once the new pinned image is @@ -701,7 +752,7 @@ async fn ensure_gateway_running_locked( &image.id, ); - if let Some((id, state, existing_fingerprint, _)) = find_gateway_container().await? { + if let Some((id, state, existing_fingerprint, _)) = existing { if existing_fingerprint == fingerprint { if state == "running" { return get_gateway_status(settings).await; @@ -715,7 +766,7 @@ async fn ensure_gateway_running_locked( // Config, a secret or the image changed — recreate so the new config // is uploaded and the pinned image is used. - remove_gateway_container(&docker, &id, &state).await?; + remove_gateway_container(&id).await?; } let id = create_gateway_container(settings, &binding, &image, &fingerprint).await?; @@ -725,8 +776,7 @@ async fn ensure_gateway_running_locked( if let Err(e) = upload_config(&id, &rendered).await { // Don't leave a half-configured container behind for the next run to // mistake for a good one. - // Never started, so "created" skips the stop. - if let Err(cleanup) = remove_gateway_container(&docker, &id, "created").await { + if let Err(cleanup) = remove_gateway_container(&id).await { log::warn!("{}", cleanup); } return Err(e); @@ -738,11 +788,15 @@ async fn ensure_gateway_running_locked( .map_err(|e| format!("Failed to start gateway container: {}", e))?; log::info!( - "Model gateway started on {}:{} ({} model(s))", + "Model gateway started on {}:{} ({} model(s), {})", binding.host_ip, settings.port, - settings.valid_models().len() + settings.valid_models().len(), + image.reference ); + if on_pin { + remove_superseded_local_builds().await; + } get_gateway_status(settings).await } @@ -941,17 +995,33 @@ mod tests { } #[test] - fn outdated_means_the_container_runs_another_image() { - let pinned = chosen(GATEWAY_REGISTRY_IMAGE, "sha256:new"); - assert!(!container_image_outdated(Some("sha256:new"), Ok(Some(&pinned)))); - assert!(container_image_outdated(Some("sha256:old"), Ok(Some(&pinned)))); + fn outdated_means_the_container_runs_neither_pinned_image() { + let both = PinnedImages { + local: Some("sha256:local".into()), + registry: Some("sha256:reg".into()), + }; + // Either pinned image is current — a later local build of the same + // pin doesn't make the registry-image container "outdated". + assert!(!container_image_outdated(Some("sha256:local"), Ok(&both))); + assert!(!container_image_outdated(Some("sha256:reg"), Ok(&both))); + assert!(container_image_outdated(Some("sha256:old"), Ok(&both))); // No pinned image at all: whatever runs is not it. - assert!(container_image_outdated(Some("sha256:old"), Ok(None))); + assert!(container_image_outdated(Some("sha256:old"), Ok(&PinnedImages::default()))); // No container, or the check failed: don't claim it. - assert!(!container_image_outdated(None, Ok(Some(&pinned)))); + assert!(!container_image_outdated(None, Ok(&both))); assert!(!container_image_outdated(Some("sha256:old"), Err(()))); } + #[test] + fn only_other_gateway_tags_are_superseded() { + let current = local_image_ref(); + assert!(is_superseded_local_build("triple-c-gateway:latest", ¤t)); + assert!(is_superseded_local_build("triple-c-gateway:v1.82.6", ¤t)); + assert!(!is_superseded_local_build(¤t, ¤t)); + assert!(!is_superseded_local_build("triple-c-gateway-other:latest", ¤t)); + assert!(!is_superseded_local_build("ghcr.io/berriai/litellm:v1.82.6", ¤t)); + } + #[test] fn new_image_changes_the_fingerprint() { let a = gateway_fingerprint("shape", "1", "sha256:old"); diff --git a/app/src-tauri/src/lib.rs b/app/src-tauri/src/lib.rs index 70f905f..fdd1f9c 100644 --- a/app/src-tauri/src/lib.rs +++ b/app/src-tauri/src/lib.rs @@ -398,6 +398,13 @@ pub fn run() { let cancel = lifecycle_setup.cancellation(); let handle = tauri::async_runtime::spawn(async move { autostart_with_retry("Model gateway", cancel, || async { + // After an app update moved the LiteLLM pin, fetch the + // new image so this start moves the gateway onto it. A + // failure is not fatal: ensure keeps a working gateway + // on its current image. + if let Err(e) = docker::gateway::pull_pinned_image_if_missing().await { + log::warn!("Model gateway image pull failed: {}", e); + } let status = docker::gateway::ensure_gateway_running(&gateway_settings).await?; if status.running { diff --git a/app/src/components/settings/GatewaySettings.test.tsx b/app/src/components/settings/GatewaySettings.test.tsx index 66da123..7ec2af3 100644 --- a/app/src/components/settings/GatewaySettings.test.tsx +++ b/app/src/components/settings/GatewaySettings.test.tsx @@ -103,26 +103,23 @@ describe("GatewaySettings", () => { ); await waitFor(() => expect(getGatewayStatus).toHaveBeenCalledTimes(2)); }); - it("can stop a gateway running an outdated image, and says so", async () => { + it("can stop a gateway running an outdated image, and says what to do", async () => { appSettings = settingsWithGateway(true); - getGatewayStatus.mockResolvedValue(status({ image_outdated: true })); + getGatewayStatus.mockResolvedValue(status({ image_outdated: true, image_exists: false })); render(); const stop = await screen.findByRole("button", { name: "Stop" }); - expect(screen.getByText(/outdated LiteLLM/i)).toBeInTheDocument(); + expect(screen.getByText(/LiteLLM update available, Pull or Build/i)).toBeInTheDocument(); fireEvent.click(stop); await waitFor(() => expect(stopGateway).toHaveBeenCalledTimes(1)); }); - it("offers Start without an image, since Start pulls it", async () => { + it("says Stop and Start applies a LiteLLM update once the image is present", async () => { appSettings = settingsWithGateway(true); - getGatewayStatus.mockResolvedValue( - status({ running: false, container_exists: false, image_exists: false }), - ); + getGatewayStatus.mockResolvedValue(status({ image_outdated: true })); render(); - expect(await screen.findByRole("button", { name: "Start" })).toBeInTheDocument(); - expect(screen.getByText(/Start will pull it/i)).toBeInTheDocument(); + expect(await screen.findByText(/update ready, Stop and Start/i)).toBeInTheDocument(); }); }); diff --git a/app/src/components/settings/GatewaySettings.tsx b/app/src/components/settings/GatewaySettings.tsx index 46fda82..b162beb 100644 --- a/app/src/components/settings/GatewaySettings.tsx +++ b/app/src/components/settings/GatewaySettings.tsx @@ -178,8 +178,7 @@ export default function GatewaySettings() { setTimeout(() => setCopied(null), 2000); }; - // A running container is shown (and stoppable) whatever its image. Start - // pulls the pinned image itself when it is missing, so it is always offered. + // A running container is shown (and stoppable) whatever its image. const tone: StatusTone = status?.running ? healthy === false || status.image_outdated ? "busy" @@ -188,19 +187,19 @@ export default function GatewaySettings() { ? "stopped" : "off"; - const statusLabel = !status - ? "Checking…" - : status.running - ? healthy === false - ? "Starting…" - : status.image_outdated - ? `Running on port ${status.port} — outdated LiteLLM, Stop and Start to update` - : `Running on port ${status.port}` - : !status.image_exists - ? "No image — Start will pull it" - : status.container_exists - ? "Stopped" - : "Image ready"; + const statusLabel = status?.running + ? healthy === false + ? "Starting…" + : status.image_outdated + ? status.image_exists + ? `Running on port ${status.port} — LiteLLM update ready, Stop and Start to apply` + : `Running on port ${status.port} — LiteLLM update available, Pull or Build to get it` + : `Running on port ${status.port}` + : !status?.image_exists + ? "No image" + : status.container_exists + ? "Stopped" + : "Image ready"; // Rendered in whichever branch is live — only one of them ever mounts. const errorLine = error ? ( @@ -258,7 +257,7 @@ export default function GatewaySettings() { {/* ── Container ─────────────────────────────────────────────── */}
- {status && ( + {(status?.image_exists || status?.running) && (