Skip to content

fix(help): indefinite hang on container --help / help / no-args - #1455

Closed
chrisgeo wants to merge 5 commits into
apple:mainfrom
full-chaos:main
Closed

chrisgeo wants to merge 5 commits into
apple:mainfrom
full-chaos:main

Conversation

@chrisgeo

@chrisgeo chrisgeo commented Apr 27, 2026 •

Copy link
Copy Markdown
Contributor

Type of Change

  • Bug fix
  • New feature
  • Breaking change
  • Documentation update

Motivation and Context

Closes #1459.

container --help, container help, and container (no args) should not require com.apple.container.apiserver to be reachable. Today, those paths can enter plugin loading before printing help, which calls ClientHealthCheck.ping() and waits on the apiserver.

A healthy build is expected to return quickly; this is not a bug in normal help rendering. The failure mode is conditional on launchd/XPC state where com.apple.container.apiserver is registered but unavailable, dead, wedged, or otherwise not replying. That state is the class of issue tracked in #1459 and is similar to stale-apiserver recovery reports in #1329, #798, and #621.

This PR is a defensive robustness fix: help/default-command rendering should remain local, and idempotent XPC requests with explicit timeouts should actually return when the reply callback never fires.

Summary

This PR fixes two independent defects:

  1. Help/default commands should not ping the API server — Application.swift, HelpCommand.swift, and DefaultCommand.swift now print base help without constructing a PluginLoader first.
  2. Idempotent XPC timeouts should actually unblock — XPCClient.send(_:timeoutForIdempotentRequest:) replaces the old TaskGroup race with a single-resume gate so a non-firing XPC reply cannot trap structured-concurrency cleanup forever.
  3. Mutating XPC sends should not silently drop late replies — the XPC API now separates mutating/unknown-safety sends from idempotent sends, preventing accidental timeout use on mutating operations.
  4. The investigation is documented — docs/internal/help-freeze-analysis.md captures the call chain, tradeoffs, and remaining follow-ups.

Why the help-path fix is separate from the XPC fix

There are two independent defects:

  • Defect A (symptom). Help/default rendering called createPluginLoader() → ClientHealthCheck.ping() to fetch appRoot/installRoot/logRoot purely so printModifiedHelpText could enrich help with plugin commands. The ping is structurally unnecessary for base help output.

  • Defect B (depth). The old XPCClient.send(... responseTimeout:) raced Task.sleep against the XPC reply inside a withThrowingTaskGroup, but throwing from group.next() caused structured-concurrency cleanup to await the still-suspended XPC child task. Cancelling the Swift task does not cancel xpc_connection_send_message_with_reply, so a non-firing callback could still block indefinitely.

Defect A removes the apiserver dependency from help/default paths. Defect B makes explicit idempotent XPC timeouts behave as timeouts when the XPC reply never arrives.

Reproduction scope

No deterministic setup is currently known for creating the stale/wedged launchd state. On a healthy checkout, the following should return quickly, and reviewer testing confirmed that behavior after make all:

make all

time .build/debug/container --help
time .build/debug/container help
time .build/debug/container

The bug tracked by #1459 applies when the apiserver is registered but not replying. In that state, pre-fix help/default paths can block before printing help because they ping the apiserver while preparing plugin-enriched help.

launchctl bootout ... is a recovery/cleanup action observed in related stale-apiserver cases, not a reliable reproduction step.

Build/test guidance

For normal source builds and verification, follow BUILDING.md:

make all test integration

For installed release-style testing:

BUILD_CONFIGURATION=release make all test integration
BUILD_CONFIGURATION=release make install

The .build/debug/container timings above are diagnostic context matching the reviewer command, not the canonical setup for reproducing or validating installed helper/plugin layout.

Known regression in this PR

Plugin enrichment in --help / help / no-args output is removed. The output is the original OVERVIEW: ... USAGE: ... CONTAINER SUBCOMMANDS: ... block, without a trailing PLUGINS: section.

This keeps the freeze fix minimal and avoids entangling it with API design questions on PluginLoader. A follow-up can restore plugin enrichment by extracting filesystem-only plugin discovery from PluginLoader.findPlugins(); the proposed shape is sketched in docs/internal/help-freeze-analysis.md.

Verification

  • swift build --product container — clean

  • make test — 366/366 unit tests pass

  • make swift-fmt-check — clean

  • Added Tests/ContainerXPCTests/XPCClientTests.swift coverage for:

    • idempotent timeout returning within the bound
    • reusable clients surviving idempotent timeout
    • late replies after timeout being ignored cleanly
    • plain mutating-safe sends completing when the server replies
    • plain sends ignoring cancellation after dispatch
    • plain sends honoring cancellation before dispatch
  • Manual diagnostic smoke test on macOS 26 with com.apple.container.apiserver registered with launchd but inactive (active count = 0, state = spawn scheduled):

    $ time .build/debug/container --help
    ... full help output ...
    real  0m0.11s
    
    $ time .build/debug/container help
    ... full help output ...
    real  0m0.11s
    
    $ time .build/debug/container
    ... full help output ...
    real  0m0.11s

    All exit 0 immediately. Before this PR these paths could block while trying to reach the apiserver before printing help.

What this PR explicitly does not fix

  1. A deterministic way to create the stale/wedged apiserver launchd state tracked by [Bug]: help/default commands can hang when apiserver launchd state is wedged #1459.
  2. All apiserver startup/stop hangs reported in [Bug]: container system start hangs indefinitely at Verifying apiserver is running... #1329, [Bug]: Can't get container system commands to work #798, or [Bug]: "container system start" hangs when app root is placed on an external disk #621.
  3. ClientHealthCheck.ping's 60s default xpcRegistrationTimeout.
  4. Reusable ContainerClient / NetworkClient mutating calls with no timeout; this is intentional until mutating operations have an idempotency/recovery protocol.
  5. launchctl bootout-style recovery as a built-in CLI command.

Workaround for affected users

If the local apiserver launchd state is stale or wedged, related reports have recovered with bootout + restart:

launchctl bootout gui/$(id -u)/com.apple.container.apiserver 2>/dev/null
launchctl bootout user/$(id -u)/com.apple.container.apiserver 2>/dev/null
container system start

Full reasoning, the call-chain trace, the audit of affected XPC callers, and the design tradeoffs are in docs/internal/help-freeze-analysis.md. The doc is intentionally written for adversarial review — please push back on anything that doesn't hold up.

@chrisgeo
chrisgeo marked this pull request as draft April 27, 2026 13:26
Adds docs/internal/help-freeze-analysis.md describing the two defects that
combine to produce an indefinite hang on `container --help` when
`com.apple.container.apiserver` is dead, wedged, or stale-registered in
launchd:

  A. The help path requires the daemon to be reachable, because
     `Application.main` calls `createPluginLoader()` (which pings the
     API server) before printing help.

  B. `XPCClient.send`'s timeout cannot actually unblock the function:
     the structured TaskGroup must await the XPC child task, which is
     suspended in a `withCheckedThrowingContinuation` that only resumes
     when the C callback fires.

The document is intended to be reviewed alongside the two follow-up
commits that implement the fixes.
Help rendering must not depend on `com.apple.container.apiserver` being
reachable. When the API server is dead, wedged, or stale-registered in
launchd, the previous behavior was an indefinite hang on:

  container --help
  container help
  container

All three paths called `Application.createPluginLoader()` (which pings
the API server to fetch `appRoot`/`installRoot`/`logRoot`) just to
enrich the help text with plugin commands. The ping is structurally
unnecessary for help: `PluginLoader.alterCLIHelpText` only reads
`pluginDirectories` and `pluginFactories`.

This commit removes the call from each help path and extends
`printModifiedHelpText` with an optional `unavailableMessage:` so that
contexts which deliberately skipped plugin loading do not print the
misleading 'PLUGINS: not available, run `container system start`'
notice. `DefaultCommand` is reordered so the API server is contacted
only when there is a plugin command to dispatch.

Plugin enrichment in help output is removed by this commit. A follow-up
can restore it by extracting filesystem-only plugin discovery from
`PluginLoader.findPlugins` (see docs/internal/help-freeze-analysis.md
for the proposed shape).

Verified by running each path with no apiserver running on macOS 26:
all three return immediately with exit 0 and the original
`OVERVIEW: A container platform for macOS` block.
The previous implementation raced `Task.sleep` against the XPC reply
inside a `withThrowingTaskGroup`. When the timeout won, structured
concurrency required the group to await the XPC child task before the
group scope could return — but that child was suspended in a
`withCheckedThrowingContinuation` that only resumes when the C
`xpc_connection_send_message_with_reply` callback fires. Cancelling a
Swift Task does not cancel the underlying C call. If the remote service
was wedged (no reply, no connection invalidation), the child never
resumed and the group never returned, regardless of the supplied
`responseTimeout`. The `responseTimeout` parameter was therefore
silently ineffective in exactly the failure mode it was meant to
mitigate.

This commit replaces the TaskGroup with a single-resume gate
(`ResumptionState`) over a `CheckedContinuation` wrapped in a
`withTaskCancellationHandler`. The continuation is resumed by whichever
of the following completes first:

  1. The XPC reply callback fires.
  2. `responseTimeout` elapses.
  3. The current Task is cancelled.

Late completions from the other paths are dropped silently, so the
underlying XPC connection remains valid for subsequent sends. This is
required for callers that hold a long-lived `XPCClient`
(`ContainerClient`, `NetworkClient`); a simpler design that called
`xpc_connection_cancel` on timeout would brick those clients after a
single timed-out send.

Tradeoffs documented in docs/internal/help-freeze-analysis.md:
  - On timeout/cancel, the eventual late XPC reply is retained by XPC
    until the connection is released. For short-lived clients this is
    GC'd within milliseconds; for long-lived reusable clients the worst
    case is one orphaned `xpc_object_t` per timed-out send.
  - The unstructured `Task` that runs the timeout sleep is not
    cancelled when the parent task is cancelled; it wakes up later and
    becomes a no-op via `tryResume`.

Reviewers: a unit test that injects a connection with a non-firing reply
would meaningfully cover both the timeout path and the reusable-client
guarantee. Happy to add it in this PR or as a follow-up — preference?
The Codex adversarial review of this branch flagged that
`XPCClient.send(_:responseTimeout:)` can drop a late XPC reply after
its timeout fires. For idempotent reads (`ClientHealthCheck.ping`,
`list` operations) that is a deliberate tradeoff: the connection
remains valid for subsequent sends and the next caller can re-issue
the request. For mutating operations the same behavior is unsafe:
the caller surfaces `.timeout`, the user retries, and the original
operation may still commit on the server — duplicate or out-of-order
container/network state under any slow-but-not-dead daemon.

An independent audit of the call sites contradicted the operator note
written when the freeze fix was first proposed. Four mutating call
sites were already reaching the unsafe path:

  - ContainerClient.create (containerCreate, 60s default via xpcSend)
  - NetworkClient.create   (networkCreate,  60s default via xpcSend)
  - NetworkClient.delete   (networkDelete,  60s default via xpcSend)
  - SandboxClient.create   (sandboxCreateEndpoint, 60s timeout: param)

This commit removes that footgun at the API surface so future call
sites cannot reach for it by accident:

  send(_:)                                 -- mutating-safe; no timeout
  send(_:timeoutForIdempotentRequest:)     -- explicit; late-reply drop
                                              acknowledged at call site

The old `responseTimeout:` spelling is retained as
`@available(*, unavailable, ...)` so any reintroduction in a future
patch fails to build with a teaching error pointing at the two
overloads.

Cancellation contract:

  - send(_:) checks Task.isCancelled before dispatch via
    Task.checkCancellation(); after dispatch, cancellation is ignored
    and the call completes only when the daemon replies or the
    underlying connection is invalidated. Honoring cancellation after
    dispatch would re-introduce the same late-commit ambiguity as a
    timeout.
  - send(_:timeoutForIdempotentRequest:) keeps the existing
    reply/timeout/cancellation race semantics, with late replies
    dropped silently so reusable clients keep working.

Call-site migrations:

  - ContainerClient gains an `xpcSendIdempotent(message:timeout:)`
    helper. `create` uses the no-timeout `xpcSend(message:)`; `list`
    uses the idempotent helper with its existing 10s bound.
  - NetworkClient (APIService) follows the same split: `create` and
    `delete` use the no-timeout helper; `list` keeps its 1s bound via
    the idempotent helper.
  - SandboxClient.create drops its `timeout:` parameter; the only
    caller (ContainersService) was already passing the default.
  - ClientHealthCheck.ping calls the idempotent overload with a
    non-optional Duration. All seven ping callers in ContainerCommands
    are unchanged at the call site.

