Repository navigation
Conversation
Add RequestContext::after_response(budget, task) and the adapter-facing AfterResponseScheduler/AfterResponseHandle in edgezero-core, plus the after-response-tasks manifest capability (Axum Native, Fastly BoundedCooperative, Cloudflare and Spin Unsupported). Axum spawns each task on the server's LocalSet, releases it when Hyper drops the response body, bounds it with a Tokio timeout inside its own outbound callback scope, and drains registered tasks on SIGTERM within the existing shutdown grace after connections settle. Fastly queues tasks per request lifecycle and drives them after the response is sent, inside the same callback scope, each raced against its budget. Adapters without a scheduler return 501 at registration. Closes #476.
Address self-review findings on the after-response task work: - Cover the Fastly registry lifecycle used by run_app and serve_app through send_request_with_registries_and_hooks_for_test, and assert that a prepare hook cannot replace the adapter scheduler. - Stamp each Fastly lifecycle with a generation so a retained handle is rejected instead of queuing into a later request. - Let an idle tracker win over an elapsed deadline in the Axum task wait, and log abandoned tasks on every shutdown exit path. - Classify Axum as BoundedCooperative, matching its await-point cancellation, and document AxumDevServer::run draining. - Add tests for the shared grace, a second signal during the task wait, Fastly outbound requests from a task, and native replacement. - Keep the handler example from failing pages on unsupported adapters and sync the design and plan documents with the code.
Move the abandoned-task warning from drain_tasks into run_owned through AfterResponseTracker::warn_abandoned, so the prebound serve() path and the unusable-deadline return also report cancelled tasks, exactly once. Exercise the prepare-hook override through the registry funnel test too.
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 now stacks on #517, the top of the line
One behavior change, from the port: the base records an Checked locally at |
Exercise the consumer path Trusted Server relies on for follow-up writes: - Axum: a conditional Add record write inside a task is acknowledged and readable by a later request, without delaying the response. - Axum: SIGTERM arrives while a request is in flight, the handler then registers a KV write; the request and the write both complete within the grace, the process exits 0, and the value survives a restart. - Fastly: a guarded record write inside a task lands after delivery. Ignored in CI because the bare Viceroy runner has no KV stores; run it from the adapter crate, whose runner loads the demo fastly.toml.
|
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 RequestContext::after_response and a core scheduler trait, with bounded implementations for Axum (tasks start when Hyper drops the response body, and shutdown waits for them within the grace period) and Fastly (tasks are queued per request and run after delivery inside the callback scope). Cloudflare and Spin report the capability as Unsupported. The Axum design is solid and well tested: tasks are tracked with a watch channel, the grace period is shared with connection draining, and registration closes once the response body is released.
Two problems need fixing before merge. First, nothing limits how many tasks a request can register or how long a budget can be. Second, on Fastly the tasks run before a NotCommitted delivery's fallback response is sent, which delays the client. The second one is a Fastly-only ordering issue.
I could not run the CI gates (fmt, clippy, tests) because I only had read access.
Comments not anchored to the diff:
- crates/edgezero-adapter-fastly/src/after_response.rs:1262 — 🔧 No limit on queued tasks or budget:
lifecycle.tasks.pushaccepts any number of tasks, anddrainonly caps each budget atDEADLINE_FAR_FUTURE. A handler in a loop, or one that sets a budget from request input, can grow memory without limit and keep the Fastly invocation busy long after the response. The Axum tracker has the same problem in production between shutdowns. The project guide asks for no unbounded growth.
Fix: add a per-request task limit and a maximum budget, either as core constants or as adapter config. Reject anything over the limit in AfterResponseHandle::schedule with a semantic error, and add tests for both rejection paths.
- crates/edgezero-adapter-fastly/src/request.rs:1472 — 🔧 Tasks run before a NotCommitted fallback is sent:
with_after_responsedrains the tasks before it returns theFastlyRequestDelivery. When delivery did not commit, the caller still has to send a native replacement response, so the client waits for every task to finish or hit its budget. The testafter_response_task_runs_when_delivery_did_not_commitconfirms this ordering. It also breaks the documented promise that tasks start after the response attempt ends.
Fix: return the delivery to the caller first and drain afterwards. Alternatively, when may_send_native_response() is true, send the native fallback before draining.
dhruv8sh
left a comment
There was a problem hiding this comment.
PR Review
Summary
This PR adds RequestContext::after_response(budget, task) with a portable AfterResponseHandle and AfterResponseScheduler in core. Axum gets a release-on-body-drop scheduler with a tracker that SIGTERM drains within the shutdown grace. Fastly gets a lifecycle-scoped, generation-stamped queue that is drained inside the callback scope after delivery. Cloudflare and Spin return a 501 capability error. Overall the design is careful and well tested. I found no blocking issues.
😃 Praise
- Axum ties the release to the drop of
AxumEgressBody. This covers a normal finish, a client disconnect and a cancelled service future without extra code. The tests show all three over a real Hyper connection, including the keep-alive case. - Connections and tasks share one grace in
drain_tasks, using abiasedselect where an idle tracker wins over a deadline that has already passed. The subprocess tests cover the shared grace, grace exhaustion and a second signal. - Fastly stamps each lifecycle with a generation and inserts the handle after the
preparescratch extensions. This means a handle kept from an earlier request on a reusedserve_appinstance is rejected, and a hook cannot replace the adapter's handle. Both cases have tests. - Core tests use
block_onand a drop probe to show that a task which fails to register is never polled and is dropped.
Findings
Blocking
None.
Non-blocking
- 🤔 No per-request cap on registered tasks: each
schedulecall queues a boxed future on Fastly or spawns a task on Axum, with no limit on the count (crates/edgezero-adapter-fastly/src/after_response.rs:80,crates/edgezero-adapter-axum/src/after_response.rs:94). See the inline comment.
📌 Out of Scope
ChristianPavilonis
left a comment
There was a problem hiding this comment.
I'd hold this until both adapters enforce the budget before polling a task, and Axum measures it from egress release. Neither fix requires preempting work already running in a poll.
With a 50 ms budget, controlled-clock checks reproduced task work at 100 ms in the Axum scheduler and in the Fastly task drain with an injected progress driver. The existing Axum listener and SIGTERM tests passed. The hosted Fastly contract suite passed 42 tests and skipped the guarded-write test, which needs a KV-configured runner.
- Cap each request at 64 after-response tasks and each budget at 30 s (MAX_AFTER_RESPONSE_TASKS, MAX_AFTER_RESPONSE_BUDGET), enforced in AfterResponseHandle::schedule; a refused task does not use a slot. - Add core run_within_budget, which checks the absolute deadline before every poll of the task and keeps a timer to wake pending work. Axum and Fastly both use it instead of timeout/select, which polled the task first. - Axum: the release publishes its time as it drops, and each task's deadline derives from it, so a busy executor no longer extends a budget. - Docs and rustdoc describe the budget as starting when the response attempt ends and cancelling before the next poll, plus the limits.
|
@dhruv8sh, on the two findings in your first review body:
|
Takes the base's three new commits (949c0b6). CHANGELOG.md conflicted in Unreleased; both the after-response and the portable client info / JA4 sections are kept.
ChristianPavilonis
left a comment
There was a problem hiding this comment.
Re-review of 54e7a4b8..3249e15d (author commit cb2bdff2 plus a merge that only brings in base commits).
All four items from my last review are addressed: expiry is checked before polling on both adapters through the shared run_within_budget, the Axum budget starts at release, and the rustdoc and Fastly guide wording are updated.
Approving so I'm not blocking, on the understanding that you'll handle the two inline comments before merging.
Bring in PR #517's portable ClientInfo review fixes and the review fixes below it, from PR #454 down to PR #275, including PR #406's RunMode hosting with prepare_service and the drain split between development and production, PR #439's Geo sanitization, the KV Geo and record fixes, the trusted-proxy rule that leaves an unresolved client unavailable and main's lockfile versions. CHANGELOG.md: both sides added Unreleased sections at the top. The resolution keeps the base's sections first, then this PR's "After-Response Tasks (#476)". crates/edgezero-core/src/context.rs: the imports keep this PR's after_response items and the base's FrameworkErrorDetail. The impl keeps this PR's after_response method ahead of body_bytes, as alphabetical order requires now that PR #407 removed the impl's ordering expect. body_bytes takes PR #407's updated doc. crates/edgezero-adapter-axum/src/dev_server.rs: PR #406 moved service construction into prepare_service and drains by RunMode. This PR attached an AfterResponseTracker to the service and passed it to drain_tasks. run_owned now creates the tracker and attaches it to prepare_service's result. The production RunMode arms pass the tracker to drain_tasks. With the tracker, run_owned is 102 lines, so its too_many_lines expect from before PR #406's review is restored.
Bring in PR #517's merge of PR #514 (Spin KV Geo misconfiguration as a redacted 500 and Spin Geo timers that re-arm after an early wake) and PR #275's Fastly contract test fix for the production error-body key order. CHANGELOG.md: PR #514's "Spin KV Geo and Cloudflare platform Geo" section, now in PR #517, and this PR's "After-Response Tasks (#476)" were both inserted after "KV-backed Geo". The base section comes first, then this PR's.
|
Round 12 identity realignment:
Each merge message says what it carries and how any conflict was resolved. |
|
Round 15 identity realignment:
Each merge message says what it carries and how any conflict was resolved. |
…s at shutdown Only the production entrypoints drain tasks within the shutdown grace; run_app and AxumDevServer cancel them with their connections.
Review follow-up: fixes committed to this branchA full review of this PR turned up the problems below; each would otherwise have needed a follow-up ticket, so it is fixed on this branch instead. Every item names its commit.
Fixes made on the PRs below this one in the stack were merged into this branch with merge commits. |
Summary
ctx.after_response(budget, task): the task starts once the response attempt ends at the adapter's terminal egress boundary, and is cancelled when its budget elapses. Axum drains registered tasks on SIGTERM within the existing shutdown grace. Adapters without support (Cloudflare, Spin for now) return501 Not Implementedat registration instead of dropping work silently.after-response-tasksmanifest capability so apps can declare itrequiredand havebuild/serve/deployrefuse adapters that cannot run it.Stacked on #517 (
feat/portable-client-info); this work needs #406's SIGTERM drain and #275's Fastly callback scope. Design:docs/superpowers/specs/2026-11-17-after-response-tasks-design.md; plan:docs/superpowers/plans/2026-11-17-after-response-tasks.md.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-core/src/after_response.rs(new)AfterResponseScheduleradapter trait,AfterResponseHandleextension handle, 501 when absent; reject zero/over-30-second budgets and more than 64 accepted tasks per requestedgezero-core/src/context.rsRequestContext::after_response(budget, task)edgezero-core/src/manifest.rsCapability::AfterResponseTasks(after-response-tasks)edgezero-adapter-axum/src/after_response.rs(new)spawn_localon the serverLocalSet, gated on a release signal, an absolute release timestamp and a deadline check before every task poll inside a fresh outbound callback scope;watch-based task tracker; registration closes once releasededgezero-adapter-axum/src/{service,response}.rsAxumEgressBodyand fires when Hyper drops the body (final frame handed over, or early disconnect/cancellation)edgezero-adapter-axum/src/dev_server.rsdrain_taskswaits for the tracker after connections settle, under the same grace deadline (an idle tracker wins over an elapsed deadline); pending tasks at the grace are cancelled → existinggrace exhaustedfailure; abandoned tasks are logged on every exit path. Applies to production entrypoints,run_appandAxumDevServer::runedgezero-adapter-fastly/src/after_response.rs(new),request.rsfinish_request, tasks are drained inside the samewith_callbackscope (outbound and timers work), each checked against its absolute deadline before every poll, with a paired wake timer; handle inserted only while armed, afterprepareextensions; each lifecycle has a generation so a retained handle is rejected;send_request_with_registries_and_hooks_for_testexposes therun_app/serve_appfunnel to contract testsedgezero-adapter-*/src/cli.rsBoundedCooperative(budget cancels at await/yield points), Cloudflare/SpinUnsupportedtests/after_response.rs), subprocess SIGTERM tests; Fastly host tests and Viceroy contract testscapabilities.md(new checked matrix),handlers.md,adapters/axum.md,adapters/fastly.md,CHANGELOG.md;scripts/check_outbound_docs_contract.mjschecks the new matrixCloses
Closes #476
This PR targets
feat/portable-client-info, 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. Hosted check counts in this historical record do not verify later revisions.
Local, Rust 1.98.1 / Node 24.20.0 (pinned versions):
cargo test --workspace --all-targetscargo clippy --workspace --all-targets --all-features -- -D warnings, plus the per-adapter wasm/native clippy matrix fromformat.ymland Fastly--features cli/--no-default-featurescargo fmt --all -- --checkcargo check --workspace --all-targets --features "fastly cloudflare spin"wasm32-wasip1(Fastly) /wasm32-wasip2(Spin) /wasm32-unknown-unknown(Cloudflare, core)examples/app-demoworkspace:cargo test --workspace --all-targets, fmt, clippynpm run lint && npm run format && npm run build;node scripts/check_outbound_docs_contract.mjs--test contract42/42,--lib357/357run_appregistry funnel fails its contract testprepareextensions fails the hook-override testsexamples/app-demowith a/after-taskroute (registers a task with a 1.5 s timer):run_app: the response arrives in ~1 ms and the task completes ~1.5 s later. SIGTERM right after the response waits ~1.5 s and exits 0. With a 1 s grace the task is cancelled, the process exits 1 withgrace exhausted, and the abandoned-task warning is logged.viceroy serve(0.21.0): the response arrives in ~1–2 ms and the task completes ~1.5 s later on two consecutive requests.spin upand Cloudflarewrangler dev --local:/after-taskreturns501withafter-response tasks are not supported by this adapter, while existing routes are unaffected.Not verified: deployed Fastly Compute and a production Axum container/ECS stop; Trusted Server consumer integration. Hosted verification for the latest review follow-up is recorded below.
Notes and limitations
ResponseEgressOutcome::HostHandoff), not proof of client receipt. Tasks run whatever the outcome (completed, error response, disconnect).BoundedCooperativefor both. On Fastly a blocked hostcall cannot be preempted.serve_appinstance, and — when delivery did not commit — a caller-sent native replacement response, by at most the longest registered budget (documented trade-off; skipping would drop work silently).waitUntil) #478 (CloudflarewaitUntil) and After-response capability error on Spin #483 (Spin capability error naming the adapter).Checklist
{id}syntax (not:id)edgezero_core(nothttpcrate)KvRegistry/ConfigRegistry/SecretRegistry(not the legacy single-handle setters) — not touchedHistorical review follow-up at
66573b5d66573b5d extracts the existing Fastly per-task deadline/timer wrapper into a private helper used by production drain. Lifecycle-backed regressions check timely completion, simultaneous deadline/task readiness, and expiry before the first poll. The disabled-predicate control performs the forbidden write and fails; restored code passes. Task output/failure prose now has its own design bullet.
The five required local Cargo gates, isolated harness (680 passed, 4 ignored), selected Fastly feature/WASM lints, seven host and seven Viceroy guest tests, and docs lint/format pass with Rust 1.98.1 and Node 24.20.0 (debug information disabled to bound storage). The prescribed suite also passed Axum CI but stops at Fastly record-contract: stock Viceroy 0.22.0 returns Written for a stale conditional write where PreconditionFailed is required. The repository documents its local-runtime repair and CI uses that repaired binary; this is an unqualified local runtime result, not a pass. No hosted deployment was exercised. The signed follow-up is GitHub Verified; all 30 hosted checks subsequently passed at
66573b5d. Those results are historical after the dependency follow-up below.Current dependency and cancellation-fixture follow-up at
c01ccea4Six existing locks refresh only
pin-project-lite0.2.17→0.2.19 version/checksum. The old version is yanked: locked downloads remain valid, but fresh offline consumers exclude it. Prefetching the updated closure supplies a non-yanked version while preserving fresh lock generation. Manifests and runtime image pins remain unchanged.Three fake-Cargo cancellation fixtures performed two real identity captures before the controlled child started, exceeding their unchanged 5-second observation bound. A scoped test-only identity override and owned fake rustc version stub remove that setup cost. Production fingerprinting, deadlines and existing assertions are unchanged; nested unwind verifies restoration.
Current Rust 1.98.1 checks pass: all five required Cargo gates (3,162 workspace tests, 7 ignored), isolated harness (681 passed, 4 ignored, two test threads), standalone harness format/strict Clippy/non-test compilation, all three actual cancellation fixtures and identity restoration, Fastly/Cloudflare WASM compilation, and seven host plus seven Viceroy 0.22.0 guest deadline tests.
Shared dependency evidence used a pristine cache containing only locked 0.2.17: the actual macro and generated AWS fresh consumers failed, then actual macro/AWS/Dynamo/celld consumers passed offline after adding 0.2.19. Nested generated build dependency files confirmed 0.2.19. These proofs cover the shared dependency class and were not repeated on this branch. All 30 hosted checks now pass on
c01ccea4, including the current native/Wasm suites and clean processed Rust CodeQL analysis (27 rules, zero findings). Broader prescribed runtime/Docker qualification was not repeated; the historical stock-Viceroy record-contract limitation remains separate.