Skip to content

feat(sandbox): implement long-running workload sandbox lifecycle engine - #157

Merged
dan-petty merged 5 commits into
release/v0.2.16from
feat/workload-sandbox-lifecycle-engine
Sep 12, 2026
Merged

dan-petty merged 5 commits into
release/v0.2.16from
feat/workload-sandbox-lifecycle-engine

Conversation

@dan-petty

Copy link
Copy Markdown
Owner

Summary

Implements a foundational execution tier orchestrating isolated, long-running rootless Docker container sandboxes and dynamic host port allocation, addressing #106.

Key Capabilities

  • Lifecycle Engine (src/devops_cli/sandbox/engine.py): Provision, inspect, and tear down detached background containers (deploy, status, stop, exec).
  • Dynamic Port Allocator (src/devops_cli/sandbox/ports.py): Probes and binds host ports in range 10000-60000 with socket bind conflict avoidance.
  • Strict Security Boundaries: Enforces rootless execution, cap_drop=["ALL"], security_opt=["no-new-privileges:true"], pids_limit=256, read-only rootfs with /tmp tmpfs, and rejects forbidden mounts (/, home, .git, .ssh, .kube, .aws, docker.sock).
  • Persistent State Ledger (src/devops_cli/sandbox/registry.py): Thread- and process-safe atomic JSON registry under .data/sandbox/instances.json.
  • Typer CLI (src/devops_cli/commands/sandbox.py): devops sandbox deploy, status, stop, exec with Rich rendering and --dry-run support.
  • FastMCP Tools & Resource (src/devops_cli/ai/mcp/server.py): Exposes sandbox_deploy, sandbox_status, sandbox_stop, sandbox_exec, and resource://sandbox/instances.
  • Comprehensive Test Suite (tests/test_sandbox_lifecycle.py): 29 unit tests with 97.35% code coverage, cyclomatic complexity $\le 10$, and maximum nesting depth $\le 5$.

Closes #106

Copilot AI lite review requested due to automatic review settings September 12, 2026 00:01
@dan-petty dan-petty added this to the v0.2.16 milestone Sep 12, 2026
@dan-petty dan-petty added type/feature Type feature: a new function scope/cli Core CLI framework, Typer subcommands, options, and tables priority/p0-critical Priority P0: a release blocker or a critical defect status/in-review Status In Review: the pull request of the item is open labels Sep 12, 2026
Comment thread src/devops_cli/sandbox/ports.py Fixed

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Changes recommended

Unresolved critical containment and lifecycle findings prevent safe approval.

Get a fresh assessment by requesting another Copilot review.

Pull request overview

This PR adds a long-running Docker sandbox lifecycle engine with persistent state, dynamic ports, CLI commands, and MCP integrations.

Changes:

  • Adds sandbox models, registry, port allocation, and lifecycle orchestration.
  • Adds Typer CLI commands and FastMCP tools/resources.
  • Adds tests, configuration, exceptions, and documentation.
File summaries
File Description
tests/test_sandbox_lifecycle.py Sandbox lifecycle tests
tests/test_architectural_invariants.py Exception invariants
src/devops_cli/sandbox/registry.py Persistent instance registry
src/devops_cli/sandbox/ports.py Dynamic host port allocation
src/devops_cli/sandbox/models.py Sandbox data models
src/devops_cli/sandbox/engine.py Docker lifecycle orchestration
src/devops_cli/sandbox/__init__.py Public sandbox exports
src/devops_cli/main.py CLI registration
src/devops_cli/lang/en/help.py Command help text
src/devops_cli/exceptions/sandbox.py Sandbox exceptions
src/devops_cli/exceptions/__init__.py Exception exports
src/devops_cli/config/defaults.py Registry defaults
src/devops_cli/config/constants.py Error constants
src/devops_cli/commands/sandbox.py Sandbox CLI commands
src/devops_cli/ai/mcp/server.py MCP tools and resource
README.md Command matrix
docs/MCP_TOOLS.md MCP documentation
docs/ERRORS.md Error catalog
docs/commands/sandbox.md Sandbox command reference
docs/CLI_REFERENCE.md CLI reference
docs/agent/tasks/task-106-workload-sandbox-lifecycle-engine.md Task tracking
docs/agent/task.md Task index
Review details

