Skip to content

fix(sandbox): pass --init so tini reaps zombie processes - #74083

Closed
luckylhb90 wants to merge 1 commit into
openclaw:mainfrom
luckylhb90:fix/sandbox-docker-init
Closed

luckylhb90 wants to merge 1 commit into
openclaw:mainfrom
luckylhb90:fix/sandbox-docker-init

Conversation

@luckylhb90

Copy link
Copy Markdown

Summary

  • Problem:
    What: Adding --init to the docker sandbox makes tini the PID 1 and reaps zombie processes.
    Why: Long-running sandboxes generate a large number of short-lived child processes (shell/browser helpers), and the entrypoint does not reap them → processes accumulate → kernel.pid_max is exhausted → subsequent fork/exec fails.
    Evidence: A new test was added to assert that --init appears in the output of buildSandboxCreateArgs and is placed after create; all 17 local tests passed.
    Risk: Extremely low, --init is an official Docker feature, and the daemon comes with tini.

Change Type (select all)

  • Bug fix
  • Feature
  • Refactor required for the fix
  • Docs
  • Security hardening
  • Chore/infra

Scope (select all touched areas)

  • Gateway / orchestration
  • Skills / tool execution
  • Auth / tokens
  • Memory / storage
  • Integrations
  • API / contracts
  • UI / DX
  • CI/CD / infra

Linked Issue/PR

  • Closes #
  • Related #
  • This PR fixes a bug or regression

Root Cause (if applicable)

For bug fixes or regressions, explain why this happened, not just what changed. Otherwise write N/A. If the cause is unclear, write Unknown.

  • Root cause:
  • Missing detection / guardrail:
  • Contributing context (if known):

Regression Test Plan (if applicable)

For bug fixes or regressions, name the smallest reliable test coverage that should catch this. Otherwise write N/A.

  • Coverage level that should have caught this:
    • Unit test
    • Seam / integration test
    • End-to-end test
    • Existing coverage already sufficient
  • Target test or file:
  • Scenario the test should lock in:
  • Why this is the smallest reliable guardrail:
  • Existing test that already covers this (if any):
  • If no new test is added, why not:

User-visible / Behavior Changes

List user-visible changes (including defaults/config).
If none, write None.

Diagram (if applicable)

For UI changes or non-trivial logic flows, include a small ASCII diagram reviewers can scan quickly. Otherwise write N/A.

Before:
[user action] -> [old state]

After:
[user action] -> [new state] -> [result]

Security Impact (required)

  • New permissions/capabilities? (Yes/No)
  • Secrets/tokens handling changed? (Yes/No)
  • New/changed network calls? (Yes/No)
  • Command/tool execution surface changed? (Yes/No)
  • Data access scope changed? (Yes/No)
  • If any Yes, explain risk + mitigation:

Repro + Verification

Environment

  • OS:
  • Runtime/container:
  • Model/provider:
  • Integration/channel (if any):
  • Relevant config (redacted):

Steps

Expected

Actual

Evidence

Attach at least one:

  • Failing test/log before + passing after
  • Trace/log snippets
  • Screenshot/recording
  • Perf numbers (if relevant)

Human Verification (required)

What you personally verified (not just CI), and how:

  • Verified scenarios:
  • Edge cases checked:
  • What you did not verify:

Review Conversations

  • I replied to or resolved every bot review conversation I addressed in this PR.
  • I left unresolved only the conversations that still need reviewer or maintainer judgment.

If a bot review conversation is addressed by this PR, resolve that conversation yourself. Do not leave bot review conversation cleanup for maintainers.

Compatibility / Migration

  • Backward compatible? (Yes/No)
  • Config/env changes? (Yes/No)
  • Migration needed? (Yes/No)
  • If yes, exact upgrade steps:

Risks and Mitigations

List only real risks for this PR. Add/remove entries as needed. If none, write None.

  • Risk:
    • Mitigation:

@luckylhb90
luckylhb90 requested a review from a team as a code owner April 29, 2026 04:55
@openclaw-barnacle openclaw-barnacle Bot added docker Docker and sandbox tooling agents Agent runtime and tooling size: XS triage: refactor-only Candidate: refactor/cleanup-only PR without maintainer context. labels Apr 29, 2026
@greptile-apps

greptile-apps Bot commented Apr 29, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR adds --init to the docker create arguments so tini becomes PID 1 inside sandbox containers, preventing zombie process accumulation from short-lived child processes. The change is one line in docker.ts with matching test updates.

Confidence Score: 5/5

Safe to merge — minimal, well-tested one-line addition using a stable, official Docker feature.

The change is a single args.push('--init') call backed by a clear comment and a new dedicated test. --init is a long-standing Docker flag that simply enables the built-in tini shim; it introduces no new attack surface or behavioral change beyond proper zombie reaping.

No files require special attention.

Reviews (1): Last reviewed commit: "fix(sandbox): pass --init so tini reaps ..." | Re-trigger Greptile

@clawsweeper

clawsweeper Bot commented Apr 29, 2026 •

