Skip to content
Merged
10 changes: 10 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -391,8 +391,18 @@ k3s-secrets: ## Create gateway secrets from ~/.config/egg/

deploy: k3s-secrets ## Deploy egg to k3s
@echo "Deploying to k3s with tag $(EGG_IMAGE_TAG)..."
@command -v envsubst >/dev/null 2>&1 || { \
echo "ERROR: envsubst not found. Install GNU gettext: 'dnf install gettext' or 'brew install gettext'." >&2; \
exit 1; \
}
export KUBECONFIG=$${KUBECONFIG:-/etc/rancher/k3s/k3s.yaml} && \
export EGG_HOST_HOME="$${EGG_HOST_HOME:-$$HOME}" && \
export EGG_HOST_REPO_MAP="$${EGG_HOST_REPO_MAP:-$$(scripts/build-host-repo-map.py)}" && \
echo " EGG_HOST_HOME=$$EGG_HOST_HOME" && \
echo " EGG_HOST_REPO_MAP=$$EGG_HOST_REPO_MAP" && \
kubectl kustomize k8s/overlays/local/ | \
envsubst '$$EGG_HOST_HOME $$EGG_HOST_REPO_MAP' | \
sed -E "s|^(\s*value: )(\{.*\})$$|\1'\2'|" | \
sed -e "s|egg-orchestrator:latest|egg-orchestrator:$(EGG_IMAGE_TAG)|g" \
-e "s|egg-gateway:latest|egg-gateway:$(EGG_IMAGE_TAG)|g" \
-e "s|egg-sandbox:latest|egg-sandbox:$(EGG_IMAGE_TAG)|g" | \
Expand Down
2 changes: 1 addition & 1 deletion config/repo_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -411,7 +411,7 @@ def is_checkpoint_repo(owner: str, repo: str) -> bool:
"""Check if a repository is configured as a checkpoint destination.

Args:
owner: Repository owner (e.g. "jwbron")
owner: Repository owner (e.g. "my-org")
repo: Repository name (e.g. "egg-checkpoints")

Returns:
Expand Down
4 changes: 2 additions & 2 deletions docs/architecture/orchestrator.md
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,7 @@ During the `implement` phase, certain `.egg-state/` subdirectories are mounted r

The orchestrator calls `ensure_egg_state_dirs()` before spawning containers to create the required directories (bind mounts require existing source paths) and place `.egg-readonly` marker files explaining the restriction and current phase. Reviewer agents do not receive the `.egg-readonly` marker in the `reviews/` directory. Then `phase_readonly_mounts()` generates the readonly `MountSpec` entries, which are added alongside the existing `.git` shadow mounts. Only directories that exist on the host are mounted (missing directories are skipped). See `shared/egg_container/__init__.py` and `orchestrator/container_spawner.py`.

**Host path translation:** The gateway returns worktree paths relative to the host (e.g., `/home/jwies/.egg-worktrees/...`), but the orchestrator pod only sees these via `/home/egg/...` hostPath mounts. The spawner uses the `HOST_HOME` env var to translate host paths to orchestrator-accessible local paths for `is_dir()` checks and `ensure_egg_state_dirs()`. hostPath mount sources still use the original host paths unchanged.
**Host path translation:** The gateway returns worktree paths relative to the host (e.g., `/home/user/.egg-worktrees/...`), but the orchestrator pod only sees these via `/home/egg/...` hostPath mounts. The spawner uses the `HOST_HOME` env var to translate host paths to orchestrator-accessible local paths for `is_dir()` checks and `ensure_egg_state_dirs()`. hostPath mount sources still use the original host paths unchanged.

**Worktree state synchronization:** The orchestrator maintains bidirectional synchronization between local worktree branches and their remote counterparts:

Expand Down Expand Up @@ -559,7 +559,7 @@ if is_orchestrator_mode():
| `EGG_AGENT_ROLE` | Agent role for multi-agent mode | None |
| `EGG_BRANCH` | Target branch for the agent's worktree | `egg/{pipeline_id}/work` |
| `EGG_PRIVATE_MODE` | Private network mode (set by host wrapper, detected by `egg-sdlc`) | None |
| `HOST_HOME` | Host machine's home directory (e.g., `/home/jwies`); used to translate host worktree paths to orchestrator-accessible paths | None |
| `HOST_HOME` | Host machine's home directory (e.g., `/home/user`); used to translate host worktree paths to orchestrator-accessible paths | None |

### Constants

Expand Down
75 changes: 64 additions & 11 deletions gateway/gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -340,7 +340,7 @@ def _is_checkpoint_repo_for_request(owner: str, repo: str) -> bool:
but the orchestrator passed ``EGG_CHECKPOINT_REPO``).

Args:
owner: Repository owner (e.g. "jwbron")
owner: Repository owner (e.g. "my-org")
repo: Repository name (e.g. "checkpoints")

Returns:
Expand Down Expand Up @@ -416,32 +416,85 @@ def handle_unhandled_exception(e: Exception) -> tuple[Response, int]:
DEFAULT_THREADS = int(os.environ.get("GATEWAY_THREADS", "32"))
HEALTH_CHECK_PORT = int(os.environ.get("GATEWAY_HEALTH_PORT", "9851"))

# Host home directory for path translation
# Host home directory for path translation (explicit override).
# The gateway container uses /home/egg internally, but needs to return
# host paths to the egg launcher for Docker mount sources
# host paths to the orchestrator because those paths become the
# ``hostPath.path`` source of agent-pod mounts — if the gateway returns
# its in-pod path and the host layout doesn't match, kubelet
# ``DirectoryOrCreate``s an empty root-owned dir and the agent lands in
# an unwritable worktree (#1986).
#
# Normally we discover the host path directly from /proc/self/mountinfo
# (see ``translate_to_host_path``) so no env-var configuration is
# required. ``HOST_HOME`` remains as an explicit escape hatch for test
# environments and unusual setups where mountinfo doesn't reflect the
# real mapping.
HOST_HOME = os.environ.get("HOST_HOME", "")
CONTAINER_HOME = "/home/egg"


def _load_mount_mapping() -> list[tuple[str, str]]:
"""Read /proc/self/mountinfo and return a list of (mount_point, host_root) tuples.

For every mount visible to this process, ``mount_point`` is the path
in this process's mount namespace and ``host_root`` is the path the
kernel recorded as the mount root — for kubelet-managed ``hostPath``
volumes that's the actual host path. The list includes *all* mount
types (not just bind mounts); longest-prefix matching in
``translate_to_host_path`` ensures the most specific entry wins.

Note: ``host_root`` (``fields[3]``, the mountinfo *root* field) is
the path relative to the filesystem's root. On single-partition
systems this equals the absolute host path; on multi-partition setups
it may be relative to the partition root. The ``HOST_HOME`` env var
is the escape hatch for those configurations.

Note: mountinfo uses octal escapes for special characters in paths
(``\\040`` for space, ``\\011`` for tab, ``\\134`` for backslash).
We don't decode them — unlikely to matter for ``/home/...`` paths
but worth knowing if paths ever contain whitespace.
"""
entries: list[tuple[str, str]] = []
try:
with open("/proc/self/mountinfo") as fh:
for line in fh:
# Format: mount_id parent_id major:minor root mount_point ...
fields = line.split()
if len(fields) < 5:
continue
entries.append((fields[4], fields[3]))
except OSError:
return []
entries.sort(key=lambda p: len(p[0]), reverse=True)
return entries


_MOUNT_MAPPING: list[tuple[str, str]] = _load_mount_mapping()


def translate_to_host_path(container_path: str) -> str:
"""
Translate a container path to the corresponding host path.

