Skip to content

Extract admitted-error finalization from demo RC - #464

Open
ChristianPavilonis wants to merge 12 commits into
feat/portable-client-infofrom
review/admitted-error-finalization
Open

ChristianPavilonis wants to merge 12 commits into
feat/portable-client-infofrom
review/admitted-error-finalization

Conversation

@ChristianPavilonis

@ChristianPavilonis ChristianPavilonis commented Nov 10, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • Adds App::set_admitted_error_response_finalizer, an optional synchronous callback that runs once on each rendered admitted dispatch error, after the configured error renderer. It receives the request's existing GeoOutcome and &mut Response, so an application can add the headers its middleware adds to Ok responses.
  • EdgeZero keeps the failure classification, route and synthesized-response bookkeeping, and reapplies the rendered status and required protocol headers after the callback. Successful responses, detached errors, pre-admission refusals and admitted body-conversion errors don't call it. With no finalizer installed, behavior is unchanged.
  • This is a mechanical extraction of the demo RC commit 89c279b59b75eb33b96eb30a35f78bf933762f34. It doesn't redesign response ownership or Geo policy, and adds no body carrier, transport, timer policy or production Geo provider.

Changes

Crate / File Change
crates/edgezero-core/src/app.rs New finalizer field and setter. dispatch_admitted_with_geo calls it after rendering an admitted error and restores status and required headers. Three regression tests.
docs/guide/native-geo.md Explains when to use middleware and when to use the finalizer, and which errors bypass it.

Closes

Closes #518

Refs #461. Integration RC #462 includes this PR at 96c21d731501370044f11ca5832e85701e79a421.

Stack

Based on #517 (feat/portable-client-info). GitHub stack #539 orders this PR before #524. The finalizer runs in the shared admitted-dispatch path used by both Geo and ClientInfo.

The server-side identity plan (IABTechLab/trusted-server#1559, Part A and Part C) still says to drop #454's prototype commits and base this PR on #439's branch. That conflicts with #510 and is still open.

Head is dfec0db36401831188ee15db8f17e40084b23827. The commits after 96c21d73 are merges of the parent branches. The PR's changed lines are identical to 89c279b5. feature/kv-geoip has since moved ahead by eight commits that aren't merged here yet, including 2c41968b (Fastly and Cloudflare Geo through ctx.geo()) and 7ef4766d (Axum Geo from the manifest).

Test plan

All four admitted_error_finalizer_ tests passed after merging #517.

  • Hosted CI at dfec0db3: all 29 checks pass, including workspace tests, Axum, Fastly, Cloudflare and Spin tests and clippy, cargo fmt and docs formatting.
  • cargo test -p edgezero-core --lib admitted_error_finalizer at dfec0db3: 3 passed.
  • At the original extraction (96c21d73): Core 1,174 default-parallel tests, Axum 488 and production-hosting 36 serial cases, scoped Clippy and formatting. These results are tied to that revision.

Earlier local runs saw native parallel timing failures that nobody has classified. This PR doesn't relax their assertions or claim to fix them.

Not covered: ALB credential validation, cloud ingress, browser behavior and deployment.

Ready for review. It merges with the stack above, not directly into main.

@aram356

aram356 commented Nov 13, 2026

Copy link
Copy Markdown
Collaborator

CREATOR: From the server-side identity plan (IABTechLab/trusted-server#1559, c7dc9de77): Rebase as Part A's table says.

@ChristianPavilonis
ChristianPavilonis changed the base branch from feature/pluggable-geo-providers to feature/kv-geoip November 17, 2026 17:01
@ChristianPavilonis
ChristianPavilonis marked this pull request as ready for review November 19, 2026 21:03
@aram356 aram356 linked an issue Nov 25, 2026 that may be closed by this pull request
6 tasks

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

Approving. The finalizer is a narrow, default-off addition. It runs only on rendered admitted dispatch errors, gets the adapter-owned GeoOutcome captured before handlers can mutate extensions, and afterwards restores the rendered status, the required protocol headers (Allow, Retry-After) and the body-overflow marker. The egress framing layer independently reapplies required headers and overflow Retry-After suppression, so the in-app restoration is defense in depth. With no finalizer installed, the code path is unchanged.

Verification at 3b0d6606:

  • cargo test -p edgezero-core --lib passes 1188 tests, including the 4 finalizer tests.
  • cargo clippy -p edgezero-core --all-targets --all-features -D warnings and cargo fmt --check are clean, on the pinned 1.98.1 toolchain.
  • Broken-code checks, each run against the finalizer tests:
    • Dropping the status restore fails 3 tests.
    • Dropping the overflow-marker reinsert fails the overflow test.
    • Dropping the required-header restore and reinsert fails 2 tests.
  • The branch merges cleanly with the current feature/kv-geoip tip (7580806a). There, the Fastly and Cloudflare request paths call dispatch_admitted_with_geo, so the finalizer will receive their platform geo outcome as intended.

Non-blocking:

  1. Hosted CI is red at this head. axum tests failed in tests/production_hosting.rs (native_ids_remain_private_under_mutation_and_concurrent_hosting_requests). The host stopped with runner_failed before readiness, and cargo test only reports that failure. This looks like the fixture port-reservation race fixed on the base by 38cf420b (respawn a production hosting fixture that loses its port), which isn't merged into this branch yet. Nothing in this PR touches that path, and no finalizer is installed there. Please merge the base forward, rerun, and refresh the test plan. It currently cites an all-green run at dfec0db3, which is no longer the head.
  2. A test assertion can't fail (inline).

assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
assert_eq!(response.headers()["retry-after"], "60");
assert_eq!(response.headers()["x-geo-finalized"], "yes");
assert_eq!(provider_calls.load(Ordering::SeqCst), 1);

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.

Nit (non-blocking): the only call to CountingGeoProvider is the test's own provider.resolve(...) a few lines above. The provider is never given to the App or the router, so this assertion is always 1. It can't catch a finalizer path that resolves geography again. The handler-side mutation checks (forged cloudfront-viewer-country header, an inserted GeoOutcome::NoSelection) are what actually prove the finalizer sees the original outcome. Consider dropping the counter, or renaming the test to describe what it does check, e.g. admitted_error_finalizer_receives_dispatch_geo_despite_handler_mutation.

@ChristianPavilonis
ChristianPavilonis changed the base branch from feature/kv-geoip to feat/portable-client-info November 27, 2026 18:10

@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 App::set_admitted_error_response_finalizer, an optional synchronous hook. It runs on rendered errors from admitted dispatch and receives the GeoOutcome that was already resolved, so geography is not looked up again.

Around the callback, the code takes the framework metadata out of the response first: the rendered status, RequiredErrorResponseHeaders and the body-overflow marker. Once the callback returns, it puts the status and required headers back, restores the marker and runs suppress_overflow_retry_after again. So a callback that changes the status, strips required headers or swaps in a whole new response can't alter how the failure is classified, and the overflow Retry-After suppression still applies.

When no finalizer is set, behaviour is the same as before. The tests cover:

  • the geo outcome is retained and the provider isn't called again
  • routing errors (404 and 405) keep their status and the Allow header
  • the overflow retry policy still holds when the callback replaces the response
  • the callback is skipped for successful responses, application-returned error statuses, detached errors, body-conversion errors and refused admissions

The tests block on futures directly rather than using #[tokio::test], which matches the project's convention. I found no blocking issues.

@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 adds an optional synchronous hook, App::set_admitted_error_response_finalizer. It runs once on the rendered error response of an admitted dispatch and receives the immutable GeoOutcome that was already given to the request context. After the callback, EdgeZero puts back the rendered status, the required protocol headers (Retry-After and Allow), and the overflow marker. The design is careful and the change is well contained. When no finalizer is installed, behaviour is unchanged. I found no blocking issues.

😃 Praise

  • The callback can't weaken framework guarantees. The status, RequiredErrorResponseHeaders and RequestBodyOverflowResponse are taken out before the callback runs. HeaderMap::extend (which replaces existing values) then restores them, and suppress_overflow_retry_after runs again afterwards. This works even when the callback swaps in a whole new response, and the tests cover that case.
  • The tests cover the important boundaries: renderer and finalizer call counts, failure classification kept, category-only routing messages kept, the overflow Retry-After suppressed, and the bypass for Ok responses, app-returned 4xx, detached errors, conversion errors and refused admission.

Findings

Blocking

None.

Non-blocking

  • 🤔 Provider call count assertion is tautological: In admitted_error_finalizer_retains_geo_without_resolving_again, the test calls CountingGeoProvider directly and never wires it into the app. provider_calls == 1 therefore always holds and does not show that geography isn't resolved again (crates/edgezero-core/src/app.rs:2861, 2947).
  • 📝 Finalizer has the same powers as the renderer: The callback can still set framing or hop-by-hop headers and egress extensions such as ResponseEgressDeadline. That is the same as a custom set_error_response_renderer, and egress sanitisation still runs afterwards, so this is fine. It may be worth one sentence in the doc comment.

📌 Out of Scope

  • None.

] {
let provider_calls = Arc::new(AtomicUsize::new(0));
let provider = CountingGeoProvider(resolution, Arc::clone(&provider_calls));
let status = match provider.resolve(&GeoInput {

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 assertion can't fail: provider.resolve(...) is called right here in the test, and the provider is never passed to App. Core has no app-level provider hook, so provider_calls == 1 at line 2947 always holds. It doesn't show that dispatch or the finalizer avoids resolving geography again.

The assertions that actually back the "without resolving again" claim are the outcome == finalizer_geo check and the handler mutating cloudfront-viewer-country and the GeoOutcome extension. I suggest removing CountingGeoProvider and building the GeoStatus directly, so readers don't assume the count proves something. Alternatively, drive the test through an adapter-level path where a provider is actually installed.

let status = GeoStatus::Located {
    location: GeoLocation::new(CountryCode::new("US").unwrap(), None),
    source: GeoSource::CloudFront,
    trust_basis: GeoTrustBasis::DeclaredProtectedAlb,
};

/// including application-returned error statuses. Detached errors, pre-admission errors,
/// and admitted body-conversion errors without a resolved outcome bypass this hook.
///
/// `EdgeZero` preserves failure classification and reapplies the rendered status and

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.

📝 Document what the callback can still change: The callback can set or replace any header apart from the required ones, including connection/framing headers, and it can insert egress extensions such as ResponseEgressDeadline. A custom error renderer can already do the same, and egress sanitisation runs afterwards, so this is not a bug. Still, one sentence saying the finalizer has the same trust level as set_error_response_renderer would set the right expectation for adopters.

};
self.render_error_response_with_message(error, fixed)
let mut response = self.render_error_response_with_message(error, fixed);
if let Some(finalizer) = &self.admitted_error_response_finalizer {

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.

😃 Robust restoration: Taking RequiredErrorResponseHeaders and the overflow marker out of the response before the callback, then restoring them with HeaderMap::extend (which replaces values) and running suppress_overflow_retry_after again, means the callback can't drop Allow/Retry-After or add back a forbidden Retry-After. This holds even if it replaces the whole response, which admitted_error_finalizer_preserves_body_overflow_retry_policy tests directly.

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.

Let applications finalize rendered admitted error responses

4 participants