Repository navigation
feat(sdk): warn when OpenClaw or Hermes context exceeds the managed model budget - #13059
Merged
Merged
Conversation
…odel budget Plan and apply accepted OpenClaw and Hermes routes to managed vLLM and Ollama services whose serving.contextTokens could not hold the agent's prompt, and reported nothing. The managed Ollama examples served 8192 tokens, while one measured initial OpenClaw prompt used 19,947 tokens. The pinned Hermes Agent refuses a window below 64,000 tokens or, when it cannot read the window through the sandbox proxy, assumes 131,072 (review finding HM-1). Before any mutation, plan and apply now emit Progress::Warning for a route to a managed vLLM or Ollama service when: - an OpenClaw route's effective contextWindow exceeds the service's serving.contextTokens; - the smaller of the two cannot hold 20,000 prompt tokens plus the route's reply allowance; - the route's token metadata cannot be assessed; or - a Hermes route's service serves fewer than 64,000 tokens. The warnings never reject a document. The CLI collects them even with --progress off and prints them in text output and in a JSON `warnings` field, including when the command fails. The managed Ollama examples now serve 32768 tokens with a matching route contextWindow. Progress gains a Warning variant, so exhaustive matches on it need a new arm. Validation: cargo ci passed on linux_arm64 in 526 s (fmt, clippy -D warnings, build, 1391/1391 tests, schema, bundle, 127/127 lifecycle tests). Without the production change the 14 new tests do not compile. With only the Progress::Warning variant, 10 of the 12 advisory tests fail, and the 2 tests that assert no warning fail under boundary mutants (<= 64000, >= contextTokens). With the CLI ignoring warnings, both CLI tests fail. The branch CLI reports 2 and 1 warnings for the previous managed Ollama examples and none for the updated ones. `nemoclaw-build docs --check` passes. Split from #12736. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This was referenced Oct 13, 2026
Merged
Closed
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Contributor
|
v1 documentation preview: https://nvidia-preview-nemoclaw-v1-pr-13059.docs.buildwithfern.com/nemoclaw |
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
cv
pushed a commit
that referenced
this pull request
Oct 13, 2026
…, and test fixtures (#13056) Report the gateway's reason when OpenShell rejects a credential-free mutation, and fix sandbox teardown, deployment-lock release, test-fixture flakes and the images plan message, with matching docs. Nothing here depends on Kubernetes. ## Why The review of #12736 found these problems; each predates or is independent of the cluster model services. - **F2** (#12736 review): OpenShell rejection text was discarded. `remote_error` maps every gateway status to a fixed category, so on kind a CreateSandbox rejection for conflicting `allowed_ips` endpoint metadata reached the user only as `observation query failed`. Finding the cause took a rebuilt bundle that logged `status.message()`. - **`transport.rs:220`** (#12736 review: open at 59ad198, fixed at c3496ea): removing a ready sandbox read its active-policy status, which teardown does not use, so a failing status read blocked removal. #12736 changed this without a test. - **T1** (#12736 review): the deployment lock is an `flock` on the open file description. A child spawned concurrently holds a copy of the descriptor until `exec`, so dropping `Store` could leave the deployment locked and the next open failed with `another operation holds the deployment lock`. Besides the flaky SDK suite, an SDK process that runs `tofu` can hit this. - **T1-tail** (#12736 review) and **N1** (#12736 review, nit): several tests wrote a script and executed it at once, which fails with `Text file busy` (ETXTBSY) when a concurrent spawn holds the write descriptor. Running the staged provider through `/bin/sh` stopped the staging test from checking the executable bit OpenTofu needs. - **HM-4** (#12736 review, nit): `cargo images build --platform linux/amd64 hermes` failed with Bake's `failed to find target hermes`. - **N2** (#12736 review) and [#12642](#12642): no documented OpenClaw request format, and no recovery path when a malformed request leaves the runtime `unknown`. The gateway profile-format break from #12941 had no operator note. ## What changes - **Rejection text.** `ObservationError` gains `Rejected { operation, code, detail }`. `nemoclaw_openshell::remote_rejection` keeps the gateway's detail only for CreateWorkspace, CreateSandbox, DeleteProvider and DeleteProviderProfile, whose requests carry no credentials, and only for `FailedPrecondition`, `InvalidArgument`, `AlreadyExists`, `OutOfRange` and `ResourceExhausted`. Other codes and operations return the same category as before. - **Redaction.** `ObservationError::sanitized_detail` reduces text to printable ASCII of at most 1024 characters and redacts bearer tokens, key/value credentials (`authorization`, `api_key`, `token`, `password`, `secret`) and runs of 32 or more token characters. `sanitized_resource_detail` additionally keeps one known resource name. Credential-bearing provider creation and update, reads and exec keep category-only errors. - **Teardown.** `openshell-provider` skips the active-policy status read when it reads a ready sandbox for removal (`if ready && !removing`). The owned identity checks still run. - **Lock.** `impl Drop for Store` unlocks before the file closes, which releases the `flock` for every copy of the descriptor. - **Test fixtures.** Tests execute an existing interpreter or binary (`/bin/sh`, `/bin/cat`) and pass the written script as data. The provider staging test asserts the executable bit. - **Images plan.** `images::plan` lists each platform's harnesses with `buildx bake --print agents` and names the platforms that build a requested harness. Groups and other targets keep Bake's resolution. - **Docs.** `agents.md`: the headless OpenClaw request and the reported malformed-request failure. `usage.md`: "Replace Workloads After an Unusable OpenClaw Runtime". `troubleshooting.md`: which rejections keep their detail, and table rows for both failures. `provider.md`: "Gateway Profile Format Upgrade". ## Breaking or user-visible changes - **Rust API:** `ObservationError` (from `nemoclaw-backend`, re-exported as `nemoclaw_sdk::ObservationError`) is `Clone` but no longer `Copy`, and has the new `Rejected` variant. Code that copies it must call `.clone()`, and exhaustive matches need a `Rejected` arm. The crates are `publish = false`; every use in this workspace is updated. An application using the SDK through a path dependency must make the same edits. - **Error text:** a rejected CreateWorkspace, CreateSandbox, DeleteProvider or DeleteProviderProfile now reports `OpenShell <operation> rejected (<code>): <detail>` instead of `observation query failed`. This applies to Docker, Podman and Kubernetes gateways. - **Images:** an unsupported harness now fails with, for example, `hermes is built only for linux/arm64; linux/amd64 builds deepagents, openclaw (docs/build.md#build-agent-images)`. - No configuration, schema, bundle or state format change. ## Test proof ### `cargo ci` (linux_arm64, this branch) Run on the GB300 host (aarch64). The tree tested is the commit's tree. ``` ok tools in 0s ok fmt in 1s ok clippy in 35s ok build in 76s Summary [ 19.032s] 1387 tests run: 1387 passed, 174 skipped ok test in 25s ok schema in 0s ok bundle in 178s Summary [ 364.941s] 127 tests run: 127 passed, 48 skipped ok lifecycle in 371s All selected CI steps passed in 690s ``` The test step's 4 doctests passed. The lifecycle timing report lists one local overrun: 364.9 s wall against the 300 s budget that applies on the Linux CI runners. This PR adds no lifecycle tests; the per-test (90 s) and per-binary budgets were met. `cargo run --locked -p nemoclaw-build -- docs --check` passed after `docs` generated the untracked output; no tracked file changed. ### New tests: red without the production change, green with it Each red run edited only the working tree and restored the PR tree afterwards. Commands: `cargo test --locked -p <crate> <target> -- <test names>`. | Test | Red change | Red result | Green | |---|---|---|---| | `nemoclaw-openshell` `connection::tests::live_endpoint_ambiguity_keeps_its_conflict_kind` | `remote_rejection` returns `remote_error` (v1 behaviour) | FAILED: message lacks `conflicting metadata: allowed_ips=[]` | ok | | `connection::tests::definitive_rejections_keep_bounded_gateway_text_and_other_statuses_stay_fixed` | same | FAILED: `missing operation rejection` | ok | | `openshell-provider` `fake_gateway_tests::gateway_validation_rejections_preserve_details_for_credential_free_mutations` | `connected.rs` restored to v1 | FAILED: `missing CreateWorkspace rejection detail: observation query failed` | ok | | `fake_gateway_tests::credential_requests_reads_and_exec_keep_backend_rejection_text_private` | guard: passes on v1 by design; mutant opts CreateProvider into `remote_rejection` | FAILED under the mutant: `Rejected { operation: "CreateProvider", …, detail: "PRIVATE_SENTINEL" }` ≠ `Query` | ok | | `fake_gateway_tests::ready_sandbox_teardown_needs_owned_identity_but_not_active_policy_status` | `transport.rs` restored to v1 (`if ready {`) | FAILED: removal read returned `Err(Transport)` | ok | | `nemoclaw-sdk` `error::workload_details_redact_short_bearer_and_quoted_credentials` | `sanitize_detail` returns its input | FAILED: secret kept | ok | | `error::workload_details_are_single_line_bounded_and_redact_token_like_runs` | same | FAILED: `safe.len() <= 1024` | ok | | `error::resource_details_preserve_only_the_exact_known_name_outside_credentials` | same | FAILED: name appears 5 times, expected 1 | ok | | the three `error::` tests | `observation.rs` restored to v1 | does not compile: no `sanitized_detail`, no `Rejected` (E0599) | ok | | `nemoclaw-sdk` `state::tests::dropping_store_releases_lock_while_a_duplicate_descriptor_remains_open` | `state/mod.rs` restored to v1 (no `Drop for Store`) | FAILED: `Conflict("another operation holds the deployment lock or locking failed")` | ok | | `nemoclaw-build` `images::harnesses_missing_from_the_selected_platform_name_the_platforms_that_build_them` (needs `docker buildx`; v0.37.1 here) | `images.rs` restored to v1 | FAILED: got `docker failed to plan the image build` | ok | | `nemoclaw-test-fixtures` `tofu::tests::stages_only_the_selected_provider_and_cleans_only_its_workspace` (changed test) | mutant: staging sets mode 0644 | FAILED: executable-bit assertion | ok | ### Repeated runs of the touched suites In-process `cargo test` runs on this host, which is where the descriptor races occur (nextest isolates each test). Branch and v1 (29bb057) ran under the same load. | Suite | This branch | v1 | |---|---|---| | `cargo test -p nemoclaw-sdk --lib` | 22/22 runs passed (192 tests) | 7/22; failures in `state::tests::lock_excludes_other_operations_and_atomic_intent_survives_reopen` (`Conflict("another operation holds the deployment lock…")`), `deployment::tests::changing_gateway_management_at_the_same_endpoint_preserves_saved_state`, `deployment::export::tests::export_reports_recovery_for_each_saved_operation_state_without_changing_files` | | `cargo test -p nemoclaw-test-fixtures --lib` | 50/50 | 46/50; kept logs show `Text file busy` in the staging test | | `cargo test -p nemoclaw-runtime --lib vllm::runtime` | 10/10 | 10/10 | | `cargo test -p nemoclaw-provider --lib hardware::ssh` | 10/10 | 10/10 | | `cargo test -p nemoclaw-sdk --test integration kubernetes_connection` | 10/10 | 10/10 | ### Lifecycle tests This PR adds no lifecycle-only tests. All 127 selected by the `lifecycle` profile passed. The ones that drive the changed OpenShell code through OpenTofu: - `openshell-provider::contract`: all 44 passed, including `standalone::standalone_hcl_rejects_replacement_and_unauthorized_removal_during_plan`, `standalone::standalone_hcl_recovers_lost_delete_response_without_repeating_the_mutation`, `standalone::standalone_registrations_replace_and_remove_without_destroy_mode` and the 22 example-configuration tests. - `nemoclaw-e2e::integration` teardown paths, all passed: `deployment::failed_first_apply_can_destroy_bound_resources_without_successful_reapply`, `deployment::destroy_waits_for_graceful_sandbox_stop_without_retrying`, `deployment::rejected_policy_fails_promptly_with_context_and_allows_recovery_or_destroy`, `deployment::sandbox_startup_failure_names_reason_and_guidance_and_allows_destroy`, `deployment::pi_start_failure_names_the_sandbox_in_cli_text_and_json_and_allows_destroy`, `deployment::mixed_sandboxes_reorder_add_recover_export_and_destroy_independently`. <details><summary>All 127 lifecycle tests (passed)</summary> - `fabric-provider::contract` (3): `capabilities::capabilities_judge_the_image_for_the_configuration`, `pi_configuration_updates_without_replacing_the_sandbox`, `readiness::readiness_reports_the_configured_agent_and_its_failed_health` - `nemoclaw-e2e::integration` (49): `deployment::` (24), `export_observations::` (4), `fabric_deployment::` (4), `helm_recovery::` (5), `inference_discovery::optional_catalog_failures_preserve_complete_unchanged_plans_and_typed_uncertainty`, `multiple_providers::provider_union_export_reapply_drift_and_destroy_remain_scoped_to_each_sandbox`, `remote_service::` (9), `sandbox_readiness::standalone_sandbox_completion_rejects_unknown_health_and_retains_bindings` - `nemoclaw-provider::contract` (29): `discovery::` (3), `gateway_readiness::` (1), `gateway_storage::` (1), `inference_capabilities::` (3), `kubernetes_hcl::` (1), `kubernetes_lifecycle::` (2), `provider_protocol::` (4), `runtime_image::` (1), `service_capacity::` (1), `service_readiness::` (2), `service_storage::` (6), `vllm_runtime::` (4) - `openshell-provider::contract` (44): `capabilities::` (2), `standalone::` (20), and the example configurations `explicit_policy`, `fabric`, `fabric_claude`, `fabric_codex`, `fabric_hermes`, `fabric_mini_swe_agent`, `fabric_nooa`, `fabric_nooa_bench`, `fabric_openclaw`, `fabric_pi`, `fabric_remote_agent`, `hermes_auth`, `hermes_interfaces`, `inference_tuning`, `inline_inference`, `local`, `multiple_models`, `multiple_providers`, `multiple_sandboxes`, `openclaw_dashboard`, `openclaw_web_search`, `tavily_web_search` - `nemoclaw-fixture-provider::archive` `the_fixture_provider_is_found_beside_the_test_executables`, `nemoclaw-test-fixtures::ssh_relay` `the_relay_is_found_beside_the_test_executables` </details> ### Live evidence (not qualification; #12732 stays open) This branch merged with `v1` 025b95a (local merge ba8499b, GB300 host, aarch64, 2026-10-13): - `cargo ci live-docker`: **11/11 passed** in 352 s, and the Docker inventory was the same before and after. - The suite includes `v1`'s new `dummy_agent::the_dummy_agent_completes_a_managed_docker_lifecycle` (48.1 s). It destroys a ready sandbox through the bundled OpenShell provider and checks that no sandbox containers or volumes remain, which is the live path of the teardown change (`if ready && !removing`). - Full `cargo ci` on the merged tree: 1394 tests + 127 lifecycle, all passed, 727 s. The branch needs no change for the new `v1`; "Update branch" produces the tested tree. No kind or GPU run: nothing in this PR depends on them. ## Depends on / merge order - Base: `v1` at 29bb057. No dependencies; it merges in parallel with #13057, #13058 and #13059, and the four branches merge into each other without conflicts. - #13060 is opened on this branch and retargets to `v1` when this branch is deleted after merge. - #13061 needs this PR and #13058 in `v1`. - Lines of #12736 in these files that this PR leaves out, for the later PRs to carry: the `ModelRuntimeStopped` doc comment in `observation.rs` (#13061); in `provider.md`, the cluster `owner`/`generation` paragraph and the "cluster resource identity refresh" clause of the profile-format note (#13062); in `usage.md`, "including the cluster model and credential PVCs" (#13062). Split from #12736. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
cv
pushed a commit
that referenced
this pull request
Oct 13, 2026
…#13057) Bearer vLLM services now answer only the authenticated inference endpoints and public `GET /health`; every other request gets 404 before it reaches vLLM. ## Why Native vLLM authentication guards only `/v1` paths. On a live bearer service, `POST /invocations` returned a full chat completion without the key, and `/tokenize` and `/metrics` answered too (review finding **X1**). Recipe `VLLM_*` variables can also register management routes under `/v1`, such as `/v1/load_lora_adapter`, which any key holder could then call, including a sandbox through its injected key (**X1-L1**). The review of the first filter also found: - The image-build test used a hand-built copy of vLLM's app, so an upstream middleware change would pass unnoticed (**X1-T1**). - `HEAD /health` and plain `OPTIONS` reached vLLM's router (**X1-N1**, **X1-N2**). - A missing or wrong routes label produced a rejection that did not name the label (**X1-N3**). - The vLLM-only route files were staged into the Ollama build contexts too (**X1-N4**). **Why Rust.** The first revision of this PR filtered routes with a Python ASGI middleware loaded into vLLM and checked it with a Python test during the image build. The repository's own code is Rust, so the filter now runs in the Rust runtime supervisor, which is already the image's entrypoint, in front of vLLM. That also retires X1-T1 and X1-N4: there is no Python filter to test in the image and no route file to stage. ## What changes vLLM moves to loopback TCP, so its launch changes only by host and port; the runtime container's own network namespace keeps that port unreachable from outside the container. - **Route filter in the supervisor.** For bearer services, the Rust supervisor (`nemoclaw-runtime`, the image entrypoint) binds `0.0.0.0:<serving.port>` before it starts vLLM, so a port conflict fails startup, and serves HTTP/1.1 there with hyper (`crates/nemoclaw-runtime/src/vllm/runtime/routes.rs`). It forwards only: - `GET /v1/models`, and `POST` to `/v1/chat/completions`, `/v1/completions`, `/v1/responses`, `/v1/messages` and `/v1/messages/count_tokens`, all of which still require the key; - `GET /health`, which stays public. The filter compares the method and the request-target path exactly as received, with no percent-decoding or dot-segment removal, and accepts only origin-form targets. Every other request gets `404 {"error":"Not found"}` with or without the key and opens no connection to vLLM. That includes `OPTIONS`, `HEAD`, `CONNECT`, absolute-form targets, other spellings of an allowed path (`//`, `/./`, `..`, `%2e`, `/V1`, a trailing slash), and requests that carry `Upgrade` (WebSocket, h2c). An HTTP/2 preface closes the connection. - **Forwarding.** Allowed requests keep their method, path, query and end-to-end headers, including `Authorization`. Hop-by-hop headers (`Connection` and the headers it names, `Keep-Alive`, `Proxy-*`, `TE`, `Trailer`, `Transfer-Encoding`, `Upgrade`) are dropped in both directions. Request and response bodies stream, so completion events reach the client as vLLM produces them, and a client that disconnects closes its vLLM request. vLLM's uvicorn trusts forwarding headers from loopback (`proxy_headers` on, `forwarded_allow_ips=127.0.0.1` in the pinned ARM64 base's uvicorn 0.52.4), and every filtered request now comes from loopback, so the filter sets `X-Forwarded-For` to the connecting address and drops `X-Forwarded-Proto`; a client cannot choose the address or scheme vLLM records. If vLLM does not accept the connection, the client gets `502 {"error":"Bad gateway"}`; if the client's body cannot be read, such as invalid chunked framing, it gets `400 {"error":"Bad request"}`. A client must send its request headers within 30 s. - **Connection limit.** The filter serves at most 256 connections at once; later clients wait in the listen backlog until one closes. When the filter starts, the supervisor raises its soft open-file limit to the hard limit (vLLM, already running, keeps the limit it inherited and raises itself), and the cap shrinks so that two descriptors per connection plus 128 kept for the supervisor fit the limit. Without the cap, about 1,000 idle connections exhausted the container's default soft limit of 1024, the supervisor's memory sample could not open `/proc/meminfo`, and the supervisor stopped vLLM until reapply. - **Launch.** Bearer vLLM starts with `--host 127.0.0.1 --port <serving.port + 1>`, or `--port 65534` when `serving.port` is 65535 (the schema allows 1024 to 65535), and no `--middleware`. Readiness still probes `http://127.0.0.1:<serving.port>/v1/models` with the key, now through the filter. Services without `authentication` get the same arguments as before and no filter. - **Lifecycle.** The filter runs beside supervision. If it fails, the supervisor stops vLLM and reports `inference route filter failed; managed service stopped; reapply required`. When supervision ends for any other reason, including an operator stop, the filter closes its listener and open connections before the supervisor returns. - **Images.** The `vllm`, `vllm-amd64` and `qwen38` Dockerfiles install and run no Python for routing; they add only `org.nemoclaw.inference.routes=openai-v2`, which now identifies the supervisor filter. `runtimes/vllm/nemoclaw_vllm_routes.py` is deleted, `runtimes/vllm/test_auth.py` is back to its `v1` content, and the build no longer stages either file (`stage_workload_files` and its reserved manifest names are gone). - **Label enforcement.** Unchanged from the first revision of this PR: Docker bearer installs require `org.nemoclaw.inference.routes=openai-v2`, and the provider's rejection names the label and points to `docs/build.md`. - **Dependencies.** `nemoclaw-runtime` declares `hyper`, `hyper-util` and `http-body-util` under its `execution` feature, at the versions `reqwest` already locked (hyper 1.11.1, hyper-util 0.1.20, http-body-util 0.1.5). `Cargo.lock` gains three lines in the runtime's dependency list. The runtime's Linux dependency closure gains one crate, `httpdate` 1.0.3, from hyper's server feature; `tests/dependencies.rs` passes unchanged. - **Docs.** `docs/inference.md` describes the filter, the loopback port, the 404, 400 and 502 responses, the header timeout, the connection limit, half-closed clients and logging; `docs/build.md` says what the label identifies. ## Breaking or user-visible changes - **Existing bearer vLLM images must be rebuilt.** Images built before this change lack `org.nemoclaw.inference.routes=openai-v2`, so plan and apply reject them with: `runtime image platform or required backend, recipe, authentication, or route-restriction (org.nemoclaw.inference.routes) labels are incompatible; rebuild the runtime image (docs/build.md) and update its digest` - Bearer services return 404 for `/invocations`, `/tokenize`, `/metrics`, `/ping`, `/version`, `/load`, `/openapi.json`, `/inference/v1/generate`, LoRA load and unload, `OPTIONS` and `HEAD`, even with the key. - Compared with the Python filter in the first revision of this PR: - Percent-encoded spellings of an allowed path, such as `/v1/%6Dodels`, now get 404; the Python filter saw the decoded path. - WebSocket requests get an HTTP 404 instead of a close with code 1008. - Requests that offer an h2c upgrade get 404, including those `curl --http2` and other clients send to an `http://` URL; uvicorn ignored the offer and answered over HTTP/1.1. - While vLLM is loading or after it stops accepting connections, allowed requests get 502 from the supervisor. - A request body that cannot be read gets 400 `{"error":"Bad request"}` from the supervisor instead of uvicorn's plain-text 400. - Connections that do not complete a request head within 30 s, including idle keep-alive connections, are closed. - A client that half-closes its socket after sending a request gets no response; the supervisor treats it as a disconnect, where uvicorn answered. - More than 256 concurrent connections wait to be accepted. - Rejected requests (404) and 502s are not logged; uvicorn's access log recorded them. - vLLM records each bearer client by the address the filter puts in `X-Forwarded-For`, with port 0. Checked against the pinned ARM64 base's `uvicorn.middleware.proxy_headers` (no GPU): `X-Forwarded-For: 172.18.0.1` from 127.0.0.1 gives client `('172.18.0.1', 0)`; a client-supplied `203.0.113.7` and `X-Forwarded-Proto: https` would give `('203.0.113.7', 0)` and `https`, which the filter prevents. - Services without `authentication: bearer` are unchanged. ## Test proof ### `cargo ci` Run on Linux ARM64 (a shared 72-core host) at this PR's head `e40278c9e`, which merges `v1` `a5445c7fe` into the review-fix commit `c623b0a0e`: ``` ok fmt in 1s ok clippy in 20s ok build in 38s Summary [ 19.219s] 1404 tests run: 1404 passed, 175 skipped ok test in 25s ok schema in 0s ok bundle in 40s Summary [ 383.847s] 127 tests run: 127 passed, 49 skipped ok lifecycle in 389s All selected CI steps passed in 515s ``` The doctests passed (4). Local runs only report budgets: the unpartitioned lifecycle wall time (383.8 s) is over the 300 s per-partition budget, as on every split branch. This PR adds no lifecycle tests; the bearer `remote_service` tests, which require the routes label at plan, passed. `cargo ci` also passed at `25586e02e` (1401 tests) and at `c623b0a0e` (1404 tests, 565 s). ### New and changed tests: red on the parent, green here Commands: `cargo nextest run --locked -p <crate> --lib -E '<filter>'`. | Test | Without the change | On this branch | |---|---|---| | `nemoclaw-runtime` `vllm::runtime::routes::tests::*` (15 tests from `25586e02e`) | No filter on the parent, so the tests do not compile (`cannot find function allowed / serve / bind / supervise`, `unresolved import http_body_util`). Behavioral failures: the mutation table below and the next row. | 15 passed | | `…::routes::tests::vllm_records_the_connecting_address_instead_of_forwarding_headers_from_the_client` | FAIL with the filter forwarding the client's headers: `left: ["203.0.113.7", "198.51.100.1"]`, `right: ["127.0.0.1"]` | PASS | | `…::routes::tests::connections_beyond_the_limit_wait_until_a_served_one_closes` (review fix) | FAIL at `25586e02e`, with `serve` taking a limit it ignored: `the filter served a connection beyond its limit` | PASS | | `…::routes::tests::the_filter_raises_the_open_file_limit_and_leaves_descriptors_for_the_supervisor` (review fix) | FAIL: after lowering the soft limit to 1024, it stayed there (`left: Some(1024)`, `right: Some(1048576)`) | PASS | | `…::routes::tests::a_request_body_that_cannot_be_read_gets_bad_request` (review fix) | FAIL: a non-hexadecimal chunk size got `["502"]` and `{"error":"Bad gateway"}` | PASS | | `nemoclaw-sdk` `services::installers::vllm::tests::bearer_vllm_listens_on_loopback_beside_the_published_port_with_otherwise_unchanged_arguments` (changed, and renamed in the review fix) | FAIL at `c7de4c807`: bearer arguments had `--host 0.0.0.0`, `--middleware nemoclaw_vllm_routes.OpenAIRoutes`, `--port 18888` instead of `--host 127.0.0.1 --port 18889` | PASS (also checks 65535 → 65534) | All 18 route tests passed 30 of 30 `--stress-count` iterations. Two of them, the port-bind and operator-stop tests, asserted at `25586e02e` on an ephemeral port they had released, which another test in the same process could take; they failed 10 of 100 single-process runs (`cargo test` style). They no longer reuse a released port; after the fix the route tests failed 0 of 100 single-process runs, 0 of 40 with 16 test threads, and 0 of 30 beside 32 busy loops. The route tests drive the real filter on a loopback port against a stand-in vLLM that counts connections and records each request, and use raw sockets so no client library normalizes a target. They cover: each allowed route forwarded with `Authorization`, query and body intact; every X1 probe (`/invocations`, `/tokenize`, `/metrics`, `/v1/load_lora_adapter`, `/v1/models/<id>`, `/version`, `OPTIONS /v1/chat/completions`, `HEAD /health`, `//invocations`, `/v1/../invocations`, `/v1/%2e%2e/invocations`, `/./invocations`, `/health/../invocations`, `/v1/..%2finvocations`, `/V1/chat/completions`, absolute-form `http://127.0.0.1:PORT/invocations` and `…/v1/models`, `/invocations?x=/v1/`, `/v1invocations`, `/v1/chat/completions/../../invocations`, `//v1/chat/completions`) answered 404 with zero connections to vLLM; WebSocket and h2c upgrades, `CONNECT` and `OPTIONS *` refused; hop-by-hop headers removed both ways; a client's `X-Forwarded-For` replaced by its address and its `X-Forwarded-Proto` dropped; the first SSE event delivered while vLLM still holds the stream open; a client disconnect, before or during streaming, closing the vLLM connection; 502 when vLLM refuses; 400 for a non-hexadecimal or overflowing chunk size; five pipelined requests on one connection, including a request smuggled inside a body, each filtered; a stalled or silent connection closed by the header timeout; with a limit of two, a third connection waiting while two served ones stay open and served once one closes; the soft open-file limit raised to the hard limit, and the connection cap leaving 128 descriptors free at any limit; a port conflict failing `bind`; a failed filter stopping the vLLM process; and an operator stop closing the filter's open connections and its listener, which resets a connection waiting in the backlog. Each production property was also broken on its own in `routes.rs`: 22 mutations, 16 at `25586e02e` and 6 for the review fixes, grouped below; each made at least one route test fail. The operator-stop and port-bind mutations were run again against the changed tests and still fail them. | Mutation | Failing tests | |---|---| | `allowed` returns `true` (no filter) | matcher, X1 probes (`POST /invocations` got 200), upgrades, pipelining | | absolute-form not rejected | matcher, X1 probes (`GET http://…/v1/models` got 200) | | `Upgrade` not rejected | matcher, upgrades | | request or response hop-by-hop headers kept | hop-by-hop (`connection reached vLLM`, `x-upstream-hop reached the client`) | | response body buffered | streaming, client disconnect (first event never arrives) | | no header timeout | header timeout | | connect error not mapped to 502 | 502 | | filter failure ignored by supervision | failed filter (vLLM stand-in kept running) | | filter not stopped when supervision ends | operator stop (idle connection stays open) | | `bind` on `127.0.0.1` | port bind (not all interfaces) | | query or `Authorization` dropped | allowed routes | | connections detached from the filter | operator stop (idle connection stays open) | | a client's `X-Forwarded-For` or `X-Forwarded-Proto` kept | forwarding headers | | no connection limit, or a slot released at accept instead of when the connection closes | connection limit (`the filter served a connection beyond its limit`) | | soft open-file limit not raised | open-file limit (`left: Some(1024)`) | | cap ignores the reserve, or counts one descriptor per connection | open-file limit (fails at 130 descriptors) | | unreadable request body mapped to 502 | bad request (`["502"]`) | `ambiguous_request_framing_never_reaches_vllm` is characterization of hyper 1.11.1, not a red test: with both `Content-Length` and `Transfer-Encoding: chunked`, hyper drops the length, decodes the chunked body and closes the connection after the response, so vLLM gets one chunked request and the trailing `/invocations` is never parsed; `Transfer-Encoding: gzip` with a length, two different lengths, and `Transfer-Encoding` on HTTP/1.0 get hyper's 400 without reaching vLLM. The tests removed with the Python filter: `runtime::tests::only_vllm_runtime_contexts_receive_the_shared_routes_and_their_image_build_check` (with `stage_workload_files`), and the reserved-name half of `artifacts::artifact_inputs_cannot_overwrite_retained_build_or_workload_inputs`, which is back to `v1`'s `artifact_inputs_cannot_overwrite_the_retained_build_manifest`. The label tests in `nemoclaw-sdk` and `nemoclaw-provider`, and the lifecycle `remote_service` bearer fixtures, are unchanged and pass. ### Connection flood A throwaway ignored test, not committed, ran `serve` on a fixed port, `routes::supervise` with `/bin/sleep` as vLLM, and `run_owned`'s once-a-second memory sampler. Another process opened up to 1,100 idle connections to the port, sending nothing. | Tree | `prlimit --nofile` | Result | |---|---|---| | `25586e02e` | `1024:524288` | after 7 s, supervision returned `Protection("memory observation failed: host memory is unobservable; managed service stopped; reapply required")` and the stand-in was stopped | | this branch | `1024:524288` | soft limit raised to 524288, cap 256; after 40 s supervision was still running with 269 open descriptors, and the stand-in was alive | | this branch | `1024:1024` | soft limit stays 1024, cap 256; after 40 s supervision was still running with 269 open descriptors, and the stand-in was alive | ### Retained source and image - **Offline rebuild.** The ignored `nemoclaw-build` test `runtime::tests::retained_runtime_rebuilds_offline_without_protobuf_or_a_dependency_cache` passed in 51.9 s at `25586e02e` and in 52.6 s at `c623b0a0e`, whose dependencies are unchanged. It vendored and compiled `hyper` 1.11.1, `hyper-util` 0.1.20, `http-body-util` 0.1.5 and `httpdate` 1.0.3 from the retained archive with no dependency cache and no protoc. - **Dependency closure.** `cargo tree -p nemoclaw-runtime -e normal` for `aarch64-` and `x86_64-unknown-linux-gnu` lists 175 packages, compared with 174 at `c7de4c807`; `httpdate` 1.0.3 is the only addition. - **Image.** The table below describes the image built at `25586e02e`, before the review fixes, which did not change the Dockerfiles. The live run below used an image built at `c623b0a0e` (`sha256:62d0c76cd07c…`), checked the same way for route files and its retained `routes.rs`. `cargo run --locked -p nemoclaw-build --no-default-features -- runtime runtimes/vllm/build.json` at `25586e02e` finished in 532 s and printed `Runtime image loaded: nc-prototype-vllm@sha256:6adb9cc9088b7be5f945d1032b91672e84ebe27f0d840027cc14c0abb6492871`. | Check | Observed | |---|---| | Image ID and labels | `sha256:6adb9cc9088b…`, arm64; `org.nemoclaw.inference.routes=openai-v2`, `org.nemoclaw.inference.authentication=bearer-v1`, `org.nemoclaw.backend=vllm`, `org.nemoclaw.runtime.spec=v1` | | Build steps | `[2/5]`–`[5/5]` are the four `COPY` lines; no `RUN` step | | `docker history --no-trunc` | NemoClaw adds 4 `COPY`s, `ENTRYPOINT`, `CMD` and `LABEL`; no line names `nemoclaw_vllm_routes` or `test_vllm_auth` | | Files (`docker run --network none`) | `/opt/nemoclaw/source` holds only `Dockerfile`, `LICENSE`, `NOTICE.md`, `build.json`, `supervisor-source.tar.gz` and `supervisor.json`; `find /` finds no `nemoclaw_vllm_routes*` or `test_vllm_auth*`; Python cannot import `nemoclaw_vllm_routes` | | Supervisor | The binary contains the filter's failure message; the source archive contains `crates/nemoclaw-runtime/src/vllm/runtime/routes.rs` | ### Not run on this branch - An image build for `vllm-amd64` and `qwen38`. Their Dockerfiles differ from `v1` only by the label. - A client that holds all 256 connections while vLLM loads. The readiness probe goes through the filter with a 1 s timeout, so such a client can delay readiness; held until the startup budget runs out, that would stop vLLM. This follows from the design and was not tested. ### Live evidence (not qualification; #12732 stays open) `split/2-vllm-route-filter` @ `c623b0a0e` (the Rust route filter), with this head's `dist/linux_arm64` bundle (`0.1.0-dev.bc051796453ca7cb`). Run on 2026-10-13 on one GB300 (ARM64) with the local Docker engine (containerd image store) and a Docker managed gateway. **Image build from this head.** I ran `cargo run --locked -p nemoclaw-build --no-default-features -- runtime runtimes/vllm/build.json` in a clean clone at `c623b0a0e`. It exited 0 after 688 s. - Result: `nc-prototype-vllm@sha256:62d0c76cd07c…`, labelled `org.nemoclaw.inference.routes=openai-v2`, `authentication=bearer-v1` and `backend=vllm`. - The image has no `nemoclaw_vllm_routes*` or `test_vllm_auth*` file. - The `routes.rs` in the image's retained supervisor source is byte-identical to this head's file. | Check | Observed | |---|---| | Plan with the `openai-v1` image | Rejected in 1 s: `Runtime image compatibility check failed runtime image platform or required backend, recipe, authentication, or route-restriction (org.nemoclaw.inference.routes) labels are incompatible; …` | | Plan with the new image | `Plan incomplete · 7 known resource changes` (EXIT 0) | | Apply: bearer vLLM `Qwen/Qwen3-4B`, profile `gb300`, port 18899, OpenClaw sandbox | Took 336 s, including the model download. Runtime `nvidia`, 1 GPU request. | | Processes in the model container | PID 1 is `nemoclaw-runtime`. vLLM runs with `--host 127.0.0.1 --port 18900`. No process has `--middleware`. | | TCP listeners (read from `/proc/net/tcp`) | `0.0.0.0:18899` belongs to PID 1, `nemoclaw-runtime`. `127.0.0.1:18900` belongs to vLLM's `api_server`. The container publishes only port 18899, bound to 172.30.151.1. | | Key file | Mode 600, 1 link, 64 bytes | | X1 HTTP probes inside the container, against port 18899 (14) | `/v1/models` and `/v1/chat/completions` returned 401 without the key and 200 with it. `/v1/completions` with the key: 200. `GET /health`: 200. These returned 404, even with the key: `/invocations`, `/tokenize`, `/metrics`, `/v1/load_lora_adapter`, `/v1/models/<id>`, `/version`, `OPTIONS`, `HEAD /health`. | | X1 raw-socket bypass probes (24) | All 404. **Unexpected completions: 0** | | Routes this head adds | `POST /v1/responses`, `/v1/messages` and `/v1/messages/count_tokens` returned 401 without the key and 200 with it. | | Other methods and request forms, all sent with the key | All returned 404: `HEAD /v1/models`, `OPTIONS /v1/models`, `CONNECT 127.0.0.1:18900`, a WebSocket upgrade on `GET /v1/models`, an h2c upgrade on `GET /health`, and an absolute-form `GET http://…/health`. Each 404 has `content-type: application/json` and the body `{"error":"Not found"}`. `GET /health?x=1` returned 200. | | Do rejected requests reach vLLM? | No. vLLM's access log has 0 lines for any rejected route. | | Can other hosts reach vLLM's port 18900? | No. Inside the container, `172.30.151.3:18900` refuses connections. From another container on the deployment network, port 18899 answered `/health` 200, `/v1/models` 401, and `/metrics` and `/v1/load_lora_adapter` 404. Port 18900 at `172.30.151.3` refused the connection (curl exit 7). From the host, `172.30.151.1:18900` refused. | | Streaming inside the container | A `stream: true` request through port 18899 returned `text/event-stream`, chunked. 115 events arrived, the first at 121 ms and the last at 4079 ms. | | **OpenClaw agent turn** through OpenShell `ExecSandbox` on the Docker gateway | Succeeded in 16 s. The sandbox's `baseUrl` is `http://172.30.151.1:18899/v1`. Qwen3-4B called the `tts` and `message` tools, then replied "I'll help you with that. Let me check the necessary steps…". vLLM logged 3 × `POST /v1/chat/completions 200` from 172.30.151.1, through the filter. | | Streaming from the sandbox | The sandbox's Python sent the sandbox's `openshell:resolve:env:` credential placeholder as the key. The response was 200 `text/event-stream`. 115 events arrived: the first at 122 ms, then a median gap of 32.5 ms, the last at 3888 ms. | | Other routes from the sandbox (OpenShell injects the key) | `GET /v1/models` returned 200. The filter returned 404 for `/v1/models/<id>` and `/v1/load_lora_adapter`. OpenShell's own policy returned 403 `policy_denied` for `/metrics`, `/tokenize`, `/invocations`, `/version` and `/health`, so they never reached the filter. | | Bearer key in the sandbox environment (23 vars) / `/sandbox/.openclaw` (21 files) / state files / model log | **0/0/0/0** | | Destroy | `Destroy complete · 12s`. The model and agent containers were removed. The gateway-init container, the network and the gateway, model and auth volumes were retained. GPU back to 0 MiB. | Notes: - Every apply ended with the known upstream "Fabric readiness could not be established" (`fabric_health_unsupported`). This is not a failure of this PR. - An earlier image for this PR, `sha256:6adb9cc9…`, was built from `25586e02e`, before the hardening commit, and its `routes.rs` differs. This run used a new image built from `c623b0a0e`. - vLLM's `EngineCore` process also listens on six random ports on the container address, for torch.distributed and ZMQ. These ports do not serve HTTP. vLLM opens them with or without the filter, and this PR does not change them. - The probes run with the container's own `python3`, the interpreter vLLM uses. They are test scaffolding, not repository code. - Turns and sandbox probes went through a debug `ExecSandbox` tool, built against this head's SDK, that is not part of this PR. For the Docker gateway it connects the same way the provider does: to the plaintext loopback endpoint, with no credential. - The sandbox sent 6 `POST /v1/chat/completions` requests: 3 for the turn and 3 for streaming. The first two streaming attempts got 200 from vLLM but printed nothing, because the probe buffered its output and then waited on the kept-alive connection. The streaming row shows the rerun, sent with `Connection: close`. - The OpenClaw image is `nc-pr12736s8@sha256:dadc747a…`, built from `split/8`. #### On Kubernetes, through the stack The stack top #13063 with this filter merged (`3e25941f5`), its own bundle, and a vLLM image built from that head (`sha256:ff09fb4b79a3…`, same `routes.rs`), on kind `nvkind-demo` (one GB300): - The model Pod has one container. `0.0.0.0:18888` belongs to `nemoclaw-runtime`; vLLM listens only on `127.0.0.1:18889`, and port 18889 on the Pod IP refuses connections. The NetworkPolicy still blocks a plain Pod in the namespace. - 14 HTTP and 24 raw-socket probes in the Pod: **0 unexpected completions**; the extra routes, methods and upgrade checks match Docker. Streaming: 115 events, the first at 136 ms. - **OpenClaw turn** through the OpenShell supervisor: succeeded in 17 s, with 4 × `POST /v1/chat/completions 200`, all from the supervisor Pod. **Hermes turn at 64K context**: `kind GPU ok.` in 3 s; Hermes's `GET /v1/models` context probe gets 401 as before. - The bearer key appears 0 times in the sandbox environment, export, state files, ConfigMaps and model Pod log. Destroy kept the model and credential PVCs; GPU back to 0 MiB. ## Depends on and merge order - Base: `v1`. This PR has no dependencies and can merge in parallel with #13056, #13058 and #13059. - #13062 needs this PR in `v1`, because cluster bearer images need the routes label. #13062 also adds the cluster parts of this change: - the label in the SDK image-metadata check, with its message (the rest of X1-N3); - the Kubernetes wording in `docs/kubernetes.md`; - the `docs/inference.md` sentence about the supervisor-only NetworkPolicy; - a one-line `docs/kubernetes.md` fix from the move to Rust: WebSocket upgrades now get 404 like any other refused request. Managed services are not supported on Kubernetes in `v1`, so this PR leaves those out. Split from #12736. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
cv
pushed a commit
that referenced
this pull request
Oct 13, 2026
…el services (#13058) Docker-managed vLLM and Ollama services get CPU and memory limits, and a service-level `updatePolicy` that stops plan and apply from replacing a running model container unless the user opts in. ## Why On `v1`, every managed model container on Docker runs with a fixed 104 GiB memory limit and no CPU cap. An image, model, or serving change replaces the running container without asking, so a routine re-apply, for example from automation that bumps an image, can take a serving model down. This PR also carries the fixes for the review findings on the limits commit of #12736 (review at 487cfc8, items N1–N7): | Finding | Problem | Fixed here by | |---|---|---| | CL-1 / N1 (medium) | Lowering `memoryLimitGiB` resized the running model in place under `Preserve` and could OOM-kill it | A `memory-limit-gib` label forces replacement, and `preserve_docker_models` refuses an in-place memory decrease | | CL-2 / N2 | The new default had no release note and no CLI hint | Release-notes entry, and a `help` field on `DockerModelUpdateRefused` naming `spec.services.<name>.updatePolicy` | | CL-5 / N5 | A 1 s CFS period gave up to 1 s throttle stalls | 100 ms period, `quota = millis × 100`, raised to the kernel's 1000 µs minimum | | CL-6 / N6 | Docs said `Preserve` blocks limit changes when Docker applied memory in place; no `/proc` watchdog caveat; no CFS period | `inference.md`, `usage.md`, `provider.md` updated | | CL-7 / N7 | Tests accepted the in-place memory update and never checked provider refresh | Unit cases for memory decreases and Podman with SSH placement; e2e steps for the stopped-container refresh and memory refusal | CL-3 and CL-4 concern the legacy `kubernetes.*` field migration, which is not part of this split. ## What changes - **Configuration.** `container.cpuLimitMillis` and `container.memoryLimitGiB` on `kind: vllm` and `kind: ollama`, and a per-service `updatePolicy` (`Preserve`, the default, or `Recreate`). The new `ServiceUpdatePolicy` type lives in `services/update_policy.rs` and is exported as `nemoclaw_sdk::services::ServiceUpdatePolicy`. The schema default comes from `registry::constrain_schema`. - **Validation.** An explicit memory limit must cover `sharedMemoryGiB` under private IPC and the inline recipe's `preparationMemoryGiB`. A zero CPU limit is refused before native container creation. - **Docker compilation** (`docker_compute.rs`, `managed/spec.rs`). - A CPU limit sets `cpu_period = 100000` and `cpu_quota = cpuLimitMillis × 100` (at least 1000) in the OpenTofu resource and in the native `HostConfig`. - A memory limit sets `memory` and `memory_swap`. - Labels `nemoclaw.nvidia.com/cpu-limit-millis` (when a CPU limit is set) and `nemoclaw.nvidia.com/memory-limit-gib` (when memory differs from 104 GiB) force replacement. Without them, the pinned Docker provider v4.6.0 would update limits in place, drop the CFS quota, and could OOM-kill the model by lowering memory. - Omitted limits add no CPU settings or labels and keep the 104 GiB memory limit; `Process` omits `cpu_limit_millis` when unset, so existing specifications serialize unchanged. - **Update safety** (`deployment/runtime.rs`). `preserve_docker_models` runs during runtime observation for plan and apply. Under `Preserve` it refuses a plan that deletes a running or incompletely observed model container, or lowers its `memory`/`memory_swap`, with the new `Error::DockerModelUpdateRefused`. Missing containers, containers the provider refreshes as stopped (`must_run = false`), deposed instances, the gateway, and the Ollama proxy are not affected. - **CLI.** The refusal carries a `help` line in text and JSON output that names `spec.services.<name>.updatePolicy: Recreate` and links the new docs section. - **Docs.** New "Set Container Limits and Update Policy" section in `docs/inference.md`; updates to `usage.md` (change table, Podman note), `provider.md` (generated Docker attributes), `troubleshooting.md`, and a release-notes entry. Schema and `docs/reference/configuration.md` regenerated. ## Breaking or user-visible changes - **Docker model updates default to `Preserve`.** Changing a managed vLLM or Ollama service's image, model, serving settings, `cpuLimitMillis`, or `memoryLimitGiB` now fails at plan and apply while the container runs: ``` Docker model service 'qwen' is preserved by updatePolicy: Preserve; replacing a running or incompletely observed container requires explicit updatePolicy: Recreate, which permits downtime if the replacement cannot start; resources retained ``` Set `spec.services.<name>.updatePolicy: Recreate` to allow the replacement and its downtime. Changing only the policy does not restart the container. - Declaring `memoryLimitGiB: 104` (the default) does not replace an existing container. - Rust API: `managed::Process` gains `cpu_limit_millis: Option<u32>`, and `Error` gains `DockerModelUpdateRefused { service }`. ## Test proof `cargo ci` on linux_arm64 (aarch64, `CARGO_BUILD_JOBS=16`), tree `b63292802` (commit `c8166f739`, on top of `642211537`, which merges `v1` a5445c7): ``` ok tools in 0s ok fmt in 1s ok clippy in 21s ok build in 37s Summary [ 18.905s] 1392 tests run: 1392 passed, 177 skipped ok test in 24s ok schema in 0s ok bundle in 64s Summary [ 424.928s] 129 tests run: 129 passed (1 slow), 49 skipped ok lifecycle in 430s All selected CI steps passed in 580s ``` The test step also ran 4 doctests, all passing. `nemoclaw-build docs` (local link and heading check) also passes. The slow test is `nemoclaw-provider::contract service_readiness::standalone_proxy_readiness_rechecks_identity_and_credentials_without_sdk_or_gateway` (10.3 s against its 10 s limit). This PR does not change that binary, and `v1` runs the test in 9.9 s on this host. ### New tests: red on `v1`, green here "v1 code" means every production file in this PR reset to `v1` 29bb057, with this PR's test files kept. "Hunk removed" means the branch with one production hunk taken out or disabled. Each run was restored to the commit afterwards. | Test | v1 code | Hunk removed (branch) | Branch | |---|---|---|---| | `deployment::runtime::tests::docker_model_updates_preserve_running_containers_unless_recreation_is_explicit` | FAIL: `updatePolicy` is an unknown field | FAIL without the `preserve_docker_models` call; FAIL without the memory-decrease check (CL-1) | PASS | | `managed::spec::tests::zero_cpu_limit_is_rejected_before_native_container_creation` | FAIL: unknown field `cpu_limit_millis` | FAIL without the `cpu_limit_millis != Some(0)` check | PASS | | `managed::spec::tests::legacy_service_process_keeps_its_fields_without_cpu_limit` | does not compile (E0609, no field `cpu_limit_millis` on `Process`) | FAIL without `skip_serializing_if` on `cpu_limit_millis` | PASS | | `runtime_compile::docker_model_limits_reach_opentofu_and_native_container_configuration` | FAIL: `container.cpuLimitMillis` is an unknown field | FAIL without the memory-limit label; FAIL without the CPU quota on the Docker resource | PASS | | `runtime_compile::omitted_docker_model_limits_keep_independent_legacy_defaults` | does not compile (E0609) | FAIL without the memory-limit label; FAIL without `skip_serializing_if` | PASS | | `runtime_compile::docker_model_update_policy_does_not_change_runtime_resources` | FAIL: `updatePolicy` is an unknown field | FAIL when the policy is made to change the runtime process (a mutation; there is no hunk to remove) | PASS | | `runtime_compile::portable_container_memory_limits_cover_shared_memory_and_recipe_preparation_on_docker` | FAIL: `container.memoryLimitGiB` is an unknown field | FAIL without `validate_memory` | PASS | | `formatting::tests::docker_model_refusal_names_the_service_update_policy_field` (nemoclaw-cli) | does not compile (E0599, no variant `DockerModelUpdateRefused`) | FAIL without the `help` arm | PASS | Commands: `cargo nextest run --locked -p nemoclaw-sdk -p nemoclaw-cli --profile ci -E 'test(=…)'` for the unit and integration tests. Each "v1 code" run first compiled out the tests that cannot compile there (`#[cfg(any())]`) so the rest of the binary could run. ### Lifecycle-only tests (`remote_service`, run with the bundle from `cargo ci bundle`) | Test | Branch | Time | |---|---|---| | `remote_service::remote_model_reapply_and_drift_keep_bindings_and_stop_on_observation_failure` | PASS | 85.6 s | | `remote_service::remote_ollama_recovers_reapplies_and_stops_on_observation_failure_keeping_data` | PASS | 82.9 s | | `remote_service::managed_bearer_credentials_survive_recovery_reapply_and_replacement_outside_state` | PASS | 73.4 s | | `remote_service::managed_bearer_cleanup_recovers_damage_keeps_bindings_and_teardown_accepts_both_identities` | PASS | 73.0 s | | `remote_service::managed_pi_applies_without_generation_and_refused_sandbox_changes_keep_intent` | PASS | 60.7 s | | `remote_service::remote_ollama_preserve_refuses_image_and_memory_changes_and_recreate_plans_replacement` | PASS | 42.8 s | | `remote_service::remote_vllm_preserve_refuses_image_change_and_recreate_plans_replacement` | PASS | 26.4 s | | `remote_service::partial_runtime_destroy_retains_storage_without_creating_network` | PASS | 10.3 s | | `remote_service::partial_ollama_destroy_retains_storage_without_creating_network` | PASS | 10.0 s | | `remote_service::unverified_ollama_images_are_checked_after_pull_before_storage` | PASS | 9.2 s | | `remote_service::unverified_vllm_images_are_checked_after_pull_before_storage` | PASS | 9.0 s | Every scenario now deploys with `cpuLimitMillis` (1250 for vLLM, 10 for Ollama) and `memoryLimitGiB: 64`. What this PR adds to them: - Each apply through the shared `Scenario::apply` helper checks `CpuPeriod`, `CpuQuota`, `Memory` and `MemorySwap` in the container's `HostConfig`, and its `memory-limit-gib` label, for vLLM and, in `remote_ollama_preserve_…`, for Ollama. - An image change (vLLM and Ollama) and a memory decrease (Ollama) are refused at plan and apply, leaving the engine state, runtime state and `intent.json` unchanged, then planned as a replacement under `Recreate`. These steps run in their own scenarios, `remote_vllm_preserve_…` and `remote_ollama_preserve_…`, each ending with the no-probe check, so `remote_model_…` and `remote_ollama_recovers_…` keep close to `v1`'s steps and time. - A stopped vLLM container, which the provider refreshes as `must_run = false`, is replaced under `Preserve`. - The bearer key survives an image replacement under `Recreate`. Reds: each run rebuilt the bundle with `cargo ci bundle` from the modified tree, then ran `NEMOCLAW_TEST_BUNDLE=$PWD/dist/linux_arm64 cargo nextest run --locked --workspace --all-targets --profile lifecycle --run-ignored only -E 'test(/^remote_service::/)'` on all 11 `remote_service` tests. - **v1 code** (`v1` a5445c7 with its own bundle, and this branch's `remote_service.rs`): all 11 fail at scenario setup, because `v1` rejects `container.cpuLimitMillis` ("unknown fields are not allowed"). - **Without the `preserve_docker_models` call:** `remote_vllm_preserve_…` and `remote_ollama_preserve_…` fail, because the plan they expect to be refused succeeds. The other 9 pass: `managed_bearer_credentials_…` uses `Recreate`, and `remote_model_…` and `remote_ollama_recovers_…` no longer change the image or memory. - **Without the memory-limit label:** the five scenarios that apply through `Scenario::apply` (`remote_model_…`, both `…_preserve_…` tests, `managed_bearer_cleanup_…` and `managed_pi_…`) fail the `memory-limit-gib` label check after their first apply. In a diagnostic run that applied `remote_ollama_preserve_…` without that check, it failed because a memory decrease under `Recreate` plans an in-place `["update"]`, not a replacement. That in-place update is the CL-1 failure. - **With stopped containers also protected** (the `must_run != false` clause removed): `remote_model_…` fails, because the plan for its stopped container is refused with `DockerModelUpdateRefused`. The other 10 pass. **Timing budget.** On linux_amd64, this PR's first CI run took 91.3 s for `remote_ollama_recovers_…`, over the 90 s per-test lifecycle limit in `.config/test-budgets.yaml`, and 81.0 s for `remote_model_…`; `v1` runs them there in 65.7–68.7 s and 67.5–68.7 s. This PR had added an image change and a memory decrease to `remote_ollama_recovers_…`, and `Preserve` refusals to `remote_model_…`'s existing image-change step. Those steps now run in `remote_vllm_preserve_…` and `remote_ollama_preserve_…`, as #13042 split the deployment lifecycle test into explicit scenarios; no limit changes. In three runs of the `remote_service` tests on this host, interleaved with `v1` a5445c7's: | Test | This PR | `v1` | Estimate on linux_amd64 | |---|---|---|---| | `remote_model_…` | 85.0–85.3 s | 86.4–87.3 s | 67 s | | `remote_ollama_recovers_…` | 86.0–87.0 s | 86.0–87.4 s | 67 s | | `remote_ollama_preserve_…` | 42.7–43.1 s | — | 33–39 s | | `remote_vllm_preserve_…` | 25.5–26.3 s | — | 20–24 s | Each estimate multiplies this PR's time by `v1`'s linux_amd64 time over its time here: 0.77–0.79 for the two existing tests, and 0.77–0.91 (the range across `remote_service` tests) for the new ones. CI runs the lifecycle suite in two slices with a 300 s budget each. Run the same way here (`cargo ci lifecycle --partition slice:N/2`, twice each), this branch's slices took 208.9–211.1 s and 218.0–226.6 s; `v1`'s took 208.9–209.0 s and 198.7–201.7 s here and 201.6–206.0 s and 184.2–186.8 s on linux_amd64. Scaled the same way, this branch's slices would take about 204 s and 206 s there. ## Depends on / merge order - Base: `v1` (a5445c7 is merged into this branch). No dependencies; merges in parallel with #13056, #13057 and #13059. - It shares files with #13057 (`remote_service.rs`, `vllm/mod.rs`) and #13059 (`formatting.rs`). `git merge-tree` of this branch with the planning slices for #13056, #13057, #13059 and #13060 reports no conflicts. - #13061 needs this PR in `v1`, because its cluster settings use `ServiceUpdatePolicy`. #13062 adds back the Kubernetes and OpenShift wording removed from this PR's doc comments and docs, and the `kubernetes.is_none()` guards in `preserve_docker_models`. ### Live evidence (not qualification; #12732 stays open) `split/3-docker-container-limits` @ `fe97763b7`, this branch's `dist/linux_arm64` bundle (`0.1.0-dev.2857ec70977bc92c`). 2026-10-12, one GB300 (ARM64), local Docker engine, Docker managed gateway. **Setup.** A copy of #12736's review deployment `docker-openclaw` with a fresh UID and state directory, on 172.30.142.0/24 port 17842: - managed Ollama `qwen3:0.6b`, profile `gb300`, image `nc-prototype-ollama@sha256:dea377de…`; - `container.cpuLimitMillis: 4000`, `container.memoryLimitGiB: 48`; - an OpenClaw sandbox (image built from `split/8`; `image/` is identical to `v1`). | Check | Observed | |---|---| | Plan | `Plan incomplete · 6 known resource changes` | | Apply | Ollama created in 1 s, agent runtime in 17 s. Apply ended after 102 s with the known readiness message. | | `docker inspect` of the model container | `CpuPeriod=100000`, `CpuQuota=400000` (4000 millis × 100), `NanoCpus=0`, `Memory=51539607552` (48 GiB), labels `nemoclaw.nvidia.com/cpu-limit-millis=4000` and `memory-limit-gib=48`, runtime `nvidia` | | `memoryLimitGiB` 48 → 40 under the default `Preserve`: plan | EXIT 1: `Docker model service 'qwen' is preserved by updatePolicy: Preserve; replacing a running or incompletely observed container requires explicit updatePolicy: Recreate, which permits downtime if the replacement cannot start; resources retained`, plus the `DockerModelUpdateRefused` help (below) | | Same change: apply | EXIT 1: `No runtime resources changed.` plus the same help | | Container after the refused change | Same container ID; `Memory` still 48 GiB | | Same change with `updatePolicy: Recreate` | 68 s. `ollama/qwen: delete complete`, then `create complete`. New container ID with `Memory=42949672960` (40 GiB), label `memory-limit-gib=40`, `CpuQuota=400000` unchanged. The next plan: `No resource changes planned.` | | Destroy | `Destroy complete · 10s`; GPU back to 0 MiB | The help printed at both plan and apply: `To replace the running model container, set spec.services.qwen.updatePolicy: Recreate and apply again; the model is unavailable until the replacement starts. See docs/inference.md#set-container-limits-and-update-policy.` Notes: - Both applies ended with the known upstream "Fabric readiness could not be established" (`fabric_health_unsupported`). This is not a failure of this PR. - Destroy retained the gateway-init container, the network and the `gateway-data` and `ollama-qwen-data` volumes, as designed. Split from #12736. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
cv
added a commit
that referenced
this pull request
Oct 13, 2026
Moves the OpenClaw and Hermes context advisory out of `Deployment::run` into its own module. The warnings stay the same. ## Why #13059 added about 90 lines of advisory logic inline in `Deployment::run`, between validation and opening the state store. Each of its four warnings repeated the `(self.progress)(Progress::Warning { … })` call. Its tests went through `Deployment::plan` and `apply` against a missing bundle, and almost every case looped over both operations. ## Change - `deployment::context_advisory::context_warnings(&Document) -> Result<Vec<String>, ConfigError>` returns the warnings in sandbox and route order. `Deployment::run` emits each one as `Progress::Warning` at the same point as before. - The Hermes and OpenClaw checks are separate methods. Messages, thresholds, and metadata handling are unchanged. - The unit tests call the function directly, after the same `defaults` and `validate` that `run` performs. - A new test, `plan_and_apply_report_the_advisory_before_creating_state_or_mutating`, checks that plan and apply report the same warnings before they create state or start a mutation. That covers the wiring the old per-test loops checked. One difference: `run` now emits warnings after evaluating every route, not as it goes. The lookups that could fail at that point already passed `validate`, so the output is the same. ## Validation - `cargo test -p nemoclaw-sdk --lib deployment::`: 107 passed (12 advisory tests before, 13 now). - `cargo ci` on linux_arm64: all steps passed.
10 tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Plan and apply warn, before any mutation, when an OpenClaw or Hermes route's context does not fit the managed vLLM or Ollama service it uses.
Why
Plan and apply accepted agent routes to managed model services whose
serving.contextTokenscould not hold the agent's prompt, and said nothing:8192tokens. One measured initial OpenClaw prompt used 19,947 tokens before any reply, so the first turn could overflow the server or be silently truncated.MINIMUM_CONTEXT_LENGTHat theHERMES_REVISIONinimage/fabric/Dockerfile). Below it, Hermes refuses to start when it can read the server's window. In operator tests it could not read the window behind the sandbox proxy and assumed 131,072 tokens instead, so longer conversations can overrun the server. This is review finding HM-1 on [tracking] feat(kubernetes): manage vLLM and Ollama services (split) #12736.What changes
SDK (
deployment/mod.rs): a newProgress::Warning { message }event. Plan and apply check each OpenClaw and Hermes sandbox route to a managed vLLM or Ollama service before opening the bundle or state, and warn when:contextWindow(default32768at the pinned adapter revision, oroverrides.settings.model_metadata.contextWindow) exceeds the service'sserving.contextTokens;20000plus the effective reply allowance (overrides.settings.model_metadata.maxTokens, elseoverrides.maxTokens, else4096);settings.model_metadatais not an object, or itscontextWindowormaxTokensis not a positive integer, so the budget cannot be assessed (the value is not echoed and no default is substituted);serving.contextTokensbelow64000(HERMES_MINIMUM_CONTEXT_TOKENS).Other harnesses, external providers, and routes without a managed service are skipped. The warnings never reject a document.
CLI (
formatting.rs,progress/model.rs): warnings are collected even with--progress off, de-duplicated, and printed after the result as aWarnings:section in text output and as awarningsarray in JSON output. Both also appear when the command fails. Progress shows each warning as a durable line that does not mark work as active.Examples:
examples/managed-ollama.yamlandexamples/managed-ollama-gpu.yamlserve32768tokens and set the route'smodel_metadata.contextWindowto32768.Docs:
docs/inference.mddescribes the budget rules and adds "Size the Context for Hermes";docs/reference/cli.mddocuments thewarningsfield and that warnings survive--progress offand failures.Breaking or user-visible changes
Warnings:section, and JSON results and JSON errors gain awarningsarray (omitted when empty; it does not changecomplete).examples/managed-hermes.yaml(unchanged here) now warns, because its Hermes route uses managed Ollama atcontextTokens: 8192.nemoclaw_sdk::Progressgains theWarning { message }variant, so exhaustive matches onProgressneed a new arm.Test proof
cargo cion linux_arm64 at this commit (the fullCI / Bundlestep list, lifecycle withNEMOCLAW_TEST_BUNDLEfrom the bundle step):The timing report flagged the lifecycle wall time (403.6 s against 300 s) and the
nemoclaw-provider::contractandopenshell-provider::contractsums. Those budgets apply only on Linux CI runners, and this run shared the host with other builds. An earlier run of the same code, differing by one docs sentence, kept both contract binaries within budget (97.3 s and 174.8 s) with a 374 s lifecycle wall. This PR changes no test in those binaries.New tests: red without the production change, green with it. Each red run kept the new tests and reverted the production hunks in the working tree.
Progress::Warningvariant addednative_route_window_above_the_service_limit_warns_even_with_initial_prompt_room,native_route_mismatch_is_assessed_independently_of_unusable_reply_metadata,small_managed_openclaw_context_warns_before_plan_or_apply_mutation,route_context_warns_even_when_the_managed_service_has_room,context_advisory_reserves_the_effective_reply_allowance,context_advisory_follows_native_defaults_and_metadata_precedence,context_advisory_reports_unusable_metadata_without_guessing_or_echoing_values,context_advisory_uses_the_selected_harness_and_service_budget,context_advisory_resolves_referenced_harnesses_and_local_providers,hermes_routes_to_managed_services_below_its_minimum_context_warn)E0599 no variant named Warning found for enum deployment::Progressleft: 0, expected 1 or 2 warnings)native_route_window_at_or_below_the_service_limit_needs_no_mismatch_warning,hermes_routes_at_its_minimum_context_need_no_warning_whatever_the_route_metadatacontext <= 64000,contextWindow >= contextTokens)formatting::tests::warnings_survive_hidden_progress_and_successful_or_failed_json_outputE0599, 3 sites)Progress::Warningandformatting.rsat base: fail (text output has no warning)progress::model::tests::warnings_are_durable_without_marking_work_as_activeProgress::Warning: fail (Option::unwrap()onNone)Commands:
cargo nextest run --locked -p nemoclaw-sdk --lib -E 'test(/^deployment::context_warnings::/)'andcargo nextest run --locked -p nemoclaw-cli -E 'test(/^formatting::tests::warnings_survive|warnings_are_durable/)'. On the branch, all 14 passed in a filtered run and again in thecargo citest step (JUnit: 14/14 pass, 0 failures of 1391).Examples. Without a bundle, plan fails after the advisory, so the branch binary can report warnings for each example.
nemoclaw --progress off plan -o json:v1(contextTokens: 8192)32768)examples/managed-ollama.yamlexamples/managed-ollama-gpu.yamlAcross every file under
examples/(credential variables set to dummy values), onlyexamples/managed-hermes.yamlwarns on this branch.Docs.
cargo run -p nemoclaw-build -- docs --checkpasses (local links and anchors).Lifecycle-only tests. This PR adds none. The existing lifecycle suite passed 127/127, including the 9
nemoclaw-e2eremote_servicetests that plan and apply Docker managed vLLM and Ollama services.Depends on / merge order
v1(29bb057). No dependencies; merges in parallel with fix: report bounded OpenShell rejections and harden teardown, locking, and test fixtures #13056, fix(runtime)!: restrict bearer vLLM to authenticated inference routes #13057 and feat(services)!: add container limits and updatePolicy for Docker model services #13058.docs/inference.mdwith fix(runtime)!: restrict bearer vLLM to authenticated inference routes #13057 and feat(services)!: add container limits and updatePolicy for Docker model services #13058, andcrates/nemoclaw-cli/src/formatting.rswith feat(services)!: add container limits and updatePolicy for Docker model services #13058.git merge-treeof this branch with the PR-1, PR-2, PR-3 and PR-5 slices reports no conflicts.v1: its NetworkPolicy warning usesProgress::Warning. When feat(kubernetes): manage vLLM and Ollama services on managed cluster gateways #13062 adds managed cluster services and the cluster inference design doc, it extends this PR'sdocs/inference.mdtext to Kubernetes and adds the operator-report note todocs/limits.md. feat(sdk): route sandboxes on Kubernetes gateways to in-cluster model servers #13063 adds the cluster examples back to the advisory tests.Live evidence (not qualification; #12732 stays open)
split/4-context-advisory@4fda90b4f, this branch'sdist/linux_arm64bundle (0.1.0-dev.c4afaf1c80e8d2ea). 2026-10-12, GB300 host (ARM64), local Docker engine. This was plan only, so no containers ran and the GPU was not used.Setup. Each plan used this branch's
examples/managed-ollama-gpu.yaml(OpenClaw) orexamples/managed-hermes.yaml(Hermes) with:gb300;nc-prototype-ollama@sha256:dea377de…;split/8(image/is identical tov1), because Docker plan inspects the sandbox image.Each case ran
plan(text) and--progress off plan -o json. Each took about 5 s, and all ended withPlan incomplete · 6 known resource changes(no gateway yet).contextTokens/ routecontextWindowWarning:lineswarningsThe warnings printed:
OpenClaw sandbox assistant route primary advertises contextWindow=32768, exceeding managed service qwen serving.contextTokens=8192; longer conversations can exceed the server limit. Set overrides.settings.model_metadata.contextWindow to 8192 or less, …OpenClaw sandbox assistant route primary uses managed service qwen with serving.contextTokens=8192 and settings.model_metadata.contextWindow=32768; allow at least 22048 tokens for an initial prompt of about 20,000 tokens plus 2048 reply tokens. …Hermes sandbox assistant route primary uses managed service ollama-server with serving.contextTokens=32768; Hermes requires a model context window of at least 64000 tokens and can refuse to start or fail longer conversations below it. Set serving.contextTokens to 64000 or more …The 8192 case gave the same message with 8192.Plans created no containers, and no network on 172.30.143–147.0/24.
For the cluster cases of the advisory, which #13063 adds, see PR-8's evidence: Hermes on cluster vLLM warns at 32K and is silent at 64K.
Split from #12736.
🤖 Generated with Claude Code