The gateway runs with paths like /home/egg/.egg-worktrees/...
but the egg launcher needs host paths like /home/user/.egg-worktrees/...
for Docker mount sources.
Tries in order:
1. /proc/self/mountinfo — find the longest mount_point that is a
prefix of ``container_path`` and substitute with its host root.
This works for any hostPath volume without configuration.
2. ``HOST_HOME`` env var — explicit override, used when mountinfo is
not available or needs to be bypassed (tests, unusual setups).

Args:
container_path: Path inside the gateway container

Returns:
The corresponding host path, or original path if translation not possible
The corresponding host path, or the original path if no
translation is possible.
"""
if not HOST_HOME:
# No host home configured - return as-is (may cause mount issues)
return container_path
for mount_point, host_root in _MOUNT_MAPPING:
if container_path == mount_point or container_path.startswith(mount_point + "/"):
return host_root + container_path[len(mount_point) :]

if container_path.startswith(CONTAINER_HOME):
if HOST_HOME and container_path.startswith(CONTAINER_HOME):
return container_path.replace(CONTAINER_HOME, HOST_HOME, 1)

return container_path
Expand Down
165 changes: 165 additions & 0 deletions gateway/tests/test_translate_host_path.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
"""Tests for ``gateway.translate_to_host_path``.

The gateway returns host paths to the orchestrator to use as
``hostPath.path`` sources for agent-pod mounts. If the translation is
wrong, kubelet ``DirectoryOrCreate``s an empty root-owned dir and the
agent lands in an unwritable worktree (#1986). These tests cover the
two translation strategies: mountinfo-based auto-discovery (primary)
and the ``HOST_HOME`` env var (fallback).
"""

from __future__ import annotations

import sys
from pathlib import Path
from unittest.mock import patch

import pytest

sys.path.insert(0, str(Path(__file__).parent.parent))

import gateway as gateway_module # noqa: E402


@pytest.fixture
def override_bind_mounts():
"""Replace the module-level mount table with a test fixture."""
original = gateway_module._MOUNT_MAPPING

def _set(entries: list[tuple[str, str]]) -> None:
# Sort longest-first to match _load_mount_mapping's contract.
gateway_module._MOUNT_MAPPING = sorted(entries, key=lambda p: len(p[0]), reverse=True)

yield _set
gateway_module._MOUNT_MAPPING = original


@pytest.fixture
def override_host_home():
"""Temporarily set HOST_HOME at module scope."""
original = gateway_module.HOST_HOME

def _set(value: str) -> None:
gateway_module.HOST_HOME = value

yield _set
gateway_module.HOST_HOME = original


class TestMountinfoTranslation:
"""Auto-discovered translation via /proc/self/mountinfo."""

def test_longest_prefix_wins(self, override_bind_mounts, override_host_home):
# A nested hostPath mount must beat its parent emptyDir mount.
override_bind_mounts(
[
("/home/egg", "/var/lib/kubelet/pods/abc/emptydir/home"),
("/home/egg/.egg-worktrees", "/home/user/.egg-worktrees"),
]
)
override_host_home("")

result = gateway_module.translate_to_host_path("/home/egg/.egg-worktrees/pipeline-1/repo")

assert result == "/home/user/.egg-worktrees/pipeline-1/repo"

def test_exact_mount_point_match(self, override_bind_mounts, override_host_home):
override_bind_mounts([("/home/egg/.egg-worktrees", "/home/user/.egg-worktrees")])
override_host_home("")

assert (
gateway_module.translate_to_host_path("/home/egg/.egg-worktrees")
== "/home/user/.egg-worktrees"
)

def test_sibling_paths_not_conflated(self, override_bind_mounts, override_host_home):
# /home/egg-other must not match the /home/egg mount_point.
override_bind_mounts([("/home/egg", "/host/egg")])
override_host_home("")

assert gateway_module.translate_to_host_path("/home/egg-other/x") == "/home/egg-other/x"

def test_no_mountinfo_match_falls_through(self, override_bind_mounts, override_host_home):
override_bind_mounts([("/home/egg", "/host/egg")])
override_host_home("")

assert gateway_module.translate_to_host_path("/other/path") == "/other/path"


class TestHostHomeFallback:
"""Explicit HOST_HOME env var, used when mountinfo lookup misses."""

def test_host_home_used_when_mountinfo_empty(self, override_bind_mounts, override_host_home):
override_bind_mounts([])
override_host_home("/home/user")

assert (
gateway_module.translate_to_host_path("/home/egg/.egg-worktrees/x")
== "/home/user/.egg-worktrees/x"
)

def test_mountinfo_takes_precedence_over_host_home(
self, override_bind_mounts, override_host_home
):
# mountinfo disagrees with HOST_HOME — trust mountinfo because it
# reflects what the kernel actually set up.
override_bind_mounts([("/home/egg/.egg-worktrees", "/real/host/path")])
override_host_home("/stale/home")

assert (
gateway_module.translate_to_host_path("/home/egg/.egg-worktrees/x")
== "/real/host/path/x"
)

def test_no_translation_when_both_unavailable(self, override_bind_mounts, override_host_home):
override_bind_mounts([])
override_host_home("")

assert (
gateway_module.translate_to_host_path("/home/egg/.egg-worktrees/x")
== "/home/egg/.egg-worktrees/x"
)

def test_host_home_ignored_for_non_container_path(
self, override_bind_mounts, override_host_home
):
override_bind_mounts([])
override_host_home("/home/user")

assert gateway_module.translate_to_host_path("/other/path") == "/other/path"


class TestLoadMountMapping:
"""``_load_mount_mapping`` parses /proc/self/mountinfo."""

def test_parses_mount_point_and_root(self, tmp_path):
mountinfo = tmp_path / "mountinfo"
mountinfo.write_text("1 0 0:1 /host/root /pod/mount rw,relatime - tmpfs tmpfs rw\n")
with patch("gateway.open", lambda *a, **kw: mountinfo.open()):
result = gateway_module._load_mount_mapping()
assert ("/pod/mount", "/host/root") in result

def test_sorts_longest_first(self, tmp_path):
mountinfo = tmp_path / "mountinfo"
mountinfo.write_text(
"1 0 0:1 /r1 /a rw,relatime - tmpfs tmpfs rw\n"
"2 0 0:2 /r2 /a/b rw,relatime - tmpfs tmpfs rw\n"
)
with patch("gateway.open", lambda *a, **kw: mountinfo.open()):
result = gateway_module._load_mount_mapping()
assert result[0] == ("/a/b", "/r2")
assert result[1] == ("/a", "/r1")

def test_skips_malformed_lines(self, tmp_path):
mountinfo = tmp_path / "mountinfo"
mountinfo.write_text("garbage\n1 0 0:1 /r /m rw,relatime - tmpfs tmpfs rw\n")
with patch("gateway.open", lambda *a, **kw: mountinfo.open()):
result = gateway_module._load_mount_mapping()
assert result == [("/m", "/r")]

def test_returns_empty_when_mountinfo_missing(self):
def _raise(*_a, **_kw):
raise OSError(2, "No such file or directory")

with patch("gateway.open", _raise):
assert gateway_module._load_mount_mapping() == []
12 changes: 7 additions & 5 deletions k8s/overlays/local/patches/gateway-volumes.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@
# worktrees. These append to the base's volumes/volumeMounts by name
# (no conflicts, so strategic merge does the right thing here).
#
# Paths are hardcoded to /home/jwies/ because kustomize has no native
# env var substitution. For a different host user, edit these paths or
# use envsubst before `kubectl apply`.
# ``${EGG_HOST_HOME}`` is expanded by ``envsubst`` in the Makefile's
# ``deploy`` target — defaults to ``$HOME`` on the machine running the
# deploy, so these hostPaths resolve to the current user's home
# without per-developer edits. Override via
# ``make deploy EGG_HOST_HOME=/data/egg`` for a different host layout.
apiVersion: apps/v1
kind: Deployment
metadata:
Expand All @@ -25,9 +27,9 @@ spec:
volumes:
- name: repos
hostPath:
path: /home/jwies/repos
path: ${EGG_HOST_HOME}/repos
type: Directory
- name: worktrees
hostPath:
path: /home/jwies/.egg-worktrees
path: ${EGG_HOST_HOME}/.egg-worktrees
type: DirectoryOrCreate
23 changes: 13 additions & 10 deletions k8s/overlays/local/patches/orchestrator-volumes.yaml
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
# Strategic merge patch: add local-dev-only host mounts for the orchestrator.
# Appends to base volumes/volumeMounts by name.
#
# ⚠ DEVELOPER-SPECIFIC PATHS — edit before use ⚠
# Every `/home/jwies/...` below and the owner/repo → host path map in
# EGG_HOST_REPO_MAP point at this PR author's layout. Kustomize has no
# env-var substitution, so other contributors must replace these with
# their own $HOME and repo paths before `make deploy`. Tracked as a
# follow-up in #1760: make this portable (envsubst wrapper, Helm chart,
# or render from ~/.config/egg/repositories.yaml).
# ``${EGG_HOST_HOME}`` and ``${EGG_HOST_REPO_MAP}`` are expanded by
# ``envsubst`` in the Makefile's ``deploy`` target:
# - ``EGG_HOST_HOME`` defaults to ``$HOME``.
# - ``EGG_HOST_REPO_MAP`` is a JSON map ``owner/repo → host_path``
# auto-derived by ``scripts/build-host-repo-map.py`` from
# ``~/.config/egg/repositories.yaml`` (``local_repos.paths`` with
# the ``origin`` remote URL parsed to recover ``owner/repo``).
# Override either at deploy time:
# make deploy EGG_HOST_HOME=/data/egg
# EGG_HOST_REPO_MAP='{"owner/repo":"/path"}' make deploy
apiVersion: apps/v1
kind: Deployment
metadata:
Expand Down Expand Up @@ -35,7 +38,7 @@ spec:
# mounts when spawning sandbox Jobs. Local-dev only; production
# k8s would use a PV-backed repo store instead.
- name: EGG_HOST_REPO_MAP
value: '{"jwbron/testing":"/home/jwies/khan/testing","jwbron/egg":"/home/jwies/khan/egg","Khan/webapp":"/home/jwies/khan/webapp","Khan/internal-services":"/home/jwies/khan/internal-services","Khan/jenkins-jobs":"/home/jwies/khan/jenkins-jobs","Khan/buildmaster2":"/home/jwies/khan/buildmaster2"}'
value: '${EGG_HOST_REPO_MAP}'
volumeMounts:
# repos mount is read-write because the orchestrator creates
# per-pipeline worktrees inside each repo's .git/worktrees/.
Expand All @@ -49,11 +52,11 @@ spec:
volumes:
- name: repos
hostPath:
path: /home/jwies/repos
path: ${EGG_HOST_HOME}/repos
type: Directory
- name: worktrees
hostPath:
path: /home/jwies/.egg-worktrees
path: ${EGG_HOST_HOME}/.egg-worktrees
type: DirectoryOrCreate
- name: secrets
secret:
Expand Down
2 changes: 1 addition & 1 deletion orchestrator/kubernetes_spawner.py
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,7 @@ def _host_to_local_volumes(repo_volumes: dict[str, str]) -> dict[str, str]:
"""Translate host paths to orchestrator-local paths for filesystem ops.

The gateway returns worktree paths relative to the Docker host
(e.g. ``/home/jwies/.egg-worktrees/...``), but the orchestrator
(e.g. ``/home/user/.egg-worktrees/...``), but the orchestrator
container only sees these via a volume mount at ``/home/egg/...``.
Uses the ``HOST_HOME`` env var to perform the translation.
"""
Expand Down
Loading
Loading