Skip to content

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

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

prk-Jr wants to merge 8 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, defer the first user poll past host handoff, and give each task a fresh outbound callback scope.
  • Measure min(budget, 30 seconds) from one shared release instant and reject retained handles used by another active dispatch before calling Workers.
  • 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 54e7a4b8), 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 (historical comparison): a git merge-tree comparison with #496 reported 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, src/outbound.rs Add the request-local release gate, host-turn yield, and bounded local task scheduler; reject foreign-dispatch and post-release registration.
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, src/test_runtime.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

Current local verification covers signed commit 136ed0d8 with Rust 1.98.1, Node.js 24.20.0, and lock-matched wasm-bindgen 0.2.128. Hosted CI for this revision is pending; earlier green runs do not verify this commit.

  • cargo test --workspace --all-targets — final source passed; the initial sandbox-denied socket run was superseded by a successful run with local socket access.
  • cargo clippy --workspace --all-targets --all-features -- -D warnings
  • cargo fmt --all -- --check
  • cargo check --workspace --all-targets --features "fastly cloudflare spin"
  • cargo check -p edgezero-adapter-spin --target wasm32-wasip2 --features spin
  • Cloudflare native crate tests: 42 passed.
  • Strict Cloudflare WASM Clippy with cloudflare and cloudflare,test-utils; both configurations passed.
  • Cloudflare WASM library and contracts with cloudflare,test-utils: 148 and 40 passed. Standalone cloudflare library/contract suites also passed.
  • Docs lint, Prettier check, build, and outbound documentation contract check.
  • Regressions for host-turn ordering, delayed first poll, sibling budgets, foreign handles while the original stream remains open, nested/pending/unwinding identity restoration, owning body-producer registration, and host-timer setup failure.
  • All three initial scheduler regressions fail on the original code. A selectively incomplete deadline-renewal control fails the expired-task regression; clean and restored versions pass.
  • Real #[event(fetch)] consumer using public CloudflareService dispatch in local workerd 2026-04-15: original 204 background-work responses took 95–203 ms; corrected responses took 2.4–4.2 ms against a 62–163 ms inline-work control. Expired siblings stay unpolled, unexpired siblings run, cross-request registration is rejected, and the original streaming body can still register its own work. The corrected runtime log has no cross-context warnings.

The final runtime comparison uses the repository's resolved worker/worker-macros/worker-sys 0.8.5 and wasm-bindgen 0.2.128. Earlier exploratory runs with newer transitive SDK components were superseded. Hosted Cloudflare deployment was not exercised. Budgets remain cooperative and consume host-turn/executor delay; Workers can independently terminate waitUntil work. Panic recovery requires unwinding and is not guaranteed on an aborting WASM build.

App-demo, Fastly target/runtime qualification, and browser ingress were not separately rerun locally for these Cloudflare fixes; the applicable hosted jobs remain separate verification obligations.

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.

@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.

Comment thread docs/guide/adapters/cloudflare.md Resolved
@prk-Jr

prk-Jr commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator Author

Follow-up in 136ed0d8:

  • R1, R2, and R3 are corrected with regressions and a repository-lock-matched local workerd before/after comparison. All 11 inline conversations have individual replies.
  • The timing test now gives the successful task a 500 ms budget around its 25 ms delay while holding the stream for 600 ms. Separate assertions identify early polling versus rejected recursive work.
  • The implementation plan now points to this PR for publication/review status and labels its old verification record historical. The guides still explicitly limit panic recovery to unwinding builds.
  • All five repository gates passed locally, along with both Cloudflare WASM Clippy configurations, 148 WASM library tests, 40 contracts, standalone-feature suites, and docs checks. The selective deadline-renewal control fails as intended; clean/restored code passes. The new commit is GitHub Verified.

GitHub currently reports zero check runs and zero workflow runs for this head. Hosted CI remains unverified, so the inline conversations remain open. Hosted Cloudflare deployment was not exercised. The PR description now reflects this current revision and evidence instead of the older green head.

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