Repository navigation
test(sdk): pin Kubernetes recovery behavior under injected failures - #12909
Merged
Merged
Conversation
Add 40 tests: 30 for how the SDK's Kubernetes operations behave when the cluster API fails or an earlier run was interrupted, 8 for the fault helper they use, and 2 for document validation and the plan check. The failures are HTTP 401, 403 and 500, a dropped connection, a lost create response, a corrupt receipt, expired development certificates, a changed OpenShift range, and a plan that replaces a bound resource. A fault-injecting wrapper around the fake Kubernetes API logs every request, and Snapshot checks that objects and state files are unchanged. The tests pass on unchanged production code, so they pin it; 25 temporary production changes each made at least one of them fail. One OpenTofu test is renamed and also asserts that a create that returns state with an error is tainted and that the next plan is delete plus create. Refs #12731. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Contributor
…ction-recovery # Conflicts: # crates/nemoclaw-provider/tests/contract/provider_protocol.rs # crates/nemoclaw-sdk/tests/main.rs # crates/test-support/kube_api.rs
6 tasks
8 tasks
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 <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Adds 40 tests: 30 for how the SDK's Kubernetes operations behave when the cluster API fails or an earlier run was interrupted, 8 for the fault helper that they use, and 2 for document validation and the plan check. It also renames and extends one OpenTofu test. Together they cover scenarios 2, 3, 8, 9, 10 and 11, and the corrupt-receipt half of 4, on the list in #12731; scenario 1 is done in #12825. Scenarios 5, 6, 7 and 12 and the deleted-receipt half of 4 are not in this change. Production code is unchanged;
src/deployment/plan.rsgains only a#[cfg(test)]module.Failure
Applying the storage and authentication resources creates a Namespace, a KEK Secret and a development issuer (six objects) in the user's cluster and records each by UID in a local receipt.
docs/design/architecture.mdsays a failed or incomplete observation stops and preserves the prior binding, and that ownership is checked during observation and again before mutation. #12731 asks to verify that authentication, transport and incomplete-observation failures preserve resource bindings and persistent state, and that ownership is verified before recovery changes resources. The tests group this as three invariants, each with a regression they are written to catch:Nonewould pass as absence (the gateway StatefulSet, an issuer object during teardown, the Agent Sandbox CRD), and an answer without auidwould pass as an identity.Decision
Most tests call
OperationsandDevelopmentagainst the fake Kubernetes API that SDK tests already use, wrapped bytests/support/kube_faults.rs. A rule decides per request whether to fail it with an HTTP status or a dropped connection, to apply a write and then drop the connection (a lost response), or to apply it and answer without the object'suid. The wrapper logs every request, andSnapshotcompares the cluster objects and the contents of every state file before and after.check_planand document validation are tested directly.kube_api.rschanges only by makingstatuspublic. The older fault tests inkubernetes_storage.rsandkubernetes_operations.rskeep their own fixtures; moving them ontokube_faults.rsis a separate change.The tests are characterization tests: they pass on the unchanged production code, so they pin current behavior and need no production change. No behavior changes, so there is no failing test to observe first; instead, temporary changes to production code show that the tests fail when the behavior they guard breaks (see Validation). Where production is inconsistent, a test pins what it finds and says so: a 500 on the kube-system read and on the StorageClass list is
Transport, where the other reads reportQuery.Coverage
Paths are under
crates/nemoclaw-sdkunless noted. Scenario numbers are those on #12731.tests/support/kube_faults.rsSnapshot, platform fixturestests/kubernetes_read_failures.rsuid; a client TLS Secret missing one entrytests/kubernetes_lost_create_response.rstests/kubernetes_corrupt_receipt.rstests/kubernetes_expired_authentication.rsDevelopmentandOperationstests/kubernetes_openshift_reapply.rstests/deployment.rsplanandapplybefore the bundle opens or state is createdsrc/deployment/plan.rscheck_planrejects replacing a bound platform resourcecrates/nemoclaw-e2e/tests/provider_protocol.rsValidation
Run on
0906b1b03d, based onv1ata46f63be1d, darwin_arm64:cargo fmt --checkandcargo clippy --locked --workspace --all-targets -- -D warnings: clean.integrationbinary, 1 in the library unit tests) undercargo nextest run --locked --profile ci -p nemoclaw-sdk, filtered to them: 40 passed in each of 5 consecutive runs and in 3 runs with all 40 at once (--test-threads 40).NEMOCLAW_TEST_TOFU=<absolute path to dist/darwin_arm64/libexec/tofu> cargo test --locked -p nemoclaw-e2e --test integration provider_protocol::real_tofu -- --ignored: 3 passed, including the extended test.tofu versionreports OpenTofu v1.12.6. Thelifecyclestep ofcargo ciruns all ofprovider_protocol, including these three.cfg(unix)forced false in the SDK tests,cargo clippy -p nemoclaw-sdk --tests -- -D warningsis clean and the 11 tests that remain pass. This checks unused items and imports; it is not a Windows build.cargo ci: passed on0906b1b03d(856 s): fmt, clippy, build, test (1311 passed), schema, bundle and lifecycle (112 passed).Mutation probes: 25 temporary changes to production code, each reverted so the diff holds none. Each made at least one new test fail, and every new test outside
kube_faults.rsfailed under at least one of them. They include a read error mapped toNone, a 409 on create mapped toQuery, a re-run that adopts, or deletes and re-creates, the object that a 409 reports, a 401 mapped toQuery, a receipt that does not parse treated as empty, the certificate validity check ignored, expired material regenerated, a changed OpenShift identity accepted, a StatefulSet or cluster identity without auidadopted, a failed read mapped toIncompleteat each of five reads,connectwriting the private key first, validation errors ignored, andcheck_planrelaxed for every provider resource.Limits of this evidence
uidare synthetic: an API server assigns every object auid. They show that the SDK refuses to record or adopt such an answer, not that one occurs. The client TLS Secret that lacks a key is stored in the fake API; whether the chart can leave one out is not tested.KubernetesBackend::ensurereturns that object's identity with the error, OpenTofu taints the instance, andnemoclaw applystops at the plan check before it reaches the refusal that the lost-create tests pin.Test / windows_amd64) runs 11 of the 40 tests. The other 29 arecfg(unix): 28 inkubernetes_read_failures.rs,kubernetes_lost_create_response.rs,kubernetes_corrupt_receipt.rsandkubernetes_openshift_reapply.rs(#![cfg(unix)], askubernetes_operations.rsis), and 1 in theoperationsmodule ofkubernetes_expired_authentication.rs.Observations for maintainers
BindingMismatch, and no SDK path deletes an unrecorded object (Cluster::deleteruns only for recorded issuer objects), so it stays until someone removes it. The tests pin the refusal; a change that adds adoption or cleanup after ownership verification will change them.ensureof storage saves the cluster binding (server address and kube-systemuid) before it reads the Agent Sandbox CRD, controller and StorageClass, so a failed read of one leaves a receipt that holds only that binding. The scenario list on [Kubernetes/OpenShift] Broaden v1 recovery tests and document inference limitations #12731 left this unselected; three tests pin it.Transport(read_failureinstorage.rs);Cluster::getand the Helm release listing reportQuery. A recorded gateway whose StatefulSet has nouidisBindingMismatch, where first adoption of the same answer isIncomplete; only the latter is pinned.readandensureof the authentication resource andconnectfail withAuthentication; teardown does not load the certificates, and no test covers it.connectwrites each credential it decodes tostate/clientbefore it reads the next, so a Secret that lacks one leaves the earlier ones. The private key is written last.Refs #12731
🤖 Generated with Claude Code