Suppressed comments (15)

docs/CLI_REFERENCE.md:5707

  • The unescaped | characters in the network description are parsed as table delimiters, so this generated command-reference row renders with extra columns instead of one description cell. Escape the separators in the generator or this synchronized copy.
| `--network` | `string` | `bridge` | Docker network mode (bridge | host | none). |

docs/commands/sandbox.md:32

  • The unescaped | characters in the network description are parsed as table delimiters, so this generated command-reference row renders with extra columns instead of one description cell. Escape the separators (or fix the documentation generator) before publishing the reference.
| `--network` | `string` | `bridge` | Docker network mode (bridge | host | none). |

src/devops_cli/ai/mcp/server.py:1168

  • instance_id is appended without the repository's MCP argument validation. Passing instance_id='--all' causes the tool to request the entire inventory even when all_instances is false, exposing unrelated sandboxes. Reject hyphen-prefixed identifiers before constructing the CLI command.
    if instance_id:
        cmd.append(instance_id)

src/devops_cli/ai/mcp/server.py:1197

  • The MCP wrapper does not validate the instance ID or terminate option parsing before appending the container command. An ID beginning with - can be treated as an outer CLI flag, and command arguments such as --workdir can alter the wrapper's --workdir option instead of running inside the container. Validate the ID and insert -- before command.
    cmd = ["uv", "run", "devops", "sandbox", "exec", instance_id]
    if workdir:
        cmd.extend(["--workdir", workdir])
    cmd.extend(command)

src/devops_cli/ai/mcp/server.py:1177

  • With both selectors at their defaults, this MCP tool constructs devops sandbox stop --timeout ... without an instance or --all, which the CLI deliberately rejects. A valid tool invocation therefore fails; validate that exactly one selector is supplied before dispatching.
def sandbox_stop(
    instance_id: str | None = None,
    all_instances: bool = False,
    timeout: int = 10,
) -> str:

src/devops_cli/commands/sandbox.py:218

  • stop --all prints an error for an individual target but returns normally, so automation receives exit code 0 even when one or more containers were not stopped. Track per-target failures and exit nonzero after attempting all targets.
    for target in targets:
        try:
            stopped = engine.stop(target, timeout=timeout)
            print_success(
                f"Sandbox '{stopped.name}' stopped and removed [ID: {stopped.instance_id}]"
            )
        except SandboxNotFoundError as exc:
            print_error(f"Cannot stop '{target}': {exc}")
    return None

src/devops_cli/sandbox/engine.py:124

  • This dictionary collapses repeated container port/protocol pairs. For ports=[80, 80], allocation records two host ports but Docker receives only the last mapping, so the ledger reports a binding that is not actually published. Reject duplicate container ports before allocation or validate uniqueness in the deployment model.
        ports_map = {f"{b.container_port}/{b.protocol}": b.host_port for b in port_bindings}

src/devops_cli/sandbox/engine.py:316

  • Both fallback commands use check=False and their return codes are ignored. If the SDK and CLI stop/remove operations both fail, _terminate_container still returns and stop marks the registry entry stopped, allowing future deployments to reuse its port while the container may still be running. Confirm termination before updating the ledger and raise a sandbox error on failure.
        except Exception as exc:
            logger.debug("Docker SDK container stop failed (%s); trying subprocess", exc)
            run_subprocess(["docker", "stop", "-t", str(timeout), container_id], check=False)
            run_subprocess(["docker", "rm", "-f", container_id], check=False)

src/devops_cli/sandbox/engine.py:341

  • The Docker SDK execution path has no timeout, and SandboxDeployConfig.timeout is not available to exec. A hung command can therefore block the direct CLI indefinitely, unlike the bounded subprocess fallback. Add an explicit execution timeout and enforce it consistently on both paths.
            client = _get_docker_client()
            container = client.containers.get(inst.container_id)
            exit_code, output = container.exec_run(command, workdir=workdir)

src/devops_cli/sandbox/engine.py:246

  • The new status and exec lifecycle operations have no OpenTelemetry span or metric when the Docker SDK path is used, unlike deploy and stop. Normal status/exec calls are therefore invisible to the existing lifecycle observability pattern. Instrument these operations around the full SDK and fallback paths.
    def status(self, identifier: str | None = None) -> list[SandboxInstance]:
        """Query sandbox status and reconcile liveness against Docker daemon."""

src/devops_cli/sandbox/engine.py:282

  • A missing container is handled by the broad exception here and leaves the ledger in RUNNING. After an external removal, status and port allocation continue treating the sandbox as live indefinitely; distinguish Docker-not-found from daemon connectivity failures and mark the instance stopped/failed when it is gone.
        except Exception as exc:
            logger.debug("Failed polling container %s status: %s", inst.container_id, exc)

src/devops_cli/sandbox/engine.py:62

  • This introduces a second sandbox implementation alongside devops_cli.docker.sandbox.WorkloadSandboxRunner, duplicating workspace validation, Docker SDK/subprocess setup, and security flags. Keeping the two engines independent means containment and fallback fixes can diverge; factor shared Docker/security primitives or extend the existing runner.
class WorkloadSandboxEngine:
    """Orchestrator for managing isolated background Docker container sandboxes."""

src/devops_cli/sandbox/engine.py:345

  • The SDK path calls exec_run without demux=True, so Docker combines stderr into output and this code always returns stderr="". The subprocess fallback returns separate streams, making SandboxExecResult and CLI behavior depend on which backend is available; request/demultiplex the streams consistently.
            exit_code, output = container.exec_run(command, workdir=workdir)
            stdout = (
                output.decode("utf-8", errors="replace")
                if isinstance(output, bytes)
                else str(output)

src/devops_cli/sandbox/models.py:28

  • These port fields accept arbitrary integers, and the allocator never validates requested container ports. The CLI accepts values such as 0 or 70000 and only fails later during Docker creation; constrain container and host ports to 1-65535 and report a typed validation error before allocation.
    container_port: int
    host_port: int
    protocol: str = "tcp"

src/devops_cli/sandbox/registry.py:76

  • This read-modify-write sequence has no thread or inter-process lock. Concurrent deploy/stop/register operations can read the same list and the last atomic replace drops the other operation's record, contradicting the process-safe ledger claim and losing port reservations. Lock the whole transaction or use a transactional store.
        instances = self.list_instances()
        filtered = [inst for inst in instances if inst.instance_id != instance.instance_id]
        filtered.append(instance)
        self._save_instances(filtered)
  • Files reviewed: 22/22 changed files
  • Comments generated: 17
  • Review effort level: Lite

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread src/devops_cli/ai/mcp/server.py Resolved
Comment thread src/devops_cli/ai/mcp/server.py Resolved
Comment thread src/devops_cli/commands/sandbox.py Resolved
Comment thread src/devops_cli/sandbox/engine.py Resolved
Comment thread src/devops_cli/sandbox/engine.py Resolved
Comment thread src/devops_cli/sandbox/engine.py Resolved
Comment thread src/devops_cli/sandbox/ports.py Resolved
Comment thread docs/agent/task.md Resolved
@dan-petty
dan-petty merged commit 73113ea into release/v0.2.16 Sep 12, 2026
4 checks passed
@dan-petty
dan-petty deleted the feat/workload-sandbox-lifecycle-engine branch September 12, 2026 02:10
dan-petty added a commit that referenced this pull request Sep 12, 2026
* docs(changelog): document v0.2.15 release highlights and features (#105)

* docs(changelog): document v0.2.15 release highlights and features

* docs(changelog): clarify k8s logs invocation and list all 11 security scanners

* docs(agents): update agent instructions to honor API rate limits and quotas (#130)

* docs(agents): update agent instructions to honor API rate limits and quotas

- Add API rate limiting, complexity budgeting, and quota guidelines to AGENTS.md across core engineering, GitHub integration, and AI inference.
- Synchronize DEVOPS_CLI_AGENTS_METADATA_TEMPLATE in instruction_generator.py with rate-limiting rules.
- Add regression test assertions to test_instruction_generator.py.
- Track deliverable in task-129-agent-instructions-rate-limits.md.

Closes #129

* docs(agents): include AI inference rate limits and expand generator test assertions

* docs(agents): make semaphore example executable and link PR in task tracking

* feat(ai): render chat persona title in orange styling (#133)

* feat(ai): render chat persona title in orange styling

- Render persona title in bold dark_orange in chat section header rule
- Output persona reply prompt in bold dark_orange using Rich console
- Preserve bold cyan styling for 'You:' user prompt
- Update unit tests in test_ai_cmd.py asserting persona and user prompt colors

Closes #132

* test(ai): assert dark_orange section header styling and update task status to In Review

* fix(k8s): review pod restarts, eliminate cgroup oom kills, and optimize workload resource limits (#136)

* fix(k8s): review pod restarts, eliminate cgroup oom kills, and optimize workload resource limits

- Remove hard memory limits on Ollama DaemonSet (leaving requests at 3000m CPU and 8Gi RAM), allowing dynamic memory bursting into available node RAM without cgroup OOM kills
- Add startupProbe to Ollama DaemonSet with 5-minute failure threshold for cold starts and large model weight loading
- Relax Ollama livenessProbe (10s timeout, 15s period, 6 failure threshold) to prevent premature kubelet SIGKILL terminations during heavy inference
- Raise memory and CPU limits across core workloads (ArgoCD controller, repoServer, server, and Redis; Valkey; Jaeger; Registry; Fluent Bit; and Loki)
- Add comprehensive regression tests in tests/test_k8s.py verifying resource limit invariants and probe resilience
- Create task tracking document docs/agent/tasks/task-135-k8s-pod-restarts-resource-limits.md

Closes #135

* fix(k8s): bound Ollama memory limit, enforce probe contracts, and assert all resource changes

* feat(k8s): deploy squid caching proxy with ssl bump, observability, and failover handling (#134)

* feat(k8s): deploy squid caching proxy with ssl bump, observability, and failover handling

- Deploy high-capacity Squid caching proxy configured for 100GB single objects
- Enable SSL-Bump TLS interception with dynamic cert generation for Ollama 70B layers
- Add Prometheus observability via squid-exporter sidecar on port 9301
- Enable structured JSON access logging to stdout and Cache Manager API
- Implement LFUDA dynamic aging eviction with proactive high/low watermarks (92%/85%)
- Integrate Squid proxy env vars and CA certificate mount in ollama-daemonset
- Document failover architecture across node crash, WAN outage, and storage domains
- Add comprehensive unit test suite in test_k8s_squid.py

Closes #131

* fix(docker): format and sort imports in _client helper

* refactor(k8s): relocate squid docker assets to k8s/squid/docker to prevent SDK namespace shadowing

* feat(k8s): add condor node affinity for high-capacity 1.8TB NVMe storage allocation

* fix(docker): format import order in client builder

* fix(k8s): resolve review feedback on squid probes, egress policy, ca sync, and chown

* feat(docs): implement document compaction engine and enhance review self-improvement loop (#138)

* feat(docs): implement document compaction engine and enhance review self-improvement loop

- Author DocCompactor engine supporting roadmap, release notes, and log compaction
- Integrate devops docs compact subcommand with check, dry-run, and series filtering
- Expose docs_compact tool on FastMCP server and synchronize MCP JSON schemas
- Harden reference extractor to exclude glob patterns, examples, and stdlib prefixes
- Resolve executive summary reporting error handling for skipped and errored files
- Enhance review prompts and system instructions for closed-loop self-improvement
- Constrain Loki logging NetworkPolicy ingress to ingress-nginx controller
- Add comprehensive test suites for compaction engine and MCP tools

Closes #137

* fix(docs): resolve review feedback on error sanitization, path containment, and syntax boundaries

- Sanitize and bound error strings in pipeline errored_files registry to <= 256 chars
- Enforce strict regex validation and archive directory containment for release series
- Use negative lookbehind boundaries for secret tokens to support underscore identifiers
- Restore process dry-run state via try/finally in docs compact CLI command
- Refine log header version extraction and eliminate hardcoded series strings
- Populate roadmap and release notes section counters in DocCompactionResult
- Truncate caller-provided details in DocCompactionError to 256 characters
- Replace hardcoded package prefixes with dynamic importlib package introspection

* feat(ai): format chat responses as rich markdown and failover ollama models

* docs(roadmap): add agentic sandbox iteration architecture tasks

* feat(k8s): enable squid caching forward proxy cluster-wide and resolve root ca (#143)

* feat(k8s): enable squid caching forward proxy cluster-wide and resolve root ca

* feat(ai): support chat model cli overrides and map llm gateway to roadmap

* fix(k8s): address copilot review on squid proxy security and ca rotation

* feat(k8s): enable in-cluster squid proxying, store-id caching, and loopback rewriting

* fix(k8s): resolve pod restarts on gpu-feature-discovery and prometheus stack with burstable qos

* docs(agent): reconcile task lifecycles for v0.2.16 milestone release merge

* docs(devcontainer): align devcontainer usage guide with modern best practices (#145)

* docs(devcontainer): align devcontainer usage guide with modern best practices

* docs(devcontainer): address peer review feedback and improve configuration examples

* docs: remove obsolete development log and redundant pending features docs (#146) (#147)

* docs: remove obsolete development log and redundant pending features docs (#146)

* docs(agent): update task 146 status to in review with PR #147

* docs(routine): distinguish docs compaction from manual task archival

* refactor(core): decouple circular module imports and streamline convoluted import patterns (#148) (#149)

* refactor(core): decouple circular module imports and streamline convoluted import patterns (#148)

* fix(test): resolve child module import edges in invariant check and decouple config settings (#148)

* fix(k8s): route stack lifecycle run_subprocess and forward patches to _stack_lifecycle (#148)

* docs(architecture): document pre-1.0 alpha status, zero legacy remnants, and post-1.0 semver policy (#150) (#151)

* docs(architecture): document pre-1.0 alpha status, zero legacy remnants, and post-1.0 semver policy (#150)

* docs(security): sanitize homelab configurations and align release manuals with pre-1.0 alpha policy

- Fix Copilot review feedback on RELEASE_CYCLE.md: use generic SemVer placeholders X.Y.0 and X.Y.Z
- Fix Copilot review feedback on knowledge base: qualify release_management.md and release_engineering_and_semver_governance.md with pre-1.0 alpha zero backwards compatibility policy vs post-1.0 SemVer 2.0.0 governance
- Sanitize internal hostnames, RFC 1918 IPs, and hardware mount paths across k8s/squid/deployment.yaml, tests/test_k8s_squid.py, docs/ROADMAP.md, docs/squid-failover-and-observability.md, and docs/agent/tasks/
- Update AGENTS.md and instruction_generator.py with comprehensive prohibitions against recording internal infrastructure details
- Ground changes in Issue #152 and docs/agent/tasks/task-152-sanitize-internal-systems-and-strengthen-instructions.md

* docs(security): gate pre-1.0 alpha notice on devops-cli and sanitize cluster network docs (#152) (#153)

* docs(security): gate pre-1.0 alpha notice on devops-cli and sanitize cluster network docs (#152)

- Gate pre-1.0 alpha notice on meta.is_devops_cli across generate_pointer_stub, generate_instruction_content, and generate_agents_md so external scaffolded projects do not receive DevOps CLI-specific alpha notices
- Update test_instruction_generator.py to verify is_devops_cli gating behavior on pointer stubs and AGENTS.md
- Sanitize LAN speed reference in docs/squid-failover-and-observability.md to local cluster network speed
- Update task tracking in docs/agent/tasks/task-152-sanitize-internal-systems-and-strengthen-instructions.md

* docs(agent): update task-152 PR reference to #153

* test(ai): assert absence of pre-1.0 alpha lifecycle block for generic external projects

* fix(security): remediate devsecops findings and consolidate embedding configuration (#154) (#155)

* fix(security): remediate devsecops findings and consolidate embedding configuration (#154)

- Remediate review session findings for credential leakage, injection, and resource exhaustion
- Consolidate embedding configuration under ai.tasks.embedding and remove duplicate keys from rag
- Add offline fallback to tldextract and test-wide network egress guard
- Protect local user runtime config.yaml from automated sanitization rewrites
- Enhance review falsification rules, feedback export, and common hallucinations catalog

* fix(security): remediate pr 155 review comments and exclude documented example network references (#154)

* docs(roadmap): add milestones v0.2.19, v0.2.20, and v0.2.21, and mark task 154 complete

* chore(release): bump version to v0.2.16 and finalize changelog

* feat(sandbox): implement long-running workload sandbox lifecycle engine (#157)

* feat(sandbox): implement long-running workload sandbox lifecycle engine

* docs(agent): update task 106 tracking to In Review with PR 157

* feat(sandbox): remediate pr review findings, update agent instructions, and resolve threads

* fix(sandbox): address bandit b108 tmpfs mount false positive and format

* docs(roadmap): reprioritize roadmap and redistribute features across v0.2.17-v0.2.19

* feat(ci): automatically apply formatting and linting across CLI and CI commands (#159)

* feat(ci): automatically apply formatting and linting across CLI and CI commands (#158)

- Default --fix to True on devops ci, devops ci format, and devops ci lint
- Support --check flag for non-mutating validation
- Introduce top-level devops format and devops lint CLI commands with clean usage
- Move _layouts/ and assets/ to docs/ for Jekyll GitHub Pages compliance
- Prevent event loop deadlock in introspect_mcp_tools and offload check_docs
- Update test suites, architectural invariants, and documentation

* fix(docs): address PR 159 review comments on executor cleanup, alias docs, and jekyll layout

- Introspect leaf command aliases directly so devops format and devops lint generate clean leaf command usage rather than inheriting all ci subcommands
- Implement non-blocking thread pool executor cleanup with wait=False, cancel_futures=True and asyncio.wait_for in introspect_mcp_tools
- Remove /docs/ prefix in docs/_layouts/default.html navigation and footer links to prevent 404s on GitHub Pages
- Configure default layout in docs/github-pages.config.yaml for Jekyll markdown pages
- Synchronize task tracking and regenerate documentation

* chore(tasks): mark task-158 as done upon PR #159 merge

* fix(release): add release notes extraction fallback and enforce changelog version check (#140, #160)

Resolves release orchestration failures where release notes extraction fails due to missing version headers or changelog discrepancies:
- Strictly enforce matching version in CHANGELOG.md during devops release check (fatal Exit 1)
- Implement layered fallback extraction across CHANGELOG.md -> docs/RELEASE_NOTES.md -> git commit log
- Defensive fallback to git commit log in .github/workflows/release.yml
- Decompose release_check to maintain cyclomatic complexity <= 10
- Comprehensive unit tests in tests/test_release.py

* chore(tasks): mark task-140 as done upon PR #160 merge

* docs(release): update v0.2.16 changelog and release notes highlights

* fix(review): address PR 161 comments on sandbox port allocation, secret lookbehind, and gfd image

* fix(sandbox): align requested_ports type annotation in SandboxRegistry with allocate_ports
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

priority/p0-critical Priority P0: a release blocker or a critical defect scope/cli Core CLI framework, Typer subcommands, options, and tables status/in-review Status In Review: the pull request of the item is open type/feature Type feature: a new function

Projects

No open projects

Development

Successfully merging this pull request may close these issues.

3 participants