Copy link
Copy Markdown
Contributor

Thanks for the context here. I swept through the related work, and this is now duplicate or superseded.

Keep open: the branch targets a real sandbox PID-1 zombie issue that current main still has, but it is not merge-ready because it adds the Docker init flag without a recreate/hash rollout for existing long-lived containers and only provides unit-test proof.

Root-cause cluster
Relationship: fixed_by_candidate
Canonical: #68691
Summary: The canonical issue tracks Docker sandbox PID-1 zombie accumulation; this PR is the direct --init candidate, while the companion hash PR covers rollout and other zombie work affects adjacent process/runtime surfaces.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Canonical path: Close this stale PR. The latest review rated it F, the branch still lacks merge-ready proof, and there has been no human follow-up after the durable review.

So I’m closing this here because the remaining work is already tracked in the canonical issue.

Review details

Best possible solution:

Close this stale PR. The latest review rated it F, the branch still lacks merge-ready proof, and there has been no human follow-up after the durable review.

Do we have a high-confidence way to reproduce the issue?

Yes, source-level: current main creates sandbox containers without Docker --init and runs sleep infinity as PID 1, matching the linked reporter logs. I did not run a live long-duration Docker zombie workload in this read-only review.

Is this the best way to solve the issue?

No, not as submitted. Docker --init is the right fresh-container primitive, but the best fix also needs a create-args hash/recreate path and real Docker proof for existing long-lived sandboxes.

Security review:

Security review cleared: No concrete security or supply-chain concern found; the diff changes Docker create arguments and tests without dependencies, workflows, secrets, package resolution, or permissions.

AGENTS.md: found and applied where relevant.

What I checked:

  • stale F-rated PR: PR was opened 2026-04-29T04:55:47Z, is older than 60 days, and the latest review rated it F.
  • proof blocker: real behavior proof is mock_only and proof tier is F, so this branch is not merge-ready without contributor follow-up.
  • no human follow-up: live comments and timeline hydrated by apply contain no non-automation activity after the ClawSweeper review.

Likely related people:

  • Peter Steinberger: Authored the sandbox config-hash auto-recreate path and later browser hash migration work around the affected lifecycle boundary. (role: feature history owner; confidence: high; commits: 79d8267413cc, 1835dec2004f, 1f1fc095a0ab; files: src/agents/sandbox/docker.ts, src/agents/sandbox/config-hash.ts, src/agents/sandbox/browser.ts)
  • Josh Avant: Recently changed explicit Docker env-policy hashing on the same sandbox create and reuse path that a refresh must preserve. (role: recent area contributor; confidence: medium; commits: 045a581069dc, 6f1076351cbe; files: src/agents/sandbox/docker.ts, src/agents/sandbox/config-hash.ts, src/agents/sandbox/browser.ts)
  • Davanum Srinivas: Added the sandbox browser security hash epoch pattern, the closest merged analogue for forcing recreation when a sandbox runtime contract changes. (role: adjacent owner; confidence: medium; commits: fbf11ebdb711; files: src/agents/sandbox/constants.ts, src/agents/sandbox/browser.ts, src/agents/sandbox/config-hash.ts)
  • Ayu: Authored the merged Docker runtime-image tini fix, which resolves the main image PID-1 surface but not agent-created sandbox containers. (role: adjacent merged fix author; confidence: medium; commits: e63e4f9551e9; files: Dockerfile, docs/install/docker.md, docs/install/fly.md)

Codex review notes: model internal, reasoning high; reviewed against 010b61746379.

@aaajiao

aaajiao commented May 3, 2026

Copy link
Copy Markdown
Contributor

Original reporter of #68691 here — confirming the production impact described in this PR's summary.

Long-lived OpenClaw sandbox in production: scope: "agent" + prune.idleHours: 0 + prune.maxAgeDays: 0, container running for weeks. Original symptom (#68691) was PPID=1 zombies stacking after each bash/git/pnpm subprocess that exited before its parent. Bumped pidsLimit 256 → 1024 as a band-aid; not a fix.

Echoing clawsweeper's P2 (and the parallel review on #68691): the hash-rollout gap is the real blocker for our pattern. With prune.maxAgeDays: 0, the container would never recreate naturally after this PR merges — it would keep its non-init PID 1 indefinitely.

Minimal fix: add a static INIT_EPOCH = 1 to the config-hash input in src/agents/sandbox/config-hash.ts, alongside the existing mountFormatVersion / browserSecurityEpoch pattern. One line; reusable for any future container-flag change.

Happy to test a patched branch with the hash-epoch addition on our long-lived sandbox if it helps maintainers verify the recreate path.

stubbi added a commit to stubbi/openclaw-operator that referenced this pull request May 12, 2026
## Summary

Adds `spec.shareProcessNamespace` (default `true`) to
`OpenClawInstance`. When enabled, all containers in the pod share a PID
namespace and the Kubernetes `pause` container becomes PID 1,
automatically reaping zombie processes that accumulate under the Node.js
gateway (which does not call `waitpid()` on orphaned children).

Closes #471.
Supersedes #476 — incorporates @alexander-morris's production-validated
approach with the docs, unit tests, e2e tests, and field placement
requested in [the review on
#476](#476 (review)).

## Background

[#471](#471)
reported 28 defunct processes accumulating under PID 1 on a production
OpenClaw pod (QMD, git, shells, plugin helpers). Image-level fixes
(`tini` in the entrypoint) are the most durable long-term solution and
are tracked upstream at openclaw/openclaw#74083, but operator users have
no clean way to wrap the entrypoint today. PID-namespace sharing is the
standard Kubernetes-native answer and stacks harmlessly with a future
upstream init process.

@alexander-morris validated the approach in production (28 agents, 7+
hours, zero zombie accumulation, zero unrelated restarts on 24/28 pods).

## Changes

**Core:**
- `api/v1alpha1/openclawinstance_types.go` — `ShareProcessNamespace
*bool` with `+kubebuilder:default=true`, placed next to `Security`
(pod-level runtime/security cluster) per review feedback on #476.
- `internal/resources/statefulset.go` — `shareProcessNamespace()`
helper; treats `nil` as `true` so instances stored before the field
existed still get the fix on next reconcile.

**Generated (do not hand-edit):**
- `api/v1alpha1/zz_generated.deepcopy.go`
- `config/crd/bases/openclaw.rocks_openclawinstances.yaml`
-
`charts/openclaw-operator/templates/crds/openclaw.rocks_openclawinstances.yaml`

**Tests:**
- `internal/resources/resources_test.go` — three new builder cases:
default-true (field unset), explicit-true, explicit-false. Pattern
matches the existing `AutomountServiceAccountToken` tests.
- `test/e2e/e2e_suite_test.go` — two new specs in the controller suite:
default-true and explicit-false override. Pattern matches the adjacent
`runtimeClassName` spec.

**Docs:**
- `README.md` — new feature-table row and a "Shared Process Namespace"
subsection with opt-out snippet and security trade-off.
- `docs/api-reference.md` — `spec.shareProcessNamespace` field reference
with type/default/behavior, security implication, and upgrade note about
pod-template rollout for existing instances.

## Security trade-off (called out in docs)

With sharing enabled, every container in the pod can see and signal
every other container's processes. A compromised sidecar (Tailscale,
Ollama, browser, custom) could send signals to the gateway and vice
versa. For most deployments the zombie-reaping benefit clearly outweighs
this; users with mutually-distrusting sidecars can opt out per instance
and reap inside their image (`tini`/`dumb-init`).

## Upgrade impact

Flipping the default to `true` means every existing `OpenClawInstance`
will get a one-time pod-template change on next reconcile, rolling pods.
Operators running large fleets should plan a maintenance window. Called
out in the api-reference upgrade note.

## Test plan

- [x] `go test ./internal/resources/` passes (3 new tests covering
default/true/false)
- [x] `make lint` passes (golangci-lint v1.64.5)
- [x] `go vet ./...` clean
- [x] `make generate manifests sync-chart-crds` regenerates cleanly (no
manual edits to generated files)
- [ ] E2E suite passes in CI on a real kind cluster (new specs follow
the existing `runtimeClassName` pattern)

## Credit

Production validation and original PR by @alexander-morris in #476.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: alexander-morris <[email protected]>
Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale due to inactivity.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added stale Marked as stale due to inactivity triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. labels May 30, 2026
@clawsweeper clawsweeper Bot added the rating: 🌊 off-meta tidepool PR readiness rating does not apply to this item. label May 30, 2026
@barnacle-openclaw barnacle-openclaw Bot removed the stale Marked as stale due to inactivity label May 30, 2026
@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale due to inactivity.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label Jun 14, 2026
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. and removed rating: 🌊 off-meta tidepool PR readiness rating does not apply to this item. labels Jun 14, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the stale Marked as stale due to inactivity label Jun 15, 2026
@clawsweeper clawsweeper Bot removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Jun 17, 2026
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Jun 17, 2026
@steipete steipete self-assigned this Jul 10, 2026
@steipete

Copy link
Copy Markdown
Contributor

Thank you @luckylhb90 — this fix has landed on main through #103441 as f698703934f, with your contribution preserved through a co-author trailer.

The final version keeps --init in the shared Docker sandbox create arguments and adds one shared create-arguments epoch to both ordinary and browser configuration hashes. That ensures idle old containers recreate while recently active containers remain running and receive the existing recreate hint. Real Docker proof confirmed HostConfig.Init=true, PID 1 docker-init, zero zombies after an orphaned-grandchild scenario, cold recreation, and hot deferral; exact-head CI passed in run 29072559013.

The original fork head was too stale for the safe maintainer GraphQL update path without generating a repository-wide payload, so the reviewed one-commit version was carried in the maintainer replacement. Closing this PR as superseded by the landed fix.

@steipete steipete closed this Jul 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docker Docker and sandbox tooling merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: XS status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. triage: refactor-only Candidate: refactor/cleanup-only PR without maintainer context.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants