mocker icon indicating copy to clipboard operation
mocker copied to clipboard

`ps --filter ancestor=` compares the text the container was started with, not the image

Open PixCZ opened this issue 1 month ago • 1 comments

mocker version: 0.9.8 (Homebrew) — macOS 27, container 1.6.0, arm64. Code references are against main @ 1a13c1f.

Summary

Docker resolves ancestor= to an image (name, name:tag or ID) and matches containers by that image's digest. mocker compares the value against the string the container was started with, exactly or as a prefix: a container started as alpine:3.20 is found by ancestor=alpine:3.20 and by ancestor=alp, but not by its ID and not by docker.io/library/alpine:3.20.

Found while fixing run <image id>; filed alongside that report so the three can go in together. With that fix a container started by ID records the resolved name, so the mismatch would only move around until the comparison is on the image itself.

Reproduction

$ mocker run -d --name probe alpine:3.20 sleep 60
$ mocker ps -q -f ancestor=d9e853e87e55 | wc -l
0                      # Docker: 1
$ mocker ps -q -f ancestor=docker.io/library/alpine:3.20 | wc -l
0                      # Docker: 1
$ mocker ps -q -f ancestor=alp | wc -l
1                      # Docker: 0

ContainerListOptions.filtered: $0.image == value || $0.image.hasPrefix(value).

Proposed behaviour (what the branch does)

  • ImageManager.isAncestor(_:of:in:) looks both the filter value and the container's image up in the local images and compares digests. An ID (full, truncated or bare hex), alpine:3.20 and docker.io/library/alpine:3.20 all find the container however it was started; a bare alpine means alpine:latest, as Docker's lookup does (stricter than before, where it matched alpine:3.20 by prefix); an ID prefix two images share names neither.
  • The image listing is fetched only when an ancestor= filter is present.
  • Not followed: descendants (images built FROM the ancestor), which Docker includes. The store keeps no parent chain to walk.

After, with the branch (on top of 0.9.8), container 1.6.0, same container:

$ for a in d9e853e87e55 sha256:d9e853e87e55 alpine:3.20 docker.io/library/alpine:3.20 alpine alp; do
    printf '%-32s %s\n' "$a" "$(mocker ps -q -f ancestor=$a | wc -l)"; done
d9e853e87e55                     1
sha256:d9e853e87e55              1
alpine:3.20                      1
docker.io/library/alpine:3.20    1
alpine                           0
alp                              0

A tested fix is on my fork, branch fix/ps-ancestor (compare); the diff is below. Happy to open it as a PR if you'd like, or you can take it from here — whichever is easier for you.

Proposed fix: git diff main...fix/ps-ancestor
diff --git a/COMMANDS.md b/COMMANDS.md
index b87bf61..e8d34cd 100644
--- a/COMMANDS.md
+++ b/COMMANDS.md
@@ -308,6 +308,10 @@ mocker ps [OPTIONS]
 | `--latest` | `-l` | Show the latest created container |
 | `--size` | `-s` | Display total file sizes |
 
+Filters: `name`, `status`, `id`, `label` and `ancestor`. `ancestor=` takes a name, `name:tag`
+or image ID and matches the image itself, however the container was started (`alpine:3.20`,
+`docker.io/library/alpine:3.20` or the ID all find it); a bare name means `:latest`, as in Docker.
+
 ### `mocker exec`
 
 Execute a command in a running container.
diff --git a/Sources/Mocker/Commands/ContainerListOptions.swift b/Sources/Mocker/Commands/ContainerListOptions.swift
index 82c792a..08832f3 100644
--- a/Sources/Mocker/Commands/ContainerListOptions.swift
+++ b/Sources/Mocker/Commands/ContainerListOptions.swift
@@ -33,7 +33,11 @@ struct ContainerListOptions: ParsableArguments {
         let engine = try ContainerEngine(config: config)
         // --latest / --last include all states regardless of --all (matches Docker).
         let includeAll = all || latest || last != nil
-        var containers = try filtered(try await engine.list(all: includeAll))
+        // `ancestor=` compares images, not the text they were started with, so only that
+        // filter pays for a listing.
+        let images = filter.contains { $0.hasPrefix("ancestor=") }
+            ? try await ImageManager(config: config).list(enrich: false) : []
+        var containers = try filtered(try await engine.list(all: includeAll), images: images)
 
         if latest {
             containers = Array(containers.prefix(1))
@@ -81,7 +85,8 @@ struct ContainerListOptions: ParsableArguments {
     }
 
     /// Apply Docker-style `--filter` predicates. Pure; safe to unit-test.
-    func filtered(_ containers: [ContainerInfo]) throws -> [ContainerInfo] {
+    /// - Parameter images: the local images, which `ancestor=` resolves both sides against.
+    func filtered(_ containers: [ContainerInfo], images: [ImageInfo] = []) throws -> [ContainerInfo] {
         var containers = containers
         for f in try ListFilter.parse(filter, supported: ["name", "status", "id", "label", "ancestor"]) {
             let value = f.value
@@ -100,7 +105,7 @@ struct ContainerListOptions: ParsableArguments {
                     containers = containers.filter { $0.labels[value] != nil }
                 }
             case "ancestor":
-                containers = containers.filter { $0.image == value || $0.image.hasPrefix(value) }
+                containers = containers.filter { ImageManager.isAncestor(value, of: $0.image, in: images) }
             default:
                 break  // unreachable: `parse` rejected every other key
             }
diff --git a/Sources/MockerKit/Image/ImageManager.swift b/Sources/MockerKit/Image/ImageManager.swift
index 049d17f..06ab1e9 100644
--- a/Sources/MockerKit/Image/ImageManager.swift
+++ b/Sources/MockerKit/Image/ImageManager.swift
@@ -160,6 +160,17 @@ public actor ImageManager {
             && (image.repository == ref.fullRepository || image.repository.hasSuffix("/\(ref.repository)"))
     }
 
+    /// Whether a container started from `containerImage` runs the image `reference` names —
+    /// `ps --filter ancestor=`. Both sides are looked up in `images` and compared by digest,
+    /// so an ID, `alpine:3.20` and `docker.io/library/alpine:3.20` all mean the same image
+    /// and a bare `alpine` means `alpine:latest`, as in Docker. An ID prefix shared by two
+    /// images names neither. Pure, so the matching can be tested without a store.
+    public static func isAncestor(_ reference: String, of containerImage: String, in images: [ImageInfo]) -> Bool {
+        let wanted = Set(images.filter { matches($0, reference: reference) }.map(\.id))
+        guard wanted.count == 1 else { return false }
+        return images.contains { wanted.contains($0.id) && matches($0, reference: containerImage) }
+    }
+
     /// Remove dangling images, or with `all` every image not in `inUse`, then let the
     /// runtime drop the blobs nothing references any more.
     /// - Returns: the images removed and the bytes their digests freed (a digest another
diff --git a/Tests/MockerTests/ListFilterTests.swift b/Tests/MockerTests/ListFilterTests.swift
index 2d5958d..667c702 100644
--- a/Tests/MockerTests/ListFilterTests.swift
+++ b/Tests/MockerTests/ListFilterTests.swift
@@ -41,4 +41,40 @@ struct ListFilterTests {
         #expect(try imageIDs("reference=docker.io/library/alpine:latest") == ["b"])
         #expect(try imageIDs("reference=mybuild") == ["c"])
     }
+
+    // `ps --filter ancestor=` — compared by digest, so however the container names its image.
+    private let local = [
+        ImageInfo(id: "sha256:d9e853e87e55", repository: "docker.io/library/alpine", tag: "3.20"),
+        ImageInfo(id: "sha256:06d7adf3e0ef", repository: "docker.io/library/alpine", tag: "latest"),
+        ImageInfo(id: "sha256:d9e8ff000000", repository: "ghcr.io/acme/app", tag: "1.0"),
+    ]
+
+    private let containers = [
+        ContainerInfo(id: "c1", name: "short", image: "alpine:3.20", state: .running, status: "Up", created: .now),
+        ContainerInfo(id: "c2", name: "qualified", image: "docker.io/library/alpine:3.20", state: .running, status: "Up", created: .now),
+        ContainerInfo(id: "c3", name: "latest", image: "alpine", state: .running, status: "Up", created: .now),
+        ContainerInfo(id: "c4", name: "app", image: "ghcr.io/acme/app:1.0", state: .running, status: "Up", created: .now),
+    ]
+
+    private func containerIDs(_ filter: String) throws -> [String] {
+        try ContainerLs.parse(["--filter", filter]).options.filtered(containers, images: local).map(\.id)
+    }
+
+    @Test("ps: ancestor finds the image by ID, short name or qualified name alike")
+    func ancestorMatchesByImage() throws {
+        // `images -q` prints the ID; a container is recorded under whatever name started it.
+        #expect(try containerIDs("ancestor=d9e853e87e55") == ["c1", "c2"])
+        #expect(try containerIDs("ancestor=sha256:d9e853e87e55") == ["c1", "c2"])
+        #expect(try containerIDs("ancestor=alpine:3.20") == ["c1", "c2"])
+        #expect(try containerIDs("ancestor=docker.io/library/alpine:3.20") == ["c1", "c2"])
+    }
+
+    @Test("ps: a bare ancestor name means :latest, and a prefix is not a name")
+    func ancestorIsNotAPrefixMatch() throws {
+        #expect(try containerIDs("ancestor=alpine") == ["c3"])
+        #expect(try containerIDs("ancestor=alp").isEmpty)
+        #expect(try containerIDs("ancestor=nginx").isEmpty)
+        // An ID prefix two images share names neither.
+        #expect(try containerIDs("ancestor=d9e8").isEmpty)
+    }
 }

PixCZ avatar Oct 25 '26 19:10 PixCZ

Shipped in 0.9.9 (ref #114), checked with the Homebrew build on container 1.5.0.

us avatar Oct 25 '26 22:10 us