Tests: a new ContainerXPCTests target uses an in-process
`xpc_endpoint_create`-based listener so the contract can be exercised
without a live mach service. Six tests cover both overloads:

  - idempotentTimeoutReturnsWithinBound — verifies the .timeout error
    code (not .interrupted) and that elapsed time is within the
    expected window
  - reusableClientSurvivesIdempotentTimeout — same XPCClient instance
    survives a timeout and can complete a follow-up send
  - lateReplyAfterIdempotentTimeoutIsIgnoredCleanly — server replies
    after the client has timed out; subsequent send still works
  - plainSendCompletesWhenServerReplies — happy path
  - plainSendIgnoresCancellationAfterDispatch — Task.cancel() after
    dispatch must NOT short-circuit; the task waits for the reply
  - plainSendHonorsCancellationBeforeDispatch — pre-dispatch
    cancellation surfaces CancellationError

What this commit does not address:

  - No idempotency token or recovery query (Codex's third suggestion).
    This commit prevents the unsafe combination at the API; it does not
    give callers a way to safely time out a mutating request and then
    ask the daemon "did it actually commit?".
  - Reusable ContainerClient/NetworkClient mutating calls now have no
    timeout (correctly so, per the new contract). Wedged-daemon
    scenarios will hang those callers indefinitely; the user-visible
    workaround (`launchctl bootout`) remains the only escape today.

Both are reasonable follow-ups but out of scope for closing the freeze
regression.
@chrisgeo
chrisgeo marked this pull request as ready for review April 27, 2026 20:14
@chrisgeo chrisgeo changed the title DRAFT: fix(help): indefinite hang on container --help / help / no-args fix(help): indefinite hang on container --help / help / no-args Apr 27, 2026
@jglogan

jglogan commented Apr 28, 2026 •

Copy link
Copy Markdown
Contributor

Hi @chrisgeo, could you please file a bug issue with clear and reliable reproduction steps, and then in this PR description indicate the the PR "Closes #issue-id."?

Please ensure that you have Read the Manual when preparing reproduction steps involving builds, as the ones in this PR seem to indicate that this hasn't been done.

I'm running this and cannot duplicate the issue. It doesn't mean that it's not an issue (there are definitely some XPC cancelation issues but the most pertinent ones relate to the calls from the API server to the container runtime plugin), but we're going to need how to get the system in the state that requires the fix.

I ran:

$ make all
...build output...

$ time .build/debug/container --help
... full help output ...
.build/debug/container --help  0.03s user 0.02s system 4% cpu 0.945 total

$ time .build/debug/container help
... full help output ...
.build/debug/container help  0.02s user 0.01s system 76% cpu 0.038 total

$ time .build/debug/container
... full help output ...
.build/debug/container  0.03s user 0.01s system 78% cpu 0.054 total

@chrisgeo

Copy link
Copy Markdown
Contributor Author

Thanks — agreed that the original description overstated reproducibility.

I filed #1459 and updated the PR description with Closes #1459. I also revised the repro section to distinguish:

  1. healthy make all behavior, which should return quickly and matches your result;
  2. the stale/wedged apiserver launchd/XPC state where this help/default-path bug applies;
  3. launchctl bootout as recovery/cleanup, not a repro step.

I also added explicit BUILDING.md guidance and clarified that the .build/debug/container timings are diagnostic context matching your command, not the canonical installed-helper/plugin-layout setup.

- A recent change moved the list and delete
  network XPC calls within an availability check,
  making them only available on macOS 26.
  However, there are some code flows that rely
  on being able to call `list` on the NetworksService,
  including anything that uses `networkClient.builtin`.
- `container` does not officially support macOS 15
  and as a result we do not have GitHub action runners
  for validation on macOS 15. That said, we try to avoid
  breaking compatibility on macOS 15 as much as
  possible.

Signed-off-by: Kathryn Baldauf <[email protected]>
@chrisgeo chrisgeo closed this Apr 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: help/default commands can hang when apiserver launchd state is wedged

3 participants