Skip to content

fix(harbor): preserve startup context with job overlays - #5186

Merged
yuhezhang-ai merged 11 commits into
mainfrom
yuhez/harbor-overlay-startup
Nov 5, 2026
Merged

yuhezhang-ai merged 11 commits into
mainfrom
yuhez/harbor-overlay-startup

Conversation

@yuhezhang-ai

@yuhezhang-ai yuhezhang-ai commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do?

Adding job-level Compose services to a Dockerfile-based Harbor task could change the account and directory used by its startup commands. For example, a Dockerfile that creates app and sets WORKDIR /home/app/work could start as root in the base image's /srv; a separate [agent].user could also become the startup account.

For Dockerfile tasks without their own Compose file, whose image configuration the loader has resolved, preserve startup context when job services are attached:

  • Finish Dockerfile setup before applying the startup directory and inherited image account. Preserve that directory across sandbox reconnection; run volume copy-up from / so setup can create the service directory later.
  • Install and validate the image account only when an entrypoint, command, enabled image healthcheck, inherited post_start hook, or task healthcheck uses it. Reject unsupported inherited user/group pairs before provisioning services or running setup. Explicit service and hook accounts retain precedence; the later agent keeps its configured account.
  • Run the seed's task healthcheck as the resolved explicit main.user when provided, including integer conversion for decimal strings. Null/empty values retain the image fallback.
  • Preserve integer UIDs for unnamed numeric users on single-sandbox and composed paths. Document provider limits: Docker and OpenSandbox plain exec support unnamed integer UIDs; other providers and OpenSandbox PTY/bash sessions require a named user. User/group pairs remain Docker-only.
  • Document explicit startup overrides and the existing ordering in which named/external volumes are mounted before Dockerfile RUN setup.

This addresses the follow-up from #4863, explicitly deferred in its approval. A separate issue is unnecessary because that thread identifies the defect. #4863 is merged; this PR targets main independently of the remaining Harbor stack.

The task-healthcheck user override also applies to tasks with their own environment/docker-compose.yaml, without a job-level overlay. Their [environment.healthcheck] runs as the resolved explicit services.main.user, including integer conversion for decimal strings; null/empty values retain the image fallback.

The session-routing CI failure also exposed a pre-existing test assumption that a TCP listener distributes sessions across workers. Both the worker-exit and state-preservation tests now seed each worker through its private socket and verify through public TCP. Real worker termination, replacement, lost-session 410 errors, and surviving-session rewards remain checked. Production routing behavior is unchanged.

Validation

Validated source: 5ac77dee4a5965fcb7ccba0893d88e44f287bfd7, with main 31fe314d70a2b9800afc1779f3bd87ba25ab705e integrated. Python 3.13.14; checkout dependencies refreshed from the lockfile using uv 0.13.4 with dev and sandbox extras.

pytest environment_servers/harbor/tests \
  tests/unit_tests/sandbox/test_docker_compose.py \
  tests/unit_tests/sandbox/test_sandbox.py \
  tests/unit_tests/sandbox/test_sandbox_connect.py \
  tests/unit_tests/sandbox/test_compose_fields.py \
  tests/unit_tests/sandbox/test_compose_volumes.py \
  tests/unit_tests/data/tasks/harbor/test_harbor_compose_overlay.py \
  tests/unit_tests/test_public_api.py \
  -q --tb=short --durations=5 -o log_cli=false
NEMO_GYM_MULTIWORKER_E2E=1 pytest tests/e2e/session_routing \
  -q --tb=short --durations=5 -o log_cli=false
