← Back to Pull requests

fix(podman): tighten compose compatibility #3035

Open
iandvt opened this pull request with 1222 lines diff across 9 files
View on GitHub
iandvt iandvt commented on Sep 01, 2026 22:53 UTC
Author

Description

Ports the remaining Podman fixes from #1432 onto the shared ContainerRuntime lifecycle from #2872 and #3672. Without these changes, podman-compose 1.x corrupts exec output with its JSON banner and default TTY, fails fallback when docker needs root, rejects --no-TTY, and stretches readiness waits past timeout_sec.

  • Shares probe_podman_compose_ls() between resolve_podman_runtime() and PodmanEnvironment._check_compose_provider() so Harbor falls back to podman-compose --in-pod=false when Docker requires root or podman.socket is down.

  • Adds ContainerRuntime.exec_via_engine for podman-compose 1.x so UnixOps.engine_exec() resolves containers by Compose project and service labels (preferring running containers) and runs podman exec directly.

  • Switches Compose exec and _apply_network_policy() to -T, keeps stderr on its own pipe (merge_stderr=False), and unwraps a single callback exception from the stderr TaskGroup without mutating __context__ or turning a callback TimeoutError into a command timeout.

  • Gates down --rmi local on ContainerRuntime.remove_local_images, bounds readiness waiters by monotonic wall time, and adds local Podman setup notes to docs-mintlify/sandboxes/pre-integrated-sandboxes.mdx.
  • Validation

  • Passed ruff check ., ruff format --check ., scoped ty check (src/harbor/environments/docker/, podman.py, options.py), and the 4 touched environment unit suites (249 passed, 2 Windows-only skipped) on 021f19a113dba1f924157ee05da11699a7ff0262.

  • tests/unit/environments/test_options.py and tests/runtime/test_network_policy_matrix_podman.py were not rerun locally after rebasing onto cf4bd0043f4e3a91847edf1b799343caf74cf182 because the local venv lacks harbor-framework-client>=0.3.0; both will run in CI.
  • Diff: 1222 lines (+1099 / -123) across 9 files Reviewer: iandvt Review duration: 130966m
    All Vouch review confidence checks passed
    Residual risk 0.13 = Change Risk (0.76) × (1 − Review Confidence (0.82)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.76 · 1222 lines diff across 9 files
    0.76
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.92 · 5 substantive comment(s)
    0.92
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    82%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Self Review self_review
    0.140
    Real PR Conversation Timeline
    20 items
    github-actions[bot] github-actions[bot] commented on Sep 01, 2026 22:54 UTC
    Bot

    Enjoy a better diff viewing experience by clicking one of these URLs:

  • <a href="https://devinreview.com/harbor-framework/harbor/pull/3035" target="_blank" rel="noopener noreferrer">devinreview</a>

  • <a href="https://diffshub.com/harbor-framework/harbor/pull/3035" target="_blank" rel="noopener noreferrer">diffshub</a>

  • <a href="https://linear.review/harbor-framework/harbor/pull/3035" target="_blank" rel="noopener noreferrer">linear</a>
  • devin-ai-integration[bot] devin-ai-integration[bot] commented on code on Sep 01, 2026 22:56 UTC
    Code Review
    src/harbor/environments/docker/docker.py:1
    @@ -1024,15 +1025,22 @@ async def _wait_until_compose_exec_ready(self, timeout_sec: int = 90) -> None:
             Used only when the compose frontend cannot ``up --wait``.
             """
             last_error: str | None = None
    -        for _ in range(timeout_sec):
    +        deadline = time.monotonic() + timeout_sec
    +        while (remaining := deadline - time.monotonic()) > 0:
    +            command_timeout = min(5, int(remaining))
    +            if command_timeout == 0:
    +                await asyncio.sleep(remaining)
    +                break

    <!-- devin-review-comment {"id": "BUG_pr-review-job-844fff306c614cfebcf3a8e92fdffd3e_0001", "file_path": "src/harbor/environments/docker/docker.py", "start_line": 1030, "end_line": 1033, "side": "RIGHT", "based_on_repo_rules": false, "kind": "bug"} -->

    🟡 Final readiness interval goes unprobed

    When less than one second remains, both readiness waiters call sleep instead of probing. Containers ready during that interval fail startup.

    <details>
    <summary>Prompt for agents</summary>

    Both DockerEnvironment._wait_until_compose_exec_ready and DockerEnvironment._wait_until_egress_sidecar_ready truncate the remaining monotonic time to an integer command timeout. When the remainder falls below one second, they sleep until the deadline and raise without checking readiness again. Preserve the elapsed deadline while allowing a final probe during that fractional interval, and cover both waiters with a test where readiness arrives during the last subsecond.
    

    </details>

    <!-- devin-review-badge-begin -->
    <a href="https://app.devin.ai/review/harbor-framework/harbor/pull/3035" target="_blank">
    <picture>
    <source media="(prefers-color-scheme: dark)" srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=3">
    <img src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=3" alt="Devin Review">
    </picture>
    </a>
    <!-- devin-review-badge-end -->

    ---
    Was this helpful? React with 👍 or 👎 to provide feedback.

    devin-ai-integration[bot] devin-ai-integration[bot] commented on Sep 01, 2026 22:56 UTC
    Reviewer

    [!NOTE]

    Newer findings are available below. Devin Review posted a newer report on this PR, in addition to the findings presented here.

    Devin Review found 1 potential issue.

    <!-- devin-review-badge-begin -->
    <a href="https://app.devin.ai/review/harbor-framework/harbor/pull/3035" target="_blank">
    <picture>
    <source media="(prefers-color-scheme: dark)" srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=3">
    <img src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=3" alt="Devin Review">
    </picture>
    </a>
    <!-- devin-review-badge-end -->

    iandvt iandvt commented on code on Sep 02, 2026 00:17 UTC
    Code Review
    src/harbor/environments/docker/docker.py:1
    @@ -1024,15 +1025,22 @@ async def _wait_until_compose_exec_ready(self, timeout_sec: int = 90) -> None:
             Used only when the compose frontend cannot ``up --wait``.
             """
             last_error: str | None = None
    -        for _ in range(timeout_sec):
    +        deadline = time.monotonic() + timeout_sec
    +        while (remaining := deadline - time.monotonic()) > 0:
    +            command_timeout = min(5, int(remaining))
    +            if command_timeout == 0:
    +                await asyncio.sleep(remaining)
    +                break

    Fix in 036f86b6.

    devin-ai-integration[bot] devin-ai-integration[bot] commented on code on Sep 02, 2026 00:19 UTC
    Code Review
    src/harbor/environments/docker/docker.py:1
    @@ -1024,15 +1025,22 @@ async def _wait_until_compose_exec_ready(self, timeout_sec: int = 90) -> None:
             Used only when the compose frontend cannot ``up --wait``.
             """
             last_error: str | None = None
    -        for _ in range(timeout_sec):
    +        deadline = time.monotonic() + timeout_sec
    +        while (remaining := deadline - time.monotonic()) > 0:
    +            command_timeout = min(5, int(remaining))
    +            if command_timeout == 0:
    +                await asyncio.sleep(remaining)
    +                break

    ✅ Resolved: Both readiness waiters now pass the fractional remaining deadline to the final probe instead of sleeping without probing.

    egorse-tel egorse-tel commented on Sep 11, 2026 06:25 UTC
    Contributor

    1. PR did not worked for me out of box

    Had to create ~/.config/containers/containers.conf

    [engine]
    compose_providers = ["podman-compose"]
    

    Have podman version 4.9.3 and podman-compose version: 1.0.6

    Do have docker/docker compose but at least docker requires sudo.

    2.

    ❯ harbor run --dataset harbor/hello-world --agent pi --env podman
      1/1 Mean: 0.000 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 0:00:16 0:00:00
    
    harbor/hello-world • pi
    ┏━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━┓
    ┃ Trials ┃ Exceptions ┃  Mean ┃
    ┡━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━┩
    │      0 │          1 │ 0.000 │
    └────────┴────────────┴───────┘
    
    ┏━━━━━━━━━━━━━━┳━━━━━━━┓
    ┃ Exception    ┃ Count ┃
    ┡━━━━━━━━━━━━━━╇━━━━━━━┩
    │ RuntimeError │     1 │
    └──────────────┴───────┘
    
    Job Info
    Total runtime: 16s
    Results written to jobs/2026-09-11__09-21-31/result.json
    Inspect results by running `harbor view jobs`
    Share results by running `harbor upload jobs/2026-09-11__09-21-31`
    

    Exception:

    ❯ cat jobs/2026-09-11__09-21-31/hello-world__LRYybng/exception.txt
    Traceback (most recent call last):
      File "/home/egorse-tel/.local/share/uv/tools/harbor/lib/python3.12/site-packages/harbor/agents/installed/base.py", line 954, in setup
        await self.install(environment)
      File "/home/egorse-tel/.local/share/uv/tools/harbor/lib/python3.12/site-packages/harbor/agents/installed/pi.py", line 83, in install
        await self.ensure_system_dependencies(environment, ("curl",))
      File "/home/egorse-tel/.local/share/uv/tools/harbor/lib/python3.12/site-packages/harbor/agents/installed/base.py", line 662, in ensure_system_dependencies
        dict.fromkeys(
      File "/home/egorse-tel/.local/share/uv/tools/harbor/lib/python3.12/site-packages/harbor/agents/installed/base.py", line 663, in <genexpr>
        package for spec in specs for package in spec.packages[manager]
                                                 ~~~~~~~~~~~~~^^^^^^^^^
    KeyError: 'podman-compose version: 1.0.6\n[\'podman\', \'--version\', \'\']\nusing podman version: 4.9.3\n ** merged:\n {\n  "services": {\n    "main": {\n      "cpus": 1.0,\n      "mem_limit": "2048m",\n      "build": {\n        "context": "/home/egorse-tel/.cache/harbor/tasks/packages/hello-world/hello-world/38d7a077f07fbee8efc78db5dec9a72f82e727510ad1dcfeac0b55fa845256b7/environment"\n      },\n      "pull_policy": "build",\n      "command": [\n        "sh",\n        "-c",\n        "sleep infinity"\n      ],\n      "environment": {},\n      "volumes": [\n        {\n          "type": "bind",\n          "source": "/home/egorse-tel/projects/ai/harbor/jobs/2026-09-11__09-21-31/hello-world__LRYybng/verifier",\n          "target": "/logs/verifier"\n        },\n        {\n          "type": "bind",\n          "source": "/home/egorse-tel/projects/ai/harbor/jobs/2026-09-11__09-21-31/hello-world__LRYybng/agent",\n          "target": "/logs/agent"\n        },\n        {\n          "type": "bind",\n          "source": "/home/egorse-tel/projects/ai/harbor/jobs/2026-09-11__09-21-31/hello-world__LRYybng/artifacts/logs/artifacts",\n          "target": "/logs/artifacts"\n        }\n      ]\n    }\n  },\n  "_dirname": "/tmp/tmpjv7y9y1h"\n}\npodman exec --interactive --user root --tty hello-world__lryybng__env_main_1 bash -c for manager in apt-get dnf yum apk; do if command -v "$manager" >/dev/null 2>&1; then printf "%s" "$manager"; break; fi; done\napt-getexit code: 0'
    
    The above exception was the direct cause of the following exception:
    
    Traceback (most recent call last):
      File "/home/egorse-tel/.local/share/uv/tools/harbor/lib/python3.12/site-packages/harbor/trial/trial.py", line 406, in run
        await self._prepare()
      File "/home/egorse-tel/.local/share/uv/tools/harbor/lib/python3.12/site-packages/harbor/trial/trial.py", line 450, in _prepare
        await self._setup_agent()
      File "/home/egorse-tel/.local/share/uv/tools/harbor/lib/python3.12/site-packages/harbor/trial/trial.py", line 1455, in _setup_agent
        await asyncio.wait_for(
      File "/usr/lib/python3.12/asyncio/tasks.py", line 520, in wait_for
        return await fut
               ^^^^^^^^^
      File "/home/egorse-tel/.local/share/uv/tools/harbor/lib/python3.12/site-packages/harbor/agents/installed/base.py", line 958, in setup
        raise RuntimeError(f"Agent install failed: {exc}") from exc
    RuntimeError: Agent install failed: 'podman-compose version: 1.0.6\n[\'podman\', \'--version\', \'\']\nusing podman version: 4.9.3\n ** merged:\n {\n  "services": {\n    "main": {\n      "cpus": 1.0,\n      "mem_limit": "2048m",\n      "build": {\n        "context": "/home/egorse-tel/.cache/harbor/tasks/packages/hello-world/hello-world/38d7a077f07fbee8efc78db5dec9a72f82e727510ad1dcfeac0b55fa845256b7/environment"\n      },\n      "pull_policy": "build",\n      "command": [\n        "sh",\n        "-c",\n        "sleep infinity"\n      ],\n      "environment": {},\n      "volumes": [\n        {\n          "type": "bind",\n          "source": "/home/egorse-tel/projects/ai/harbor/jobs/2026-09-11__09-21-31/hello-world__LRYybng/verifier",\n          "target": "/logs/verifier"\n        },\n        {\n          "type": "bind",\n          "source": "/home/egorse-tel/projects/ai/harbor/jobs/2026-09-11__09-21-31/hello-world__LRYybng/agent",\n          "target": "/logs/agent"\n        },\n        {\n          "type": "bind",\n          "source": "/home/egorse-tel/projects/ai/harbor/jobs/2026-09-11__09-21-31/hello-world__LRYybng/artifacts/logs/artifacts",\n          "target": "/logs/artifacts"\n        }\n      ]\n    }\n  },\n  "_dirname": "/tmp/tmpjv7y9y1h"\n}\npodman exec --interactive --user root --tty hello-world__lryybng__env_main_1 bash -c for manager in apt-get dnf yum apk; do if command -v "$manager" >/dev/null 2>&1; then printf "%s" "$manager"; break; fi; done\napt-getexit code: 0'
    

    mintlify[bot] mintlify[bot] commented on Oct 30, 2026 18:29 UTC
    Bot

    <!-- mintlify-fork-preview-approval -->

    Preview approval required

    This pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit 4d1485d.

    Approve preview

    devin-ai-integration[bot] devin-ai-integration[bot] commented on code on Oct 30, 2026 18:32 UTC
    Code Review
    src/harbor/environments/docker/docker_unix.py:1
    @@ -219,19 +227,72 @@ async def _resolve_service_container(self, service: str) -> str:
                 stdout=asyncio.subprocess.PIPE,
                 stderr=asyncio.subprocess.DEVNULL,
             )
    -        stdout, _ = await proc.communicate()
    -        suffixes = (f"_{service}_1", f"-{service}-1")
    +        try:
    +            if timeout_sec:
    +                stdout, _ = await asyncio.wait_for(
    +                    proc.communicate(), timeout=timeout_sec
    +                )
    +            else:
    +                stdout, _ = await proc.communicate()
    +        except asyncio.TimeoutError:
    +            await DockerEnvironment._terminate_process(proc)
    +            raise RuntimeError(f"Command timed out after {timeout_sec} seconds")
    +
    +        exact_names = (f"{project}_{service}_1", f"{project}-{service}-1")
             for line in stdout.decode(errors="replace").splitlines():
                 cid, _, name = line.partition("\t")
                 name = name.strip()
                 cid = cid.strip()
    -            if name.endswith(suffixes):
    +            if name in exact_names:

    <!-- devin-review-comment {"id": "BUG_pr-review-job-2c44387009734db59336ede25aa20f37_0001", "file_path": "src/harbor/environments/docker/docker_unix.py", "start_line": 241, "end_line": 246, "side": "RIGHT", "based_on_repo_rules": false, "kind": "bug"} -->

    🔴 Custom container names block Podman execution

    When a task sets container_name, _resolve_service_container rejects its project-labeled container because its name differs from the generated names. Podman 1.x cannot run readiness checks or task commands, and engine-copy downloads also fail.

    <details>
    <summary>Learn more</summary>

    A task's Compose file is merged over Harbor's base service, so it can assign container_name to main or a sidecar Compose paths. The engine query already filters by the correct Compose project label, but the returned name is checked against only two generated names. In the Podman 1.x path, every task command uses engine_exec, including the initial readiness check. This failure also applies to downloads using the engine fallback download_file.

    Example: A project trial-a with main: {container_name: my-agent} produces a project-labeled container named my-agent. The lookup rejects it, so startup fails despite the container running.

    Recommended fix: Resolve service identity from the Compose service label in addition to the project label, rather than inferring it solely from the container name. Preserve project isolation and handle replicas deterministically.

    </details>

    <!-- devin-review-badge-begin -->
    <a href="https://app.devin.ai/review/harbor-framework/harbor/pull/3035" target="_blank"><picture><source media="(prefers-color-scheme: dark)" srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4" alt="Devin Review"></picture></a>
    <!-- devin-review-badge-end -->

    ---
    Was this helpful? React with 👍 or 👎 to provide feedback.

    devin-ai-integration[bot] devin-ai-integration[bot] commented on Oct 30, 2026 18:32 UTC
    Reviewer

    [!NOTE]

    Newer findings are available below. Devin Review posted a newer report on this PR, in addition to the findings presented here.

    Devin Review found 1 new potential issue.

    <!-- devin-review-badge-begin -->
    <a href="https://app.devin.ai/review/harbor-framework/harbor/pull/3035" target="_blank"><picture><source media="(prefers-color-scheme: dark)" srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4" alt="Devin Review"></picture></a>
    <!-- devin-review-badge-end -->

    devin-ai-integration[bot] devin-ai-integration[bot] commented on code on Oct 30, 2026 19:03 UTC
    Code Review
    src/harbor/environments/docker/docker_unix.py:1
    @@ -219,19 +227,72 @@ async def _resolve_service_container(self, service: str) -> str:
                 stdout=asyncio.subprocess.PIPE,
                 stderr=asyncio.subprocess.DEVNULL,
             )
    -        stdout, _ = await proc.communicate()
    -        suffixes = (f"_{service}_1", f"-{service}-1")
    +        try:
    +            if timeout_sec:
    +                stdout, _ = await asyncio.wait_for(
    +                    proc.communicate(), timeout=timeout_sec
    +                )
    +            else:
    +                stdout, _ = await proc.communicate()
    +        except asyncio.TimeoutError:
    +            await DockerEnvironment._terminate_process(proc)
    +            raise RuntimeError(f"Command timed out after {timeout_sec} seconds")
    +
    +        exact_names = (f"{project}_{service}_1", f"{project}-{service}-1")
             for line in stdout.decode(errors="replace").splitlines():
                 cid, _, name = line.partition("\t")
                 name = name.strip()
                 cid = cid.strip()
    -            if name.endswith(suffixes):
    +            if name in exact_names:

    ✅ Resolved: Resolved: service-label filtering and fallback candidate selection now allow custom container names to be resolved.

    devin-ai-integration[bot] devin-ai-integration[bot] commented on code on Oct 30, 2026 19:03 UTC
    Code Review
    src/harbor/environments/docker/docker_unix.py:1
    @@ -213,25 +221,88 @@ async def _resolve_service_container(self, service: str) -> str:
                     "-a",
                     "--filter",
                     f"label=com.docker.compose.project={project}",
    +                "--filter",
    +                f"label=com.docker.compose.service={service}",
                     "--format",
                     "{{.ID}}\t{{.Names}}",
                 ),
                 stdout=asyncio.subprocess.PIPE,
                 stderr=asyncio.subprocess.DEVNULL,
             )
    -        stdout, _ = await proc.communicate()
    -        suffixes = (f"_{service}_1", f"-{service}-1")
    +        try:
    +            if timeout_sec:
    +                stdout, _ = await asyncio.wait_for(
    +                    proc.communicate(), timeout=timeout_sec
    +                )
    +            else:
    +                stdout, _ = await proc.communicate()
    +        except asyncio.TimeoutError:
    +            await DockerEnvironment._terminate_process(proc)
    +            raise RuntimeError(f"Command timed out after {timeout_sec} seconds")
    +
    +        exact_names = (f"{project}_{service}_1", f"{project}-{service}-1")
    +        fallback: str | None = None
             for line in stdout.decode(errors="replace").splitlines():
                 cid, _, name = line.partition("\t")
                 name = name.strip()
                 cid = cid.strip()
    -            if name.endswith(suffixes):
    -                return cid or name
    +            candidate = cid or name
    +            if not candidate:
    +                continue
    +            if name in exact_names:
    +                return candidate
    +            if fallback is None:
    +                fallback = candidate
    +        if fallback is not None:
    +            return fallback

    <!-- devin-review-comment {"id": "BUG_pr-review-job-e7e4ff36dd02499ea86cc06f6e08b1ae_0001", "file_path": "src/harbor/environments/docker/docker_unix.py", "start_line": 254, "end_line": 257, "side": "RIGHT", "based_on_repo_rules": false, "kind": "bug"} -->

    🟡 Stopped replica blocks scaled service execution

    When replica 1 is absent, _resolve_service_container can select a stopped replica listed before a running one. podman ps -a includes both, so service execution fails despite a running replica.

    <details>
    <summary>Learn more</summary>

    The service lookup supplies the container ID to engine_exec and to downloads. podman ps -a includes stopped containers. Exact-name matching does not apply when replica 1 is absent or the service uses custom names, and the fallback does not distinguish running from stopped containers. A stopped candidate listed first can therefore make an available service fail to execute or download.

    Example: A service has replicas app_api_2 (running) and app_api_3 (stopped), with app_api_1 removed. If ps -a lists replica 3 first, service_exec("true", service="api") calls podman exec on replica 3 and fails.

    Recommended fix: Resolve running containers first, or include running state in the ps output and prefer running candidates before falling back to stopped ones. Preserve the exact-name preference among usable candidates.

    </details>

    <!-- devin-review-badge-begin -->
    <a href="https://app.devin.ai/review/harbor-framework/harbor/pull/3035" target="_blank"><picture><source media="(prefers-color-scheme: dark)" srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4" alt="Devin Review"></picture></a>
    <!-- devin-review-badge-end -->

    ---
    Was this helpful? React with 👍 or 👎 to provide feedback.

    devin-ai-integration[bot] devin-ai-integration[bot] commented on Oct 30, 2026 19:03 UTC
    Reviewer

    [!NOTE]

    Newer findings are available below. Devin Review posted a newer report on this PR, in addition to the findings presented here.

    Devin Review found 1 new potential issue.

    <!-- devin-review-badge-begin -->
    <a href="https://app.devin.ai/review/harbor-framework/harbor/pull/3035" target="_blank"><picture><source media="(prefers-color-scheme: dark)" srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4" alt="Devin Review"></picture></a>
    <!-- devin-review-badge-end -->

    devin-ai-integration[bot] devin-ai-integration[bot] commented on code on Oct 30, 2026 19:28 UTC
    Code Review
    src/harbor/environments/docker/docker_unix.py:1
    @@ -213,25 +221,88 @@ async def _resolve_service_container(self, service: str) -> str:
                     "-a",
                     "--filter",
                     f"label=com.docker.compose.project={project}",
    +                "--filter",
    +                f"label=com.docker.compose.service={service}",
                     "--format",
                     "{{.ID}}\t{{.Names}}",
                 ),
                 stdout=asyncio.subprocess.PIPE,
                 stderr=asyncio.subprocess.DEVNULL,
             )
    -        stdout, _ = await proc.communicate()
    -        suffixes = (f"_{service}_1", f"-{service}-1")
    +        try:
    +            if timeout_sec:
    +                stdout, _ = await asyncio.wait_for(
    +                    proc.communicate(), timeout=timeout_sec
    +                )
    +            else:
    +                stdout, _ = await proc.communicate()
    +        except asyncio.TimeoutError:
    +            await DockerEnvironment._terminate_process(proc)
    +            raise RuntimeError(f"Command timed out after {timeout_sec} seconds")
    +
    +        exact_names = (f"{project}_{service}_1", f"{project}-{service}-1")
    +        fallback: str | None = None
             for line in stdout.decode(errors="replace").splitlines():
                 cid, _, name = line.partition("\t")
                 name = name.strip()
                 cid = cid.strip()
    -            if name.endswith(suffixes):
    -                return cid or name
    +            candidate = cid or name
    +            if not candidate:
    +                continue
    +            if name in exact_names:
    +                return candidate
    +            if fallback is None:
    +                fallback = candidate
    +        if fallback is not None:
    +            return fallback

    ✅ Resolved: Resolved: the lookup now records running candidates separately and prioritizes them over stopped candidates.

    iandvt iandvt commented on Oct 30, 2026 19:33 UTC
    Author

    @egorse-tel Thanks for testing this and posting the traceback. Both issues are fixed in f3e96f4f.

    1. PR did not worked for me out of box

    > Had to create ~/.config/containers/containers.conf

    > [engine]
    > compose_providers = ["podman-compose"]
    > 

    > Have podman version 4.9.3 and podman-compose version: 1.0.6

    > Do have docker/docker compose but at least docker requires sudo.

    resolve_podman_runtime() now runs podman compose ls before selecting the Compose V2 path. When docker needs sudo or the Podman socket is down, that check fails and Harbor falls back to podman-compose --in-pod=false on its own. You can remove the containers.conf override.

    2.

    > KeyError: 'podman-compose version: 1.0.6\n[\'podman\', \'--version\', \'\']\nusing podman version: 4.9.3\n ** merged:\n ...
    > podman exec --interactive --user root --tty hello-world__lryybng__env_main_1 bash -c for manager in apt-get dnf yum apk; do if command -v "$manager" >/dev/null 2>&1; then printf "%s" "$manager"; break; fi; done\napt-getexit code: 0'
    > 

    podman-compose 1.0.6 dumps its version banner, merged Compose JSON, and exit code: 0 to stdout on every exec and allocates --tty by default. On podman-compose 1.x, Harbor now resolves the container with podman ps and runs podman exec directly without a TTY. Compose exec also passes -T now and keeps stderr on its own pipe instead of merging it into stdout, so Pi._get_system_package_manager() gets "apt-get".

    devin-ai-integration[bot] devin-ai-integration[bot] commented on code on Nov 26, 2026 04:22 UTC
    Code Review
    src/harbor/environments/docker/docker_unix.py:1
    @@ -213,25 +221,102 @@ async def _resolve_service_container(self, service: str) -> str:
                     "-a",
                     "--filter",
                     f"label=com.docker.compose.project={project}",
    +                "--filter",
    +                f"label=com.docker.compose.service={service}",
                     "--format",
    -                "{{.ID}}\t{{.Names}}",
    +                "{{.ID}}\t{{.Names}}\t{{.State}}",
                 ),
                 stdout=asyncio.subprocess.PIPE,
                 stderr=asyncio.subprocess.DEVNULL,
             )
    -        stdout, _ = await proc.communicate()
    -        suffixes = (f"_{service}_1", f"-{service}-1")
    +        try:
    +            if timeout_sec:
    +                stdout, _ = await asyncio.wait_for(
    +                    proc.communicate(), timeout=timeout_sec
    +                )
    +            else:
    +                stdout, _ = await proc.communicate()
    +        except asyncio.TimeoutError:
    +            await DockerEnvironment._terminate_process(proc)
    +            raise RuntimeError(f"Command timed out after {timeout_sec} seconds")
    +
    +        exact_names = (f"{project}_{service}_1", f"{project}-{service}-1")
    +        running_exact: str | None = None
    +        running_fallback: str | None = None
    +        stopped_exact: str | None = None
    +        stopped_fallback: str | None = None
             for line in stdout.decode(errors="replace").splitlines():
    -            cid, _, name = line.partition("\t")
    +            cid, _, remainder = line.partition("\t")
    +            name, _, state = remainder.partition("\t")
                 name = name.strip()
                 cid = cid.strip()
    -            if name.endswith(suffixes):
    -                return cid or name
    +            state = state.strip().lower()
    +            candidate = cid or name
    +            if not candidate:
    +                continue
    +            is_running = state == "running" or state == ""
    +            is_exact = name in exact_names
    +            if is_running and is_exact and running_exact is None:
    +                running_exact = candidate
    +            elif is_running and running_fallback is None:
    +                running_fallback = candidate
    +            elif not is_running and is_exact and stopped_exact is None:
    +                stopped_exact = candidate
    +            elif not is_running and stopped_fallback is None:
    +                stopped_fallback = candidate
    +        resolved = (
    +            running_exact or running_fallback or stopped_exact or stopped_fallback
    +        )
    +        if resolved is not None:
    +            return resolved
             raise RuntimeError(
                 f"Could not resolve container for compose service {service!r} "
                 f"in project {project!r}."
             )
     
    +    async def engine_exec(
    +        self,
    +        *,
    +        service: str,
    +        exec_options: list[str],
    +        command_args: list[str],
    +        timeout_sec: float | None = None,
    +    ) -> ExecResult:
    +        """Run ``exec`` directly on the engine when the compose wrapper is noisy.
    +
    +        podman-compose 1.x prints its version banner, merged compose JSON, and
    +        trailing ``exit code:`` line to stdout/stderr on every invocation, which
    +        corrupts command output. Resolve the service container via the engine
    +        and run ``podman exec`` directly without a TTY.
    +        """
    +        deadline = (
    +            time.monotonic() + timeout_sec
    +            if timeout_sec is not None and timeout_sec > 0
    +            else None
    +        )
    +        container = await self._resolve_service_container(
    +            service,
    +            timeout_sec=timeout_sec,
    +        )

    <!-- devin-review-comment {"id": "BUG_pr-review-job-1d77bb84a69849fdacf97759bbe00296_0001", "file_path": "src/harbor/environments/docker/docker_unix.py", "start_line": 297, "end_line": 300, "side": "RIGHT", "based_on_repo_rules": false, "kind": "bug"} -->

    🔴 Podman startup misses sandbox containers

    With podman-compose 1.x and job-scoped Podman storage, _resolve_service_container searches Harbor’s default store. Compose startup uses the job’s store, so the readiness probe never finds the running container.

    <details>
    <summary>Learn more</summary>

    The job’s environment.env becomes persistent_env in create_environment_from_config. Compose startup gets those variables through the Compose subprocess launcher. Podman honors CONTAINERS_STORAGE_CONF when selecting container storage. The readiness probe calls exec, which now looks for the service with podman ps under Harbor’s original environment before launching podman exec with the Compose environment. The lookup therefore searches the wrong store and the trial fails its readiness check.

    Example: A rootless Podman job sets environment.env.CONTAINERS_STORAGE_CONF to an absolute configuration file with a different graphroot. Compose starts main in that store, but Harbor keeps polling its usual store until startup times out.

    Recommended fix: Use the same effective Podman environment for service lookup and command execution as for Compose startup. Add a readiness regression test that verifies the job’s storage configuration reaches both podman ps and podman exec.

    </details>

    <!-- devin-review-badge-begin -->
    <a href="https://app.devin.ai/review/harbor-framework/harbor/pull/3035" target="_blank"><picture><source media="(prefers-color-scheme: dark)" srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4" alt="Devin Review"></picture></a>
    <!-- devin-review-badge-end -->

    ---
    Was this helpful? React with 👍 or 👎 to provide feedback.

    devin-ai-integration[bot] devin-ai-integration[bot] commented on Nov 26, 2026 04:22 UTC
    Reviewer

    Devin Review found 1 new potential issue.

    3 flags not posted on this PR by your GitHub settings — view them in Devin Review. (Configure)

    <!-- devin-review-badge-begin -->
    <a href="https://app.devin.ai/review/harbor-framework/harbor/pull/3035" target="_blank"><picture><source media="(prefers-color-scheme: dark)" srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4" alt="Devin Review"></picture></a>
    <!-- devin-review-badge-end -->

    iandvt iandvt commented on code on Nov 26, 2026 05:20 UTC
    Code Review
    src/harbor/environments/docker/docker_unix.py:1
    @@ -213,25 +221,102 @@ async def _resolve_service_container(self, service: str) -> str:
                     "-a",
                     "--filter",
                     f"label=com.docker.compose.project={project}",
    +                "--filter",
    +                f"label=com.docker.compose.service={service}",
                     "--format",
    -                "{{.ID}}\t{{.Names}}",
    +                "{{.ID}}\t{{.Names}}\t{{.State}}",
                 ),
                 stdout=asyncio.subprocess.PIPE,
                 stderr=asyncio.subprocess.DEVNULL,
             )
    -        stdout, _ = await proc.communicate()
    -        suffixes = (f"_{service}_1", f"-{service}-1")
    +        try:
    +            if timeout_sec:
    +                stdout, _ = await asyncio.wait_for(
    +                    proc.communicate(), timeout=timeout_sec
    +                )
    +            else:
    +                stdout, _ = await proc.communicate()
    +        except asyncio.TimeoutError:
    +            await DockerEnvironment._terminate_process(proc)
    +            raise RuntimeError(f"Command timed out after {timeout_sec} seconds")
    +
    +        exact_names = (f"{project}_{service}_1", f"{project}-{service}-1")
    +        running_exact: str | None = None
    +        running_fallback: str | None = None
    +        stopped_exact: str | None = None
    +        stopped_fallback: str | None = None
             for line in stdout.decode(errors="replace").splitlines():
    -            cid, _, name = line.partition("\t")
    +            cid, _, remainder = line.partition("\t")
    +            name, _, state = remainder.partition("\t")
                 name = name.strip()
                 cid = cid.strip()
    -            if name.endswith(suffixes):
    -                return cid or name
    +            state = state.strip().lower()
    +            candidate = cid or name
    +            if not candidate:
    +                continue
    +            is_running = state == "running" or state == ""
    +            is_exact = name in exact_names
    +            if is_running and is_exact and running_exact is None:
    +                running_exact = candidate
    +            elif is_running and running_fallback is None:
    +                running_fallback = candidate
    +            elif not is_running and is_exact and stopped_exact is None:
    +                stopped_exact = candidate
    +            elif not is_running and stopped_fallback is None:
    +                stopped_fallback = candidate
    +        resolved = (
    +            running_exact or running_fallback or stopped_exact or stopped_fallback
    +        )
    +        if resolved is not None:
    +            return resolved
             raise RuntimeError(
                 f"Could not resolve container for compose service {service!r} "
                 f"in project {project!r}."
             )
     
    +    async def engine_exec(
    +        self,
    +        *,
    +        service: str,
    +        exec_options: list[str],
    +        command_args: list[str],
    +        timeout_sec: float | None = None,
    +    ) -> ExecResult:
    +        """Run ``exec`` directly on the engine when the compose wrapper is noisy.
    +
    +        podman-compose 1.x prints its version banner, merged compose JSON, and
    +        trailing ``exit code:`` line to stdout/stderr on every invocation, which
    +        corrupts command output. Resolve the service container via the engine
    +        and run ``podman exec`` directly without a TTY.
    +        """
    +        deadline = (
    +            time.monotonic() + timeout_sec
    +            if timeout_sec is not None and timeout_sec > 0
    +            else None
    +        )
    +        container = await self._resolve_service_container(
    +            service,
    +            timeout_sec=timeout_sec,
    +        )
    devin-ai-integration[bot] devin-ai-integration[bot] commented on code on Nov 26, 2026 05:20 UTC
    Code Review
    src/harbor/environments/docker/docker_unix.py:1
    @@ -213,25 +221,102 @@ async def _resolve_service_container(self, service: str) -> str:
                     "-a",
                     "--filter",
                     f"label=com.docker.compose.project={project}",
    +                "--filter",
    +                f"label=com.docker.compose.service={service}",
                     "--format",
    -                "{{.ID}}\t{{.Names}}",
    +                "{{.ID}}\t{{.Names}}\t{{.State}}",
                 ),
                 stdout=asyncio.subprocess.PIPE,
                 stderr=asyncio.subprocess.DEVNULL,
             )
    -        stdout, _ = await proc.communicate()
    -        suffixes = (f"_{service}_1", f"-{service}-1")
    +        try:
    +            if timeout_sec:
    +                stdout, _ = await asyncio.wait_for(
    +                    proc.communicate(), timeout=timeout_sec
    +                )
    +            else:
    +                stdout, _ = await proc.communicate()
    +        except asyncio.TimeoutError:
    +            await DockerEnvironment._terminate_process(proc)
    +            raise RuntimeError(f"Command timed out after {timeout_sec} seconds")
    +
    +        exact_names = (f"{project}_{service}_1", f"{project}-{service}-1")
    +        running_exact: str | None = None
    +        running_fallback: str | None = None
    +        stopped_exact: str | None = None
    +        stopped_fallback: str | None = None
             for line in stdout.decode(errors="replace").splitlines():
    -            cid, _, name = line.partition("\t")
    +            cid, _, remainder = line.partition("\t")
    +            name, _, state = remainder.partition("\t")
                 name = name.strip()
                 cid = cid.strip()
    -            if name.endswith(suffixes):
    -                return cid or name
    +            state = state.strip().lower()
    +            candidate = cid or name
    +            if not candidate:
    +                continue
    +            is_running = state == "running" or state == ""
    +            is_exact = name in exact_names
    +            if is_running and is_exact and running_exact is None:
    +                running_exact = candidate
    +            elif is_running and running_fallback is None:
    +                running_fallback = candidate
    +            elif not is_running and is_exact and stopped_exact is None:
    +                stopped_exact = candidate
    +            elif not is_running and stopped_fallback is None:
    +                stopped_fallback = candidate
    +        resolved = (
    +            running_exact or running_fallback or stopped_exact or stopped_fallback
    +        )
    +        if resolved is not None:
    +            return resolved
             raise RuntimeError(
                 f"Could not resolve container for compose service {service!r} "
                 f"in project {project!r}."
             )
     
    +    async def engine_exec(
    +        self,
    +        *,
    +        service: str,
    +        exec_options: list[str],
    +        command_args: list[str],
    +        timeout_sec: float | None = None,
    +    ) -> ExecResult:
    +        """Run ``exec`` directly on the engine when the compose wrapper is noisy.
    +
    +        podman-compose 1.x prints its version banner, merged compose JSON, and
    +        trailing ``exit code:`` line to stdout/stderr on every invocation, which
    +        corrupts command output. Resolve the service container via the engine
    +        and run ``podman exec`` directly without a TTY.
    +        """
    +        deadline = (
    +            time.monotonic() + timeout_sec
    +            if timeout_sec is not None and timeout_sec > 0
    +            else None
    +        )
    +        container = await self._resolve_service_container(
    +            service,
    +            timeout_sec=timeout_sec,
    +        )

    ✅ Resolved: This finding concerned job-scoped Podman storage not reaching service discovery. The current changes add the same environment to both podman ps and podman cp, directly fixing the affected lookup path; readiness is also covered by the added environment propagation on ps and exec.

    SSchott SSchott commented on Nov 26, 2026 09:20 UTC
    Contributor

    Wanted to mention I just faced the --no-TTY issue, and I am patching this locally. Passing this PR would help.

    Reviewers
    Assignees
    iandvt iandvt
    Labels
    risk: low confidence: 82.2% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 75.7% (HIGH) · Higher = larger blast radius
    75.7%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 82.2% · Lower = rushed or shallow review
    82.2%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 13.5% · Safe to merge
    13.5%