From f48355c20a10909d78f748170739f28ad494af9f Mon Sep 17 00:00:00 2001 From: prk-Jr Date: Wed, 18 Nov 2026 23:39:02 +0530 Subject: [PATCH 01/13] feat: return an adapter-named capability error for Spin after-response tasks Spin does not run after-response tasks. Every converted Spin request now carries a scheduler that rejects registration with 501 Not Implemented and the message exported as edgezero_adapter_spin::AFTER_RESPONSE_UNSUPPORTED, instead of core's generic "not supported by this adapter" message. The task is dropped without being polled. The handle is installed in into_core_request_head, which every native Spin entry point uses (run_app, run_app_with_platform, dispatch_app, AppExt::dispatch, dispatch, dispatch_with_kv_label, into_core_request). The capability matrix already reports Spin Unsupported, so required = ["after-response-tasks"] still refuses Spin. Tests: host unit test for the scheduler; wasm32 contract test dispatching a real SpinRequest. Docs: capabilities, Spin guide, changelog, core after_response docs, design and plan. --- CHANGELOG.md | 5 +- .../src/after_response.rs | 73 ++++++++++ crates/edgezero-adapter-spin/src/lib.rs | 7 + crates/edgezero-adapter-spin/src/request.rs | 2 + .../edgezero-adapter-spin/tests/contract.rs | 59 +++++++++ crates/edgezero-core/src/after_response.rs | 8 +- docs/guide/adapters/spin.md | 14 ++ docs/guide/capabilities.md | 5 +- .../2026-11-18-spin-after-response-error.md | 36 +++++ ...-11-18-spin-after-response-error-design.md | 125 ++++++++++++++++++ 10 files changed, 329 insertions(+), 5 deletions(-) create mode 100644 crates/edgezero-adapter-spin/src/after_response.rs create mode 100644 docs/superpowers/plans/2026-11-18-spin-after-response-error.md create mode 100644 docs/superpowers/specs/2026-11-18-spin-after-response-error-design.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 78e841b13..0cdcfceb2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,7 +9,10 @@ after the response attempt ends and is cancelled at its budget. Adapters without support return `501 Not Implemented` at registration. - Add the `after-response-tasks` capability: Axum and Fastly `BoundedCooperative`, - Cloudflare and Spin `Unsupported` (tracked in #478 and #483). + Cloudflare and Spin `Unsupported` (Cloudflare tracked in #478). +- Spin rejects after-response tasks with a `501` that names the adapter + (`edgezero_adapter_spin::AFTER_RESPONSE_UNSUPPORTED`) on every converted request, instead of + core's generic message (#483). - Axum production, `run_app` and `AxumDevServer::run` shutdown now waits for registered after-response tasks within the existing shutdown grace, after connections drain. Tasks still pending at the grace make the process exit non-zero with `grace exhausted`. diff --git a/crates/edgezero-adapter-spin/src/after_response.rs b/crates/edgezero-adapter-spin/src/after_response.rs new file mode 100644 index 000000000..23866f401 --- /dev/null +++ b/crates/edgezero-adapter-spin/src/after_response.rs @@ -0,0 +1,73 @@ +//! Spin's after-response capability error. +//! +//! Spin does not run after-response tasks. Every converted request carries a scheduler that +//! rejects them with a `501` naming the Spin adapter, instead of core's generic error. + +use std::time::Duration; + +use edgezero_core::after_response::{AfterResponseHandle, AfterResponseScheduler}; +use edgezero_core::error::EdgeError; +use futures_util::future::LocalBoxFuture; + +struct SpinAfterResponseUnsupported; + +impl AfterResponseScheduler for SpinAfterResponseUnsupported { + #[inline] + fn schedule( + &self, + _budget: Duration, + task: LocalBoxFuture<'static, ()>, + ) -> Result<(), EdgeError> { + drop(task); + Err(EdgeError::not_implemented( + crate::AFTER_RESPONSE_UNSUPPORTED, + )) + } +} + +/// Handle inserted into every Spin request so registration fails with the Spin capability error. +pub(crate) fn unsupported_handle() -> AfterResponseHandle { + AfterResponseHandle::new(SpinAfterResponseUnsupported) +} + +#[cfg(test)] +mod tests { + use super::unsupported_handle; + use crate::AFTER_RESPONSE_UNSUPPORTED; + use edgezero_core::http::StatusCode; + use std::cell::Cell; + use std::rc::Rc; + use std::time::Duration; + + struct DropProbe(Rc>); + + #[expect( + clippy::missing_trait_methods, + reason = "`Drop::pin_drop` is unstable (`pin_ergonomics`) and conflicts with `drop`" + )] + impl Drop for DropProbe { + fn drop(&mut self) { + self.0.set(true); + } + } + + #[test] + fn registration_reports_spin_capability_error_and_drops_task_unpolled() { + let polled = Rc::new(Cell::new(false)); + let dropped = Rc::new(Cell::new(false)); + let probe = DropProbe(Rc::clone(&dropped)); + let observed = Rc::clone(&polled); + + let error = unsupported_handle() + .schedule(Duration::from_secs(1), async move { + let _probe = probe; + observed.set(true); + }) + .unwrap_err(); + + assert_eq!(error.status(), StatusCode::NOT_IMPLEMENTED); + assert_eq!(error.message(), AFTER_RESPONSE_UNSUPPORTED); + assert!(!polled.get(), "a rejected task is never polled"); + assert!(dropped.get(), "a rejected task is dropped at registration"); + } +} diff --git a/crates/edgezero-adapter-spin/src/lib.rs b/crates/edgezero-adapter-spin/src/lib.rs index ab5bc12bb..3b1d01ede 100644 --- a/crates/edgezero-adapter-spin/src/lib.rs +++ b/crates/edgezero-adapter-spin/src/lib.rs @@ -1,5 +1,7 @@ //! Adapter helpers for Spin (Fermyon). +#[cfg(any(test, all(feature = "spin", target_arch = "wasm32")))] +mod after_response; #[cfg(all(feature = "cli", not(target_arch = "wasm32")))] pub mod cli; @@ -76,6 +78,11 @@ pub const AKAMAI_FUNCTIONS_PLATFORM: edgezero_core::PlatformMetadata = ), ); +/// Message of the `501 Not Implemented` error that `RequestContext::after_response` returns on +/// Spin, which does not run after-response tasks. +pub const AFTER_RESPONSE_UNSUPPORTED: &str = + "after-response tasks are not supported by the Spin adapter"; + /// Generic Spin resource limits and accounting are runtime-configured. pub const SPIN_PLATFORM: edgezero_core::PlatformMetadata = edgezero_core::PlatformMetadata::new( edgezero_core::PlatformFact::unknown(edgezero_core::PlatformUnknownReason::RuntimeConfigured), diff --git a/crates/edgezero-adapter-spin/src/request.rs b/crates/edgezero-adapter-spin/src/request.rs index 0b5b9e6bc..a09665b9c 100644 --- a/crates/edgezero-adapter-spin/src/request.rs +++ b/crates/edgezero-adapter-spin/src/request.rs @@ -10,6 +10,7 @@ pub(crate) mod test_support; use crate::SpinResponse; +use crate::after_response::unsupported_handle; use crate::config_store::SpinConfigStore; use crate::context::{SpinRequestContext, parse_client_addr}; use crate::ingress::capture_request_ingress; @@ -162,6 +163,7 @@ fn into_core_request_head(parts: RequestParts, outbound_clock: MonotonicClock) - request .extensions_mut() .insert(outbound_client(outbound_clock)); + request.extensions_mut().insert(unsupported_handle()); request } diff --git a/crates/edgezero-adapter-spin/tests/contract.rs b/crates/edgezero-adapter-spin/tests/contract.rs index 2503b266a..8d6ccf3d0 100644 --- a/crates/edgezero-adapter-spin/tests/contract.rs +++ b/crates/edgezero-adapter-spin/tests/contract.rs @@ -980,6 +980,65 @@ mod tests { }); } + #[test] + fn native_request_after_response_registration_reports_spin_capability_error() { + sdk_block_on(async { + let polls = Arc::new(AtomicUsize::new(0)); + let drops = Arc::new(AtomicUsize::new(0)); + let handler_polls = Arc::clone(&polls); + let handler_drops = Arc::clone(&drops); + let router = RouterService::builder() + .get("/task", move |ctx: RequestContext| { + let task_polls = Arc::clone(&handler_polls); + let probe = DropSignal(Arc::clone(&handler_drops)); + async move { + let error = ctx + .after_response(Duration::from_secs(1), async move { + let _probe = probe; + task_polls.fetch_add(1, Ordering::SeqCst); + }) + .expect_err("Spin must reject after-response tasks"); + Ok::<_, EdgeError>(format!( + "{} {}", + error.status().as_u16(), + error.message() + )) + } + }) + .get("/control", |_ctx: RequestContext| async { + Ok::<_, EdgeError>("control") + }) + .build(); + let app = App::new(router); + + for (path, expected) in [ + ( + "/task", + format!("501 {}", edgezero_adapter_spin::AFTER_RESPONSE_UNSUPPORTED), + ), + ("/control", "control".to_owned()), + ] { + let outgoing_request = SpinRequest::builder() + .method("GET") + .uri(format!("http://example.test{path}")) + .body(http_body_util::Empty::::new()) + .expect("outgoing-compatible request"); + let wasi_request = outgoing_request.into_request().expect("WASI request"); + let incoming_request = + SpinRequest::from_request(wasi_request).expect("incoming Spin request"); + + let mut response = dispatch_request(&app, incoming_request) + .await + .expect("Spin response"); + + assert_eq!(response.response_mut().status(), StatusCode::OK); + assert_eq!(captured_body(response).as_ref(), expected.as_bytes()); + } + assert_eq!(polls.load(Ordering::SeqCst), 0, "task must never be polled"); + assert_eq!(drops.load(Ordering::SeqCst), 1, "task must be dropped"); + }); + } + struct CountingMiddleware(Arc); #[async_trait::async_trait(?Send)] diff --git a/crates/edgezero-core/src/after_response.rs b/crates/edgezero-core/src/after_response.rs index 78c3201d8..79f645736 100644 --- a/crates/edgezero-core/src/after_response.rs +++ b/crates/edgezero-core/src/after_response.rs @@ -2,8 +2,9 @@ //! //! A handler registers a task through [`RequestContext::after_response`](crate::context::RequestContext::after_response). //! The adapter starts it once the request's response attempt has ended at the adapter's terminal -//! egress boundary, and cancels it when its budget runs out. Adapters without support install no -//! handle, so registration fails with [`EdgeError::NotImplemented`]. +//! egress boundary, and cancels it when its budget runs out. Adapters without support install +//! either no handle or one that rejects every task, so registration fails with +//! [`EdgeError::NotImplemented`]. use std::fmt; use std::sync::Arc; @@ -13,7 +14,8 @@ use futures_util::future::LocalBoxFuture; use crate::error::EdgeError; -/// Message returned when the adapter installed no after-response scheduler for the request. +/// Message returned when no after-response scheduler is installed for the request. Adapters that +/// install a rejecting scheduler may use their own message. pub const AFTER_RESPONSE_UNSUPPORTED: &str = "after-response tasks are not supported by this adapter"; diff --git a/docs/guide/adapters/spin.md b/docs/guide/adapters/spin.md index 87ed403cd..5c84ee8d4 100644 --- a/docs/guide/adapters/spin.md +++ b/docs/guide/adapters/spin.md @@ -431,6 +431,20 @@ operations invocation-local. Standard response delivery remains lazy under host backpressure; retention adds no whole-response buffer or collection cap. Restore `run_app` and remove the cache to roll back; default generated entry points are unchanged. +## After-response tasks + +Spin does not run after-response tasks. `ctx.after_response(budget, task)` returns +`EdgeError::NotImplemented` (`501`) with the message +`after-response tasks are not supported by the Spin adapter`, exported as +`edgezero_adapter_spin::AFTER_RESPONSE_UNSUPPORTED`. The task is dropped without being polled. +Every Spin entry point that converts a native request installs this error, including +`run_app`, `dispatch_app` and `request::into_core_request`. Branch on the status or the +`not_implemented` kind rather than the message (core's constant of the same name does not match +on Spin), and do the work inline or elsewhere. An application +that cannot run without the tasks can declare `after-response-tasks` under +`[capabilities] required`, so `edgezero build`, `serve` and `deploy` refuse Spin. See the +[after-response task matrix](/guide/capabilities#after-response-task-matrix). + ## Runtime ingress metadata Conversion captures SDK URI parts before rebuilding the core request. Origin diff --git a/docs/guide/capabilities.md b/docs/guide/capabilities.md index daa814ff6..86028806a 100644 --- a/docs/guide/capabilities.md +++ b/docs/guide/capabilities.md @@ -355,8 +355,11 @@ so CPU-bound or blocking work overruns it. the same outbound scope. The budget is checked whenever a task yields to the adapter's progress driver; a blocked hostcall cannot be preempted. The tasks delay the next request on a reused `serve_app` instance, and a caller-sent native replacement after an uncommitted delivery. -- Cloudflare and Spin install no scheduler, so registration returns `501 Not Implemented`. Cloudflare +- Cloudflare installs no scheduler, so registration returns `501 Not Implemented`. Cloudflare `waitUntil` support is tracked in [#478](https://github.com/IABTechLab/edgezero/issues/478). +- Spin rejects every registration with `501 Not Implemented` and the message + `after-response tasks are not supported by the Spin adapter` + (`edgezero_adapter_spin::AFTER_RESPONSE_UNSUPPORTED`). The task is dropped without being polled. ## Outbound Matrix diff --git a/docs/superpowers/plans/2026-11-18-spin-after-response-error.md b/docs/superpowers/plans/2026-11-18-spin-after-response-error.md new file mode 100644 index 000000000..237473c9d --- /dev/null +++ b/docs/superpowers/plans/2026-11-18-spin-after-response-error.md @@ -0,0 +1,36 @@ +# Spin after-response capability error — plan + +Design: [`2026-11-18-spin-after-response-error-design.md`](../specs/2026-11-18-spin-after-response-error-design.md). +Issue: #483. Base branch: `feature/476-after-response-tasks` (PR #509). + +## Tasks + +1. **Failing tests first.** + - `crates/edgezero-adapter-spin/src/after_response.rs` host unit tests: the handle returns + `501` with `AFTER_RESPONSE_UNSUPPORTED`; the task is never polled and is dropped at + registration (drop probe uses core's `missing_trait_methods` expect pattern). + - `crates/edgezero-adapter-spin/tests/contract.rs` (`ingress_contract`) wasm32 test: a real + `SpinRequest` dispatched through `test_support::dispatch_request` to a route that registers a + task returns a `501` response naming the Spin adapter; the task is never polled and is + dropped; a control route on the same app returns `200`. +2. **Implement.** Define `AFTER_RESPONSE_UNSUPPORTED` ungated in `lib.rs` (no `pub use`, which + the `restriction` lint group denies). Add the module (gated like `ingress`: `any(test, + all(feature = "spin", target_arch = "wasm32"))`), insert the handle in + `into_core_request_head`. +3. **Docs.** `capabilities.md` bullet, `adapters/spin.md` section, `CHANGELOG.md` line, and core's + `after_response` module and constant docs (an unsupported adapter may install a rejecting handle). +4. **Negative control.** Run the contract test with the constant present but without the module, import and + insertion; the wasm32 contract test must fail with the + generic core message. Restore. +5. **Verification.** + - `cargo fmt --all -- --check` + - `cargo clippy --workspace --all-targets --all-features -- -D warnings` + - `cargo test --workspace --all-targets` + - `cargo check --workspace --all-targets --features "fastly cloudflare spin"` + - `cargo check -p edgezero-adapter-spin --target wasm32-wasip2 --features spin` + - Spin wasm clippy (`spin`, `spin,test-utils`) as in `format.yml` + - Spin wasm32 `--test contract --test sdk_resources` under Wasmtime 48.0.2 (the CI sdk-tests phase) + - `node scripts/check_outbound_docs_contract.mjs`; docs `npm run lint && npm run format` + - Runtime: `spin up` (4.1.0) on a scratch copy of `examples/app-demo` outside the repo, with a + route whose task would log `AFTER_TASK_RAN`; expect `501` with the Spin message, no marker + in the logs after 2 s, and an existing route `200`. diff --git a/docs/superpowers/specs/2026-11-18-spin-after-response-error-design.md b/docs/superpowers/specs/2026-11-18-spin-after-response-error-design.md new file mode 100644 index 000000000..54c78b9d7 --- /dev/null +++ b/docs/superpowers/specs/2026-11-18-spin-after-response-error-design.md @@ -0,0 +1,125 @@ +# Spin after-response capability error + +Date: 2026-11-18 +Status: approved for implementation. + +Issue: [#483](https://github.com/IABTechLab/edgezero/issues/483). Base: [PR #509](https://github.com/IABTechLab/edgezero/pull/509) +(`feature/476-after-response-tasks`), which adds `RequestContext::after_response`, the +`after-response-tasks` capability, and the portable `501` returned when no scheduler is installed. + +## Goal + +A Spin handler that calls `ctx.after_response(budget, task)` gets an explicit capability error +that names the Spin adapter. The task is never polled and is dropped at registration. Apps that +declare `after-response-tasks` as required are refused for Spin before deployment. + +## Why an explicit error, not support + +The issue fixes the scope: Spin returns a capability error. Spin's request lifecycle gives no +documented guarantee that work continues once the response is complete, and hosted Spin +(Akamai Functions) publishes no post-response execution budget. Running tasks there could drop +them silently, which is the outcome #476 forbids. Real support would need its own design and +platform evidence; it is out of scope. + +## Current behavior on the base + +Spin installs no `AfterResponseHandle`. Registration falls through to core's generic +`EdgeError::not_implemented("after-response tasks are not supported by this adapter")`. The +capability matrix already reports Spin `Unsupported`, so `required = ["after-response-tasks"]` +already fails for Spin. + +The gap is that the error is implicit. It is indistinguishable from a bare core context or an +adapter that forgot to install a scheduler, and it says nothing about which adapter refused. + +## Contract + +- **Status and kind.** Registration on any Spin request returns `EdgeError::NotImplemented` + (HTTP `501`, kind `not_implemented`), unchanged from the base. +- **Message.** `after-response tasks are not supported by the Spin adapter`. Defined, with no + cfg gate, as `edgezero_adapter_spin::AFTER_RESPONSE_UNSUPPORTED` in `lib.rs` (beside + `SPIN_PLATFORM`), so host-side app tests can name it too. Applications should branch on the + status or kind, not the message. +- **Task.** Never polled. Dropped before `after_response` returns. +- **Zero budget.** Unchanged core rule: core rejects it with `500` before the scheduler is called. +- **Reach.** The handle is installed where every native Spin request becomes a core request + (`into_core_request_head`). That covers `run_app`, `run_app_with_platform`, `dispatch_app`, + `AppExt::dispatch`, `dispatch`, `dispatch_with_kv_label` and the public `into_core_request`. + Not covered, by construction: `send_assembly_error` (no app, no handlers), and the test-utils + `dispatch_ingress_*` bridges, which build the core request with `request_builder()` and already + omit `SpinRequestContext` and ingress metadata. Those keep core's generic `501`. +- **Handler-inserted handles.** Spin has no pre-dispatch `prepare` hook. A handler or middleware + that inserts its own `AfterResponseHandle` into extensions replaces the adapter's, as with any + extension. That is the application's explicit choice and is not guarded. + +## Design + +New host-compilable module `crates/edgezero-adapter-spin/src/after_response.rs`: + +```rust +// lib.rs, ungated +pub const AFTER_RESPONSE_UNSUPPORTED: &str = + "after-response tasks are not supported by the Spin adapter"; + +// after_response.rs, gated any(test, all(feature = "spin", target_arch = "wasm32")) +use edgezero_core::after_response::{AfterResponseHandle, AfterResponseScheduler}; + +struct SpinAfterResponseUnsupported; + +impl AfterResponseScheduler for SpinAfterResponseUnsupported { + fn schedule(&self, _budget: Duration, task: LocalBoxFuture<'static, ()>) + -> Result<(), EdgeError> + { + drop(task); + Err(EdgeError::not_implemented(crate::AFTER_RESPONSE_UNSUPPORTED)) + } +} + +pub(crate) fn unsupported_handle() -> AfterResponseHandle; +``` + +`request::into_core_request_head` inserts `after_response::unsupported_handle()` next to the +existing `SpinRequestContext` and outbound client. + +The module compiles on the host (no `spin_sdk` imports), so its unit tests run under the plain +`cargo test --workspace`. The insertion is covered end to end in `tests/contract.rs` +(`ingress_contract`, `spin,test-utils`, wasm32 under Wasmtime): a real `SpinRequest` goes through +`test_support::dispatch_request`, which shares `into_core_request_head` with the production +funnels. CI runs that suite; it does not run the adapter's wasm32 `--lib` tests, whose binary +imports Spin KV resources that plain Wasmtime does not provide. + +Core changes only in documentation: its module doc and its `AFTER_RESPONSE_UNSUPPORTED` doc no +longer imply that an unsupported adapter installs no handle. No change to other adapters, the CLI +capability matrix, or the manifest. + +## Docs + +- `docs/guide/capabilities.md`: the after-response bullet says Spin installs a rejecting + scheduler that returns `501` naming the Spin adapter; Cloudflare keeps its own sentence. +- `docs/guide/adapters/spin.md`: short "After-response tasks" section. +- `CHANGELOG.md`: under the existing after-response heading, Spin no longer listed as pending + (#483); state the adapter-named `501`. + +## Acceptance and preservation + +| Scenario | Base | Intended | Evidence | +| --- | --- | --- | --- | +| Spin handler registers a task | 501, generic message | registration error is 501 with the Spin message | wasm32 contract test dispatching a real `SpinRequest` (handler echoes status and message in a 200 body); `spin up` probe propagates the error with `?` and observes a 501 response | +| Task registered on Spin | dropped unpolled | dropped unpolled | host unit test with poll and drop probes | +| Zero budget on Spin | 500 | 500 | existing core test (core rejects before any scheduler) | +| Bare core context (no adapter) | 501, generic message | unchanged | existing core unit test | +| `required = ["after-response-tasks"]` on Spin | refused | refused | existing `adapter_capability_matrix_matches_contracts` | +| Existing Spin routes | unchanged | unchanged | existing Spin suites; `spin up` control route | + +Runtime probe (`spin up` 4.1.0, scratch copy of `examples/app-demo`, not committed): a route +registers a task that would log a unique marker and returns the registration error's status and +message. Expect `501` with the Spin message, no marker in the Spin logs after a pause, and an +existing route still `200`. + +A negative control removes the insertion and its import and confirms the wasm32 contract test fails with the +generic message. + +## Out of scope + +- Running after-response tasks on Spin. +- Cloudflare (#478, PR #512). PR #512 edits the same capabilities bullet; whichever lands second + rebases that sentence. From dd05d1288461636f9c2f9e682fe7d43b9f4720bd Mon Sep 17 00:00:00 2001 From: prk-Jr Date: Wed, 18 Nov 2026 23:45:41 +0530 Subject: [PATCH 02/13] docs: state Spin's zero-budget 500 and widen the #512 overlap note Installing a rejecting Spin scheduler changes a zero budget from 501 to 500: core now finds a handle and rejects the budget before the scheduler, as it already does on Axum and Fastly. The guides, changelog and spec claimed every Spin registration returns 501 and that the zero budget case was unchanged. Correct them and pin the 500 with a Spin unit test. Also note that core pre-dispatch hooks can replace or remove the handle (removal falls back to core's 501), that PR #512 overlaps on the CHANGELOG line as well as the capabilities bullet, and point the #509 design at the follow-up. --- CHANGELOG.md | 3 ++- .../src/after_response.rs | 9 ++++++++ docs/guide/adapters/spin.md | 7 +++--- docs/guide/capabilities.md | 5 +++-- .../2026-11-18-spin-after-response-error.md | 8 ++++--- .../2026-11-17-after-response-tasks-design.md | 2 +- ...-11-18-spin-after-response-error-design.md | 22 ++++++++++++------- 7 files changed, 38 insertions(+), 18 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0cdcfceb2..a672df1f5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,7 +12,8 @@ Cloudflare and Spin `Unsupported` (Cloudflare tracked in #478). - Spin rejects after-response tasks with a `501` that names the adapter (`edgezero_adapter_spin::AFTER_RESPONSE_UNSUPPORTED`) on every converted request, instead of - core's generic message (#483). + core's generic message (#483). A zero budget on Spin now returns `500`, as on Axum and Fastly, + instead of `501`. - Axum production, `run_app` and `AxumDevServer::run` shutdown now waits for registered after-response tasks within the existing shutdown grace, after connections drain. Tasks still pending at the grace make the process exit non-zero with `grace exhausted`. diff --git a/crates/edgezero-adapter-spin/src/after_response.rs b/crates/edgezero-adapter-spin/src/after_response.rs index 23866f401..c4af7d3e4 100644 --- a/crates/edgezero-adapter-spin/src/after_response.rs +++ b/crates/edgezero-adapter-spin/src/after_response.rs @@ -70,4 +70,13 @@ mod tests { assert!(!polled.get(), "a rejected task is never polled"); assert!(dropped.get(), "a rejected task is dropped at registration"); } + + #[test] + fn zero_budget_is_a_programming_error_before_the_capability_error() { + let error = unsupported_handle() + .schedule(Duration::ZERO, async {}) + .unwrap_err(); + + assert_eq!(error.status(), StatusCode::INTERNAL_SERVER_ERROR); + } } diff --git a/docs/guide/adapters/spin.md b/docs/guide/adapters/spin.md index 5c84ee8d4..767d5c55b 100644 --- a/docs/guide/adapters/spin.md +++ b/docs/guide/adapters/spin.md @@ -433,11 +433,12 @@ and remove the cache to roll back; default generated entry points are unchanged. ## After-response tasks -Spin does not run after-response tasks. `ctx.after_response(budget, task)` returns -`EdgeError::NotImplemented` (`501`) with the message +Spin does not run after-response tasks. `ctx.after_response(budget, task)` with a positive budget +returns `EdgeError::NotImplemented` (`501`) with the message `after-response tasks are not supported by the Spin adapter`, exported as `edgezero_adapter_spin::AFTER_RESPONSE_UNSUPPORTED`. The task is dropped without being polled. -Every Spin entry point that converts a native request installs this error, including +A zero budget is a programming error and returns `500`, as on every adapter that installs a +scheduler. Every Spin entry point that converts a native request installs this error, including `run_app`, `dispatch_app` and `request::into_core_request`. Branch on the status or the `not_implemented` kind rather than the message (core's constant of the same name does not match on Spin), and do the work inline or elsewhere. An application diff --git a/docs/guide/capabilities.md b/docs/guide/capabilities.md index 86028806a..71a17de5b 100644 --- a/docs/guide/capabilities.md +++ b/docs/guide/capabilities.md @@ -357,9 +357,10 @@ so CPU-bound or blocking work overruns it. `serve_app` instance, and a caller-sent native replacement after an uncommitted delivery. - Cloudflare installs no scheduler, so registration returns `501 Not Implemented`. Cloudflare `waitUntil` support is tracked in [#478](https://github.com/IABTechLab/edgezero/issues/478). -- Spin rejects every registration with `501 Not Implemented` and the message - `after-response tasks are not supported by the Spin adapter` +- Spin rejects every registration with a positive budget with `501 Not Implemented` and the + message `after-response tasks are not supported by the Spin adapter` (`edgezero_adapter_spin::AFTER_RESPONSE_UNSUPPORTED`). The task is dropped without being polled. + A zero budget returns `500`, as on Axum and Fastly. ## Outbound Matrix diff --git a/docs/superpowers/plans/2026-11-18-spin-after-response-error.md b/docs/superpowers/plans/2026-11-18-spin-after-response-error.md index 237473c9d..efa2316f0 100644 --- a/docs/superpowers/plans/2026-11-18-spin-after-response-error.md +++ b/docs/superpowers/plans/2026-11-18-spin-after-response-error.md @@ -8,11 +8,13 @@ Issue: #483. Base branch: `feature/476-after-response-tasks` (PR #509). 1. **Failing tests first.** - `crates/edgezero-adapter-spin/src/after_response.rs` host unit tests: the handle returns `501` with `AFTER_RESPONSE_UNSUPPORTED`; the task is never polled and is dropped at - registration (drop probe uses core's `missing_trait_methods` expect pattern). + registration (drop probe uses core's `missing_trait_methods` expect pattern); a zero budget + through the Spin handle returns `500`. - `crates/edgezero-adapter-spin/tests/contract.rs` (`ingress_contract`) wasm32 test: a real `SpinRequest` dispatched through `test_support::dispatch_request` to a route that registers a - task returns a `501` response naming the Spin adapter; the task is never polled and is - dropped; a control route on the same app returns `200`. + task gets a `501` registration error with the Spin message (the handler echoes status and + message in a `200` body); the task is never polled and is dropped once; a control route on + the same app returns `200`. 2. **Implement.** Define `AFTER_RESPONSE_UNSUPPORTED` ungated in `lib.rs` (no `pub use`, which the `restriction` lint group denies). Add the module (gated like `ingress`: `any(test, all(feature = "spin", target_arch = "wasm32"))`), insert the handle in diff --git a/docs/superpowers/specs/2026-11-17-after-response-tasks-design.md b/docs/superpowers/specs/2026-11-17-after-response-tasks-design.md index b8524fc4c..c1c758a65 100644 --- a/docs/superpowers/specs/2026-11-17-after-response-tasks-design.md +++ b/docs/superpowers/specs/2026-11-17-after-response-tasks-design.md @@ -68,7 +68,7 @@ New `Capability::AfterResponseTasks` (`after-response-tasks`). Applications can ## Cloudflare and Spin -No scheduler is installed, so registration returns the 501 capability error. Their private egress `spawn` hooks stay unchanged. #478 and #483 own the change. +No scheduler is installed, so registration returns the 501 capability error. Their private egress `spawn` hooks stay unchanged. #478 and #483 own the change. (#483 later installs a rejecting Spin scheduler; see `2026-11-18-spin-after-response-error-design.md`.) ## Preservation and acceptance diff --git a/docs/superpowers/specs/2026-11-18-spin-after-response-error-design.md b/docs/superpowers/specs/2026-11-18-spin-after-response-error-design.md index 54c78b9d7..8a190f7a7 100644 --- a/docs/superpowers/specs/2026-11-18-spin-after-response-error-design.md +++ b/docs/superpowers/specs/2026-11-18-spin-after-response-error-design.md @@ -33,23 +33,28 @@ adapter that forgot to install a scheduler, and it says nothing about which adap ## Contract -- **Status and kind.** Registration on any Spin request returns `EdgeError::NotImplemented` - (HTTP `501`, kind `not_implemented`), unchanged from the base. +- **Status and kind.** Registration with a positive budget on any Spin request returns + `EdgeError::NotImplemented` (HTTP `501`, kind `not_implemented`), unchanged from the base. - **Message.** `after-response tasks are not supported by the Spin adapter`. Defined, with no cfg gate, as `edgezero_adapter_spin::AFTER_RESPONSE_UNSUPPORTED` in `lib.rs` (beside `SPIN_PLATFORM`), so host-side app tests can name it too. Applications should branch on the status or kind, not the message. - **Task.** Never polled. Dropped before `after_response` returns. -- **Zero budget.** Unchanged core rule: core rejects it with `500` before the scheduler is called. +- **Zero budget.** Changes from `501` to `500`. On the base, Spin installed no handle, so core's + `schedule_with` returned `501` before any budget check. With a handle installed, core's + `AfterResponseHandle::schedule` rejects a zero budget with `500` before the scheduler is called. + That is #509's rule for a programming error, and Axum and Fastly already behave this way. + Cloudflare, which still installs no handle, keeps `501` until #478. - **Reach.** The handle is installed where every native Spin request becomes a core request (`into_core_request_head`). That covers `run_app`, `run_app_with_platform`, `dispatch_app`, `AppExt::dispatch`, `dispatch`, `dispatch_with_kv_label` and the public `into_core_request`. Not covered, by construction: `send_assembly_error` (no app, no handlers), and the test-utils `dispatch_ingress_*` bridges, which build the core request with `request_builder()` and already omit `SpinRequestContext` and ingress metadata. Those keep core's generic `501`. -- **Handler-inserted handles.** Spin has no pre-dispatch `prepare` hook. A handler or middleware - that inserts its own `AfterResponseHandle` into extensions replaces the adapter's, as with any - extension. That is the application's explicit choice and is not guarded. +- **Application-inserted handles.** Spin has no adapter `prepare` hook. Core pre-dispatch hooks, + middleware and handlers can still replace or remove the extension, as on every adapter. A + replacement is the application's explicit choice; a removal falls back to core's generic `501`, + so no task is dropped silently. Neither is guarded. ## Design @@ -105,7 +110,7 @@ capability matrix, or the manifest. | --- | --- | --- | --- | | Spin handler registers a task | 501, generic message | registration error is 501 with the Spin message | wasm32 contract test dispatching a real `SpinRequest` (handler echoes status and message in a 200 body); `spin up` probe propagates the error with `?` and observes a 501 response | | Task registered on Spin | dropped unpolled | dropped unpolled | host unit test with poll and drop probes | -| Zero budget on Spin | 500 | 500 | existing core test (core rejects before any scheduler) | +| Zero budget on Spin | 501 (no handle) | 500 | host unit test through the Spin handle | | Bare core context (no adapter) | 501, generic message | unchanged | existing core unit test | | `required = ["after-response-tasks"]` on Spin | refused | refused | existing `adapter_capability_matrix_matches_contracts` | | Existing Spin routes | unchanged | unchanged | existing Spin suites; `spin up` control route | @@ -121,5 +126,6 @@ generic message. ## Out of scope - Running after-response tasks on Spin. -- Cloudflare (#478, PR #512). PR #512 edits the same capabilities bullet; whichever lands second +- Cloudflare (#478, PR #512). PR #512 edits the same `capabilities.md` bullet and the same + `CHANGELOG.md` capability line, and says Spin installs no scheduler; whichever lands second rebases that sentence. From 450122063e89ef6c8905d306e68482f855417ca0 Mon Sep 17 00:00:00 2001 From: prk-Jr Date: Fri, 20 Nov 2026 15:13:47 +0530 Subject: [PATCH 03/13] test: restore blocking mode on streams accepted by std fixtures Fixtures that poll a non-blocking std TcpListener read the accepted stream with set_read_timeout. macOS accept(2) copies O_NONBLOCK to the accepted socket (Linux does not), so those reads failed with WouldBlock at once and tests failed at random on macOS under parallel load. Add a small accept_blocking helper per crate (store-aws, adapter-axum tests, cli tests) that restores blocking mode, route all nine accept sites through it, and cover it with a test that fails on macOS when the accepted stream does not wait for its read timeout. --- .../tests/fixtures/blocking_accept.rs | 68 +++++++++++++++++++ .../tests/native_aws_startup.rs | 7 +- .../tests/native_celld_startup.rs | 7 +- .../tests/celld_generated_proof.rs | 8 ++- .../tests/dynamodb_generated_proof.rs | 8 ++- .../tests/native_store_generated_proof.rs | 10 ++- .../tests/support/blocking_accept.rs | 68 +++++++++++++++++++ .../src/dynamodb_records_tests.rs | 3 +- .../edgezero-store-aws/src/dynamodb_tests.rs | 3 +- crates/edgezero-store-aws/src/lib.rs | 6 ++ .../edgezero-store-aws/src/secrets_manager.rs | 3 +- crates/edgezero-store-aws/src/test_net.rs | 68 +++++++++++++++++++ 12 files changed, 250 insertions(+), 9 deletions(-) create mode 100644 crates/edgezero-adapter-axum/tests/fixtures/blocking_accept.rs create mode 100644 crates/edgezero-cli/tests/support/blocking_accept.rs create mode 100644 crates/edgezero-store-aws/src/test_net.rs diff --git a/crates/edgezero-adapter-axum/tests/fixtures/blocking_accept.rs b/crates/edgezero-adapter-axum/tests/fixtures/blocking_accept.rs new file mode 100644 index 000000000..2eb24b00c --- /dev/null +++ b/crates/edgezero-adapter-axum/tests/fixtures/blocking_accept.rs @@ -0,0 +1,68 @@ +//! Accept helper for test fixtures that poll a non-blocking std listener. + +use std::io; +use std::net::{SocketAddr, TcpListener, TcpStream}; + +/// Accepts one connection and returns its stream in blocking mode. +/// +/// Fixtures make the listener non-blocking so their accept loop can poll a deadline or stop +/// flag. macOS `accept(2)` copies `O_NONBLOCK` to the accepted socket (Linux does not), so a +/// read on the returned stream would otherwise fail with `WouldBlock` at once instead of +/// honouring its read timeout. `WouldBlock` from `accept` itself is still returned to the caller. +#[inline] +pub(crate) fn accept_blocking(listener: &TcpListener) -> io::Result<(TcpStream, SocketAddr)> { + let (stream, peer) = listener.accept()?; + stream.set_nonblocking(false)?; + Ok((stream, peer)) +} + +#[cfg(test)] +mod tests { + use super::accept_blocking; + use std::io::{ErrorKind, Read as _}; + use std::net::{TcpListener, TcpStream}; + use std::thread; + use std::time::{Duration, Instant}; + + #[test] + fn stream_accepted_from_nonblocking_listener_waits_for_read_timeout() { + let listener = TcpListener::bind("127.0.0.1:0").expect("bind loopback"); + listener + .set_nonblocking(true) + .expect("nonblocking listener"); + let address = listener.local_addr().expect("listener address"); + let _client = TcpStream::connect(address).expect("connect loopback client"); + let deadline = Instant::now() + .checked_add(Duration::from_secs(2)) + .expect("deadline fits the monotonic clock"); + let (mut stream, _peer) = loop { + match accept_blocking(&listener) { + Ok(accepted) => break accepted, + Err(error) if error.kind() == ErrorKind::WouldBlock => { + assert!( + Instant::now() < deadline, + "loopback connection was not queued" + ); + thread::sleep(Duration::from_millis(5)); + } + Err(error) => panic!("accept failed: {error}"), + } + }; + stream + .set_read_timeout(Some(Duration::from_millis(200))) + .expect("read timeout"); + let started = Instant::now(); + let error = stream + .read(&mut [0_u8; 1]) + .expect_err("the client sent nothing"); + let waited = started.elapsed(); + assert!( + matches!(error.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut), + "unexpected read error: {error}" + ); + assert!( + waited >= Duration::from_millis(150), + "read returned after {waited:?}, before its 200 ms timeout" + ); + } +} diff --git a/crates/edgezero-adapter-axum/tests/native_aws_startup.rs b/crates/edgezero-adapter-axum/tests/native_aws_startup.rs index a0b6283ce..849f268c8 100644 --- a/crates/edgezero-adapter-axum/tests/native_aws_startup.rs +++ b/crates/edgezero-adapter-axum/tests/native_aws_startup.rs @@ -4,12 +4,17 @@ //! They exercise the public runner and real pinned SDK, not a provider seam. No AWS account, //! DNS hostname, external socket, image, or real cloud credential is used. +#[cfg(test)] +#[path = "fixtures/blocking_accept.rs"] +mod blocking_accept; + #[cfg(test)] #[expect( clippy::arbitrary_source_item_ordering, reason = "loopback fixture helpers remain grouped before startup scenarios" )] mod tests { + use crate::blocking_accept::accept_blocking; use std::fmt::Write as _; use std::fs; use std::io::{ErrorKind, Read, Write as _}; @@ -83,7 +88,7 @@ mod tests { .checked_add(watch) .expect("fixture deadline fits the monotonic clock"); loop { - match listener.accept() { + match accept_blocking(&listener) { Ok((mut stream, peer)) => { assert!(peer.ip().is_loopback(), "fixture peer was not loopback"); stream diff --git a/crates/edgezero-adapter-axum/tests/native_celld_startup.rs b/crates/edgezero-adapter-axum/tests/native_celld_startup.rs index a9dbe9c54..8d057f909 100644 --- a/crates/edgezero-adapter-axum/tests/native_celld_startup.rs +++ b/crates/edgezero-adapter-axum/tests/native_celld_startup.rs @@ -8,8 +8,13 @@ reason = "fixture helpers precede startup scenarios" )] +#[cfg(test)] +#[path = "fixtures/blocking_accept.rs"] +mod blocking_accept; + #[cfg(test)] mod tests { + use crate::blocking_accept::accept_blocking; use std::fs; use std::io::{ErrorKind, Read, Write as _}; use std::net::{SocketAddr, TcpListener, TcpStream}; @@ -47,7 +52,7 @@ mod tests { thread::spawn(move || { let deadline = Instant::now().checked_add(WAIT).expect("fixture deadline"); while !worker_stop.load(Ordering::Relaxed) && Instant::now() < deadline { - match listener.accept() { + match accept_blocking(&listener) { Ok((mut stream, peer)) => { assert!(peer.ip().is_loopback()); stream diff --git a/crates/edgezero-cli/tests/celld_generated_proof.rs b/crates/edgezero-cli/tests/celld_generated_proof.rs index 8b96613bd..fcfd83537 100644 --- a/crates/edgezero-cli/tests/celld_generated_proof.rs +++ b/crates/edgezero-cli/tests/celld_generated_proof.rs @@ -4,6 +4,11 @@ //! `EDGEZERO_CELLD_STORE_SERVICE`, Node.js and OpenSSL; missing tools are //! failures, not skips. +#[cfg(test)] +#[cfg(unix)] +#[path = "support/blocking_accept.rs"] +mod blocking_accept; + #[cfg(test)] #[cfg(unix)] mod tests { @@ -12,6 +17,7 @@ mod tests { reason = "keep fixture ownership, generated source and proof steps together" )] + use crate::blocking_accept::accept_blocking; use std::collections::BTreeMap; use std::env; use std::fmt::Write as _; @@ -76,7 +82,7 @@ mod tests { let worker = thread::spawn(move || { let end = deadline(Duration::from_mins(10)); while !worker_stop.load(Ordering::Relaxed) && Instant::now() < end { - match listener.accept() { + match accept_blocking(&listener) { Ok((mut stream, peer)) => { assert!(peer.ip().is_loopback()); stream diff --git a/crates/edgezero-cli/tests/dynamodb_generated_proof.rs b/crates/edgezero-cli/tests/dynamodb_generated_proof.rs index 3cadaabdf..aa13389d3 100644 --- a/crates/edgezero-cli/tests/dynamodb_generated_proof.rs +++ b/crates/edgezero-cli/tests/dynamodb_generated_proof.rs @@ -7,6 +7,11 @@ //! fixture with dummy credentials and a cleared child environment. Serialize builds that share //! `EDGEZERO_GENERATED_TEST_TARGET_DIR`. +#[cfg(test)] +#[cfg(unix)] +#[path = "support/blocking_accept.rs"] +mod blocking_accept; + #[cfg(test)] mod tests { #[cfg(unix)] @@ -16,6 +21,7 @@ mod tests { reason = "group test fixture types and their protocol helpers by responsibility" )] + use crate::blocking_accept::accept_blocking; use std::collections::BTreeMap; use std::env; use std::fs; @@ -64,7 +70,7 @@ mod tests { let worker = thread::spawn(move || { let deadline = deadline_after(Duration::from_mins(3)); while !worker_stop.load(Ordering::Relaxed) && Instant::now() < deadline { - match listener.accept() { + match accept_blocking(&listener) { Ok((mut stream, peer)) => { assert!(peer.ip().is_loopback(), "fixture accepts loopback only"); stream diff --git a/crates/edgezero-cli/tests/native_store_generated_proof.rs b/crates/edgezero-cli/tests/native_store_generated_proof.rs index 8675e585a..c15981573 100644 --- a/crates/edgezero-cli/tests/native_store_generated_proof.rs +++ b/crates/edgezero-cli/tests/native_store_generated_proof.rs @@ -20,10 +20,16 @@ //! `EDGEZERO_GENERATED_TEST_TARGET_DIR` can select a shared target directory; otherwise builds //! use the generated project's `target/`. Serialize builds that share a target directory. +#[cfg(test)] +#[cfg(unix)] +#[path = "support/blocking_accept.rs"] +mod blocking_accept; + #[cfg(test)] #[cfg(unix)] mod tests { + use crate::blocking_accept::accept_blocking; use std::env::var_os; use std::fs; use std::io::{ErrorKind, Read as _, Write as _}; @@ -114,7 +120,7 @@ mod tests { let mut extra = Vec::new(); let deadline = deadline_after(SERVICE_GRACE); while Instant::now() < deadline { - match listener.accept() { + match accept_blocking(&listener) { Ok((mut extra_stream, peer)) => { assert!(peer.ip().is_loopback(), "only literal loopback peers"); extra_stream @@ -304,7 +310,7 @@ mod tests { fn accept_before(listener: &TcpListener, deadline: Instant) -> (TcpStream, SocketAddr) { loop { - match listener.accept() { + match accept_blocking(listener) { Ok((stream, peer)) => { assert!(peer.ip().is_loopback(), "fixture peer must be loopback"); return (stream, peer); diff --git a/crates/edgezero-cli/tests/support/blocking_accept.rs b/crates/edgezero-cli/tests/support/blocking_accept.rs new file mode 100644 index 000000000..2eb24b00c --- /dev/null +++ b/crates/edgezero-cli/tests/support/blocking_accept.rs @@ -0,0 +1,68 @@ +//! Accept helper for test fixtures that poll a non-blocking std listener. + +use std::io; +use std::net::{SocketAddr, TcpListener, TcpStream}; + +/// Accepts one connection and returns its stream in blocking mode. +/// +/// Fixtures make the listener non-blocking so their accept loop can poll a deadline or stop +/// flag. macOS `accept(2)` copies `O_NONBLOCK` to the accepted socket (Linux does not), so a +/// read on the returned stream would otherwise fail with `WouldBlock` at once instead of +/// honouring its read timeout. `WouldBlock` from `accept` itself is still returned to the caller. +#[inline] +pub(crate) fn accept_blocking(listener: &TcpListener) -> io::Result<(TcpStream, SocketAddr)> { + let (stream, peer) = listener.accept()?; + stream.set_nonblocking(false)?; + Ok((stream, peer)) +} + +#[cfg(test)] +mod tests { + use super::accept_blocking; + use std::io::{ErrorKind, Read as _}; + use std::net::{TcpListener, TcpStream}; + use std::thread; + use std::time::{Duration, Instant}; + + #[test] + fn stream_accepted_from_nonblocking_listener_waits_for_read_timeout() { + let listener = TcpListener::bind("127.0.0.1:0").expect("bind loopback"); + listener + .set_nonblocking(true) + .expect("nonblocking listener"); + let address = listener.local_addr().expect("listener address"); + let _client = TcpStream::connect(address).expect("connect loopback client"); + let deadline = Instant::now() + .checked_add(Duration::from_secs(2)) + .expect("deadline fits the monotonic clock"); + let (mut stream, _peer) = loop { + match accept_blocking(&listener) { + Ok(accepted) => break accepted, + Err(error) if error.kind() == ErrorKind::WouldBlock => { + assert!( + Instant::now() < deadline, + "loopback connection was not queued" + ); + thread::sleep(Duration::from_millis(5)); + } + Err(error) => panic!("accept failed: {error}"), + } + }; + stream + .set_read_timeout(Some(Duration::from_millis(200))) + .expect("read timeout"); + let started = Instant::now(); + let error = stream + .read(&mut [0_u8; 1]) + .expect_err("the client sent nothing"); + let waited = started.elapsed(); + assert!( + matches!(error.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut), + "unexpected read error: {error}" + ); + assert!( + waited >= Duration::from_millis(150), + "read returned after {waited:?}, before its 200 ms timeout" + ); + } +} diff --git a/crates/edgezero-store-aws/src/dynamodb_records_tests.rs b/crates/edgezero-store-aws/src/dynamodb_records_tests.rs index 93e431f6a..738c845c1 100644 --- a/crates/edgezero-store-aws/src/dynamodb_records_tests.rs +++ b/crates/edgezero-store-aws/src/dynamodb_records_tests.rs @@ -9,6 +9,7 @@ use super::*; use crate::dynamodb_kv::sdk_tests::{active_table, loopback_client, read_request}; use crate::settings::{AwsPreparationLimits, DynamoDbKvLimits}; +use crate::test_net::accept_blocking; use edgezero_core::record_store::{RecordKeyLayout, contract}; use edgezero_core::time::MonotonicClock; use serde_json::{Value, json}; @@ -77,7 +78,7 @@ impl Fixture { let worker_stopped = Arc::clone(&stopped); let worker = thread::spawn(move || { while !worker_stopped.load(Ordering::Acquire) { - match listener.accept() { + match accept_blocking(&listener) { Ok((mut stream, _)) => { stream .set_read_timeout(Some(Duration::from_secs(3))) diff --git a/crates/edgezero-store-aws/src/dynamodb_tests.rs b/crates/edgezero-store-aws/src/dynamodb_tests.rs index 861d054cb..522c9d8e9 100644 --- a/crates/edgezero-store-aws/src/dynamodb_tests.rs +++ b/crates/edgezero-store-aws/src/dynamodb_tests.rs @@ -12,6 +12,7 @@ use super::*; use crate::preparation::AwsPreparation; use crate::settings::{AwsPreparationLimits, DynamoDbKvLimits, DynamoDbKvSettings}; +use crate::test_net::accept_blocking; use edgezero_core::time::MonotonicClock; use std::collections::{BTreeMap, HashMap, VecDeque}; use std::io::{ErrorKind, Read as _, Write as _}; @@ -144,7 +145,7 @@ impl DynamoFixture { let worker_accepted = Arc::clone(&accepted); let worker = thread::spawn(move || { while !worker_stopped.load(Ordering::Acquire) { - match listener.accept() { + match accept_blocking(&listener) { Ok((mut stream, _)) => { worker_accepted.fetch_add(1, Ordering::Relaxed); stream diff --git a/crates/edgezero-store-aws/src/lib.rs b/crates/edgezero-store-aws/src/lib.rs index c4df04a63..24c7e3e56 100644 --- a/crates/edgezero-store-aws/src/lib.rs +++ b/crates/edgezero-store-aws/src/lib.rs @@ -53,6 +53,12 @@ mod secrets_manager; #[cfg(test)] #[cfg(all(not(target_arch = "wasm32"), feature = "secrets-manager"))] mod snapshot_tests; +#[cfg(test)] +#[cfg(all( + not(target_arch = "wasm32"), + any(feature = "secrets-manager", feature = "dynamodb-kv") +))] +mod test_net; #[cfg(all( not(target_arch = "wasm32"), any( diff --git a/crates/edgezero-store-aws/src/secrets_manager.rs b/crates/edgezero-store-aws/src/secrets_manager.rs index d5fcd961e..6fe0b06bd 100644 --- a/crates/edgezero-store-aws/src/secrets_manager.rs +++ b/crates/edgezero-store-aws/src/secrets_manager.rs @@ -323,6 +323,7 @@ fn classify_sdk_error( mod tests { use super::{classify_operation_error, materialize_payload}; use crate::PreparationError; + use crate::test_net::accept_blocking; use aws_sdk_secretsmanager::error::{ConnectorError, SdkError}; use aws_sdk_secretsmanager::operation::get_secret_value::GetSecretValueOutput; use aws_sdk_secretsmanager::primitives::Blob; @@ -465,7 +466,7 @@ mod tests { let mut bodies = Vec::new(); for response in responses { let stream = loop { - match worker_listener.accept() { + match accept_blocking(&worker_listener) { Ok((stream, peer)) => { assert!(peer.ip().is_loopback(), "fixture peer must be loopback"); break stream; diff --git a/crates/edgezero-store-aws/src/test_net.rs b/crates/edgezero-store-aws/src/test_net.rs new file mode 100644 index 000000000..2eb24b00c --- /dev/null +++ b/crates/edgezero-store-aws/src/test_net.rs @@ -0,0 +1,68 @@ +//! Accept helper for test fixtures that poll a non-blocking std listener. + +use std::io; +use std::net::{SocketAddr, TcpListener, TcpStream}; + +/// Accepts one connection and returns its stream in blocking mode. +/// +/// Fixtures make the listener non-blocking so their accept loop can poll a deadline or stop +/// flag. macOS `accept(2)` copies `O_NONBLOCK` to the accepted socket (Linux does not), so a +/// read on the returned stream would otherwise fail with `WouldBlock` at once instead of +/// honouring its read timeout. `WouldBlock` from `accept` itself is still returned to the caller. +#[inline] +pub(crate) fn accept_blocking(listener: &TcpListener) -> io::Result<(TcpStream, SocketAddr)> { + let (stream, peer) = listener.accept()?; + stream.set_nonblocking(false)?; + Ok((stream, peer)) +} + +#[cfg(test)] +mod tests { + use super::accept_blocking; + use std::io::{ErrorKind, Read as _}; + use std::net::{TcpListener, TcpStream}; + use std::thread; + use std::time::{Duration, Instant}; + + #[test] + fn stream_accepted_from_nonblocking_listener_waits_for_read_timeout() { + let listener = TcpListener::bind("127.0.0.1:0").expect("bind loopback"); + listener + .set_nonblocking(true) + .expect("nonblocking listener"); + let address = listener.local_addr().expect("listener address"); + let _client = TcpStream::connect(address).expect("connect loopback client"); + let deadline = Instant::now() + .checked_add(Duration::from_secs(2)) + .expect("deadline fits the monotonic clock"); + let (mut stream, _peer) = loop { + match accept_blocking(&listener) { + Ok(accepted) => break accepted, + Err(error) if error.kind() == ErrorKind::WouldBlock => { + assert!( + Instant::now() < deadline, + "loopback connection was not queued" + ); + thread::sleep(Duration::from_millis(5)); + } + Err(error) => panic!("accept failed: {error}"), + } + }; + stream + .set_read_timeout(Some(Duration::from_millis(200))) + .expect("read timeout"); + let started = Instant::now(); + let error = stream + .read(&mut [0_u8; 1]) + .expect_err("the client sent nothing"); + let waited = started.elapsed(); + assert!( + matches!(error.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut), + "unexpected read error: {error}" + ); + assert!( + waited >= Duration::from_millis(150), + "read returned after {waited:?}, before its 200 ms timeout" + ); + } +} From 6ac23fb7e01c80cfcb66a10488a70c16bfec90e6 Mon Sep 17 00:00:00 2001 From: prk-Jr Date: Fri, 20 Nov 2026 15:13:47 +0530 Subject: [PATCH 04/13] test: run source-bound proxy hosting tests only on Linux by default Four production_hosting tests drive the native proxy fixture, which binds its upstream socket to 127.0.0.2 or 127.0.0.3 so the server sees distinct peers. Linux routes all of 127.0.0.0/8 to lo; macOS lo0 has only 127.0.0.1, so the bind fails with EADDRNOTAVAIL, the relay drops the connection, and the tests see an empty response or TLS UnexpectedEof. Ignore them off Linux with a reason that gives the lo0 alias commands needed to run them with --ignored. --- .../tests/production_hosting.rs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/crates/edgezero-adapter-axum/tests/production_hosting.rs b/crates/edgezero-adapter-axum/tests/production_hosting.rs index c74a86c0f..c0e2bd8c2 100644 --- a/crates/edgezero-adapter-axum/tests/production_hosting.rs +++ b/crates/edgezero-adapter-axum/tests/production_hosting.rs @@ -567,6 +567,10 @@ mod tests { } #[test] + #[cfg_attr( + not(target_os = "linux"), + ignore = "binds extra loopback source addresses (127.0.0.2, 127.0.0.3), which only Linux routes by default (macOS lo0 has only 127.0.0.1); on macOS run with --ignored after `sudo ifconfig lo0 alias 127.0.0.2 up` and `sudo ifconfig lo0 alias 127.0.0.3 up`" + )] fn native_source_bound_single_proxy_and_mapped_cidr_match_only_owned_peers() { for networks in [ "127.0.0.2/32", @@ -627,6 +631,10 @@ mod tests { } #[test] + #[cfg_attr( + not(target_os = "linux"), + ignore = "binds extra loopback source addresses (127.0.0.2, 127.0.0.3), which only Linux routes by default (macOS lo0 has only 127.0.0.1); on macOS run with --ignored after `sudo ifconfig lo0 alias 127.0.0.2 up` and `sudo ifconfig lo0 alias 127.0.0.3 up`" + )] fn native_two_proxy_chain_stops_at_untrusted_hop_and_gateway_replaces_prefix() { for (networks, boundary) in [ ("127.0.0.2/32,127.0.0.3/32", "127.0.0.1"), @@ -773,6 +781,10 @@ mod tests { } #[test] + #[cfg_attr( + not(target_os = "linux"), + ignore = "binds extra loopback source addresses (127.0.0.2, 127.0.0.3), which only Linux routes by default (macOS lo0 has only 127.0.0.1); on macOS run with --ignored after `sudo ifconfig lo0 alias 127.0.0.2 up` and `sudo ifconfig lo0 alias 127.0.0.3 up`" + )] fn native_selected_families_conflicts_malformed_sets_gaps_and_exhaustion() { for family in ["forwarded", "x-forwarded"] { let roots = Roots::new(); @@ -847,6 +859,10 @@ mod tests { } #[test] + #[cfg_attr( + not(target_os = "linux"), + ignore = "binds extra loopback source addresses (127.0.0.2, 127.0.0.3), which only Linux routes by default (macOS lo0 has only 127.0.0.1); on macOS run with --ignored after `sudo ifconfig lo0 alias 127.0.0.2 up` and `sudo ifconfig lo0 alias 127.0.0.3 up`" + )] fn native_verified_tls_ingress_overwrites_public_assertions_and_rejects_wrong_name() { let roots = Roots::new(); let addr = address(); From ce8421a947b67299bcb092c0736801f34227e042 Mon Sep 17 00:00:00 2001 From: prk-Jr Date: Fri, 20 Nov 2026 19:03:36 +0530 Subject: [PATCH 05/13] test: make the Secrets Manager attempt-timeout proof deterministic The SDK's 100 ms attempt deadline runs from the start of the attempt. Under parallel load the child can be descheduled between the TCP connect and the request write, so the SDK correctly abandons the connection before sending anything. The fixture treated that as fatal ("SDK closed before request headers"), which failed the test about once in 20 full store-aws runs on macOS. The test now uses a fixture that accepts every attempt and never answers, recording whether the client closed each connection itself. The operation budget is 10 s, so only the attempt deadline can close a held connection within the 5 s bound. The test asserts that every attempt was closed that way, that the SDK made 1 to 3 attempts, and that any full request named the fixture ARN. Removing the attempt timeout from the provider makes the test fail. --- .../edgezero-store-aws/src/secrets_manager.rs | 146 +++++++++++++++--- 1 file changed, 123 insertions(+), 23 deletions(-) diff --git a/crates/edgezero-store-aws/src/secrets_manager.rs b/crates/edgezero-store-aws/src/secrets_manager.rs index 6fe0b06bd..4ac8358e2 100644 --- a/crates/edgezero-store-aws/src/secrets_manager.rs +++ b/crates/edgezero-store-aws/src/secrets_manager.rs @@ -332,13 +332,27 @@ mod tests { use std::io::{Read as _, Write as _}; use std::net::{TcpListener, TcpStream}; use std::process::{Command, Stdio}; - use std::sync::atomic::{AtomicU64, Ordering}; + use std::sync::Arc; + use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::thread; use std::time::{Duration, Instant}; + /// How long the holding fixture waits for the client to abandon an unanswered attempt. + /// The timeout child's attempt deadline is 100 ms and its operation budget is 10 s, so only + /// the attempt deadline can close a held connection inside this bound. + const HOLD_BOUND: Duration = Duration::from_secs(5); + const TEST_ARN: &str = "arn:aws:secretsmanager:us-east-1:111122223333:secret:fixture-AbCdEf"; static NEXT_FIXTURE: AtomicU64 = AtomicU64::new(0); + /// One connection the SDK opened against `holding_fixture`. + struct HeldConnection { + /// The client closed the connection within `HOLD_BOUND`. + closed_by_client: bool, + /// Lowercased request head and body, when the complete request arrived first. + request: Option<(String, String)>, + } + struct LoopbackFixture { listener: TcpListener, worker: thread::JoinHandle>, @@ -359,7 +373,6 @@ mod tests { #[derive(Clone)] enum FixtureResponse { Decryption, - Delay(Duration), Denied, InternalError, Json(String), @@ -421,21 +434,9 @@ mod tests { body.contains(TEST_ARN), "request must contain only the fictional fixture ARN" ); - if let FixtureResponse::Delay(delay) = response { - thread::sleep(delay); - let payload = b"{\"SecretString\":\"VALUE_SENTINEL\"}"; - let _header_write = write!( - stream, - "HTTP/1.1 200 OK\r\nContent-Type: application/x-amz-json-1.1\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", - payload.len() - ); - let _body_write = stream.write_all(payload); - return (headers, body); - } let (status, code, payload) = match response { FixtureResponse::Decryption => (400_u16, "Bad Request", r#"{"__type":"DecryptionFailure","message":"VALUE_SENTINEL"}"#.to_owned()), FixtureResponse::Denied => (400_u16, "Bad Request", r#"{"__type":"AccessDeniedException","message":"ARN_SENTINEL CREDENTIAL_SENTINEL"}"#.to_owned()), - FixtureResponse::Delay(_) => return (headers, body), FixtureResponse::InternalError => (500_u16, "Internal Server Error", r#"{"__type":"InternalServiceError","message":"SDK_ERROR_SENTINEL"}"#.to_owned()), FixtureResponse::Json(payload) => (200_u16, "OK", payload), FixtureResponse::Missing => (400_u16, "Bad Request", r#"{"__type":"ResourceNotFoundException","message":"ARN_SENTINEL"}"#.to_owned()), @@ -450,6 +451,89 @@ mod tests { (headers, body) } + /// Accepts every connection the SDK opens and never answers, so the client's attempt + /// deadline is the only thing that ends each attempt. The deadline runs from the start of + /// the attempt, so a descheduled child can abandon a connection before writing its request; + /// that is recorded as a client-side close, not treated as a fixture failure. + fn holding_fixture() -> ( + String, + Arc, + thread::JoinHandle>, + ) { + let listener = TcpListener::bind("127.0.0.1:0").expect("bind literal loopback only"); + listener + .set_nonblocking(true) + .expect("nonblocking listener"); + let endpoint = format!( + "http://{}", + listener.local_addr().expect("loopback address") + ); + let stop = Arc::new(AtomicBool::new(false)); + let worker_stop = Arc::clone(&stop); + let worker = thread::spawn(move || { + let deadline = Instant::now() + .checked_add(Duration::from_secs(30)) + .expect("fixture deadline fits the monotonic clock"); + let mut held = Vec::new(); + while !worker_stop.load(Ordering::Acquire) { + match accept_blocking(&listener) { + Ok((stream, peer)) => { + assert!(peer.ip().is_loopback(), "fixture peer must be loopback"); + held.push(hold(stream)); + } + Err(error) if error.kind() == ErrorKind::WouldBlock => { + assert!(Instant::now() < deadline, "SDK child did not finish"); + thread::sleep(Duration::from_millis(5)); + } + Err(error) => panic!("fixture accept failed: {error}"), + } + } + held + }); + (endpoint, stop, worker) + } + + fn hold(mut stream: TcpStream) -> HeldConnection { + stream + .set_read_timeout(Some(HOLD_BOUND)) + .expect("held connection bound"); + let mut received = Vec::new(); + let mut chunk = [0_u8; 4096]; + let closed_by_client = loop { + match stream.read(&mut chunk) { + Ok(0) => break true, + Ok(read) => { + received.extend_from_slice(&chunk[..read]); + assert!(received.len() < 64 * 1024, "bounded held request"); + } + Err(error) if error.kind() == ErrorKind::ConnectionReset => break true, + Err(error) + if matches!(error.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) => + { + break false; + } + Err(error) => panic!("held connection read failed: {error}"), + } + }; + let request = received + .windows(4) + .position(|bytes| bytes == b"\r\n\r\n") + .and_then(|end| { + let head = String::from_utf8_lossy(&received[..end]).to_ascii_lowercase(); + let length = head + .lines() + .find_map(|line| line.strip_prefix("content-length:").map(str::trim)) + .and_then(|value| value.parse::().ok())?; + let body = received.get(end.checked_add(4)?..)?; + (body.len() >= length) + .then(|| (head, String::from_utf8_lossy(&body[..length]).into_owned())) + }); + HeldConnection { + closed_by_client, + request, + } + } + fn loopback_fixture(responses: Vec) -> (String, LoopbackFixture) { let listener = TcpListener::bind("127.0.0.1:0").expect("bind literal loopback only"); listener @@ -773,20 +857,34 @@ mod tests { #[test] fn real_sdk_attempt_timeout_is_observed_without_an_outer_retry_loop() { - let (endpoint, fixture) = - loopback_fixture(vec![FixtureResponse::Delay(Duration::from_millis(350))]); + let (endpoint, stop, fixture) = holding_fixture(); let child = isolated_sdk_child(&endpoint, "timeout"); - let requests = fixture.join().expect("fixture thread"); + stop.store(true, Ordering::Release); + let held = fixture.join().expect("fixture thread"); assert!( child.status.success(), "timeout child failed: {}", String::from_utf8_lossy(&child.stderr) ); - assert_eq!( - requests.len(), - 1, - "SDK timeout behavior is inside the one provider operation" + assert!( + (1..=3).contains(&held.len()), + "only the SDK's own attempts (at most 3) reach the fixture: {} connections", + held.len() + ); + assert!( + held.iter().all(|connection| connection.closed_by_client), + "the attempt deadline, not the 10 s operation budget, ends every unanswered attempt" ); + for (head, body) in held + .iter() + .filter_map(|connection| connection.request.as_ref()) + { + assert!(head.contains("x-amz-target: secretsmanager.getsecretvalue")); + assert!( + body.contains(TEST_ARN), + "request must name only the fixture ARN" + ); + } } /// Invoked only by an env-cleared child process launched by the parent fixture. @@ -821,8 +919,10 @@ mod tests { crate::settings::AwsPreparationLimits { connect_timeout_ms: 50, attempt_timeout_ms: 100, - operation_timeout_ms: 500, - preparation_timeout_ms: 2_000, + // Far beyond the attempt deadline, so only the attempt deadline can end an + // unanswered attempt. + operation_timeout_ms: 10_000, + preparation_timeout_ms: 12_000, ..crate::settings::AwsPreparationLimits::default() } } else { From 09b09d9ee51da6e9953d3c8722f1640036740738 Mon Sep 17 00:00:00 2001 From: prk-Jr Date: Fri, 20 Nov 2026 19:12:36 +0530 Subject: [PATCH 06/13] test: keep hosting port reservations from leaking into fixture processes macOS marks a new socket close-on-exec only after socket() returns. When a parallel test spawned a fixture process in that gap, the child inherited another test's port reservation and kept it bound after the test released it. That test's fixture server then failed to bind (AddrInUse); lsof showed another fixture process holding the port as a CLOSED socket. Separately, a released reservation could be served by another test's server during a "nothing answers" check. Together these failed 6 of 20 macOS runs. Reservations and fixture spawns now hold one lock, so they never overlap. Tests that assert nothing answers keep their reservation bound, but not listening, until the check is done. --- .../tests/production_hosting.rs | 84 ++++++++++++------- 1 file changed, 55 insertions(+), 29 deletions(-) diff --git a/crates/edgezero-adapter-axum/tests/production_hosting.rs b/crates/edgezero-adapter-axum/tests/production_hosting.rs index c0e2bd8c2..1c50aaef9 100644 --- a/crates/edgezero-adapter-axum/tests/production_hosting.rs +++ b/crates/edgezero-adapter-axum/tests/production_hosting.rs @@ -20,13 +20,14 @@ mod tests { use std::os::unix::fs::{MetadataExt as _, PermissionsExt as _, symlink}; use std::os::unix::process::ExitStatusExt as _; use std::process::{Child, Command, ExitStatus, Stdio}; - use std::sync::{Arc, Mutex, mpsc}; + use std::sync::{Arc, Mutex, MutexGuard, PoisonError, mpsc}; use std::thread::{self, JoinHandle}; use std::time::{Duration, Instant}; use edgezero_core::blob_envelope::BlobEnvelope; use serde_json::{Value, json}; use tempfile::TempDir; + use tokio::net::TcpSocket; const WAIT: Duration = Duration::from_secs(5); @@ -64,11 +65,34 @@ mod tests { .expect("envelope") } + /// macOS marks a new socket close-on-exec only after `socket()` returns, so a fixture + /// process spawned by a parallel test in that gap inherits it. An inherited reservation + /// stays bound in that process, and the fixture server that later binds the port fails + /// with `AddrInUse`. Reservations and spawns hold this lock so they never overlap. + static RESERVE_OR_SPAWN: Mutex<()> = Mutex::new(()); + + fn reserve_or_spawn() -> MutexGuard<'static, ()> { + RESERVE_OR_SPAWN + .lock() + .unwrap_or_else(PoisonError::into_inner) + } + + /// Reserves a loopback port for a fixture server that binds it itself. fn address() -> SocketAddr { - TcpListener::bind("127.0.0.1:0") - .expect("port reservation") - .local_addr() - .expect("address") + reserved_address().0 + } + + /// Reserves a loopback port and keeps it bound, but not listening, until the holder drops. + /// No parallel test can bind the port meanwhile and nothing accepts a connection to it, so + /// a "nothing answers" check cannot reach a server that reused a released reservation. + fn reserved_address() -> (SocketAddr, TcpSocket) { + let _reserving = reserve_or_spawn(); + let socket = TcpSocket::new_v4().expect("port reservation socket"); + socket + .bind(SocketAddr::from((Ipv4Addr::LOCALHOST, 0))) + .expect("port reservation"); + let addr = socket.local_addr().expect("reserved address"); + (addr, socket) } fn command(mode: &str, roots: &Roots, addr: SocketAddr) -> Command { @@ -101,11 +125,13 @@ mod tests { impl Server { fn spawn(mut command: Command, addr: SocketAddr) -> Self { + let spawning = reserve_or_spawn(); let mut child = command .stdout(Stdio::piped()) .stderr(Stdio::piped()) .spawn() .expect("fixture process"); + drop(spawning); let output = Arc::new(Mutex::new(String::new())); let (sender, events) = mpsc::channel(); let stdout = child.stdout.take().expect("stdout"); @@ -173,14 +199,14 @@ mod tests { } fn signal(&self, name: &str) { - assert!( - Command::new("kill") - .arg(format!("-{name}")) - .arg(self.child.id().to_string()) - .status() - .expect("send signal") - .success() - ); + let spawning = reserve_or_spawn(); + let status = Command::new("kill") + .arg(format!("-{name}")) + .arg(self.child.id().to_string()) + .status() + .expect("send signal"); + drop(spawning); + assert!(status.success()); } fn socket(&self) -> io::Result { @@ -1660,7 +1686,7 @@ mod tests { (None, None, Some("RECORDS_SENTINEL"), "REQUEST_RECORDS"), (None, None, Some("FALSE"), "REQUEST_RECORDS"), ] { - let addr = address(); + let (addr, _addr_held) = reserved_address(); let mut launch = command("diagnostics", &roots, addr); if let Some(value) = networks { launch.env("EDGEZERO__ADAPTER__TRUSTED_PROXY_CIDRS", value); @@ -1701,7 +1727,7 @@ mod tests { ), ("EDGEZERO__LOGGING__REQUEST_RECORDS", "REQUEST_RECORDS"), ] { - let addr = address(); + let (addr, _addr_held) = reserved_address(); let mut launch = command("diagnostics", &roots, addr); let mut raw = b"NON_UNICODE_SENTINEL".to_vec(); raw.push(0xff); @@ -1844,7 +1870,7 @@ mod tests { OsString::from_vec(vec![0xff]), ] { let roots = Roots::new(); - let addr = address(); + let (addr, _addr_held) = reserved_address(); let mut launch = command(mode, &roots, addr); launch.env("EDGEZERO__ADAPTER__JSON_BODY_LIMIT_BYTES", value); let log = failed(launch, addr, "JSON_BODY_LIMIT_BYTES"); @@ -1948,7 +1974,7 @@ mod tests { #[test] fn stop_during_startup_never_binds_or_becomes_ready() { let roots = Roots::new(); - let addr = address(); + let (addr, _addr_held) = reserved_address(); let mut server = Server::spawn(command("starting", &roots, addr), addr); server.wait_line("INITIALIZING"); TcpStream::connect_timeout(&addr, Duration::from_millis(50)) @@ -1982,7 +2008,7 @@ mod tests { "settings", ), ] { - let addr = address(); + let (addr, _addr_held) = reserved_address(); let mut cmd = command("initialized", &roots, addr); cmd.env(key, value); failed(cmd, addr, category); @@ -1991,15 +2017,15 @@ mod tests { ("hook-error", "application configuration"), ("initializer-error", "initializer"), ] { - let addr = address(); + let (addr, _addr_held) = reserved_address(); failed(command(mode, &roots, addr), addr, category); } - let addr = address(); + let (addr, _addr_held) = reserved_address(); let mut cmd = command("initialized", &roots, addr); cmd.env_remove("EDGEZERO__ADAPTER__CONFIG_DIR"); failed(cmd, addr, "CONFIG_DIR"); let missing = roots.cwd.path().join("missing-data-SENTINEL"); - let missing_addr = address(); + let (missing_addr, _missing_addr_held) = reserved_address(); let mut missing_cmd = command("initialized", &roots, missing_addr); missing_cmd.env("EDGEZERO__ADAPTER__DATA_DIR", &missing); failed(missing_cmd, missing_addr, "DATA_DIR"); @@ -2022,10 +2048,10 @@ mod tests { let roots = Roots::new(); let file = roots.config.path().join("local-config-settings.json"); fs::remove_file(&file).expect("missing file fixture"); - let addr = address(); + let (addr, _addr_held) = reserved_address(); failed(command("initialized", &roots, addr), addr, "missing"); fs::create_dir_all(&file).expect("non-regular fixture"); - let directory_addr = address(); + let (directory_addr, _directory_addr_held) = reserved_address(); failed( command("initialized", &roots, directory_addr), directory_addr, @@ -2033,7 +2059,7 @@ mod tests { ); fs::remove_dir(&file).expect("remove fixture directory"); roots.map(&json!({"settings": {"CONFIG_SENTINEL": true}})); - let malformed_addr = address(); + let (malformed_addr, _malformed_addr_held) = reserved_address(); failed( command("initialized", &roots, malformed_addr), malformed_addr, @@ -2052,7 +2078,7 @@ mod tests { ), ] { roots.map(&map); - let typed_addr = address(); + let (typed_addr, _typed_addr_held) = reserved_address(); failed( command("initialized", &roots, typed_addr), typed_addr, @@ -2063,7 +2089,7 @@ mod tests { serde_json::from_str(&blob("valid-greeting", "fixture_token")).expect("envelope"); envelope["data"]["greeting"] = json!("CHANGED_CONFIG_SENTINEL"); roots.map(&json!({"settings": serde_json::to_string(&envelope).expect("envelope")})); - let integrity_addr = address(); + let (integrity_addr, _integrity_addr_held) = reserved_address(); failed( command("initialized", &roots, integrity_addr), integrity_addr, @@ -2137,7 +2163,7 @@ mod tests { .expect("snapshot") .ends_with("selected-greeting") ); - let second_addr = address(); + let (second_addr, _second_addr_held) = reserved_address(); failed( command("initialized", &roots, second_addr), second_addr, @@ -2289,7 +2315,7 @@ mod tests { #[cfg(not(feature = "geo-cloudfront"))] fn geo_hosting_rejects_unavailable_cloudfront() { let cwd = tempfile::tempdir().expect("unrelated cwd"); - let addr = address(); + let (addr, _addr_held) = reserved_address(); let mut server = Server::spawn(geo_command("geo-cloudfront", &cwd, addr), addr); assert!(!server.wait().success()); let log = server.log(); @@ -2365,7 +2391,7 @@ mod tests { #[test] fn geo_hosting_invalid_policy_never_initializes_or_listens() { let cwd = tempfile::tempdir().expect("unrelated cwd"); - let addr = address(); + let (addr, _addr_held) = reserved_address(); let mut server = Server::spawn(geo_command("geo-invalid-policy", &cwd, addr), addr); assert!(!server.wait().success()); assert!(!server.log().contains("INITIALIZED")); From d86a5d326c92607c33d627533368c47c1a6c8184 Mon Sep 17 00:00:00 2001 From: prk-Jr Date: Fri, 20 Nov 2026 19:28:17 +0530 Subject: [PATCH 07/13] test: close remaining gaps in the macOS hosting and timeout fixtures production_hosting: client streams from Server::socket and raw_request also take the reservation/spawn lock, so a concurrently spawned fixture cannot inherit one and keep the connection open after the test drops it. Because a held reservation always refuses connections, "nothing answers" checks now also assert that the server never reached its listener bind. Secrets Manager: the holding fixture drains every queued connection after the child exits before counting attempts, so a starved fixture thread cannot undercount them. --- .../tests/production_hosting.rs | 29 ++++++++++++++++--- .../edgezero-store-aws/src/secrets_manager.rs | 8 ++++- 2 files changed, 32 insertions(+), 5 deletions(-) diff --git a/crates/edgezero-adapter-axum/tests/production_hosting.rs b/crates/edgezero-adapter-axum/tests/production_hosting.rs index 1c50aaef9..2bf70337f 100644 --- a/crates/edgezero-adapter-axum/tests/production_hosting.rs +++ b/crates/edgezero-adapter-axum/tests/production_hosting.rs @@ -67,8 +67,9 @@ mod tests { /// macOS marks a new socket close-on-exec only after `socket()` returns, so a fixture /// process spawned by a parallel test in that gap inherits it. An inherited reservation - /// stays bound in that process, and the fixture server that later binds the port fails - /// with `AddrInUse`. Reservations and spawns hold this lock so they never overlap. + /// stays bound in that process, so the fixture server that later binds the port fails with + /// `AddrInUse`, and an inherited client stream stays open after the test drops it. Port + /// reservations, client streams and spawns hold this lock so they never overlap. static RESERVE_OR_SPAWN: Mutex<()> = Mutex::new(()); fn reserve_or_spawn() -> MutexGuard<'static, ()> { @@ -77,6 +78,12 @@ mod tests { .unwrap_or_else(PoisonError::into_inner) } + /// Opens a client stream without letting a concurrently spawned fixture inherit it. + fn connect(addr: SocketAddr, timeout: Duration) -> io::Result { + let _connecting = reserve_or_spawn(); + TcpStream::connect_timeout(&addr, timeout) + } + /// Reserves a loopback port for a fixture server that binds it itself. fn address() -> SocketAddr { reserved_address().0 @@ -85,6 +92,8 @@ mod tests { /// Reserves a loopback port and keeps it bound, but not listening, until the holder drops. /// No parallel test can bind the port meanwhile and nothing accepts a connection to it, so /// a "nothing answers" check cannot reach a server that reused a released reservation. + /// While held, the check cannot fail by itself: callers also assert that the server never + /// reached its listener bind. fn reserved_address() -> (SocketAddr, TcpSocket) { let _reserving = reserve_or_spawn(); let socket = TcpSocket::new_v4().expect("port reservation socket"); @@ -210,7 +219,7 @@ mod tests { } fn socket(&self) -> io::Result { - let socket = TcpStream::connect_timeout(&self.addr, Duration::from_millis(50))?; + let socket = connect(self.addr, Duration::from_millis(50))?; socket.set_read_timeout(Some(WAIT))?; socket.set_write_timeout(Some(WAIT))?; Ok(socket) @@ -272,6 +281,10 @@ mod tests { "startup diagnostic leaked fixture contents: {log}" ); assert!(!log.contains("INITIALIZED")); + assert!( + !log.contains("startup bind"), + "failed startup reached bind: {log}" + ); TcpStream::connect_timeout(&addr, Duration::from_millis(50)) .expect_err("failed startup never accepts connections"); log @@ -403,7 +416,7 @@ mod tests { } fn raw_request(addr: SocketAddr, request: &str) -> String { - let mut socket = TcpStream::connect_timeout(&addr, WAIT).expect("wire connection"); + let mut socket = connect(addr, WAIT).expect("wire connection"); socket.set_read_timeout(Some(WAIT)).expect("read timeout"); socket.set_write_timeout(Some(WAIT)).expect("write timeout"); socket.write_all(request.as_bytes()).expect("wire request"); @@ -2323,6 +2336,10 @@ mod tests { assert!(!log.contains("INITIALIZED")); assert!(!log.contains("HOOK_ENTERED")); assert!(!log.contains("ready")); + assert!( + !log.contains("startup bind"), + "unavailable implementation reached bind" + ); TcpStream::connect_timeout(&addr, Duration::from_millis(50)) .expect_err("unavailable implementation never binds"); assert_eq!(fs::read_dir(cwd.path()).expect("unrelated cwd").count(), 0); @@ -2397,6 +2414,10 @@ mod tests { assert!(!server.log().contains("INITIALIZED")); assert!(!server.log().contains("HOOK_ENTERED")); assert!(!server.log().contains("x-origin-verify-fixture")); + assert!( + !server.log().contains("startup bind"), + "invalid policy reached bind" + ); TcpStream::connect_timeout(&addr, Duration::from_millis(50)) .expect_err("invalid policy never binds"); assert_eq!(fs::read_dir(cwd.path()).expect("unrelated cwd").count(), 0); diff --git a/crates/edgezero-store-aws/src/secrets_manager.rs b/crates/edgezero-store-aws/src/secrets_manager.rs index 4ac8358e2..d1adbefca 100644 --- a/crates/edgezero-store-aws/src/secrets_manager.rs +++ b/crates/edgezero-store-aws/src/secrets_manager.rs @@ -475,13 +475,19 @@ mod tests { .checked_add(Duration::from_secs(30)) .expect("fixture deadline fits the monotonic clock"); let mut held = Vec::new(); - while !worker_stop.load(Ordering::Acquire) { + loop { + // Read the flag before accepting: once the child has exited, every connection it + // opened is already queued, so draining until `WouldBlock` counts all of them. + let stopping = worker_stop.load(Ordering::Acquire); match accept_blocking(&listener) { Ok((stream, peer)) => { assert!(peer.ip().is_loopback(), "fixture peer must be loopback"); held.push(hold(stream)); } Err(error) if error.kind() == ErrorKind::WouldBlock => { + if stopping { + break; + } assert!(Instant::now() < deadline, "SDK child did not finish"); thread::sleep(Duration::from_millis(5)); } From e8cf40eb59221b77c3bb3a9984ed9d54ff0daedf Mon Sep 17 00:00:00 2001 From: Aram Grigoryan <132480+aram356@users.noreply.github.com> Date: Mon, 23 Nov 2026 11:39:23 -0800 Subject: [PATCH 08/13] test: run the trusted-proxy hosting tests on every platform Four production_hosting tests bound the proxy fixture's upstream socket to 127.0.0.2 or 127.0.0.3 so the server saw distinct peers. macOS lo0 has only 127.0.0.1, so 6ac23fb7 ignored them off Linux. The server checks one socket fact, its direct peer. Every earlier hop reaches it only as Forwarded or X-Forwarded-For text. So every proxy socket now uses 127.0.0.1 and the trusted ranges name 127.0.0.1, including its mapped /128 and /127 forms. An appending proxy now writes the predecessor it is given, from 192.0.2.0/24, instead of its real client address. That address would also be 127.0.0.1, so the walk would skip it as trusted and accept the visitor's forged earlier hop. The single-proxy test's non-owning range becomes 127.0.0.0/32, the peer's sibling in the 127.0.0.0/31 that the mapped /127 truncates to, as 127.0.0.3/32 was for 127.0.0.2. The two-proxy chain keeps three distinct hops (198.51.100.99, 192.0.2.1, 192.0.2.2) behind the real 127.0.0.1 ingress peer. The exhaustion row's only hop becomes the trusted 127.0.0.1. Each test fails under one temporary production mutation: widening every trusted network by one prefix bit, walking past the first untrusted hop, resolving an all-trusted chain to its leftmost hop, and keeping an earlier Forwarded element's proto. The four tests passed 10 of 10 runs on macOS, alone and in the full suite. --- .../tests/fixtures/native_proxy.rs | 67 +++++++------ .../tests/production_hosting.rs | 93 +++++++++---------- 2 files changed, 79 insertions(+), 81 deletions(-) diff --git a/crates/edgezero-adapter-axum/tests/fixtures/native_proxy.rs b/crates/edgezero-adapter-axum/tests/fixtures/native_proxy.rs index 35953db96..492810218 100644 --- a/crates/edgezero-adapter-axum/tests/fixtures/native_proxy.rs +++ b/crates/edgezero-adapter-axum/tests/fixtures/native_proxy.rs @@ -1,4 +1,9 @@ -//! Test-only source-bound proxy and verified TLS ingress. No response is collected here. +//! Test-only loopback proxy and verified TLS ingress. No response is collected here. +//! +//! Every proxy socket is on 127.0.0.1, the IPv4 loopback address every platform has, so the +//! server's direct peer is always a real 127.0.0.1 socket. An appending proxy writes the +//! predecessor it is given rather than its own socket peer: the server only sees that hop as +//! header text, and a real 127.0.0.1 predecessor would collide with the trusted peer. #![expect( clippy::arbitrary_source_item_ordering, reason = "fixture ownership precedes bounded relay helpers" @@ -15,7 +20,7 @@ use rustls::{ClientConfig, RootCertStore, ServerConfig}; use tokio::io::{ AsyncRead, AsyncReadExt as _, AsyncWrite, AsyncWriteExt as _, copy_bidirectional_with_sizes, }; -use tokio::net::{TcpListener, TcpSocket, TcpStream}; +use tokio::net::{TcpListener, TcpStream}; use tokio::runtime::Builder; use tokio::sync::oneshot; use tokio::task::JoinSet; @@ -30,10 +35,12 @@ pub(crate) enum Assertions { /// Keep deliberate malformed/gap inputs unchanged while preserving a real owned peer. Preserve, AppendForwarded { + predecessor: IpAddr, host: &'static str, scheme: &'static str, }, AppendXForwarded { + predecessor: IpAddr, host: &'static str, scheme: &'static str, }, @@ -59,12 +66,7 @@ impl LocalProxy { #[must_use] #[inline] - pub(crate) fn start( - upstream: SocketAddr, - source: Ipv4Addr, - assertions: Assertions, - tls: bool, - ) -> Self { + pub(crate) fn start(upstream: SocketAddr, assertions: Assertions, tls: bool) -> Self { let std_listener = StdTcpListener::bind((Ipv4Addr::LOCALHOST, 0)).expect("proxy listener"); let addr = std_listener.local_addr().expect("proxy address"); std_listener @@ -86,17 +88,17 @@ impl LocalProxy { () = async { let _closed = (&mut stopped).await; } => break, _finished = tasks.join_next(), if !tasks.is_empty() => {}, accepted = listener.accept(), if tasks.len() < 64 => { - let (socket, peer) = accepted.expect("proxy accept"); + let (socket, _peer) = accepted.expect("proxy accept"); let task_acceptor = tls_acceptor.clone(); tasks.spawn(async move { let operation = async { if let Some(acceptor) = task_acceptor { if let Ok(mut client) = acceptor.accept(socket).await { - let _relayed = relay(&mut client, peer, upstream, source, assertions).await; + let _relayed = relay(&mut client, upstream, assertions).await; } } else { let mut client = socket; - let _relayed = relay(&mut client, peer, upstream, source, assertions).await; + let _relayed = relay(&mut client, upstream, assertions).await; } }; let _bounded = timeout(Duration::from_secs(5), operation).await; @@ -165,7 +167,14 @@ where } } -fn rewrite(head: &str, peer: SocketAddr, assertions: Assertions) -> io::Result { +fn forwarded_node(address: IpAddr) -> String { + match address { + IpAddr::V4(ip) => ip.to_string(), + IpAddr::V6(ip) => format!("\"[{ip}]\""), + } +} + +fn rewrite(head: &str, assertions: Assertions) -> io::Result { let mut lines = head.split("\r\n"); let request = lines .next() @@ -176,13 +185,13 @@ fn rewrite(head: &str, peer: SocketAddr, assertions: Assertions) -> io::Result ip.to_string(), - IpAddr::V6(ip) => format!("\"[{ip}]\""), - }; match assertions { Assertions::Preserve => {} - Assertions::AppendForwarded { host, scheme } => { + Assertions::AppendForwarded { + predecessor, + host, + scheme, + } => { let previous = headers .iter() .filter(|(name, _)| name.eq_ignore_ascii_case("forwarded")) @@ -190,7 +199,8 @@ fn rewrite(head: &str, peer: SocketAddr, assertions: Assertions) -> io::Result>() .join(","); headers.retain(|(name, _)| !name.eq_ignore_ascii_case("forwarded")); - let assertion = format!("for={predecessor};host=\"{host}\";proto={scheme}"); + let node = forwarded_node(predecessor); + let assertion = format!("for={node};host=\"{host}\";proto={scheme}"); headers.push(( "Forwarded".into(), if previous.is_empty() { @@ -200,7 +210,11 @@ fn rewrite(head: &str, peer: SocketAddr, assertions: Assertions) -> io::Result { + Assertions::AppendXForwarded { + predecessor, + host, + scheme, + } => { let previous = headers .iter() .filter(|(name, _)| name.eq_ignore_ascii_case("x-forwarded-for")) @@ -208,7 +222,7 @@ fn rewrite(head: &str, peer: SocketAddr, assertions: Assertions) -> io::Result>() .join(","); headers.retain(|(name, _)| !name.to_ascii_lowercase().starts_with("x-forwarded-")); - let node = peer.ip().to_string(); + let node = predecessor.to_string(); headers.push(( "X-Forwarded-For".into(), if previous.is_empty() { @@ -231,10 +245,7 @@ fn rewrite(head: &str, peer: SocketAddr, assertions: Assertions) -> io::Result ip.to_string(), - IpAddr::V6(ip) => format!("\"[{ip}]\""), - }; + let node = forwarded_node(client); headers.push(( "Forwarded".into(), format!("for={node};host=\"{host}\";proto={scheme}"), @@ -255,19 +266,15 @@ fn rewrite(head: &str, peer: SocketAddr, assertions: Assertions) -> io::Result( client: &mut Client, - peer: SocketAddr, upstream: SocketAddr, - source: Ipv4Addr, assertions: Assertions, ) -> io::Result<()> where Client: AsyncRead + AsyncWrite + Unpin, { let (head, body_prefix) = read_head(client).await?; - let rewritten = rewrite(&head, peer, assertions)?; - let socket = TcpSocket::new_v4()?; - socket.bind(SocketAddr::new(IpAddr::V4(source), 0))?; - let mut origin = socket.connect(upstream).await?; + let rewritten = rewrite(&head, assertions)?; + let mut origin = TcpStream::connect(upstream).await?; origin.write_all(rewritten.as_bytes()).await?; origin.write_all(&body_prefix).await?; // Finite, per-direction relay buffers. Never collect a response or body for proxying. diff --git a/crates/edgezero-adapter-axum/tests/production_hosting.rs b/crates/edgezero-adapter-axum/tests/production_hosting.rs index 2bf70337f..d4ce3823b 100644 --- a/crates/edgezero-adapter-axum/tests/production_hosting.rs +++ b/crates/edgezero-adapter-axum/tests/production_hosting.rs @@ -31,6 +31,10 @@ mod tests { const WAIT: Duration = Duration::from_secs(5); + /// The visitor address an appending test proxy reports as its predecessor. It lies outside + /// every trusted range, so a chain walk that accepts it stopped at the proxy's assertion. + const VISITOR: IpAddr = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 1)); + struct Roots { config: TempDir, cwd: TempDir, @@ -606,16 +610,14 @@ mod tests { } #[test] - #[cfg_attr( - not(target_os = "linux"), - ignore = "binds extra loopback source addresses (127.0.0.2, 127.0.0.3), which only Linux routes by default (macOS lo0 has only 127.0.0.1); on macOS run with --ignored after `sudo ifconfig lo0 alias 127.0.0.2 up` and `sudo ifconfig lo0 alias 127.0.0.3 up`" - )] fn native_source_bound_single_proxy_and_mapped_cidr_match_only_owned_peers() { + // The mapped /127 truncates to 127.0.0.0/31, so 127.0.0.0/32 is the sibling of the + // peer inside that range and the one listed network that does not own it. for networks in [ - "127.0.0.2/32", - "::ffff:127.0.0.2/128", - "::ffff:127.0.0.2/127", - "127.0.0.3/32", + "127.0.0.1/32", + "::ffff:127.0.0.1/128", + "::ffff:127.0.0.1/127", + "127.0.0.0/32", ] { let roots = Roots::new(); let addr = address(); @@ -626,8 +628,8 @@ mod tests { server.ready(); let proxy = LocalProxy::start( addr, - Ipv4Addr::new(127, 0, 0, 2), Assertions::AppendForwarded { + predecessor: VISITOR, host: "public.example", scheme: "https", }, @@ -640,10 +642,10 @@ mod tests { ), ); let value = response_json(&response); - let trusted = networks != "127.0.0.3/32"; + let trusted = networks != "127.0.0.0/32"; assert_metadata( &value, - if trusted { "127.0.0.1" } else { "127.0.0.2" }, + if trusted { "192.0.2.1" } else { "127.0.0.1" }, if trusted { "public.example" } else { @@ -661,7 +663,7 @@ mod tests { .expect("proxy peer") .parse() .expect("peer address"); - assert_eq!(peer.ip(), IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2))); + assert_eq!(peer.ip(), IpAddr::V4(Ipv4Addr::LOCALHOST)); assert_no_diagnostic_headers(&response); server.signal("TERM"); assert!(server.wait().success()); @@ -670,14 +672,14 @@ mod tests { } #[test] - #[cfg_attr( - not(target_os = "linux"), - ignore = "binds extra loopback source addresses (127.0.0.2, 127.0.0.3), which only Linux routes by default (macOS lo0 has only 127.0.0.1); on macOS run with --ignored after `sudo ifconfig lo0 alias 127.0.0.2 up` and `sudo ifconfig lo0 alias 127.0.0.3 up`" - )] fn native_two_proxy_chain_stops_at_untrusted_hop_and_gateway_replaces_prefix() { + // The ingress is the server's real 127.0.0.1 peer. It reports the first proxy as + // 192.0.2.2, and the first proxy reports the visitor, so the chain has three + // distinct hops: 198.51.100.99 (visitor-supplied), 192.0.2.1, then 192.0.2.2. + let first_proxy = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 2)); for (networks, boundary) in [ - ("127.0.0.2/32,127.0.0.3/32", "127.0.0.1"), - ("127.0.0.3/32", "127.0.0.2"), + ("127.0.0.1/32,192.0.2.2/32", "192.0.2.1"), + ("127.0.0.1/32", "192.0.2.2"), ] { let roots = Roots::new(); let addr = address(); @@ -688,8 +690,8 @@ mod tests { server.ready(); let ingress = LocalProxy::start( addr, - Ipv4Addr::new(127, 0, 0, 3), Assertions::AppendForwarded { + predecessor: first_proxy, host: "final.example", scheme: "https", }, @@ -697,8 +699,8 @@ mod tests { ); let first = LocalProxy::start( ingress.addr(), - Ipv4Addr::new(127, 0, 0, 2), Assertions::AppendForwarded { + predecessor: VISITOR, host: "earlier.example", scheme: "http", }, @@ -716,7 +718,7 @@ mod tests { value["handler"]["peer"] .as_str() .expect("last proxy peer") - .starts_with("127.0.0.3:") + .starts_with("127.0.0.1:") ); server.signal("TERM"); assert!(server.wait().success()); @@ -725,13 +727,12 @@ mod tests { let roots = Roots::new(); let addr = address(); let mut server = Server::spawn( - native_command("diagnostics", &roots, addr, "127.0.0.3/32", "forwarded"), + native_command("diagnostics", &roots, addr, "127.0.0.1/32", "forwarded"), addr, ); server.ready(); let gateway = LocalProxy::start( addr, - Ipv4Addr::new(127, 0, 0, 3), Assertions::ReplaceForwarded { client: "203.0.113.7".parse().expect("verified gateway client"), host: "gateway.example", @@ -758,13 +759,8 @@ mod tests { } fn assert_missing_unresolved_and_duplicate_family(addr: SocketAddr, family: &str) { - // This source-bound relay preserves deliberate bad inputs rather than sanitizing them. - let gateway = LocalProxy::start( - addr, - Ipv4Addr::new(127, 0, 0, 2), - Assertions::Preserve, - false, - ); + // This trusted relay preserves deliberate bad inputs rather than sanitizing them. + let gateway = LocalProxy::start(addr, Assertions::Preserve, false); let absent = if family == "forwarded" { "Forwarded: host=partial.example;proto=https\r\nX-Forwarded-For: 198.51.100.9\r\n" } else { @@ -773,7 +769,7 @@ mod tests { let missing_client = response_json(&raw_request(gateway.addr(), &metadata_request(absent))); assert_metadata( &missing_client, - "127.0.0.2", + "127.0.0.1", "partial.example", "https", if family == "forwarded" { @@ -788,16 +784,17 @@ mod tests { } else { "X-Forwarded-For: unknown\r\nX-Forwarded-Host: gap.example\r\nX-Forwarded-Proto: https\r\n" }, + // The only hop is the trusted peer itself, so the walk exhausts the chain. if family == "forwarded" { - "Forwarded: for=127.0.0.2;host=gap.example;proto=https\r\n" + "Forwarded: for=127.0.0.1;host=gap.example;proto=https\r\n" } else { - "X-Forwarded-For: 127.0.0.2\r\nX-Forwarded-Host: gap.example\r\nX-Forwarded-Proto: https\r\n" + "X-Forwarded-For: 127.0.0.1\r\nX-Forwarded-Host: gap.example\r\nX-Forwarded-Proto: https\r\n" }, ] { let value = response_json(&raw_request(gateway.addr(), &metadata_request(headers))); assert_metadata( &value, - "127.0.0.2", + "127.0.0.1", "gap.example", "https", "unresolved_chain", @@ -812,7 +809,7 @@ mod tests { response_json(&raw_request(gateway.addr(), &metadata_request(duplicate))); assert_metadata( &malformed_duplicate, - "127.0.0.2", + "127.0.0.1", "direct.example:8080", "http", "malformed", @@ -820,36 +817,34 @@ mod tests { } #[test] - #[cfg_attr( - not(target_os = "linux"), - ignore = "binds extra loopback source addresses (127.0.0.2, 127.0.0.3), which only Linux routes by default (macOS lo0 has only 127.0.0.1); on macOS run with --ignored after `sudo ifconfig lo0 alias 127.0.0.2 up` and `sudo ifconfig lo0 alias 127.0.0.3 up`" - )] fn native_selected_families_conflicts_malformed_sets_gaps_and_exhaustion() { for family in ["forwarded", "x-forwarded"] { let roots = Roots::new(); let addr = address(); let mut server = Server::spawn( - native_command("diagnostics", &roots, addr, "127.0.0.2/32", family), + native_command("diagnostics", &roots, addr, "127.0.0.1/32", family), addr, ); server.ready(); let assertions = if family == "forwarded" { Assertions::AppendForwarded { + predecessor: VISITOR, host: "selected.example", scheme: "https", } } else { Assertions::AppendXForwarded { + predecessor: VISITOR, host: "selected.example", scheme: "https", } }; - let proxy = LocalProxy::start(addr, Ipv4Addr::new(127, 0, 0, 2), assertions, false); + let proxy = LocalProxy::start(addr, assertions, false); for (prefix, expected_result, client, host, scheme) in [ ( "Forwarded: for=198.51.100.1;host=wrong.example;proto=http\r\nX-Forwarded-For: 203.0.113.1\r\nX-Forwarded-Host: wrong.example\r\nX-Forwarded-Proto: http\r\n", "accepted", - "127.0.0.1", + "192.0.2.1", "selected.example", "https", ), @@ -860,7 +855,7 @@ mod tests { "X-Forwarded-For: bad-address\r\n" }, "malformed", - "127.0.0.2", + "127.0.0.1", "direct.example:8080", "http", ), @@ -871,7 +866,7 @@ mod tests { "X-Forwarded-For: unknown\r\n" }, "accepted", - "127.0.0.1", + "192.0.2.1", "selected.example", "https", ), @@ -898,22 +893,18 @@ mod tests { } #[test] - #[cfg_attr( - not(target_os = "linux"), - ignore = "binds extra loopback source addresses (127.0.0.2, 127.0.0.3), which only Linux routes by default (macOS lo0 has only 127.0.0.1); on macOS run with --ignored after `sudo ifconfig lo0 alias 127.0.0.2 up` and `sudo ifconfig lo0 alias 127.0.0.3 up`" - )] fn native_verified_tls_ingress_overwrites_public_assertions_and_rejects_wrong_name() { let roots = Roots::new(); let addr = address(); let mut server = Server::spawn( - native_command("diagnostics", &roots, addr, "127.0.0.2/32", "forwarded"), + native_command("diagnostics", &roots, addr, "127.0.0.1/32", "forwarded"), addr, ); server.ready(); let proxy = LocalProxy::start( addr, - Ipv4Addr::new(127, 0, 0, 2), Assertions::AppendForwarded { + predecessor: VISITOR, host: "native-proxy.test", scheme: "https", }, @@ -927,7 +918,7 @@ mod tests { let value = response_json(&response); assert_metadata( &value, - "127.0.0.1", + "192.0.2.1", "native-proxy.test", "https", "accepted", From 58a238f8495afe1a8b35338bd9ee4d84dc7fe7fd Mon Sep 17 00:00:00 2001 From: prk-Jr Date: Wed, 2 Dec 2026 23:13:36 +0530 Subject: [PATCH 09/13] Share native test fixtures and strengthen timeout evidence --- .../tests/fixtures/blocking_accept.rs | 68 ------ .../tests/fixtures/native_proxy.rs | 39 ++-- .../tests/native_aws_startup.rs | 6 +- .../tests/native_celld_startup.rs | 6 +- .../tests/production_hosting.rs | 66 ++---- .../tests/celld_generated_proof.rs | 7 +- .../tests/dynamodb_generated_proof.rs | 7 +- .../tests/native_store_generated_proof.rs | 7 +- .../tests/support/blocking_accept.rs | 68 ------ crates/edgezero-core/src/lib.rs | 3 + .../src/test_net.rs | 6 +- .../src/dynamodb_records_tests.rs | 2 +- .../edgezero-store-aws/src/dynamodb_tests.rs | 2 +- crates/edgezero-store-aws/src/lib.rs | 6 - .../edgezero-store-aws/src/secrets_manager.rs | 219 +++++++++++++----- 15 files changed, 221 insertions(+), 291 deletions(-) delete mode 100644 crates/edgezero-adapter-axum/tests/fixtures/blocking_accept.rs delete mode 100644 crates/edgezero-cli/tests/support/blocking_accept.rs rename crates/{edgezero-store-aws => edgezero-core}/src/test_net.rs (93%) diff --git a/crates/edgezero-adapter-axum/tests/fixtures/blocking_accept.rs b/crates/edgezero-adapter-axum/tests/fixtures/blocking_accept.rs deleted file mode 100644 index 2eb24b00c..000000000 --- a/crates/edgezero-adapter-axum/tests/fixtures/blocking_accept.rs +++ /dev/null @@ -1,68 +0,0 @@ -//! Accept helper for test fixtures that poll a non-blocking std listener. - -use std::io; -use std::net::{SocketAddr, TcpListener, TcpStream}; - -/// Accepts one connection and returns its stream in blocking mode. -/// -/// Fixtures make the listener non-blocking so their accept loop can poll a deadline or stop -/// flag. macOS `accept(2)` copies `O_NONBLOCK` to the accepted socket (Linux does not), so a -/// read on the returned stream would otherwise fail with `WouldBlock` at once instead of -/// honouring its read timeout. `WouldBlock` from `accept` itself is still returned to the caller. -#[inline] -pub(crate) fn accept_blocking(listener: &TcpListener) -> io::Result<(TcpStream, SocketAddr)> { - let (stream, peer) = listener.accept()?; - stream.set_nonblocking(false)?; - Ok((stream, peer)) -} - -#[cfg(test)] -mod tests { - use super::accept_blocking; - use std::io::{ErrorKind, Read as _}; - use std::net::{TcpListener, TcpStream}; - use std::thread; - use std::time::{Duration, Instant}; - - #[test] - fn stream_accepted_from_nonblocking_listener_waits_for_read_timeout() { - let listener = TcpListener::bind("127.0.0.1:0").expect("bind loopback"); - listener - .set_nonblocking(true) - .expect("nonblocking listener"); - let address = listener.local_addr().expect("listener address"); - let _client = TcpStream::connect(address).expect("connect loopback client"); - let deadline = Instant::now() - .checked_add(Duration::from_secs(2)) - .expect("deadline fits the monotonic clock"); - let (mut stream, _peer) = loop { - match accept_blocking(&listener) { - Ok(accepted) => break accepted, - Err(error) if error.kind() == ErrorKind::WouldBlock => { - assert!( - Instant::now() < deadline, - "loopback connection was not queued" - ); - thread::sleep(Duration::from_millis(5)); - } - Err(error) => panic!("accept failed: {error}"), - } - }; - stream - .set_read_timeout(Some(Duration::from_millis(200))) - .expect("read timeout"); - let started = Instant::now(); - let error = stream - .read(&mut [0_u8; 1]) - .expect_err("the client sent nothing"); - let waited = started.elapsed(); - assert!( - matches!(error.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut), - "unexpected read error: {error}" - ); - assert!( - waited >= Duration::from_millis(150), - "read returned after {waited:?}, before its 200 ms timeout" - ); - } -} diff --git a/crates/edgezero-adapter-axum/tests/fixtures/native_proxy.rs b/crates/edgezero-adapter-axum/tests/fixtures/native_proxy.rs index a33126423..0a04442ee 100644 --- a/crates/edgezero-adapter-axum/tests/fixtures/native_proxy.rs +++ b/crates/edgezero-adapter-axum/tests/fixtures/native_proxy.rs @@ -32,20 +32,31 @@ use super::tests::reserve_or_spawn; const MAX_HEAD: usize = 0x8000; const RELAY_BUFFER: usize = 0x4000; +#[derive(Clone, Copy)] +pub(crate) struct Hop { + predecessor: IpAddr, + host: &'static str, + scheme: &'static str, +} + +impl Hop { + #[must_use] + #[inline] + pub(crate) const fn new(predecessor: IpAddr, host: &'static str, scheme: &'static str) -> Self { + Self { + predecessor, + host, + scheme, + } + } +} + #[derive(Clone, Copy)] pub(crate) enum Assertions { /// Keep deliberate malformed/gap inputs unchanged while preserving a real owned peer. Preserve, - AppendForwarded { - predecessor: IpAddr, - host: &'static str, - scheme: &'static str, - }, - AppendXForwarded { - predecessor: IpAddr, - host: &'static str, - scheme: &'static str, - }, + AppendForwarded(Hop), + AppendXForwarded(Hop), ReplaceForwarded { client: IpAddr, host: &'static str, @@ -225,11 +236,11 @@ fn rewrite(head: &str, assertions: Assertions) -> io::Result { } match assertions { Assertions::Preserve => {} - Assertions::AppendForwarded { + Assertions::AppendForwarded(Hop { predecessor, host, scheme, - } => { + }) => { let previous = headers .iter() .filter(|(name, _)| name.eq_ignore_ascii_case("forwarded")) @@ -248,11 +259,11 @@ fn rewrite(head: &str, assertions: Assertions) -> io::Result { }, )); } - Assertions::AppendXForwarded { + Assertions::AppendXForwarded(Hop { predecessor, host, scheme, - } => { + }) => { let previous = headers .iter() .filter(|(name, _)| name.eq_ignore_ascii_case("x-forwarded-for")) diff --git a/crates/edgezero-adapter-axum/tests/native_aws_startup.rs b/crates/edgezero-adapter-axum/tests/native_aws_startup.rs index 8dd6478e1..a48713e86 100644 --- a/crates/edgezero-adapter-axum/tests/native_aws_startup.rs +++ b/crates/edgezero-adapter-axum/tests/native_aws_startup.rs @@ -4,17 +4,13 @@ //! They exercise the public runner and real pinned SDK, not a provider seam. No AWS account, //! DNS hostname, external socket, image, or real cloud credential is used. -#[cfg(test)] -#[path = "fixtures/blocking_accept.rs"] -mod blocking_accept; - #[cfg(test)] #[expect( clippy::arbitrary_source_item_ordering, reason = "loopback fixture helpers remain grouped before startup scenarios" )] mod tests { - use crate::blocking_accept::accept_blocking; + use edgezero_core::test_net::accept_blocking; use std::fmt::Write as _; use std::fs; use std::io::{self, ErrorKind, Read, Write as _}; diff --git a/crates/edgezero-adapter-axum/tests/native_celld_startup.rs b/crates/edgezero-adapter-axum/tests/native_celld_startup.rs index 78f132064..96cfd2849 100644 --- a/crates/edgezero-adapter-axum/tests/native_celld_startup.rs +++ b/crates/edgezero-adapter-axum/tests/native_celld_startup.rs @@ -8,13 +8,9 @@ reason = "fixture helpers precede startup scenarios" )] -#[cfg(test)] -#[path = "fixtures/blocking_accept.rs"] -mod blocking_accept; - #[cfg(test)] mod tests { - use crate::blocking_accept::accept_blocking; + use edgezero_core::test_net::accept_blocking; use std::fs; use std::io::{ErrorKind, Read, Write as _}; use std::net::{SocketAddr, TcpListener, TcpStream}; diff --git a/crates/edgezero-adapter-axum/tests/production_hosting.rs b/crates/edgezero-adapter-axum/tests/production_hosting.rs index 33f3888de..5c15d05d0 100644 --- a/crates/edgezero-adapter-axum/tests/production_hosting.rs +++ b/crates/edgezero-adapter-axum/tests/production_hosting.rs @@ -11,7 +11,7 @@ mod native_proxy; reason = "subprocess fixtures group setup, process ownership and acceptance scenarios" )] mod tests { - use super::native_proxy::{Assertions, LocalProxy, verified_tls_request}; + use super::native_proxy::{Assertions, Hop, LocalProxy, verified_tls_request}; use std::collections::HashSet; use std::ffi::{OsStr, OsString}; use std::fs; @@ -580,13 +580,18 @@ mod tests { assert!(id.bytes().all(|byte| byte.is_ascii_hexdigit())); } - fn assert_peer_ip(value: &Value, expected: Ipv4Addr) { + fn assert_peer_ip(value: &Value, expected: Ipv4Addr, listener: SocketAddr) { let peer: SocketAddr = value["handler"]["peer"] .as_str() .expect("owned peer") .parse() .expect("socket peer"); assert_eq!(peer.ip(), IpAddr::V4(expected)); + assert_ne!( + peer.port(), + listener.port(), + "accepted peer must not be the listener" + ); } fn assert_no_diagnostic_headers(response: &str) { @@ -712,7 +717,7 @@ mod tests { for field in ["client_source", "host_source", "scheme_source"] { assert_eq!(value["handler"][field], "direct"); } - assert_peer_ip(&value, Ipv4Addr::LOCALHOST); + assert_peer_ip(&value, Ipv4Addr::LOCALHOST, server.addr()); let expected_bytes = request .split("\r\n") .skip(1) @@ -740,7 +745,7 @@ mod tests { } #[test] - fn native_source_bound_single_proxy_and_mapped_cidr_match_only_owned_peers() { + fn native_single_loopback_proxy_requires_matching_peer_cidr() { // The mapped /127 truncates to 127.0.0.0/31, so 127.0.0.0/32 is the sibling of the // peer inside that range and the one listed network that does not own it. for networks in [ @@ -758,11 +763,7 @@ mod tests { server.ready(); let proxy = LocalProxy::start( server.addr(), - Assertions::AppendForwarded { - predecessor: VISITOR, - host: "public.example", - scheme: "https", - }, + Assertions::AppendForwarded(Hop::new(VISITOR, "public.example", "https")), false, ); let response = raw_request( @@ -788,7 +789,7 @@ mod tests { "untrusted_peer" }, ); - assert_peer_ip(&value, Ipv4Addr::LOCALHOST); + assert_peer_ip(&value, Ipv4Addr::LOCALHOST, server.addr()); assert_no_diagnostic_headers(&response); server.signal("TERM"); assert!(server.wait().success()); @@ -815,20 +816,12 @@ mod tests { server.ready(); let ingress = LocalProxy::start( server.addr(), - Assertions::AppendForwarded { - predecessor: first_proxy, - host: "final.example", - scheme: "https", - }, + Assertions::AppendForwarded(Hop::new(first_proxy, "final.example", "https")), false, ); let first = LocalProxy::start( ingress.addr(), - Assertions::AppendForwarded { - predecessor: VISITOR, - host: "earlier.example", - scheme: "http", - }, + Assertions::AppendForwarded(Hop::new(VISITOR, "earlier.example", "http")), false, ); let value = response_json(&raw_request( @@ -839,7 +832,7 @@ mod tests { )); assert_metadata(&value, Some(boundary), "final.example", "https", "accepted"); assert_eq!(value["handler"]["host_source"], "trusted_forwarded"); - assert_peer_ip(&value, Ipv4Addr::LOCALHOST); + assert_peer_ip(&value, Ipv4Addr::LOCALHOST, server.addr()); server.signal("TERM"); assert!(server.wait().success()); assert_final_zero(&server); @@ -889,7 +882,7 @@ mod tests { "http", "absent", ); - assert_peer_ip(&absent, Ipv4Addr::LOCALHOST); + assert_peer_ip(&absent, Ipv4Addr::LOCALHOST, addr); assert_eq!(absent["handler"]["client_source"], "direct"); let without_address = if family == "forwarded" { @@ -916,7 +909,7 @@ mod tests { "partial" }, ); - assert_peer_ip(&missing_client, Ipv4Addr::LOCALHOST); + assert_peer_ip(&missing_client, Ipv4Addr::LOCALHOST, addr); for headers in [ if family == "forwarded" { "Forwarded: for=unknown;host=gap.example;proto=https\r\n" @@ -932,7 +925,7 @@ mod tests { ] { let value = response_json(&raw_request(gateway.addr(), &metadata_request(headers))); assert_metadata(&value, None, "gap.example", "https", "unresolved_chain"); - assert_peer_ip(&value, Ipv4Addr::LOCALHOST); + assert_peer_ip(&value, Ipv4Addr::LOCALHOST, addr); let source = if family == "forwarded" { "trusted_forwarded" } else { @@ -955,7 +948,7 @@ mod tests { "http", "malformed", ); - assert_peer_ip(&malformed_duplicate, Ipv4Addr::LOCALHOST); + assert_peer_ip(&malformed_duplicate, Ipv4Addr::LOCALHOST, addr); } #[test] @@ -968,18 +961,11 @@ mod tests { addr, ); server.ready(); + let hop = Hop::new(VISITOR, "selected.example", "https"); let assertions = if family == "forwarded" { - Assertions::AppendForwarded { - predecessor: VISITOR, - host: "selected.example", - scheme: "https", - } + Assertions::AppendForwarded(hop) } else { - Assertions::AppendXForwarded { - predecessor: VISITOR, - host: "selected.example", - scheme: "https", - } + Assertions::AppendXForwarded(hop) }; let proxy = LocalProxy::start(server.addr(), assertions, false); for (prefix, expected_result, client, host, scheme) in [ @@ -1015,7 +1001,7 @@ mod tests { ] { let value = response_json(&raw_request(proxy.addr(), &metadata_request(prefix))); assert_metadata(&value, client, host, scheme, expected_result); - assert_peer_ip(&value, Ipv4Addr::LOCALHOST); + assert_peer_ip(&value, Ipv4Addr::LOCALHOST, server.addr()); } assert_missing_unresolved_and_duplicate_family(server.addr(), family); server.signal("TERM"); @@ -1046,11 +1032,7 @@ mod tests { server.ready(); let proxy = LocalProxy::start( server.addr(), - Assertions::AppendForwarded { - predecessor: VISITOR, - host: "native-proxy.test", - scheme: "https", - }, + Assertions::AppendForwarded(Hop::new(VISITOR, "native-proxy.test", "https")), true, ); let request = metadata_request( @@ -1930,7 +1912,7 @@ mod tests { "https", "accepted", ); - assert_peer_ip(&value, Ipv4Addr::LOCALHOST); + assert_peer_ip(&value, Ipv4Addr::LOCALHOST, server.addr()); server.signal(shutdown); assert!(server.wait().success(), "{}", server.log()); diff --git a/crates/edgezero-cli/tests/celld_generated_proof.rs b/crates/edgezero-cli/tests/celld_generated_proof.rs index 1a392a3b0..5d286a4ab 100644 --- a/crates/edgezero-cli/tests/celld_generated_proof.rs +++ b/crates/edgezero-cli/tests/celld_generated_proof.rs @@ -6,11 +6,6 @@ //! `CELLD_BIN`, Node.js and OpenSSL. The app trusts the fixture certificate //! through `SSL_CERT_FILE`. -#[cfg(test)] -#[cfg(unix)] -#[path = "support/blocking_accept.rs"] -mod blocking_accept; - #[cfg(test)] #[cfg(unix)] mod tests { @@ -19,7 +14,7 @@ mod tests { reason = "keep fixture ownership, generated source and proof steps together" )] - use crate::blocking_accept::accept_blocking; + use edgezero_core::test_net::accept_blocking; use std::collections::BTreeMap; use std::env; #[cfg(target_os = "linux")] diff --git a/crates/edgezero-cli/tests/dynamodb_generated_proof.rs b/crates/edgezero-cli/tests/dynamodb_generated_proof.rs index 753e2a196..95bc8bee9 100644 --- a/crates/edgezero-cli/tests/dynamodb_generated_proof.rs +++ b/crates/edgezero-cli/tests/dynamodb_generated_proof.rs @@ -7,11 +7,6 @@ //! fixture with dummy credentials and a cleared child environment. Serialize builds that share //! `EDGEZERO_GENERATED_TEST_TARGET_DIR`. -#[cfg(test)] -#[cfg(unix)] -#[path = "support/blocking_accept.rs"] -mod blocking_accept; - #[cfg(test)] mod tests { #[cfg(unix)] @@ -21,7 +16,7 @@ mod tests { reason = "group test fixture types and their protocol helpers by responsibility" )] - use crate::blocking_accept::accept_blocking; + use edgezero_core::test_net::accept_blocking; use std::collections::BTreeMap; use std::env; use std::fs; diff --git a/crates/edgezero-cli/tests/native_store_generated_proof.rs b/crates/edgezero-cli/tests/native_store_generated_proof.rs index e2d09a7f0..384d61cc3 100644 --- a/crates/edgezero-cli/tests/native_store_generated_proof.rs +++ b/crates/edgezero-cli/tests/native_store_generated_proof.rs @@ -20,15 +20,10 @@ //! `EDGEZERO_GENERATED_TEST_TARGET_DIR` can select a shared target directory; otherwise builds //! use the generated project's `target/`. Serialize builds that share a target directory. -#[cfg(test)] -#[cfg(unix)] -#[path = "support/blocking_accept.rs"] -mod blocking_accept; - #[cfg(test)] #[cfg(unix)] mod tests { - use crate::blocking_accept::accept_blocking; + use edgezero_core::test_net::accept_blocking; use std::env::var_os; use std::fs; use std::io::{ErrorKind, Read as _, Write as _}; diff --git a/crates/edgezero-cli/tests/support/blocking_accept.rs b/crates/edgezero-cli/tests/support/blocking_accept.rs deleted file mode 100644 index 2eb24b00c..000000000 --- a/crates/edgezero-cli/tests/support/blocking_accept.rs +++ /dev/null @@ -1,68 +0,0 @@ -//! Accept helper for test fixtures that poll a non-blocking std listener. - -use std::io; -use std::net::{SocketAddr, TcpListener, TcpStream}; - -/// Accepts one connection and returns its stream in blocking mode. -/// -/// Fixtures make the listener non-blocking so their accept loop can poll a deadline or stop -/// flag. macOS `accept(2)` copies `O_NONBLOCK` to the accepted socket (Linux does not), so a -/// read on the returned stream would otherwise fail with `WouldBlock` at once instead of -/// honouring its read timeout. `WouldBlock` from `accept` itself is still returned to the caller. -#[inline] -pub(crate) fn accept_blocking(listener: &TcpListener) -> io::Result<(TcpStream, SocketAddr)> { - let (stream, peer) = listener.accept()?; - stream.set_nonblocking(false)?; - Ok((stream, peer)) -} - -#[cfg(test)] -mod tests { - use super::accept_blocking; - use std::io::{ErrorKind, Read as _}; - use std::net::{TcpListener, TcpStream}; - use std::thread; - use std::time::{Duration, Instant}; - - #[test] - fn stream_accepted_from_nonblocking_listener_waits_for_read_timeout() { - let listener = TcpListener::bind("127.0.0.1:0").expect("bind loopback"); - listener - .set_nonblocking(true) - .expect("nonblocking listener"); - let address = listener.local_addr().expect("listener address"); - let _client = TcpStream::connect(address).expect("connect loopback client"); - let deadline = Instant::now() - .checked_add(Duration::from_secs(2)) - .expect("deadline fits the monotonic clock"); - let (mut stream, _peer) = loop { - match accept_blocking(&listener) { - Ok(accepted) => break accepted, - Err(error) if error.kind() == ErrorKind::WouldBlock => { - assert!( - Instant::now() < deadline, - "loopback connection was not queued" - ); - thread::sleep(Duration::from_millis(5)); - } - Err(error) => panic!("accept failed: {error}"), - } - }; - stream - .set_read_timeout(Some(Duration::from_millis(200))) - .expect("read timeout"); - let started = Instant::now(); - let error = stream - .read(&mut [0_u8; 1]) - .expect_err("the client sent nothing"); - let waited = started.elapsed(); - assert!( - matches!(error.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut), - "unexpected read error: {error}" - ); - assert!( - waited >= Duration::from_millis(150), - "read returned after {waited:?}, before its 200 ms timeout" - ); - } -} diff --git a/crates/edgezero-core/src/lib.rs b/crates/edgezero-core/src/lib.rs index 5be4dcfb9..5bff38cf9 100644 --- a/crates/edgezero-core/src/lib.rs +++ b/crates/edgezero-core/src/lib.rs @@ -54,6 +54,9 @@ pub mod store_registry; /// module docs. Enable via the `test-utils` feature in `[dev-dependencies]`. #[cfg(any(test, feature = "test-utils"))] pub mod test_env; +/// Native socket helpers for cross-crate test fixtures. +#[cfg(all(not(target_arch = "wasm32"), any(test, feature = "test-utils")))] +pub mod test_net; pub mod time; pub use body::{Body, BodyPayload, BodyStream}; diff --git a/crates/edgezero-store-aws/src/test_net.rs b/crates/edgezero-core/src/test_net.rs similarity index 93% rename from crates/edgezero-store-aws/src/test_net.rs rename to crates/edgezero-core/src/test_net.rs index 2eb24b00c..e36c5b3aa 100644 --- a/crates/edgezero-store-aws/src/test_net.rs +++ b/crates/edgezero-core/src/test_net.rs @@ -5,12 +5,16 @@ use std::net::{SocketAddr, TcpListener, TcpStream}; /// Accepts one connection and returns its stream in blocking mode. /// +/// # Errors +/// +/// Returns the listener accept error or an error restoring blocking mode. +/// /// Fixtures make the listener non-blocking so their accept loop can poll a deadline or stop /// flag. macOS `accept(2)` copies `O_NONBLOCK` to the accepted socket (Linux does not), so a /// read on the returned stream would otherwise fail with `WouldBlock` at once instead of /// honouring its read timeout. `WouldBlock` from `accept` itself is still returned to the caller. #[inline] -pub(crate) fn accept_blocking(listener: &TcpListener) -> io::Result<(TcpStream, SocketAddr)> { +pub fn accept_blocking(listener: &TcpListener) -> io::Result<(TcpStream, SocketAddr)> { let (stream, peer) = listener.accept()?; stream.set_nonblocking(false)?; Ok((stream, peer)) diff --git a/crates/edgezero-store-aws/src/dynamodb_records_tests.rs b/crates/edgezero-store-aws/src/dynamodb_records_tests.rs index 63616e527..5b743ba93 100644 --- a/crates/edgezero-store-aws/src/dynamodb_records_tests.rs +++ b/crates/edgezero-store-aws/src/dynamodb_records_tests.rs @@ -9,8 +9,8 @@ use super::*; use crate::dynamodb_kv::sdk_tests::{active_table, loopback_client, read_request}; use crate::settings::{AwsPreparationLimits, DynamoDbKvLimits}; -use crate::test_net::accept_blocking; use edgezero_core::record_store::{RecordKeyLayout, contract}; +use edgezero_core::test_net::accept_blocking; use edgezero_core::time::MonotonicClock; use serde_json::{Value, json}; use std::collections::{BTreeMap, BTreeSet, VecDeque}; diff --git a/crates/edgezero-store-aws/src/dynamodb_tests.rs b/crates/edgezero-store-aws/src/dynamodb_tests.rs index a6d032f0f..989cf9680 100644 --- a/crates/edgezero-store-aws/src/dynamodb_tests.rs +++ b/crates/edgezero-store-aws/src/dynamodb_tests.rs @@ -12,7 +12,7 @@ use super::*; use crate::preparation::AwsPreparation; use crate::settings::{AwsPreparationLimits, DynamoDbKvLimits, DynamoDbKvSettings}; -use crate::test_net::accept_blocking; +use edgezero_core::test_net::accept_blocking; use edgezero_core::time::MonotonicClock; use std::collections::{BTreeMap, HashMap, VecDeque}; use std::io::{ErrorKind, Read as _, Write as _}; diff --git a/crates/edgezero-store-aws/src/lib.rs b/crates/edgezero-store-aws/src/lib.rs index 24c7e3e56..c4df04a63 100644 --- a/crates/edgezero-store-aws/src/lib.rs +++ b/crates/edgezero-store-aws/src/lib.rs @@ -53,12 +53,6 @@ mod secrets_manager; #[cfg(test)] #[cfg(all(not(target_arch = "wasm32"), feature = "secrets-manager"))] mod snapshot_tests; -#[cfg(test)] -#[cfg(all( - not(target_arch = "wasm32"), - any(feature = "secrets-manager", feature = "dynamodb-kv") -))] -mod test_net; #[cfg(all( not(target_arch = "wasm32"), any( diff --git a/crates/edgezero-store-aws/src/secrets_manager.rs b/crates/edgezero-store-aws/src/secrets_manager.rs index 53ecede1d..72d457254 100644 --- a/crates/edgezero-store-aws/src/secrets_manager.rs +++ b/crates/edgezero-store-aws/src/secrets_manager.rs @@ -148,10 +148,16 @@ impl AwsPreparation { .operation_timeout(operation_budget) .operation_attempt_timeout(attempt_budget) .build(); + let customized_request = request.customize(); + #[cfg(test)] + #[expect( + clippy::shadow_reuse, + reason = "test-only instrumentation keeps the production request path included in test builds" + )] + let customized_request = customized_request.interceptor(tests::SdkExecutionProbe); let result = timeout( operation_budget, - request - .customize() + customized_request .config_override( aws_sdk_secretsmanager::Config::builder().timeout_config(per_operation), ) @@ -197,6 +203,8 @@ impl AwsPreparation { } fn classify_operation_error(error: &SdkError) -> PreparationError { + #[cfg(test)] + tests::record_attempt_timeout(error); if matches!(error, SdkError::TimeoutError(_)) || matches!(error, SdkError::DispatchFailure(failure) if failure.is_timeout()) { @@ -303,11 +311,11 @@ fn classify_sdk_error( mod tests { use super::{classify_operation_error, materialize_payload}; use crate::PreparationError; - use crate::test_net::accept_blocking; use aws_sdk_secretsmanager::error::{ConnectorError, SdkError}; use aws_sdk_secretsmanager::operation::get_secret_value::GetSecretValueOutput; use aws_sdk_secretsmanager::primitives::Blob; use bytes::Bytes; + use edgezero_core::test_net::accept_blocking; use std::io::{Error as IoError, ErrorKind}; use std::io::{Read as _, Write as _}; use std::net::{TcpListener, TcpStream}; @@ -318,19 +326,41 @@ mod tests { use std::time::{Duration, Instant}; /// How long the holding fixture waits for the client to abandon an unanswered attempt. - /// The timeout child's attempt deadline is 100 ms and its operation budget is 10 s, so only - /// the attempt deadline can close a held connection inside this bound. + /// This bounds the fixture read after accept; it does not identify the client's timeout + /// cause, since an attempt may already have ended before the fixture accepts it. const HOLD_BOUND: Duration = Duration::from_secs(5); const TEST_ARN: &str = "arn:aws:secretsmanager:us-east-1:111122223333:secret:fixture-AbCdEf"; static NEXT_FIXTURE: AtomicU64 = AtomicU64::new(0); + static SDK_EXECUTIONS: AtomicU64 = AtomicU64::new(0); + static OBSERVED_ATTEMPT_TIMEOUT: AtomicBool = AtomicBool::new(false); + + #[derive(Debug)] + pub(super) struct SdkExecutionProbe; + + #[expect( + clippy::missing_trait_methods, + reason = "the execution observer must retain the SDK defaults for every other pipeline hook" + )] + impl aws_sdk_secretsmanager::config::Intercept for SdkExecutionProbe { + fn name(&self) -> &'static str { + "test-sdk-execution-count" + } + + fn read_before_execution( + &self, + _context: &aws_sdk_secretsmanager::config::interceptors::BeforeSerializationInterceptorContextRef<'_>, + _config: &mut aws_sdk_secretsmanager::config::ConfigBag, + ) -> Result<(), aws_smithy_runtime_api::box_error::BoxError> { + SDK_EXECUTIONS.fetch_add(1, Ordering::Relaxed); + Ok(()) + } + } /// One connection the SDK opened against `holding_fixture`. struct HeldConnection { /// The client closed the connection within `HOLD_BOUND`. closed_by_client: bool, - /// Lowercased request head and body, when the complete request arrived first. - request: Option<(String, String)>, } struct LoopbackFixture { @@ -362,6 +392,44 @@ mod tests { Success, } + pub(super) fn record_attempt_timeout( + error: &SdkError, + ) { + if !matches!(error, SdkError::TimeoutError(_)) { + return; + } + // aws-smithy-runtime 1.16.0 exposes no typed kind/duration accessor for its private + // MaybeTimeoutError. Recheck this exact comparison when upgrading the pinned SDK. + // Source text is compared locally and never printed or retained. + let mut source: Option<&dyn std::error::Error> = Some(error); + while let Some(source_error) = source { + if source_error.to_string() + == "operation attempt timeout (single attempt) occurred after 100ms" + { + OBSERVED_ATTEMPT_TIMEOUT.store(true, Ordering::Relaxed); + } + source = source_error.source(); + } + } + + #[expect( + clippy::print_stdout, + reason = "only fixed verified timeout markers reach the parent fixture" + )] + fn report_timeout_evidence() { + assert_eq!( + SDK_EXECUTIONS.load(Ordering::Relaxed), + 1, + "preparation must issue one SDK send; the SDK alone owns retries" + ); + assert!( + OBSERVED_ATTEMPT_TIMEOUT.load(Ordering::Relaxed), + "the pinned SDK must report the exact 100 ms attempt timeout before sanitization" + ); + println!("sdk-executions: 1"); + println!("sdk-attempt-timeout: 100ms"); + } + fn assert_sdk_fixture_scope() { let endpoint = std::env::var("AWS_ENDPOINT_URL_SECRETS_MANAGER").expect("fixture endpoint required"); @@ -378,43 +446,81 @@ mod tests { ); } - fn respond(mut stream: TcpStream, response: FixtureResponse) -> (String, String) { - stream - .set_read_timeout(Some(Duration::from_secs(3))) - .expect("request read timeout"); - let mut request = Vec::new(); - let mut chunk = [0_u8; 4096]; - let header_end = loop { - let read = stream.read(&mut chunk).expect("read request headers"); - assert_ne!(read, 0, "SDK closed before request headers"); - request.extend_from_slice(&chunk[..read]); - if let Some(end) = request.windows(4).position(|bytes| bytes == b"\r\n\r\n") { - break end - .checked_add(4) - .expect("header terminator offset fits request"); - } - assert!(request.len() < 64 * 1024, "bounded fixture request headers"); - }; - let headers = String::from_utf8_lossy(&request[..header_end]).to_ascii_lowercase(); - let content_length = headers + /// Decode and validate complete SDK requests; timeout attempts may close before completion. + #[expect( + clippy::unwrap_in_result, + reason = "None means incomplete; malformed fixture requests must fail rather than look incomplete" + )] + fn decode_request(received: &[u8]) -> Option<(String, String)> { + let header_end = received + .windows(4) + .position(|bytes| bytes == b"\r\n\r\n")? + .checked_add(4) + .expect("header offset fits request"); + let headers = String::from_utf8_lossy(&received[..header_end]).to_ascii_lowercase(); + let length = headers .lines() .find_map(|line| line.strip_prefix("content-length:").map(str::trim)) .and_then(|value| value.parse::().ok()) .expect("SDK content length"); let body_end = header_end - .checked_add(content_length) + .checked_add(length) .expect("bounded request body end fits usize"); - while request.len() < body_end { - let read = stream.read(&mut chunk).expect("read request body"); - assert_ne!(read, 0, "SDK closed before request body"); - request.extend_from_slice(&chunk[..read]); - } - let body = String::from_utf8_lossy(&request[header_end..body_end]).into_owned(); + let body = String::from_utf8_lossy(received.get(header_end..body_end)?).into_owned(); assert!(headers.contains("x-amz-target: secretsmanager.getsecretvalue")); assert!( body.contains(TEST_ARN), - "request must contain only the fictional fixture ARN" + "request must contain the fictional fixture ARN" ); + Some((headers, body)) + } + + #[test] + fn fixture_decoder_waits_for_complete_headers_and_body() { + let body = serde_json::json!({"SecretId": TEST_ARN}).to_string(); + let head = format!( + "POST / HTTP/1.1\r\nX-Amz-Target: secretsmanager.GetSecretValue\r\nContent-Length: {}\r\n\r\n", + body.len() + ); + assert!(decode_request(b"POST / HTTP/1.1\r\n").is_none()); + assert!(decode_request(head.as_bytes()).is_none()); + let request = format!("{head}{body}"); + let (headers, decoded) = decode_request(request.as_bytes()).expect("complete request"); + assert!(headers.contains("x-amz-target: secretsmanager.getsecretvalue")); + assert_eq!(decoded, body); + } + + #[test] + #[should_panic(expected = "SDK closed before the complete request")] + fn scripted_fixture_rejects_incomplete_request() { + let listener = TcpListener::bind("127.0.0.1:0").expect("fixture listener"); + let mut client = + TcpStream::connect(listener.local_addr().expect("address")).expect("client"); + client + .write_all(b"POST / HTTP/1.1\r\n") + .expect("partial headers"); + client + .shutdown(std::net::Shutdown::Write) + .expect("close incomplete request"); + let (stream, _) = accept_blocking(&listener).expect("accept"); + let _response = respond(stream, FixtureResponse::Success); + } + + fn respond(mut stream: TcpStream, response: FixtureResponse) -> (String, String) { + stream + .set_read_timeout(Some(Duration::from_secs(3))) + .expect("request read timeout"); + let mut request = Vec::new(); + let mut chunk = [0_u8; 4096]; + let (headers, body) = loop { + if let Some(decoded) = decode_request(&request) { + break decoded; + } + let read = stream.read(&mut chunk).expect("read complete SDK request"); + assert_ne!(read, 0, "SDK closed before the complete request"); + request.extend_from_slice(&chunk[..read]); + assert!(request.len() < 64 * 1024, "bounded fixture request"); + }; let (status, code, payload) = match response { FixtureResponse::Decryption => (400_u16, "Bad Request", r#"{"__type":"DecryptionFailure","message":"VALUE_SENTINEL"}"#.to_owned()), FixtureResponse::Denied => (400_u16, "Bad Request", r#"{"__type":"AccessDeniedException","message":"ARN_SENTINEL CREDENTIAL_SENTINEL"}"#.to_owned()), @@ -503,23 +609,10 @@ mod tests { Err(error) => panic!("held connection read failed: {error}"), } }; - let request = received - .windows(4) - .position(|bytes| bytes == b"\r\n\r\n") - .and_then(|end| { - let head = String::from_utf8_lossy(&received[..end]).to_ascii_lowercase(); - let length = head - .lines() - .find_map(|line| line.strip_prefix("content-length:").map(str::trim)) - .and_then(|value| value.parse::().ok())?; - let body = received.get(end.checked_add(4)?..)?; - (body.len() >= length) - .then(|| (head, String::from_utf8_lossy(&body[..length]).into_owned())) - }); - HeldConnection { - closed_by_client, - request, - } + // Complete requests are validated identically to scripted responses; an attempt + // that times out before writing its full request remains legitimate. + let _request = decode_request(&received); + HeldConnection { closed_by_client } } fn loopback_fixture(responses: Vec) -> (String, LoopbackFixture) { @@ -860,6 +953,15 @@ mod tests { "timeout child failed: {}", String::from_utf8_lossy(&child.stderr) ); + let output = String::from_utf8_lossy(&child.stdout); + assert!( + output.contains("sdk-executions: 1\n"), + "exactly one SDK send is required" + ); + assert!( + output.contains("sdk-attempt-timeout: 100ms\n"), + "the SDK must identify the configured 100 ms attempt timeout" + ); assert!( (1..=3).contains(&held.len()), "only the SDK's own attempts (at most 3) reach the fixture: {} connections", @@ -867,18 +969,8 @@ mod tests { ); assert!( held.iter().all(|connection| connection.closed_by_client), - "the attempt deadline, not the 10 s operation budget, ends every unanswered attempt" + "the SDK must abandon every unanswered fixture connection" ); - for (head, body) in held - .iter() - .filter_map(|connection| connection.request.as_ref()) - { - assert!(head.contains("x-amz-target: secretsmanager.getsecretvalue")); - assert!( - body.contains(TEST_ARN), - "request must name only the fixture ARN" - ); - } } /// Invoked only by an env-cleared child process launched by the parent fixture. @@ -928,6 +1020,9 @@ mod tests { ) .expect("valid session"); let result = session.prepare_secrets(&settings, "runtime").await; + if scenario == "timeout" { + report_timeout_evidence(); + } match scenario.as_str() { "retry" | "current" | "stage" | "version" | "dedup" => { let handle = result.expect("fixture-backed mapped secret prepares"); From bbcb62f180d77264999dcbc45fa6bb5c197bb103 Mon Sep 17 00:00:00 2001 From: prk-Jr Date: Wed, 2 Dec 2026 23:33:44 +0530 Subject: [PATCH 10/13] Clarify unsupported task registration validation precedence --- CHANGELOG.md | 12 +++--- .../src/after_response.rs | 8 ++-- crates/edgezero-adapter-spin/src/lib.rs | 4 +- crates/edgezero-core/src/after_response.rs | 6 ++- crates/edgezero-core/src/context.rs | 12 +++--- docs/guide/adapters/spin.md | 9 +++-- docs/guide/capabilities.md | 7 ++-- docs/guide/handlers.md | 4 +- .../2026-11-18-spin-after-response-error.md | 3 +- ...-11-18-spin-after-response-error-design.md | 38 +++++++++++-------- 10 files changed, 61 insertions(+), 42 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8fcbd948e..dacb62a38 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -137,13 +137,15 @@ readiness settings, and request records. eligible after the response attempt ends; its budget starts then, and the adapter cancels it before its next poll once the budget expires. A request may register at most 64 tasks, each with a budget of at most 30 s (`MAX_AFTER_RESPONSE_TASKS`, `MAX_AFTER_RESPONSE_BUDGET`). Adapters - without support return `501 Not Implemented` at registration. + without support return `501 Not Implemented` when no handle is installed or after an installed + handle's budget and task-limit checks pass. - Add the `after-response-tasks` capability: Axum and Fastly `BoundedCooperative`, Cloudflare `BoundedCooperative` (#478), and Spin `Unsupported`. -- Spin rejects after-response tasks with a `501` that names the adapter - (`edgezero_adapter_spin::AFTER_RESPONSE_UNSUPPORTED`) on every converted request, instead of - core's generic message (#483). A zero budget on Spin now returns `500`, as on Axum and Fastly, - instead of `501`. +- Spin installs a rejecting after-response scheduler on every converted request. Registrations + that pass core's budget and task-limit checks receive a `501` naming the adapter + (`edgezero_adapter_spin::AFTER_RESPONSE_UNSUPPORTED`), instead of core's generic message (#483). + A zero or over-limit budget on Spin now returns `500` before reaching the scheduler, instead + of the generic `501` returned when no handle was installed. - Axum production, `run_app` and `AxumDevServer::run` shutdown now waits for registered after-response tasks within the existing shutdown grace, after connections drain. Tasks still pending at the grace make the process exit non-zero with `grace exhausted`. diff --git a/crates/edgezero-adapter-spin/src/after_response.rs b/crates/edgezero-adapter-spin/src/after_response.rs index c4af7d3e4..8034a7e66 100644 --- a/crates/edgezero-adapter-spin/src/after_response.rs +++ b/crates/edgezero-adapter-spin/src/after_response.rs @@ -1,7 +1,9 @@ //! Spin's after-response capability error. //! -//! Spin does not run after-response tasks. Every converted request carries a scheduler that -//! rejects them with a `501` naming the Spin adapter, instead of core's generic error. +//! Spin does not run after-response tasks. Every converted request carries a rejecting scheduler. +//! Core first checks the budget and task limit; zero or over-limit budgets return `500`. +//! Registrations that pass those checks reach the scheduler and receive a `501` naming Spin, +//! instead of core's generic error. use std::time::Duration; @@ -25,7 +27,7 @@ impl AfterResponseScheduler for SpinAfterResponseUnsupported { } } -/// Handle inserted into every Spin request so registration fails with the Spin capability error. +/// Installs Spin's capability error after core's budget and task-limit checks pass. pub(crate) fn unsupported_handle() -> AfterResponseHandle { AfterResponseHandle::new(SpinAfterResponseUnsupported) } diff --git a/crates/edgezero-adapter-spin/src/lib.rs b/crates/edgezero-adapter-spin/src/lib.rs index 7c87be8a4..9b5fb878a 100644 --- a/crates/edgezero-adapter-spin/src/lib.rs +++ b/crates/edgezero-adapter-spin/src/lib.rs @@ -81,8 +81,8 @@ pub const AKAMAI_FUNCTIONS_PLATFORM: edgezero_core::PlatformMetadata = ), ); -/// Message of the `501 Not Implemented` error that `RequestContext::after_response` returns on -/// Spin, which does not run after-response tasks. +/// Message of Spin's rejecting after-response scheduler's `501 Not Implemented` error. +/// Core checks the budget and task limit before calling that scheduler. pub const AFTER_RESPONSE_UNSUPPORTED: &str = "after-response tasks are not supported by the Spin adapter"; diff --git a/crates/edgezero-core/src/after_response.rs b/crates/edgezero-core/src/after_response.rs index 2f6a2300c..1244f4e87 100644 --- a/crates/edgezero-core/src/after_response.rs +++ b/crates/edgezero-core/src/after_response.rs @@ -4,8 +4,10 @@ //! The task becomes eligible once the request's response attempt ends at the adapter's terminal //! egress boundary, and its budget starts at that point. Once the budget expires, the adapter //! cancels the task before its next poll; it cannot interrupt a running poll. Adapters without -//! support install either no handle or one that rejects every task, so registration fails with -//! [`EdgeError::NotImplemented`]. +//! support install either no handle or one that rejects every task. Without a handle, +//! registration returns [`EdgeError::NotImplemented`] for any budget. An installed handle first +//! checks the budget and task limit, returning an internal error if either is invalid. A +//! rejecting scheduler returns [`EdgeError::NotImplemented`] after those checks pass. use std::fmt; use std::future::poll_fn; diff --git a/crates/edgezero-core/src/context.rs b/crates/edgezero-core/src/context.rs index 0a8f4645a..a1134a057 100644 --- a/crates/edgezero-core/src/context.rs +++ b/crates/edgezero-core/src/context.rs @@ -358,12 +358,14 @@ impl RequestContext { /// request's scope. /// /// # Errors - /// Returns [`EdgeError::NotImplemented`] when the adapter does not support after-response - /// tasks. Returns an internal error for a zero `budget`, a `budget` above - /// [`MAX_AFTER_RESPONSE_BUDGET`](crate::after_response::MAX_AFTER_RESPONSE_BUDGET), once the + /// Without an installed handle, returns [`EdgeError::NotImplemented`] for any budget. + /// An installed handle first returns an internal error for a zero `budget`, a `budget` above + /// [`MAX_AFTER_RESPONSE_BUDGET`](crate::after_response::MAX_AFTER_RESPONSE_BUDGET), or once the /// request registered - /// [`MAX_AFTER_RESPONSE_TASKS`](crate::after_response::MAX_AFTER_RESPONSE_TASKS) tasks, or - /// for the adapter's scheduling error. The task is dropped unpolled on error. + /// [`MAX_AFTER_RESPONSE_TASKS`](crate::after_response::MAX_AFTER_RESPONSE_TASKS) tasks. If those + /// checks pass, returns the adapter's scheduling error, including + /// [`EdgeError::NotImplemented`] from an unsupported scheduler. The task is dropped unpolled + /// on error. #[inline] pub fn after_response(&self, budget: Duration, task: F) -> Result<(), EdgeError> where diff --git a/docs/guide/adapters/spin.md b/docs/guide/adapters/spin.md index 70c90d987..dcf3650d6 100644 --- a/docs/guide/adapters/spin.md +++ b/docs/guide/adapters/spin.md @@ -612,12 +612,13 @@ and remove the cache to roll back; default generated entry points are unchanged. ## After-response tasks -Spin does not run after-response tasks. `ctx.after_response(budget, task)` with a positive budget -returns `EdgeError::NotImplemented` (`501`) with the message +Spin does not run after-response tasks. Core checks registration limits first: the budget must +be positive and at most 30 seconds, and the request must have a task slot available. Violating +those limits returns `500`. Registrations that pass these checks reach Spin's scheduler and +return `EdgeError::NotImplemented` (`501`) with the message `after-response tasks are not supported by the Spin adapter`, exported as `edgezero_adapter_spin::AFTER_RESPONSE_UNSUPPORTED`. The task is dropped without being polled. -A zero budget is a programming error and returns `500`, as on every adapter that installs a -scheduler. Every Spin entry point that converts a native request installs this error, including +Every Spin entry point that converts a native request installs this scheduler, including `run_app`, `dispatch_app` and `request::into_core_request`. Branch on the status or the `not_implemented` kind rather than the message (core's constant of the same name does not match on Spin), and do the work inline or elsewhere. An application diff --git a/docs/guide/capabilities.md b/docs/guide/capabilities.md index d47982e62..45f1512cc 100644 --- a/docs/guide/capabilities.md +++ b/docs/guide/capabilities.md @@ -382,10 +382,11 @@ so CPU-bound or blocking work overruns it. 30 seconds after response completion or disconnect across all `waitUntil` calls; platform CPU/memory limits or earlier termination can shorten execution. Tasks have no persistence or automatic retry. See [Workers context limits](https://developers.cloudflare.com/workers/runtime-apis/context/#waituntil). -- Spin rejects every registration with a positive budget with `501 Not Implemented` and the - message `after-response tasks are not supported by the Spin adapter` +- Spin rejects registrations that pass core's budget and task-limit checks with `501 Not Implemented` + and the message `after-response tasks are not supported by the Spin adapter` (`edgezero_adapter_spin::AFTER_RESPONSE_UNSUPPORTED`). The task is dropped without being polled. - A zero budget returns `500`, as on Axum and Fastly. + Core returns `500` for a zero budget, a budget above 30 seconds, or an exhausted task limit before + calling the scheduler. ## Outbound Matrix diff --git a/docs/guide/handlers.md b/docs/guide/handlers.md index 19ee79e90..1e97cc74c 100644 --- a/docs/guide/handlers.md +++ b/docs/guide/handlers.md @@ -355,7 +355,9 @@ async fn page(ctx: RequestContext) -> Result<&'static str, EdgeError> { } ``` -Registration returns `501 Not Implemented` on adapters without support; see the +Without an installed handle, registration returns `501 Not Implemented` for any budget. An +installed handle checks the budget and task limit first, returning `500` for invalid limits; +unsupported schedulers return `501` after those checks pass. See the [after-response task matrix](./capabilities.md#after-response-task-matrix). Declare `after-response-tasks` as a required capability when the work is not optional. Tasks return `()`, so handle and log their own failures. A task cannot register further tasks. Cloudflare caps the diff --git a/docs/superpowers/plans/2026-11-18-spin-after-response-error.md b/docs/superpowers/plans/2026-11-18-spin-after-response-error.md index efa2316f0..bc92785a6 100644 --- a/docs/superpowers/plans/2026-11-18-spin-after-response-error.md +++ b/docs/superpowers/plans/2026-11-18-spin-after-response-error.md @@ -1,7 +1,8 @@ # Spin after-response capability error — plan Design: [`2026-11-18-spin-after-response-error-design.md`](../specs/2026-11-18-spin-after-response-error-design.md). -Issue: #483. Base branch: `feature/476-after-response-tasks` (PR #509). +Issue: #483. Original design base: `feature/476-after-response-tasks` (PR #509). +Current PR base: `feature/478-cloudflare-after-response` (PR #512). ## Tasks diff --git a/docs/superpowers/specs/2026-11-18-spin-after-response-error-design.md b/docs/superpowers/specs/2026-11-18-spin-after-response-error-design.md index 8a190f7a7..124d36a20 100644 --- a/docs/superpowers/specs/2026-11-18-spin-after-response-error-design.md +++ b/docs/superpowers/specs/2026-11-18-spin-after-response-error-design.md @@ -3,14 +3,17 @@ Date: 2026-11-18 Status: approved for implementation. -Issue: [#483](https://github.com/IABTechLab/edgezero/issues/483). Base: [PR #509](https://github.com/IABTechLab/edgezero/pull/509) -(`feature/476-after-response-tasks`), which adds `RequestContext::after_response`, the -`after-response-tasks` capability, and the portable `501` returned when no scheduler is installed. +Issue: [#483](https://github.com/IABTechLab/edgezero/issues/483). Original design base: +[PR #509](https://github.com/IABTechLab/edgezero/pull/509) (`feature/476-after-response-tasks`), +which adds `RequestContext::after_response`, the `after-response-tasks` capability, and the +portable `501` returned when no scheduler is installed. The current PR base is +[PR #512](https://github.com/IABTechLab/edgezero/pull/512) (`feature/478-cloudflare-after-response`), +which already installs Cloudflare's scheduler on managed requests. ## Goal -A Spin handler that calls `ctx.after_response(budget, task)` gets an explicit capability error -that names the Spin adapter. The task is never polled and is dropped at registration. Apps that +A Spin handler that calls `ctx.after_response(budget, task)` within core's registration limits +gets an explicit capability error that names the Spin adapter. The task is never polled and is dropped at registration. Apps that declare `after-response-tasks` as required are refused for Spin before deployment. ## Why an explicit error, not support @@ -21,7 +24,7 @@ documented guarantee that work continues once the response is complete, and host them silently, which is the outcome #476 forbids. Real support would need its own design and platform evidence; it is out of scope. -## Current behavior on the base +## Behavior on the original #509 design base Spin installs no `AfterResponseHandle`. Registration falls through to core's generic `EdgeError::not_implemented("after-response tasks are not supported by this adapter")`. The @@ -33,18 +36,21 @@ adapter that forgot to install a scheduler, and it says nothing about which adap ## Contract -- **Status and kind.** Registration with a positive budget on any Spin request returns - `EdgeError::NotImplemented` (HTTP `501`, kind `not_implemented`), unchanged from the base. +- **Status and kind.** Registration that passes core's budget and task-limit checks on a Spin + request returns `EdgeError::NotImplemented` (HTTP `501`, kind `not_implemented`), unchanged + from the original design base for those inputs. - **Message.** `after-response tasks are not supported by the Spin adapter`. Defined, with no cfg gate, as `edgezero_adapter_spin::AFTER_RESPONSE_UNSUPPORTED` in `lib.rs` (beside `SPIN_PLATFORM`), so host-side app tests can name it too. Applications should branch on the status or kind, not the message. - **Task.** Never polled. Dropped before `after_response` returns. -- **Zero budget.** Changes from `501` to `500`. On the base, Spin installed no handle, so core's - `schedule_with` returned `501` before any budget check. With a handle installed, core's - `AfterResponseHandle::schedule` rejects a zero budget with `500` before the scheduler is called. - That is #509's rule for a programming error, and Axum and Fastly already behave this way. - Cloudflare, which still installs no handle, keeps `501` until #478. +- **Registration limits.** On the original #509 design base, Spin installed no handle, so core's + `schedule_with` returned `501` for any budget. With a handle installed, + `AfterResponseHandle::schedule` first returns `500` for a zero budget, a budget above 30 seconds, + or an exhausted 64-task limit, before calling the scheduler. Refused tasks release their slot. + Cloudflare had no handle on that original base and returned `501` for a zero budget. On the + current #512 base, managed Cloudflare requests have a handle and return `500` for that input. + Bare contexts without a handle continue returning the generic `501` for any budget. - **Reach.** The handle is installed where every native Spin request becomes a core request (`into_core_request_head`). That covers `run_app`, `run_app_with_platform`, `dispatch_app`, `AppExt::dispatch`, `dispatch`, `dispatch_with_kv_label` and the public `into_core_request`. @@ -126,6 +132,6 @@ generic message. ## Out of scope - Running after-response tasks on Spin. -- Cloudflare (#478, PR #512). PR #512 edits the same `capabilities.md` bullet and the same - `CHANGELOG.md` capability line, and says Spin installs no scheduler; whichever lands second - rebases that sentence. +- Cloudflare support (#478, PR #512) is supplied by the current base. The CHANGELOG and capability + guide have already been reconciled to retain Cloudflare's support and Spin's unsupported + capability with its installed rejecting scheduler. From cb37b00e69666f042541a6067b1b07c2922ef020 Mon Sep 17 00:00:00 2001 From: prk-Jr Date: Thu, 3 Dec 2026 07:19:50 +0530 Subject: [PATCH 11/13] fix(ci): refresh offline dependency and isolate process fixtures --- Cargo.lock | 4 +-- .../fixtures/request-fidelity/Cargo.lock | 4 +-- .../fixtures/reusable-app/Cargo.lock | 4 +-- crates/edgezero-test-harness/src/main.rs | 23 ++++++++++-- crates/edgezero-test-harness/src/startup.rs | 35 +++++++++++++++++++ examples/app-demo/Cargo.lock | 4 +-- examples/geo-kv-prototype/Cargo.lock | 4 +-- examples/geo-spin-loader/Cargo.lock | 4 +-- 8 files changed, 67 insertions(+), 15 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5de661a8c..3e53b0222 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2521,9 +2521,9 @@ dependencies = [ [[package]] name = "pin-project-lite" -version = "0.2.17" +version = "0.2.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +checksum = "f120c8d5021b34abd2f2ffd7ee96687cbcd6c54a3e68d86b6169f4a5cd480ffe" [[package]] name = "pin-utils" diff --git a/crates/edgezero-test-harness/fixtures/request-fidelity/Cargo.lock b/crates/edgezero-test-harness/fixtures/request-fidelity/Cargo.lock index 61cd28627..d7ffca03b 100644 --- a/crates/edgezero-test-harness/fixtures/request-fidelity/Cargo.lock +++ b/crates/edgezero-test-harness/fixtures/request-fidelity/Cargo.lock @@ -1046,9 +1046,9 @@ dependencies = [ [[package]] name = "pin-project-lite" -version = "0.2.17" +version = "0.2.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +checksum = "f120c8d5021b34abd2f2ffd7ee96687cbcd6c54a3e68d86b6169f4a5cd480ffe" [[package]] name = "potential_utf" diff --git a/crates/edgezero-test-harness/fixtures/reusable-app/Cargo.lock b/crates/edgezero-test-harness/fixtures/reusable-app/Cargo.lock index b9a601443..569120f67 100644 --- a/crates/edgezero-test-harness/fixtures/reusable-app/Cargo.lock +++ b/crates/edgezero-test-harness/fixtures/reusable-app/Cargo.lock @@ -1609,9 +1609,9 @@ dependencies = [ [[package]] name = "pin-project-lite" -version = "0.2.17" +version = "0.2.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +checksum = "f120c8d5021b34abd2f2ffd7ee96687cbcd6c54a3e68d86b6169f4a5cd480ffe" [[package]] name = "potential_utf" diff --git a/crates/edgezero-test-harness/src/main.rs b/crates/edgezero-test-harness/src/main.rs index 350366483..48f0ad3aa 100644 --- a/crates/edgezero-test-harness/src/main.rs +++ b/crates/edgezero-test-harness/src/main.rs @@ -1487,11 +1487,17 @@ mod process_tests { return; }; let path = PathBuf::from(std::env::var_os("EDGEZERO_PROCESS_TEST_DIR").unwrap()); - if mode == "static-check" { + if matches!(mode.as_str(), "static-check" | "cargo-cancellation") { let arguments = serde_json::from_str(&std::env::var("EDGEZERO_STATIC_CHECK_ARGS").unwrap()) .unwrap(); - exit_result(run(arguments)); + let result = if mode == "cargo-cancellation" { + // Supervisor fixtures exercise fake Cargo, not source/compiler fingerprinting. + startup::with_fixture_build_id(TEST_BUILD_ID, || run(arguments)) + } else { + run(arguments) + }; + exit_result(result); } if mode == "acceptance-blocked-git" { let ready = path.join("git-started"); @@ -1879,16 +1885,24 @@ case "$1" in esac "#).unwrap(); fs::set_permissions(&cargo, fs::Permissions::from_mode(0o700)).unwrap(); + let compiler = fixture.0.join("rustc"); + fs::write( + &compiler, + "#!/bin/sh\ncase \"$1\" in\n --version) printf 'rustc process-fixture\\n' ;;\n *) exit 64 ;;\nesac\n", + ) + .unwrap(); + fs::set_permissions(&compiler, fs::Permissions::from_mode(0o700)).unwrap(); let output = fixture.0.join("evidence"); let mut command = static_check_command(&fixture, "--help"); command + .env("EDGEZERO_PROCESS_TEST_MODE", "cargo-cancellation") .env( "EDGEZERO_STATIC_CHECK_ARGS", json!(["--adapter", adapter, "--suite", suite, "--output", output,]).to_string(), ) .env("EDGEZERO_TEST_HELPER", std::env::current_exe().unwrap()) .env("CARGO", &cargo) - .env("RUSTC", executable("RUSTC", "rustc").unwrap()) + .env("RUSTC", &compiler) .env("WRANGLER_BIN", &cargo) .env("WORKER_BUILD_BIN", &cargo); let mut controller = @@ -1948,6 +1962,9 @@ esac descendant_closed, "{adapter}: Cargo descendant retained its socket" ); + let events = fs::read_to_string(output.join("events.jsonl")).unwrap(); + let run: serde_json::Value = serde_json::from_str(events.lines().next().unwrap()).unwrap(); + assert_eq!(run["fixture_build_id"], TEST_BUILD_ID); } #[test] diff --git a/crates/edgezero-test-harness/src/startup.rs b/crates/edgezero-test-harness/src/startup.rs index 018bec708..ca0298fa7 100644 --- a/crates/edgezero-test-harness/src/startup.rs +++ b/crates/edgezero-test-harness/src/startup.rs @@ -26,6 +26,8 @@ const UNATTESTED_FAULT_PATHS: &[&str] = &[ static LAUNCHES: Mutex>>> = Mutex::new(Vec::new()); thread_local! { static CURRENT: RefCell>>> = const { RefCell::new(None) }; + #[cfg(test)] + static FIXTURE_BUILD_ID: RefCell> = const { RefCell::new(None) }; } #[derive(Clone)] @@ -61,9 +63,25 @@ pub struct Launch { } pub fn build_id() -> Result { + #[cfg(test)] + if let Some(identity) = FIXTURE_BUILD_ID.with_borrow(|identity| *identity) { + return Ok(identity.to_owned()); + } build_identity::current() } +#[cfg(test)] +pub(crate) fn with_fixture_build_id(identity: &'static str, run: impl FnOnce() -> T) -> T { + struct Restore(Option<&'static str>); + impl Drop for Restore { + fn drop(&mut self) { + FIXTURE_BUILD_ID.with_borrow_mut(|identity| *identity = self.0); + } + } + let _restore = Restore(FIXTURE_BUILD_ID.with_borrow_mut(|id| id.replace(identity))); + run() +} + pub fn owned_process_group(port: u16) -> Result { let registered = find(port).ok_or("no owned runtime for this port")?; let mut launch = registered.lock().unwrap(); @@ -318,6 +336,23 @@ pub fn remaining(port: u16, budget: Duration) -> Result { mod identity_tests { use super::*; + #[test] + fn fixture_identity_restores_real_capture_after_nested_unwind() { + let real = build_id().unwrap(); + with_fixture_build_id("outer-fixture", || { + assert_eq!(build_id().unwrap(), "outer-fixture"); + let failed = std::panic::catch_unwind(|| { + with_fixture_build_id("inner-fixture", || { + assert_eq!(build_id().unwrap(), "inner-fixture"); + panic!("controlled fixture unwind"); + }); + }); + assert!(failed.is_err()); + assert_eq!(build_id().unwrap(), "outer-fixture"); + }); + assert_eq!(build_id().unwrap(), real); + } + #[test] fn unchanged_build_identity_keeps_each_launch_nonce_fresh() { let mut first = Command::new("unused-test-command"); diff --git a/examples/app-demo/Cargo.lock b/examples/app-demo/Cargo.lock index 8ed6a707e..d5e9e7f75 100644 --- a/examples/app-demo/Cargo.lock +++ b/examples/app-demo/Cargo.lock @@ -2486,9 +2486,9 @@ dependencies = [ [[package]] name = "pin-project-lite" -version = "0.2.17" +version = "0.2.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +checksum = "f120c8d5021b34abd2f2ffd7ee96687cbcd6c54a3e68d86b6169f4a5cd480ffe" [[package]] name = "pin-utils" diff --git a/examples/geo-kv-prototype/Cargo.lock b/examples/geo-kv-prototype/Cargo.lock index fefd2cd54..57ef5c782 100644 --- a/examples/geo-kv-prototype/Cargo.lock +++ b/examples/geo-kv-prototype/Cargo.lock @@ -1666,9 +1666,9 @@ checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" [[package]] name = "pin-project-lite" -version = "0.2.17" +version = "0.2.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +checksum = "f120c8d5021b34abd2f2ffd7ee96687cbcd6c54a3e68d86b6169f4a5cd480ffe" [[package]] name = "pin-utils" diff --git a/examples/geo-spin-loader/Cargo.lock b/examples/geo-spin-loader/Cargo.lock index f8ef1830c..d0bb96e9b 100644 --- a/examples/geo-spin-loader/Cargo.lock +++ b/examples/geo-spin-loader/Cargo.lock @@ -810,9 +810,9 @@ checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" [[package]] name = "pin-project-lite" -version = "0.2.17" +version = "0.2.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +checksum = "f120c8d5021b34abd2f2ffd7ee96687cbcd6c54a3e68d86b6169f4a5cd480ffe" [[package]] name = "potential_utf" From f75296d8ac14c112db6c7c2f325cabb60915167e Mon Sep 17 00:00:00 2001 From: prk-Jr Date: Thu, 3 Dec 2026 07:27:21 +0530 Subject: [PATCH 12/13] Refresh offline dependency closure and isolate cancellation fixtures --- Cargo.lock | 4 +-- .../fixtures/request-fidelity/Cargo.lock | 4 +-- .../fixtures/reusable-app/Cargo.lock | 4 +-- crates/edgezero-test-harness/src/main.rs | 23 ++++++++++-- crates/edgezero-test-harness/src/startup.rs | 35 +++++++++++++++++++ examples/app-demo/Cargo.lock | 4 +-- 6 files changed, 63 insertions(+), 11 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5de661a8c..3e53b0222 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2521,9 +2521,9 @@ dependencies = [ [[package]] name = "pin-project-lite" -version = "0.2.17" +version = "0.2.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +checksum = "f120c8d5021b34abd2f2ffd7ee96687cbcd6c54a3e68d86b6169f4a5cd480ffe" [[package]] name = "pin-utils" diff --git a/crates/edgezero-test-harness/fixtures/request-fidelity/Cargo.lock b/crates/edgezero-test-harness/fixtures/request-fidelity/Cargo.lock index 61cd28627..d7ffca03b 100644 --- a/crates/edgezero-test-harness/fixtures/request-fidelity/Cargo.lock +++ b/crates/edgezero-test-harness/fixtures/request-fidelity/Cargo.lock @@ -1046,9 +1046,9 @@ dependencies = [ [[package]] name = "pin-project-lite" -version = "0.2.17" +version = "0.2.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +checksum = "f120c8d5021b34abd2f2ffd7ee96687cbcd6c54a3e68d86b6169f4a5cd480ffe" [[package]] name = "potential_utf" diff --git a/crates/edgezero-test-harness/fixtures/reusable-app/Cargo.lock b/crates/edgezero-test-harness/fixtures/reusable-app/Cargo.lock index b9a601443..569120f67 100644 --- a/crates/edgezero-test-harness/fixtures/reusable-app/Cargo.lock +++ b/crates/edgezero-test-harness/fixtures/reusable-app/Cargo.lock @@ -1609,9 +1609,9 @@ dependencies = [ [[package]] name = "pin-project-lite" -version = "0.2.17" +version = "0.2.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +checksum = "f120c8d5021b34abd2f2ffd7ee96687cbcd6c54a3e68d86b6169f4a5cd480ffe" [[package]] name = "potential_utf" diff --git a/crates/edgezero-test-harness/src/main.rs b/crates/edgezero-test-harness/src/main.rs index 350366483..48f0ad3aa 100644 --- a/crates/edgezero-test-harness/src/main.rs +++ b/crates/edgezero-test-harness/src/main.rs @@ -1487,11 +1487,17 @@ mod process_tests { return; }; let path = PathBuf::from(std::env::var_os("EDGEZERO_PROCESS_TEST_DIR").unwrap()); - if mode == "static-check" { + if matches!(mode.as_str(), "static-check" | "cargo-cancellation") { let arguments = serde_json::from_str(&std::env::var("EDGEZERO_STATIC_CHECK_ARGS").unwrap()) .unwrap(); - exit_result(run(arguments)); + let result = if mode == "cargo-cancellation" { + // Supervisor fixtures exercise fake Cargo, not source/compiler fingerprinting. + startup::with_fixture_build_id(TEST_BUILD_ID, || run(arguments)) + } else { + run(arguments) + }; + exit_result(result); } if mode == "acceptance-blocked-git" { let ready = path.join("git-started"); @@ -1879,16 +1885,24 @@ case "$1" in esac "#).unwrap(); fs::set_permissions(&cargo, fs::Permissions::from_mode(0o700)).unwrap(); + let compiler = fixture.0.join("rustc"); + fs::write( + &compiler, + "#!/bin/sh\ncase \"$1\" in\n --version) printf 'rustc process-fixture\\n' ;;\n *) exit 64 ;;\nesac\n", + ) + .unwrap(); + fs::set_permissions(&compiler, fs::Permissions::from_mode(0o700)).unwrap(); let output = fixture.0.join("evidence"); let mut command = static_check_command(&fixture, "--help"); command + .env("EDGEZERO_PROCESS_TEST_MODE", "cargo-cancellation") .env( "EDGEZERO_STATIC_CHECK_ARGS", json!(["--adapter", adapter, "--suite", suite, "--output", output,]).to_string(), ) .env("EDGEZERO_TEST_HELPER", std::env::current_exe().unwrap()) .env("CARGO", &cargo) - .env("RUSTC", executable("RUSTC", "rustc").unwrap()) + .env("RUSTC", &compiler) .env("WRANGLER_BIN", &cargo) .env("WORKER_BUILD_BIN", &cargo); let mut controller = @@ -1948,6 +1962,9 @@ esac descendant_closed, "{adapter}: Cargo descendant retained its socket" ); + let events = fs::read_to_string(output.join("events.jsonl")).unwrap(); + let run: serde_json::Value = serde_json::from_str(events.lines().next().unwrap()).unwrap(); + assert_eq!(run["fixture_build_id"], TEST_BUILD_ID); } #[test] diff --git a/crates/edgezero-test-harness/src/startup.rs b/crates/edgezero-test-harness/src/startup.rs index 018bec708..ca0298fa7 100644 --- a/crates/edgezero-test-harness/src/startup.rs +++ b/crates/edgezero-test-harness/src/startup.rs @@ -26,6 +26,8 @@ const UNATTESTED_FAULT_PATHS: &[&str] = &[ static LAUNCHES: Mutex>>> = Mutex::new(Vec::new()); thread_local! { static CURRENT: RefCell>>> = const { RefCell::new(None) }; + #[cfg(test)] + static FIXTURE_BUILD_ID: RefCell> = const { RefCell::new(None) }; } #[derive(Clone)] @@ -61,9 +63,25 @@ pub struct Launch { } pub fn build_id() -> Result { + #[cfg(test)] + if let Some(identity) = FIXTURE_BUILD_ID.with_borrow(|identity| *identity) { + return Ok(identity.to_owned()); + } build_identity::current() } +#[cfg(test)] +pub(crate) fn with_fixture_build_id(identity: &'static str, run: impl FnOnce() -> T) -> T { + struct Restore(Option<&'static str>); + impl Drop for Restore { + fn drop(&mut self) { + FIXTURE_BUILD_ID.with_borrow_mut(|identity| *identity = self.0); + } + } + let _restore = Restore(FIXTURE_BUILD_ID.with_borrow_mut(|id| id.replace(identity))); + run() +} + pub fn owned_process_group(port: u16) -> Result { let registered = find(port).ok_or("no owned runtime for this port")?; let mut launch = registered.lock().unwrap(); @@ -318,6 +336,23 @@ pub fn remaining(port: u16, budget: Duration) -> Result { mod identity_tests { use super::*; + #[test] + fn fixture_identity_restores_real_capture_after_nested_unwind() { + let real = build_id().unwrap(); + with_fixture_build_id("outer-fixture", || { + assert_eq!(build_id().unwrap(), "outer-fixture"); + let failed = std::panic::catch_unwind(|| { + with_fixture_build_id("inner-fixture", || { + assert_eq!(build_id().unwrap(), "inner-fixture"); + panic!("controlled fixture unwind"); + }); + }); + assert!(failed.is_err()); + assert_eq!(build_id().unwrap(), "outer-fixture"); + }); + assert_eq!(build_id().unwrap(), real); + } + #[test] fn unchanged_build_identity_keeps_each_launch_nonce_fresh() { let mut first = Command::new("unused-test-command"); diff --git a/examples/app-demo/Cargo.lock b/examples/app-demo/Cargo.lock index 8ed6a707e..d5e9e7f75 100644 --- a/examples/app-demo/Cargo.lock +++ b/examples/app-demo/Cargo.lock @@ -2486,9 +2486,9 @@ dependencies = [ [[package]] name = "pin-project-lite" -version = "0.2.17" +version = "0.2.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +checksum = "f120c8d5021b34abd2f2ffd7ee96687cbcd6c54a3e68d86b6169f4a5cd480ffe" [[package]] name = "pin-utils" From 1ee3a4604f3abf18e86631f1a297a5992a01543e Mon Sep 17 00:00:00 2001 From: Aram Grigoryan <132480+aram356@users.noreply.github.com> Date: Fri, 4 Dec 2026 11:58:41 -0800 Subject: [PATCH 13/13] Stop listing an exhausted task limit among Spin's after-response 500 causes A refused registration gives its slot back, so Spin never reaches the 64-task limit. --- docs/guide/adapters/spin.md | 5 ++--- docs/guide/capabilities.md | 4 ++-- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/docs/guide/adapters/spin.md b/docs/guide/adapters/spin.md index 795088c63..ef99adc16 100644 --- a/docs/guide/adapters/spin.md +++ b/docs/guide/adapters/spin.md @@ -612,9 +612,8 @@ and remove the cache to roll back; default generated entry points are unchanged. ## After-response tasks -Spin does not run after-response tasks. Core checks registration limits first: the budget must -be positive and at most 30 seconds, and the request must have a task slot available. Violating -those limits returns `500`. Registrations that pass these checks reach Spin's scheduler and +Spin does not run after-response tasks. Core checks the budget first: it must be positive and at +most 30 seconds, or registration returns `500`. Registrations that pass reach Spin's scheduler and return `EdgeError::NotImplemented` (`501`) with the message `after-response tasks are not supported by the Spin adapter`, exported as `edgezero_adapter_spin::AFTER_RESPONSE_UNSUPPORTED`. The task is dropped without being polled. diff --git a/docs/guide/capabilities.md b/docs/guide/capabilities.md index 9df865a76..984530ac5 100644 --- a/docs/guide/capabilities.md +++ b/docs/guide/capabilities.md @@ -387,8 +387,8 @@ so CPU-bound or blocking work overruns it. - Spin rejects registrations that pass core's budget and task-limit checks with `501 Not Implemented` and the message `after-response tasks are not supported by the Spin adapter` (`edgezero_adapter_spin::AFTER_RESPONSE_UNSUPPORTED`). The task is dropped without being polled. - Core returns `500` for a zero budget, a budget above 30 seconds, or an exhausted task limit before - calling the scheduler. + Core returns `500` for a zero budget or a budget above 30 seconds before calling the scheduler. A + refused registration does not use one of the 64 task slots, so Spin never reaches the task limit. ## Outbound Matrix