Repository navigation
Add portable conditional KV records across providers - #510
ChristianPavilonis wants to merge 23 commits into
Conversation
Preserve record and current stock-service/Geo ancestry. Add the service record API, prepared Rust client, generated TLS proofs and two-node resend/deadline/takeover checks. Local checkpoint only. Native SDK, stock celld and strict lint checks pass; final SDK acceptance remains blocked by an observed Viceroy concurrent-CAS defect. Keep exact-one-winner assertions unchanged.
#517 (10ed380) tops ChristianPavilonis's line on #439: - #510, the KvStore record contract with DynamoDB and celld providers on Axum (#472, #473); - #454, portable KV-backed geo; - #514, country and region through ctx.geo() on Cloudflare and Spin (#480, #486); - #517, the portable ClientInfo contract with its Fastly, Axum, Cloudflare and Spin mappings (#475, #90, #91, #92, #485). #517 also merged #469 and #502 itself, so its tree contains everything this branch had. The only conflicts were JA4 lines that #517 refactors on top of #469; this merge takes #517's version, and its tree is identical to #517's.
|
For the identity integration branch (#495), I pushed |
|
For the identity integration branch (#495), I pushed |
The generated records initializer wrote PROOF_ENTERED with std::fs::write, so App::ready could read the marker after it was created and before "records-ready" was written. It now writes a staged file and renames it into place, as the ordinary proof's initializer does.
|
For the identity integration branch (#495), I pushed |
prk-Jr
left a comment
There was a problem hiding this comment.
Requesting changes for one blocking question on the Fastly CAS contract; one smaller non-blocking item is inline.
The record design is careful overall. Generation allocation is transactional and survives deletion on redb, DynamoDB and celld; cursors are bound to scope, format, layout and partition; and Overwrite/Add/CAS outcomes are kept separate from MutationUncertain. Hosted checks are green at a296a067.
Blocking: a CAS against a deleted (absent) key is not established on Fastly.
RecordWriteMode::IfGenerationMatch promises "write only while this key still has the supplied generation". So a writer holding a generation from before a delete must get PreconditionFailed, not recreate the key. redb, DynamoDB (#generation = :expected against a missing item) and celld (existing === undefined is rejected) all reject this by construction. The Fastly provider instead passes the generation straight to the native if_generation_match and relies on the platform.
The only Fastly runtime this repository tests against does not reject it. In Viceroy's ObjectStores::insert (0.21.0 upstream, and unchanged by patches/viceroy/0.22.0-body-readiness.patch), the precondition only fails when existing is Some with a different generation (if let Some(g) = generation && let Some(val) = &existing && val.generation != g). With no current value, the insert proceeds. Scenario: client A looks up k (generation G), client B deletes k, then A's CAS(G) returns Written and the deleted record comes back.
Nothing in the PR shows what production Fastly does here, and no test covers it. assert_record_contract checks a stale CAS only after the key has been recreated (assert_deletion → Add → assert_stale), never while it is absent, and the Fastly record_cases fixture has no such case either. I added assert_stale(records, key, before_delete) straight after the delete in assert_deletion and ran the Axum shared-contract test, and it passes. So the extra assertion is compatible with the other providers and would discriminate this case.
Suggested resolution:
- Add the CAS-on-absent assertion to the shared contract (and the Fastly record fixture) so every provider runs it.
- Establish the production Fastly behaviour from Fastly's documentation or a hosted run. If production rejects it, this becomes the Viceroy disclosure alongside the existing race gap. If not, Fastly needs a documented limitation, or the CAS capability should not be claimed for Fastly yet.
Checks I ran (Rust 1.98.1, at a296a067): edgezero-core record_api and record_configuration tests pass. The Axum public_handle_shared_record_contract passes both unmodified and with the extra absent-key assertion. I did not run DynamoDB Local, stock celld or Fastly WASM locally; for those I relied on the hosted results.
| RecordWriteMode::Add => request.mode(InsertMode::Add), | ||
| RecordWriteMode::Overwrite => request.mode(InsertMode::Overwrite), | ||
| RecordWriteMode::IfGenerationMatch(generation) => { | ||
| request.if_generation_match(generation.as_u64()) |
There was a problem hiding this comment.
Blocking. On a missing key this native precondition is not rejected by Viceroy: ObjectStores::insert only fails when an existing value has a different generation, so a stale CAS after a delete recreates the record. The redb, DynamoDB and celld providers all return PreconditionFailed here. Please establish the production Fastly behaviour and cover the case in the shared contract (see the review summary).
There was a problem hiding this comment.
b4be3c3 adds the missing-key case to the shared contract the Fastly WASM fixture already runs. With the updated fixture, stock Viceroy 0.22.0 returned Written instead of PreconditionFailed. The inherited atomic-insert repair fixes the race, but still only compares generations when a row exists. The plan now distinguishes those two findings.
Fastly’s Compute docs say a conditional write only succeeds when the current generation matches. The existing production deployment was reported to be working; I did not run or inspect a separate hosted missing-key trace. No adapter workaround or contract exception is included. I’m leaving this open until the missing-key emulator fix comes through #275 and #439 and the required Fastly suite passes.
aram356
left a comment
There was a problem hiding this comment.
PR Review
Summary
Found while reviewing the rc/identity integration branch (#495) and traced to this PR. Each finding was re-checked at this head (b4be3c3d); line numbers refer to it.
Requesting changes for three blocking findings and one question.
Findings
Blocking
- 🔧 Fastly record-store misconfiguration answers every request with 400. See
fastly/src/lib.rs. - 🔧 The
kv-records.mdsample does not compile. Seekv-records.md:63. - 🔧 CHANGELOG:
## Unreleasedhas no entry for the portable record contract (require_record_store,RecordLayout, conditional writes, record listing) or the DynamoDB and celld record providers. - ❓ Should one key outside the layout fail every Fastly record list page? See
fastly/src/key_value_store.rs:174.
Non-blocking
- 🤔 Record cursors carry the binding scope, including the DynamoDB table ARN, in plaintext. See
record_store.rs. - 🤔 DynamoDB partition listing walks allocator rows first. See
dynamodb_records.rs:558. - 🤔 Fastly record reads report every error as a retryable 503. See
fastly/src/key_value_store.rs:330.
CI Status
- GitHub reports no checks at
b4be3c3d.
| .any(|id| !metadata.is_some_and(|meta| meta.ids.contains(&id.as_str()))) | ||
| { | ||
| return Err( | ||
| KvError::Validation("record declaration uses an undeclared ID".to_owned()).into(), |
There was a problem hiding this comment.
🔧 A deployment misconfiguration reaches every visitor as 400
A record declaration that names an undeclared store ID is an operator error, but KvError::Validation maps to 400, so every request answers as if the client sent something wrong. Axum refuses to start for the same mistake. Return EdgeError::internal here and keep 4xx for request-derived failures. #275 (outbound contract checks), #514 and #517 (Spin settings, 422) have the same class of problem.
There was a problem hiding this comment.
Fixed in 8cc8133. build_target_app now returns EdgeError::internal, so an undeclared record store ID answers 500. record_layouts_must_name_declared_ids_without_opening_a_provider asserts the status and message. Cloudflare (lib.rs:88-91) and Spin (lib.rs:123-126) still map the same mistake to KvError::Validation (400); I will follow up on those here.
There was a problem hiding this comment.
Follow-up in a839312: Cloudflare and Spin now report an undeclared record store ID as EdgeError::internal (500) too. The record_requirement_refuses_unsupported_platform_before_store_preparation tests in both crates assert the 500 and the message.
| In your existing `Hooks::configure` implementation: | ||
|
|
||
| ```rust | ||
| app.require_record_store("sessions", RecordLayout::new(FirstSegmentLayout)?)?; |
There was a problem hiding this comment.
🔧 This sample does not compile
Compiled as a scratch test, it fails with E0277: the trait bound RecordLayout: RecordKeyLayout is not satisfied: require_record_store takes KeyLayout: RecordKeyLayout + 'static (core/src/app.rs:563-570). Pass FirstSegmentLayout directly, or change the signature to take a RecordLayout.
There was a problem hiding this comment.
Fixed in 702ad42. The sample passes FirstSegmentLayout directly and drops the unused RecordLayout import. All three Rust blocks in this guide now compile in a scratch test.
| let page = self.with_store(|store| { | ||
| strong_list_page(store, prefix, native_cursor.as_deref(), limit) | ||
| })?; | ||
| for key in &page.keys { |
There was a problem hiding this comment.
❓ Should one key outside the layout fail every list page that contains it?
Every listed key goes through binding.layout.resolve(key)? (:169-176). docs/guide/kv.md:163 seeds key = "__init__" into the sessions store for Viceroy, which is the same ID the records guide binds, so ordinary listing fails on that store locally. Skip keys the layout does not cover, or document that a record-bound store must hold only layout keys.
There was a problem hiding this comment.
Addressed in 1a14228 with docs, per the decision on this question. kv.md now declares the Viceroy sessions store empty (sessions = []) instead of seeding __init__. kv-records.md states that a record-bound store must hold only layout keys, and that a page containing another key fails listing.
| .cursor | ||
| .map(|native| { | ||
| serde_json::to_string(&RecordCursor { | ||
| scope: self.binding.scope.clone(), |
There was a problem hiding this comment.
🤔 Record cursors serialize the binding scope in plaintext
For DynamoDB records, scope is the JSON of the endpoint, table ARN (with the account ID), table ID, region, table and namespace (store-aws/src/dynamodb_records.rs:107-115), and this cursor is what apps hand to HTTP clients for pagination. Debug already hides scope, and celld binds its cursors with a hash. Bind with a SHA-256 of the scope instead.
There was a problem hiding this comment.
Fixed in 15dcf26. The new RecordBinding::scope_digest() (SHA-256, hex) replaces the raw scope in every record cursor: core partition cursors, DynamoDB partition and Scan cursors, Axum redb cursors and Fastly ordinary cursors. Tests assert that no endpoint, ARN, account ID, table ID, DB path or store name appears in a cursor, and that a cursor from another scope is rejected before any I/O. Previously issued cursors become invalid; the feature is unreleased.
| values.insert(":pk".to_owned(), AttributeValue::S(self.partition_key(query_partition)?)); | ||
| let output = self.inner.client.query().table_name(&self.inner.table).consistent_read(true) | ||
| .scan_index_forward(true).limit(native_limit) | ||
| .key_condition_expression("#pk = :pk") |
There was a problem hiding this comment.
🤔 Partition listing walks allocator rows before reaching any record
Limit applies before filter_expression, and allocator rows sort before value rows and are never deleted. A traversal therefore returns empty pages first and reads every key ever written. :prefix is built and then dropped because "Query cannot filter a key attribute", but a key condition can use the sort key: #pk = :pk AND begins_with(#sk, :prefix). No format change is needed.
There was a problem hiding this comment.
Fixed in c1fc9e2. The partition Query key condition is now #pk = :pk AND begins_with(#sk, :prefix), so allocator rows (g#…) never consume Limit. The mock applies the sort-key condition before Limit, and the traversal test goes from 2 empty pages to 0. decode_cursor also rejects a partition cursor whose sk falls outside r#<prefix>. That check goes slightly beyond the finding, so drop it if you prefer. The env-gated DynamoDB Local test was not run.
| body: Bytes::from(response.take_body_bytes()), | ||
| })), | ||
| Err(KVStoreError::ItemNotFound) => Ok(None), | ||
| Err(_) => Err(KvError::Unavailable), |
There was a problem hiding this comment.
🤔 Every lookup error except ItemNotFound becomes Unavailable (503, retryable)
The write path distinguishes InvalidKey, ItemBadRequest and similar errors (:404-416), but record lookup here and strong list (:444, :447) collapse them all. A rejected key or a tampered list cursor then becomes a retry loop. Reuse the write path's mapping.
There was a problem hiding this comment.
Fixed in 2b6eb62. A shared rejection_error now classifies InvalidKey, ItemBadRequest and the other rejections the same way for mutations, record lookup and both strong-list paths. Unknown read failures stay Unavailable, and reads never yield MutationUncertain. Covered by read_rejections_match_mutations_and_unknown_read_failures_stay_retryable.
A record declaration naming an undeclared store ID is a deployment mistake, not a client error, so it must not answer every request with 400.
require_record_store takes a RecordKeyLayout and validates it itself; wrapping it in RecordLayout::new does not compile.
Every listed key on a record binding goes through the layout, so the Viceroy __init__ seed in the sessions example broke listing once sessions was record-bound.
Record lookup and strong list mapped every error to a retryable 503, so a rejected key or cursor became a retry loop. Reads now share the mutation path's rejection classification and fall back to Unavailable only for unknown outcomes.
Limit applies before the filter, so allocator rows, which sort first and are never deleted, produced empty pages ahead of every partition's values. Move the r#<partition> prefix into the key condition and reject partition cursors outside that range.
Cursors are handed to HTTP clients, and the DynamoDB scope holds the endpoint and table ARN with its account ID, while redb's holds the database path. Core, DynamoDB, redb and Fastly cursors now carry only RecordBinding::scope_digest, a SHA-256 of the scope.
Covers require_record_store, RecordLayout/RecordKeyLayout, conditional writes, partition listing and cursors, and the DynamoDB and celld record providers.
|
CHANGELOG finding from the review: fixed in 81be117. |
…rors A record declaration naming an undeclared store ID is a deployment mistake, not a client error, so it must not answer every request with 400. Matches the Fastly adapter.
prk-Jr
left a comment
There was a problem hiding this comment.
PR Review
Summary
Follow-up review at a839312d. The new commits deal with most of the review feedback since a296a067: Fastly/Cloudflare/Spin misconfiguration now returns 500, the guide sample compiles, record cursors carry a scope digest, DynamoDB partition queries use a begins_with key condition, Fastly read errors use the mutation classification, and the shared contract now runs a stale CAS while the key is absent. The record design is still careful. I'm requesting changes because my earlier blocking finding about Fastly CAS on an absent key is still open, the branch now conflicts with its base, and no hosted CI has run on this head.
😃 Praise
- Every provider now runs the absent-key CAS assertion (
record_store.rs:77), and redb, DynamoDB and celld reject it by construction. The DynamoDB partition-query fix also tightens cursor validation, so a forged allocator-row position is rejected (dynamodb_records.rs:434-446). - The production code reviewed here matches the stated atomicity model. redb checks and allocates in one write transaction. DynamoDB uses a per-key allocator that is never reset, plus a conditional
PutItemwith SDK retries disabled (max_attempts(1)), so a resent request cannot turn a committed CAS intoPreconditionFailed. celld checks the instance, ledger and precondition and performs the write inside onetransactionSync. Each mutation also gets a new ID from the client.
Prior findings status
- 🔧 Still open: a stale CAS on a deleted key is not established on Fastly (
crates/edgezero-adapter-fastly/src/key_value_store.rs:372). b4be3c3 added the shared-contract assertion I asked for. However, the Fastly provider still passes the generation straight to nativeif_generation_match. The repository's Viceroy patch (patches/viceroy/0.22.0-body-readiness.patch, theif let Some(g) = generation && let Some(val) = &existinghunk) still only rejects when a row exists. The Fastlyrecord-contractphase thatcrates/edgezero-test-harness/src/runners/ci.rs:239-260adds to the Fastly CI suite would therefore fail on the pinned emulator. The author's reply and the plan (docs/superpowers/plans/2026-11-13-kv-record-contract.md:15-21) confirm this. Production Fastly behaviour is also still unverified: the linked JS SDK page doesn't cover a missing key, and no hosted trace was run. Please land the emulator fix through the base, or take Fastly out of the CAS claim or document it as a Fastly limitation, so the required suite can pass. - ✅ Resolved: celld ordinary
existson record bindings now uses the live, instance-checked lookup. Onlyrecords.exists_stronguses the physicalHEAD.
Findings
Blocking
- 🔧 Merge conflict with the current base:
git merge-tree --write-treeagainstfeature/pluggable-geo-providers(dd34d19d) reportsCONFLICT (content): Merge conflict in CHANGELOG.md. The base's new native Geo entry and this PR's### Portable conditional KV recordsentry both insert directly under## Unreleased. Please forward-merge the base and keep both entries. - 🔧 No hosted CI on this head: GitHub reports zero check runs and zero statuses for
a839312d, and none forb4be3c3d. The workflows only trigger on PRs targetingmain. The last green set was ata296a067, which predates the absent-key assertion that is expected to fail the Fastly suite. Please run the full suite for this exact head (for example by temporarily targetingmain, or with a manual dispatch) and link it.
Non-blocking
- 🤔 celld Add/CAS judge expired rows by physical presence (inline at
services/celld-store/src/index.js:860). This is a cross-provider difference that the portable guide doesn't spell out.
Checks run locally (Rust 1.98.1, --locked, at a839312d)
cargo fmt --all -- --check: pass.cargo testforedgezero-core,-adapter-axum,-store-aws,-store-celld,-adapter-fastly,-adapter-cloudflareand-adapter-spin: pass (includes the Axum shared record contract).cargo clippy --all-targets --all-features -D warningsfor core, axum, store-aws, store-celld, fastly and cli on the host target: pass. Cloudflare onwasm32-unknown-unknownand Spin onwasm32-wasip2: pass.node --test services/celld-store/test/*.test.mjson the pinned Node 24.20.0: 28/28 pass. Two empty-body cases fail on Node 24.12, which looks like a local runtime difference, not this PR.- Not run: Fastly WASM under the pinned Viceroy 0.22.0, DynamoDB Local, stock celld interop and the full workspace. Test scripts, specs and plans were only skimmed.
CI Status
- No hosted checks reported for
a839312d(blocking, see above).
| RecordWriteMode::Add => request.mode(InsertMode::Add), | ||
| RecordWriteMode::Overwrite => request.mode(InsertMode::Overwrite), | ||
| RecordWriteMode::IfGenerationMatch(generation) => { | ||
| request.if_generation_match(generation.as_u64()) |
There was a problem hiding this comment.
🔧 Still open: a stale CAS can recreate a deleted key on the tested Fastly runtime
The shared contract now asserts the right behaviour (thanks). This call still passes the generation through unchanged, and the pinned Viceroy (with patches/viceroy/0.22.0-body-readiness.patch applied) only fails the precondition when existing is Some. So the Fastly record-contract phase wired into runners/ci.rs fails at assert_stale straight after the delete. Production Fastly is still unverified.
To unblock, any one of these is enough:
- Land the emulator fix in the base so the required Fastly suite passes on this head.
- Document it as a Fastly limitation (and have the contract skip that one assertion for Fastly only).
- Don't claim
IfGenerationMatchon Fastly yet.
Leaving a required suite that is known to fail is not mergeable.
| let result; | ||
| if (meta.op === "put") { | ||
| const { allocator } = readMeta(this.sql); | ||
| const existing = meta.op === "record-put" ? this.row(meta.key) : undefined; |
There was a problem hiding this comment.
🤔 Add/CAS see expired-but-unswept rows, while lookup hides them
this.row() doesn't apply live(row, now). Until the alarm sweep runs (sweepIntervalMs = 60s, in batches of 256), two things happen:
- A CAS that holds a pre-expiry generation returns
Writtenand revives a value thatlookupalready reports as absent. lookupreturnsNonewhileAddreturnsPreconditionFailed, so a "lookup miss, then Add" flow keeps losing for up to a minute.
redb evaluates Add/CAS against live rows (key_value_store_records.rs:216), so the two record providers behave differently. The celld README and the stock-celld spec describe this as intended, but the portable guide (docs/guide/kv-records.md:145-149) only says celld "can hide expired rows". Consider either applying live() to existing here (sweep never resets the allocator, so generations stay unique), or stating this behaviour in the portable TTL section.
| records.delete(key).await.unwrap(); | ||
| assert_eq!(kv.get_bytes(key).await.unwrap(), None); | ||
| assert!(!records.exists_strong(key).await.unwrap()); | ||
| assert_stale(records, key, before_delete).await; |
There was a problem hiding this comment.
😃 Running the stale CAS while the key is absent, and then confirming it stayed absent, is exactly the check that separates a provider that recreates the key from one that doesn't. Putting it in the shared contract means every provider gets it for free.
| .scan_index_forward(true).limit(native_limit) | ||
| // Value SKs share `r#<partition>`; allocator `g#` rows sort first | ||
| // and stay outside the key range, so `Limit` counts only values. | ||
| .key_condition_expression("#pk = :pk AND begins_with(#sk, :prefix)") |
There was a problem hiding this comment.
😃 Bounding the Query with begins_with(#sk, :prefix) keeps Limit counting only value rows. Pairing it with the value_position check in decode_cursor also closes off allocator-row cursors. Nice fix.
|
📝 Correction to blocking item 3 in my review above: the workflows are not restricted to PRs targeting |
Summary
Changes
edgezero-coreedgezero-store-awsservices/celld-storeedgezero-store-celldCloses
Closes #472
Closes #473
Stack placement
Base this PR on #439. #454 belongs above this PR; #464 belongs above #454 but remains outside official stack membership. Preserve existing PR identities and ordinary forward-merge ancestry.
flowchart TD A["#439: native Geo"] --> B["This PR: conditional records"] B --> C["#454: KV-backed Geo"] C --> D["#464: error finalization, outside stack membership"]Test plan
Local verification uses Rust 1.98.1 with locked dependencies.
cargo test --workspace --all-targetsafter merging current Add pluggable native Geo providers and protected CloudFront ingress #439. Follow-up lint-only changes also pass the affected adapter and example tests.cargo clippy --workspace --all-targets --all-features -- -D warningscargo fmt --all -- --checkcargo check --workspace --all-targets --features "fastly cloudflare spin"examples/app-demonative workspace tests and strict all-target/all-feature Clippy.Known validation gap
The Viceroy emulator's record race can report more than one successful CAS writer. The one-winner assertion remains unchanged and the failed result remains disclosed. The emulator checks and replacement use separate locking intervals. Its repair is explicitly deferred; no retries for a favorable schedule, serialization, weakened assertions or runtime patch are included here. Successful individual runs do not establish atomicity. This does not establish a production Fastly defect or qualify the full Fastly concurrency acceptance criterion in #472.
Operational limits
Stock celld retains one serialized namespace object and allocator. Same-instance snapshot rollback/restore is not protected. Local/emulator proofs do not qualify production IAM, capacity, hosted fleets, backups or deployment. Native connector credentials remain outside published application configuration. No release, deployment, infrastructure apply or image publication is part of this PR.
Checklist