Skip to content

[Bug]: ImageStore.pull hangs forever when a registry stops sending a blob mid-body #1028

Open

Description

@AustinKelsay

I have done the following

  • I have searched the existing issues
  • If possible, I've reproduced the issue using the 'main' branch of this project

Steps to reproduce

RegistryClient leaves HTTPClient.Configuration.timeout.read unset. When a registry accepts a blob request, sends the response head and part of the body, then sends nothing more without closing the connection, ImageStore.pull neither returns nor throws. We first hit this in normal use: a cold pull sat on one partly downloaded layer for more than 25 minutes.

Reproduction (needs Python 3 and access to Docker Hub; the four files are below):

  1. Put Package.swift, Sources/repro/main.swift, repro-1-no-read-timeout.sh and stall-proxy.py in a directory repro/.
  2. In repro/, run swift build -c release, then bash repro-1-no-read-timeout.sh.

The script pulls docker.io/library/node:22-bookworm-slim into a fresh store twice:

  • directly, as a control;
  • through stall-proxy.py, a local HTTPS CONNECT proxy. It freezes the first tunnel to Docker Hub's blob CDN after 256 KiB of server data and holds the tunnel open. RegistryClient honors HTTPS_PROXY, so no code change is needed.

The script stops the second pull after 180 s. A stalled ... after 262144 bytes line in the proxy log confirms the test condition; without it the script prints inconclusive.

Package.swift
// swift-tools-version: 6.2
import Foundation
import PackageDescription

// CONTAINERIZATION_PATH=<checkout> builds against a local (patched) copy instead.
let containerization: Package.Dependency = ProcessInfo.processInfo.environment["CONTAINERIZATION_PATH"]
    .map { .package(path: $0) } ?? .package(url: "https://github.com/apple/containerization.git", exact: "0.57.0")

let package = Package(
    name: "repro",
    platforms: [.macOS("26.0")],
    dependencies: [
        containerization,
    ],
    targets: [
        .executableTarget(
            name: "repro",
            dependencies: [.product(name: "Containerization", package: "containerization")]
        ),
    ]
)
Sources/repro/main.swift
// Minimal reproductions for two ImageStore issues in Containerization 0.57.0.
//
//   repro pull <store> <reference>          pull one image (prints elapsed time every 15s)
//   repro create <store> <prefix> <count>   add <count> image records named <prefix>-N
//   repro instances <store> <count>         two ImageStore instances in this process each add <count> records
//   repro tag <store> <existing> <prefix> <count>  tag <existing> as <prefix>-N, <count> times
//   repro count <store> <prefix>            how many records named <prefix>-N exist
//   repro has <store> <reference>           whether a record exists
//   repro cleanup <store>                   ImageStore.cleanUpOrphanedBlobs()

import Containerization
import ContainerizationOCI
import Foundation

setvbuf(stdout, nil, _IOLBF, 0)
let args = CommandLine.arguments.dropFirst().map { $0 }
guard args.count >= 2 else {
    print("usage: repro pull|create|count|has|cleanup <store> ...")
    exit(2)
}
let store = try ImageStore(path: URL(fileURLWithPath: args[1]))
let start = ContinuousClock.now

// Records only: the digest needs no content for this, and nothing reads it.
let descriptor = Descriptor(
    mediaType: MediaTypes.index,
    digest: "sha256:" + String(repeating: "0", count: 64),
    size: 0
)

