Skip to content

Retry an after-response write that loses its CAS - #1660

Open
dhruv8sh wants to merge 9 commits into
feat/1598-ec-route-fastlyfrom
fix/1553-after-response-cas-retry
Open

dhruv8sh wants to merge 9 commits into
feat/1598-ec-route-fastlyfrom
fix/1553-after-response-cas-retry

Conversation

@dhruv8sh

@dhruv8sh dhruv8sh commented Nov 24, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Changes

File Change
Cargo.toml, crates/trusted-server-adapter-axum/Cargo.toml, Cargo.lock EdgeZero rev 9d02d7b3 → e9a22a70 (#536 merged onto it).
crates/trusted-server-core/src/ec/kv_backend.rs EcKvStore::update (default Unsupported) with EcKvReplacement, EcKvPlan, EcKvUpdate, EcKvUpdateOutcome and EcKvUpdateError. Test support: RecordBackedEcKv runs EdgeZero's real RecordHandle::update over any test double through a record KvStore bridge; ConflictInjectingEcKv moves here with a race closure; WriteFailingEcKv counts inserts.
crates/trusted-server-core/src/ec/record_backend.rs RecordEcKvStore::update and LazyRecordEcKvStore::update over RecordHandle::update; EdgeZero Unsupported maps to EcKvUpdateError::Unsupported.
crates/trusted-server-core/src/ec/kv.rs commit_after_response spends the permit, makes one EcKvStore::update with MAX_AFTER_RESPONSE_ATTEMPTS = 2 and maps its outcome; on Unsupported it overwrites last-write-wins. Test constructors build graphs with the record update.
crates/trusted-server-core/src/ec/page_load.rs AfterResponseRejection: Skipped, Conflict, StaleRead, StoreFailed, WriteFailed.
crates/trusted-server-core/src/ec/after_response.rs Plans against each snapshot EdgeZero reads and maps the result to an outcome. Logs After-response lookups: write outcome=<outcome> conflicts=<n>. Tests: retry against a fresh read, second conflict gives up, opt-out supersedes, withdrawn row not revived, stale re-read, missing re-read, failed re-read, failed first read, store error not retried, last-write-wins fallback writes and still skips a withdrawn row; each asserts the conflict count.
crates/trusted-server-adapter-fastly/src/post_delivery.rs Removes the duplicate outcome log, which now lives in core.
docs/guide/edgezero.md, docs/guide/native-rc-demo.md The new pin.
docs/superpowers/specs/2026-10-30-s2s-eid-collection-design.md §5.2.1, §9.1, §9.2 and scenario 23 describe the retry, where its loop lives, the fallback, the stale-read and failed outcomes, and the conflict count.
CHANGELOG.md Unreleased entry.

Closes

Closes #1553

Depends on IABTechLab/edgezero#536.

Spec

Spec: not a new feature. It is the follow-up the s2s EID collection spec deferred to #1553, and that spec is updated.

Test plan

  • cargo test-fastly && cargo test-fastly-reuse (4451 passed) and cargo test-axum && cargo test-cloudflare && cargo test-spin
  • cargo clippy-fastly && cargo clippy-axum && cargo clippy-cloudflare && cargo clippy-cloudflare-wasm && cargo clippy-spin-native && cargo clippy-spin-wasm && cargo clippy-cli && cargo clippy-codegen
  • cargo fmt --all -- --check
  • cargo test --manifest-path crates/trusted-server-integration-tests/Cargo.toml --test parity
  • CLI tests, native build-digest test and lint, scripts/lint-wasm-clock.sh
  • JS tests and format: no JS changes
  • Docs format: Prettier check on the changed docs, spec and CHANGELOG.md
  • Manual testing via fastly compute serve
  • Other: mutation checks. Removing the last-write-wins fallback, or reporting stale_read as conflict, fails named tests. EdgeZero's own tests cover the loop (KV identity graph #536).

Notes for review

  • Only Conflict retries. Store errors report failed and drop the results; the source stays due, so the next navigation asks again. Read and write failures inside the update are no longer told apart in the log, since EdgeZero returns one error.
  • The last-write-wins fallback is reachable only for an EcKvStore without update; every production store is RecordEcKvStore, which has it. Its overwrite can replace a withdrawal tombstone written between its read and its write.
  • Two tests that handed the graph a plan built from an older read than the one EdgeZero guards the write with were removed: that cannot happen now, because the guard is always the generation of the row the planner saw. Their scenarios stay covered by the racing-store tests.
  • The write outcome is still log-only; the s2s spec's §12.2 "metrics" is not added here.
  • Stays a draft until Add a bounded re-read and re-plan update for records edgezero#536 merges and the pin can move to rc/identity.

Checklist

  • Feature PRs: spec linked above, ending in a review log of two or more agent review rounds (not a feature)
  • Changes follow AGENTS.md conventions
  • No unwrap() in production code — use expect("should ...")
  • Uses log macros (not println!)
  • New code has tests
  • No secrets or credentials committed

On a conflict, the follow-up write now re-reads the row and re-plans
against it once instead of dropping its results. The re-plan sees every
write since, so lookups superseded by a newer opt-out are discarded and a
withdrawn row is never revived.

A conflicting write lands nothing, so commit_after_response hands the
AfterResponseWrite permit back on Conflict only. At most one follow-up
write lands per navigation.

The outcome log line moves into core and adds conflicts=<n> so the
conflict rate can be measured.

Closes #1553
The permit for the follow-up write used to leave KvIdentityGraph on a
conflict, inside a rejection whose Option field said whether a retry was
allowed. KvIdentityGraph::commit_after_response now spends the permit once
and runs the bounded retry itself: it reads the row, asks a re-plan closure
for the update, and after a conflict reads and re-plans again, for at most
MAX_AFTER_RESPONSE_ATTEMPTS attempts. At most one write lands. The
rejection is now an enum (Skipped, Conflict, ReadFailed, WriteFailed), so
a conflict cannot be mistaken for a store failure.

Fastly KV is eventually consistent, so a re-read can return the generation
that just lost the CAS. That re-read now ends with outcome conflict and no
second write. A failed read of the row now reports failed instead of
no_row, so no_row means only a missing or withdrawn row.

ConflictInjectingEcKv moves to kv_backend::test_support. Its race closure
writes through serialize_entry, so the raced row carries real metadata.
kv.rs and after_response.rs both use it, and RacingEcKv is removed. The
retry tests now assert the conflict count, and new tests cover a stale
re-read, failed reads and an unretried store error.

The CHANGELOG and spec no longer say the retry honours every withdrawal
recorded since dispatch. A row withdrawn and given consent again before
the read is not detected, which is now tracked in #1664.

Refs #1553
A lost CAS proves the row exists at a newer generation, so a re-read that
returns the generation that just lost, or no row at all, is a stale read
of an eventually consistent store. Reporting it as `conflict` hid it among
real second-attempt conflicts, and a stale Missing row was reported as
`no_row`. Both now stop without a second write as `stale_read`, so the two
can be measured apart and `no_row` keeps meaning a missing or withdrawn
row. Fastly generations are unique but not ordered, so an older generation
cannot be detected and is not faked.

Also describe the permit as spent before the first read, run the scenario
23 tombstone test through the real planner with an exact outcome, and keep
MAX_AFTER_RESPONSE_ATTEMPTS and serialize_entry from widening production
visibility (a cfg(test) accessor serves the test stores).

Refs #1553
@dhruv8sh
dhruv8sh marked this pull request as ready for review November 24, 2026 14:20
EcKvStore gains update, which RecordEcKvStore implements with EdgeZero's RecordHandle::update (IABTechLab/edgezero#536). KvIdentityGraph keeps the permit and the identity plan and makes one bounded update; a store without it reports Unsupported and the write falls back to last-write-wins. EdgeZero is pinned to the rc/identity commit 9d02d7b3 with #536 merged.

Signed-off-by: dhruv8sh <dhruv8sh@proton.me>
This PR now stacks on #1662 instead of #1641, so rc/identity can take both
as plain merges. #1662's new head (9df0101) sits on #1661, #1656, #1626, #1636,
#1646 and #1642, which sit on #1641, so the merge brings #1642 (awaited
identity lookups and /auction body EIDs), #1646 (Axum identity through the
shared application), #1636 (Axum's after-response drain on #1646's runner),
#1626 (provider opt-outs and legacy EID expiry), #1656 (the configurable
Edge Cookie browser gate), #1661 (refusing EC creation when a trusted JA4
contradicts the User-Agent) and #1662 (EC route acceptance on Fastly and
the mirrored expiry cap), and the identity chain below #1641.

