Repository navigation
Portable KV-backed Geo lookup - #454
ChristianPavilonis wants to merge 30 commits into
Conversation
e4ede10 to
c155e5d
Compare
aram356
left a comment
There was a problem hiding this comment.
PR Review
Summary
This PR adds a standalone KV Geo prototype: a CSV importer, the p1 binary index, digest-validated async lookup through KvHandle, the design spec and the results record. The lookup algorithm holds up under a randomized differential check: 872,448 lookups compared against naive range containment, covering both families, object budgets of 512–4096 bytes and cache budgets of 0, 2 KiB and 1 MiB, with zero mismatches. The blocking issues are about keeping the crate buildable and the evidence accurate. Nothing in CI builds it, its pins break on the next root bump, several tests can't fail, and the results doc's provenance doesn't match this head.
Findings
Blocking
- 🔧 No CI coverage, and exact pins coupled to the root: a simulated root
serde_jsonbump makes this crate unresolvable while CI stays green (examples/geo-kv-prototype/Cargo.toml:8) - 🔧 Object cache effectively untested: a cache that stores nothing passes all 10 tests (
examples/geo-kv-prototype/src/index.rs:635) - 🔧 Overlap-rejection test can't fail: no build succeeds at 140 bytes, and deleting the overlap check still passes (
examples/geo-kv-prototype/src/index.rs:763) - 🔧 Results doc provenance and coverage claims don't match this head (
docs/superpowers/plans/2026-11-05-kv-geo-prototype-results.md:9)
Non-blocking
- 🤔 Cache hit skips the family check, so warm and cold resolvers can disagree (
src/index.rs:531) - 🤔 IPv4-mapped input misses (
src/index.rs:501) - 🤔 Generation ID isn't derived from content (
src/index.rs:274) - ♻️ Validation runs after publication (
src/index.rs:291,src/main.rs:55) - ♻️ Second SHA-256 stack (
Cargo.toml:20) - 🤔
loadandArtifactStorehave no tests (src/import.rs:149) - ⛏ I/O errors lose the path (
src/import.rs:132) - ⛏
oracle_mismatchesis a constant (src/main.rs:128) - 🌱 An interrupted write blocks every rerun (
src/store.rs:98) - 🌱 Before p1 is frozen:
- The manifest serializes
u128bounds as JSON numbers and each digest as a 32-element array. IPv6 bounds above 2^53 lose precision in JavaScript andjq, and each digest takes about 115 characters as an array versus 64 as hex. Hex strings fix both. - Tests match
anyhowerrors by substring, which doesn't give the bounded failure categories spec §9 asks for. A typed error enum would. Cache::getcallsorder.retainon every hit, which costs O(entries). A production cache needs O(1) LRU bookkeeping.Resolver::lookup(&mut self)can't be shared across concurrent requests as written.
- The manifest serializes
📌 Out of Scope
- Dependabot's cargo entry covers only
/. Standalone lockfiles such as this crate's get updated only when someone notices a root bump broke them. A tracking issue across the standalone crates would cover this.
CI Status
- PR checks: 18/18 pass at
c52bdaf3 - Local workspace gates (fmt, clippy, test, feature check, spin wasm32): PASS
- Local prototype checks: fmt PASS, tests PASS (10/10), clippy
-D warningsPASS, release build PASS,cargo checkforwasm32-unknown-unknownandwasm32-wasip1PASS - None of the workspace gates or PR checks compile this crate.
How the findings were checked
- Mutation testing:
cargo mutantsonindex.rs,import.rsandstore.rsproduced 243 mutants: 146 caught, 71 missed, 20 unviable, 6 timeouts. - Probe tests in a scratch copy covered the cache/family divergence, IPv4-mapped input, the minimum budget and the randomized differential check.
- CLI run: end-to-end
build/verify/lookupon synthetic Country-shaped CSV.
dhruv8sh
left a comment
There was a problem hiding this comment.
PR Review
Summary
Standalone, opt-in geo-KV prototype (own [workspace], no production impact) plus design/results docs. Lookup algorithm looks correct and is well validated; only non-blocking notes.
😃 Praise
- Lookups are verified against a plain containment search over the original, unmerged source networks (
import.rs:224-236).XKis kept with acore_country_supportedflag rather than widening or dropping it, and the lookup path uses onlyKvHandlewithblock_ontests.
Findings
Non-blocking
- 🤔 Generation check after write (
src/main.rs:55) — inline - 🤔 O(n) cache hit bookkeeping (
src/index.rs:427) — inline - ⛏ Silent edition fallback (
src/import.rs:150) — inline - ⛏ Manifest size unbounded on read (
src/index.rs:466) — inline - 🌱 Prototype not exercised by CI: its own
[workspace]means root CI never builds or tests it, so it can rot asedgezero-corechanges. Consider acargo test --locked --manifest-path examples/geo-kv-prototype/Cargo.tomlstep or a follow-up issue. - 📝 Results doc predates the toolchain bump: it records Rust 1.95.0 and base
72ceed7e; the repo is now on 1.98.1 and the measurements weren't rerun. Keep that caveat visible.
CI Status
- fmt: PASS
- clippy (prototype,
-D warnings): PASS - tests (prototype): PASS (10 passed, 0 failed)
#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.
The workspace now pins url =2.5.9 for main's Fastly SDK 0.13.3 upgrade (#529), and this example resolves edgezero-core from the workspace, so its lockfile no longer satisfied the manifests after the merge. A targeted `cargo update -p url --precise 2.5.9` moves url to 2.5.9 and form_urlencoded to 1.2.3, matching the v0.0.12 lockfiles.
|
For the identity integration branch (#495), I pushed
|
kv_geo_listener_checks_reader_provenance_and_pinned_objects reused its pre-spawn address after the host was ready; it now uses server.addr(), which follows a respawn.
|
For the identity integration branch (#495), I pushed |
|
For the identity integration branch (#495), I pushed |
prk-Jr
left a comment
There was a problem hiding this comment.
PR Review
Summary
Re-review at 7580806a (base a296a067). The PR is now opt-in managed Axum KV Geo serving, plus Fastly/Cloudflare platform geo and the operator tool. I found no code defects in the core lookup, publication or Axum wiring. All four blocking items from my earlier review are fixed. One blocking docs issue remains: docs/guide/native-geo.md is now wrong in ways this PR caused.
😃 Praise
- A missing or corrupt index object is always a provider failure, never a geographic miss. Cached objects are re-checked against the parent's family, envelope and level on every hit.
kv_geo_listener_checks_reader_provenance_and_pinned_objectsdrives every outcome through a real listener with distinguishable values: checked forwarded reader, IPv4-mapped input,XKas unsupported geography, a gap, IPv6 country-only, a removed leaf (provider failure) and a missing root (no readiness, port never bound).
Earlier blocking findings
- CI never built the tool: fixed.
test.yml:219-229runs standalone fmt, clippy-D warningsand--lockedtests on every PR. - Object cache untested: fixed. With
Cache::getalways missing,repeated_lookup_uses_cache_without_backend_readsand the eviction test fail. Without the recency update, the eviction test fails. - Overlap test couldn't fail: fixed. With
range.start > endchanged to>=atgeo/kv.rs:273, or the check removed,rejects_overlaps_with_a_compatible_object_budgetfails. - Results doc provenance: fixed. The serving results name
7c0cd31e. Since then the tool changed only in its default object size, README and a lockfileurlbump.
Findings
Blocking
- 🔧
docs/guide/native-geo.mdcontradicts the new behaviour (unchanged lines, so not inline):- L273-287: the
describe()classifier matchesGeoUnavailableReasonexhaustively but has no arms forMissingReaderIp,NoMatchorUnsupportedGeography. That enum isn't#[non_exhaustive], so the documented snippet no longer compiles. The same snippet in the Axumgeo.rsmodule docs was updated in this PR. - L313: says Fastly and Cloudflare expose
NoSelection. They now always passGeoOutcome::platform(...), asconfiguration.md:566in this PR says. - L289-291: says located results carry
GeoSource::CloudFrontandDeclaredProtectedAlb. The Fastly, Cloudflare and Kv sources and their trust bases now exist. - Fix: add the three arms (or a wildcard), update the adapter sentence, and generalize the source/trust sentence.
- L273-287: the
Non-blocking
- 🤔
forwarded-requiredwithout a trusted proxy starts and never locates (crates/edgezero-adapter-axum/src/geo.rs:394, inline) - 🤔 Breaking geo API changes have no CHANGELOG entry:
GeoSource/GeoTrustBasisbecame#[non_exhaustive]with new variants.GeoUnavailableReasongained three variants but stays exhaustive, which is inconsistent and will break downstream matches again.GeoProviderId::newnow rejectsfastly,cloudflareandkv. Fastly/Cloudflarectx.geo()moves fromNoSelectiontoSelected. This is within the 0.x policy, but worth recording. Consider#[non_exhaustive]onGeoUnavailableReason. - 🤔 Depth failure leaves a receipt that blocks reruns (
examples/geo-kv-prototype/src/main.rs:106, inline) - ⛏ README path limit says 32 (
README.md:152, inline) - ⛏ README example folder name says 64k (
README.md:19, inline) - ⛏ Configuration table omits
kv(docs/guide/configuration.md:579, inline) - ⛏ Core
geo::kvCI line can select zero tests (.github/workflows/test.yml:226, inline) - ⛏
geo_mixed_provider_fieldshas no message (crates/edgezero-core/src/manifest.rs:1530, inline) - 🌱 Test gaps: nothing unit-tests KV selection from the manifest (
configured_kv, the documented primary path); only the all-settings path runs, in the listener test. Changing the importer overlap check (import.rs:130-135) from<to<=survives every test, because no case shares an endpoint, e.g.1.0.0.0/24plus1.0.0.255/32.expectFailureinrun_geo_kv_integration.mjs:408-412asserts only exit code 1, so the conflict-publish and incomplete-tree steps would pass for unrelated failures.
📌 Out of Scope
- Landing order (#439, #502, #510 before this PR) and the #438 decision on full-tree verification instead of the MMDB checks are maintainer decisions the PR already asks for.
CI Status
- PR checks at
7580806a: 29 pass, 2 fail.cache-restore-smokeandcache-new-revision-smokefail onTARGET_CACHE_HIT=false(seed cache not found). This PR doesn't touch that workflow. The same jobs pass on #510, and main's #435 addresses this seed-verification race. They need a rerun or a main sync before merge. - fmt: PASS (local).
- tests: PASS locally, 3,053 passed, 0 failed, 9 ignored (
cargo test --workspace --all-targets, Rust 1.99.1). The Axumkv_geolistener test passes on 1.98.1. The standalone tool passes 10 unit + 2 CLI tests (default and all-features) and the Node helper passes 8/8. - clippy: PASS on hosted 1.98.1 and in a focused local 1.98.1 run over the core/Axum geo-kv code. Local workspace clippy on 1.99.1 fails only on newer lints in unchanged files.
- Not run: the full celld/DynamoDB integration and the local Fastly/Cloudflare wasm suites (they ran in CI).
| let get = |key| env.get(&["adapter", "geo", key]); | ||
| let reader_ip = match get("reader_ip").or_else(|| manifest?.reader_ip.as_deref()) { | ||
| Some("direct-peer") => KvGeoReaderIp::DirectPeer, | ||
| Some("forwarded-required") => KvGeoReaderIp::ForwardedRequired, |
There was a problem hiding this comment.
🤔 forwarded-required without a trusted proxy starts, passes readiness and never locates
ForwardedRequired uses only a client approved by the trusted proxy policy. Nothing checks at startup that such a policy exists. With EDGEZERO__ADAPTER__TRUSTED_PROXY_CIDRS unset, the managed listener starts and verifies its roots. Every request then reports missing_reader_ip.
I ran this in a scratch copy as a variant of kv_geo_listener_checks_reader_provenance_and_pinned_objects, with the trusted proxy and forwarding-family settings removed. A request with Forwarded: for=192.0.2.9 returned {"provider":"kv","status":"missing_reader_ip"}.
The guide says geo misconfiguration never falls back to off, and CloudFront rejects missing networks at startup. Here a misconfiguration is effectively off with no startup signal. It isn't wrong geography, so this is non-blocking.
Fix: reject forwarded-required at startup when the trusted proxy policy is empty. The runner has options.trusted_proxy_policy() next to options.native_geo(..), and the dev path has native.policy.
| "process_peak_rss_bytes": peak_rss_bytes(), | ||
| "store": store.stats(), | ||
| }); | ||
| write_json(&out.join("receipt.json"), &receipt)?; |
There was a problem hiding this comment.
🤔 A too-deep build leaves a receipt that blocks reruns
receipt.json, inventory.json and build-report.json are written before publication::Artifact::open(out) (L109). That call enforces the three-object path limit through Resolver::open. With a small budget on City data (e.g. 1024), every object and the receipt land, then the command fails with the generic message. Reruns in that directory then fail at the existing-output check (L61) with the generic message, not the classified "use a different output directory". lookup and verify on that directory also fail. fs::write of the receipt is also not atomic.
This is source-read only; I had no licensed data to execute it.
Fix: check root depth against index::limits(0).max_path_objects (or run the Artifact-style validation) before writing the receipt and inventory. Write them via temp file and rename.
|
|
||
| ## Format and measurement limits | ||
|
|
||
| Core owns the `EZG1` binary encoding and schema validation. Objects use sorted intervals, embedded six-byte source locations and digest-addressed children; the manifest binds both family roots and source hashes. No full index preload or key listing is required for lookup. Reader limits here are a 384 KiB object ceiling, 32 objects per path, and 4,096 cache entries. Cache payload bytes are configurable for local verification; remote verification disables caching. These are tool limits, not a claim about deployed capacity or final schema defaults. |
There was a problem hiding this comment.
⛏ Wrong path limit
This says 32 objects per path, but src/index.rs:10 sets max_path_objects: 3, matching Axum's MAX_PATH_OBJECTS. An operator choosing a small object-bytes would expect deeper trees to be accepted. Suggest saying 3, matching managed Axum startup.
| BIN="$PWD/$TARGET/release/geo-kv-prototype" | ||
|
|
||
| SOURCE="$HOME/.cache/edgezero/geo/source/GeoLite2-City-CSV_RELEASE" | ||
| OUT="$HOME/.cache/edgezero/geo/artifacts-64k" |
There was a problem hiding this comment.
⛏ Example label no longer matches the build
OUT is named artifacts-64k, but build "$SOURCE" "$OUT" now uses the 16 KiB default. Rename the directory or pass 65536 explicitly.
|
|
||
| | Field | Runtime override | Description | | ||
| | ------------------------------- | ------------------------------------------------------- | ------------------------------------------- | | ||
| | `provider` | `EDGEZERO__ADAPTER__GEO__PROVIDER` | `cloudfront` or `off` | |
There was a problem hiding this comment.
⛏ Table omits the KV provider
provider also accepts kv (ManifestGeoProvider::Kv). The KV keys store_id, pin, reader_ip, lookup_timeout_ms and max_in_flight and their EDGEZERO__ADAPTER__GEO__* overrides are missing too. native-geo.md documents them correctly. Add the rows or link there.
| cargo clippy --offline --locked --manifest-path examples/geo-kv-prototype/Cargo.toml --all-targets --all-features -- -D warnings | ||
| cargo test --offline --locked --manifest-path examples/geo-kv-prototype/Cargo.toml | ||
| cargo test --offline --locked --manifest-path examples/geo-kv-prototype/Cargo.toml --all-features | ||
| node --test scripts/run_geo_kv_integration.test.mjs |
There was a problem hiding this comment.
⛏ This line can pass with zero tests
The neighbouring Geo steps use scripts/run_test_nonzero.sh, but this one doesn't. A rename of geo::kv would select nothing and still pass. Wrap it like the kv_geo line below.
| if (assertion && (kv || geo.provider == Some(ManifestGeoProvider::Kv))) | ||
| || (kv && geo.provider == Some(ManifestGeoProvider::CloudFront)) | ||
| { | ||
| return Err(ValidationError::new("geo_mixed_provider_fields")); |
There was a problem hiding this comment.
⛏ Error has no message
This renders as adapters[0].geo.__all__: Validation error: geo_mixed_provider_fields [{}]. The sibling geo validation errors carry human-readable messages. Set error.message (e.g. "KV and CloudFront geo fields cannot be combined").
What this PR delivers
This replaces the prototype-only serving story with opt-in, managed Axum KV Geo. The portable reader takes a checked IP and uses the existing
KvHandleinterface and a pinned immutable generation. It has no CSV, MMDB, native SDK, or backend-specific lookup dependency. Off remains the default; protected CloudFront and supplied-provider behavior are preserved.The standalone operator tool builds GeoLite City or Country CSV artifacts, publishes with read-back and manifest-last ordering, and verifies the full tree through the serving binding against an independent CSV oracle. It supports ordinary stock celld and DynamoDB KV. The serving identity is read-only; the publisher can retire prior generations by inventory. No new service API, storage provisioning, or EC binding is required.
docs/superpowers/specs/2026-11-05-kv-geo-design.mddocs/guide/native-geo.mdexamples/geo-kv-prototype/README.mdReview and landing order
This branch still targets #510 (
feat/kv-record-contract). It includes the #439 provider foundation and a local reconciliation of #502. Please confirm that #439 lands first, that #502 and #510 are reconciled into the target before #454 lands, and that #454 need not carry their changes as its own feature diff. The PR base has not been changed.Tracks #438. Maintainer decision requested before closure: accept a full-tree verification through the read-only serving binding before rollout, plus pinned manifest and nonempty root checks before Axum readiness, in place of the MMDB-specific malformed-file and mount checks. A required descendant missing or corrupt at request time is a provider failure, not a geographic miss or fallback.
Evidence
The local workspace run passed 3,051 tests with 9 existing ignores, alongside strict Clippy, feature checks, and the Spin WASM build. The earlier CLI test stall reproduces on both base and candidate only with terminal stdin. The workspace run used noninteractive stdin without adding any skips. The final standalone default and all-feature suites passed after the object-size decision. The Axum native feature lint matrix passed locally after the compiled-out fixture fixes.
The combined backend proof passed on stock celld and DynamoDB Local, including full-tree readback, managed Axum requests, and 4,096 IPv4/IPv6 oracle comparisons per backend and object size. The same 16 KiB artifacts avoided repeat KV reads in the sampled workload on both backends, so 16 KiB is now the default. 64 KiB remains an explicit option for fewer objects and fewer cold path reads. The report records which binaries were measured. Hosted IAM, production performance and durability are not claimed. No licensed source or derived data is checked in.
Trusted Server integration, deployment, and tags are out of scope for this PR.