Skip to content

[tracking] feat(kubernetes): manage vLLM and Ollama services (split) - #12736

Closed
gaveezy wants to merge 58 commits into
v1from
codex/cluster-model-services
Closed

gaveezy wants to merge 58 commits into
v1from
codex/cluster-model-services

Conversation

@gaveezy

@gaveezy gaveezy commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

Do not merge. Closed, not merged. This PR is split into 8 smaller PRs so that each one can be reviewed and merged with its own test proof. It was closed early because NVIDIA/NemoClaw limits each author to 5 open PRs, and the split PRs need those slots. This description stays the tracker. #13061, #13062 and #13063 were closed by the same limit, and each is reopened as earlier PRs merge. Nothing more will be pushed to this branch.

Its head, 99378ac87, stays the reference. The top of the stack (#13063) equals 99378ac87 merged with v1, except for the items below. This was checked against 29bb05794 and again after the stack was merged forward to 025b95a2a, with the same 25-file difference both times:

The split

v1 (29bb05794)
 ├─ #13056 fix: OpenShell rejections, teardown, lock, fixtures ── #13060 refactor: Services hook ─┐
 ├─ #13057 fix(runtime)!: bearer vLLM route filter ───────────────────────────┐                  │
 ├─ #13058 feat(services)!: Docker container limits + updatePolicy ──┐        │                  │
 └─ #13059 feat(sdk): OpenClaw/Hermes context advisory ──────────────┼────────┤                  │
               (#13056 + #13058 merged) ── #13061 SDK reconciler ── #13062 cluster services ── #13063 sandbox routing

Merge checklist

Don't cut a release between #13062 and #13063. In that window, cluster model services work, but sandboxes can't route to them yet: #13062 refuses such documents at plan.

When v1 moves, merge origin/v1 into the lowest open branch, then merge each branch into the next one up. Don't rebase or force-push.

PRs and their test proof

Each PR is one signed commit. Every branch passed the full cargo ci on the GB300 host (aarch64): tools, fmt, clippy -D warnings, build, test, schema, bundle, lifecycle. Each PR body has a red/green table that shows each new test failing without the production change. Live runs used each branch's own bundle on 2026-10-12. They are not qualification; #12732 stays open.

PR Scope cargo ci tests (+ lifecycle) Live evidence on the branch
#13056 OpenShell rejection detail, sandbox teardown, deployment-lock release, test-fixture races, images plan message 1387 (+127) none needed (unit, fake-gateway and contract tests)
#13057 bearer vLLM answers only the authenticated inference routes; openai-v2 image label 1380 (+127) Docker: in-image route tests ran in the image build (6 OK); openai-v1 image rejected at plan; 401/200 with the key; 0 completions over 38 bypass probes
#13058 Docker container.cpuLimitMillis / memoryLimitGiB and service updatePolicy 1385 (+127) Docker GPU: CpuQuota 400000, 48 GiB; a change under Preserve refused with the container unchanged; Recreate replaced it at 40 GiB
#13059 context advisory for OpenClaw and Hermes 1391 (+127) Docker plan: OpenClaw 0/2 warnings; Hermes warns at 32K and is silent at 64K
#13060 Services hook in the OpenShell and Fabric providers 1393 (+127) cargo ci live-docker 10/10; Docker inventory unchanged
#13061 SDK reconciler for cluster model storage and workloads; gated, nothing reaches it yet 1507 (+127) exercised live under #13062
#13062 nemoclaw_kubernetes_service{,_storage}: vLLM and Ollama on managed cluster gateways 1544 (+135) kind GB300: rejections before mutation, Pod security, supervisor-only NetworkPolicy, 0 route-bypass completions, named drift, Preserve/Recreate, A5 dry-run, A2 preflight (4 s, Pod kept), 15-min Unschedulable grace untainted (919 s), recovery without re-download, PVCs retained
#13063 sandboxes route to cluster services: credential source, Service grants, FQDN, port-change refusal 1573 (+138) kind GB300: OpenClaw turns on bearer vLLM and Ollama and a Hermes turn at 64K, all POST 200 from the supervisor; key in sandbox env, export, state and ConfigMaps 0/0/0/0; U1 port refusal; foreign backend refused

Where the review findings went

Findings PR
F2 (OpenShell rejection text), transport.rs:220 teardown, T1 / T1-tail (lock, ETXTBSY), N1 (executable bit), HM-4, N2 #13056
X1 and its follow-ups (route allowlist, label version, NetworkPolicy warning) #13057
CL-1 to CL-7 (Docker limits, Preserve/Recreate, help text) #13058
HM-1 (Hermes and OpenClaw context) #13059
N1b (injected-services test in the regular step) #13060
X2-* (node-fit preflight, Unschedulable grace and autoscaling, never-served Pods, untainted first apply, RBAC and PV-topology messages) #13061; end to end in #13062
M1 (OpenTofu contract tests for both resources), L1, D3n, MG-WORD-3, N2b #13062
F1 (ClusterIP grants), F8 (FQDN), T2-PINS (source owner, name and host), T5–T7, U1, MG-WORD-2 #13063

Not carried over: the legacy-field migration (aliases, deprecation warnings, intent rewrite and its docs).

The review threads on this PR stay open. Each finding's code now lives in the PR named above.

🤖 Generated with Claude Code

Managed cluster deployments rejected spec.services and required external
inference. Reuse the hosted runtime contracts with explicit cluster resources,
verified image metadata, retained model and credential volumes, and owned
Service endpoint grants through the existing SDK/provider lifecycle.

Record the compatibility baseline and pending live GPU/OpenShift qualification.
Behavioral failures were observed before implementation. cargo ci passes all
1282 native tests and 101 bundle lifecycle tests; fern check has zero errors.

Refs #12732.
@copy-pr-bot

copy-pr-bot Bot commented Oct 7, 2026

Copy link
Copy Markdown

Auto-sync is disabled for draft pull requests in this repository. Workflows must be run manually.

Contributors can view more details about this message here.

@gaveezy
gaveezy marked this pull request as ready for review October 7, 2026 09:51
@github-actions

github-actions Bot commented Oct 7, 2026

Copy link
Copy Markdown
Contributor

@kaofelix

kaofelix commented Oct 7, 2026

Copy link
Copy Markdown
Collaborator

Non-blocking review notes:

  1. Readiness polling cadence (kubernetes/services/operations.rs::wait_ready): the loop polls read() every second, and each poll re-verifies Pod identity and re-executes status.json inside the container. Over a long model-load timeout (vLLM can take many minutes), that's a lot of API-server and exec churn. Polling less often once the Pod is Running would cut that load without delaying failure detection.
  2. Regex recompilation (kubernetes/services/mod.rs, StorageSpec::validate / Spec::validate): each call compiles its patterns with regex::Regex::new(...), and validation runs on every decode, plan and read. Cache the compiled regexes in std::sync::LazyLock statics, as nemoclaw-runtime/src/schema.rs already does for its validator.
  3. Minor (nemoclaw-provider/src/cluster_services.rs::plan): the port-change branch calls specification(prior)? twice; the second call can reuse the first result.
  4. Namespace-wide ingress (kubernetes/services/resources.rs NetworkPolicy): ingress.from: [{"podSelector": {}}] lets any pod in the namespace reach the model. That's intended, since the gateway needs access, but docs/kubernetes.md should say so.

@kaofelix
kaofelix self-requested a review October 7, 2026 13:45
@gaveezy
gaveezy marked this pull request as draft October 7, 2026 13:46
@gaveezy gaveezy self-assigned this Oct 7, 2026
@gaveezy

gaveezy commented Oct 7, 2026

Copy link
Copy Markdown
Contributor Author

marking as draft for now while verifying on the real deployment

gaveezy added 16 commits October 7, 2026 15:05
Align sandbox and provider grants and use resolvable cluster endpoints. Preserve ownership through interrupted creates and runtime updates, narrow model ingress, improve readiness and rejection diagnostics, and validate declared capacity before deployment.

Regression tests cover the reported failures and post-exec identity races. cargo ci passes 1337 native tests, four doctests, and 101 packaged lifecycle tests; Fern validation reports zero errors. Live GPU retesting remains pending.

Refs #12732.
Integrate v1 at 2cfa33b. Preserve cluster readiness, retained storage, and endpoint provenance through the provider resource definitions, and retain compiled observation checks and state generation allocation.

Validation: cargo ci passed 1,359 native tests, four doctests, and 104 packaged lifecycle tests. Fern validation passed with zero errors.
Dry-run replacement Pods and ConfigMaps before deleting the running workload, and cover unchanged active Pods plus saved receipts after interrupted updates. Align Docker OpenClaw examples at 32768 tokens, correct operator-report provenance, document native invocation and admission limits, and use existing interpreters in two more test fixtures.

Validation: A5 regression observed failing before implementation; cargo ci passed 1362 native tests, four doctests, and 104 packaged lifecycle tests. Fern check passed with zero errors.
Merge v1 at 98984b0. Preserve both dependency sets and route cluster credential and profile checks through the extracted OpenShell provider without an SDK production dependency.

Validated with the provider library compile check, all 24 OpenShell provider tests, and both cluster service adapter tests. Existing profile, grant, and teardown regression assertions are retained.
Merge v1 at ecae3f4. Keep platform and OpenShell resource ownership separate, retain cluster identity callbacks in both gateway clients, and package an OpenShell entry point with NemoClaw service checks.

Update affected state and schema fixtures to the upstream resource names and retain earlier-state refusal. Workspace compilation, both provider suites, and 16 SDK runtime tests passed. Add a packaged credential-refresh regression for the provider entry point.
Merge v1 at 8b11a3a. Retain semantic cluster-source validation while adopting typed sandbox and profile inputs. Keep both backend dependencies, update native-state fixtures, and check cluster network grants survive the typed graph.

Focused export, cluster compilation, and OpenShell provider tests passed. Full CI follows with the updated bundle.
Exercise the configured gateway client through registration and refresh in regular Cargo tests. Check the key reaches its declared credential slot while state and metadata retain only its reference, and preserve callbacks across reconnect.

Check the real adapter rejects owner, endpoint, Service-host, and authentication changes before Kubernetes credential lookup. Both tests pass in cargo test --workspace cluster_credentials and catch six deliberate routing, key, and validation regressions. Production behavior is unchanged.
cv added a commit that referenced this pull request Oct 8, 2026
Closes #12785. Part of #12782.

## Failure

`nemoclaw_kubernetes_storage`, `nemoclaw_kubernetes_auth` and
`nemoclaw_kubernetes_gateway` were the last `nemoclaw` types that took
one SDK-compiled `spec` string. An HCL author could not declare a
managed Kubernetes or OpenShift gateway without reproducing the SDK's
internal JSON.

## Decision

- **Attributes:** the three resources take the cluster target and
identity as attributes: `name`, `compute_driver` (`kubernetes` or
`openshift`), `endpoint`, `kubeconfig_env`, `context`, `namespace`,
`authentication_profile` and an optional `environment` list.
- **Identity:** `owner` and `generation` are optional and computed,
generated on create. Generated graphs keep supplying the SDK's values.
- **Typed list:** `environment` is a `list(string)` carried through the
existing structured adapter. The `nemoclaw` provider now serves types
with structured inputs through that adapter.
- **Validation:** invalid values are reported at their attribute without
echoing them. The backend rebuilds the same internal specification from
the attributes, so cluster objects and receipts are unchanged. A changed
target or identity still fails planning and retains the resources.
- **SDK, compiling and reading state:** the SDK compiles the attributes
and reads them back from OpenTofu state, including the `environment`
list.
- **SDK, comparing intent:** teardown and runtime binding checks compare
the typed attributes, and plan identity checks cover the new ones.
Export now checks every typed resource against intent, not only those
with a `spec`. Since #12831, managed gateways and their storage had
dropped out of that export check; this restores it.
- **Docs:** the provider guide lists the attributes. It says the three
resources must share one `owner`, because their receipt is keyed by
owner and name. `docs/limits.md` and the provider guide no longer list
compiled-`spec` types; no `nemoclaw` type takes one now.

## Validation

- **New tests:**
- A provider schema test checks the typed attributes, generated identity
and the `environment` list on all three resources.
- An SDK test round-trips each compiled Kubernetes and OpenShift
resource through its attributes and rejects invalid driver, namespace,
kubeconfig variable, endpoint, profile and reserved environment values.
- An end-to-end test writes `nemoclaw_kubernetes_storage` in HCL and
plans it through pinned OpenTofu without a cluster. It also rejects an
invalid namespace at its attribute.
- **Updated tests:** the existing Kubernetes compile, runtime binding,
teardown and refresh tests now use the attributes.
- **Suites:**
  - `nemoclaw-sdk`, `nemoclaw-provider` and `nemoclaw-build` tests pass.
  - The standalone and production-provider OpenTofu tests pass.
- Workspace clippy at `-D warnings`, fmt and the schema check are clean.
- **Not done:** I did not run the live cluster tests.

The draft #12736 already conflicts with `v1`. It also edits
`nemoclaw-provider/src/provider.rs`, `services/validation.rs` and
`docs/provider.md`, so it will need to follow these attributes.

## Follow-up

The first CI run failed five Helm recovery lifecycle tests with
"observation is incomplete". The resource adapter requires every
attribute in an observation, and a Kubernetes row without an
`environment` list left out `environment_json`. Observations now report
it as empty. A new unit test checks that each Kubernetes observation
reports every attribute; it failed before the fix. The 14 Helm recovery
tests and the SDK's Kubernetes and export tests pass against a rebuilt
bundle.
Merge v1 while preserving managed cluster callbacks in the bundled OpenShell and Fabric providers, SDK-owned runtime image requirements, and typed upstream resource settings. Retain the latest authored-HCL lifecycle tests.
Preserve cluster context and recovery guidance while adopting the upstream wording, bundle verification cache, and lifecycle CI changes.
gaveezy and others added 11 commits October 12, 2026 11:00
…llbacks

Only the bundled Fabric provider constructs FabricProvider::with_services,
and only the ignored lifecycle test exercised it. A regression that
ignored the injected services and used the default Docker callbacks
passed every test in the regular step and failed only in lifecycle.

Add a unit test that creates a cluster provider profile in the fake
gateway through a counting stub, configures FabricProvider::with_services
with that stub, and reads the profile through the provider's gateway
client, which Fabric resources and data sources use to observe sandbox
parents. The read must succeed and call the stub's cluster-source
validation and address lookup. RawValue is private to tf-provider, so a
test outside the crate cannot call the provider's resources in process;
the test therefore lives in provider.rs, beside the client field.

Validation: the test passes. With with_services mutated to use
Arc::default(), it fails with Err(BindingMismatch) while the other 18
fabric-provider library tests pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Hai Nguyen <haingu@nvidia.com>
Three ignored tests said "requires explicit verified NEMOCLAW_TEST_BUNDLE",
a wording the rest of the workspace no longer uses; upstream writes
"requires a verified NEMOCLAW_TEST_BUNDLE". Use that wording and keep each
reason's suffix.

Validation: git grep finds no "explicit verified NEMOCLAW" in crates. The
lifecycle profile selects these tests by name, so its selection is
unchanged; the two cluster_credentials bundled tests pass with a bundle
built from this branch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Hai Nguyen <haingu@nvidia.com>
The ClusterReads comment said it replaces only cluster reads and Pod exec,
but it returns a fixed key without resolving it and a fixed Service
address, and nothing in it models Pod exec. Two tests asserted that the
fixture's exec_calls stayed empty although they create no sandbox; the
fixture records ExecSandbox calls only for an existing sandbox, so those
assertions could not fail. The Fabric bundled test rechecked the
in-process resolution counter after an out-of-process tofu plan, which
cannot change it.

Describe what ClusterReads replaces, drop the two vacuous exec_calls
assertions, and check the resolution counter before the plan with a note
that the bundled provider runs out of process.

Validation: cluster_credentials:: with --include-ignored and a bundle
built from this branch passes 3 of 3.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Hai Nguyen <haingu@nvidia.com>
The OpenTofu contract for the cluster model resources never changed
cluster objects between applies. The drift errors for a substituted Pod
UID or a missing Service were covered only by in-process SDK tests, so
disabling the Pod UID check left the shipped contract tests passing.

Add a separate test per backend that applies the model, substitutes the
Pod with a foreign UID, then deletes the Service. Each tofu plan must fail
naming the object and the binding field ("metadata.uid", "object
presence") while terraform.tfstate stays byte-identical; after the objects
are restored, plan reports no changes. The tests sit apart from lifecycle()
so other changes to that scenario do not conflict with them.

Validation: with a bundle built from this branch, the four
kubernetes_models contract tests pass; the new ones took 4.5 s (vLLM) and
4.3 s (Ollama) under the lifecycle profile at load average 25. With the
Pod UID check in operations.rs disabled, or a missing Service skipped like
a missing Pod, both new tests fail and both lifecycle tests still pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Hai Nguyen <haingu@nvidia.com>
testing.md and integration-tests.md said the lifecycle profile selects
Helm recovery tests in the nemoclaw-sdk library. #13002 moved those to
nemoclaw-e2e's helm_recovery module, and the only SDK test the profile now
selects is plan_and_apply_refuse_cluster_port_changes_with_separate_state_files.
That test builds its saved OpenTofu states from SDK internals, so it stays
in the SDK instead of moving behind test-scenarios hooks.

Name that test, its purpose and its run command, and list helm_recovery
with the other nemoclaw-e2e system-test modules.

Validation: .config/nextest.toml selects that test by name and the e2e
helm_recovery module by prefix. The test passes with a bundle built from
this branch. nemoclaw-build docs reports no link errors.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Hai Nguyen <haingu@nvidia.com>
The nemoclaw-provider::contract budget comment said 29 tests; the binary
had 31 lifecycle tests at 487cfc8 and has 33 with the drift tests. The
29 belongs to the runs that set the budget, so keep it as the measurement
and state the current count. The budget numbers are unchanged: raising
them needs CI timing, which this change does not have.

Validation: 33 #[ignore] tests in crates/nemoclaw-provider/tests/contract,
and cargo nextest --profile lifecycle --run-ignored only selects them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Hai Nguyen <haingu@nvidia.com>
The rollout fix lets the default Preserve policy replace cluster Pods that are missing, terminal, never scheduled, or never started their runtime container. The update policy field docs, the generated schema and configuration reference, usage.md, and inference.md still said Preserve refuses any nonterminal or pending Pod.

Describe Preserve as refusing replacement of a Docker container that is running or a cluster Pod that may be serving, and link inference.md to the full rule in kubernetes.md.

Validation: nemoclaw-build schema regenerated the schema and configuration reference; schema --check passes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Hai Nguyen <haingu@nvidia.com>
The architecture check now reports a wrong-platform cluster runtime image by itself, so the label mismatch message no longer covers platform. Name only the required labels. Also correct the contract binary test count in the budget comment to 38.

Validation: cargo test -p nemoclaw-fabric (9 passed) and the SDK image_metadata tests (9 passed).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Hai Nguyen <haingu@nvidia.com>
The real-application route test failed every vLLM image build: building vLLM's argument parser resolves its platform, and Docker build steps have no GPU, so vLLM raised "Failed to infer device type". Earlier runs passed only because this host's default Docker runtime is nvidia and the image sets NVIDIA_VISIBLE_DEVICES=all.

Select vLLM's CPU platform before importing vLLM. The route tests build the FastAPI application and start no engine, so the platform does not affect them.

Validation: in nc-prototype-vllm with --runtime=runc (no GPU), all 6 tests pass; with the nvidia runtime, all 6 pass; with a pass-through filter in place of the route module, 371 subtests fail.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Hai Nguyen <haingu@nvidia.com>
The Hermes section implied that serving.contextTokens of 64000 or more is enough. Hermes still cannot read the served window through the sandbox proxy at that size, so it assumes its built-in 131,072-token window for Qwen models and longer conversations can exceed the server limit before it compacts them.

State that the overrun also applies at 65536. A complete fix needs the Fabric Hermes adapter to pass the route's context length.

Validation: documentation only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Hai Nguyen <haingu@nvidia.com>
The bearer route filter now passes only listed inference requests, but images kept org.nemoclaw.inference.routes=openai-v1, the label of the earlier filter that passed every /v1 path. Image validation therefore accepted an earlier image whose filter still exposed management routes such as /v1/load_lora_adapter when the owner enabled them.

Label the narrowed filter openai-v2 in the vLLM, vLLM AMD64, and qwen38 images, require that value in SDK image validation, and update fixtures and documentation. openai-v1 images are now rejected before the runtime starts.

Validation: the SDK route-label test fails when validation still requires openai-v1 and passes with openai-v2; SDK image_metadata (9), vLLM installer (5), provider runtime_image (2), and SDK bearer integration (2) tests pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Hai Nguyen <haingu@nvidia.com>
@cv cv added the v1 NemoClaw v1 branch label Oct 12, 2026
@gaveezy gaveezy changed the title feat(kubernetes): manage vLLM and Ollama services [tracking] feat(kubernetes): manage vLLM and Ollama services (split) Oct 13, 2026
@gaveezy gaveezy closed this Oct 13, 2026
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
…13081)

Adds 19 tests for a managed Kubernetes deployment whose apply or destroy
is cancelled or fails part-way: 12 in the SDK's `integration` binary,
which run `Deployment` over a scripted OpenTofu, and 7 in
`nemoclaw-e2e`'s `helm_recovery` module, which run `destroy` through the
bundled OpenTofu and Helm provider. They cover scenarios 5, 6 and 7 and
the deleted-receipt half of 4 on [the list in
#12731](#12731 (comment)).
Scenarios 1 to 3, 8 to 11 and the corrupt-receipt half of 4 are in
#12825 and #12909; scenario 12 (live) is not in this change. Production
code is unchanged. `docs/contributing/testing.md` and
`integration-tests.md` describe the new tests.

## Failure

A Kubernetes apply or destroy can stop after OpenTofu has created or
deleted resources: the user cancels, OpenTofu fails, or the host exits.
`docs/design/scope.md` says the SDK then refuses what it cannot verify,
keeps enough state to recover, and keeps retained storage. #12731 asks
for tests of these rules. Each item names the regression a test is
written to catch.

SDK tests, apply:
- The record must mark an apply unfinished before OpenTofu starts. A
later save leaves resources that no record covers if the host exits
first.
- Until the same document settles the stage, a revised document, a
destroy and an export must be refused, and a refusal must not run
OpenTofu or change the record.
- A gateway connection that fails after the runtime stage settled must
keep its error class, must not start the OpenShell stage, and must not
leave the apply unfinished. A cancel while it waits for the cluster must
end it.

SDK tests, destroy:
- A cancelled destroy must block apply until destroy runs again. Its
retry must not reconnect once the OpenShell stage is done and must
report the retained storage and workspace.
- A retry whose OpenTofu state was lost must be refused instead of
reported as finished, and a destroy plan that deletes the retained
storage must be refused before anything is applied.

e2e tests, destroy:
- A deleted or truncated receipt must stop destroy and its preview while
OpenTofu plans, with nothing changed, the damaged receipt included. A
bound storage read as absent, or a receipt recreated empty, would let
destroy go on without a verified identity.
- A Helm release record that OpenTofu does not bind must stop destroy
before it deletes any issuer object: the release may still run, and its
gateway authenticates against that issuer.
- An authentication failure (HTTP 401) must stop destroy before
planning, after the saved plan, and when only the issuer's ConfigMaps
are read. The Helm provider drops its release binding under a 401, so
the SDK must restore it, and a retry must finish.
- A second destroy must launch no plan or apply, and a cancel at the
first refresh must return without waiting for the refresh to fail.

## Decision

The SDK alone decides the stage order, the unfinished-apply and
unfinished-destroy state it saves, and what it refuses, so its rules are
tested without OpenTofu. `tests/support/scripted_tofu.rs` writes a
bundle whose manifest verifies and whose `libexec/tofu` is a short shell
script. The script logs each call, replays canned `show -json` state and
plans, and ends an apply as a control file says: succeed, fail, or block
until the SDK interrupts it. A test cancels at a chosen progress event,
then asks the public operations what the SDK kept. It compares the saved
record's text before and after and decodes the record only for the
resource generations that canned bindings must carry. These tests run in
the `test` step and need no bundle.

What depends on OpenTofu and the providers (refresh, plan, state
persistence, the Kubernetes provider's own observations, the Helm
provider's handling of a rejected lookup, interrupts) cannot be scripted
honestly, so the e2e tests run against the bundled ones and the
in-memory Kubernetes API that the module's five tests already use. The
harness gains a request log, a 401 fault (on every request, or on
ConfigMap reads only), `prepare()` and `import_release()` that split
`create()`, and a `Snapshot`. The `Snapshot` compares the OpenTofu
state's resources and lineage, the bindings, the cluster objects, the
durable files, the receipt's bytes, and the writes the cluster received
whether or not a fault rejected them, so a delete sent under a 401
shows. The tests copy, delete, truncate and restore the receipt's bytes
and never decode it, and they read no `intent.json`. Each test that
makes destroy fail or stop ends by removing the cause, if any, and
running destroy again, which must finish. The five existing tests keep
their assertions; they now read the write count from the request log and
use the new `failing_after_plan` and `assert_export_refused` helpers.

These are characterization tests: they pass on unchanged production
code, so there is no failing test to observe first. Mutation probes
(below) show that each test fails when the behavior it guards breaks.

## Coverage

SDK, `crates/nemoclaw-sdk/tests/kubernetes_interruption.rs` (12 tests,
names shortened):

| Test | Checks |
|---|---|
| `cancelling_the_first_kubernetes_runtime_apply_...` | A cancel while
OpenTofu applies the runtime stage: the record was saved before OpenTofu
started; plan and apply of another namespace, destroy and export are
refused; the same document resumes |
| `a_failed_first_kubernetes_runtime_apply_...` | The same after
OpenTofu fails, with its diagnostic kept |
| `a_revised_document_after_an_interrupted_kubernetes_apply_...` | The
refusal runs no plan or apply and changes neither the record nor the
OpenShell stage's state |
| `cancelling_before_the_runtime_mutation_...` | A cancel before the
runtime plan saves no record, so another document is not refused |
| `cancelling_an_unchanged_kubernetes_runtime_apply_...` | An unchanged
runtime stage still applies, sets no unfinished marker, and keeps the
saved record |
| `cancelling_between_the_stages_..._while_the_cluster_is_silent_...` |
A cancel while the gateway connection waits ends the apply, starts no
OpenShell stage, and leaves the runtime settled |
| `a_missing_kubeconfig_...`, `a_missing_receipt_...`,
`a_refused_connection_...` | The connection error keeps its class
(`Authentication`, `Incomplete`, `Transport`), no OpenShell stage
starts, and a revised document is not refused as unfinished |
| `an_interrupted_kubernetes_destroy_blocks_apply_and_its_retry_...` |
apply, plan and export are refused until destroy runs again; the retry
makes no connection, plans no finished stage, applies the runtime stage
once, and reports the retained storage and workspace |
|
`a_kubernetes_destroy_retry_is_refused_when_the_runtime_state_was_lost`
| A retry whose runtime state is missing is refused and changes nothing
|
| `a_kubernetes_destroy_plan_that_deletes_retained_storage_...` | The
plan is refused before the record is marked destroying and before any
apply |

e2e, `crates/nemoclaw-e2e/tests/helm_recovery/` (7 tests, names
shortened):

| Test | Checks |
|---|---|
|
`receipt::a_deleted_or_truncated_receipt_stops_destroy_while_planning_...`
| Destroy and its preview fail while OpenTofu plans with an incomplete
observation and change no state, binding, object, write or the receipt;
the restored receipt lets destroy finish |
|
`release_record::destroy_keeps_the_issuer_while_a_release_record_has_no_binding_...`
| Destroy stops at authentication's removal with no write; apply and
export stay refused; once the record is gone destroy removes the issuer
and keeps storage |
| `destroy_faults::a_second_destroy_after_completion_...` | A second
destroy and its preview report the retained storage, launch no plan or
apply, and change nothing |
| `destroy_faults::an_authentication_failure_before_planning_...` |
Destroy and its preview stop on the 401; nothing changes and no write is
attempted; a retry finishes |
| `destroy_faults::an_authentication_failure_after_the_saved_plan_...` |
The dropped Helm binding is restored, no write is attempted, and the
retry consumes the recovery checkpoint |
| `destroy_faults::an_authentication_failure_reading_the_issuer_...` |
With only ConfigMap reads rejected, Helm uninstalls the release and the
issuer's objects stay; a retry removes them |
| `destroy_faults::cancelling_at_the_first_refresh_...` | A cancel
returns `Cancelled` with a healthy API and returns well before an
unreachable API would fail the refresh; state, bindings, objects and
writes are unchanged |

## Validation

Run on `3a00cbda0e`, based on v1 at `29bb057949`, macOS arm64.

- `cargo ci`: passed in 478 s: fmt, clippy, build, test (1356 passed),
schema, bundle and lifecycle (134 passed).
- Timing in `cargo ci` (budgets apply on Linux CI only): the `test` step
took 29.0 s for 1356 tests (budget 45 s), and the 12 SDK tests sum to 32
s with 8 test threads, the slowest 4.0 s (limit 8 s). The 12 SDK tests
alone run in about 5 s. In the `lifecycle` step the 12 `helm_recovery`
tests sum to 63.7 s next to the other modules, the slowest 14.0 s (an
existing test with an unreachable API); the new e2e tests take 2.6 to
4.4 s each.
- `cargo run -p nemoclaw-build -- docs --check` and `fern check`:
passed; the one fern warning also appears on v1.
- Windows approximation: with `#![cfg(unix)]` replaced by
`#![cfg(any())]` in both new SDK files, `cargo clippy -p nemoclaw-sdk
--tests -- -D warnings` is clean. This checks unused items and imports;
it is not a Windows build.
- Linux aarch64: an earlier revision ran in an Ubuntu 24.04 container
(dash as `/bin/sh`, a `linux_arm64` bundle built from the same sources).
Under nextest the SDK tests took 0.06 to 0.19 s each over 35 rounds
without a failure, and the e2e tests 22 rounds with one failure, the
cancel test at 2 CPUs under load, which led to the tolerance described
below. The run also found the lock race described under Observations;
this revision fixes it for the SDK tests and documents it for the e2e
tests. This revision was not rerun on Linux.

Mutation probes: temporary changes to production code, each reverted so
the diff holds none. SDK tests: 28 changes, 27 make at least one test
fail, and each of the 12 tests fails under at least one. They include a
marker that is never saved, saved after OpenTofu returns, or saved after
it even on failure; a marker that ignores a changed document; a settled
apply that never clears the marker; a failed apply that clears it; a
destroy that does not block apply, retries with a connection, applies a
plan that deletes retained storage, or accepts lost state; a gateway
connection that ignores a cancel, checks it only on entry, or lets the
OpenShell stage run after a failure, also for a transport error; and a
revision refused only when the OpenShell stage has no bindings. The
survivor, a destroy that does not save its record before the stages, is
equivalent for these flows: the same destroy saves it again before it
returns. e2e tests: 20 changes, 17 make at least one test fail, and each
of the 7 new tests fails under at least one; provider-side changes ran
through a debug provider swapped into a copy of the bundle with its
manifest hash updated. They include a bound storage read as absent, an
unreadable receipt reported as another error class, a missing receipt
recreated on read, the issuer removed while a release record exists, a
delete sent before the reads, a 401 read as absence or as a permission
failure, a failed issuer read taken as absence, the early return for a
destroyed deployment dropped, the Helm binding restore skipped, a
destroying record saved before planning, a cancel not observed while
OpenTofu runs, and `apply` allowed during an unfinished destroy. Three
survive: an unreadable receipt read as a missing one (destroy stops
either way; only the number of incomplete observations differs, which no
test pins); a destroy that does not save its record before the stages
(equivalent, as above); and no interrupt sent on cancel with the 5 s
kill kept (see the next section).

## Limits of this evidence

- A script stands in for OpenTofu in the SDK tests. They show what the
SDK saves and refuses for the plans and states the tests write, not what
OpenTofu or a provider produces. The script reports no bindings after a
settled runtime stage, so a revised document that no unfinished state
refuses is not shown to be accepted by a deployment with bindings, which
also compares the revision with them. The e2e tests cover destroy only;
the apply-side cases have no real-OpenTofu counterpart here.
- The tests pin the current rule that a deployment whose first runtime
apply failed or was cancelled cannot be destroyed or revised until the
same document settles the stage (`IDs were not saved`).
`docs/usage.md:294` says that after a failed runtime apply, revised
intent or teardown can proceed, which this rule refuses, and
`docs/troubleshooting.md:41` names a message that no code emits; both
are corrected separately.
- The fake Kubernetes API serves plain HTTP on loopback. It shows no
RBAC, TLS or token validation, and 429, 503 and 504 are not injected
because the client retries them for minutes. It holds no
PersistentVolumeClaims, so retained state in the e2e tests is the
Namespace, the KEK Secret and the receipt; scenario 12 covers the claims
on Kind.
- The 401 tests depend on Helm provider 3.3.0 treating a rejected
release lookup as an absent release: it drops the binding and sends no
delete. A provider upgrade can change them.
- The cancel test bounds the return at 8 s from the cancel: the SDK
kills OpenTofu after 5 s without an answer to the interrupt, and an
unreachable API fails the refresh after about 10.5 s (measured on macOS
arm64). OpenTofu normally exits within 0.1 s of the interrupt. On a
loaded host the kill is reached, and the OpenTofu it kills leaves
`.terraform.tfstate.lock.info`, which the file comparison ignores, so a
regression that stops sending the interrupt but keeps the kill is not
detected. If the refresh's own timeout fell below the bound, the
unreachable row would stop testing the cancel. OpenTofu may also persist
its state when interrupted (the serial rises and the check results are
re-sorted), so the state comparison covers resources and lineage, not
bytes.
- Cancellation is tested at progress events, not by killing the host, so
"the record is saved before OpenTofu starts" is shown by what the script
finds when it starts.
- The new files are `cfg(unix)`, so Windows runs none of them. Linux
amd64 was not run. Not covered: a cancel during the OpenShell stage,
destroy with the gateway down, a delete that Kubernetes rejects
part-way, and the live cluster behavior of scenario 12.

## Observations for maintainers

- Observed, not pinned: with a receipt written before the issuer was
recorded (storage objects only), destroy returns `Destroyed`, uninstalls
the Helm release, retires the authentication resource without deleting
anything, and leaves the six issuer objects in the cluster. The receipt
records none of them, and a second destroy reports nothing. An
unrecorded issuer is not confirmed absence, so this looks like a defect;
no test pins it.
- With a Helm release record that OpenTofu does not bind, `plan_destroy`
lists the issuer's removal, and `destroy` then stops before deleting it.
The preview does not run the removal's own checks.
- `Progress::MutationStarted` is emitted for every `tofu apply`,
including the destroys above that delete nothing, and as soon as the
process exists, before it prints anything, so a cancel at that event
interrupts the child before it writes. The SDK tests cancel at the first
resource event instead.
- Under `cargo test`, which runs tests as threads of one process, a
child that one thread forks keeps another test's deployment lock until
it executes. On Linux the 9 SDK tests of an earlier revision then failed
with "another operation holds the deployment lock" in 14 of 50 rounds,
and the five existing e2e tests alone in 1 of 10 rounds at 5 threads
(the twelve in 7 of 10 at 12 threads); macOS and nextest, which runs
each test in its own process, showed none. A process-wide mutex now
serializes the scripted SDK tests, and the documented e2e command passes
`--test-threads=4`. The durable fix is to release the lock when `Store`
drops, which the draft #12736 adds.
- With no receipt, the gateway connection fails at once, and
`tokio::select!` picks the failure or the cancel at random. The SDK test
of a cancel during the connection therefore seeds a receipt and cancels
once the cluster has accepted the request.

Refs #12731

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
cv pushed a commit that referenced this pull request Oct 13, 2026
…odel budget (#13059)

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.contextTokens` could not hold the agent's prompt, and said
nothing:

- The managed Ollama examples served `8192` tokens. One measured initial
OpenClaw prompt used 19,947 tokens before any reply, so the first turn
could overflow the server or be silently truncated.
- The pinned Hermes Agent requires a context window of at least 64,000
tokens (`MINIMUM_CONTEXT_LENGTH` at the `HERMES_REVISION` in
`image/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 #12736.

## What changes

- **SDK** (`deployment/mod.rs`): a new `Progress::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:
- an OpenClaw route's effective `contextWindow` (default `32768` at the
pinned adapter revision, or
`overrides.settings.model_metadata.contextWindow`) exceeds the service's
`serving.contextTokens`;
- the smaller of the two is below `20000` plus the effective reply
allowance (`overrides.settings.model_metadata.maxTokens`, else
`overrides.maxTokens`, else `4096`);
- `settings.model_metadata` is not an object, or its `contextWindow` or
`maxTokens` is not a positive integer, so the budget cannot be assessed
(the value is not echoed and no default is substituted);
- a Hermes route uses a service with `serving.contextTokens` below
`64000` (`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 a `Warnings:` section in text output and as a `warnings` array 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.yaml` and
`examples/managed-ollama-gpu.yaml` serve `32768` tokens and set the
route's `model_metadata.contextWindow` to `32768`.
- **Docs:** `docs/inference.md` describes the budget rules and adds
"Size the Context for Hermes"; `docs/reference/cli.md` documents the
`warnings` field and that warnings survive `--progress off` and
failures.

## Breaking or user-visible changes

- Plan and apply can print new warnings. Text output gains a `Warnings:`
section, and JSON results and JSON errors gain a `warnings` array
(omitted when empty; it does not change `complete`).
- Of the shipped examples, only `examples/managed-hermes.yaml`
(unchanged here) now warns, because its Hermes route uses managed Ollama
at `contextTokens: 8192`.
- Rust API: `nemoclaw_sdk::Progress` gains the `Warning { message }`
variant, so exhaustive matches on `Progress` need a new arm.

## Test proof

**`cargo ci`** on linux_arm64 at this commit (the full `CI / Bundle`
step list, lifecycle with `NEMOCLAW_TEST_BUNDLE` from the bundle step):

```
ok tools in 0s
ok fmt in 1s
ok clippy in 22s
ok build in 42s
     Summary [  19.195s] 1391 tests run: 1391 passed, 174 skipped
ok test in 25s
ok schema in 0s
ok bundle in 25s
     Summary [ 403.614s] 127 tests run: 127 passed (1 slow), 48 skipped
ok lifecycle in 409s
All selected CI steps passed in 526s
```

The timing report flagged the lifecycle wall time (403.6 s against 300
s) and the `nemoclaw-provider::contract` and
`openshell-provider::contract` sums. 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.

| Test | Base production code | Only the `Progress::Warning` variant
added | Branch |
|---|---|---|---|
| 10 advisory tests that expect a warning
(`native_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`) |
does not compile: `E0599 no variant named Warning found for enum
deployment::Progress` | **fail** (`left: 0`, expected 1 or 2 warnings) |
pass |
|
`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_metadata`
| does not compile (same error) | pass: they assert that no warning is
emitted. With the advisory present, both **fail** under boundary mutants
(`context <= 64000`, `contextWindow >= contextTokens`) | pass |
|
`formatting::tests::warnings_survive_hidden_progress_and_successful_or_failed_json_output`
| does not compile (`E0599`, 3 sites) | with the CLI ignoring
`Progress::Warning` and `formatting.rs` at base: **fail** (text output
has no warning) | pass |
|
`progress::model::tests::warnings_are_durable_without_marking_work_as_active`
| does not compile | with the CLI ignoring `Progress::Warning`: **fail**
(`Option::unwrap()` on `None`) | pass |

Commands: `cargo nextest run --locked -p nemoclaw-sdk --lib -E
'test(/^deployment::context_warnings::/)'` and `cargo 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 the `cargo ci`
test 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`:

| Example | `v1` (`contextTokens: 8192`) | This branch (`32768`) |
|---|---|---|
| `examples/managed-ollama.yaml` | 2 warnings (route window 32768
exceeds 8192; 8192 < 24096 budget) | 0 |
| `examples/managed-ollama-gpu.yaml` | 1 warning (8192 < 22048 budget) |
0 |

Across every file under `examples/` (credential variables set to dummy
values), only `examples/managed-hermes.yaml` warns on this branch.

**Docs.** `cargo run -p nemoclaw-build -- docs --check` passes (local
links and anchors).

**Lifecycle-only tests.** This PR adds none. The existing lifecycle
suite passed 127/127, including the 9 `nemoclaw-e2e` `remote_service`
tests that plan and apply Docker managed vLLM and Ollama services.

## Depends on / merge order

- Base: `v1` (29bb057). No dependencies; merges in parallel with
#13056, #13057 and #13058.
- It shares `docs/inference.md` with #13057 and #13058, and
`crates/nemoclaw-cli/src/formatting.rs` with #13058. `git merge-tree` of
this branch with the PR-1, PR-2, PR-3 and PR-5 slices reports no
conflicts.
- #13062 needs this PR in `v1`: its NetworkPolicy warning uses
`Progress::Warning`. When #13062 adds managed cluster services and the
cluster inference design doc, it extends this PR's `docs/inference.md`
text to Kubernetes and adds the operator-report note to
`docs/limits.md`. #13063 adds the cluster examples back to the advisory
tests.

### Live evidence (not qualification; #12732 stays open)

`split/4-context-advisory` @ `4fda90b4f`, this branch's
`dist/linux_arm64` bundle (`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) or
`examples/managed-hermes.yaml` (Hermes) with:
- a fresh UID, endpoint and subnet, and profile `gb300`;
- the local `nc-prototype-ollama@sha256:dea377de…`;
- OpenClaw and Hermes agent images built from `split/8` (`image/` is
identical to `v1`), 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 with `Plan incomplete · 6 known resource
changes` (no gateway yet).

| Case | `contextTokens` / route `contextWindow` | Text `Warning:` lines
| JSON `warnings` |
|---|---|---|---|
| OpenClaw, shipped example | 32768 / 32768 | 0 | 0 |
| OpenClaw, service at 8192 | 8192 / 32768 | 2 | 2 |
| Hermes, shipped example | 8192 / – | 1 | 1 |
| Hermes, 32K | 32768 / – | 1 | 1 |
| Hermes, 64K | 65536 / – | 0 | 0 |

The 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](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
cv deleted the codex/cluster-model-services branch November 21, 2026 20:43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

v1 NemoClaw v1 branch

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants