Repository navigation
Conversation
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.
#509 (2620377) adds bounded work after the response on Fastly and Axum, drained on Axum SIGTERM (EZI-1, #476). #512 (cdc232c) runs it on Cloudflare through waitUntil (#478), and #515 (ec347a2) reports Spin's capability error (#483). The line now stacks on #517 and each PR merged the one below it, so this merge is clean.
|
For Trusted Server's identity integration chain, this PR's base #509 now stacks on #517. Checked locally at |
|
For the identity integration branch (#495), I pushed |
|
For the identity integration branch (#495), I pushed |
|
For the identity integration branch (#495), I pushed |
dhruv8sh
left a comment
There was a problem hiding this comment.
This PR adds Cloudflare after-response tasks. Each task is registered with Workers waitUntil right away, but it waits on a request-local oneshot gate before it starts. A single ReleaseGuard owns that gate. The guard moves from CloudflareEgressRuntime to WorkersCommitter and then into the spawned response pump. It is dropped when the response writer finishes, on bodyless handoff, on sync errors or failed fallback, and when dispatch is abandoned. Dropping it closes registration and releases all waiting tasks.
Each task's budget is min(budget, 30s) and starts only after release. Tasks run in a fresh outbound callback scope, and a panicking task is caught so it can't stop the others. The capability matrix, the docs and the docs-contract script are updated to match.
I didn't find any blocking issues. Things I checked:
- The gate uses a poison-tolerant mutex and sends signals only after the lock is released.
- Registering after release returns an error, and the task you passed in is never polled.
spawnusestake(), so the guard moves into the writer exactly once.- Gates for different requests are independent.
Tests cover streaming, bodyless responses, fallback, source errors, abort, abandoned dispatch, fresh-scope outbound and timeout cancellation.
Minor, non-blocking notes:
docs/superpowers/plans/...still has two unchecked items (signing/push and self-review), so the plan doc doesn't match a merged state.- Panic isolation only works where panics unwind. As the spec itself says, an ordinary aborting WASM panic on Workers can still end the invocation, so the "panicked" log path is mostly for host builds.
I couldn't run CI gates (fmt, clippy, tests) here because I only had read access.
dhruv8sh
left a comment
There was a problem hiding this comment.
PR Review
Summary
This PR turns on RequestContext::after_response for Cloudflare. Each task is queued with Workers waitUntil as soon as it is registered, but it is not polled until a request-local gate opens. A single ReleaseGuard closes registration and opens that gate. The guard starts in CloudflareEgressRuntime, moves to WorkersCommitter, and goes into the spawned response writer. Because the guard releases when it is dropped, every terminal path opens the gate: stream completion, a cancelled or failed writer, a bodyless handoff, fallback (whether it succeeds or fails), and an abandoned dispatch. I found no blocking problems. The design is sound and the contract tests cover the important edges.
😃 Praise
- Ownership-based release is a clean design. Tying the gate to
Dropof a guard that follows the response pump means no terminal path can forget to release. Theafter_response_releases_when_dispatch_is_abandonedandafter_response_releases_after_failed_fallbacktests confirm this. - The task's deadline and outbound callback scope are created only after release, so slow streaming does not use up the task's budget.
after_response_waits_for_stream_and_budget_starts_at_releaseand the fresh-scope/stale-scope fetch test check both behaviours directly. - The
Gatemutex is never held while the SDK is called or while waiters are signalled. BothregisterandDroprelease the lock beforewait_untilorsend.
Findings
Blocking
None.
Non-blocking
- ⛏ Unused
Defaultderive onGate: the derived default setswaiters = None, which is a gate that is already closed, and nothing uses it (see inline comment). - 🤔 Timer error is discarded: the timer-failure branch logs without the underlying error (see inline comment).
- 🤔 Timing-sensitive contract test:
after_response_waits_for_stream_and_budget_starts_at_releasedepends on wall-clock margins of 20, 25, 60 and 100 ms. On a busy CI runner the 60 ms budget could expire during the 25 msDelayplus scheduling overhead, which would makecompleted == 1fail. Consider wider margins, for example a 500 ms budget against a 25 ms delay. - 📝 Plan has unchecked items: in
docs/superpowers/plans/2026-11-18-cloudflare-after-response.md, the Task 5 items for publishing and self-review are still[ ]. That is fine if it is intentional, but tick them or remove them before merge so the plan matches what landed.
📌 Out of Scope
- Panic isolation in
run_boundedonly works in unwinding builds. Normalwasm32Workers builds abort on panic, and the docs say so. If panic isolation becomes a goal, track whether a Workers-side unwind configuration is possible as a separate issue.
|
|
||
| const MAX_BUDGET: Duration = Duration::from_secs(30); | ||
|
|
||
| #[derive(Default)] |
There was a problem hiding this comment.
⛏ Unused Default derive: Gate::default() produces waiters: None, which is a gate that is already closed and rejects every registration. Nothing calls it, because ReleaseGuard::new builds the gate explicitly with Some(Vec::new()). Remove the derive so nobody constructs a gate that silently refuses all tasks.
struct Gate {
waiters: Mutex<Option<Vec<oneshot::Sender<()>>>>,
}| Either::Left((Ok(()), _task)) => { | ||
| log::warn!("after-response task exceeded its budget and was cancelled"); | ||
| } | ||
| Either::Left((Err(_error), _task)) => { |
There was a problem hiding this comment.
🤔 Timer error is discarded: this branch throws away the EdgeError from time.wait_until, so the log line can't explain why the timer failed. Including the error costs nothing and helps when debugging in production:
Either::Left((Err(error), _task)) => {
log::warn!("after-response task timer failed; the task was cancelled: {error}");
}
ChristianPavilonis
left a comment
There was a problem hiding this comment.
I reviewed #512 against its live #509 base, feature/476-after-response-tasks at 54e7a4b8. Please address R1–R3 before advertising the Cloudflare capability. R4–R9 are optional.
The three behavioral findings reproduced with the compiled adapter and normal Rust fetch entrypoint in local workerd. Focused Cloudflare WASM and native tests, WASM Clippy, formatting, and the docs contract check passed. Hosted Cloudflare was not exercised.
| ) -> Result<CfResponse, EdgeError> { | ||
| let request_method = egress.request_method().clone(); | ||
| let mut committer = WorkersCommitter { | ||
| release: runtime.release, |
There was a problem hiding this comment.
R1 · P1: A task can delay a bodyless response. The bodyless branch at line 362 does not spawn a writer, so this guard drops when conversion returns, before the SDK hands the response back to Workers. The released task can run its first poll before the host's response Promise reaction. With the actual Rust fetch entrypoint in local workerd, a warm 204 took 198–214 ms with synchronous first-poll work versus 5–6 ms without it.
Separate registration closure from making tasks runnable on the no-writer path. Release at native handoff if available, or defer the first user-task poll by a host turn. Please add a 204 regression through #[event(fetch)] with a synchronous first poll.
| .unwrap_or_else(PoisonError::into_inner) | ||
| .take(); | ||
| for sender in waiters.unwrap_or_default() { | ||
| let _closed = sender.send(()); |
There was a problem hiding this comment.
R2 · P2: A late waiter gets a fresh budget. The gate sends only (), and line 115 computes a deadline when each waiter is first polled, not at release as documented. In local workerd a 5 ms sibling still ran after an earlier poll advanced the Workers clock by 190–196 ms. Cooperative cancellation allows that earlier poll to overrun; it should not let an expired sibling start.
Send one monotonic release instant to all waiters and derive their deadlines from it. Add a regression that first polls a waiter after its deadline and verifies the user task stays unpolled.
| ) -> Result<(), EdgeError> { | ||
| let released = self.gate.register()?; | ||
| let clock = self.clock.clone(); | ||
| self.context.wait_until(async move { |
There was a problem hiding this comment.
R3 · P2: A retained handle can register work under the wrong invocation. With request A still streaming, request B successfully used A's handle. The task waited on A's gate, but workerd binds waitUntil to the current invocation, which was B. The local runtime warned that the Promise resolved across request contexts after the creating request had ended. B's lifetime can cut short work still waiting for A.
Check the owning request's identity before calling the SDK. Add a test that attempts the registration from B while A's body is still open.
| } | ||
|
|
||
| struct WorkersCommitter { | ||
| release: Option<ReleaseGuard>, |
There was a problem hiding this comment.
R4 · Optional: Keep egress ownership state in one struct. The committer and runtime now both declare the release guard, context, and signal, and the conversion copies that shape field by field at lines 1017–1021. Have the private committer take the runtime whole, keeping the optional guard for assembly errors and moving it into the writer as today.
| )] | ||
| impl Drop for ReleaseGuard { | ||
| fn drop(&mut self) { | ||
| let waiters = self |
There was a problem hiding this comment.
R5 · Optional: Put the gate transition on Gate. The registration side owns its lock and state rules, but the drop guard reaches into the same state to close and drain it. Let the guard call Gate::close_and_release so those rules live together. Keep signalling outside the lock.
| assert!(deadline_body_releases_source_for_test()); | ||
| } | ||
|
|
||
| fn recording_context() -> (Env, Context, Array, NumericTimeoutGuard) { |
There was a problem hiding this comment.
R6 · Optional: Share the recording Workers context fixture. This recreates the promise recorder from src/response.rs:1139–1154 and discards a no-op context along the way. Put the recording-context factory in the shared test support, leaving the environment and timer setup with the callers.
| assert!( | ||
| handle | ||
| .schedule(Duration::from_secs(1), async move { | ||
| late_state.started_early.fetch_add(1, Ordering::SeqCst); |
There was a problem hiding this comment.
R7 · Optional: Distinguish an early task from a rejected recursive task. This increments started_early if a recursive registration runs after release. Use separate flags and assertions so a failure tells us whether the original task started too soon or the rejected recursive task ran.
| let deadline = time.clock().deadline_after(budget.min(MAX_BUDGET)); | ||
| let callback = OutboundScopeOwner::callback(); | ||
| let result = callback | ||
| .run( | ||
| AssertUnwindSafe(async move { | ||
| match select(time.wait_until(deadline), task).await { | ||
| Either::Left((Ok(()), _task)) => { | ||
| log::warn!("after-response task exceeded its budget and was cancelled"); |
There was a problem hiding this comment.
R8 · Nit: Log the effective timeout budget. Axum and Fastly include the duration in this warning. On Cloudflare, the capped duration tells operators whether the warning came from a short configured budget or the 30-second cap.
| let deadline = time.clock().deadline_after(budget.min(MAX_BUDGET)); | |
| let callback = OutboundScopeOwner::callback(); | |
| let result = callback | |
| .run( | |
| AssertUnwindSafe(async move { | |
| match select(time.wait_until(deadline), task).await { | |
| Either::Left((Ok(()), _task)) => { | |
| log::warn!("after-response task exceeded its budget and was cancelled"); | |
| let effective_budget = budget.min(MAX_BUDGET); | |
| let deadline = time.clock().deadline_after(effective_budget); | |
| let callback = OutboundScopeOwner::callback(); | |
| let result = callback | |
| .run( | |
| AssertUnwindSafe(async move { | |
| match select(time.wait_until(deadline), task).await { | |
| Either::Left((Ok(()), _task)) => { | |
| log::warn!( | |
| "after-response task exceeded its {effective_budget:?} budget and was cancelled" | |
| ); |
| - Learn about [Fastly Compute](/guide/adapters/fastly) as an alternative | ||
| - Explore the [Axum adapter](/guide/adapters/axum) for local development | ||
|
|
||
| ## After-response tasks |
There was a problem hiding this comment.
R9 · Nit: Keep “Next Steps” last. Move this section above the closing navigation, as in the other adapter guides. The section anchor and text can stay the same.
Summary
RequestContext::after_response(budget, task)on Cloudflare Workers so background work starts after terminal response egress without delaying delivery.waitUntilpromises, give each task a fresh outbound callback scope, and cancel pending work atmin(budget, 30 seconds)after release.after-response-tasksasBoundedCooperativefor Cloudflare and document Workers lifetime limits, registration closure, and lack of persistence or retries.Stacked on #509 (
feature/476-after-response-tasks, basea5c176e1), which supplies the portable task API and response-egress foundation. This PR targets that branch; its changes are the Cloudflare implementation of #478.Integration note: a current
git merge-treecomparison with #496 reports conflicts in Axum response conversion, Cloudflare/Spin contracts, and core error/extractor code. These siblings need reconciliation when integrated.Changes
edgezero-adapter-cloudflare/src/after_response.rs,src/lib.rsedgezero-adapter-cloudflare/src/request.rs,src/response.rsedgezero-adapter-cloudflare/src/cli.rsBoundedCooperativesupport and update the capability test.edgezero-adapter-cloudflare/tests/contract.rsand colocated testsCHANGELOG.mdscripts/check_outbound_docs_contract.mjsCloses
Closes #478
This PR targets
feature/476-after-response-tasks, so merging it into that branch does not automatically close the linked issue(s); close them manually or upon default-branch integration.Test plan
Historical author-reported local verification below (original head unrecorded unless an explicit SHA is given). These results, counts, timings and negative controls were not rerun in this audit, and their underlying local logs were unavailable; checked boxes retain the original report. At the current head
953f0031, all 18 reported hosted checks are passing.Local checks used Rust 1.98.1 and Node.js 24.20.0. Current reported GitHub checks are passing.
cargo test --workspace --all-targetscargo clippy --workspace --all-targets --all-features -- -D warningscargo fmt --all -- --checkcargo check --workspace --all-targets --features "fastly cloudflare spin"wasm32-wasip1(Fastly) /wasm32-wasip2(Spin) /wasm32-unknown-unknown(Cloudflare) — Cloudflare Worker built and Spin target checked; Fastly target build not rerun for this Cloudflare change.examples/app-demoworkspace:cd examples/app-demo && cargo test --workspace --all-targetscd docs && npm run lint && npm run format && npm run buildedgezero serve --adapter axum— runtime verification used Cloudflare below.cloudflareandcloudflare,test-utils; Cloudflare WASM unit/contract suites and browser ingress suite; outbound documentation contract check.1, expected0).run_appconsumer under local Wrangler 4.83/workerd: response-first return about 3 ms versus an inline-delay control about 306 ms; delayed completion, streaming/full post-egress budget, pending-task drop, fresh outbound transport and old-scope revocation, 204 handoff, 500 fallback, and overlapping request gates all passed.The local workerd run exercises the actual Worker artifact. Hosted Cloudflare deployment was not exercised. Budgets are cooperative, and Workers independently limits the shared
waitUntillifetime; these checks do not establish durable completion. Panic isolation requires an unwinding build; an aborting WASM panic can terminate the invocation.Checklist
{id}syntax (not:id)edgezero_core(nothttpcrate)KvRegistry/ConfigRegistry/SecretRegistry(not the legacy single-handle setters) — existing store wiring is unchanged