8000 fix(sandbox): release old images after any replacement, never a named one by ID by geminixiang · Pull Request #177 · geminixiang/mikan · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/adr/0023-mikan-keeps-its-sandbox-image-current.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ ADR 0009 left pulling to deployments: mikan compared containers with the local i
- **One image per release.** A release publishes `:<version>`; stable releases also move `:latest`. A release whose Dockerfile is unchanged and whose image is under 30 days old tags the previous image instead of rebuilding it, so most upgrades download nothing and replace no container, while tools still refresh about monthly.
- **The version picks the image.** `--sandbox=oci` resolves to that release's tag, so mikan and its sandbox upgrade and roll back together. `oci:<image>` keeps any other image.
- **mikan pulls.** A pull at start is a manifest check when nothing changed. A failed pull is a warning, and offices keep the local image; an image that exists only locally keeps working. Creating a container waits for the same pull rather than starting another.
- **mikan removes only what it stopped using.** After replacing a container for image drift, it runs `rmi` without force on the old container's published reference, or on its image ID otherwise. Engines refuse while any container uses the image, and an image ID while a name still points to it, so an operator's own images and tags stay.
- **mikan removes only what it stopped using.** After replacing a container whose image differs from the configured one, for any drift reason, it runs `rmi` without force on the old container's published reference, or on its image ID when no name points to that image any more. Engines refuse while any container uses the image, and an image with a name is never removed by ID, because Docker deletes it even then, so an operator's own images and tags stay.

## Considered options

Expand Down
18 changes: 11 additions & 7 deletions docs/research/sandbox-image-versions-2026-10.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,13 @@ Each release publishes `ghcr.io/geminixiang/mikan-sandbox:<version>`, and stable

## Engine behavior the design relies on

| Behavior | Result |
| -------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- |
| `pull` of a reference already present and current | completes after a manifest check and changes nothing |
| `pull` of a reference the registry lacks | fails; a local image with that reference stays usable |
| `rmi <reference>` without `-f` while any container, running or stopped, uses the image | refused (nerdctl: "image is being used by stopped container"; Docker when it is the only name) |
| `rmi <image ID>` | Docker refuses while several names point to the image; nerdctl answers "no such image" for any ID |
| a tag moved by a pull or `tag` on nerdctl | leaves no unnamed image behind |
| Behavior | Result |
| -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
| `pull` of a reference already present and current | completes after a manifest check and changes nothing |
| `pull` of a reference the registry lacks | fails; a local image with that reference stays usable |
| `rmi <reference>` without `-f` while any container, running or stopped, uses the image | refused (nerdctl: "image is being used by stopped container"; Docker when it is the only name) |
| `rmi <image ID>` | Docker refuses while several names point to the image but deletes an image with exactly one name; nerdctl answers "no such image" for any ID |
| a tag moved by a pull or `tag` on nerdctl | leaves no unnamed image behind |

## Design

Expand Down Expand Up @@ -54,3 +54,7 @@ Rejected:
| C7 running office during an upgrade | stays on 1.0.0 | stays on 1.0.0 |
| C8 new office after upgrading | 1.1.0 | 1.1.0 |
| C9 `:latest` moved on the registry, daemon restarted | stays on 1.0.0 | moves to 1.1.0 |

## Correction after the first p 8000 roduction run

mikan 1.4.0-beta.0 on the production deployment replaced its first two offices for `network` and `binds` drift, not `image`, and all 33 containers on the previous `:latest` carry a network label from an older format. Removal ran only for `image` drift, so those images would never have been released. Removal now follows any replacement whose old image differs from the configured one. The same review found that Docker deletes an image by ID when one name still points to it, so an image is removed by ID only when it has no name.
2 changes: 1 addition & 1 deletion src/sandbox/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ This directory defines sandbox configuration, the execution environments tools r