pre-commit run --all-files
(cd fern && npm run check)
git diff --check
  • 1,242 Harbor/sandbox/public-API tests passed; 2 opt-in OpenSandbox survival checks skipped. The volume-copy test combines setup/no-setup and default/explicit placement groups, covering all eight variants while retaining cleanup and external-volume assertions.
  • 5 routing tests passed; 8 optional stress tests skipped.
  • New own-Compose tests cover nobody and decimal string 1000 without a job overlay. Both fail under a scratch restriction of the override to job overlays and pass with the approved implementation. The fixture retains the actual resolved Compose document.
  • All-files pre-commit and diff checks passed. The private guardwords catalog was unavailable, so that catalog check skipped. Fern reported zero errors and one warning for unavailable authenticated missing-redirect checks.
  • Both follow-up commits have DCO sign-off. Full-suite CI applies because the PR changes shared sandbox code.
  • The follow-up adds tests and docs and resolves merge conflicts without introducing new runtime behavior. No fresh model rollout was run for it; prior live evidence is attributed below.

Real model and sandbox validation

Four episodes used the production Harbor HTTP server, Compose adapter, OpenSandbox provider, model-driven shell harness, and verifier on 961754cf0209e490731ba8819ae9b64c35038d12 (prior evidence, not fresh runs on the latest main integration):

Case Task healthcheck account Agent account Result
Pull-mode Dockerfile, inherited account nobody root reward 1, verifier exit 0
Dockerfile RUN setup, inherited account nobody root reward 1, verifier exit 0
Image nobody:nogroup, explicit service root root root reward 1, verifier exit 0
Image nobody:nogroup, explicit service string 12345 integer UID 12345 root reward 1, verifier exit 0

The task healthcheck used /tmp/agent-work; the image startup directory remained /tmp/startup-work. The audit checked saved model responses, accounts, directories, exact answer bytes, file ownership, verifier output, and Redis-companion connectivity. All nine known sandboxes, including preflight, were confirmed deleted through the provider API.

The model was Qwen2.5-0.5B-Instruct Q4_K_M, revision 9217f5db79a29953eb74d5343926648285ec7e67, served by llama.cpp b10936 on CPU. Model and provider responses were real. This is focused API-level functional evidence, not full CLI, production-scale, or performance validation. Live shared-volume mounting remains untested; local shell/provider tests cover copy-up, directory setup, data, and cleanup.

Earlier live evidence covered startup hooks on c35ab9a7e (4 episodes) and startup/agent account and directory parity on dd1420bdd (7 episodes). Those are prior results, not fresh runs on this head.

Compatibility and benchmark impact

No configuration migration. Explicit service/hook accounts retain precedence, and subsequent agent execution keeps its own account. Tasks relying on the incorrect startup context may behave differently. Unsupported inherited image user/group pairs used by this startup path are rejected before provisioning. Providers must support numeric users for unnamed UID execution. Benchmark impact has not been measured.

@yuhezhang-ai yuhezhang-ai added bug Something isn't working area:sandbox Sandbox providers, isolation, and sandbox runtime contracts labels Oct 28, 2026
@copy-pr-bot

copy-pr-bot Bot commented Oct 28, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@yuhezhang-ai
yuhezhang-ai marked this pull request as ready for review October 28, 2026 16:33
@yuhezhang-ai yuhezhang-ai added the needs-review PR is ready for code review and waiting on a reviewer label Oct 28, 2026
@yuhezhang-ai

Copy link
Copy Markdown
Contributor Author

/ok to test f9e32cc

@github-actions

github-actions Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

@svcnvidia-nemo-ci svcnvidia-nemo-ci 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.

SHIP WITH CARE — three RISK findings affecting startup-user precedence, numeric-user resolution, and named-volume initialization.

Completed the broad light review across all nine changed files and their directly affected setup, startup, reconnect, and cleanup paths. One delegated report was unavailable; I independently inspected its API, configuration-generation, documentation, and reconnect-test scope.

Static source review only. Tests and live-rollout results in the PR description were not independently executed. Suggested corrections below require author verification.


Inline comments (escaped v1):

  • environment_servers/harbor/sandboxes.py line 727: RISK — Honor an explicit service user before validating the image fallback

    Failure: On OpenSandbox, take a recorded root base image, Dockerfile FROM image\nUSER root:1234\n, [agent].user = "root", [verifier].user = "root", and a job overlay with services.main.user: root. No executed phase requests group 1234, but this new branch installs task.entrypoint_user anyway. _set_default_user rejects root:1234 with a 422 before the adapter applies the explicit root override. This introduces a false rejection of a supported overlay configuration; the explicit verifier user is important because otherwise the independent verifier-group precheck also rejects it.

    Correction: Could this condition exclude an effective explicit main user?

                    if image_startup and document["services"]["main"].get("user") in (None, ""):
    

    The image identity should be a fallback, not a prerequisite for an overriding Compose identity. The adapter already passes the explicit user to the command and healthcheck. Keep group validation for identities actually used by Dockerfile RUN steps and verification.

    Preservation / acceptance: Proposed regression: the configuration above, with image healthcheck true, must start command and healthcheck as root and hand subsequent agent execution root. Without the service override, the unsupported image group must still be rejected. Treat integer user: 0 as an override; null/empty must retain image-default installation and numeric resolution. Retain the existing operator override test: startup uses operator in /operator, while Dockerfile setup leaves /home/app/work owned by app. Source-reasoned suggestion; not executed.

  • environment_servers/harbor/sandboxes.py line 731: RISK — Preserve integer fallback for cached unnamed numeric users

    Failure: Use a root base image with no passwd entry for UID 12345, Dockerfile FROM image\nRUN true\nUSER 12345\nWORKDIR /tmp/work\n, [agent].user = "root", an image healthcheck of true, and an attached job service. The trailing WORKDIR makes _apply_overlay.effective_user cache names["12345"] = "12345". This new startup call consumes that cache, and _set_default_user mistakes it for a resolved account name. Startup receives string "12345", so OpenSandbox invokes su rather than its integer UID path. Bootstrap/command execution fails instead of running as UID 12345. Previously this image-user cache was not installed before group startup, and the later agent user in this example is root. The new numeric startup test has no RUN overlay and therefore misses the populated-cache case.

    Correction: Make the overlay cache use the same missing-entry representation as _user_name. At the assignment and return in overlay.py lines 163–164, use:

    user_names[uid] = name[-1] if name and name[-1] else ""
    return (user_names[uid] or uid) + (f":{group}" if group else "")

    Then _user_name returns None for the cached miss and _set_default_user selects integer 12345. Overlay chown still receives the raw UID, and overlay RUN still passes through _exec_user.

    Preservation / acceptance: Proposed regression: run this configuration through the real adapter with a fake provider that rejects numeric account-name strings but accepts integer UIDs; startup and image healthcheck must receive integer 12345, followed by root for agent execution. Retain named UID resolution to agent, including one lookup, and unnamed UID RUN behavior: bare UIDs are integers, Docker-only uid:gid remains a string with its group, and unsupported providers still reject groups. Keep the new no-RUN startup cases and explicit service-user precedence. Suggested helper correction is source-reasoned, not executed.

  • nemo_gym/sandbox/adapters/docker_compose.py line 597: RISK — Defer WORKDIR for named-volume copy-up sandboxes too

    Failure: Consider an image-only task with FROM base\nRUN useradd -m app\nUSER app\nWORKDIR /home/app/work\n, where the base lacks /home/app/work, and a job overlay adding main.volumes: [cache:/cache] with volumes: {cache: {}}. The changed producer now publishes the final WORKDIR for overlay tasks. However, _prepare_volumes runs before the setup-aware service creation loop, and this copy-up seed retains that directory. Its first seed.exec therefore receives the nonexistent final directory through AsyncSandbox's cwd default, failing under the strict-directory contract modeled by the existing OpenSandbox regression fixture. Main's setup never runs. Previously the synthesized overlay service omitted this final WORKDIR. Blast radius is setup-dependent tasks with a managed, copy-enabled main volume; the added Harbor tests use a volume-free main.

    Correction: In this seed_spec = replace(...), add:

    workdir=None if name in self.service_setup else self._plans[name]["spec"].workdir,

    The copy-up seed reads the unmodified image and must not require its post-setup directory. Keep applying the final directory to the actual service after setup. This suggested code is source-reasoned and needs verification before adoption.

    Preservation / acceptance: Proposed regression: extend the existing volume fake with the strict cwd check, a missing final directory, and a setup hook that creates it. Start must succeed; copy-up must run without the missing cwd, preserve the image's seed bytes, and main's command must then run in the final directory. Retain the changed setup/upload test's result "uploaded", the no-setup directory test's expected pwd, and volume copy/cleanup assertions: "image data" survives, external data is untouched, and every sandbox is closed. Preserve seed pull policies and caller options. Services without setup retain their existing directory behavior; external/nocopy volumes still skip copy-up, and explicit working-directory overrides still govern the actual service.

Review generated by codex. This was a full review. Request a full review with /review reset=true.

…startup

Signed-off-by: Yuhe Zhang <[email protected]>

# Conflicts:
#	environment_servers/harbor/tests/test_compose_overlay.py
@yuhezhang-ai

Copy link
Copy Markdown
Contributor Author

Addressed all three findings from this review in 8c01ad7. Also merged main and resolved the test conflict, preserving both startup and task-healthcheck assertions.

  1. Explicit Compose user: Explicit Compose users now take precedence without validating the unused image identity. Tests cover root, integer 0, and null/empty fallback behavior. The live sandbox case also passed.

  2. Unnamed numeric UID cache: Missing account names now remain distinguishable in the cache, so unnamed numeric users reach startup as integer UIDs. Regression tests and a live episode verified startup as UID 12345 followed by agent execution as root.

  3. Named-volume copy-up directory: Volume copy-up no longer uses a working directory that service setup has yet to create. Tests verify copied data, final startup directory, external-volume preservation, and cleanup. Live shared-volume mounting remains untested because the provided configuration has no shared-storage path.

Validation: the new regressions reproduced all three issues before the fixes (5 failures, 11 controls passing). After fixes, 583 tests passed, 2 skipped; all-files pre-commit passed; Fern reported zero errors. 5/5 real model/OpenSandbox episodes passed, with all 9 owned sandboxes confirmed deleted. The PR description records the exact checks and validation limits.

@yuhezhang-ai

Copy link
Copy Markdown
Contributor Author

/ok to test 8c01ad7

@adil-a adil-a 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.

Thanks, this closes the startup gap from #4863 cleanly for the Dockerfile cases. I reviewed it with code reading plus scratch reproductions against this branch and main. No blockers. One regression is worth fixing before merge (sandboxes.py:731), and the other inline notes are small fixes, test gaps or wording.

Pre-existing gaps the reproductions also turned up. None is caused by this PR, so these are possible follow-ups, not requests here:

  • On the group path, a WORKDIR that already exists in the base image (e.g. /srv) is chowned to the image USER. The single sandbox's overlay_workdir_command leaves an existing directory alone, as BuildKit does.
  • A built image whose record has no WorkingDir starts its entrypoint and image healthcheck in [environment].workdir in a group, but in / in a single sandbox.
  • In a group, main's entrypoint and image healthcheck start before /logs/{agent,verifier,artifacts} exist. _prepare_workdir runs after _create_compose, while the single sandbox prepares them first.
  • The adapter runs a CMD-SHELL image healthcheck with /bin/sh -c rather than the record's Shell, and resolve_compose drops StartInterval.

Comment thread environment_servers/harbor/sandboxes.py Resolved
Comment thread environment_servers/harbor/sandboxes.py Resolved
Comment thread environment_servers/harbor/overlay.py Resolved

@adil-a adil-a 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.

Re-reviewed 961754c and the merge from main. All five open items are addressed, and I've resolved the four threads. The session-routing e2e fix also checks out: both tests now seed round-robin through each worker's private socket, and verification still goes over public TCP. The merge's conflict resolutions look clean, and all 688 Harbor server tests pass at head. One new, non-blocking note is inline.