EdgeZero pin: this PR pinned e9a22a70, a preview that merges EdgeZero 536
(RecordHandle::update) into the older rc/identity commit 9d02d7b3. The base
carries #1506's repin to rc/identity at 459bd27d (42e0c46), which merges
EdgeZero 536 itself, so the workspace and Axum manifests, Cargo.lock, the
EdgeZero guide and the native RC guide take the base's pin and text. This
PR's CHANGELOG entry keeps its description of the retry and names the
459bd27d pin.

After-response write: #1646 moved the after-response lookup run from the
Fastly adapter into core's IdentityApp::run_after_response_lookups, so
post_delivery.rs takes the base's call into the identity app. The shared
runner calls this PR's commit_after_response_lookups without logging the
outcome itself, since this PR moves that log line into
commit_after_response_lookups, where it also reports the conflict count.
Each follow-up write still logs one outcome line.

Core test support: #1613 compiles kv_backend's test_support module for the
test-utils feature as well as tests, with each test-only store gated
#[cfg(test)]. This PR's EcKvRecords, RecordBackedEcKv and
ConflictInjectingEcKv doubles, its Race type and the imports only they use
are gated the same way, since test-utils builds lack
KvIdentityGraph::serialize_entry_for_test and use none of them.

Axum drain tests: #1636's after_response_drain_tests fixture store
implements insert but not update. This PR sends the follow-up write through
EcKvStore::update, so the fixture's write fell back to last-write-wins,
skipped the guarded insert that records and holds the write, and four
drain tests failed. The fixture now implements update over its own lookup
and insert with EdgeZero's RecordHandle::update contract: read, plan,
write under the read generation, and re-read after a lost precondition,
ending as StaleRead when the re-read returns the rejected generation or no
row. The follow-up write is guarded again and the drain tests pass.

EC KV store: the imports take this PR's AfterResponseCommit and
AfterResponseRejection and the base's PartnerRegistry and write plan;
Generation is no longer used there.

Page-load write docs: the module comment keeps this PR's sentence that the
graph spends the follow-up permit once, so at most one follow-up update
lands, and #1646's sentence on the auction body EID update.

CHANGELOG: this PR's compare-and-swap retry entry stays first under
Changed, followed by #1661's JA4 entry, #1617's health and readiness entry
and #1506's pin entry.

S2S design logging: this PR adds the `stale_read` outcome and the
`conflicts` count to the after-response write log, and #1488 adds that the
hashed-email call logs one debug line with the reply status or transport
error only. The paragraph keeps both.
@aram356
aram356 changed the base branch from feat/record-backend-edgezero to feat/1598-ec-route-fastly November 26, 2026 08:06
aram356 added a commit that referenced this pull request Nov 26, 2026
#1660 (173d6d0) retries an after-response identity write that loses its
compare-and-swap through EdgeZero's RecordHandle::update, with at most one
follow-up write and a stale_read outcome for a stale re-read. It now sits on
#1662: its merge of #1662's chain takes the chain's EdgeZero pin, 459bd27d,
which carries EdgeZero 536, in place of its preview pin e9a22a70, and moves
its outcome log onto #1646's shared runner. The merge is clean.
@aram356

aram356 commented Nov 26, 2026

Copy link
Copy Markdown
Collaborator

For the identity integration branch (#1608), I pushed 173d6d06f, a merge of #1662's new head 9df010122 onto this PR's 96a9c152c. This PR now stacks on #1662 instead of #1641, so rc/identity takes both as plain merges, and I changed the base to feat/1598-ec-route-fastly (#1662). #1662's head sits on #1661, #1656, #1626, #1636, #1646 and #1642, which sit on #1641, so the merge brings those PRs and the chain below #1641, with #1506's repin of EdgeZero to rc/identity at 459bd27d. The merge conflicted in 10 files. Resolutions:

  • EdgeZero pin: this PR pinned e9a22a70, a preview that merges EdgeZero KV identity graph #536 (RecordHandle::update) into the older rc/identity commit 9d02d7b3. 459bd27d merges EdgeZero KV identity graph #536 itself, so the workspace and Axum manifests, Cargo.lock, the EdgeZero guide and the native RC guide take the base's pin and text. This PR's CHANGELOG entry keeps its description of the retry and now names 459bd27d.
  • After-response write: Run Axum identity through the shared application #1646 moved the after-response lookup run from the Fastly adapter into core's IdentityApp::run_after_response_lookups, so Fastly post_delivery.rs takes the base's call into the identity app. The shared runner calls this PR's commit_after_response_lookups without logging the outcome itself, and this PR moves that log line into commit_after_response_lookups, where it also reports the conflict count. Each follow-up write still logs one outcome line.
  • Core test support: Add shared identity conformance fixtures and Fastly coverage #1613 compiles kv_backend's test_support module for the test-utils feature as well as for tests, with each test-only store gated #[cfg(test)]. This PR's EcKvRecords, RecordBackedEcKv and ConflictInjectingEcKv doubles, its Race type and the imports only they use are gated the same way, since test-utils builds lack KvIdentityGraph::serialize_entry_for_test and use none of them.
  • Axum drain tests: Drain Axum after-response identity tasks on SIGTERM #1636's after_response_drain_tests fixture store implements insert but not update. This PR sends the follow-up write through EcKvStore::update, so the fixture's write fell back to last-write-wins, skipped the guarded insert that records and holds the write, and four drain tests failed. The fixture now implements update over its own lookup and insert with EdgeZero's RecordHandle::update contract: read, plan, write under the read generation, and re-read after a lost precondition, ending as StaleRead when the re-read returns the rejected generation or no row. Drain Axum after-response identity tasks on SIGTERM #1636's owner may want to review this change to that PR's test file.
  • EC KV store imports take this PR's AfterResponseCommit and AfterResponseRejection and the base's PartnerRegistry and write plan; Generation is no longer used there.
  • Page-load write docs keep this PR's sentence that the graph spends the follow-up permit once, so at most one follow-up update lands, and Run Axum identity through the shared application #1646's sentence on the auction body EID update.
  • CHANGELOG: this PR's compare-and-swap retry entry stays first under Changed, followed by Refuse EC creation when a trusted JA4 contradicts the UA #1661's JA4 entry, Standardize health and startup-failure responses across adapters #1617's health and readiness entry and Cut Trusted Server over to EdgeZero PR 275 #1506's pin entry.
  • S2S design logging keeps both additions: this PR's stale_read outcome and conflicts count, and Add identity providers for ID5, LiveIntent, LiveRamp, ConnectID and UID2 #1488's single debug line for the hashed-email call.

This PR's own behavior is unchanged: the bounded retry, stale_read, the withdrawn and opt-out handling, and the outcome log with conflicts.

Checked at 173d6d06f: fmt, clippy-fastly and clippy-axum pass; test-fastly 4387 passed, 0 failed; test-axum 130 passed and 4 failed (the four drain tests) before the fixture change and 134 passed, 0 failed after it. Five runs on Viceroy each passed ec::after_response (25), ec::kv (123) and ec::record_backend (5). Of five runs of the Axum drain tests, four passed 10 of 10 and one failed task_budget_cancels_work_independently_of_shutdown_grace, where the fixture's loopback probe got a transport error; the same probe failure was seen on rc/identity before this change, and the full rc/identity test-axum then passed 136 of 136.

#1662's new head 9a1e6b1 brings #1539's cf4e815, "Expect the failure router in the native container test", and #1646's a18abf4, "Compare undeclared Axum KV stores with assert_eq". The merge is clean.
aram356 added a commit that referenced this pull request Nov 26, 2026
…dentity

#1660 (39cfe15) carries #1539's cf4e815, "Expect the failure router in the native container test", and #1646's a18abf4, "Compare undeclared Axum KV stores with assert_eq". The merge is clean.
@aram356

aram356 commented Nov 26, 2026

Copy link
Copy Markdown
Collaborator

For the identity integration branch (#1608), I pushed 39cfe1570, a merge of #1662's new head 9a1e6b1f1, which brings #1539's cf4e815d4, the native container test's failure-router expectation, and #1646's a18abf428, the reworked KV check in the store metadata test. The only change to this PR's tree is that store test. The merge had no conflicts.

Takes #1662's new head faaf573, which carries #1506's repin of EdgeZero to
rc/identity at 1619078a (8edc50e), a revert that removes EdgeZero 522
(portable Fastly record providers) and 524 (outbound mTLS client
identities).

The merge is clean.

This PR's own EdgeZero pin text moves from 459bd27d to 1619078a as well, in
the `CHANGELOG.md` entry that names the commit #1506 pins, which still
carries EdgeZero 536.
aram356 added a commit that referenced this pull request Nov 27, 2026
#1660 (ac73237) carries #1506's repin of EdgeZero to rc/identity at
1619078a (8edc50e), a revert that removes EdgeZero 522 (portable Fastly
record providers) and 524 (outbound mTLS client identities), through the
chain below it. The merge is clean.
@aram356

aram356 commented Nov 27, 2026

Copy link
Copy Markdown
Collaborator

For the identity integration branch (#1608), I pushed ac73237ff.

Takes #1662's new head faaf573, which carries #1506's repin of EdgeZero to rc/identity at 1619078a (8edc50e), a revert that removes IABTechLab/edgezero#522 (portable Fastly record providers) and IABTechLab/edgezero#524 (outbound mTLS client identities).

The merge is clean.

This PR's own EdgeZero pin text moves from 459bd27d to 1619078a as well, in the CHANGELOG.md entry that names the commit #1506 pins, which still carries IABTechLab/edgezero#536.

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

The bounded retry is the right shape. Before merging, I'd fix the two provider races called out inline and add a focused test for each. The store fallback is a separate, non-blocking note.

Reviewed against #1662 at faaf573e0cc5. The 25 focused core tests and 10 Axum drain tests passed locally; they don't cover the two provider races.

}
let snapshot = &graph.load_snapshot(ec_id).await;
let commit = graph
.commit_after_response(permit, ec_id, |snapshot| {

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 · P2: A retry can clear a newer LiveRamp opt-out. A navigation sees an old remembered opt-out just before it expires and gets Forget from a renewed cookie. After expiry, another navigation gets a LiveRamp server opt-out and commits it between the first navigation's read and CAS. If there's no UID to remove, write_plan.rs:187–203 remembers the opt-out without advancing the revocation marker. The retry then honors the older Forget, clears the new opt-out, and writes the UID. Before this PR, losing that CAS dropped the result.

Please advance the revocation marker when a server opt-out installs new memory, even if there's no UID to clear, and add a race test. The current opt-out test injects a changed revocation directly and misses this case.

let snapshot = &graph.load_snapshot(ec_id).await;
let commit = graph
.commit_after_response(permit, ec_id, |snapshot| {
plan_follow_up(snapshot, registry, ec_id, lookups)

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 retry can replace a fresher UID2 token with an older cookie token. The cookie can pass the expiry check at dispatch (ec/coordinator/mod.rs:1006–1012) and then lose its first CAS to a server refresh for the same source. Replanning with the original lookups replaces the winner's token and refresh state at ec/write_plan.rs:178–182 without checking freshness again. Before this PR, losing that CAS dropped the cookie result.

Please retain cookie provenance and apply the existing UID2 freshness rule to the row being written. Add a race test where the CAS winner updates the same source; the current success test changes a different source.

Err(AfterResponseRejection::StaleRead)
}
Err(EcKvUpdateError::Store(report)) => Err(AfterResponseRejection::StoreFailed(report)),
Err(EcKvUpdateError::Unsupported) => self.overwrite_after_response(ec_id, plan).await,

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, non-blocking: The default fallback drops CAS even when the store supports it. An existing EcKvStore can implement IfGenerationMatch and still inherit update returning Unsupported. This branch switches that store from the old guarded write to Overwrite. A withdrawal between the fallback's read and write can then be overwritten. The fallback test uses an in-memory store that already supports CAS. The built-in Fastly and Axum stores override update, so this is a store-interface issue, not a known failure in either built-in adapter.

I'd retain one guarded write for stores that lack the retry hook and reserve the requested last-write-wins fallback for stores that explicitly lack conditional writes.

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.

Retry an after-response write that loses its CAS

3 participants