- `identity.ts` derives credential authorization keys and runtime resource keys separately, so neither can collide with the other.
- A backend without managed projection cannot enforce a private office's visibility; `warnUnenforcedPrivateOffice` in `registry.ts` logs that once per office and lets the run continue, because those backends are operator-selected trusted deployments.
- Managed image containers (`provisioner.ts`) are disposable (ADR 0014): only the bind mounts from the office projection and vault outlive them. A container with mount or network drift, or a stopped one whose image differs from the local tag's image ID, is replaced with `rm -f` and `run`. A running container is never replaced for an image change. `prepareImage` pulls the configured image once per process, at daemon start; `--sandbox=oci` means the image published for this mikan version (ADR 0023). After an image replacement the provisioner runs `rmi` without force on what the old container used, and relies on the engine refusing while any container still uses it; nerdctl cannot remove by image ID, which costs nothing because a tag that moves on containerd leaves no unnamed image behind.
- Managed image containers (`provisioner.ts`) are disposable (ADR 0014): only the bind mounts from the office projection and vault outlive them. A container with mount or network drift, or a stopped one whose image differs from the local tag's image ID, is replaced with `rm -f` and `run`. A running container is never replaced for an image change. `prepareImage` pulls the configured image once per process, at daemon start; `--sandbox=oci` means the image published for this mikan version (ADR 0023). Whenever it replaces a container whose image differs from the configured one, whatever the drift reason, the provisioner runs `rmi` without force on the old container's published reference, or on its image ID only when that image has no name left, because Docker deletes an image by ID even while one name still points to it. Engines refuse `rmi` while any container uses the image. nerdctl cannot remove by image ID, which costs nothing because a tag that moves on containerd leaves no unnamed image behind.
- `provision`, `stop`, and `remove` are serialized per key.
- A backend is accepted by its contract, not its technology: per-office environment isolation, adjustable resource limits, a persistent workspace and vault, and a workspace mounted from the host on the same machine, on Linux and macOS ([ADR 0022](../../docs/adr/0022-sandbox-contract-not-a-container-engine.md)). Today it is the docker command set, run by the first of `nerdctl`, `podman`, and `docker` whose `info` succeeds, detected once per process unless `CONTAINER_ENGINE` pins one (`engine.ts`). Containers belong to the engine that created them, so a host whose detected engine changes gets new containers and leaves the old ones behind. The provisioner uses only queries the three answer alike: `ps`/`network ls` name filters for existence, `.Mounts` for binds, mikan's `mikan.network` and `mikan.image-id` labels for network and image drift, and `--cpu-period`/`--cpu-quota` for CPU limits, because nerdctl ignores `update --cpus`, Podman reports binds with mount options and its network mode as `bridge`, and nerdctl reports `.Image` as a name. `src/test/container-provisioner-engine.test.ts` runs the provisioner against whichever engine is configured.
- A sandbox reaches tools only as Pi's `ExecutionEnv` (`@earendil-works/pi-durable/env`): `host` is Pi's `NodeExecutionEnv` and `container` is pi-env's `RemoteExecutionEnv` (`@earendil-works/pi-env`) talking to Pi's `pi-env` daemon inside the container. `oci` has no environment of its own; the harness resolver provisions its container and then builds a `container` environment for it. A new backend implements `ExecutionEnv` and passes `registerEnvConformance`, as `src/test/container-execution-env.test.ts` does, instead of adding a mikan-specific interface.
Expand Down
23 changes: 17 additions & 6 deletions src/sandbox/provisioner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,11 +114,10 @@ export class DockerContainerManager {
: await this.runtimeDrift(containerKey, containerName, mounts, status);
if (drift) {
log.logInfo(`Container ${containerName} is out of date (${drift}); replacing container`);
const previousImage =
drift === "image" ? await this.containerImage(containerName) : undefined;
const leftBehind = await this.imageLeftBehind(containerName);
await this.replaceContainer(containerKey, containerName, mounts, options);
log.logInfo(`Container ${containerName} replaced from image ${this.image}`);
if (previousImage) await this.removeImageIfUnused(previousImage);
if (leftBehind) await this.removeImageIfUnused(leftBehind);
} else if (status === "stopped") {
await this.run(["start", containerName]);
log.logInfo(`Container ${containerName} started`);
Expand Down Expand Up @@ -503,16 +502,28 @@ export class DockerContainerManager {
}
}

private async containerImage(containerName: string): Promise<string | undefined> {
private async imageLeftBehind(containerName: string): Promise<string | undefined> {
const { stdout } = await this.run([
"inspect",
"-f",
`{{.Config.Image}}\t{{index .Config.Labels "${DockerContainerManager.IMAGE_ID_LABEL_KEY}"}}`,
containerName,
]);
const [reference = "", imageId] = stdout.trim().split("\t");
const [reference = "", label] = stdout.trim().split("\t");
const imageId = this.normalizeDockerValue(label);
if (imageId && imageId === (await this.localImageId())) return undefined;
if (reference !== this.image && isPublishedSandboxImage(reference)) return reference;
return this.normalizeDockerValue(imageId);
if (imageId && (await this.isUnnamedImage(imageId))) return imageId;
return undefined;
}

private async isUnnamedImage(imageId: string): Promise<boolean> {
try {
const { stdout } = await this.run(["image", "inspect", "-f", "{{len .RepoTags}}", imageId]);
return stdout.trim() === "0";
} catch {
return false;
}
}

private async removeImageIfUnused(image: string): Promise<void> {
Expand Down
27 changes: 24 additions & 3 deletions src/test/provisioner.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ class FakeEngine {
readonly calls: string[][] = [];
readonly failures = new Map<string, Error>();
readonly holds = new Map<string, Promise<unknown>>();
readonly removedImageIds: string[] = [];
readonly exec = vi.fn<DockerExecFile>(async (_file, args) => this.handle(args));

seed(name: string, key: string, overrides: Partial<FakeContainer> = {}): FakeContainer {
Expand Down Expand Up @@ -101,6 +102,9 @@ class FakeEngine {
case "inspect":
return { stdout: `${this.inspect(args[2] ?? "", name)}\n` };
case "image": {
if (args.includes("{{len .RepoTags}}")) {
return { stdout: `${[...this.images.values()].filter((id) => id === name).length}\n` };
}
const id = this.images.get(name);
if (!id) throw new Error(`Error: no such image: ${name}`);
return { stdout: `${id}\n` };
Expand All @@ -113,6 +117,7 @@ class FakeEngine {
throw new Error(`conflict: unable to delete ${name} (must be forced)`);
}
this.images.delete(name);
this.removedImageIds.push(name);
return { stdout: `Untagged: ${name}\n` };
case "network":
return { stdout: this.network(args) };
Expand Down Expand Up @@ -607,7 +612,7 @@ describe("DockerContainerManager", () => {
expect(engine.callsOf("rmi")).toEqual([["rmi", "sha256:old"]]);
});

test("an operator's own image is removed only by ID, which engines refuse while it keeps a name", async () => {
test("an operator's own image that still has a name is never removed", async () => {
const engine = new FakeEngine();
engine.images.set("acme/sandbox:dev", "sha256:old");
engine.seed("mikan-sandbox-alice", "alice", {
Expand All @@ -618,10 +623,26 @@ describe("DockerContainerManager", () => {

await manager(engine).provision("alice");

expect(engine.callsOf("rmi")).toEqual([["rmi", "sha256:old"]]);
expect(engine.callsOf("rmi")).toEqual([]);
expect(engine.images.get("acme/sandbox:dev")).toBe("sha256:old");
});

test("an office replaced for its network still releases its older image", async () => {
const engine = new FakeEngine();
engine.images.set(OLD, "sha256:old");
engine.seed("mikan-sandbox-alice", "alice", {
running: false,
image: OLD,
labels: { "mikan.image-id": "sha256:old", "mikan.network": "legacy-network" },
});

await manager(engine).provision("alice");

expect(engine.callsOf("rmi")).toEqual([["rmi", OLD]]);
expect(engine.images.has(OLD)).toBe(false);
});

test("replacing a container for anything but its image removes no image", async () => {
test("replacing a container that is already on the configured image removes no image", async () => {
const engine = new FakeEngine();
engine.seed("mikan-sandbox-alice", "alice", { running: false, image: IMAGE });

Expand Down
Loading
0