image_user = await self._image_user_name(sandbox, task, names)
# The task healthcheck uses main's container user, independently of the later agent.
image_user = None
if compose is not None and task.config.environment.healthcheck is not None:

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 task-healthcheck main.user override also changes own-Compose tasks with no overlay, and no test or doc covers that

compose is not None also holds for a task that ships environment/docker-compose.yaml with no job overlay, because _uses_compose is task.needs_compose or ... (sandboxes.py:390). So for such a task with services.main.user and an [environment.healthcheck], the seed check now runs as that user. On main it ran as the image user. My repro has an own-Compose task, no overlay, and a group that loads the resolved document:

  • user: nobody: root before this commit, 'nobody' now.
  • user: "1000": root before, int 1000 now.

This looks right to me. The adapter already runs main's command and its image healthcheck as that same user: (docker_compose.py:491-501, 875), and it is likely what Harbor's exec does when it passes no -u. But the PR description scopes the change to Dockerfile tasks without their own Compose file. The fern paragraph (harbor-tasks.mdx:557-562) covers only overlays, and README:92 says only that the check "is polled at seed". Nothing pins it either. When I gated the override on overlay_files(self.config.compose_overlay), all 688 harbor tests still passed. Every new test is overlay-only, and FakeCompose.document is hard-coded to an empty main (conftest.py:659).

Suggestion: keep the behavior and pin it. Add an own-Compose seed test with no overlay, where main.user is a name and a decimal string, that asserts the task check's exec user. Also add a line in the PR description and in the Compose-tasks docs (README:92) saying the task check runs as main's Compose user: when one is set.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Addressed in 5ac77de. The behavior is intentional for tasks with their own Compose file too. Added no-overlay seed tests for user: nobody and user: "1000", asserting that every task-healthcheck attempt receives nobody and integer 1000, respectively. The fixture now retains the resolved Compose document.

Both tests fail when the override is restricted to job overlays and pass with the current implementation. Updated the Harbor README, Fern docs, and PR description to state this scope. Local validation after integrating main: 1,242 tests passed (2 opt-in skips), plus all 5 routing tests (8 optional stress skips).

adil-a
adil-a previously approved these changes Nov 3, 2026
@yuhezhang-ai

Copy link
Copy Markdown
Contributor Author

/ok to test 5ac77de

@yuhezhang-ai
yuhezhang-ai disabled auto-merge November 5, 2026 19:57
@yuhezhang-ai
yuhezhang-ai added this pull request to the merge queue Nov 5, 2026
@github-actions

github-actions Bot commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/42099370055

@github-actions

github-actions Bot commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/42099694429

Merged via the queue into main with commit d45f9cf Nov 5, 2026
105 of 108 checks passed
@yuhezhang-ai
yuhezhang-ai deleted the yuhez/harbor-overlay-startup branch November 5, 2026 20:18
adil-a added a commit that referenced this pull request Nov 7, 2026
Conflicts:
- data/harbor-tasks.mdx: this PR splits it into data/task-folders/*. Main's new
  text moves to the matching page: the numeric USER note to Task Folder Format
  [agent], the Compose healthcheck user to Multi-Container Tasks, the job-overlay
  startup paragraph (#5186) to its overlay section, and the source-less committed
  entry (SkillsBench) to Author Task Folders. The skills_dir upload (#5699) is
  added to the [environment] table.
- integrate-existing-agents.mdx: keep the Harbor task folders column and take
  main's intro and BrowseComp row. BrowseComp runs task folders only as root,
  because it refuses a task user.
- environment_servers/harbor/README.md: keep the trimmed README. Its facts are
  now on the pages above.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Adil Asif <[email protected]>

This branch was previously deployed

1 inactive deployment
public — 5ac77dee Deployed Nov 5, 2026 by copy-pr-bot[bot] via release / finalize / notify #10337
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:sandbox Sandbox providers, isolation, and sandbox runtime contracts bug Something isn't working needs-review PR is ready for code review and waiting on a reviewer QA_verified

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants