Skip to content

Enable Cloudflare after-response tasks with gated waitUntil - #512

Open
prk-Jr wants to merge 7 commits into
feature/476-after-response-tasksfrom
feature/478-cloudflare-after-response
Open

prk-Jr wants to merge 7 commits into
feature/476-after-response-tasksfrom
feature/478-cloudflare-after-response

Conversation

@prk-Jr

@prk-Jr prk-Jr commented Nov 18, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • Enable RequestContext::after_response(budget, task) on Cloudflare Workers so background work starts after terminal response egress without delaying delivery.
  • Retain tasks with gated waitUntil promises, give each task a fresh outbound callback scope, and cancel pending work at min(budget, 30 seconds) after release.
  • Report after-response-tasks as BoundedCooperative for Cloudflare and document Workers lifetime limits, registration closure, and lack of persistence or retries.

Stacked on #509 (feature/476-after-response-tasks, base a5c176e1), 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-tree comparison with #496 reports conflicts in Axum response conversion, Cloudflare/Spin contracts, and core error/extractor code. These siblings need reconciliation when integrated.

Changes

Crate / File Change
edgezero-adapter-cloudflare/src/after_response.rs, src/lib.rs Add the request-local release gate and bounded local task scheduler; reject registration after release.
edgezero-adapter-cloudflare/src/request.rs, src/response.rs Install the scheduler in shared dispatch and keep release ownership through native handoff, stream termination, fallback, cancellation, and abandoned dispatch.
edgezero-adapter-cloudflare/src/cli.rs Advertise BoundedCooperative support and update the capability test.
edgezero-adapter-cloudflare/tests/contract.rs and colocated tests Cover service/prebuilt dispatch, streaming release, budgets, stale handles, request isolation, fresh outbound scopes, timeout cancellation, and terminal error paths.
Cloudflare, capability, and handler guides; CHANGELOG.md Describe effective budgets, platform limits, and outbound request construction inside tasks.
scripts/check_outbound_docs_contract.mjs Keep the documented capability matrix aligned with adapter reporting.
Design and implementation documents Record the contract, architecture, verification scope, and implementation plan.

Closes

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-targets
  • cargo clippy --workspace --all-targets --all-features -- -D warnings
  • cargo fmt --all -- --check
  • cargo check --workspace --all-targets --features "fastly cloudflare spin"
  • WASM builds: 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-demo workspace: cd examples/app-demo && cargo test --workspace --all-targets
  • Docs build: cd docs && npm run lint && npm run format && npm run build
  • Manual testing via edgezero serve --adapter axum — runtime verification used Cloudflare below.
  • Other: Cloudflare native crate tests; strict Cloudflare WASM Clippy with cloudflare and cloudflare,test-utils; Cloudflare WASM unit/contract suites and browser ingress suite; outbound documentation contract check.
  • Negative gate control: deliberately bypassing release in an isolated copy makes the streaming contract test fail because task cancellation occurs while the stream is still active (1, expected 0).
  • Public run_app consumer 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 waitUntil lifetime; these checks do not establish durable completion. Panic isolation requires an unwinding build; an aborting WASM panic can terminate the invocation.

Checklist

  • Changes follow CLAUDE.md conventions
  • No Tokio deps added to core or adapter crates
  • Route params use {id} syntax (not :id)
  • Types imported from edgezero_core (not http crate)
  • Store wiring goes through KvRegistry / ConfigRegistry / SecretRegistry (not the legacy single-handle setters) — existing store wiring is unchanged
  • New code has tests
  • No secrets or credentials committed

@prk-Jr prk-Jr self-assigned this Nov 18, 2026
@prk-Jr
prk-Jr marked this pull request as ready for review November 18, 2026 09:28
@prk-Jr prk-Jr linked an issue Nov 18, 2026 that may be closed by this pull request
2 tasks
prk-Jr added a commit that referenced this pull request Nov 18, 2026
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.
@aram356
aram356 added this pull request to stack #511 November 19, 2026 05:03
aram356 added a commit that referenced this pull request Nov 19, 2026
#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.
@aram356

aram356 commented Nov 19, 2026

Copy link
Copy Markdown
Collaborator

For Trusted Server's identity integration chain, this PR's base #509 now stacks on #517. cdc232c8 merges #509's new head 2620377a. The one conflict was adapter-cloudflare/src/request.rs's dispatch_with_handles: this PR's after_response::arm(..) and CloudflareEgressRuntime::with_after_response(..) now sit alongside the base's geo and client-info capture. No behavior or test changes.

Checked locally at cdc232c8: cargo fmt, workspace clippy with all features, both Fastly clippy runs, the wasm feature check, cargo test --workspace --all-targets (3,116 passed), Cloudflare clippy on wasm32-unknown-unknown, and the Cloudflare wasm tests in Node (lib 143, contract 38, including this PR's after-response tests), all passing.

Takes #509's new head a5c176e, which adds test coverage for guarded writes
inside after-response tasks. The merge is clean, and this PR's tree changes
only by those tests.
aram356 added a commit that referenced this pull request Nov 20, 2026
Takes #512's new head 953f003, which carries #509's new tests for guarded
writes inside after-response tasks. The merge is clean, and this PR's tree
changes only by those tests.
aram356 added a commit that referenced this pull request Nov 20, 2026
#509 (a5c176e) adds test coverage for guarded writes inside after-response
tasks on Axum and Fastly. #512 and #515 each merged the PR below them, so
this merge is clean and the branch tree equals #515's head.
@aram356

aram356 commented Nov 20, 2026

Copy link
Copy Markdown
Collaborator

For the identity integration branch (#495), 953f0031 merges #509's new head a5c176e1, which adds tests for guarded writes inside after-response tasks. The merge is clean and changes this PR's tree only by those tests.

Bring in main's Fastly SDK 0.13.3 upgrade (#529) with Viceroy 0.22.0
and the Fastly CLI 17.2.0 upgrade (#531), with PR #275's exact pins at
0.13.3 and url 2.5.9, its Viceroy readiness repair on 0.22.0 and its
typed Image Optimizer unavailability check for SDK 0.13.3.
Bring in PR #275's installation of the wasm32-unknown-unknown target
before the Viceroy 0.22.0 readiness repair builds, which the fastly
wasm tests and Portable record contracts (Fastly) jobs need.
@aram356

aram356 commented Nov 25, 2026

Copy link
Copy Markdown
Collaborator

For the identity integration branch (#495), I pushed fbd75ff2 and 786cbb93, two merges of #509's new heads. fbd75ff2 takes EdgeZero main's Fastly SDK 0.13.3 upgrade (#529), with Viceroy 0.22.0 and the Fastly CLI 17.2.0 upgrade (#531), with #275's exact pins at 0.13.3 and url 2.5.9, its Viceroy readiness repair on 0.22.0, its typed Image Optimizer unavailability check and its drain of declared uploads after an early response on Axum. 786cbb93 takes #275's d8cd85c8, which installs the wasm32-unknown-unknown target before the Viceroy 0.22.0 readiness repair builds, as the fastly wasm tests and Portable record contracts (Fastly) jobs need. Both merges had no conflicts.

Bring in PR #275's atomic conditional KV insert in the Viceroy readiness
repair, and the production hosting tests' held port reservations and
spawn-token respawn from PR #406 up, with each later PR's tests reading
the live host's address.
@aram356

aram356 commented Nov 26, 2026

Copy link
Copy Markdown
Collaborator

For the identity integration branch (#495), I pushed f18da45b, a merge of #509's new head that brings #275's 41cdf035, which makes conditional KV inserts atomic in the Viceroy readiness repair, as the Fastly record contract's native race needs, and the production hosting tests' held port reservations and spawn-token respawn from #406 up, with each later PR's tests reading the live host's address. It had no conflicts.

Bring in PR #275's batch cutoff test fix, which advances the test clock
when the request arms its own deadline instead of after dispatch, and
the AWS emulator proofs' readiness markers from PRs #414 and #510, now
published by rename.
@aram356

aram356 commented Nov 26, 2026

Copy link
Copy Markdown
Collaborator

For the identity integration branch (#495), I pushed e4c6647a, a merge of #509's new head that brings #275's 0e2a58ae, which fixes an intermittent failure of the batch cutoff test by advancing its clock when the request arms its deadline timer, and the AWS emulator proofs' readiness markers from #414 and #510, now published by rename. It had no conflicts.

@dhruv8sh dhruv8sh left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
  • spawn uses take(), 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:

  1. docs/superpowers/plans/... still has two unchecked items (signing/push and self-review), so the plan doc doesn't match a merged state.
  2. 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 dhruv8sh left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 Drop of a guard that follows the response pump means no terminal path can forget to release. The after_response_releases_when_dispatch_is_abandoned and after_response_releases_after_failed_fallback tests 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_release and the fresh-scope/stale-scope fetch test check both behaviours directly.
  • The Gate mutex is never held while the SDK is called or while waiters are signalled. Both register and Drop release the lock before wait_until or send.

Findings

Blocking

None.

Non-blocking

  • ⛏ Unused Default derive on Gate: the derived default sets waiters = 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_release depends 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 ms Delay plus scheduling overhead, which would make completed == 1 fail. 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_bounded only works in unwinding builds. Normal wasm32 Workers 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)]

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⛏ 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)) => {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤔 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 ChristianPavilonis left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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(());

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +115 to +122
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");

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Suggested change
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

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

After-response work on Cloudflare (waitUntil)

4 participants