do {
switch args[0] {
case "pull":
    let ticker = Task {
        while !Task.isCancelled {
            try await Task.sleep(for: .seconds(15))
            print("still pulling after \(ContinuousClock.now - start)")
        }
    }
    let image = try await store.pull(reference: args[2], platform: .current)
    ticker.cancel()
    print("pulled \(image.reference) in \(ContinuousClock.now - start)")

case "create":
    for i in 0..<Int(args[3])! {
        try await store.create(description: .init(reference: "example.com/\(args[2])-\(i):latest", descriptor: descriptor))
    }

case "instances":
    let count = Int(args[2])!
    let stores = [store, try ImageStore(path: URL(fileURLWithPath: args[1]))]
    try await withThrowingTaskGroup(of: Void.self) { group in
        for (n, s) in stores.enumerated() {
            group.addTask {
                for i in 0..<count {
                    try await s.create(description: .init(reference: "example.com/instance\(n)-\(i):latest", descriptor: descriptor))
                }
            }
        }
        try await group.waitForAll()
    }
    let names = try await store.list().map(\.reference)
    for n in stores.indices {
        print("records from instance \(n): \(names.filter { $0.hasPrefix("example.com/instance\(n)-") }.count) of \(count)")
    }

case "tag":
    for i in 0..<Int(args[4])! {
        _ = try await store.tag(existing: args[2], new: "example.com/\(args[3])-\(i):latest")
    }

case "count":
    let names = try await store.list().map(\.reference)
    print(names.filter { $0.hasPrefix("example.com/\(args[2])-") }.count)

case "has":
    let found = try await store.getOrNil(reference: args[2]) != nil
    print(found ? "present" : "missing")

case "cleanup":
    let (deleted, freed) = try await store.cleanUpOrphanedBlobs()
    print("deleted \(deleted.count) blobs, \(freed) bytes")

default:
    print("unknown command \(args[0])")
    exit(2)
}
} catch {
    print("error after \(ContinuousClock.now - start): \(error)")
    exit(1)
}
repro-1-no-read-timeout.sh
#!/bin/bash
# Issue 1: ImageStore.pull waits forever when a registry stops sending data mid-body.
#
# stall-proxy.py is an HTTPS CONNECT proxy (RegistryClient honors HTTPS_PROXY).
# It freezes the first tunnel to Docker Hub's blob CDN after 256 KiB and keeps
# it open; every other tunnel passes through.
#
# usage: ./repro-1-no-read-timeout.sh [limit seconds, default 180]
# needs: python3, access to Docker Hub
set -uo pipefail
cd "$(dirname "$0")"
LIMIT=${1:-180}
REPRO=${REPRO:-.build/release/repro}
IMAGE=docker.io/library/node:22-bookworm-slim
WORK=$(mktemp -d)
PORT=$((20000 + RANDOM % 20000))
NOPROXY=(env -u HTTPS_PROXY -u https_proxy -u HTTP_PROXY -u http_proxy -u ALL_PROXY -u all_proxy -u NO_PROXY -u no_proxy)

echo "== 1. Control: the same pull, no proxy"
"${NOPROXY[@]}" "$REPRO" pull "$WORK/control" "$IMAGE" | tail -1 || { echo "control pull failed"; exit 1; }

echo "== 2. Through a proxy that freezes one blob download (limit ${LIMIT}s)"
python3 -I stall-proxy.py "$PORT" > "$WORK/proxy.log" 2>&1 &
PROXY=$!
sleep 1
"${NOPROXY[@]}" HTTPS_PROXY="http://127.0.0.1:$PORT" "$REPRO" pull "$WORK/stalled" "$IMAGE" &
PULL=$!
for ((i = 0; i < LIMIT; i++)); do kill -0 $PULL 2>/dev/null || break; sleep 1; done
if kill -0 $PULL 2>/dev/null; then
  RESULT="pull still running after ${LIMIT}s with no error"
  kill $PULL; wait $PULL 2>/dev/null
else
  wait $PULL; RESULT="pull exited with status $?"
fi
kill $PROXY; wait $PROXY 2>/dev/null
echo "== proxy log"; cat "$WORK/proxy.log"
if grep -q " stalled " "$WORK/proxy.log"; then
  echo "RESULT: $RESULT"
else
  echo "RESULT: inconclusive, the proxy never stalled a tunnel"
fi
rm -rf "$WORK"
stall-proxy.py
#!/usr/bin/env python3
"""HTTPS CONNECT proxy that freezes the first tunnel to Docker Hub's blob CDN (production.*.docker.com).

The frozen tunnel forwards STALL_AFTER bytes from the server, then stops
reading from either side while keeping both sockets open: a registry that
accepted the request and went silent mid-blob. Every other tunnel, including
later ones to the same CDN, passes through untouched.

usage: stall-proxy.py <port> [stall_after_bytes] [always]
Logs one line per tunnel to stdout.
"""
import socket, sys, threading, time

PORT = int(sys.argv[1])
STALL_AFTER = int(sys.argv[2]) if len(sys.argv) > 2 else 256 * 1024
ALWAYS = len(sys.argv) > 3 and sys.argv[3] == "always"  # stall every CDN tunnel
CDN = ".docker.com"  # production.cloudflare. or production.cloudfront.
lock = threading.Lock()
stalled = False
held = []  # keep frozen sockets referenced so they stay open


def log(msg):
    print(f"{time.strftime('%H:%M:%S')} {msg}", flush=True)


def pipe(src, dst, limit=None, on_limit=None):
    sent = 0
    try:
        while True:
            data = src.recv(65536)
            if not data:
                break
            if limit is not None and sent + len(data) >= limit:
                dst.sendall(data[: limit - sent])
                on_limit()
                return  # stop reading: the tunnel stays open and silent
            dst.sendall(data)
            sent += len(data)
    except OSError:
        pass
    try:
        dst.shutdown(socket.SHUT_WR)
    except OSError:
        pass


def handle(client):
    global stalled
    req = b""
    while b"\r\n\r\n" not in req:
        chunk = client.recv(4096)
        if not chunk:
            client.close()
            return
        req += chunk
    line = req.split(b"\r\n", 1)[0].decode()
    method, target, _ = line.split(" ", 2)
    if method != "CONNECT":
        client.sendall(b"HTTP/1.1 405 Method Not Allowed\r\n\r\n")
        client.close()
        return
    host, port = target.rsplit(":", 1)
    upstream = socket.create_connection((host, int(port)), timeout=30)
    upstream.settimeout(None)
    client.sendall(b"HTTP/1.1 200 Connection Established\r\n\r\n")

    freeze = False
    with lock:
        if host.startswith("production.") and host.endswith(CDN) and (ALWAYS or not stalled):
            stalled = freeze = True
    log(f"tunnel {target}{' (will stall)' if freeze else ''}")
    if freeze:
        def frozen():
            held.extend([client, upstream])
            log(f"stalled {target} after {STALL_AFTER} bytes")
        threading.Thread(target=pipe, args=(upstream, client, STALL_AFTER, frozen), daemon=True).start()
        # client -> upstream keeps flowing so the request is sent
        threading.Thread(target=pipe, args=(client, upstream), daemon=True).start()
    else:
        threading.Thread(target=pipe, args=(client, upstream), daemon=True).start()
        threading.Thread(target=pipe, args=(upstream, client), daemon=True).start()


srv = socket.socket()
srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
srv.bind(("127.0.0.1", PORT))
srv.listen(64)
log(f"listening on 127.0.0.1:{PORT}, stalling the first {CDN} tunnel after {STALL_AFTER} bytes")
while True:
    c, _ = srv.accept()
    threading.Thread(target=handle, args=(c,), daemon=True).start()

Reproducibility: 2 of 2 runs.

Current behavior

With the CDN tunnel stalled, the pull is still pending at 180 s with no error, and the script kills it. The control pull of the same image completes.

Cause, at 0.57.0 (0ac42ce2):

  • RegistryClient.init builds HTTPClient.Configuration() and keeps the default timeout. With read nil, AsyncHTTPClient waits on an idle connection indefinitely.
  • request(...) passes deadline: .distantFuture. AsyncHTTPClient applies that deadline only until the response head arrives, so a finite deadline would leave this pull hung too. The idle read timeout is the setting that covers a stalled body.
  • The body is read in request's closure (L294), after the retry loop. A stall there reaches the caller without a retry.

Expected behavior

The pull fails with an error once no data has arrived for a bounded time, so callers can retry or report it.

Suggested fix (tested). Set an idle read timeout on the client:

@@ -118,6 +118,8 @@ public final class RegistryClient: ContentClient {
         self.retryOptions = retryOptions
         self.bufferSize = bufferSize
         var httpConfiguration = HTTPClient.Configuration()
+        // Fail a request that receives no data for 60 s instead of waiting forever.
+        httpConfiguration.timeout.read = .seconds(60)
 
         // proxy configuration assumes all client requests will go to `base` URL
         self.proxyURL = ProxyUtils.proxyFromEnvironment(scheme: scheme, host: host)

With this patch on 0.57.0, the same script's stalled pull exits with HTTPClientError.readTimeout about 60 s after the proxy stalls the tunnel. The control pull still completes.

For review:

  • tokenConfiguration copies httpConfiguration (L141), so token requests get the same timeout. AsyncHTTPClient starts the read timer after the request is fully sent, so a long blob upload is unaffected. A registry must send its response within 60 s after an upload completes.
  • Open questions: whether 60 s is the right default, and whether RegistryClient.init should take it as a parameter. A parameter would also let a test use a short timeout against MockRegistryServer.

Environment

- OS: macOS 26.5.2 (25F84), arm64
- Xcode: 26.6 (17F113)
- Swift: Apple Swift version 6.3.3 (swiftlang-6.3.3.1.3 clang-2100.1.1.101)
- Containerization: 0.57.0 (0ac42ce2), package used directly; host-side ImageStore and RegistryClient only, no VM or guest kernel involved

Relevant log output

# 0.57.0
== 1. Control: the same pull, no proxy
pulled docker.io/library/node:22-bookworm-slim in 16.20184675 seconds
== 2. Through a proxy that freezes one blob download (limit 180s)
still pulling after 15.678728042 seconds
still pulling after 31.460331583 seconds
still pulling after 47.130243417 seconds
still pulling after 62.867376125 seconds
still pulling after 78.455127583 seconds
still pulling after 93.9178565 seconds
still pulling after 109.51582566699999 seconds
still pulling after 125.35303179200001 seconds
still pulling after 141.30782233300002 seconds
still pulling after 157.18735016699998 seconds
still pulling after 172.957281292 seconds
== proxy log
14:46:52 listening on 127.0.0.1:29690, stalling the first .docker.com tunnel after 262144 bytes
14:46:53 tunnel registry-1.docker.io:443
14:46:53 tunnel auth.docker.io:443
14:46:54 tunnel production.cloudfront.docker.com:443 (will stall)
14:46:54 stalled production.cloudfront.docker.com:443 after 262144 bytes
RESULT: pull still running after 180s with no error

# 0.57.0 with the patch above
== 1. Control: the same pull, no proxy
pulled docker.io/library/node:22-bookworm-slim in 30.3216045 seconds
== 2. Through a proxy that freezes one blob download (limit 180s)
still pulling after 15.533236292 seconds
still pulling after 31.0715805 seconds
still pulling after 46.771509834 seconds
still pulling after 62.605334084 seconds
error after 62.609516541999994 seconds: HTTPClientError.readTimeout
== proxy log
15:04:04 listening on 127.0.0.1:25372, stalling the first .docker.com tunnel after 262144 bytes
15:04:05 tunnel registry-1.docker.io:443
15:04:06 tunnel auth.docker.io:443
15:04:07 tunnel production.cloudfront.docker.com:443 (will stall)
15:04:08 stalled production.cloudfront.docker.com:443 after 262144 bytes
RESULT: pull exited with status 1

Code of Conduct

  • I agree to follow this project's Code of Conduct

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions