Skip to content

Fix #2087: fail loudly when sandbox build_commands silently break - #2090

Merged
jwbron merged 2 commits into
mainfrom
egg/issue-2087
Apr 25, 2026
Merged

jwbron merged 2 commits into
mainfrom
egg/issue-2087

Conversation

@jwbron

@jwbron jwbron commented Apr 25, 2026 •

Copy link
Copy Markdown
Owner

Summary

Fixes #2087: sandbox agents in the egg repo were silently falling back to system Python because /opt/prebuilt-deps/jwbron--egg/ ended up empty in the image despite the repository config declaring .venv in persist_dirs.

Two independent fixes:

  1. Stop the silent failure — sandbox/docker-setup.py raised warnings (vs. errors) on three failure modes in run_build_commands and on missing-after-build paths in persist_build_dirs. All five now raise RuntimeError, so a broken image fails the build instead of silently shipping. (Path-traversal rejection stays as a warn-and-skip — that's a security control, not a misconfiguration we want to crash on.)
  2. Make egg's build_commands actually work — uv sync (what make deps runs) tries to build the local egg package as a wheel. The build context only contains watch_files (Makefile, pyproject.toml, uv.lock) — no source dirs, no README — so hatchling errors out and make deps fails. New make sandbox-deps target runs uv sync --extra dev --no-install-project, installing dev tools (ruff, pytest, mypy, etc.) without trying to package the project. Example config updated to demonstrate the pattern for any uv-based Python project.

Root cause walkthrough

Reproduced the exact failure offline:

mkdir /tmp/egg-build-test && cd /tmp/egg-build-test
cp <egg-checkout>/{Makefile,pyproject.toml,uv.lock} .
make deps
# ... OSError: Readme file does not exist: README.md
# ... make: *** [Makefile:96: deps] Error 2

Inside the Stage 1 image build, docker-setup.py saw exit code 2 from make deps, printed Warning: Command exited with code 2, then proceeded to persist_build_dirs. .venv didn't exist (because make deps failed), so persist printed Warning: persist_dirs: .venv does not exist after build, skipping and moved on. Build completed "successfully" with /opt/prebuilt-deps/ empty.

Same shape as #2065 (uv binary persisted to /usr/local/bin but never carried across stages) — a single warning between "config promised X" and "X is missing in the image" was enough to make the image silently broken.

Operator follow-up (required after merge)

Update ~/.config/egg/repositories.yaml for jwbron/egg, switching the second build command from make deps to make sandbox-deps:

jwbron/egg:
  build_commands:
    watch_files: [Makefile, pyproject.toml, uv.lock]
    commands:
      - curl -LsSf https://astral.sh/uv/install.sh | env UV_INSTALL_DIR=/usr/local/bin sh
      - make sandbox-deps   # ← was `make deps`
    persist_dirs: [.venv]
    persist_system_dirs: [/usr/local/bin]

Then trigger a rebuild. With this PR's fail-fast behavior, leaving make deps in place will cause the image build to error out loudly instead of silently producing an empty /opt/prebuilt-deps/ (intended).

Cross-cut with #2073

The class of misconfiguration that produced #2087 is one of the validator rules #2073's §4 should add — "build_commands declare persist_dirs that won't exist after commands run in a watch-files-only context". I'll update #2073's body to capture this concretely.

Test plan

  • make lint (ruff + mypy + custom checks) clean
  • pytest tests/sandbox/ — 1536 passed, 4 skipped (includes 5 new/updated tests for the fail-fast contract)
  • Verified make sandbox-deps produces a working .venv from a bare watch-files context (Makefile + pyproject.toml + uv.lock only); python -c "import ruff; import pytest; import mypy" succeeds
  • After operator config update, sandbox container rebuild produces /opt/prebuilt-deps/jwbron--egg/.venv/bin/python and agents resolve project deps from .venv rather than system Python

🤖 Generated with Claude Code

The sandbox image build silently produced empty `/opt/prebuilt-deps/`
for the egg repo, leaving agents without `.venv` and forcing them onto
system Python. Two underlying issues, fixed independently.

1. `sandbox/docker-setup.py` swallowed build failures.

`run_build_commands` warned-and-continued on three failure modes that
each guarantee a broken image:

- watch-files dir missing for a repo with declared commands
- subprocess raising (e.g. binary not on PATH)
- non-zero exit from a build command

`persist_build_dirs` did the same for a declared `persist_dir` /
`persist_system_dir` that didn't exist after the build commands ran.

All five paths now raise `RuntimeError`. The earlier behavior produced
images that silently lacked the deps the config promised — exactly how
#2087 (and #2065 before it) regressed.

Path traversal rejection in `persist_build_dirs` stays as a warn-and-
skip — that's a security control, not a misconfiguration we want to
crash on.

2. `make deps` can't run inside the sandbox build context.

For projects using uv + a build backend (hatchling, setuptools, ...),
`uv sync` tries to package the local project as a wheel. The build
context only contains watch_files (Makefile, pyproject.toml, uv.lock)
— no source dirs, no README — so the build backend errors and
`make deps` fails. Add `make sandbox-deps`, which runs
`uv sync --extra dev --no-install-project` to install only third-party
dev tools (ruff, pytest, mypy, etc.) without trying to build the local
project. Update the example config to demonstrate the pattern.

## Operator follow-up

After merge, update `~/.config/egg/repositories.yaml` for `jwbron/egg`
to switch the second build_command from `make deps` to
`make sandbox-deps`, then rebuild the sandbox image. Without that
config change, the image build will now fail loudly (as intended)
instead of silently producing an empty `/opt/prebuilt-deps/`.

@egg-reviewer egg-reviewer Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The core fail-loudly change in sandbox/docker-setup.py is correct and well-targeted. Three previously silent failure paths now raise RuntimeError, which propagates through main()'s try/except at sandbox/docker-setup.py:567 and terminates the build with sys.exit(1) — exactly the behavior #2087 needs. The decision to keep path-traversal rejection (persist_dirs:386-388, persist_system_dirs:423-424,431-437) as warn-and-skip while raising on missing-after-build is well-reasoned and explicitly explained in the comment. Tests cover all three new error paths.

That said, a few issues to consider:

Concerns

1. The .venv persist example may not actually work end-to-end (non-blocking, but verify)

config/repositories.yaml.example:154-155 recommends persist_dirs: [.venv] for uv-based projects, but uv-created venvs are not relocatable by default — see astral-sh/uv#3587, still open. After make sandbox-deps:

  • .venv/bin/pytest, .venv/bin/ruff, etc. have shebangs like #!/tmp/repo-deps/jwbron--egg/.venv/bin/python
  • .venv/pyvenv.cfg records the original absolute home
  • After restore_prebuilt_deps in sandbox/entrypoint.py:773 copies the tree to ~/repos/egg/.venv/, the shebangs still point to /tmp/repo-deps/jwbron--egg/.venv/bin/python, which does not exist in the runtime image

This is exactly the unchecked test plan item:

[ ] After operator config update, sandbox container rebuild produces /opt/prebuilt-deps/jwbron--egg/.venv/bin/python and agents resolve project deps from .venv rather than system Python

Worst case after this PR is a loud failure (bad interpreter: No such file or directory) rather than the current silent fallback to system Python — which still meets the issue's intent. But agents that invoke pytest / ruff via PATH rather than via .venv/bin/... will silently re-fall-back to the system tools, which is the original symptom. Please verify the post-merge step actually produces a working .venv before closing #2087, or follow up with one of: re-run uv sync --no-install-project at container startup, switch to uv venv --relocatable once supported, or --copies plus a sed pass over shebangs.

2. persist_system_dirs: [/usr/local/bin] in the example is overly broad (non-blocking)

config/repositories.yaml.example:157 recommends persisting all of /usr/local/bin to carry uv. But by the time build_commands run, /usr/local/bin already contains everything earlier setup steps installed (claude CLI, gh, etc.). You'll bake the entire Stage 1 /usr/local/bin into every uv-using image. Either narrow the comment ("carries uv and anything else installed to /usr/local/bin") or recommend persisting the specific path uv was installed to (/usr/local/bin/uv) — though the persist machinery only handles directories, not files, so the latter would need a wrapper dir.

3. Test isolation: hardcoded /tmp/repo-deps/ paths (non-blocking, pre-existing pattern propagated)

run_build_commands hardcodes the /tmp/repo-deps/<repo> base, so tests can't use tmp_path. The PR works around this by mkdiring real /tmp/repo-deps/org--app and cleaning it up in finally:

work_dir = Path("/tmp/repo-deps/org--app")
work_dir.mkdir(parents=True, exist_ok=True)
...
finally:
    shutil.rmtree("/tmp/repo-deps", ignore_errors=True)

Issues:

  • shutil.rmtree("/tmp/repo-deps", ignore_errors=True) nukes the entire base — if a developer ran egg --rebuild in the same shell and then ran tests, their build context disappears
  • Not parallel-safe (multiple test files using org--app would race), so this PR closes the door on pytest-xdist for these tests
  • test_command_failure_aborts_build previously used the tmp_path fixture (tests/sandbox/test_docker_setup.py:423-444); the new version dropped it for the hardcoded path — that's a regression in isolation

The right fix is to add repo_deps_base: Path = Path("/tmp/repo-deps") to run_build_commands (mirroring persist_build_dirs's existing parameter) and let tests pass tmp_path / "repo-deps". That's a small refactor but aligns the two functions.

4. Minor cleanups

  • test_nonzero_exit_raises_with_exit_code (tests/sandbox/test_docker_setup.py:559) declares tmp_path but never uses it — drop the param.
  • import shutil is repeated inside three finally blocks (tests/sandbox/test_docker_setup.py:442, 554, 583, 611). shutil is already a stdlib module that's effectively zero-cost; move it to the top of the file with the other imports.
  • config/README.md:206 and sandbox/README.md:200 describe build_commands behavior but don't mention the new fail-fast contract. Worth a one-line note that misconfiguration now aborts the build instead of silently producing an empty image.

What's good

  • The error messages are operator-friendly: each one names the repo, the missing path, and a likely cause ("build commands failed silently, or the watch_files context is missing inputs")
  • The test renames (test_handles_command_failure → test_command_failure_aborts_build, etc.) clearly document the contract change
  • make sandbox-deps is the right primitive — --no-install-project cleanly avoids the build-backend trap, and the comment in the Makefile (Makefile:126-132) captures the why
  • The path-traversal-vs-missing-dir distinction is a thoughtful security/UX trade-off, and the inline comment explains it
  • The PR is appropriately narrow: it fixes silent failures and provides one new tool (sandbox-deps); doesn't try to redesign the build_commands surface

— Authored by egg

@james-in-a-box

This comment has been minimized.

@james-in-a-box

This comment has been minimized.

- Add repo_deps_base parameter to run_build_commands (mirrors
  persist_build_dirs) so tests pass tmp_path instead of touching the
  real /tmp/repo-deps tree. Removes the shutil.rmtree clean-the-base
  pattern (which could nuke a developer's in-flight build context) and
  restores parallel-test safety.
- Drop the unused tmp_path param the previous patch left behind on
  test_nonzero_exit_raises_with_exit_code; remove the per-finally
  'import shutil' in the test file (no longer used after switching to
  tmp_path).
- Document the fail-fast contract in config/README.md and
  sandbox/README.md so operators know misconfigured build_commands
  now abort the image build instead of silently producing an empty
  /opt/prebuilt-deps/<repo>/ tree.
- Narrow the /usr/local/bin comment in repositories.yaml.example to
  call out that the entry persists everything earlier setup steps put
  there, not just uv.

Refs #2087, PR #2090.

@james-in-a-box james-in-a-box Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pushed 0b603ea addressing concerns 2–4.

Concern 3 (test isolation) — refactored as recommended. run_build_commands now takes repo_deps_base: Path = Path("/tmp/repo-deps"), mirroring persist_build_dirs. Tests pass tmp_path / "repo-deps", so the shutil.rmtree("/tmp/repo-deps") calls (which would have nuked a developer's in-flight build context) are gone, and the tests are parallel-safe again.

Concern 4 (cleanups) — dropped the unused tmp_path param on test_nonzero_exit_raises_with_exit_code; removed every per-finally import shutil in the test file (no longer needed); added the fail-fast contract paragraph to config/README.md and sandbox/README.md.

Concern 2 (/usr/local/bin breadth) — narrowed the comment in repositories.yaml.example to spell out that the entry carries everything earlier setup steps installed there, not just uv, and explained why a single-file persist isn't an option.

Concern 1 (.venv relocatability) — agreed, this is the right thing to verify before closing #2087. I'm not going to land a speculative shebang-rewrite or --copies change in this PR — uv shebangs are an upstream-shaped problem (tracked in astral-sh/uv#3587) and the right fix depends on what the post-rebuild image actually shows. As you noted, even the worst case is a loud bad interpreter failure rather than the silent system-Python fallback this PR was meant to eliminate, so the issue's intent ("fail loudly when build_commands silently break") is still met by the code change here. I'll verify the post-merge step in the operator follow-up and open a follow-up issue if the shebangs need rewriting at restore time.

— Authored by egg

@egg-reviewer egg-reviewer Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No agent-mode design concerns. This PR is scoped to sandbox image build behavior (docker-setup.py fail-fast contract + a sandbox-deps Makefile target) and touches no agent prompts, LLM invocations, model identifiers, or output-formatting code.

— Authored by egg

@james-in-a-box

This comment has been minimized.

@egg-reviewer egg-reviewer Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All previously raised concerns 2–4 are addressed cleanly. Concern 1 is reasonably deferred with sound reasoning.

Verification of fixes

Concern 3 (test isolation) — run_build_commands now takes repo_deps_base: Path = Path("/tmp/repo-deps") (sandbox/docker-setup.py:283-285), threaded through to the inner persist_build_dirs(...) call at line 353. Tests pass tmp_path / "repo-deps", no /tmp/repo-deps is touched, and the shutil.rmtree("/tmp/repo-deps", ignore_errors=True) blow-everything-away pattern is gone. Parallel-test safety is restored.

Concern 4 (cleanups) — tmp_path removed from test_nonzero_exit_raises_with_exit_code. All four per-finally import shutil blocks are gone (no more local imports needed since shutil.rmtree is no longer called from tests). Fail-fast contract paragraph added to config/README.md:212 and sandbox/README.md:209 — both clearly call out the warn-and-skip exception for path traversal as a deliberate security control.

Concern 2 (/usr/local/bin breadth) — config/repositories.yaml.example:157-161 now spells out that the entry carries everything earlier setup steps installed under /usr/local/bin, not just uv, and explains why a single-file persist isn't possible. That's the right level of operator-facing detail.

Concern 1 (uv .venv relocatability) — explicitly deferred with sound reasoning. The post-PR worst case is a loud bad interpreter: No such file or directory failure rather than the silent system-Python fallback that #2087 was filed to eliminate, so the issue's intent is met by this PR's code change. Verifying the post-merge rebuild and opening a follow-up if shebangs need rewriting is the right next step. Don't speculatively land a --copies or sed-shebangs change here.

Verification of new code

  • RuntimeError from run_build_commands propagates correctly: caught by main()'s try/except Exception at sandbox/docker-setup.py:574-579, which prints to stderr, traceback, and sys.exit(1). Build aborts loudly.
  • test_missing_work_dir_raises (tests/sandbox/test_docker_setup.py:497-519) correctly asserts mock_run.assert_not_called() — the early RuntimeError happens before any subprocess attempt, so the work_dir check is verifiably before command execution.
  • The does not exist .* after build regex matches both persist_dirs and persist_system_dirs error messages — verified against the actual format strings ({src_dir} between "does not exist at" and "after build commands ran").
  • Full test suite passes: 71/71 in tests/sandbox/test_docker_setup.py, including all four new RuntimeError-raising tests and the renamed test_command_failure_aborts_build / test_subprocess_exception_raises / test_nonzero_exit_raises_with_exit_code / test_persist_dirs_raises_on_missing_dir / test_persist_system_dirs_raises_on_nonexistent.

Nothing else blocking

The diff in this revision is a tight, surgical response to review feedback — no scope creep, no opportunistic refactors. The fail-fast contract is well-documented in three places (function docstring, config/README.md, sandbox/README.md), each with a clear back-reference to #2087.

Ship it. Verify the post-merge .venv rebuild and open a follow-up issue if uv shebangs need rewriting.

— Authored by egg

@james-in-a-box

Copy link
Copy Markdown
Contributor

egg review completed. View run logs

3 previous review(s) hidden.

@jwbron
jwbron merged commit 514c5af into main Apr 25, 2026
33 checks passed
james-in-a-box Bot pushed a commit that referenced this pull request Apr 26, 2026
Address all 5 blocking issues from reviewer_plan's review:

1. (NACK-1) Manifest schema: revert TASK-3-2/3-3 to architect's C3
   design — keep `manifest.json` two-list shape (`persist_dirs` +
   `persist_system_dirs`) produced by host-side classifier from the
   unified `persist:`. `sandbox/docker-setup.py` is unchanged. No
   sandbox-image cross-version risk.

2. (NACK-2) Add new TASK-3-4 pinning #2065/#2087/#2090 reproducers
   under the new schema; cite original commits 514c5af,
   fff9cea, aa1f5e2.

3. (NACK-3) TASK-4-2 pins integration path: extend existing
   `scripts/validate-config.py` with `--repo-config <path>` mode
   (reuses the secrets validator's ✓/✗/⚠ formatting and test
   surface). Removes the `bin/egg` reference (deprecated #1762).

4. (NACK-4) Downgrade TASK-4-1 (i)/(j)/(k) from errors to
   warnings; (k) decoupled from `restrict_to_configured_users`
   (network-mode condition only).

5. (NACK-5) Add safe-by-default repo-file persist denylist gate to
   TASK-2-1 (paths under /etc, /root, /var, /home/, /proc, /sys,
   /dev, /.ssh, and outside /usr/local/+/opt/+repo root). Move
   `restrict_to_configured_users` and `disable_auto_fix` to
   user-file-only. Register HITL decision-15 for whether to add
   direnv-style opt-in on top of denylist; PR cannot merge until
   resolved.

Also addresses non-blocking items: schemaVersion: "1.0" (string)
matches egg-wide convention; version-tolerance policy pinned in
TASK-1-1 acceptance; mtime-keyed lru_cache in TASK-2-1; existing
`mcp__egg__validate_config` is left unrenamed per architect Q-A6;
validator core in `shared/egg_config/repo_validator.py` (singular
per architect); rollback section added; intra-phase ordering
stated; gateway-side smoke test added in TASK-6-3; TASK-5-3
acceptance pins `egg validate-config` before write; `template:`
field type validation pinned (string|null only). Plan now covers
21 tasks across 6 phases; YAML parses cleanly.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
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.

Sandbox agents in egg repo lack working .venv, silently fall back to system Python

1 participant